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