Merge pull request #15800 from eileenmcnaughton/anet_valid
[civicrm-core.git] / CRM / Core / Config / MagicMerge.php
CommitLineData
c0a1f187
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
c0a1f187 5 | |
bc77d7c0
TO
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 |
c0a1f187
TO
9 +--------------------------------------------------------------------+
10 */
11
12/**
13 * Class CRM_Core_Config_MagicMerge
14 *
15 * Originally, the $config object was based on a single, serialized
16 * data object stored in the database. As the needs for settings
9e1e6020
TO
17 * grew (with robust metadata, system overrides, extension support,
18 * and multi-tenancy), the $config started to store a mix of:
c0a1f187
TO
19 * (a) canonical config options,
20 * (b) dynamically generated runtime data,
21 * (c) cached data derived from other sources (esp civicrm_setting)
22 * (d) instances of service objects
23 *
24 * The config object is now deprecated. Settings and service objects
25 * should generally be accessed via Civi::settings() and Civi::service().
26 *
27 * MagicMerge provides backward compatibility. You may still access
28 * old properties via $config, but they will be loaded from their
29 * new services.
30 */
31class CRM_Core_Config_MagicMerge {
32
33 /**
34 * Map old config properties to their contemporary counterparts.
35 *
36 * @var array
37 * Array(string $configAlias => Array(string $realType, string $realName)).
38 */
39 private $map;
40
518fa0ee
SL
41 private $locals;
42 private $settings;
c0a1f187 43
be2fb01f 44 private $cache = [];
7dba62da 45
8246bca4 46 /**
47 * CRM_Core_Config_MagicMerge constructor.
48 */
c0a1f187
TO
49 public function __construct() {
50 $this->map = self::getPropertyMap();
51 }
52
8246bca4 53 /**
54 * Set the map to the property map.
55 */
c0a1f187
TO
56 public function __wakeup() {
57 $this->map = self::getPropertyMap();
58 }
59
60 /**
f806379b
TO
61 * Get a list of $config properties and the entities to which they map.
62 *
63 * This is used for two purposes:
64 *
65 * 1. Runtime: Provide backward-compatible interface for reading these
66 * properties.
67 * 2. Upgrade: Migrate old properties of config_backend into settings.
68 *
c0a1f187
TO
69 * @return array
70 */
71 public static function getPropertyMap() {
e3d28c74
TO
72 // Each mapping: $propertyName => Array(0 => $type, 1 => $foreignName|NULL, ...).
73 // If $foreignName is omitted/null, then it's assumed to match the $propertyName.
74 // Other parameters may be specified, depending on the type.
be2fb01f 75 return [
9e1e6020 76 // "local" properties are unique to each instance of CRM_Core_Config (each request).
be2fb01f
CW
77 'doNotResetCache' => ['local'],
78 'inCiviCRM' => ['local'],
79 'keyDisable' => ['local'],
80 'userFrameworkFrontend' => ['local'],
81 'userPermissionTemp' => ['local'],
9e1e6020
TO
82
83 // "runtime" properties are computed from define()s, $_ENV, etc.
84 // See also: CRM_Core_Config_Runtime.
be2fb01f
CW
85 'dsn' => ['runtime'],
86 'initialized' => ['runtime'],
87 'userFramework' => ['runtime'],
88 'userFrameworkClass' => ['runtime'],
89 'userFrameworkDSN' => ['runtime'],
90 'userFrameworkURLVar' => ['runtime'],
91 'userHookClass' => ['runtime'],
92 'cleanURL' => ['runtime'],
be2fb01f 93 'templateDir' => ['runtime'],
9e1e6020 94
d4330c62 95 // "boot-svc" properties are critical services needed during init.
7f835399 96 // See also: Civi\Core\Container::getBootService().
be2fb01f
CW
97 'userSystem' => ['boot-svc'],
98 'userPermissionClass' => ['boot-svc'],
d4330c62 99
be2fb01f
CW
100 'userFrameworkBaseURL' => ['user-system', 'getAbsoluteBaseURL'],
101 'userFrameworkVersion' => ['user-system', 'getVersion'],
518fa0ee
SL
102 // ugh typo.
103 'useFrameworkRelativeBase' => ['user-system', 'getRelativeBaseURL'],
d4330c62 104
9e1e6020
TO
105 // "setting" properties are loaded through the setting layer, esp
106 // table "civicrm_setting" and global $civicrm_setting.
107 // See also: Civi::settings().
be2fb01f
CW
108 'backtrace' => ['setting'],
109 'contact_default_language' => ['setting'],
110 'countryLimit' => ['setting'],
111 'customTranslateFunction' => ['setting'],
112 'dateInputFormat' => ['setting'],
113 'dateformatDatetime' => ['setting'],
114 'dateformatFull' => ['setting'],
115 'dateformatPartial' => ['setting'],
116 'dateformatTime' => ['setting'],
117 'dateformatYear' => ['setting'],
118 'dateformatFinancialBatch' => ['setting'],
119 'dateformatshortdate' => ['setting'],
518fa0ee
SL
120 // renamed.
121 'debug' => ['setting', 'debug_enabled'],
be2fb01f
CW
122 'defaultContactCountry' => ['setting'],
123 'defaultContactStateProvince' => ['setting'],
124 'defaultCurrency' => ['setting'],
125 'defaultSearchProfileID' => ['setting'],
126 'doNotAttachPDFReceipt' => ['setting'],
127 'empoweredBy' => ['setting'],
518fa0ee
SL
128 // renamed.
129 'enableComponents' => ['setting', 'enable_components'],
be2fb01f
CW
130 'enableSSL' => ['setting'],
131 'fatalErrorHandler' => ['setting'],
132 'fieldSeparator' => ['setting'],
133 'fiscalYearStart' => ['setting'],
134 'geoAPIKey' => ['setting'],
135 'geoProvider' => ['setting'],
136 'includeAlphabeticalPager' => ['setting'],
137 'includeEmailInName' => ['setting'],
138 'includeNickNameInName' => ['setting'],
139 'includeOrderByClause' => ['setting'],
140 'includeWildCardInName' => ['setting'],
141 'inheritLocale' => ['setting'],
142 'languageLimit' => ['setting'],
143 'lcMessages' => ['setting'],
144 'legacyEncoding' => ['setting'],
145 'logging' => ['setting'],
146 'mailThrottleTime' => ['setting'],
147 'mailerBatchLimit' => ['setting'],
148 'mailerJobSize' => ['setting'],
149 'mailerJobsMax' => ['setting'],
150 'mapAPIKey' => ['setting'],
151 'mapProvider' => ['setting'],
152 'maxFileSize' => ['setting'],
518fa0ee
SL
153 // renamed.
154 'maxAttachments' => ['setting', 'max_attachments'],
8913e915 155 'maxAttachmentsBackend' => ['setting', 'max_attachments_backend'],
be2fb01f
CW
156 'monetaryDecimalPoint' => ['setting'],
157 'monetaryThousandSeparator' => ['setting'],
158 'moneyformat' => ['setting'],
159 'moneyvalueformat' => ['setting'],
160 'provinceLimit' => ['setting'],
161 'recaptchaOptions' => ['setting'],
162 'recaptchaPublicKey' => ['setting'],
163 'recaptchaPrivateKey' => ['setting'],
164 'forceRecaptcha' => ['setting'],
165 'replyTo' => ['setting'],
166 'secondDegRelPermissions' => ['setting'],
167 'smartGroupCacheTimeout' => ['setting'],
168 'timeInputFormat' => ['setting'],
169 'userFrameworkLogging' => ['setting'],
170 'userFrameworkUsersTableName' => ['setting'],
171 'verpSeparator' => ['setting'],
172 'wkhtmltopdfPath' => ['setting'],
173 'wpBasePage' => ['setting'],
174 'wpLoadPhp' => ['setting'],
e3d28c74 175
0bd3f65c
TO
176 // "path" properties are managed via Civi::paths and $civicrm_paths
177 // Option: `mkdir` - auto-create dir
178 // Option: `restrict` - auto-restrict remote access
179 'configAndLogDir' => ['path', 'civicrm.log', ['mkdir', 'restrict']],
180 'templateCompileDir' => ['path', 'civicrm.compile', ['mkdir', 'restrict']],
181
9e1e6020
TO
182 // "setting-path" properties are settings with special filtering
183 // to return normalized file paths.
cdbea577
C
184 // Option: `mkdir` - auto-create dir
185 // Option: `restrict` - auto-restrict remote access
be2fb01f
CW
186 'customFileUploadDir' => ['setting-path', NULL, ['mkdir', 'restrict']],
187 'customPHPPathDir' => ['setting-path'],
188 'customTemplateDir' => ['setting-path'],
189 'extensionsDir' => ['setting-path', NULL, ['mkdir']],
190 'imageUploadDir' => ['setting-path', NULL, ['mkdir']],
191 'uploadDir' => ['setting-path', NULL, ['mkdir', 'restrict']],
e3d28c74 192
cdbea577
C
193 // "setting-url" properties are settings with special filtering
194 // to return normalized URLs.
195 // Option: `noslash` - don't append trailing slash
196 // Option: `rel` - convert to relative URL (if possible)
be2fb01f
CW
197 'customCSSURL' => ['setting-url', NULL, ['noslash']],
198 'extensionsURL' => ['setting-url'],
199 'imageUploadURL' => ['setting-url'],
200 'resourceBase' => ['setting-url', 'userFrameworkResourceURL', ['rel']],
201 'userFrameworkResourceURL' => ['setting-url'],
c0a1f187 202
9e1e6020 203 // "callback" properties are generated on-demand by calling a function.
0d1823d7 204 // @todo remove geocodeMethod. As of Feb 2018, $config->geocodeMethod works but gives a deprecation warning.
be2fb01f
CW
205 'geocodeMethod' => ['callback', 'CRM_Utils_Geocode', 'getProviderClass'],
206 'defaultCurrencySymbol' => ['callback', 'CRM_Core_BAO_Country', 'getDefaultCurrencySymbol'],
207 ];
c0a1f187
TO
208 }
209
8246bca4 210 /**
211 * Get value.
212 *
213 * @param string $k
214 *
215 * @return mixed
216 * @throws \CRM_Core_Exception
217 */
c0a1f187
TO
218 public function __get($k) {
219 if (!isset($this->map[$k])) {
220 throw new \CRM_Core_Exception("Cannot read unrecognized property CRM_Core_Config::\${$k}.");
221 }
fd78a9e5 222 if (isset($this->cache[$k])) {
7dba62da
TO
223 return $this->cache[$k];
224 }
e3d28c74
TO
225
226 $type = $this->map[$k][0];
227 $name = isset($this->map[$k][1]) ? $this->map[$k][1] : $k;
c0a1f187
TO
228
229 switch ($type) {
230 case 'setting':
23bb9c85 231 return $this->getSettings()->get($name);
c0a1f187 232
00f6fb2a
TO
233 // The interpretation of 'path' and 'setting-path' is similar, except
234 // that the latter originates in a stored setting.
235 case 'path':
c0a1f187 236 case 'setting-path':
ac47f7ca 237 // Array(0 => $type, 1 => $setting, 2 => $actions).
00f6fb2a
TO
238 $value = ($type === 'path')
239 ? Civi::paths()->getVariable($name, 'path')
240 : Civi::paths()->getPath($this->getSettings()->get($name));
e3d28c74
TO
241 if ($value) {
242 $value = CRM_Utils_File::addTrailingSlash($value);
ac47f7ca 243 if (isset($this->map[$k][2]) && in_array('mkdir', $this->map[$k][2])) {
f7cc6e55 244 if (!is_dir($value) && !CRM_Utils_File::createDir($value, FALSE)) {
be2fb01f 245 CRM_Core_Session::setStatus(ts('Failed to make directory (%1) at "%2". Please update the settings or file permissions.', [
895c19e7
TO
246 1 => $k,
247 2 => $value,
be2fb01f 248 ]));
895c19e7 249 }
e3d28c74 250 }
ac47f7ca 251 if (isset($this->map[$k][2]) && in_array('restrict', $this->map[$k][2])) {
e3d28c74
TO
252 CRM_Utils_File::restrictAccess($value);
253 }
254 }
7dba62da 255 $this->cache[$k] = $value;
e3d28c74
TO
256 return $value;
257
cdbea577 258 case 'setting-url':
be2fb01f 259 $options = !empty($this->map[$k][2]) ? $this->map[$k][2] : [];
6ec7e639 260 $value = $this->getSettings()->get($name);
cdbea577
C
261 if ($value && !(in_array('noslash', $options))) {
262 $value = CRM_Utils_File::addTrailingSlash($value, '/');
6ec7e639 263 }
cdbea577
C
264 $this->cache[$k] = Civi::paths()->getUrl($value,
265 in_array('rel', $options) ? 'relative' : 'absolute');
7dba62da 266 return $this->cache[$k];
c0a1f187
TO
267
268 case 'runtime':
7f835399 269 return \Civi\Core\Container::getBootService('runtime')->{$name};
c0a1f187 270
d4330c62
TO
271 case 'boot-svc':
272 $this->cache[$k] = \Civi\Core\Container::getBootService($name);
273 return $this->cache[$k];
274
c0a1f187
TO
275 case 'local':
276 $this->initLocals();
277 return $this->locals[$name];
278
d4330c62
TO
279 case 'user-system':
280 $userSystem = \Civi\Core\Container::getBootService('userSystem');
be2fb01f 281 $this->cache[$k] = call_user_func([$userSystem, $name]);
d4330c62
TO
282 return $this->cache[$k];
283
c0a1f187
TO
284 case 'service':
285 return \Civi::service($name);
286
287 case 'callback':
288 // Array(0 => $type, 1 => $obj, 2 => $getter, 3 => $setter, 4 => $unsetter).
289 if (!isset($this->map[$k][1], $this->map[$k][2])) {
290 throw new \CRM_Core_Exception("Cannot find getter for property CRM_Core_Config::\${$k}");
291 }
be2fb01f 292 return \Civi\Core\Resolver::singleton()->call([$this->map[$k][1], $this->map[$k][2]], [$k]);
c0a1f187
TO
293
294 default:
295 throw new \CRM_Core_Exception("Cannot read property CRM_Core_Config::\${$k} ($type)");
296 }
297 }
298
8246bca4 299 /**
300 * Set value.
301 *
302 * @param string $k
303 * @param mixed $v
304 *
305 * @throws \CRM_Core_Exception
306 */
c0a1f187
TO
307 public function __set($k, $v) {
308 if (!isset($this->map[$k])) {
309 throw new \CRM_Core_Exception("Cannot set unrecognized property CRM_Core_Config::\${$k}");
310 }
7dba62da 311 unset($this->cache[$k]);
dc640254 312 $type = $this->map[$k][0];
82eff07b 313
c0a1f187
TO
314 switch ($type) {
315 case 'setting':
dc640254 316 case 'setting-path':
cdbea577 317 case 'setting-url':
00f6fb2a 318 case 'path':
d4330c62 319 case 'user-system':
c0a1f187 320 case 'runtime':
dc640254 321 case 'callback':
6504e96d 322 case 'boot-svc':
dc640254 323 // In the past, changes to $config were not persisted automatically.
cdf3884e 324 $this->cache[$k] = $v;
c0a1f187
TO
325 return;
326
327 case 'local':
328 $this->initLocals();
cdf3884e 329 $this->locals[$k] = $v;
c0a1f187
TO
330 return;
331
c0a1f187
TO
332 default:
333 throw new \CRM_Core_Exception("Cannot set property CRM_Core_Config::\${$k} ($type)");
334 }
335 }
336
8246bca4 337 /**
338 * Is value set.
339 *
340 * @param string $k
341 *
342 * @return bool
343 */
c0a1f187
TO
344 public function __isset($k) {
345 return isset($this->map[$k]);
346 }
347
8246bca4 348 /**
349 * Unset value.
350 *
351 * @param string $k
352 *
353 * @throws \CRM_Core_Exception
354 */
c0a1f187
TO
355 public function __unset($k) {
356 if (!isset($this->map[$k])) {
357 throw new \CRM_Core_Exception("Cannot unset unrecognized property CRM_Core_Config::\${$k}");
358 }
7dba62da 359 unset($this->cache[$k]);
dc640254
TO
360 $type = $this->map[$k][0];
361 $name = isset($this->map[$k][1]) ? $this->map[$k][1] : $k;
c0a1f187
TO
362
363 switch ($type) {
364 case 'setting':
365 case 'setting-path':
cdbea577 366 case 'setting-url':
23bb9c85 367 $this->getSettings()->revert($k);
c0a1f187
TO
368 return;
369
370 case 'local':
371 $this->initLocals();
372 $this->locals[$name] = NULL;
373 return;
374
375 case 'callback':
376 // Array(0 => $type, 1 => $obj, 2 => $getter, 3 => $setter, 4 => $unsetter).
377 if (!isset($this->map[$k][1], $this->map[$k][4])) {
378 throw new \CRM_Core_Exception("Cannot find unsetter for property CRM_Core_Config::\${$k}");
379 }
be2fb01f 380 \Civi\Core\Resolver::singleton()->call([$this->map[$k][1], $this->map[$k][4]], [$k]);
c0a1f187
TO
381 return;
382
383 default:
384 throw new \CRM_Core_Exception("Cannot unset property CRM_Core_Config::\${$k} ($type)");
385 }
386 }
387
23bb9c85
TO
388 /**
389 * @return \Civi\Core\SettingsBag
390 */
391 protected function getSettings() {
392 if ($this->settings === NULL) {
393 $this->settings = Civi::settings();
394 }
395 return $this->settings;
396 }
397
8246bca4 398 /**
399 * Initialise local settings.
400 */
c0a1f187
TO
401 private function initLocals() {
402 if ($this->locals === NULL) {
be2fb01f 403 $this->locals = [
c0a1f187
TO
404 'inCiviCRM' => FALSE,
405 'doNotResetCache' => 0,
5f900b59 406 'keyDisable' => FALSE,
c0a1f187
TO
407 'initialized' => FALSE,
408 'userFrameworkFrontend' => FALSE,
d4330c62 409 'userPermissionTemp' => NULL,
be2fb01f 410 ];
c0a1f187
TO
411 }
412 }
413
414}