handle recurring entity delete
[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 null $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 null $componentID
127 * @param null $contactID
128 * @param null $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 null $componentID
156 * @param null $contactID
157 * @param null $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 null $domainID
207 *
208 * @return object 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 null $contactID
328 * @param int $createdID An optional ID to assign the creator to. If not set, retrieved from session
329 *
330 * @param null $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 $name
364 * @param null $componentID
365 * @param null $contactID
366 * @param null $createdID
367 * @param null $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 * Delete some or all of the items in the settings table
603 *
604 * @param string $group The group name of the entries to be deleted
605 * @param string $name The name of the setting to be deleted
606 * @param int $componentID The optional component ID (so componenets can share the same name space)
607 *
608 * @return void
609 * @static
610 * @access public
611 *
612 static function deleteItem($group, $name = NULL, $componentID = NULL, $contactID = NULL) {
613 $dao = self::dao($group, $name, $componentID, $contactID);
614 $dao->delete();
615
616 // also reset memory cache if any
617 CRM_Utils_System::flushCache();
618
619 $cacheKey = self::inCache($group, $name, $componentID, $contactID, FALSE);
620 if ($cacheKey) {
621 if ($name) {
622 unset(self::$_cache[$cacheKey][$name]);
623 }
624 else {
625 unset(self::$_cache[$cacheKey]);
626 }
627 }
628 }*/
629
630 /**
631 * This provides information about the setting - similar to the fields concept for DAO information.
632 * As the setting is serialized code creating validation setting input needs to know the data type
633 * This also helps move information out of the form layer into the data layer where people can interact with
634 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
635 * also leverages it.
636 *
637 * Note that this function should never be called when using the runtime getvalue function. Caching works
638 * around the expectation it will be called during setting administration
639 *
640 * Function is intended for configuration rather than runtime access to settings
641 *
642 * The following params will filter the result. If none are passed all settings will be returns
643 *
644 * @params string $name Name of specific setting e.g customCSSURL
645 * @params integer $componentID id of relevant component.
646 *
647 * @param null $componentID
648 * @param array $filters
649 * @param null $domainID
650 * @param null $profile
651 *
652 * @return array $result - the following information as appropriate for each setting
653 * - name
654 * - type
655 * - default
656 * - add (CiviCRM version added)
657 * - is_domain
658 * - is_contact
659 * - description
660 * - help_text
661 */
662 static function getSettingSpecification(
663 $componentID = NULL,
664 $filters = array(),
665 $domainID = NULL,
666 $profile = NULL
667 ) {
668 $cacheString = 'settingsMetadata_' . $domainID . '_' . $profile;
669 foreach ($filters as $filterField => $filterString) {
670 $cacheString .= "_{$filterField}_{$filterString}";
671 }
672 $cached = 1;
673 // the caching into 'All' seems to be a duplicate of caching to
674 // settingsMetadata__ - I think the reason was to cache all settings as defined & then those altered by a hook
675 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Specs', $cacheString, $componentID);
676 if ($settingsMetadata === NULL) {
677 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Spec', 'All', $componentID);
678 if (empty($settingsMetadata)) {
679 global $civicrm_root;
680 $metaDataFolders = array($civicrm_root. '/settings');
681 CRM_Utils_Hook::alterSettingsFolders($metaDataFolders);
682 $settingsMetadata = self::loadSettingsMetaDataFolders($metaDataFolders);
683 CRM_Core_BAO_Cache::setItem($settingsMetadata,'CiviCRM setting Spec', 'All', $componentID);
684 }
685 $cached = 0;
686 }
687
688 CRM_Utils_Hook::alterSettingsMetaData($settingsMetadata, $domainID, $profile);
689 self::_filterSettingsSpecification($filters, $settingsMetadata);
690
691 if (!$cached) {
692 // this is a bit 'heavy' if you are using hooks but this function
693 // is expected to only be called during setting administration
694 // it should not be called by 'getvalue' or 'getitem
695 CRM_Core_BAO_Cache::setItem(
696 $settingsMetadata,
697 'CiviCRM setting Specs',
698 $cacheString,
699 $componentID
700 );
701 }
702 return $settingsMetadata;
703
704 }
705
706 /**
707 * Load the settings files defined in a series of folders
708 * @param array $metaDataFolders list of folder paths
709 * @return array
710 */
711 public static function loadSettingsMetaDataFolders($metaDataFolders) {
712 $settingsMetadata = array();
713 $loadedFolders = array();
714 foreach ($metaDataFolders as $metaDataFolder) {
715 $realFolder = realpath($metaDataFolder);
716 if (is_dir($realFolder) && !isset($loadedFolders[$realFolder])) {
717 $loadedFolders[$realFolder] = TRUE;
718 $settingsMetadata = $settingsMetadata + self::loadSettingsMetaData($metaDataFolder);
719 }
720 }
721 return $settingsMetadata;
722 }
723
724 /**
725 * Load up settings metadata from files
726 */
727 static function loadSettingsMetadata($metaDataFolder) {
728 $settingMetaData = array();
729 $settingsFiles = CRM_Utils_File::findFiles($metaDataFolder, '*.setting.php');
730 foreach ($settingsFiles as $file) {
731 $settings = include $file;
732 $settingMetaData = array_merge($settingMetaData, $settings);
733 }
734 CRM_Core_BAO_Cache::setItem($settingMetaData,'CiviCRM setting Spec', 'All');
735 return $settingMetaData;
736 }
737
738 /**
739 * Filter the settings metadata according to filters passed in. This is a convenience filter
740 * and allows selective reverting / filling of settings
741 *
742 * @param array $filters Filters to match against data
743 * @param array $settingSpec metadata to filter
744 */
745 static function _filterSettingsSpecification($filters, &$settingSpec) {
746 if (empty($filters)) {
747 return;
748 }
749 else if (array_keys($filters) == array('name')) {
750 $settingSpec = array($filters['name'] => CRM_Utils_Array::value($filters['name'], $settingSpec, ''));
751 return;
752 }
753 else {
754 foreach ($settingSpec as $field => $fieldValues) {
755 if (array_intersect_assoc($fieldValues, $filters) != $filters) {
756 unset($settingSpec[$field]);
757 }
758 }
759 return;
760 }
761 }
762
763 /**
764 * Look for any missing settings and convert them from config or load default as appropriate
765 * This should be run from GenCode & also from upgrades to add any new defaults.
766 *
767 * Multisites have often been overlooked in upgrade scripts so can be expected to be missing
768 * a number of settings
769 */
770 static function updateSettingsFromMetaData() {
771 $apiParams = array(
772 'version' => 3,
773 'domain_id' => 'all',
774 'filters' => array('prefetch' => 0),
775 );
776 $existing = civicrm_api('setting', 'get', $apiParams);
777
778 if (!empty($existing['values'])) {
779 $allSettings = civicrm_api('setting', 'getfields', array('version' => 3));
780 foreach ($existing['values'] as $domainID => $domainSettings) {
781 CRM_Core_BAO_Domain::setDomain($domainID);
782 $missing = array_diff_key($allSettings['values'], $domainSettings);
783 foreach ($missing as $name => $settings) {
784 self::convertConfigToSetting($name, $domainID);
785 }
786 CRM_Core_BAO_Domain::resetDomain();
787 }
788 }
789 }
790
791 /**
792 * move an item from being in the config array to being stored as a setting
793 * remove from config - as appropriate based on metadata
794 *
795 * Note that where the key name is being changed the 'legacy_key' will give us the old name
796 */
797 static function convertConfigToSetting($name, $domainID = NULL) {
798 // we have to force this here in case more than one domain is in play.
799 // whenever there is a possibility of more than one domain we must force it
800 $config = CRM_Core_Config::singleton();
801 if (empty($domainID)) {
802 $domainID= CRM_Core_Config::domainID();
803 }
804 $domain = new CRM_Core_DAO_Domain();
805 $domain->id = $domainID;
806 $domain->find(TRUE);
807 if ($domain->config_backend) {
808 $values = unserialize($domain->config_backend);
809 } else {
810 $values = array();
811 }
812 $spec = self::getSettingSpecification(NULL, array('name' => $name), $domainID);
813 $configKey = CRM_Utils_Array::value('config_key', $spec[$name], CRM_Utils_Array::value('legacy_key', $spec[$name], $name));
814 //if the key is set to config_only we don't need to do anything
815 if(empty($spec[$name]['config_only'])){
816 if (!empty($values[$configKey])) {
817 civicrm_api('setting', 'create', array('version' => 3, $name => $values[$configKey], 'domain_id' => $domainID));
818 }
819 else {
820 civicrm_api('setting', 'fill', array('version' => 3, 'name' => $name, 'domain_id' => $domainID));
821 }
822
823 if (empty($spec[$name]['prefetch']) && !empty($values[$configKey])) {
824 unset($values[$configKey]);
825 $domain->config_backend = serialize($values);
826 $domain->save();
827 unset($config->$configKey);
828 }
829 }
830 }
831
832 /**
833 * @param $group
834 * @param $name
835 * @param bool $system
836 * @param null $userID
837 * @param bool $localize
838 * @param string $returnField
839 * @param bool $returnNameANDLabels
840 * @param null $condition
841 *
842 * @return array
843 */
844 static function valueOptions($group,
845 $name,
846 $system = TRUE,
847 $userID = NULL,
848 $localize = FALSE,
849 $returnField = 'name',
850 $returnNameANDLabels = FALSE,
851 $condition = NULL
852 ) {
853 $optionValue = self::getItem($group, $name);
854
855 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
856
857 //enabled name => label require for new contact edit form, CRM-4605
858 if ($returnNameANDLabels) {
859 $names = $labels = $nameAndLabels = array();
860 if ($returnField == 'name') {
861 $names = $groupValues;
862 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
863 }
864 else {
865 $labels = $groupValues;
866 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
867 }
868 }
869
870 $returnValues = array();
871 foreach ($groupValues as $gn => $gv) {
872 $returnValues[$gv] = 0;
873 }
874
875 if ($optionValue && !empty($groupValues)) {
876 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
877 substr($optionValue, 1, -1)
878 );
879
880 if (!empty($dbValues)) {
881 foreach ($groupValues as $key => $val) {
882 if (in_array($key, $dbValues)) {
883 $returnValues[$val] = 1;
884 if ($returnNameANDLabels) {
885 $nameAndLabels[$names[$key]] = $labels[$key];
886 }
887 }
888 }
889 }
890 }
891 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
892 }
893
894 /**
895 * @param $group
896 * @param $name
897 * @param $value
898 * @param bool $system
899 * @param null $userID
900 * @param string $keyField
901 */
902 static function setValueOption($group,
903 $name,
904 $value,
905 $system = TRUE,
906 $userID = NULL,
907 $keyField = 'name'
908 ) {
909 if (empty($value)) {
910 $optionValue = NULL;
911 }
912 elseif (is_array($value)) {
913 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
914
915 $cbValues = array();
916 foreach ($groupValues as $key => $val) {
917 if (!empty($value[$val])) {
918 $cbValues[$key] = 1;
919 }
920 }
921
922 if (!empty($cbValues)) {
923 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
924 array_keys($cbValues)
925 ) . CRM_Core_DAO::VALUE_SEPARATOR;
926 }
927 else {
928 $optionValue = NULL;
929 }
930 }
931 else {
932 $optionValue = $value;
933 }
934
935 self::setItem($optionValue, $group, $name);
936 }
937
938 /**
939 * @param $params
940 * @param null $domainID
941 */
942 static function fixAndStoreDirAndURL(&$params, $domainID = NULL) {
943 if (self::isUpgradeFromPreFourOneAlpha1()) {
944 return;
945 }
946
947 if (empty($domainID)) {
948 $domainID = CRM_Core_Config::domainID();
949 }
950 $sql = "
951 SELECT name, group_name
952 FROM civicrm_setting
953 WHERE domain_id = %1
954 AND ( group_name = %2
955 OR group_name = %3 )
956 ";
957 $sqlParams = array(
958 1 => array($domainID, 'Integer'),
959 2 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
960 3 => array(self::URL_PREFERENCES_NAME, 'String'),
961 );
962
963 $dirParams = array();
964 $urlParams = array();
965
966 $dao = CRM_Core_DAO::executeQuery($sql,
967 $sqlParams,
968 TRUE,
969 NULL,
970 FALSE,
971 TRUE,
972 // trap exceptions as error
973 TRUE
974 );
975
976 if (is_a($dao, 'DB_Error')) {
977 if (CRM_Core_Config::isUpgradeMode()) {
978 // seems like this is a 4.0 -> 4.1 upgrade, so we suppress this error and continue
979 return;
980 }
981 else {
982 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
983 exit();
984 }
985 }
986
987 while ($dao->fetch()) {
988 if (!isset($params[$dao->name])) {
989 continue;
990 }
991 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
992 $dirParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
993 }
994 else {
995 $urlParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
996 }
997 unset($params[$dao->name]);
998 }
999
1000 if (!empty($dirParams)) {
1001 self::storeDirectoryOrURLPreferences($dirParams,
1002 self::DIRECTORY_PREFERENCES_NAME
1003 );
1004 }
1005
1006 if (!empty($urlParams)) {
1007 self::storeDirectoryOrURLPreferences($urlParams,
1008 self::URL_PREFERENCES_NAME
1009 );
1010 }
1011 }
1012
1013 /**
1014 * @param $params
1015 * @param $group
1016 */
1017 static function storeDirectoryOrURLPreferences(&$params, $group) {
1018 foreach ($params as $name => $value) {
1019 // always try to store relative directory or url from CMS root
1020 $value = ($group == self::DIRECTORY_PREFERENCES_NAME) ? CRM_Utils_File::relativeDirectory($value) : CRM_Utils_System::relativeURL($value);
1021
1022 self::setItem($value, $group, $name);
1023 }
1024 }
1025
1026 /**
1027 * @param $params
1028 * @param bool $setInConfig
1029 */
1030 static function retrieveDirectoryAndURLPreferences(&$params, $setInConfig = FALSE) {
1031 if (CRM_Core_Config::isUpgradeMode()) {
1032 $isJoomla = (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') ? TRUE : FALSE;
1033 // hack to set the resource base url so that js/ css etc is loaded correctly
1034 if ($isJoomla) {
1035 $params['userFrameworkResourceURL'] = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/') . str_replace('administrator', '', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'userFrameworkResourceURL', 'value', 'name'));
1036 }
1037 if (self::isUpgradeFromPreFourOneAlpha1()) {
1038 return;
1039 }
1040 }
1041
1042 if ($setInConfig) {
1043 $config = CRM_Core_Config::singleton();
1044 }
1045
1046 $sql = "
1047 SELECT name, group_name, value
1048 FROM civicrm_setting
1049 WHERE ( group_name = %1
1050 OR group_name = %2 )
1051 AND domain_id = %3
1052 ";
1053 $sqlParams = array(1 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
1054 2 => array(self::URL_PREFERENCES_NAME, 'String'),
1055 3 => array(CRM_Core_Config::domainID(), 'Integer'),
1056 );
1057
1058 $dao = CRM_Core_DAO::executeQuery($sql,
1059 $sqlParams,
1060 TRUE,
1061 NULL,
1062 FALSE,
1063 TRUE,
1064 // trap exceptions as error
1065 TRUE
1066 );
1067
1068 if (is_a($dao, 'DB_Error')) {
1069 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
1070 exit();
1071 }
1072
1073 while ($dao->fetch()) {
1074 $value = self::getOverride($dao->group_name, $dao->name, NULL);
1075 if ($value === NULL && $dao->value) {
1076 $value = unserialize($dao->value);
1077 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
1078 $value = CRM_Utils_File::absoluteDirectory($value);
1079 }
1080 else {
1081 // CRM-7622: we need to remove the language part
1082 $value = CRM_Utils_System::absoluteURL($value, TRUE);
1083 }
1084 }
1085 // CRM-10931, If DB doesn't have any value, carry on with any default value thats already available
1086 if (!isset($value) && !empty($params[$dao->name])) {
1087 $value = $params[$dao->name];
1088 }
1089 $params[$dao->name] = $value;
1090
1091 if ($setInConfig) {
1092 $config->{$dao->name} = $value;
1093 }
1094 }
1095 }
1096
1097 /**
1098 * Determine what, if any, overrides have been provided
1099 * for a setting.
1100 *
1101 * @param $group
1102 * @param $name
1103 * @param $default
1104 *
1105 * @return mixed, NULL or an overriden value
1106 */
1107 protected static function getOverride($group, $name, $default) {
1108 global $civicrm_setting;
1109 if ($group && $name && isset($civicrm_setting[$group][$name])) {
1110 return $civicrm_setting[$group][$name];
1111 }
1112 else {
1113 return $default;
1114 }
1115 }
1116
1117 /**
1118 * civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
1119 *
1120 * @return boolean
1121 */
1122 static function isUpgradeFromPreFourOneAlpha1() {
1123 if (CRM_Core_Config::isUpgradeMode()) {
1124 $currentVer = CRM_Core_BAO_Domain::version();
1125 if (version_compare($currentVer, '4.1.alpha1') < 0) {
1126 return TRUE;
1127 }
1128 }
1129 return FALSE;
1130 }
1131 }