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