(NFC) Update CRM/Activity CRM/Admin and CRM/Batch folders to be the future coder...
[civicrm-core.git] / CRM / Admin / Form / Setting / Localization.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 = [
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 'uiLanguages' => CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME,
56 ];
57
58 public function preProcess() {
59 if (!CRM_Core_I18n::isMultiLingual()) {
60 CRM_Core_Resources::singleton()
61 ->addScriptFile('civicrm', 'templates/CRM/Admin/Form/Setting/Localization.js', 1, 'html-header');
62 }
63 }
64
65 /**
66 * Build the form object.
67 */
68 public function buildQuickForm() {
69 $config = CRM_Core_Config::singleton();
70
71 CRM_Utils_System::setTitle(ts('Settings - Localization'));
72
73 $warningTitle = json_encode(ts("Warning"));
74 $defaultLocaleOptions = CRM_Admin_Form_Setting_Localization::getDefaultLocaleOptions();
75
76 if (CRM_Core_I18n::isMultiLingual()) {
77 // add language limiter and language adder
78 $this->addCheckBox('languageLimit', ts('Available Languages'), array_flip($defaultLocaleOptions), NULL, NULL, NULL, NULL, ' &nbsp; ');
79 $this->addElement('select', 'addLanguage', ts('Add Language'), array_merge(['' => ts('- select -')], array_diff(CRM_Core_I18n::languages(), $defaultLocaleOptions)));
80
81 // add the ability to return to single language
82 $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).');
83 $this->assign('warning', $warning);
84 $warning = json_encode($warning);
85 $this->addElement('checkbox', 'makeSinglelingual', ts('Return to Single Language'),
86 NULL, ['onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)"]
87 );
88 }
89 else {
90 $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.');
91 $this->assign('warning', $warning);
92 $warning = json_encode($warning);
93 $validTriggerPermission = CRM_Core_DAO::checkTriggerViewPermission(TRUE);
94
95 if ($validTriggerPermission &&
96 !\Civi::settings()->get('logging')
97 ) {
98 $this->addElement('checkbox', 'makeMultilingual', ts('Enable Multiple Languages'),
99 NULL, ['onChange' => "if (this.checked) CRM.alert($warning, $warningTitle)"]
100 );
101 }
102 }
103 $this->addElement('select', 'contact_default_language', ts('Default Language for users'),
104 CRM_Admin_Form_Setting_Localization::getDefaultLanguageOptions());
105
106 $includeCurrency = &$this->addElement('advmultiselect', 'currencyLimit',
107 ts('Available Currencies') . ' ', self::getCurrencySymbols(),
108 [
109 'size' => 5,
110 'style' => 'width:150px',
111 'class' => 'advmultiselect',
112 ]
113 );
114
115 $includeCurrency->setButtonAttributes('add', ['value' => ts('Add >>')]);
116 $includeCurrency->setButtonAttributes('remove', ['value' => ts('<< Remove')]);
117
118 $this->addFormRule(['CRM_Admin_Form_Setting_Localization', 'formRule']);
119
120 parent::buildQuickForm();
121 }
122
123 /**
124 * @param $fields
125 *
126 * @return array|bool
127 */
128 public static function formRule($fields) {
129 $errors = [];
130 if (CRM_Utils_Array::value('monetaryThousandSeparator', $fields) ==
131 CRM_Utils_Array::value('monetaryDecimalPoint', $fields)
132 ) {
133 $errors['monetaryThousandSeparator'] = ts('Thousands Separator and Decimal Delimiter can not be the same.');
134 }
135
136 if (strlen($fields['monetaryThousandSeparator']) == 0) {
137 $errors['monetaryThousandSeparator'] = ts('Thousands Separator can not be empty. You can use a space character instead.');
138 }
139
140 if (strlen($fields['monetaryThousandSeparator']) > 1) {
141 $errors['monetaryThousandSeparator'] = ts('Thousands Separator can not have more than 1 character.');
142 }
143
144 if (strlen($fields['monetaryDecimalPoint']) > 1) {
145 $errors['monetaryDecimalPoint'] = ts('Decimal Delimiter can not have more than 1 character.');
146 }
147
148 if (trim($fields['customTranslateFunction']) &&
149 !function_exists(trim($fields['customTranslateFunction']))
150 ) {
151 $errors['customTranslateFunction'] = ts('Please define the custom translation function first.');
152 }
153
154 // CRM-7962, CRM-7713, CRM-9004
155 if (!empty($fields['defaultContactCountry']) &&
156 (!empty($fields['countryLimit']) &&
157 (!in_array($fields['defaultContactCountry'], $fields['countryLimit']))
158 )
159 ) {
160 $errors['defaultContactCountry'] = ts('Please select a default country that is in the list of available countries.');
161 }
162
163 return empty($errors) ? TRUE : $errors;
164 }
165
166 /**
167 * Set the default values for the form.
168 *
169 * @return array
170 */
171 public function setDefaultValues() {
172 parent::setDefaultValues();
173
174 // CRM-1496
175 // retrieve default values for currencyLimit
176 $this->_defaults['currencyLimit'] = array_keys(CRM_Core_OptionGroup::values('currencies_enabled'));
177
178 $this->_defaults['languageLimit'] = Civi::settings()->get('languageLimit');
179
180 // CRM-5111: unset these two unconditionally, we don’t want them to stick – ever
181 unset($this->_defaults['makeMultilingual']);
182 unset($this->_defaults['makeSinglelingual']);
183 return $this->_defaults;
184 }
185
186 public function postProcess() {
187 $values = $this->exportValues();
188
189 //cache contact fields retaining localized titles
190 //though we changed localization, so reseting cache.
191 CRM_Core_BAO_Cache::deleteGroup('contact fields');
192
193 //CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
194 CRM_Core_BAO_Cache::deleteGroup('navigation');
195
196 // we do this only to initialize monetary decimal point and thousand separator
197 $config = CRM_Core_Config::singleton();
198
199 // save enabled currencies and default currency in option group 'currencies_enabled'
200 // CRM-1496
201 if (empty($values['currencyLimit'])) {
202 $values['currencyLimit'] = [$values['defaultCurrency']];
203 }
204 elseif (!in_array($values['defaultCurrency'], $values['currencyLimit'])) {
205 $values['currencyLimit'][] = $values['defaultCurrency'];
206 }
207
208 self::updateEnabledCurrencies($values['currencyLimit'], $values['defaultCurrency']);
209
210 // unset currencyLimit so we dont store there
211 unset($values['currencyLimit']);
212
213 // make the site multi-lang if requested
214 if (!empty($values['makeMultilingual'])) {
215 CRM_Core_I18n_Schema::makeMultilingual($values['lcMessages']);
216 $values['languageLimit'][$values['lcMessages']] = 1;
217 // make the site single-lang if requested
218 }
219 elseif (!empty($values['makeSinglelingual'])) {
220 CRM_Core_I18n_Schema::makeSinglelingual($values['lcMessages']);
221 $values['languageLimit'] = '';
222 }
223
224 // add a new db locale if the requested language is not yet supported by the db
225 if (!CRM_Utils_Array::value('makeSinglelingual', $values) and CRM_Utils_Array::value('addLanguage', $values)) {
226 $domain = new CRM_Core_DAO_Domain();
227 $domain->find(TRUE);
228 if (!substr_count($domain->locales, $values['addLanguage'])) {
229 CRM_Core_I18n_Schema::addLocale($values['addLanguage'], $values['lcMessages']);
230 }
231 $values['languageLimit'][$values['addLanguage']] = 1;
232 }
233
234 // current language should be in the ui list
235 if (!in_array($values['lcMessages'], $values['uiLanguages'])) {
236 $values['uiLanguages'][] = $values['lcMessages'];
237 }
238
239 // if we manipulated the language list, return to the localization admin screen
240 $return = (bool) (CRM_Utils_Array::value('makeMultilingual', $values) or CRM_Utils_Array::value('addLanguage', $values));
241
242 $filteredValues = $values;
243 unset($filteredValues['makeMultilingual']);
244 unset($filteredValues['makeSinglelingual']);
245 unset($filteredValues['addLanguage']);
246 unset($filteredValues['languageLimit']);
247
248 Civi::settings()->set('languageLimit', CRM_Utils_Array::value('languageLimit', $values));
249
250 // save all the settings
251 parent::commonProcess($filteredValues);
252
253 if ($return) {
254 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/setting/localization', 'reset=1'));
255 }
256 }
257
258 /**
259 * Replace available currencies by the ones provided
260 *
261 * @param $currencies array of currencies ['USD', 'CAD']
262 * @param $default default currency
263 */
264 public static function updateEnabledCurrencies($currencies, $default) {
265
266 // sort so that when we display drop down, weights have right value
267 sort($currencies);
268
269 // get labels for all the currencies
270 $options = [];
271
272 $currencySymbols = CRM_Admin_Form_Setting_Localization::getCurrencySymbols();
273 for ($i = 0; $i < count($currencies); $i++) {
274 $options[] = [
275 'label' => $currencySymbols[$currencies[$i]],
276 'value' => $currencies[$i],
277 'weight' => $i + 1,
278 'is_active' => 1,
279 'is_default' => $currencies[$i] == $default,
280 ];
281 }
282
283 $dontCare = NULL;
284 CRM_Core_OptionGroup::createAssoc('currencies_enabled', $options, $dontCare);
285
286 }
287
288 /**
289 * @return array
290 */
291 public static function getAvailableCountries() {
292 $i18n = CRM_Core_I18n::singleton();
293 $country = [];
294 CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
295 $i18n->localizeArray($country, ['context' => 'country']);
296 asort($country);
297 return $country;
298 }
299
300 /**
301 * Get the default locale options.
302 *
303 * @return array
304 */
305 public static function getDefaultLocaleOptions() {
306 $domain = new CRM_Core_DAO_Domain();
307 $domain->find(TRUE);
308 $locales = CRM_Core_I18n::languages();
309 if ($domain->locales) {
310 // for multi-lingual sites, populate default language drop-down with available languages
311 $defaultLocaleOptions = [];
312 foreach ($locales as $loc => $lang) {
313 if (substr_count($domain->locales, $loc)) {
314 $defaultLocaleOptions[$loc] = $lang;
315 }
316 }
317 }
318 else {
319 $defaultLocaleOptions = $locales;
320 }
321 return $defaultLocaleOptions;
322 }
323
324 /**
325 * Get a list of currencies (with their symbols).
326 *
327 * @return array
328 * Array('USD' => 'USD ($)').
329 */
330 public static function getCurrencySymbols() {
331 $symbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
332 'labelColumn' => 'symbol',
333 'orderColumn' => TRUE,
334 ]);
335 $_currencySymbols = [];
336 foreach ($symbols as $key => $value) {
337 $_currencySymbols[$key] = "$key";
338 if ($value) {
339 $_currencySymbols[$key] .= " ($value)";
340 }
341 }
342 return $_currencySymbols;
343 }
344
345 /**
346 * Update session and uf_match table when the locale is updated.
347 *
348 * @param string $oldLocale
349 * @param string $newLocale
350 * @param array $metadata
351 * @param int $domainID
352 */
353 public static function onChangeLcMessages($oldLocale, $newLocale, $metadata, $domainID) {
354 if ($oldLocale == $newLocale) {
355 return;
356 }
357
358 $session = CRM_Core_Session::singleton();
359 if ($newLocale && $session->get('userID')) {
360 $ufm = new CRM_Core_DAO_UFMatch();
361 $ufm->contact_id = $session->get('userID');
362 if ($newLocale && $ufm->find(TRUE)) {
363 $ufm->language = $newLocale;
364 $ufm->save();
365 $session->set('lcMessages', $newLocale);
366 }
367 }
368 }
369
370 public static function onChangeDefaultCurrency($oldCurrency, $newCurrency, $metadata) {
371 if ($oldCurrency == $newCurrency) {
372 return;
373 }
374
375 // ensure that default currency is always in the list of enabled currencies
376 $currencies = array_keys(CRM_Core_OptionGroup::values('currencies_enabled'));
377 if (!in_array($newCurrency, $currencies)) {
378 if (empty($currencies)) {
379 $currencies = [$values['defaultCurrency']];
380 }
381 else {
382 $currencies[] = $newCurrency;
383 }
384
385 CRM_Admin_Form_Setting_Localization::updateEnabledCurrencies($currencies, $newCurrency);
386 }
387
388 }
389
390 /**
391 * @return array
392 */
393 public static function getDefaultLanguageOptions() {
394 return [
395 '*default*' => ts('Use default site language'),
396 'undefined' => ts('Leave undefined'),
397 'current_site_language' => ts('Use language in use at the time'),
398 ];
399 }
400
401 }