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