Ian province abbreviation patch - issue 724
[civicrm-core.git] / CRM / Core / BAO / Setting.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33
34/**
35 * BAO object for civicrm_setting table. This table is used to store civicrm settings that are not used
36 * very frequently (i.e. not on every page load)
37 *
38 * The group column is used for grouping together all settings that logically belong to the same set.
39 * Thus all settings in the same group are retrieved with one DB call and then cached for future needs.
40 */
41class CRM_Core_BAO_Setting extends CRM_Core_DAO_Setting {
42
43 /**
44 * Various predefined settings that have been migrated to the setting table.
45 */
46 const
47 ADDRESS_STANDARDIZATION_PREFERENCES_NAME = 'Address Standardization Preferences',
48 CAMPAIGN_PREFERENCES_NAME = 'Campaign Preferences',
49 DEVELOPER_PREFERENCES_NAME = 'Developer Preferences',
50 DIRECTORY_PREFERENCES_NAME = 'Directory Preferences',
51 EVENT_PREFERENCES_NAME = 'Event Preferences',
52 MAILING_PREFERENCES_NAME = 'Mailing Preferences',
53 CONTRIBUTE_PREFERENCES_NAME = 'Contribute Preferences',
54 MEMBER_PREFERENCES_NAME = 'Member Preferences',
55 MULTISITE_PREFERENCES_NAME = 'Multi Site Preferences',
56 PERSONAL_PREFERENCES_NAME = 'Personal Preferences',
57 SYSTEM_PREFERENCES_NAME = 'CiviCRM Preferences',
58 URL_PREFERENCES_NAME = 'URL Preferences',
59 LOCALIZATION_PREFERENCES_NAME = 'Localization Preferences',
60 SEARCH_PREFERENCES_NAME = 'Search Preferences';
61 static $_cache = NULL;
62
63 /**
64 * Checks whether an item is present in the in-memory cache table
65 *
66 * @param string $group
67 * (required) The group name of the item.
68 * @param string $name
69 * (required) The name of the setting.
70 * @param int $componentID
71 * The optional component ID (so components can share the same name space).
72 * @param int $contactID
73 * If set, this is a contactID specific setting, else its a global setting.
74 * @param bool|int $load if true, load from local cache (typically memcache)
75 *
76 * @param int $domainID
77 * @param bool $force
78 *
79 * @return bool
80 * true if item is already in cache
81 */
82 public static function inCache(
83 $group,
84 $name,
85 $componentID = NULL,
86 $contactID = NULL,
87 $load = FALSE,
88 $domainID = NULL,
89 $force = FALSE
90 ) {
91 if (!isset(self::$_cache)) {
92 self::$_cache = array();
93 }
94
95 $cacheKey = "CRM_Setting_{$group}_{$componentID}_{$contactID}_{$domainID}";
96
97 if (
98 $load &&
99 ($force || !isset(self::$_cache[$cacheKey]))
100 ) {
101
102 // check in civi cache if present (typically memcache)
103 $globalCache = CRM_Utils_Cache::singleton();
104 $result = $globalCache->get($cacheKey);
105 if ($result) {
106
107 self::$_cache[$cacheKey] = $result;
108 }
109 }
110
111 return isset(self::$_cache[$cacheKey]) ? $cacheKey : NULL;
112 }
113
114 /**
115 * Allow key o be cleared.
116 * @param string $cacheKey
117 */
118 public static function flushCache($cacheKey) {
119 unset(self::$_cache[$cacheKey]);
120 $globalCache = CRM_Utils_Cache::singleton();
121 $globalCache->delete($cacheKey);
122 }
123
124 /**
125 * @param $values
126 * @param $group
127 * @param int $componentID
128 * @param int $contactID
129 * @param int $domainID
130 *
131 * @return string
132 */
133 public static function setCache(
134 $values,
135 $group,
136 $componentID = NULL,
137 $contactID = NULL,
138 $domainID = NULL
139 ) {
140 if (!isset(self::$_cache)) {
141 self::$_cache = array();
142 }
143
144 $cacheKey = "CRM_Setting_{$group}_{$componentID}_{$contactID}_{$domainID}";
145
146 self::$_cache[$cacheKey] = $values;
147
148 $globalCache = CRM_Utils_Cache::singleton();
149 $result = $globalCache->set($cacheKey, $values);
150
151 return $cacheKey;
152 }
153
154 /**
155 * @param $group
156 * @param null $name
157 * @param int $componentID
158 * @param int $contactID
159 * @param int $domainID
160 *
161 * @return CRM_Core_DAO_Domain|CRM_Core_DAO_Setting
162 */
163 public static function dao(
164 $group,
165 $name = NULL,
166 $componentID = NULL,
167 $contactID = NULL,
168 $domainID = NULL
169 ) {
170 if (self::isUpgradeFromPreFourOneAlpha1()) {
171 // civicrm_setting table is not going to be present. For now we'll just
172 // return a dummy object
173 $dao = new CRM_Core_DAO_Domain();
174 $dao->id = -1; // so ->find() doesn't fetch any data later on
175 return $dao;
176 }
177 $dao = new CRM_Core_DAO_Setting();
178
179 $dao->group_name = $group;
180 $dao->name = $name;
181 $dao->component_id = $componentID;
182 if (empty($domainID)) {
183 $dao->domain_id = CRM_Core_Config::domainID();
184 }
185 else {
186 $dao->domain_id = $domainID;
187 }
188
189 if ($contactID) {
190 $dao->contact_id = $contactID;
191 $dao->is_domain = 0;
192 }
193 else {
194 $dao->is_domain = 1;
195 }
196
197 return $dao;
198 }
199
200 /**
201 * Retrieve the value of a setting from the DB table.
202 *
203 * @param string $group
204 * (required) The group name of the item.
205 * @param string $name
206 * (required) The name under which this item is stored.
207 * @param int $componentID
208 * The optional component ID (so componenets can share the same name space).
209 * @param string $defaultValue
210 * The default value to return for this setting if not present in DB.
211 * @param int $contactID
212 * If set, this is a contactID specific setting, else its a global setting.
213 *
214 * @param int $domainID
215 *
216 * @return mixed
217 * The data if present in the setting table, else null
218 */
219 public static function getItem(
220 $group,
221 $name = NULL,
222 $componentID = NULL,
223 $defaultValue = NULL,
224 $contactID = NULL,
225 $domainID = NULL
226 ) {
227
228 $overrideGroup = array();
229 if (NULL !== ($override = self::getOverride($group, $name, NULL))) {
230 if (isset($name)) {
231 return $override;
232 }
233 else {
234 $overrideGroup = $override;
235 }
236 }
237
238 if (empty($domainID)) {
239 $domainID = CRM_Core_Config::domainID();
240 }
241 $cacheKey = self::inCache($group, $name, $componentID, $contactID, TRUE, $domainID);
242
243 if ($group && !isset($name) && $cacheKey) {
244 // check value against the cache, and unset key if values are different
245 $valueDifference = CRM_Utils_Array::multiArrayDiff($overrideGroup, self::$_cache[$cacheKey]);
246 if (!empty($valueDifference)) {
247 $cacheKey = '';
248 }
249 }
250
251 if (!$cacheKey) {
252 $dao = self::dao($group, NULL, $componentID, $contactID, $domainID);
253 $dao->find();
254
255 $values = array();
256 while ($dao->fetch()) {
257 if (NULL !== ($override = self::getOverride($group, $dao->name, NULL))) {
258 $values[$dao->name] = $override;
259 }
260 elseif ($dao->value) {
261 $values[$dao->name] = unserialize($dao->value);
262 }
263 else {
264 $values[$dao->name] = NULL;
265 }
266 }
267 $dao->free();
268
269 if (!isset($name)) {
270 // merge db and override group values
271 // When no $name is present, the getItem() function should return an array
272 // consisting of the sum of all override settings + all settings present in
273 // the database for the given $group (with the overrides taking precedence,
274 // and applying even if the setting is not defined in the database).
275 //
276 $values = array_merge($values, $overrideGroup);
277 }
278
279 $cacheKey = self::setCache($values, $group, $componentID, $contactID, $domainID);
280 }
281 return $name ? CRM_Utils_Array::value($name, self::$_cache[$cacheKey], $defaultValue) : self::$_cache[$cacheKey];
282 }
283
284 /**
285 * Store multiple items in the setting table.
286 *
287 * @param array $params
288 * (required) An api formatted array of keys and values.
289 * @param array $domains Array of domains to get settings for. Default is the current domain
290 * @param $settingsToReturn
291 *
292 * @return array
293 */
294 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
295 $originalDomain = CRM_Core_Config::domainID();
296 if (empty($domains)) {
297 $domains[] = $originalDomain;
298 }
299 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
300 $settingsToReturn = array($settingsToReturn);
301 }
302 $reloadConfig = FALSE;
303
304 $fields = $result = array();
305 $fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
306 foreach ($domains as $domainID) {
307 if ($domainID != CRM_Core_Config::domainID()) {
308 $reloadConfig = TRUE;
309 CRM_Core_BAO_Domain::setDomain($domainID);
310 }
311 $config = CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
312 $result[$domainID] = array();
313 foreach ($fieldsToGet as $name => $value) {
314 if (!empty($fields['values'][$name]['prefetch'])) {
315 if (isset($params['filters']) && isset($params['filters']['prefetch'])
316 && $params['filters']['prefetch'] == 0
317 ) {
318 // we are filtering out the prefetches from the return array
319 // so we will skip
320 continue;
321 }
322 $configKey = CRM_Utils_Array::value('config_key', $fields['values'][$name], $name);
323 if (isset($config->$configKey)) {
324 $setting = $config->$configKey;
325 }
326 }
327 else {
328 $setting = CRM_Core_BAO_Setting::getItem(
329 $fields['values'][$name]['group_name'],
330 $name,
331 CRM_Utils_Array::value('component_id', $params),
332 NULL,
333 CRM_Utils_Array::value('contact_id', $params),
334 $domainID
335 );
336 }
337 if (!is_null($setting)) {
338 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
339 // e.g for revert of fill actions
340 $result[$domainID][$name] = $setting;
341 }
342 }
343 CRM_Core_BAO_Domain::resetDomain();
344 }
345 return $result;
346 }
347
348 /**
349 * Store an item in the setting table.
350 *
351 * _setItem() is the common logic shared by setItem() and setItems().
352 *
353 * @param object $value
354 * (required) The value that will be serialized and stored.
355 * @param string $group
356 * (required) The group name of the item.
357 * @param string $name
358 * (required) The name of the setting.
359 * @param int $componentID
360 * The optional component ID (so componenets can share the same name space).
361 * @param int $contactID
362 * @param int $createdID
363 * An optional ID to assign the creator to. If not set, retrieved from session.
364 *
365 * @param int $domainID
366 */
367 public static function setItem(
368 $value,
369 $group,
370 $name,
371 $componentID = NULL,
372 $contactID = NULL,
373 $createdID = NULL,
374 $domainID = NULL
375 ) {
376 $fields = array();
377 $fieldsToSet = self::validateSettingsInput(array($name => $value), $fields);
378 //We haven't traditionally validated inputs to setItem, so this breaks things.
379 //foreach ($fieldsToSet as $settingField => &$settingValue) {
380 // self::validateSetting($settingValue, $fields['values'][$settingField]);
381 //}
382
383 return self::_setItem($fields['values'][$name], $value, $group, $name, $componentID, $contactID, $createdID, $domainID);
384 }
385
386 /**
387 * Store an item in a setting table.
388 *
389 * _setItem() is the common logic shared by setItem() and setItems().
390 *
391 * @param array $metadata
392 * Metadata describing this field.
393 * @param $value
394 * @param $group
395 * @param string $name
396 * @param int $componentID
397 * @param int $contactID
398 * @param int $createdID
399 * @param int $domainID
400 */
401 public static function _setItem(
402 $metadata,
403 $value,
404 $group,
405 $name,
406 $componentID = NULL,
407 $contactID = NULL,
408 $createdID = NULL,
409 $domainID = NULL
410 ) {
411 if (empty($domainID)) {
412 $domainID = CRM_Core_Config::domainID();
413 }
414
415 $dao = self::dao($group, $name, $componentID, $contactID, $domainID);
416 $dao->find(TRUE);
417
418 if (isset($metadata['on_change'])) {
419 foreach ($metadata['on_change'] as $callback) {
420 call_user_func(
421 Civi\Core\Resolver::singleton()->get($callback),
422 unserialize($dao->value),
423 $value,
424 $metadata
425 );
426 }
427 }
428
429 if (CRM_Utils_System::isNull($value)) {
430 $dao->value = 'null';
431 }
432 else {
433 $dao->value = serialize($value);
434 }
435
436 $dao->created_date = date('Ymdhis');
437
438 if ($createdID) {
439 $dao->created_id = $createdID;
440 }
441 else {
442 $session = CRM_Core_Session::singleton();
443 $createdID = $session->get('userID');
444
445 if ($createdID) {
446 // ensure that this is a valid contact id (for session inconsistency rules)
447 $cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
448 $createdID,
449 'id',
450 'id'
451 );
452 if ($cid) {
453 $dao->created_id = $session->get('userID');
454 }
455 }
456 }
457
458 $dao->save();
459 $dao->free();
460
461 // also save in cache if needed
462 $cacheKey = self::inCache($group, $name, $componentID, $contactID, FALSE, $domainID);
463 if ($cacheKey) {
464 self::$_cache[$cacheKey][$name] = $value;
465 }
466 }
467
468 /**
469 * Store multiple items in the setting table. Note that this will also store config keys
470 * the storage is determined by the metdata and is affected by
471 * 'name' setting's name
472 * 'prefetch' = store in config
473 * 'config_only' = don't store in settings
474 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
475 * 'legacy_key' = rename from config or setting with this name
476 *
477 * _setItem() is the common logic shared by setItem() and setItems().
478 *
479 * @param array $params
480 * (required) An api formatted array of keys and values.
481 * @param null $domains
482 *
483 * @throws api_Exception
484 * @domains array an array of domains to get settings for. Default is the current domain
485 * @return array
486 */
487 public static function setItems(&$params, $domains = NULL) {
488 $originalDomain = CRM_Core_Config::domainID();
489 if (empty($domains)) {
490 $domains[] = $originalDomain;
491 }
492 $reloadConfig = FALSE;
493 $fields = $config_keys = array();
494 $fieldsToSet = self::validateSettingsInput($params, $fields);
495
496 foreach ($fieldsToSet as $settingField => &$settingValue) {
497 self::validateSetting($settingValue, $fields['values'][$settingField]);
498 }
499
500 foreach ($domains as $domainID) {
501 if ($domainID != CRM_Core_Config::domainID()) {
502 $reloadConfig = TRUE;
503 CRM_Core_BAO_Domain::setDomain($domainID);
504 }
505 $result[$domainID] = array();
506 foreach ($fieldsToSet as $name => $value) {
507 if (empty($fields['values'][$name]['config_only'])) {
508 CRM_Core_BAO_Setting::_setItem(
509 $fields['values'][$name],
510 $value,
511 $fields['values'][$name]['group_name'],
512 $name,
513 CRM_Utils_Array::value('component_id', $params),
514 CRM_Utils_Array::value('contact_id', $params),
515 CRM_Utils_Array::value('created_id', $params),
516 $domainID
517 );
518 }
519 if (!empty($fields['values'][$name]['prefetch'])) {
520 if (!empty($fields['values'][$name]['config_key'])) {
521 $name = $fields['values'][$name]['config_key'];
522 }
523 $config_keys[$name] = $value;
524 }
525 $result[$domainID][$name] = $value;
526 }
527 if ($reloadConfig) {
528 CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
529 }
530
531 if (!empty($config_keys)) {
532 CRM_Core_BAO_ConfigSetting::create($config_keys);
533 }
534 if ($reloadConfig) {
535 CRM_Core_BAO_Domain::resetDomain();
536 }
537 }
538
539 return $result;
540 }
541
542 /**
543 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
544 *
545 * This function filters on the fields like 'version' & 'debug' that are not settings
546 *
547 * @param array $params
548 * Parameters as passed into API.
549 * @param array $fields
550 * Empty array to be populated with fields metadata.
551 * @param bool $createMode
552 *
553 * @throws api_Exception
554 * @return array
555 * name => value array of the fields to be set (with extraneous removed)
556 */
557 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
558 $group = CRM_Utils_Array::value('group', $params);
559
560 $ignoredParams = array(
561 'version',
562 'id',
563 'domain_id',
564 'debug',
565 'created_id',
566 'component_id',
567 'contact_id',
568 'filters',
569 'entity_id',
570 'entity_table',
571 'sequential',
572 'api.has_parent',
573 'IDS_request_uri',
574 'IDS_user_agent',
575 'check_permissions',
576 'options',
577 'prettyprint',
578 );
579 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
580 $getFieldsParams = array('version' => 3);
581 if (count($settingParams) == 1) {
582 // ie we are only setting one field - we'll pass it into getfields for efficiency
583 list($name) = array_keys($settingParams);
584 $getFieldsParams['name'] = $name;
585 }
586 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
587 $invalidParams = (array_diff_key($settingParams, $fields['values']));
588 if (!empty($invalidParams)) {
589 throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
590 }
591 if (!empty($settingParams)) {
592 $filteredFields = array_intersect_key($settingParams, $fields['values']);
593 }
594 else {
595 // no filters so we are interested in all for get mode. In create mode this means nothing to set
596 $filteredFields = $createMode ? array() : $fields['values'];
597 }
598 return $filteredFields;
599 }
600
601 /**
602 * Validate & convert settings input
603 *
604 * @value mixed value of the setting to be set
605 * @fieldSpec array Metadata for given field (drawn from the xml)
606 */
607 public static function validateSetting(&$value, $fieldSpec) {
608 if ($fieldSpec['type'] == 'String' && is_array($value)) {
609 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
610 }
611 if (empty($fieldSpec['validate_callback'])) {
612 return TRUE;
613 }
614 else {
615 $cb = Civi\Core\Resolver::singleton()->get($fieldSpec['validate_callback']);
616 if (!call_user_func_array($cb, array(&$value, $fieldSpec))) {
617 throw new api_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
618 }
619 }
620 }
621
622 /**
623 * Validate & convert settings input - translate True False to 0 or 1
624 *
625 * @value mixed value of the setting to be set
626 * @fieldSpec array Metadata for given field (drawn from the xml)
627 */
628 public static function validateBoolSetting(&$value, $fieldSpec) {
629 if (!CRM_Utils_Rule::boolean($value)) {
630 throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
631 }
632 if (!$value) {
633 $value = 0;
634 }
635 else {
636 $value = 1;
637 }
638 return TRUE;
639 }
640
641 /**
642 * This provides information about the setting - similar to the fields concept for DAO information.
643 * As the setting is serialized code creating validation setting input needs to know the data type
644 * This also helps move information out of the form layer into the data layer where people can interact with
645 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
646 * also leverages it.
647 *
648 * Note that this function should never be called when using the runtime getvalue function. Caching works
649 * around the expectation it will be called during setting administration
650 *
651 * Function is intended for configuration rather than runtime access to settings
652 *
653 * The following params will filter the result. If none are passed all settings will be returns
654 *
655 * @param int $componentID
656 * Id of relevant component.
657 * @param array $filters
658 * @param int $domainID
659 * @param null $profile
660 *
661 * @return array
662 * the following information as appropriate for each setting
663 * - name
664 * - type
665 * - default
666 * - add (CiviCRM version added)
667 * - is_domain
668 * - is_contact
669 * - description
670 * - help_text
671 */
672 public static function getSettingSpecification(
673 $componentID = NULL,
674 $filters = array(),
675 $domainID = NULL,
676 $profile = NULL
677 ) {
678 $cacheString = 'settingsMetadata_' . $domainID . '_' . $profile;
679 foreach ($filters as $filterField => $filterString) {
680 $cacheString .= "_{$filterField}_{$filterString}";
681 }
682 $cached = 1;
683 // the caching into 'All' seems to be a duplicate of caching to
684 // settingsMetadata__ - I think the reason was to cache all settings as defined & then those altered by a hook
685 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Specs', $cacheString, $componentID);
686 if ($settingsMetadata === NULL) {
687 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Spec', 'All', $componentID);
688 if (empty($settingsMetadata)) {
689 global $civicrm_root;
690 $metaDataFolders = array($civicrm_root . '/settings');
691 CRM_Utils_Hook::alterSettingsFolders($metaDataFolders);
692 $settingsMetadata = self::loadSettingsMetaDataFolders($metaDataFolders);
693 CRM_Core_BAO_Cache::setItem($settingsMetadata, 'CiviCRM setting Spec', 'All', $componentID);
694 }
695 $cached = 0;
696 }
697
698 CRM_Utils_Hook::alterSettingsMetaData($settingsMetadata, $domainID, $profile);
699 self::_filterSettingsSpecification($filters, $settingsMetadata);
700
701 if (!$cached) {
702 // this is a bit 'heavy' if you are using hooks but this function
703 // is expected to only be called during setting administration
704 // it should not be called by 'getvalue' or 'getitem
705 CRM_Core_BAO_Cache::setItem(
706 $settingsMetadata,
707 'CiviCRM setting Specs',
708 $cacheString,
709 $componentID
710 );
711 }
712 return $settingsMetadata;
713
714 }
715
716 /**
717 * Load the settings files defined in a series of folders.
718 * @param array $metaDataFolders
719 * List of folder paths.
720 * @return array
721 */
722 public static function loadSettingsMetaDataFolders($metaDataFolders) {
723 $settingsMetadata = array();
724 $loadedFolders = array();
725 foreach ($metaDataFolders as $metaDataFolder) {
726 $realFolder = realpath($metaDataFolder);
727 if (is_dir($realFolder) && !isset($loadedFolders[$realFolder])) {
728 $loadedFolders[$realFolder] = TRUE;
729 $settingsMetadata = $settingsMetadata + self::loadSettingsMetaData($metaDataFolder);
730 }
731 }
732 return $settingsMetadata;
733 }
734
735 /**
736 * Load up settings metadata from files.
737 */
738 public static function loadSettingsMetadata($metaDataFolder) {
739 $settingMetaData = array();
740 $settingsFiles = CRM_Utils_File::findFiles($metaDataFolder, '*.setting.php');
741 foreach ($settingsFiles as $file) {
742 $settings = include $file;
743 $settingMetaData = array_merge($settingMetaData, $settings);
744 }
745 CRM_Core_BAO_Cache::setItem($settingMetaData, 'CiviCRM setting Spec', 'All');
746 return $settingMetaData;
747 }
748
749 /**
750 * Filter the settings metadata according to filters passed in. This is a convenience filter
751 * and allows selective reverting / filling of settings
752 *
753 * @param array $filters
754 * Filters to match against data.
755 * @param array $settingSpec
756 * Metadata to filter.
757 */
758 public static function _filterSettingsSpecification($filters, &$settingSpec) {
759 if (empty($filters)) {
760 return;
761 }
762 elseif (array_keys($filters) == array('name')) {
763 $settingSpec = array($filters['name'] => CRM_Utils_Array::value($filters['name'], $settingSpec, ''));
764 return;
765 }
766 else {
767 foreach ($settingSpec as $field => $fieldValues) {
768 if (array_intersect_assoc($fieldValues, $filters) != $filters) {
769 unset($settingSpec[$field]);
770 }
771 }
772 return;
773 }
774 }
775
776 /**
777 * Look for any missing settings and convert them from config or load default as appropriate.
778 * This should be run from GenCode & also from upgrades to add any new defaults.
779 *
780 * Multisites have often been overlooked in upgrade scripts so can be expected to be missing
781 * a number of settings
782 */
783 public static function updateSettingsFromMetaData() {
784 $apiParams = array(
785 'version' => 3,
786 'domain_id' => 'all',
787 'filters' => array('prefetch' => 0),
788 );
789 $existing = civicrm_api('setting', 'get', $apiParams);
790
791 if (!empty($existing['values'])) {
792 $allSettings = civicrm_api('setting', 'getfields', array('version' => 3));
793 foreach ($existing['values'] as $domainID => $domainSettings) {
794 CRM_Core_BAO_Domain::setDomain($domainID);
795 $missing = array_diff_key($allSettings['values'], $domainSettings);
796 foreach ($missing as $name => $settings) {
797 self::convertConfigToSetting($name, $domainID);
798 }
799 CRM_Core_BAO_Domain::resetDomain();
800 }
801 }
802 }
803
804 /**
805 * Move an item from being in the config array to being stored as a setting
806 * remove from config - as appropriate based on metadata
807 *
808 * Note that where the key name is being changed the 'legacy_key' will give us the old name
809 */
810 public static function convertConfigToSetting($name, $domainID = NULL) {
811 // we have to force this here in case more than one domain is in play.
812 // whenever there is a possibility of more than one domain we must force it
813 $config = CRM_Core_Config::singleton();
814 if (empty($domainID)) {
815 $domainID = CRM_Core_Config::domainID();
816 }
817 $domain = new CRM_Core_DAO_Domain();
818 $domain->id = $domainID;
819 $domain->find(TRUE);
820 if ($domain->config_backend) {
821 $values = unserialize($domain->config_backend);
822 }
823 else {
824 $values = array();
825 }
826 $spec = self::getSettingSpecification(NULL, array('name' => $name), $domainID);
827 $configKey = CRM_Utils_Array::value('config_key', $spec[$name], CRM_Utils_Array::value('legacy_key', $spec[$name], $name));
828 //if the key is set to config_only we don't need to do anything
829 if (empty($spec[$name]['config_only'])) {
830 if (!empty($values[$configKey])) {
831 civicrm_api('setting', 'create', array('version' => 3, $name => $values[$configKey], 'domain_id' => $domainID));
832 }
833 else {
834 civicrm_api('setting', 'fill', array('version' => 3, 'name' => $name, 'domain_id' => $domainID));
835 }
836
837 if (empty($spec[$name]['prefetch']) && !empty($values[$configKey])) {
838 unset($values[$configKey]);
839 $domain->config_backend = serialize($values);
840 $domain->save();
841 unset($config->$configKey);
842 }
843 }
844 }
845
846 /**
847 * @param $group
848 * @param string $name
849 * @param bool $system
850 * @param int $userID
851 * @param bool $localize
852 * @param string $returnField
853 * @param bool $returnNameANDLabels
854 * @param null $condition
855 *
856 * @return array
857 */
858 public static function valueOptions(
859 $group,
860 $name,
861 $system = TRUE,
862 $userID = NULL,
863 $localize = FALSE,
864 $returnField = 'name',
865 $returnNameANDLabels = FALSE,
866 $condition = NULL
867 ) {
868 $optionValue = self::getItem($group, $name);
869
870 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
871
872 //enabled name => label require for new contact edit form, CRM-4605
873 if ($returnNameANDLabels) {
874 $names = $labels = $nameAndLabels = array();
875 if ($returnField == 'name') {
876 $names = $groupValues;
877 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
878 }
879 else {
880 $labels = $groupValues;
881 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
882 }
883 }
884
885 $returnValues = array();
886 foreach ($groupValues as $gn => $gv) {
887 $returnValues[$gv] = 0;
888 }
889
890 if ($optionValue && !empty($groupValues)) {
891 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
892 substr($optionValue, 1, -1)
893 );
894
895 if (!empty($dbValues)) {
896 foreach ($groupValues as $key => $val) {
897 if (in_array($key, $dbValues)) {
898 $returnValues[$val] = 1;
899 if ($returnNameANDLabels) {
900 $nameAndLabels[$names[$key]] = $labels[$key];
901 }
902 }
903 }
904 }
905 }
906 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
907 }
908
909 /**
910 * @param $group
911 * @param string $name
912 * @param $value
913 * @param bool $system
914 * @param int $userID
915 * @param string $keyField
916 */
917 public static function setValueOption(
918 $group,
919 $name,
920 $value,
921 $system = TRUE,
922 $userID = NULL,
923 $keyField = 'name'
924 ) {
925 if (empty($value)) {
926 $optionValue = NULL;
927 }
928 elseif (is_array($value)) {
929 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
930
931 $cbValues = array();
932 foreach ($groupValues as $key => $val) {
933 if (!empty($value[$val])) {
934 $cbValues[$key] = 1;
935 }
936 }
937
938 if (!empty($cbValues)) {
939 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
940 array_keys($cbValues)
941 ) . CRM_Core_DAO::VALUE_SEPARATOR;
942 }
943 else {
944 $optionValue = NULL;
945 }
946 }
947 else {
948 $optionValue = $value;
949 }
950
951 self::setItem($optionValue, $group, $name);
952 }
953
954 /**
955 * @param array $params
956 * @param int $domainID
957 */
958 public static function fixAndStoreDirAndURL(&$params, $domainID = NULL) {
959 if (self::isUpgradeFromPreFourOneAlpha1()) {
960 return;
961 }
962
963 if (empty($domainID)) {
964 $domainID = CRM_Core_Config::domainID();
965 }
966 $sql = "
967 SELECT name, group_name
968 FROM civicrm_setting
969 WHERE domain_id = %1
970 AND ( group_name = %2
971 OR group_name = %3 )
972";
973 $sqlParams = array(
974 1 => array($domainID, 'Integer'),
975 2 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
976 3 => array(self::URL_PREFERENCES_NAME, 'String'),
977 );
978
979 $dirParams = array();
980 $urlParams = array();
981
982 $dao = CRM_Core_DAO::executeQuery($sql,
983 $sqlParams,
984 TRUE,
985 NULL,
986 FALSE,
987 TRUE,
988 // trap exceptions as error
989 TRUE
990 );
991
992 if (is_a($dao, 'DB_Error')) {
993 if (CRM_Core_Config::isUpgradeMode()) {
994 // seems like this is a 4.0 -> 4.1 upgrade, so we suppress this error and continue
995 return;
996 }
997 else {
998 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
999 exit();
1000 }
1001 }
1002
1003 while ($dao->fetch()) {
1004 if (!isset($params[$dao->name])) {
1005 continue;
1006 }
1007 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
1008 $dirParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
1009 }
1010 else {
1011 $urlParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
1012 }
1013 unset($params[$dao->name]);
1014 }
1015
1016 if (!empty($dirParams)) {
1017 self::storeDirectoryOrURLPreferences($dirParams,
1018 self::DIRECTORY_PREFERENCES_NAME
1019 );
1020 }
1021
1022 if (!empty($urlParams)) {
1023 self::storeDirectoryOrURLPreferences($urlParams,
1024 self::URL_PREFERENCES_NAME
1025 );
1026 }
1027 }
1028
1029 /**
1030 * @param array $params
1031 * @param $group
1032 */
1033 public static function storeDirectoryOrURLPreferences(&$params, $group) {
1034 foreach ($params as $name => $value) {
1035 // always try to store relative directory or url from CMS root
1036 $value = ($group == self::DIRECTORY_PREFERENCES_NAME) ? CRM_Utils_File::relativeDirectory($value) : CRM_Utils_System::relativeURL($value);
1037
1038 self::setItem($value, $group, $name);
1039 }
1040 }
1041
1042 /**
1043 * @param array $params
1044 * @param bool $setInConfig
1045 */
1046 public static function retrieveDirectoryAndURLPreferences(&$params, $setInConfig = FALSE) {
1047 if (CRM_Core_Config::isUpgradeMode()) {
1048 $isJoomla = (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') ? TRUE : FALSE;
1049 // hack to set the resource base url so that js/ css etc is loaded correctly
1050 if ($isJoomla) {
1051 $params['userFrameworkResourceURL'] = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/') . str_replace('administrator', '', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'userFrameworkResourceURL', 'value', 'name'));
1052 }
1053 if (self::isUpgradeFromPreFourOneAlpha1()) {
1054 return;
1055 }
1056 }
1057
1058 if ($setInConfig) {
1059 $config = CRM_Core_Config::singleton();
1060 }
1061
1062 $sql = "
1063SELECT name, group_name, value
1064FROM civicrm_setting
1065WHERE ( group_name = %1
1066OR group_name = %2 )
1067AND domain_id = %3
1068";
1069 $sqlParams = array(
1070 1 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
1071 2 => array(self::URL_PREFERENCES_NAME, 'String'),
1072 3 => array(CRM_Core_Config::domainID(), 'Integer'),
1073 );
1074
1075 $dao = CRM_Core_DAO::executeQuery($sql,
1076 $sqlParams,
1077 TRUE,
1078 NULL,
1079 FALSE,
1080 TRUE,
1081 // trap exceptions as error
1082 TRUE
1083 );
1084
1085 if (is_a($dao, 'DB_Error')) {
1086 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
1087 exit();
1088 }
1089
1090 while ($dao->fetch()) {
1091 $value = self::getOverride($dao->group_name, $dao->name, NULL);
1092 if ($value === NULL && $dao->value) {
1093 $value = unserialize($dao->value);
1094 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
1095 $value = CRM_Utils_File::absoluteDirectory($value);
1096 }
1097 else {
1098 // CRM-7622: we need to remove the language part
1099 $value = CRM_Utils_System::absoluteURL($value, TRUE);
1100 }
1101 }
1102 // CRM-10931, If DB doesn't have any value, carry on with any default value thats already available
1103 if (!isset($value) && !empty($params[$dao->name])) {
1104 $value = $params[$dao->name];
1105 }
1106 $params[$dao->name] = $value;
1107
1108 if ($setInConfig) {
1109 $config->{$dao->name} = $value;
1110 }
1111 }
1112 }
1113
1114 /**
1115 * Determine what, if any, overrides have been provided
1116 * for a setting.
1117 *
1118 * @param $group
1119 * @param string $name
1120 * @param $default
1121 *
1122 * @return mixed, NULL or an overriden value
1123 */
1124 protected static function getOverride($group, $name, $default) {
1125 global $civicrm_setting;
1126 if ($group && $name && isset($civicrm_setting[$group][$name])) {
1127 return $civicrm_setting[$group][$name];
1128 }
1129 elseif ($group && !isset($name) && isset($civicrm_setting[$group])) {
1130 return $civicrm_setting[$group];
1131 }
1132 else {
1133 return $default;
1134 }
1135 }
1136
1137 /**
1138 * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
1139 *
1140 * @return bool
1141 */
1142 public static function isUpgradeFromPreFourOneAlpha1() {
1143 if (CRM_Core_Config::isUpgradeMode()) {
1144 $currentVer = CRM_Core_BAO_Domain::version();
1145 if (version_compare($currentVer, '4.1.alpha1') < 0) {
1146 return TRUE;
1147 }
1148 }
1149 return FALSE;
1150 }
1151
1152}