Convert the contact fields cache group to standard cache backend
[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['monetaryDecimalPoint']) > 1) {
141 $errors['monetaryDecimalPoint'] = ts('Decimal Delimiter can not have more than 1 character.');
142 }
143
144 if (trim($fields['customTranslateFunction']) &&
145 !function_exists(trim($fields['customTranslateFunction']))
146 ) {
147 $errors['customTranslateFunction'] = ts('Please define the custom translation function first.');
148 }
149
150 // CRM-7962, CRM-7713, CRM-9004
151 if (!empty($fields['defaultContactCountry']) &&
152 (!empty($fields['countryLimit']) &&
153 (!in_array($fields['defaultContactCountry'], $fields['countryLimit']))
154 )
155 ) {
156 $errors['defaultContactCountry'] = ts('Please select a default country that is in the list of available countries.');
157 }
158
159 return empty($errors) ? TRUE : $errors;
160 }
161
162 /**
163 * Set the default values for the form.
164 *
165 * @return array
166 */
167 public function setDefaultValues() {
168 parent::setDefaultValues();
169
170 // CRM-1496
171 // retrieve default values for currencyLimit
172 $this->_defaults['currencyLimit'] = array_keys(CRM_Core_OptionGroup::values('currencies_enabled'));
173
174 $this->_defaults['languageLimit'] = Civi::settings()->get('languageLimit');
175
176 // CRM-5111: unset these two unconditionally, we don’t want them to stick – ever
177 unset($this->_defaults['makeMultilingual']);
178 unset($this->_defaults['makeSinglelingual']);
179 return $this->_defaults;
180 }
181
182 public function postProcess() {
183 $values = $this->exportValues();
184
185 //cache contact fields retaining localized titles
186 //though we changed localization, so reseting cache.
187 Civi::cache('fields')->flush();
188
189 //CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
190 Civi::cache('navigation')->flush();
191 // reset ACL and System caches
192 CRM_Core_BAO_Cache::resetCaches();
193
194 // we do this only to initialize monetary decimal point and thousand separator
195 $config = CRM_Core_Config::singleton();
196
197 // save enabled currencies and default currency in option group 'currencies_enabled'
198 // CRM-1496
199 if (empty($values['currencyLimit'])) {
200 $values['currencyLimit'] = [$values['defaultCurrency']];
201 }
202 elseif (!in_array($values['defaultCurrency'], $values['currencyLimit'])) {
203 $values['currencyLimit'][] = $values['defaultCurrency'];
204 }
205
206 self::updateEnabledCurrencies($values['currencyLimit'], $values['defaultCurrency']);
207
208 // unset currencyLimit so we dont store there
209 unset($values['currencyLimit']);
210
211 // make the site multi-lang if requested
212 if (!empty($values['makeMultilingual'])) {
213 CRM_Core_I18n_Schema::makeMultilingual($values['lcMessages']);
214 $values['languageLimit'][$values['lcMessages']] = 1;
215 // make the site single-lang if requested
216 }
217 elseif (!empty($values['makeSinglelingual'])) {
218 CRM_Core_I18n_Schema::makeSinglelingual($values['lcMessages']);
219 $values['languageLimit'] = '';
220 }
221
222 // add a new db locale if the requested language is not yet supported by the db
223 if (!CRM_Utils_Array::value('makeSinglelingual', $values) and CRM_Utils_Array::value('addLanguage', $values)) {
224 $domain = new CRM_Core_DAO_Domain();
225 $domain->find(TRUE);
226 if (!substr_count($domain->locales, $values['addLanguage'])) {
227 CRM_Core_I18n_Schema::addLocale($values['addLanguage'], $values['lcMessages']);
228 }
229 $values['languageLimit'][$values['addLanguage']] = 1;
230 }
231
232 // current language should be in the ui list
233 if (!in_array($values['lcMessages'], $values['uiLanguages'])) {
234 $values['uiLanguages'][] = $values['lcMessages'];
235 }
236
237 // if we manipulated the language list, return to the localization admin screen
238 $return = (bool) (CRM_Utils_Array::value('makeMultilingual', $values) or CRM_Utils_Array::value('addLanguage', $values));
239
240 $filteredValues = $values;
241 unset($filteredValues['makeMultilingual']);
242 unset($filteredValues['makeSinglelingual']);
243 unset($filteredValues['addLanguage']);
244 unset($filteredValues['languageLimit']);
245
246 Civi::settings()->set('languageLimit', CRM_Utils_Array::value('languageLimit', $values));
247
248 // save all the settings
249 parent::commonProcess($filteredValues);
250
251 if ($return) {
252 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/setting/localization', 'reset=1'));
253 }
254 }
255
256 /**
257 * Replace available currencies by the ones provided
258 *
259 * @param $currencies array of currencies ['USD', 'CAD']
260 * @param $default default currency
261 */
262 public static function updateEnabledCurrencies($currencies, $default) {
263
264 // sort so that when we display drop down, weights have right value
265 sort($currencies);
266
267 // get labels for all the currencies
268 $options = [];
269
270 $currencySymbols = CRM_Admin_Form_Setting_Localization::getCurrencySymbols();
271 for ($i = 0; $i < count($currencies); $i++) {
272 $options[] = [
273 'label' => $currencySymbols[$currencies[$i]],
274 'value' => $currencies[$i],
275 'weight' => $i + 1,
276 'is_active' => 1,
277 'is_default' => $currencies[$i] == $default,
278 ];
279 }
280
281 $dontCare = NULL;
282 CRM_Core_OptionGroup::createAssoc('currencies_enabled', $options, $dontCare);
283
284 }
285
286 /**
287 * @return array
288 */
289 public static function getAvailableCountries() {
290 $i18n = CRM_Core_I18n::singleton();
291 $country = [];
292 CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
293 $i18n->localizeArray($country, ['context' => 'country']);
294 asort($country);
295 return $country;
296 }
297
298 /**
299 * Get the default locale options.
300 *
301 * @return array
302 */
303 public static function getDefaultLocaleOptions() {
304 $domain = new CRM_Core_DAO_Domain();
305 $domain->find(TRUE);
306 $locales = CRM_Core_I18n::languages();
307 if ($domain->locales) {
308 // for multi-lingual sites, populate default language drop-down with available languages
309 $defaultLocaleOptions = [];
310 foreach ($locales as $loc => $lang) {
311 if (substr_count($domain->locales, $loc)) {
312 $defaultLocaleOptions[$loc] = $lang;
313 }
314 }
315 }
316 else {
317 $defaultLocaleOptions = $locales;
318 }
319 return $defaultLocaleOptions;
320 }
321
322 /**
323 * Get a list of currencies (with their symbols).
324 *
325 * @return array
326 * Array('USD' => 'USD ($)').
327 */
328 public static function getCurrencySymbols() {
329 $symbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
330 'labelColumn' => 'symbol',
331 'orderColumn' => TRUE,
332 ]);
333 $_currencySymbols = [];
334 foreach ($symbols as $key => $value) {
335 $_currencySymbols[$key] = "$key";
336 if ($value) {
337 $_currencySymbols[$key] .= " ($value)";
338 }
339 }
340 return $_currencySymbols;
341 }
342
343 /**
344 * Update session and uf_match table when the locale is updated.
345 *
346 * @param string $oldLocale
347 * @param string $newLocale
348 * @param array $metadata
349 * @param int $domainID
350 */
351 public static function onChangeLcMessages($oldLocale, $newLocale, $metadata, $domainID) {
352 if ($oldLocale == $newLocale) {
353 return;
354 }
355
356 $session = CRM_Core_Session::singleton();
357 if ($newLocale && $session->get('userID')) {
358 $ufm = new CRM_Core_DAO_UFMatch();
359 $ufm->contact_id = $session->get('userID');
360 if ($newLocale && $ufm->find(TRUE)) {
361 $ufm->language = $newLocale;
362 $ufm->save();
363 $session->set('lcMessages', $newLocale);
364 }
365 }
366 }
367
368 public static function onChangeDefaultCurrency($oldCurrency, $newCurrency, $metadata) {
369 if ($oldCurrency == $newCurrency) {
370 return;
371 }
372
373 // ensure that default currency is always in the list of enabled currencies
374 $currencies = array_keys(CRM_Core_OptionGroup::values('currencies_enabled'));
375 if (!in_array($newCurrency, $currencies)) {
376 if (empty($currencies)) {
377 $currencies = [$values['defaultCurrency']];
378 }
379 else {
380 $currencies[] = $newCurrency;
381 }
382
383 CRM_Admin_Form_Setting_Localization::updateEnabledCurrencies($currencies, $newCurrency);
384 }
385
386 }
387
388 /**
389 * @return array
390 */
391 public static function getDefaultLanguageOptions() {
392 return [
393 '*default*' => ts('Use default site language'),
394 'undefined' => ts('Leave undefined'),
395 'current_site_language' => ts('Use language in use at the time'),
396 ];
397 }
398
399 }