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