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