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