Merge pull request #9773 from monishdeb/CRM-19663
[civicrm-core.git] / CRM / Admin / Form / Setting / Localization.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 */
33
34 /**
35 * This class generates form components for Localization.
36 */
37 class CRM_Admin_Form_Setting_Localization extends CRM_Admin_Form_Setting {
38
39 protected $_settings = array(
40 'contact_default_language' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
41 'countryLimit' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
42 'customTranslateFunction' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
43 'defaultContactCountry' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
44 'defaultContactStateProvince' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
45 'defaultCurrency' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
46 'fieldSeparator' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
47 'inheritLocale' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
48 'lcMessages' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
49 'legacyEncoding' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
50 'monetaryThousandSeparator' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
51 'monetaryDecimalPoint' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
52 'moneyformat' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
53 'moneyvalueformat' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
54 'provinceLimit' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
55 );
56
57 /**
58 * Build the form object.
59 */
60 public function buildQuickForm() {
61 $config = CRM_Core_Config::singleton();
62
63 CRM_Utils_System::setTitle(ts('Settings - Localization'));
64
65 $warningTitle = json_encode(ts("Warning"));
66 $defaultLocaleOptions = CRM_Admin_Form_Setting_Localization::getDefaultLocaleOptions();
67
68 $domain = new CRM_Core_DAO_Domain();
69 $domain->find(TRUE);
70
71 if ($domain->locales) {
72 // add language limiter and language adder
73 $this->addCheckBox('languageLimit', ts('Available Languages'), array_flip($defaultLocaleOptions), NULL, NULL, NULL, NULL, ' &nbsp; ');
74 $this->addElement('select', 'addLanguage', ts('Add Language'), array_merge(array('' => ts('- select -')), array_diff(CRM_Core_I18n::languages(), $defaultLocaleOptions)));
75
76 // add the ability to return to single language
77 $warning = ts('This will make your CiviCRM installation a single-language one again. THIS WILL DELETE ALL DATA RELATED TO LANGUAGES OTHER THAN THE DEFAULT ONE SELECTED ABOVE (and only that language will be preserved).');
78 $this->assign('warning', $warning);
79 $warning = json_encode($warning);
80 $this->addElement('checkbox', 'makeSinglelingual', ts('Return to Single Language'),
81 NULL, array('onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)")
82 );
83 }
84 else {
85 $warning = ts('Enabling multiple languages changes the schema of your database, so make sure you know what you are doing when enabling this function; making a database backup is strongly recommended.');
86 $this->assign('warning', $warning);
87 $warning = json_encode($warning);
88 $validTriggerPermission = CRM_Core_DAO::checkTriggerViewPermission(TRUE);
89
90 if ($validTriggerPermission &&
91 !\Civi::settings()->get('logging')
92 ) {
93 $this->addElement('checkbox', 'makeMultilingual', ts('Enable Multiple Languages'),
94 NULL, array('onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)")
95 );
96 }
97 }
98 $this->addElement('select', 'contact_default_language', ts('Default Language for users'),
99 CRM_Admin_Form_Setting_Localization::getDefaultLanguageOptions());
100
101 $includeCurrency = &$this->addElement('advmultiselect', 'currencyLimit',
102 ts('Available Currencies') . ' ', self::getCurrencySymbols(),
103 array(
104 'size' => 5,
105 'style' => 'width:150px',
106 'class' => 'advmultiselect',
107 )
108 );
109
110 $includeCurrency->setButtonAttributes('add', array('value' => ts('Add >>')));
111 $includeCurrency->setButtonAttributes('remove', array('value' => ts('<< Remove')));
112
113 $this->addFormRule(array('CRM_Admin_Form_Setting_Localization', 'formRule'));
114
115 parent::buildQuickForm();
116 }
117
118 /**
119 * @param $fields
120 *
121 * @return array|bool
122 */
123 public static function formRule($fields) {
124 $errors = array();
125 if (CRM_Utils_Array::value('monetaryThousandSeparator', $fields) ==
126 CRM_Utils_Array::value('monetaryDecimalPoint', $fields)
127 ) {
128 $errors['monetaryThousandSeparator'] = ts('Thousands Separator and Decimal Delimiter can not be the same.');
129 }
130
131 if (strlen($fields['monetaryThousandSeparator']) == 0) {
132 $errors['monetaryThousandSeparator'] = ts('Thousands Separator can not be empty. You can use a space character instead.');
133 }
134
135 if (strlen($fields['monetaryThousandSeparator']) > 1) {
136 $errors['monetaryThousandSeparator'] = ts('Thousands Separator can not have more than 1 character.');
137 }
138
139 if (strlen($fields['monetaryDecimalPoint']) > 1) {
140 $errors['monetaryDecimalPoint'] = ts('Decimal Delimiter can not have more than 1 character.');
141 }
142
143 if (trim($fields['customTranslateFunction']) &&
144 !function_exists(trim($fields['customTranslateFunction']))
145 ) {
146 $errors['customTranslateFunction'] = ts('Please define the custom translation function first.');
147 }
148
149 // CRM-7962, CRM-7713, CRM-9004
150 if (!empty($fields['defaultContactCountry']) &&
151 (!empty($fields['countryLimit']) &&
152 (!in_array($fields['defaultContactCountry'], $fields['countryLimit']))
153 )
154 ) {
155 $errors['defaultContactCountry'] = ts('Please select a default country that is in the list of available countries.');
156 }
157
158 return empty($errors) ? TRUE : $errors;
159 }
160
161 /**
162 * Set the default values for the form.
163 *
164 * @return array
165 */
166 public function setDefaultValues() {
167 parent::setDefaultValues();
168
169 // CRM-1496
170 // retrieve default values for currencyLimit
171 $this->_defaults['currencyLimit'] = array_keys(CRM_Core_OptionGroup::values('currencies_enabled'));
172
173 $this->_defaults['languageLimit'] = Civi::settings()->get('languageLimit');
174
175 // CRM-5111: unset these two unconditionally, we don’t want them to stick – ever
176 unset($this->_defaults['makeMultilingual']);
177 unset($this->_defaults['makeSinglelingual']);
178 return $this->_defaults;
179 }
180
181 public function postProcess() {
182 $values = $this->exportValues();
183
184 //cache contact fields retaining localized titles
185 //though we changed localization, so reseting cache.
186 CRM_Core_BAO_Cache::deleteGroup('contact fields');
187
188 //CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
189 CRM_Core_BAO_Cache::deleteGroup('navigation');
190
191 // we do this only to initialize monetary decimal point and thousand separator
192 $config = CRM_Core_Config::singleton();
193
194 // save enabled currencies and defaul currency in option group 'currencies_enabled'
195 // CRM-1496
196 if (empty($values['currencyLimit'])) {
197 $values['currencyLimit'] = array($values['defaultCurrency']);
198 }
199 elseif (!in_array($values['defaultCurrency'],
200 $values['currencyLimit']
201 )
202 ) {
203 $values['currencyLimit'][] = $values['defaultCurrency'];
204 }
205
206 // sort so that when we display drop down, weights have right value
207 sort($values['currencyLimit']);
208
209 // get labels for all the currencies
210 $options = array();
211
212 $currencySymbols = self::getCurrencySymbols();
213 for ($i = 0; $i < count($values['currencyLimit']); $i++) {
214 $options[] = array(
215 'label' => $currencySymbols[$values['currencyLimit'][$i]],
216 'value' => $values['currencyLimit'][$i],
217 'weight' => $i + 1,
218 'is_active' => 1,
219 'is_default' => $values['currencyLimit'][$i] == $values['defaultCurrency'],
220 );
221 }
222
223 $dontCare = NULL;
224 CRM_Core_OptionGroup::createAssoc('currencies_enabled',
225 $options,
226 $dontCare
227 );
228
229 // unset currencyLimit so we dont store there
230 unset($values['currencyLimit']);
231
232 // make the site multi-lang if requested
233 if (!empty($values['makeMultilingual'])) {
234 CRM_Core_I18n_Schema::makeMultilingual($values['lcMessages']);
235 $values['languageLimit'][$values['lcMessages']] = 1;
236 // make the site single-lang if requested
237 }
238 elseif (!empty($values['makeSinglelingual'])) {
239 CRM_Core_I18n_Schema::makeSinglelingual($values['lcMessages']);
240 $values['languageLimit'] = '';
241 }
242
243 // add a new db locale if the requested language is not yet supported by the db
244 if (!CRM_Utils_Array::value('makeSinglelingual', $values) and CRM_Utils_Array::value('addLanguage', $values)) {
245 $domain = new CRM_Core_DAO_Domain();
246 $domain->find(TRUE);
247 if (!substr_count($domain->locales, $values['addLanguage'])) {
248 CRM_Core_I18n_Schema::addLocale($values['addLanguage'], $values['lcMessages']);
249 }
250 $values['languageLimit'][$values['addLanguage']] = 1;
251 }
252
253 // if we manipulated the language list, return to the localization admin screen
254 $return = (bool) (CRM_Utils_Array::value('makeMultilingual', $values) or CRM_Utils_Array::value('addLanguage', $values));
255
256 $filteredValues = $values;
257 unset($filteredValues['makeMultilingual']);
258 unset($filteredValues['makeSinglelingual']);
259 unset($filteredValues['addLanguage']);
260 unset($filteredValues['languageLimit']);
261
262 Civi::settings()->set('languageLimit', CRM_Utils_Array::value('languageLimit', $values));
263
264 // save all the settings
265 parent::commonProcess($filteredValues);
266
267 if ($return) {
268 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/setting/localization', 'reset=1'));
269 }
270 }
271
272 /**
273 * @return array
274 */
275 public static function getAvailableCountries() {
276 $i18n = CRM_Core_I18n::singleton();
277 $country = array();
278 CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
279 $i18n->localizeArray($country, array('context' => 'country'));
280 asort($country);
281 return $country;
282 }
283
284 /**
285 * Get the default locale options.
286 *
287 * @return array
288 */
289 public static function getDefaultLocaleOptions() {
290 $domain = new CRM_Core_DAO_Domain();
291 $domain->find(TRUE);
292 $locales = CRM_Core_I18n::languages();
293 if ($domain->locales) {
294 // for multi-lingual sites, populate default language drop-down with available languages
295 $defaultLocaleOptions = array();
296 foreach ($locales as $loc => $lang) {
297 if (substr_count($domain->locales, $loc)) {
298 $defaultLocaleOptions[$loc] = $lang;
299 }
300 }
301 }
302 else {
303 $defaultLocaleOptions = $locales;
304 }
305 return $defaultLocaleOptions;
306 }
307
308 /**
309 * Get a list of currencies (with their symbols).
310 *
311 * @return array
312 * Array('USD' => 'USD ($)').
313 */
314 public static function getCurrencySymbols() {
315 $symbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', array(
316 'labelColumn' => 'symbol',
317 'orderColumn' => TRUE,
318 ));
319 $_currencySymbols = array();
320 foreach ($symbols as $key => $value) {
321 $_currencySymbols[$key] = "$key";
322 if ($value) {
323 $_currencySymbols[$key] .= " ($value)";
324 }
325 }
326 return $_currencySymbols;
327 }
328
329 /**
330 * Update session and uf_match table when the locale is updated.
331 *
332 * @param string $oldLocale
333 * @param string $newLocale
334 * @param array $metadata
335 * @param int $domainID
336 */
337 public static function onChangeLcMessages($oldLocale, $newLocale, $metadata, $domainID) {
338 if ($oldLocale == $newLocale) {
339 return;
340 }
341
342 $session = CRM_Core_Session::singleton();
343 if ($newLocale && $session->get('userID')) {
344 $ufm = new CRM_Core_DAO_UFMatch();
345 $ufm->contact_id = $session->get('userID');
346 if ($newLocale && $ufm->find(TRUE)) {
347 $ufm->language = $newLocale;
348 $ufm->save();
349 $session->set('lcMessages', $newLocale);
350 }
351 }
352 }
353
354 /**
355 * @return array
356 */
357 public static function getDefaultLanguageOptions() {
358 return array(
359 '*default*' => ts('Use default site language'),
360 'undefined' => ts('Leave undefined'),
361 'current_site_language' => ts('Use language in use at the time'),
362 );
363 }
364
365 }