]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/Localization/Localization.php
Release 6.4.0
[Github/sugarcrm.git] / include / Localization / Localization.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /**
39  * Localization manager
40  * @api
41  */
42 class Localization {
43         var $availableCharsets = array(
44                 'BIG-5',        //Taiwan and Hong Kong
45                 /*'CP866'                         // ms-dos Cyrillic */
46                 /*'CP949'                         //Microsoft Korean */
47                 'CP1251',       //MS Cyrillic
48                 'CP1252',       //MS Western European & US
49                 'EUC-CN',       //Simplified Chinese GB2312
50                 'EUC-JP',       //Unix Japanese
51                 'EUC-KR',       //Korean
52                 'EUC-TW',       //Taiwanese
53                 'ISO-2022-JP',  //Japanese
54                 'ISO-2022-KR',  //Korean
55                 'ISO-8859-1',   //Western European and US
56                 'ISO-8859-2',   //Central and Eastern European
57                 'ISO-8859-3',   //Latin 3
58                 'ISO-8859-4',   //Latin 4
59                 'ISO-8859-5',   //Cyrillic
60                 'ISO-8859-6',   //Arabic
61                 'ISO-8859-7',   //Greek
62                 'ISO-8859-8',   //Hebrew
63                 'ISO-8859-9',   //Latin 5
64                 'ISO-8859-10',  //Latin 6
65                 'ISO-8859-13',  //Latin 7
66                 'ISO-8859-14',  //Latin 8
67                 'ISO-8859-15',  //Latin 9
68                 'KOI8-R',       //Cyrillic Russian
69                 'KOI8-U',       //Cyrillic Ukranian
70                 'SJIS',         //MS Japanese
71                 'UTF-8',        //UTF-8
72                 );
73         var $localeNameFormat;
74         var $localeNameFormatDefault;
75         var $default_export_charset = 'UTF-8';
76         var $default_email_charset = 'UTF-8';
77         var $currencies = array(); // array loaded with current currencies
78     var $invalidNameFormatUpgradeFilename = 'upgradeInvalidLocaleNameFormat.php';
79
80
81         /**
82          * sole constructor
83          */
84         function Localization() {
85                 global $sugar_config;
86                 $this->localeNameFormatDefault = empty($sugar_config['locale_name_format_default']) ? 's f l' : $sugar_config['default_name_format'];
87                 $this->loadCurrencies();
88         }
89
90         /**
91          * returns an array of Sugar Config defaults that are determined by locale settings
92          * @return array
93          */
94         function getLocaleConfigDefaults() {
95                 $coreDefaults = array(
96                         'currency'                                                              => '',
97                         'datef'                                                                 => 'm/d/Y',
98                         'timef'                                                                 => 'H:i',
99                         'default_currency_significant_digits'   => 2,
100                         'default_currency_symbol'                               => '$',
101                         'default_export_charset'                                => $this->default_export_charset,
102                         'default_locale_name_format'                    => 's f l',
103             'name_formats'                          => array('s f l' => 's f l', 'f l' => 'f l', 's l' => 's l', 'l, s f' => 'l, s f',
104                                                             'l, f' => 'l, f', 's l, f' => 's l, f', 'l s f' => 'l s f', 'l f s' => 'l f s'),
105                         'default_number_grouping_seperator'             => ',',
106                         'default_decimal_seperator'                             => '.',
107                         'export_delimiter'                                              => ',',
108                         'default_email_charset'                                 => $this->default_email_charset,
109                 );
110
111                 return $coreDefaults;
112         }
113
114         /**
115          * abstraction of precedence
116          * @param string prefName Name of preference to retrieve based on overrides
117          * @param object user User in focus, default null (current_user)
118          * @return string pref Most significant preference
119          */
120         function getPrecedentPreference($prefName, $user=null, $sugarConfigPrefName = '') {
121                 global $current_user;
122                 global $sugar_config;
123
124                 $userPref = '';
125                 $coreDefaults = $this->getLocaleConfigDefaults();
126                 $pref = isset($coreDefaults[$prefName]) ? $coreDefaults[$prefName] : ''; // defaults, even before config.php
127
128                 if($user != null) {
129                         $userPref = $user->getPreference($prefName);
130                 } elseif(!empty($current_user)) {
131                         $userPref = $current_user->getPreference($prefName);
132                 }
133                 // Bug 39171 - If we are asking for default_email_charset, check in emailSettings['defaultOutboundCharset'] as well
134                 if ( $prefName == 'default_email_charset' ) {
135                     if($user != null) {
136                 $emailSettings = $user->getPreference('emailSettings', 'Emails');
137             } elseif(!empty($current_user)) {
138                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
139             }
140             if ( isset($emailSettings['defaultOutboundCharset']) ) {
141                 $userPref = $emailSettings['defaultOutboundCharset'];
142             }
143                 }
144
145                 // set fallback defaults defined in this class
146                 if(isset($this->$prefName)) {
147                         $pref = $this->$prefName;
148                 }
149                 //rrs: 33086 - give the ability to pass in the preference name as stored in $sugar_config.
150                 if(!empty($sugarConfigPrefName)){
151                         $prefName = $sugarConfigPrefName;
152                 }
153                 // cn: 9549 empty() call on a value of 0 (0 significant digits) resulted in a false-positive.  changing to "isset()"
154                 $pref = (!isset($sugar_config[$prefName]) || (empty($sugar_config[$prefName]) && $sugar_config[$prefName] !== '0')) ? $pref : $sugar_config[$prefName];
155                 $pref = (empty($userPref) && $userPref !== '0') ? $pref : $userPref;
156                 return $pref;
157         }
158
159         ///////////////////////////////////////////////////////////////////////////
160         ////    CURRENCY HANDLING
161         /**
162          * wrapper for whatever currency system we implement
163          */
164         function loadCurrencies() {
165                 // doing it dirty here
166                 global $db;
167                 global $sugar_config;
168
169                 if(empty($db)) {
170                         return array();
171                 }
172
173         $load = sugar_cache_retrieve('currency_list');
174         if ( !is_array($load) ) {
175                         // load default from config.php
176                         $this->currencies['-99'] = array(
177                                 'name'          => $sugar_config['default_currency_name'],
178                                 'symbol'        => $sugar_config['default_currency_symbol'],
179                                 'conversion_rate' => 1
180                                 );
181
182             $q = "SELECT id, name, symbol, conversion_rate FROM currencies WHERE status = 'Active' and deleted = 0";
183             $r = $db->query($q);
184
185             while($a = $db->fetchByAssoc($r)) {
186                 $load = array();
187                 $load['name'] = $a['name'];
188                 $load['symbol'] = $a['symbol'];
189                 $load['conversion_rate'] = $a['conversion_rate'];
190
191                 $this->currencies[$a['id']] = $load;
192             }
193             sugar_cache_put('currency_list',$this->currencies);
194         } else {
195             $this->currencies = $load;
196         }
197
198
199         }
200
201         /**
202          * getter for currencies array
203          * @return array $this->currencies returns array( id => array(name => X, etc
204          */
205         function getCurrencies() {
206                 return $this->currencies;
207         }
208
209         /**
210          * retrieves default OOTB currencies for sugar_config and installer.
211          * @return array ret Array of default currencies keyed by ISO4217 code
212          */
213         function getDefaultCurrencies() {
214                 $ret = array(
215                         'AUD' => array( 'name'          => 'Australian Dollars',
216                                                         'iso4217'       => 'AUD',
217                                                         'symbol'        => '$'),
218                         'BRL' => array( 'name'          => 'Brazilian Reais',
219                                                         'iso4217'       => 'BRL',
220                                                         'symbol'        => 'R$'),
221                         'GBP' => array( 'name'          => 'British Pounds',
222                                                         'iso4217'       => 'GBP',
223                                                         'symbol'        => '£'),
224                         'CAD' => array( 'name'          => 'Canadian Dollars',
225                                                         'iso4217'       => 'CAD',
226                                                         'symbol'        => '$'),
227                         'CNY' => array( 'name'          => 'Chinese Yuan',
228                                                         'iso4217'       => 'CNY',
229                                                         'symbol'        => 'ï¿¥'),
230                         'EUR' => array( 'name'          => 'Euro',
231                                                         'iso4217'       => 'EUR',
232                                                         'symbol'        => '€'),
233                         'HKD' => array( 'name'          => 'Hong Kong Dollars',
234                                                         'iso4217'       => 'HKD',
235                                                         'symbol'        => '$'),
236                         'INR' => array( 'name'          => 'Indian Rupees',
237                                                         'iso4217'       => 'INR',
238                                                         'symbol'        => '₨'),
239                         'KRW' => array( 'name'          => 'Korean Won',
240                                                         'iso4217'       => 'KRW',
241                                                         'symbol'        => 'â‚©'),
242                         'YEN' => array( 'name'          => 'Japanese Yen',
243                                                         'iso4217'       => 'JPY',
244                                                         'symbol'        => 'Â¥'),
245                         'MXM' => array( 'name'          => 'Mexican Pesos',
246                                                         'iso4217'       => 'MXM',
247                                                         'symbol'        => '$'),
248                         'SGD' => array( 'name'          => 'Singaporean Dollars',
249                                                         'iso4217'       => 'SGD',
250                                                         'symbol'        => '$'),
251                         'CHF' => array( 'name'          => 'Swiss Franc',
252                                                         'iso4217'       => 'CHF',
253                                                         'symbol'        => 'SFr.'),
254                         'THB' => array( 'name'          => 'Thai Baht',
255                                                         'iso4217'       => 'THB',
256                                                         'symbol'        => '฿'),
257                         'USD' => array( 'name'          => 'US Dollars',
258                                                         'iso4217'       => 'USD',
259                                                         'symbol'        => '$'),
260                 );
261
262                 return $ret;
263         }
264         ////    END CURRENCY HANDLING
265         ///////////////////////////////////////////////////////////////////////////
266
267
268         ///////////////////////////////////////////////////////////////////////////
269         ////    CHARSET TRANSLATION
270         /**
271          * returns a mod|app_strings array in the target charset
272          * @param array strings $mod_string, et.al.
273          * @param string charset Target charset
274          * @return array Translated string pack
275          */
276         function translateStringPack($strings, $charset) {
277                 // handle recursive
278                 foreach($strings as $k => $v) {
279                         if(is_array($v)) {
280                                 $strings[$k] = $this->translateStringPack($v, $charset);
281                         } else {
282                                 $strings[$k] = $this->translateCharset($v, 'UTF-8', $charset);
283                         }
284                 }
285                 ksort($strings);
286                 return $strings;
287         }
288
289         /**
290          * translates the passed variable for email sending (export)
291          * @param       mixed the var (array or string) to translate
292          * @return      mixed the translated variable
293          */
294         function translateForEmail($var) {
295                 if(is_array($var)) {
296                         foreach($var as $k => $v) {
297                                 $var[$k] = $this->translateForEmail($v);
298                         }
299                         return $var;
300                 } elseif(!empty($var)) {
301                         return $this->translateCharset($var, 'UTF-8', $this->getOutboundEmailCharset());
302                 }
303         }
304
305         /**
306          * prepares a bean for export by translating any text fields into the export
307          * character set
308          * @param bean object A SugarBean
309          * @return bean object The bean with translated strings
310          */
311     function prepBeanForExport($bean)
312     {
313         foreach($bean->field_defs as $k => $field)
314         {
315             if (is_string($bean->$k))
316             {
317                            // $bean->$k = $this->translateCharset($bean->$k, 'UTF-8', $this->getExportCharset());
318             }
319             else
320             {
321                 $bean->$k = '';
322             }
323         }
324
325         return $bean;
326     }
327
328         /**
329          * translates a character set from one encoding to another encoding
330          * @param string string the string to be translated
331          * @param string fromCharset the charset the string is currently in
332          * @param string toCharset the charset to translate into (defaults to UTF-8)
333          * @return string the translated string
334          */
335     function translateCharset($string, $fromCharset, $toCharset='UTF-8')
336     {
337         $GLOBALS['log']->debug("Localization: translating [ {$string} ] into {$toCharset}");
338
339         // Bug #35413 Function has to use iconv if $fromCharset is not in mb_list_encodings
340         $isMb = function_exists('mb_convert_encoding');
341         $isIconv = function_exists('iconv');
342         if ($isMb == true)
343         {
344             $fromCharset = strtoupper($fromCharset);
345             $listEncodings = mb_list_encodings();
346             $isFound = false;
347             foreach ($listEncodings as $encoding)
348             {
349                 if (strtoupper($encoding) == $fromCharset)
350                 {
351                     $isFound = true;
352                     break;
353                 }
354             }
355             $isMb = $isFound;
356         }
357
358         if($isMb)
359         {
360             return mb_convert_encoding($string, $toCharset, $fromCharset);
361         }
362         elseif($isIconv)
363         {
364             return iconv($fromCharset, $toCharset, $string);
365         }
366         else
367         {
368             return $string;
369         } // end else clause
370     }
371
372         /**
373          * translates a character set from one to another, and the into MIME-header friendly format
374          */
375         function translateCharsetMIME($string, $fromCharset, $toCharset='UTF-8', $encoding="Q") {
376                 $previousEncoding = mb_internal_encoding();
377             mb_internal_encoding($toCharset);
378                 $result = mb_encode_mimeheader($string, $toCharset, $encoding);
379                 mb_internal_encoding($previousEncoding);
380                 return $result;
381         }
382
383         function normalizeCharset($charset) {
384                 $charset = strtolower(preg_replace("/[\-\_]*/", "", $charset));
385                 return $charset;
386         }
387
388         /**
389          * returns an array of charsets with keys for available translations; appropriate for get_select_options_with_id()
390          */
391         function getCharsetSelect() {
392     //jc:12293 - the "labels" or "human-readable" representations of the various charsets
393     //should be translatable
394     $translated = array();
395     foreach($this->availableCharsets as $key)
396     {
397          //$translated[$key] = translate($value);
398          $translated[$key] = translate($key);
399     }
400
401                 return $translated;
402     //end:12293
403         }
404
405         /**
406          * returns the charset preferred in descending order: User, Sugar Config, DEFAULT
407          * @param string charset to override ALL, pass a valid charset here
408          * @return string charset the chosen character set
409          */
410         function getExportCharset($charset='', $user=null) {
411                 $charset = $this->getPrecedentPreference('default_export_charset', $user);
412                 return $charset;
413         }
414
415         /**
416          * returns the charset preferred in descending order: User, Sugar Config, DEFAULT
417          * @return string charset the chosen character set
418          */
419         function getOutboundEmailCharset($user=null) {
420                 $charset = $this->getPrecedentPreference('default_email_charset', $user);
421                 return $charset;
422         }
423         ////    END CHARSET TRANSLATION
424         ///////////////////////////////////////////////////////////////////////////
425
426         ///////////////////////////////////////////////////////////////////////////
427         ////    NUMBER DISPLAY FORMATTING CODE
428         function getDecimalSeparator($user=null) {
429                 $dec = $this->getPrecedentPreference('default_decimal_separator', $user);
430                 return $dec;
431         }
432
433         function getNumberGroupingSeparator($user=null) {
434                 $sep = $this->getPrecedentPreference('default_number_grouping_seperator', $user);
435                 return $sep;
436         }
437
438         function getPrecision($user=null) {
439                 $precision = $this->getPrecedentPreference('default_currency_significant_digits', $user);
440                 return $precision;
441         }
442
443         function getCurrencySymbol($user=null) {
444                 $dec = $this->getPrecedentPreference('default_currency_symbol', $user);
445                 return $dec;
446         }
447
448         /**
449          * returns a number formatted by user preference or system default
450          * @param string number Number to be formatted and returned
451          * @param string currencySymbol Currency symbol if override is necessary
452          * @param bool is_currency Flag to also return the currency symbol
453          * @return string Formatted number
454          */
455         function getLocaleFormattedNumber($number, $currencySymbol='', $is_currency=true, $user=null) {
456                 $fnum                   = $number;
457                 $majorDigits    = '';
458                 $minorDigits    = '';
459                 $dec                    = $this->getDecimalSeparator($user);
460                 $thou                   = $this->getNumberGroupingSeparator($user);
461                 $precision              = $this->getPrecision($user);
462                 $symbol                 = empty($currencySymbol) ? $this->getCurrencySymbol($user) : $currencySymbol;
463
464                 $exNum = explode($dec, $number);
465                 // handle grouping
466                 if(is_array($exNum) && count($exNum) > 0) {
467                         if(strlen($exNum[0]) > 3) {
468                                 $offset = strlen($exNum[0]) % 3;
469                                 if($offset > 0) {
470                                         for($i=0; $i<$offset; $i++) {
471                                                 $majorDigits .= $exNum[0]{$i};
472                                         }
473                                 }
474
475                                 $tic = 0;
476                                 for($i=$offset; $i<strlen($exNum[0]); $i++) {
477                                         if($tic % 3 == 0 && $i != 0) {
478                                                 $majorDigits .= $thou; // add separator
479                                         }
480
481                                         $majorDigits .= $exNum[0]{$i};
482                                         $tic++;
483                                 }
484                         } else {
485                                 $majorDigits = $exNum[0]; // no formatting needed
486                         }
487                         $fnum = $majorDigits;
488                 }
489
490                 // handle decimals
491                 if($precision > 0) { // we toss the minor digits otherwise
492                         if(is_array($exNum) && isset($exNum[1])) {
493
494                         }
495                 }
496
497
498                 if($is_currency) {
499                         $fnum = $symbol.$fnum;
500                 }
501                 return $fnum;
502         }
503
504         /**
505          * returns Javascript to format numbers and currency for ***DISPLAY***
506          */
507         function getNumberJs() {
508                 $out = <<<eoq
509
510                         var exampleDigits = '123456789.000000';
511
512                         // round parameter can be negative for decimal, precision has to be postive
513                         function formatNumber(n, sep, dec, precision) {
514                                 var majorDigits;
515                                 var minorDigits;
516                                 var formattedMajor = '';
517                                 var formattedMinor = '';
518
519                                 var nArray = n.split('.');
520                                 majorDigits = nArray[0];
521                                 if(nArray.length < 2) {
522                                         minorDigits = 0;
523                                 } else {
524                                         minorDigits = nArray[1];
525                                 }
526
527                                 // handle grouping
528                                 if(sep.length > 0) {
529                                         var strlength = majorDigits.length;
530
531                                         if(strlength > 3) {
532                                                 var offset = strlength % 3; // find how many to lead off by
533
534                                                 for(j=0; j<offset; j++) {
535                                                         formattedMajor += majorDigits[j];
536                                                 }
537
538                                                 tic=0;
539                                                 for(i=offset; i<strlength; i++) {
540                                                         if(tic % 3 == 0 && i != 0)
541                                                                 formattedMajor += sep;
542
543                                                         formattedMajor += majorDigits.substr(i,1);
544                                                         tic++;
545                                                 }
546                                         }
547                                 } else {
548                                         formattedMajor = majorDigits; // no grouping marker
549                                 }
550
551                                 // handle decimal precision
552                                 if(precision > 0) {
553                                         for(i=0; i<precision; i++) {
554                                                 if(minorDigits[i] != undefined)
555                                                         formattedMinor += minorDigits[i];
556                                                 else
557                                                         formattedMinor += '0';
558                                         }
559                                 } else {
560                                         // we're just returning the major digits, no decimal marker
561                                         dec = ''; // just in case
562                                 }
563
564                                 return formattedMajor + dec + formattedMinor;
565                         }
566
567                         function setSigDigits() {
568                                 var sym = document.getElementById('symbol').value;
569                                 var thou = document.getElementById('default_number_grouping_seperator').value;
570                                 var dec = document.getElementById('default_decimal_seperator').value;
571                                 var precision = document.getElementById('sigDigits').value;
572                                 //umber(n, num_grp_sep, dec_sep, round, precision)
573                                 var newNumber = sym + formatNumber(exampleDigits, thou, dec, precision, precision);
574                                 document.getElementById('sigDigitsExample').value = newNumber;
575                         }
576 eoq;
577                 return $out;
578         }
579
580         ////    END NUMBER DISPLAY FORMATTING CODE
581         ///////////////////////////////////////////////////////////////////////////
582
583         ///////////////////////////////////////////////////////////////////////////
584         ////    NAME DISPLAY FORMATTING CODE
585         /**
586          * get's the Name format macro string, preferring $current_user
587          * @return string format Name Format macro for locale
588          */
589         function getLocaleFormatMacro($user=null) {
590                 $returnFormat = $this->getPrecedentPreference('default_locale_name_format', $user);
591                 return $returnFormat;
592         }
593
594         /**
595          * returns formatted name according to $current_user's locale settings
596          *
597          * @param string firstName
598          * @param string lastName
599          * @param string salutation
600          * @param string title
601          * @param string format If a particular format is desired, then pass this optional parameter as a simple string.
602          * sfl is "Salutation FirstName LastName", "l, f s" is "LastName[comma][space]FirstName[space]Salutation"
603          * @param object user object
604          * @param bool returnEmptyStringIfEmpty true if we should return back an empty string rather than a single space
605          * when the formatted name would be blank
606          * @return string formattedName
607          */
608         function getLocaleFormattedName($firstName, $lastName, $salutationKey='', $title='', $format="", $user=null, $returnEmptyStringIfEmpty = false) {
609                 global $current_user;
610                 global $app_list_strings;
611
612                 if ( $user == null ) {
613                     $user = $current_user;
614                 }
615
616                 $salutation = $salutationKey;
617                 if(!empty($salutationKey) && !empty($app_list_strings['salutation_dom'][$salutationKey])) {
618                         $salutation = (!empty($app_list_strings['salutation_dom'][$salutationKey]) ? $app_list_strings['salutation_dom'][$salutationKey] : $salutationKey);
619                 }
620
621         //check to see if passed in variables are set, if so, then populate array with value,
622         //if not, then populate array with blank ''
623                 $names = array();
624                 $names['f'] = (empty($firstName)        && $firstName   != 0) ? '' : $firstName;
625                 $names['l'] = (empty($lastName) && $lastName    != 0) ? '' : $lastName;
626                 $names['s'] = (empty($salutation)       && $salutation  != 0) ? '' : $salutation;
627                 $names['t'] = (empty($title)            && $title               != 0) ? '' : $title;
628
629                 //Bug: 39936 - if all of the inputs are empty, then don't try to format the name.
630                 $allEmpty = true;
631                 foreach($names as $key => $val){
632                         if(!empty($val)){
633                                 $allEmpty = false;
634                                 break;
635                         }
636                 }
637                 if($allEmpty){
638                         return $returnEmptyStringIfEmpty ? '' : ' ';
639                 }
640                 //end Bug: 39936
641
642                 if(empty($format)) {
643                         $this->localeNameFormat = $this->getLocaleFormatMacro($user);
644                 } else {
645                         $this->localeNameFormat = $format;
646                 }
647
648                 // parse localeNameFormat
649                 $formattedName = '';
650                 for($i=0; $i<strlen($this->localeNameFormat); $i++) {
651                         $formattedName .= array_key_exists($this->localeNameFormat{$i}, $names) ? $names[$this->localeNameFormat{$i}] : $this->localeNameFormat{$i};
652                 }
653
654                 $formattedName = trim($formattedName);
655         if (strlen($formattedName)==0) {
656             return $returnEmptyStringIfEmpty ? '' : ' ';
657         }
658
659                 if(strpos($formattedName,',',strlen($formattedName)-1)) { // remove trailing commas
660                         $formattedName = substr($formattedName, 0, strlen($formattedName)-1);
661                 }
662                 return trim($formattedName);
663         }
664
665         /**
666          * outputs some simple Javascript to show a preview of Name format in "My Account" and "Admin->Localization"
667          * @param string first First Name, use app_strings default if not specified
668          * @param string last Last Name, use app_strings default if not specified
669          * @param string salutation Saluation, use app_strings default if not specified
670          * @return string some Javascript
671          */
672         function getNameJs($first='', $last='', $salutation='', $title='') {
673                 global $app_strings;
674
675                 $salutation     = !empty($salutation) ? $salutation : $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'];
676                 $first          = !empty($first) ? $first : $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'];
677                 $last           = !empty($last) ? $last : $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST'];
678                 $title          = !empty($title) ? $title : $app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE'];
679
680                 $ret = "
681                 function setPreview() {
682                         format = document.getElementById('default_locale_name_format').value;
683                         field = document.getElementById('nameTarget');
684
685                         stuff = new Object();
686
687                         stuff['s'] = '{$salutation}';
688                         stuff['f'] = '{$first}';
689                         stuff['l'] = '{$last}';
690                         stuff['t'] = '{$title}';
691
692                         var name = '';
693                         for(i=0; i<format.length; i++) {
694                 if(stuff[format.substr(i,1)] != undefined) {
695                     name += stuff[format.substr(i,1)];
696                                 } else {
697                     name += format.substr(i,1);
698                 }
699                         }
700
701                         //alert(name);
702                         field.value = name;
703                 }
704
705         ";
706
707                 return $ret;
708         }
709
710     /**
711      * Checks to see that the characters in $name_format are allowed:  s, f, l, space/tab or punctuation
712      * @param $name_format
713      * @return bool
714      */
715     public function isAllowedNameFormat($name_format) {
716         // will result in a match as soon as a disallowed char is hit in $name_format
717         $match = preg_match('/[^sfl[:punct:][:^alnum:]\s]/', $name_format);
718         if ($match !== false && $match === 0) {
719             return true;
720         }
721         return false;
722     }
723
724     /**
725      * Checks to see if there was an invalid Name Format encountered during the upgrade
726      * @return bool true if there was an invalid name, false if all went well.
727      */
728     public function invalidLocaleNameFormatUpgrade() {
729         return file_exists($this->invalidNameFormatUpgradeFilename);
730     }
731
732     /**
733      * Creates the file that is created when there is an invalid name format during an upgrade
734      */
735     public function createInvalidLocaleNameFormatUpgradeNotice() {
736         $fh = fopen($this->invalidNameFormatUpgradeFilename,'w');
737         fclose($fh);
738     }
739
740     /**
741      * Removes the file that is created when there is an invalid name format during an upgrade
742      */
743     public function removeInvalidLocaleNameFormatUpgradeNotice() {
744         if ($this->invalidLocaleNameFormatUpgrade()) {
745             unlink($this->invalidNameFormatUpgradeFilename);
746         }
747     }
748
749
750     /**
751      * Creates dropdown items that have localized example names while filtering out invalid formats
752      *
753      * @param array un-prettied dropdown list
754      * @return array array of dropdown options
755      */
756     public function getUsableLocaleNameOptions($options) {
757         global $app_strings;
758
759         $examples = array('s' => $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'],
760                         'f' => $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'],
761                         'l' => $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST']);
762         $newOpts = array();
763         foreach ($options as $key => $val) {
764             if ($this->isAllowedNameFormat($key) && $this->isAllowedNameFormat($val)) {
765                 $newVal = '';
766                 $pieces = str_split($val);
767                 foreach ($pieces as $piece) {
768                     if (isset($examples[$piece])) {
769                         $newVal .= $examples[$piece];
770                     } else {
771                         $newVal .= $piece;
772                     }
773                 }
774                 $newOpts[$key] = $newVal;
775             }
776         }
777         return $newOpts;
778     }
779         ////    END NAME DISPLAY FORMATTING CODE
780         ///////////////////////////////////////////////////////////////////////////
781
782     /**
783      * Attempts to detect the charset used in the string
784      *
785      * @param  $str string
786      * @return string
787      */
788     public function detectCharset(
789         $str
790         )
791     {
792         if ( function_exists('mb_convert_encoding') )
793             return mb_detect_encoding($str,'ASCII,JIS,UTF-8,EUC-JP,SJIS,ISO-8859-1');
794
795         return false;
796     }
797 } // end class def
798
799 ?>