Merge pull request #15263 from JMAConsulting/financial-67
[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 'templateDir' => ['runtime'],
110
111 // "boot-svc" properties are critical services needed during init.
112 // See also: Civi\Core\Container::getBootService().
113 'userSystem' => ['boot-svc'],
114 'userPermissionClass' => ['boot-svc'],
115
116 'userFrameworkBaseURL' => ['user-system', 'getAbsoluteBaseURL'],
117 'userFrameworkVersion' => ['user-system', 'getVersion'],
118 // ugh typo.
119 'useFrameworkRelativeBase' => ['user-system', 'getRelativeBaseURL'],
120
121 // "setting" properties are loaded through the setting layer, esp
122 // table "civicrm_setting" and global $civicrm_setting.
123 // See also: Civi::settings().
124 'backtrace' => ['setting'],
125 'contact_default_language' => ['setting'],
126 'countryLimit' => ['setting'],
127 'customTranslateFunction' => ['setting'],
128 'dateInputFormat' => ['setting'],
129 'dateformatDatetime' => ['setting'],
130 'dateformatFull' => ['setting'],
131 'dateformatPartial' => ['setting'],
132 'dateformatTime' => ['setting'],
133 'dateformatYear' => ['setting'],
134 'dateformatFinancialBatch' => ['setting'],
135 'dateformatshortdate' => ['setting'],
136 // renamed.
137 'debug' => ['setting', 'debug_enabled'],
138 'defaultContactCountry' => ['setting'],
139 'defaultContactStateProvince' => ['setting'],
140 'defaultCurrency' => ['setting'],
141 'defaultSearchProfileID' => ['setting'],
142 'doNotAttachPDFReceipt' => ['setting'],
143 'empoweredBy' => ['setting'],
144 // renamed.
145 'enableComponents' => ['setting', 'enable_components'],
146 'enableSSL' => ['setting'],
147 'fatalErrorHandler' => ['setting'],
148 'fieldSeparator' => ['setting'],
149 'fiscalYearStart' => ['setting'],
150 'geoAPIKey' => ['setting'],
151 'geoProvider' => ['setting'],
152 'includeAlphabeticalPager' => ['setting'],
153 'includeEmailInName' => ['setting'],
154 'includeNickNameInName' => ['setting'],
155 'includeOrderByClause' => ['setting'],
156 'includeWildCardInName' => ['setting'],
157 'inheritLocale' => ['setting'],
158 'languageLimit' => ['setting'],
159 'lcMessages' => ['setting'],
160 'legacyEncoding' => ['setting'],
161 'logging' => ['setting'],
162 'mailThrottleTime' => ['setting'],
163 'mailerBatchLimit' => ['setting'],
164 'mailerJobSize' => ['setting'],
165 'mailerJobsMax' => ['setting'],
166 'mapAPIKey' => ['setting'],
167 'mapProvider' => ['setting'],
168 'maxFileSize' => ['setting'],
169 // renamed.
170 'maxAttachments' => ['setting', 'max_attachments'],
171 'monetaryDecimalPoint' => ['setting'],
172 'monetaryThousandSeparator' => ['setting'],
173 'moneyformat' => ['setting'],
174 'moneyvalueformat' => ['setting'],
175 'provinceLimit' => ['setting'],
176 'recaptchaOptions' => ['setting'],
177 'recaptchaPublicKey' => ['setting'],
178 'recaptchaPrivateKey' => ['setting'],
179 'forceRecaptcha' => ['setting'],
180 'replyTo' => ['setting'],
181 'secondDegRelPermissions' => ['setting'],
182 'smartGroupCacheTimeout' => ['setting'],
183 'timeInputFormat' => ['setting'],
184 'userFrameworkLogging' => ['setting'],
185 'userFrameworkUsersTableName' => ['setting'],
186 'verpSeparator' => ['setting'],
187 'wkhtmltopdfPath' => ['setting'],
188 'wpBasePage' => ['setting'],
189 'wpLoadPhp' => ['setting'],
190
191 // "path" properties are managed via Civi::paths and $civicrm_paths
192 // Option: `mkdir` - auto-create dir
193 // Option: `restrict` - auto-restrict remote access
194 'configAndLogDir' => ['path', 'civicrm.log', ['mkdir', 'restrict']],
195 'templateCompileDir' => ['path', 'civicrm.compile', ['mkdir', 'restrict']],
196
197 // "setting-path" properties are settings with special filtering
198 // to return normalized file paths.
199 // Option: `mkdir` - auto-create dir
200 // Option: `restrict` - auto-restrict remote access
201 'customFileUploadDir' => ['setting-path', NULL, ['mkdir', 'restrict']],
202 'customPHPPathDir' => ['setting-path'],
203 'customTemplateDir' => ['setting-path'],
204 'extensionsDir' => ['setting-path', NULL, ['mkdir']],
205 'imageUploadDir' => ['setting-path', NULL, ['mkdir']],
206 'uploadDir' => ['setting-path', NULL, ['mkdir', 'restrict']],
207
208 // "setting-url" properties are settings with special filtering
209 // to return normalized URLs.
210 // Option: `noslash` - don't append trailing slash
211 // Option: `rel` - convert to relative URL (if possible)
212 'customCSSURL' => ['setting-url', NULL, ['noslash']],
213 'extensionsURL' => ['setting-url'],
214 'imageUploadURL' => ['setting-url'],
215 'resourceBase' => ['setting-url', 'userFrameworkResourceURL', ['rel']],
216 'userFrameworkResourceURL' => ['setting-url'],
217
218 // "callback" properties are generated on-demand by calling a function.
219 // @todo remove geocodeMethod. As of Feb 2018, $config->geocodeMethod works but gives a deprecation warning.
220 'geocodeMethod' => ['callback', 'CRM_Utils_Geocode', 'getProviderClass'],
221 'defaultCurrencySymbol' => ['callback', 'CRM_Core_BAO_Country', 'getDefaultCurrencySymbol'],
222 ];
223 }
224
225 /**
226 * Get value.
227 *
228 * @param string $k
229 *
230 * @return mixed
231 * @throws \CRM_Core_Exception
232 */
233 public function __get($k) {
234 if (!isset($this->map[$k])) {
235 throw new \CRM_Core_Exception("Cannot read unrecognized property CRM_Core_Config::\${$k}.");
236 }
237 if (isset($this->cache[$k])) {
238 return $this->cache[$k];
239 }
240
241 $type = $this->map[$k][0];
242 $name = isset($this->map[$k][1]) ? $this->map[$k][1] : $k;
243
244 switch ($type) {
245 case 'setting':
246 return $this->getSettings()->get($name);
247
248 // The interpretation of 'path' and 'setting-path' is similar, except
249 // that the latter originates in a stored setting.
250 case 'path':
251 case 'setting-path':
252 // Array(0 => $type, 1 => $setting, 2 => $actions).
253 $value = ($type === 'path')
254 ? Civi::paths()->getVariable($name, 'path')
255 : Civi::paths()->getPath($this->getSettings()->get($name));
256 if ($value) {
257 $value = CRM_Utils_File::addTrailingSlash($value);
258 if (isset($this->map[$k][2]) && in_array('mkdir', $this->map[$k][2])) {
259 if (!is_dir($value) && !CRM_Utils_File::createDir($value, FALSE)) {
260 CRM_Core_Session::setStatus(ts('Failed to make directory (%1) at "%2". Please update the settings or file permissions.', [
261 1 => $k,
262 2 => $value,
263 ]));
264 }
265 }
266 if (isset($this->map[$k][2]) && in_array('restrict', $this->map[$k][2])) {
267 CRM_Utils_File::restrictAccess($value);
268 }
269 }
270 $this->cache[$k] = $value;
271 return $value;
272
273 case 'setting-url':
274 $options = !empty($this->map[$k][2]) ? $this->map[$k][2] : [];
275 $value = $this->getSettings()->get($name);
276 if ($value && !(in_array('noslash', $options))) {
277 $value = CRM_Utils_File::addTrailingSlash($value, '/');
278 }
279 $this->cache[$k] = Civi::paths()->getUrl($value,
280 in_array('rel', $options) ? 'relative' : 'absolute');
281 return $this->cache[$k];
282
283 case 'runtime':
284 return \Civi\Core\Container::getBootService('runtime')->{$name};
285
286 case 'boot-svc':
287 $this->cache[$k] = \Civi\Core\Container::getBootService($name);
288 return $this->cache[$k];
289
290 case 'local':
291 $this->initLocals();
292 return $this->locals[$name];
293
294 case 'user-system':
295 $userSystem = \Civi\Core\Container::getBootService('userSystem');
296 $this->cache[$k] = call_user_func([$userSystem, $name]);
297 return $this->cache[$k];
298
299 case 'service':
300 return \Civi::service($name);
301
302 case 'callback':
303 // Array(0 => $type, 1 => $obj, 2 => $getter, 3 => $setter, 4 => $unsetter).
304 if (!isset($this->map[$k][1], $this->map[$k][2])) {
305 throw new \CRM_Core_Exception("Cannot find getter for property CRM_Core_Config::\${$k}");
306 }
307 return \Civi\Core\Resolver::singleton()->call([$this->map[$k][1], $this->map[$k][2]], [$k]);
308
309 default:
310 throw new \CRM_Core_Exception("Cannot read property CRM_Core_Config::\${$k} ($type)");
311 }
312 }
313
314 /**
315 * Set value.
316 *
317 * @param string $k
318 * @param mixed $v
319 *
320 * @throws \CRM_Core_Exception
321 */
322 public function __set($k, $v) {
323 if (!isset($this->map[$k])) {
324 throw new \CRM_Core_Exception("Cannot set unrecognized property CRM_Core_Config::\${$k}");
325 }
326 unset($this->cache[$k]);
327 $type = $this->map[$k][0];
328
329 switch ($type) {
330 case 'setting':
331 case 'setting-path':
332 case 'setting-url':
333 case 'path':
334 case 'user-system':
335 case 'runtime':
336 case 'callback':
337 case 'boot-svc':
338 // In the past, changes to $config were not persisted automatically.
339 $this->cache[$k] = $v;
340 return;
341
342 case 'local':
343 $this->initLocals();
344 $this->locals[$k] = $v;
345 return;
346
347 default:
348 throw new \CRM_Core_Exception("Cannot set property CRM_Core_Config::\${$k} ($type)");
349 }
350 }
351
352 /**
353 * Is value set.
354 *
355 * @param string $k
356 *
357 * @return bool
358 */
359 public function __isset($k) {
360 return isset($this->map[$k]);
361 }
362
363 /**
364 * Unset value.
365 *
366 * @param string $k
367 *
368 * @throws \CRM_Core_Exception
369 */
370 public function __unset($k) {
371 if (!isset($this->map[$k])) {
372 throw new \CRM_Core_Exception("Cannot unset unrecognized property CRM_Core_Config::\${$k}");
373 }
374 unset($this->cache[$k]);
375 $type = $this->map[$k][0];
376 $name = isset($this->map[$k][1]) ? $this->map[$k][1] : $k;
377
378 switch ($type) {
379 case 'setting':
380 case 'setting-path':
381 case 'setting-url':
382 $this->getSettings()->revert($k);
383 return;
384
385 case 'local':
386 $this->initLocals();
387 $this->locals[$name] = NULL;
388 return;
389
390 case 'callback':
391 // Array(0 => $type, 1 => $obj, 2 => $getter, 3 => $setter, 4 => $unsetter).
392 if (!isset($this->map[$k][1], $this->map[$k][4])) {
393 throw new \CRM_Core_Exception("Cannot find unsetter for property CRM_Core_Config::\${$k}");
394 }
395 \Civi\Core\Resolver::singleton()->call([$this->map[$k][1], $this->map[$k][4]], [$k]);
396 return;
397
398 default:
399 throw new \CRM_Core_Exception("Cannot unset property CRM_Core_Config::\${$k} ($type)");
400 }
401 }
402
403 /**
404 * @return \Civi\Core\SettingsBag
405 */
406 protected function getSettings() {
407 if ($this->settings === NULL) {
408 $this->settings = Civi::settings();
409 }
410 return $this->settings;
411 }
412
413 /**
414 * Initialise local settings.
415 */
416 private function initLocals() {
417 if ($this->locals === NULL) {
418 $this->locals = [
419 'inCiviCRM' => FALSE,
420 'doNotResetCache' => 0,
421 'keyDisable' => FALSE,
422 'initialized' => FALSE,
423 'userFrameworkFrontend' => FALSE,
424 'userPermissionTemp' => NULL,
425 ];
426 }
427 }
428
429 }