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