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.
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.
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
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
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.
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.
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 ********************************************************************************/
39 * Localization manager
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
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
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
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';
84 function Localization() {
86 $this->localeNameFormatDefault = empty($sugar_config['locale_name_format_default']) ? 's f l' : $sugar_config['default_name_format'];
87 $this->loadCurrencies();
91 * returns an array of Sugar Config defaults that are determined by locale settings
94 function getLocaleConfigDefaults() {
95 $coreDefaults = array(
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,
111 return $coreDefaults;
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
120 function getPrecedentPreference($prefName, $user=null, $sugarConfigPrefName = '') {
121 global $current_user;
122 global $sugar_config;
125 $coreDefaults = $this->getLocaleConfigDefaults();
126 $pref = isset($coreDefaults[$prefName]) ? $coreDefaults[$prefName] : ''; // defaults, even before config.php
129 $userPref = $user->getPreference($prefName);
130 } elseif(!empty($current_user)) {
131 $userPref = $current_user->getPreference($prefName);
133 // Bug 39171 - If we are asking for default_email_charset, check in emailSettings['defaultOutboundCharset'] as well
134 if ( $prefName == 'default_email_charset' ) {
136 $emailSettings = $user->getPreference('emailSettings', 'Emails');
137 } elseif(!empty($current_user)) {
138 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
140 if ( isset($emailSettings['defaultOutboundCharset']) ) {
141 $userPref = $emailSettings['defaultOutboundCharset'];
145 // set fallback defaults defined in this class
146 if(isset($this->$prefName)) {
147 $pref = $this->$prefName;
149 //rrs: 33086 - give the ability to pass in the preference name as stored in $sugar_config.
150 if(!empty($sugarConfigPrefName)){
151 $prefName = $sugarConfigPrefName;
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;
159 ///////////////////////////////////////////////////////////////////////////
160 //// CURRENCY HANDLING
162 * wrapper for whatever currency system we implement
164 function loadCurrencies() {
165 // doing it dirty here
167 global $sugar_config;
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
182 $q = "SELECT id, name, symbol, conversion_rate FROM currencies WHERE status = 'Active' and deleted = 0";
185 while($a = $db->fetchByAssoc($r)) {
187 $load['name'] = $a['name'];
188 $load['symbol'] = $a['symbol'];
189 $load['conversion_rate'] = $a['conversion_rate'];
191 $this->currencies[$a['id']] = $load;
193 sugar_cache_put('currency_list',$this->currencies);
195 $this->currencies = $load;
202 * getter for currencies array
203 * @return array $this->currencies returns array( id => array(name => X, etc
205 function getCurrencies() {
206 return $this->currencies;
210 * retrieves default OOTB currencies for sugar_config and installer.
211 * @return array ret Array of default currencies keyed by ISO4217 code
213 function getDefaultCurrencies() {
215 'AUD' => array( 'name' => 'Australian Dollars',
218 'BRL' => array( 'name' => 'Brazilian Reais',
221 'GBP' => array( 'name' => 'British Pounds',
224 'CAD' => array( 'name' => 'Canadian Dollars',
227 'CNY' => array( 'name' => 'Chinese Yuan',
230 'EUR' => array( 'name' => 'Euro',
233 'HKD' => array( 'name' => 'Hong Kong Dollars',
236 'INR' => array( 'name' => 'Indian Rupees',
239 'KRW' => array( 'name' => 'Korean Won',
242 'YEN' => array( 'name' => 'Japanese Yen',
245 'MXM' => array( 'name' => 'Mexican Pesos',
248 'SGD' => array( 'name' => 'Singaporean Dollars',
251 'CHF' => array( 'name' => 'Swiss Franc',
254 'THB' => array( 'name' => 'Thai Baht',
257 'USD' => array( 'name' => 'US Dollars',
264 //// END CURRENCY HANDLING
265 ///////////////////////////////////////////////////////////////////////////
268 ///////////////////////////////////////////////////////////////////////////
269 //// CHARSET TRANSLATION
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
276 function translateStringPack($strings, $charset) {
278 foreach($strings as $k => $v) {
280 $strings[$k] = $this->translateStringPack($v, $charset);
282 $strings[$k] = $this->translateCharset($v, 'UTF-8', $charset);
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
294 function translateForEmail($var) {
296 foreach($var as $k => $v) {
297 $var[$k] = $this->translateForEmail($v);
300 } elseif(!empty($var)) {
301 return $this->translateCharset($var, 'UTF-8', $this->getOutboundEmailCharset());
306 * prepares a bean for export by translating any text fields into the export
308 * @param bean object A SugarBean
309 * @return bean object The bean with translated strings
311 function prepBeanForExport($bean)
313 foreach($bean->field_defs as $k => $field)
315 if (is_string($bean->$k))
317 // $bean->$k = $this->translateCharset($bean->$k, 'UTF-8', $this->getExportCharset());
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
335 function translateCharset($string, $fromCharset, $toCharset='UTF-8')
337 $GLOBALS['log']->debug("Localization: translating [ {$string} ] into {$toCharset}");
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');
344 $fromCharset = strtoupper($fromCharset);
345 $listEncodings = mb_list_encodings();
347 foreach ($listEncodings as $encoding)
349 if (strtoupper($encoding) == $fromCharset)
360 return mb_convert_encoding($string, $toCharset, $fromCharset);
364 return iconv($fromCharset, $toCharset, $string);
373 * translates a character set from one to another, and the into MIME-header friendly format
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);
383 function normalizeCharset($charset) {
384 $charset = strtolower(preg_replace("/[\-\_]*/", "", $charset));
389 * returns an array of charsets with keys for available translations; appropriate for get_select_options_with_id()
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)
397 //$translated[$key] = translate($value);
398 $translated[$key] = translate($key);
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
410 function getExportCharset($charset='', $user=null) {
411 $charset = $this->getPrecedentPreference('default_export_charset', $user);
416 * returns the charset preferred in descending order: User, Sugar Config, DEFAULT
417 * @return string charset the chosen character set
419 function getOutboundEmailCharset($user=null) {
420 $charset = $this->getPrecedentPreference('default_email_charset', $user);
423 //// END CHARSET TRANSLATION
424 ///////////////////////////////////////////////////////////////////////////
426 ///////////////////////////////////////////////////////////////////////////
427 //// NUMBER DISPLAY FORMATTING CODE
428 function getDecimalSeparator($user=null) {
429 $dec = $this->getPrecedentPreference('default_decimal_separator', $user);
433 function getNumberGroupingSeparator($user=null) {
434 $sep = $this->getPrecedentPreference('default_number_grouping_seperator', $user);
438 function getPrecision($user=null) {
439 $precision = $this->getPrecedentPreference('default_currency_significant_digits', $user);
443 function getCurrencySymbol($user=null) {
444 $dec = $this->getPrecedentPreference('default_currency_symbol', $user);
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
455 function getLocaleFormattedNumber($number, $currencySymbol='', $is_currency=true, $user=null) {
459 $dec = $this->getDecimalSeparator($user);
460 $thou = $this->getNumberGroupingSeparator($user);
461 $precision = $this->getPrecision($user);
462 $symbol = empty($currencySymbol) ? $this->getCurrencySymbol($user) : $currencySymbol;
464 $exNum = explode($dec, $number);
466 if(is_array($exNum) && count($exNum) > 0) {
467 if(strlen($exNum[0]) > 3) {
468 $offset = strlen($exNum[0]) % 3;
470 for($i=0; $i<$offset; $i++) {
471 $majorDigits .= $exNum[0]{$i};
476 for($i=$offset; $i<strlen($exNum[0]); $i++) {
477 if($tic % 3 == 0 && $i != 0) {
478 $majorDigits .= $thou; // add separator
481 $majorDigits .= $exNum[0]{$i};
485 $majorDigits = $exNum[0]; // no formatting needed
487 $fnum = $majorDigits;
491 if($precision > 0) { // we toss the minor digits otherwise
492 if(is_array($exNum) && isset($exNum[1])) {
499 $fnum = $symbol.$fnum;
505 * returns Javascript to format numbers and currency for ***DISPLAY***
507 function getNumberJs() {
510 var exampleDigits = '123456789.000000';
512 // round parameter can be negative for decimal, precision has to be postive
513 function formatNumber(n, sep, dec, precision) {
516 var formattedMajor = '';
517 var formattedMinor = '';
519 var nArray = n.split('.');
520 majorDigits = nArray[0];
521 if(nArray.length < 2) {
524 minorDigits = nArray[1];
529 var strlength = majorDigits.length;
532 var offset = strlength % 3; // find how many to lead off by
534 for(j=0; j<offset; j++) {
535 formattedMajor += majorDigits[j];
539 for(i=offset; i<strlength; i++) {
540 if(tic % 3 == 0 && i != 0)
541 formattedMajor += sep;
543 formattedMajor += majorDigits.substr(i,1);
548 formattedMajor = majorDigits; // no grouping marker
551 // handle decimal precision
553 for(i=0; i<precision; i++) {
554 if(minorDigits[i] != undefined)
555 formattedMinor += minorDigits[i];
557 formattedMinor += '0';
560 // we're just returning the major digits, no decimal marker
561 dec = ''; // just in case
564 return formattedMajor + dec + formattedMinor;
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;
580 //// END NUMBER DISPLAY FORMATTING CODE
581 ///////////////////////////////////////////////////////////////////////////
583 ///////////////////////////////////////////////////////////////////////////
584 //// NAME DISPLAY FORMATTING CODE
586 * get's the Name format macro string, preferring $current_user
587 * @return string format Name Format macro for locale
589 function getLocaleFormatMacro($user=null) {
590 $returnFormat = $this->getPrecedentPreference('default_locale_name_format', $user);
591 return $returnFormat;
595 * returns formatted name according to $current_user's locale settings
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
608 function getLocaleFormattedName($firstName, $lastName, $salutationKey='', $title='', $format="", $user=null, $returnEmptyStringIfEmpty = false) {
609 global $current_user;
610 global $app_list_strings;
612 if ( $user == null ) {
613 $user = $current_user;
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);
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 ''
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;
629 //Bug: 39936 - if all of the inputs are empty, then don't try to format the name.
631 foreach($names as $key => $val){
638 return $returnEmptyStringIfEmpty ? '' : ' ';
643 $this->localeNameFormat = $this->getLocaleFormatMacro($user);
645 $this->localeNameFormat = $format;
648 // parse localeNameFormat
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};
654 $formattedName = trim($formattedName);
655 if (strlen($formattedName)==0) {
656 return $returnEmptyStringIfEmpty ? '' : ' ';
659 if(strpos($formattedName,',',strlen($formattedName)-1)) { // remove trailing commas
660 $formattedName = substr($formattedName, 0, strlen($formattedName)-1);
662 return trim($formattedName);
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
672 function getNameJs($first='', $last='', $salutation='', $title='') {
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'];
681 function setPreview() {
682 format = document.getElementById('default_locale_name_format').value;
683 field = document.getElementById('nameTarget');
685 stuff = new Object();
687 stuff['s'] = '{$salutation}';
688 stuff['f'] = '{$first}';
689 stuff['l'] = '{$last}';
690 stuff['t'] = '{$title}';
693 for(i=0; i<format.length; i++) {
694 if(stuff[format.substr(i,1)] != undefined) {
695 name += stuff[format.substr(i,1)];
697 name += format.substr(i,1);
711 * Checks to see that the characters in $name_format are allowed: s, f, l, space/tab or punctuation
712 * @param $name_format
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) {
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.
728 public function invalidLocaleNameFormatUpgrade() {
729 return file_exists($this->invalidNameFormatUpgradeFilename);
733 * Creates the file that is created when there is an invalid name format during an upgrade
735 public function createInvalidLocaleNameFormatUpgradeNotice() {
736 $fh = fopen($this->invalidNameFormatUpgradeFilename,'w');
741 * Removes the file that is created when there is an invalid name format during an upgrade
743 public function removeInvalidLocaleNameFormatUpgradeNotice() {
744 if ($this->invalidLocaleNameFormatUpgrade()) {
745 unlink($this->invalidNameFormatUpgradeFilename);
751 * Creates dropdown items that have localized example names while filtering out invalid formats
753 * @param array un-prettied dropdown list
754 * @return array array of dropdown options
756 public function getUsableLocaleNameOptions($options) {
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']);
763 foreach ($options as $key => $val) {
764 if ($this->isAllowedNameFormat($key) && $this->isAllowedNameFormat($val)) {
766 $pieces = str_split($val);
767 foreach ($pieces as $piece) {
768 if (isset($examples[$piece])) {
769 $newVal .= $examples[$piece];
774 $newOpts[$key] = $newVal;
779 //// END NAME DISPLAY FORMATTING CODE
780 ///////////////////////////////////////////////////////////////////////////
783 * Attempts to detect the charset used in the string
788 public function detectCharset(
792 if ( function_exists('mb_convert_encoding') )
793 return mb_detect_encoding($str,'ASCII,JIS,UTF-8,EUC-JP,SJIS,ISO-8859-1');