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