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