comment fixes
[civicrm-core.git] / CRM / Core / BAO / Setting.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 */
33
34 /**
35 * BAO object for civicrm_setting table. This table is used to store civicrm settings that are not used
36 * very frequently (i.e. not on every page load)
37 *
38 * The group column is used for grouping together all settings that logically belong to the same set.
39 * Thus all settings in the same group are retrieved with one DB call and then cached for future needs.
40 */
41 class CRM_Core_BAO_Setting extends CRM_Core_DAO_Setting {
42
43 /**
44 * Various predefined settings that have been migrated to the setting table.
45 */
46 const
47 ADDRESS_STANDARDIZATION_PREFERENCES_NAME = 'Address Standardization Preferences',
48 CAMPAIGN_PREFERENCES_NAME = 'Campaign Preferences',
49 DEVELOPER_PREFERENCES_NAME = 'Developer Preferences',
50 DIRECTORY_PREFERENCES_NAME = 'Directory Preferences',
51 EVENT_PREFERENCES_NAME = 'Event Preferences',
52 MAILING_PREFERENCES_NAME = 'Mailing Preferences',
53 MAP_PREFERENCES_NAME = 'Map Preferences',
54 CONTRIBUTE_PREFERENCES_NAME = 'Contribute Preferences',
55 MEMBER_PREFERENCES_NAME = 'Member Preferences',
56 MULTISITE_PREFERENCES_NAME = 'Multi Site Preferences',
57 PERSONAL_PREFERENCES_NAME = 'Personal Preferences',
58 SYSTEM_PREFERENCES_NAME = 'CiviCRM Preferences',
59 URL_PREFERENCES_NAME = 'URL Preferences',
60 LOCALIZATION_PREFERENCES_NAME = 'Localization Preferences',
61 SEARCH_PREFERENCES_NAME = 'Search Preferences';
62
63 /**
64 * Retrieve the value of a setting from the DB table.
65 *
66 * @param string $group
67 * (required) The group name of the item.
68 * @param string $name
69 * (required) The name under which this item is stored.
70 * @param int $componentID
71 * The optional component ID (so componenets can share the same name space).
72 * @param string $defaultValue
73 * The default value to return for this setting if not present in DB.
74 * @param int $contactID
75 * If set, this is a contactID specific setting, else its a global setting.
76 *
77 * @param int $domainID
78 *
79 * @return mixed
80 * The data if present in the setting table, else null
81 */
82 public static function getItem(
83 $group,
84 $name = NULL,
85 $componentID = NULL,
86 $defaultValue = NULL,
87 $contactID = NULL,
88 $domainID = NULL
89 ) {
90 /** @var \Civi\Core\SettingsManager $manager */
91 $manager = \Civi::service('settings_manager');
92 $settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
93 if (TRUE) {
94 if ($name === NULL) {
95 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name should be provided.\n");
96 }
97 if ($componentID !== NULL) {
98 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Component should be omitted\n");
99 }
100 if ($defaultValue !== NULL) {
101 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Defaults should come from metadata\n");
102 }
103 }
104 return $name ? $settings->get($name) : $settings->all();
105 }
106
107 /**
108 * Store multiple items in the setting table.
109 *
110 * @param array $params
111 * (required) An api formatted array of keys and values.
112 * @param array $domains Array of domains to get settings for. Default is the current domain
113 * @param $settingsToReturn
114 *
115 * @return array
116 */
117 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
118 $originalDomain = CRM_Core_Config::domainID();
119 if (empty($domains)) {
120 $domains[] = $originalDomain;
121 }
122 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
123 $settingsToReturn = array($settingsToReturn);
124 }
125 $reloadConfig = FALSE;
126
127 $fields = $result = array();
128 $fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
129 foreach ($domains as $domainID) {
130 if ($domainID != CRM_Core_Config::domainID()) {
131 $reloadConfig = TRUE;
132 CRM_Core_BAO_Domain::setDomain($domainID);
133 }
134 $config = CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
135 $result[$domainID] = array();
136 foreach ($fieldsToGet as $name => $value) {
137 $contactID = CRM_Utils_Array::value('contact_id', $params);
138 $setting = CRM_Core_BAO_Setting::getItem(NULL, $name, NULL, NULL, $contactID, $domainID);
139 if (!is_null($setting)) {
140 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
141 // e.g for revert of fill actions
142 $result[$domainID][$name] = $setting;
143 }
144 }
145 CRM_Core_BAO_Domain::resetDomain();
146 }
147 return $result;
148 }
149
150 /**
151 * Store an item in the setting table.
152 *
153 * _setItem() is the common logic shared by setItem() and setItems().
154 *
155 * @param object $value
156 * (required) The value that will be serialized and stored.
157 * @param string $group
158 * (required) The group name of the item.
159 * @param string $name
160 * (required) The name of the setting.
161 * @param int $componentID
162 * The optional component ID (so componenets can share the same name space).
163 * @param int $contactID
164 * @param int $createdID
165 * An optional ID to assign the creator to. If not set, retrieved from session.
166 *
167 * @param int $domainID
168 */
169 public static function setItem(
170 $value,
171 $group,
172 $name,
173 $componentID = NULL,
174 $contactID = NULL,
175 $createdID = NULL,
176 $domainID = NULL
177 ) {
178 /** @var \Civi\Core\SettingsManager $manager */
179 $manager = \Civi::service('settings_manager');
180 $settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
181 $settings->set($name, $value);
182 }
183
184 /**
185 * Store multiple items in the setting table. Note that this will also store config keys
186 * the storage is determined by the metdata and is affected by
187 * 'name' setting's name
188 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
189 * 'legacy_key' = rename from config or setting with this name
190 *
191 * _setItem() is the common logic shared by setItem() and setItems().
192 *
193 * @param array $params
194 * (required) An api formatted array of keys and values.
195 * @param null $domains
196 *
197 * @throws api_Exception
198 * @domains array an array of domains to get settings for. Default is the current domain
199 * @return array
200 */
201 public static function setItems(&$params, $domains = NULL) {
202 $domains = empty($domains) ? array(CRM_Core_Config::domainID()) : $domains;
203
204 // FIXME: redundant validation
205 // FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
206
207 $fields = array();
208 $fieldsToSet = self::validateSettingsInput($params, $fields);
209
210 foreach ($fieldsToSet as $settingField => &$settingValue) {
211 self::validateSetting($settingValue, $fields['values'][$settingField]);
212 }
213
214 foreach ($domains as $domainID) {
215 Civi::settings($domainID)->add($fieldsToSet);
216 $result[$domainID] = $fieldsToSet;
217 }
218
219 return $result;
220 }
221
222 /**
223 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
224 *
225 * This function filters on the fields like 'version' & 'debug' that are not settings
226 *
227 * @param array $params
228 * Parameters as passed into API.
229 * @param array $fields
230 * Empty array to be populated with fields metadata.
231 * @param bool $createMode
232 *
233 * @throws api_Exception
234 * @return array
235 * name => value array of the fields to be set (with extraneous removed)
236 */
237 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
238 $group = CRM_Utils_Array::value('group', $params);
239
240 $ignoredParams = array(
241 'version',
242 'id',
243 'domain_id',
244 'debug',
245 'created_id',
246 'component_id',
247 'contact_id',
248 'filters',
249 'entity_id',
250 'entity_table',
251 'sequential',
252 'api.has_parent',
253 'IDS_request_uri',
254 'IDS_user_agent',
255 'check_permissions',
256 'options',
257 'prettyprint',
258 );
259 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
260 $getFieldsParams = array('version' => 3);
261 if (count($settingParams) == 1) {
262 // ie we are only setting one field - we'll pass it into getfields for efficiency
263 list($name) = array_keys($settingParams);
264 $getFieldsParams['name'] = $name;
265 }
266 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
267 $invalidParams = (array_diff_key($settingParams, $fields['values']));
268 if (!empty($invalidParams)) {
269 throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
270 }
271 if (!empty($settingParams)) {
272 $filteredFields = array_intersect_key($settingParams, $fields['values']);
273 }
274 else {
275 // no filters so we are interested in all for get mode. In create mode this means nothing to set
276 $filteredFields = $createMode ? array() : $fields['values'];
277 }
278 return $filteredFields;
279 }
280
281 /**
282 * Validate & convert settings input.
283 *
284 * @param mixed $value
285 * value of the setting to be set
286 * @param array $fieldSpec
287 * Metadata for given field (drawn from the xml)
288 *
289 * @return bool
290 * @throws \api_Exception
291 */
292 public static function validateSetting(&$value, $fieldSpec) {
293 if ($fieldSpec['type'] == 'String' && is_array($value)) {
294 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
295 }
296 if (empty($fieldSpec['validate_callback'])) {
297 return TRUE;
298 }
299 else {
300 $cb = Civi\Core\Resolver::singleton()->get($fieldSpec['validate_callback']);
301 if (!call_user_func_array($cb, array(&$value, $fieldSpec))) {
302 throw new api_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
303 }
304 }
305 }
306
307 /**
308 * Validate & convert settings input - translate True False to 0 or 1
309 *
310 * @value mixed value of the setting to be set
311 * @fieldSpec array Metadata for given field (drawn from the xml)
312 */
313 public static function validateBoolSetting(&$value, $fieldSpec) {
314 if (!CRM_Utils_Rule::boolean($value)) {
315 throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
316 }
317 if (!$value) {
318 $value = 0;
319 }
320 else {
321 $value = 1;
322 }
323 return TRUE;
324 }
325
326 /**
327 * This provides information about the setting - similar to the fields concept for DAO information.
328 * As the setting is serialized code creating validation setting input needs to know the data type
329 * This also helps move information out of the form layer into the data layer where people can interact with
330 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
331 * also leverages it.
332 *
333 * Note that this function should never be called when using the runtime getvalue function. Caching works
334 * around the expectation it will be called during setting administration
335 *
336 * Function is intended for configuration rather than runtime access to settings
337 *
338 * The following params will filter the result. If none are passed all settings will be returns
339 *
340 * @param int $componentID
341 * Id of relevant component.
342 * @param array $filters
343 * @param int $domainID
344 * @param null $profile
345 *
346 * @return array
347 * the following information as appropriate for each setting
348 * - name
349 * - type
350 * - default
351 * - add (CiviCRM version added)
352 * - is_domain
353 * - is_contact
354 * - description
355 * - help_text
356 */
357 public static function getSettingSpecification(
358 $componentID = NULL,
359 $filters = array(),
360 $domainID = NULL,
361 $profile = NULL
362 ) {
363 return \Civi\Core\SettingsMetadata::getMetadata($filters, $domainID);
364 }
365
366 /**
367 * @param $group
368 * @param string $name
369 * @param bool $system
370 * @param int $userID
371 * @param bool $localize
372 * @param string $returnField
373 * @param bool $returnNameANDLabels
374 * @param null $condition
375 *
376 * @return array
377 */
378 public static function valueOptions(
379 $group,
380 $name,
381 $system = TRUE,
382 $userID = NULL,
383 $localize = FALSE,
384 $returnField = 'name',
385 $returnNameANDLabels = FALSE,
386 $condition = NULL
387 ) {
388 $optionValue = self::getItem($group, $name);
389
390 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
391
392 //enabled name => label require for new contact edit form, CRM-4605
393 if ($returnNameANDLabels) {
394 $names = $labels = $nameAndLabels = array();
395 if ($returnField == 'name') {
396 $names = $groupValues;
397 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
398 }
399 else {
400 $labels = $groupValues;
401 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
402 }
403 }
404
405 $returnValues = array();
406 foreach ($groupValues as $gn => $gv) {
407 $returnValues[$gv] = 0;
408 }
409
410 if ($optionValue && !empty($groupValues)) {
411 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
412 substr($optionValue, 1, -1)
413 );
414
415 if (!empty($dbValues)) {
416 foreach ($groupValues as $key => $val) {
417 if (in_array($key, $dbValues)) {
418 $returnValues[$val] = 1;
419 if ($returnNameANDLabels) {
420 $nameAndLabels[$names[$key]] = $labels[$key];
421 }
422 }
423 }
424 }
425 }
426 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
427 }
428
429 /**
430 * @param $group
431 * @param string $name
432 * @param $value
433 * @param bool $system
434 * @param int $userID
435 * @param string $keyField
436 */
437 public static function setValueOption(
438 $group,
439 $name,
440 $value,
441 $system = TRUE,
442 $userID = NULL,
443 $keyField = 'name'
444 ) {
445 if (empty($value)) {
446 $optionValue = NULL;
447 }
448 elseif (is_array($value)) {
449 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
450
451 $cbValues = array();
452 foreach ($groupValues as $key => $val) {
453 if (!empty($value[$val])) {
454 $cbValues[$key] = 1;
455 }
456 }
457
458 if (!empty($cbValues)) {
459 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
460 array_keys($cbValues)
461 ) . CRM_Core_DAO::VALUE_SEPARATOR;
462 }
463 else {
464 $optionValue = NULL;
465 }
466 }
467 else {
468 $optionValue = $value;
469 }
470
471 self::setItem($optionValue, $group, $name);
472 }
473
474 /**
475 * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
476 *
477 * @return bool
478 */
479 public static function isUpgradeFromPreFourOneAlpha1() {
480 if (CRM_Core_Config::isUpgradeMode()) {
481 $currentVer = CRM_Core_BAO_Domain::version();
482 if (version_compare($currentVer, '4.1.alpha1') < 0) {
483 return TRUE;
484 }
485 }
486 return FALSE;
487 }
488
489 }