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