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