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