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