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 ********************************************************************************/
38 /*********************************************************************************
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42 * Reserved. Contributor(s): ______________________________________..
43 * *******************************************************************************/
47 var $availableCharsets = array(
48 'BIG-5', //Taiwan and Hong Kong
49 /*'CP866' // ms-dos Cyrillic */
50 /*'CP949' //Microsoft Korean */
51 'CP1251', //MS Cyrillic
52 'CP1252', //MS Western European & US
53 'EUC-CN', //Simplified Chinese GB2312
54 'EUC-JP', //Unix Japanese
57 'ISO-2022-JP', //Japanese
58 'ISO-2022-KR', //Korean
59 'ISO-8859-1', //Western European and US
60 'ISO-8859-2', //Central and Eastern European
61 'ISO-8859-3', //Latin 3
62 'ISO-8859-4', //Latin 4
63 'ISO-8859-5', //Cyrillic
64 'ISO-8859-6', //Arabic
66 'ISO-8859-8', //Hebrew
67 'ISO-8859-9', //Latin 5
68 'ISO-8859-10', //Latin 6
69 'ISO-8859-13', //Latin 7
70 'ISO-8859-14', //Latin 8
71 'ISO-8859-15', //Latin 9
72 'KOI8-R', //Cyrillic Russian
73 'KOI8-U', //Cyrillic Ukranian
77 var $localeNameFormat;
78 var $localeNameFormatDefault;
79 var $default_export_charset = 'UTF-8';
80 var $default_email_charset = 'UTF-8';
81 var $currencies = array(); // array loaded with current currencies
87 function Localization() {
89 $this->localeNameFormatDefault = empty($sugar_config['locale_name_format_default']) ? 's f l' : $sugar_config['default_name_format'];
90 $this->loadCurrencies();
94 * returns an array of Sugar Config defaults that are determined by locale settings
97 function getLocaleConfigDefaults() {
98 $coreDefaults = array(
102 'default_currency_significant_digits' => 2,
103 'default_currency_symbol' => '$',
104 'default_export_charset' => $this->default_export_charset,
105 'default_locale_name_format' => 's f l',
106 'default_number_grouping_seperator' => ',',
107 'default_decimal_seperator' => '.',
108 'export_delimiter' => ',',
109 'default_email_charset' => $this->default_email_charset,
112 return $coreDefaults;
116 * abstraction of precedence
117 * @param string prefName Name of preference to retrieve based on overrides
118 * @param object user User in focus, default null (current_user)
119 * @return string pref Most significant preference
121 function getPrecedentPreference($prefName, $user=null, $sugarConfigPrefName = '') {
122 global $current_user;
123 global $sugar_config;
126 $coreDefaults = $this->getLocaleConfigDefaults();
127 $pref = isset($coreDefaults[$prefName]) ? $coreDefaults[$prefName] : ''; // defaults, even before config.php
130 $userPref = $user->getPreference($prefName);
131 } elseif(!empty($current_user)) {
132 $userPref = $current_user->getPreference($prefName);
134 // Bug 39171 - If we are asking for default_email_charset, check in emailSettings['defaultOutboundCharset'] as well
135 if ( $prefName == 'default_email_charset' ) {
137 $emailSettings = $user->getPreference('emailSettings', 'Emails');
138 } elseif(!empty($current_user)) {
139 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
141 if ( isset($emailSettings['defaultOutboundCharset']) ) {
142 $userPref = $emailSettings['defaultOutboundCharset'];
146 // set fallback defaults defined in this class
147 if(isset($this->$prefName)) {
148 $pref = $this->$prefName;
150 //rrs: 33086 - give the ability to pass in the preference name as stored in $sugar_config.
151 if(!empty($sugarConfigPrefName)){
152 $prefName = $sugarConfigPrefName;
154 // cn: 9549 empty() call on a value of 0 (0 significant digits) resulted in a false-positive. changing to "isset()"
155 $pref = (!isset($sugar_config[$prefName]) || (empty($sugar_config[$prefName]) && $sugar_config[$prefName] !== '0')) ? $pref : $sugar_config[$prefName];
156 $pref = (empty($userPref) && $userPref !== '0') ? $pref : $userPref;
160 ///////////////////////////////////////////////////////////////////////////
161 //// CURRENCY HANDLING
163 * wrapper for whatever currency system we implement
165 function loadCurrencies() {
166 // doing it dirty here
168 global $sugar_config;
174 $load = sugar_cache_retrieve('currency_list');
175 if ( !is_array($load) ) {
176 // load default from config.php
177 $this->currencies['-99'] = array(
178 'name' => $sugar_config['default_currency_name'],
179 'symbol' => $sugar_config['default_currency_symbol'],
180 'conversion_rate' => 1
183 $q = "SELECT id, name, symbol, conversion_rate FROM currencies WHERE status = 'Active' and deleted = 0";
186 while($a = $db->fetchByAssoc($r)) {
188 $load['name'] = $a['name'];
189 $load['symbol'] = $a['symbol'];
190 $load['conversion_rate'] = $a['conversion_rate'];
192 $this->currencies[$a['id']] = $load;
194 sugar_cache_put('currency_list',$this->currencies);
196 $this->currencies = $load;
203 * getter for currencies array
204 * @return array $this->currencies returns array( id => array(name => X, etc
206 function getCurrencies() {
207 return $this->currencies;
211 * retrieves default OOTB currencies for sugar_config and installer.
212 * @return array ret Array of default currencies keyed by ISO4217 code
214 function getDefaultCurrencies() {
216 'AUD' => array( 'name' => 'Australian Dollars',
219 'BRL' => array( 'name' => 'Brazilian Reais',
222 'GBP' => array( 'name' => 'British Pounds',
225 'CAD' => array( 'name' => 'Canadian Dollars',
228 'CNY' => array( 'name' => 'Chinese Yuan',
231 'EUR' => array( 'name' => 'Euro',
234 'HKD' => array( 'name' => 'Hong Kong Dollars',
237 'INR' => array( 'name' => 'Indian Rupees',
240 'KRW' => array( 'name' => 'Korean Won',
243 'YEN' => array( 'name' => 'Japanese Yen',
246 'MXM' => array( 'name' => 'Mexican Pesos',
249 'SGD' => array( 'name' => 'Singaporean Dollars',
252 'CHF' => array( 'name' => 'Swiss Franc',
255 'THB' => array( 'name' => 'Thai Baht',
258 'USD' => array( 'name' => 'US Dollars',
265 //// END CURRENCY HANDLING
266 ///////////////////////////////////////////////////////////////////////////
269 ///////////////////////////////////////////////////////////////////////////
270 //// CHARSET TRANSLATION
272 * returns a mod|app_strings array in the target charset
273 * @param array strings $mod_string, et.al.
274 * @param string charset Target charset
275 * @return array Translated string pack
277 function translateStringPack($strings, $charset) {
279 foreach($strings as $k => $v) {
281 $strings[$k] = $this->translateStringPack($v, $charset);
283 $strings[$k] = $this->translateCharset($v, 'UTF-8', $charset);
291 * translates the passed variable for email sending (export)
292 * @param mixed the var (array or string) to translate
293 * @return mixed the translated variable
295 function translateForEmail($var) {
297 foreach($var as $k => $v) {
298 $var[$k] = $this->translateForEmail($v);
301 } elseif(!empty($var)) {
302 return $this->translateCharset($var, 'UTF-8', $this->getOutboundEmailCharset());
307 * prepares a bean for export by translating any text fields into the export
309 * @param bean object A SugarBean
310 * @return bean object The bean with translated strings
312 function prepBeanForExport($bean) {
313 foreach($bean->field_defs as $k => $field) {
314 $bean->$k = $this->translateCharset($bean->$k, 'UTF-8', $this->getExportCharset());
321 * translates a character set from one encoding to another encoding
322 * @param string string the string to be translated
323 * @param string fromCharset the charset the string is currently in
324 * @param string toCharset the charset to translate into (defaults to UTF-8)
325 * @return string the translated string
327 function translateCharset($string, $fromCharset, $toCharset='UTF-8') {
328 $GLOBALS['log']->debug("Localization: translating [ {$string} ] into {$toCharset}");
329 if(function_exists('mb_convert_encoding')) {
330 return mb_convert_encoding($string, $toCharset, $fromCharset);
331 } elseif(function_exists('iconv')) { // iconv is flakey
332 return iconv($fromCharset, $toCharset, $string);
339 * translates a character set from one to another, and the into MIME-header friendly format
341 function translateCharsetMIME($string, $fromCharset, $toCharset='UTF-8', $encoding="Q") {
342 $previousEncoding = mb_internal_encoding();
343 mb_internal_encoding($toCharset);
344 $result = mb_encode_mimeheader($string, $toCharset, $encoding);
345 mb_internal_encoding($previousEncoding);
349 function normalizeCharset($charset) {
350 $charset = strtolower(preg_replace("/[\-\_]*/", "", $charset));
355 * returns an array of charsets with keys for available translations; appropriate for get_select_options_with_id()
357 function getCharsetSelect() {
358 //jc:12293 - the "labels" or "human-readable" representations of the various charsets
359 //should be translatable
360 $translated = array();
361 foreach($this->availableCharsets as $key)
363 //$translated[$key] = translate($value);
364 $translated[$key] = translate($key);
372 * returns the charset preferred in descending order: User, Sugar Config, DEFAULT
373 * @param string charset to override ALL, pass a valid charset here
374 * @return string charset the chosen character set
376 function getExportCharset($charset='', $user=null) {
377 $charset = $this->getPrecedentPreference('default_export_charset', $user);
382 * returns the charset preferred in descending order: User, Sugar Config, DEFAULT
383 * @return string charset the chosen character set
385 function getOutboundEmailCharset($user=null) {
386 $charset = $this->getPrecedentPreference('default_email_charset', $user);
389 //// END CHARSET TRANSLATION
390 ///////////////////////////////////////////////////////////////////////////
392 ///////////////////////////////////////////////////////////////////////////
393 //// NUMBER DISPLAY FORMATTING CODE
394 function getDecimalSeparator($user=null) {
395 $dec = $this->getPrecedentPreference('default_decimal_separator', $user);
399 function getNumberGroupingSeparator($user=null) {
400 $sep = $this->getPrecedentPreference('default_number_grouping_seperator', $user);
404 function getPrecision($user=null) {
405 $precision = $this->getPrecedentPreference('default_currency_significant_digits', $user);
409 function getCurrencySymbol($user=null) {
410 $dec = $this->getPrecedentPreference('default_currency_symbol', $user);
415 * returns a number formatted by user preference or system default
416 * @param string number Number to be formatted and returned
417 * @param string currencySymbol Currency symbol if override is necessary
418 * @param bool is_currency Flag to also return the currency symbol
419 * @return string Formatted number
421 function getLocaleFormattedNumber($number, $currencySymbol='', $is_currency=true, $user=null) {
425 $dec = $this->getDecimalSeparator($user);
426 $thou = $this->getNumberGroupingSeparator($user);
427 $precision = $this->getPrecision($user);
428 $symbol = empty($currencySymbol) ? $this->getCurrencySymbol($user) : $currencySymbol;
430 $exNum = explode($dec, $number);
432 if(is_array($exNum) && count($exNum) > 0) {
433 if(strlen($exNum[0]) > 3) {
434 $offset = strlen($exNum[0]) % 3;
436 for($i=0; $i<$offset; $i++) {
437 $majorDigits .= $exNum[0]{$i};
442 for($i=$offset; $i<strlen($exNum[0]); $i++) {
443 if($tic % 3 == 0 && $i != 0) {
444 $majorDigits .= $thou; // add separator
447 $majorDigits .= $exNum[0]{$i};
451 $majorDigits = $exNum[0]; // no formatting needed
453 $fnum = $majorDigits;
457 if($precision > 0) { // we toss the minor digits otherwise
458 if(is_array($exNum) && isset($exNum[1])) {
465 $fnum = $symbol.$fnum;
471 * returns Javascript to format numbers and currency for ***DISPLAY***
473 function getNumberJs() {
476 var exampleDigits = '123456789.000000';
478 // round parameter can be negative for decimal, precision has to be postive
479 function formatNumber(n, sep, dec, precision) {
482 var formattedMajor = '';
483 var formattedMinor = '';
485 var nArray = n.split('.');
486 majorDigits = nArray[0];
487 if(nArray.length < 2) {
490 minorDigits = nArray[1];
495 var strlength = majorDigits.length;
498 var offset = strlength % 3; // find how many to lead off by
500 for(j=0; j<offset; j++) {
501 formattedMajor += majorDigits[j];
505 for(i=offset; i<strlength; i++) {
506 if(tic % 3 == 0 && i != 0)
507 formattedMajor += sep;
509 formattedMajor += majorDigits.substr(i,1);
514 formattedMajor = majorDigits; // no grouping marker
517 // handle decimal precision
519 for(i=0; i<precision; i++) {
520 if(minorDigits[i] != undefined)
521 formattedMinor += minorDigits[i];
523 formattedMinor += '0';
526 // we're just returning the major digits, no decimal marker
527 dec = ''; // just in case
530 return formattedMajor + dec + formattedMinor;
533 function setSigDigits() {
534 var sym = document.getElementById('symbol').value;
535 var thou = document.getElementById('default_number_grouping_seperator').value;
536 var dec = document.getElementById('default_decimal_seperator').value;
537 var precision = document.getElementById('sigDigits').value;
538 //umber(n, num_grp_sep, dec_sep, round, precision)
539 var newNumber = sym + formatNumber(exampleDigits, thou, dec, precision, precision);
540 document.getElementById('sigDigitsExample').value = newNumber;
546 //// END NUMBER DISPLAY FORMATTING CODE
547 ///////////////////////////////////////////////////////////////////////////
549 ///////////////////////////////////////////////////////////////////////////
550 //// NAME DISPLAY FORMATTING CODE
552 * get's the Name format macro string, preferring $current_user
553 * @return string format Name Format macro for locale
555 function getLocaleFormatMacro($user=null) {
556 $returnFormat = $this->getPrecedentPreference('default_locale_name_format', $user);
557 return $returnFormat;
561 * returns formatted name according to $current_user's locale settings
563 * @param string firstName
564 * @param string lastName
565 * @param string salutation
566 * @param string title
567 * @param string format If a particular format is desired, then pass this optional parameter as a simple string.
568 * sfl is "Salutation FirstName LastName", "l, f s" is "LastName[comma][space]FirstName[space]Salutation"
569 * @param object user object
570 * @param bool returnEmptyStringIfEmpty true if we should return back an empty string rather than a single space
571 * when the formatted name would be blank
572 * @return string formattedName
574 function getLocaleFormattedName($firstName, $lastName, $salutationKey='', $title='', $format="", $user=null, $returnEmptyStringIfEmpty = false) {
575 global $current_user;
576 global $app_list_strings;
578 if ( $user == null ) {
579 $user = $current_user;
582 $salutation = $salutationKey;
583 if(!empty($salutationKey) && !empty($app_list_strings['salutation_dom'][$salutationKey])) {
584 $salutation = (!empty($app_list_strings['salutation_dom'][$salutationKey]) ? $app_list_strings['salutation_dom'][$salutationKey] : $salutationKey);
587 //check to see if passed in variables are set, if so, then populate array with value,
588 //if not, then populate array with blank ''
590 $names['f'] = (empty($firstName) && $firstName != 0) ? '' : $firstName;
591 $names['l'] = (empty($lastName) && $lastName != 0) ? '' : $lastName;
592 $names['s'] = (empty($salutation) && $salutation != 0) ? '' : $salutation;
593 $names['t'] = (empty($title) && $title != 0) ? '' : $title;
595 //Bug: 39936 - if all of the inputs are empty, then don't try to format the name.
597 foreach($names as $key => $val){
604 return $returnEmptyStringIfEmpty ? '' : ' ';
609 $this->localeNameFormat = $this->getLocaleFormatMacro($user);
611 $this->localeNameFormat = $format;
614 // parse localeNameFormat
616 for($i=0; $i<strlen($this->localeNameFormat); $i++) {
617 $formattedName .= array_key_exists($this->localeNameFormat{$i}, $names) ? $names[$this->localeNameFormat{$i}] : $this->localeNameFormat{$i};
620 $formattedName = trim($formattedName);
621 if (strlen($formattedName)==0) {
622 return $returnEmptyStringIfEmpty ? '' : ' ';
625 if(strpos($formattedName,',',strlen($formattedName)-1)) { // remove trailing commas
626 $formattedName = substr($formattedName, 0, strlen($formattedName)-1);
628 return trim($formattedName);
632 * outputs some simple Javascript to show a preview of Name format in "My Account" and "Admin->Localization"
633 * @param string first First Name, use app_strings default if not specified
634 * @param string last Last Name, use app_strings default if not specified
635 * @param string salutation Saluation, use app_strings default if not specified
636 * @return string some Javascript
638 function getNameJs($first='', $last='', $salutation='', $title='') {
641 $salutation = !empty($salutation) ? $salutation : $app_strings['LBL_LOCALE_NAME_EXAMPLE_SALUTATION'];
642 $first = !empty($first) ? $first : $app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST'];
643 $last = !empty($last) ? $last : $app_strings['LBL_LOCALE_NAME_EXAMPLE_LAST'];
644 $title = !empty($title) ? $title : $app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE'];
647 function setPreview() {
648 format = document.getElementById('default_locale_name_format').value;
649 field = document.getElementById('nameTarget');
651 stuff = new Object();
653 stuff['s'] = '{$salutation}';
654 stuff['f'] = '{$first}';
655 stuff['l'] = '{$last}';
656 stuff['t'] = '{$title}';
659 for(i=0; i<format.length; i++) {
660 if(stuff[format.substr(i,1)] != undefined) {
661 name += stuff[format.substr(i,1)];
663 name += format.substr(i,1);
675 //// END NAME DISPLAY FORMATTING CODE
676 ///////////////////////////////////////////////////////////////////////////
679 * Attempts to detect the charset used in the string
684 public function detectCharset(
688 if ( function_exists('mb_convert_encoding') )
689 return mb_detect_encoding($str,'ASCII,JIS,UTF-8,EUC-JP,SJIS,ISO-8859-1');