Merge pull request #14301 from eileenmcnaughton/reltest
[civicrm-core.git] / Civi / Core / SettingsManager.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 namespace Civi\Core;
29
30 /**
31 * Class SettingsManager
32 * @package Civi\Core
33 *
34 * The SettingsManager is responsible for tracking settings across various
35 * domains and users.
36 *
37 * Generally, for any given setting, there are three levels where values
38 * can be declared:
39 *
40 * - Mandatory values (which come from a global $civicrm_setting).
41 * - Explicit values (which are chosen by the user and stored in the DB).
42 * - Default values (which come from the settings metadata).
43 *
44 * Note: During the early stages of bootstrap, default values are not be available.
45 * Loading the defaults requires loading metadata from various sources. However,
46 * near the end of bootstrap, one calls SettingsManager::useDefaults() to fetch
47 * and merge the defaults.
48 *
49 * Note: In a typical usage, there will only be one active domain and one
50 * active contact (each having its own bag) within a given request. However,
51 * in some edge-cases, you may need to work with multiple domains/contacts
52 * at the same time.
53 *
54 * Note: The global $civicrm_setting is meant to provide sysadmins with a way
55 * to override settings in `civicrm.settings.php`, but it has traditionally been
56 * possible for extensions to manipulate $civicrm_setting in a hook. If you do
57 * this, please call `useMandatory()` to tell SettingsManager to re-scan
58 * $civicrm_setting.
59 *
60 * @see SettingsManagerTest
61 */
62 class SettingsManager {
63
64 /**
65 * @var \CRM_Utils_Cache_Interface
66 */
67 protected $cache;
68
69 /**
70 * @var array
71 * Array (int $id => SettingsBag $bag).
72 */
73 protected $bagsByDomain = [];
74
75
76 /**
77 * @var array
78 * Array (int $id => SettingsBag $bag).
79 */
80 protected $bagsByContact = [];
81
82 /**
83 * @var array|null
84 * Array(string $entity => array(string $settingName => mixed $value)).
85 * Ex: $mandatory['domain']['uploadDir'].
86 * NULL means "autoload from $civicrm_setting".
87 */
88 protected $mandatory = NULL;
89
90 /**
91 * Whether to use defaults.
92 *
93 * @var bool
94 */
95 protected $useDefaults = FALSE;
96
97 /**
98 * @param \CRM_Utils_Cache_Interface $cache
99 * A semi-durable location to store metadata.
100 */
101 public function __construct($cache) {
102 $this->cache = $cache;
103 }
104
105 /**
106 * Ensure that all defaults values are included with
107 * all current and future bags.
108 *
109 * @return SettingsManager
110 */
111 public function useDefaults() {
112 if (!$this->useDefaults) {
113 $this->useDefaults = TRUE;
114
115 if (!empty($this->bagsByDomain)) {
116 foreach ($this->bagsByDomain as $bag) {
117 /** @var SettingsBag $bag */
118 $bag->loadDefaults($this->getDefaults('domain'));
119 }
120 }
121
122 if (!empty($this->bagsByContact)) {
123 foreach ($this->bagsByContact as $bag) {
124 /** @var SettingsBag $bag */
125 $bag->loadDefaults($this->getDefaults('contact'));
126 }
127 }
128 }
129
130 return $this;
131 }
132
133 /**
134 * Ensure that mandatory values are included with
135 * all current and future bags.
136 *
137 * If you call useMandatory multiple times, it will
138 * re-scan the global $civicrm_setting.
139 *
140 * @return SettingsManager
141 */
142 public function useMandatory() {
143 $this->mandatory = NULL;
144
145 foreach ($this->bagsByDomain as $bag) {
146 /** @var SettingsBag $bag */
147 $bag->loadMandatory($this->getMandatory('domain'));
148 }
149
150 foreach ($this->bagsByContact as $bag) {
151 /** @var SettingsBag $bag */
152 $bag->loadMandatory($this->getMandatory('contact'));
153 }
154
155 return $this;
156 }
157
158 /**
159 * @param int|NULL $domainId
160 * @return SettingsBag
161 */
162 public function getBagByDomain($domainId) {
163 if ($domainId === NULL) {
164 $domainId = \CRM_Core_Config::domainID();
165 }
166
167 if (!isset($this->bagsByDomain[$domainId])) {
168 $this->bagsByDomain[$domainId] = new SettingsBag($domainId, NULL);
169 if (\CRM_Core_Config::singleton()->dsn) {
170 $this->bagsByDomain[$domainId]->loadValues();
171 }
172 $this->bagsByDomain[$domainId]
173 ->loadMandatory($this->getMandatory('domain'))
174 ->loadDefaults($this->getDefaults('domain'));
175 }
176 return $this->bagsByDomain[$domainId];
177 }
178
179 /**
180 * @param int|NULL $domainId
181 * For the default domain, leave $domainID as NULL.
182 * @param int|NULL $contactId
183 * For the default/active user's contact, leave $domainID as NULL.
184 * @return SettingsBag
185 * @throws \CRM_Core_Exception
186 * If there is no contact, then there's no SettingsBag, and we'll throw
187 * an exception.
188 */
189 public function getBagByContact($domainId, $contactId) {
190 if ($domainId === NULL) {
191 $domainId = \CRM_Core_Config::domainID();
192 }
193 if ($contactId === NULL) {
194 $contactId = \CRM_Core_Session::getLoggedInContactID();
195 if (!$contactId) {
196 throw new \CRM_Core_Exception("Cannot access settings subsystem - user or domain is unavailable");
197 }
198 }
199
200 $key = "$domainId:$contactId";
201 if (!isset($this->bagsByContact[$key])) {
202 $this->bagsByContact[$key] = new SettingsBag($domainId, $contactId);
203 if (\CRM_Core_Config::singleton()->dsn) {
204 $this->bagsByContact[$key]->loadValues();
205 }
206 $this->bagsByContact[$key]
207 ->loadDefaults($this->getDefaults('contact'))
208 ->loadMandatory($this->getMandatory('contact'));
209 }
210 return $this->bagsByContact[$key];
211 }
212
213 /**
214 * Determine the default settings.
215 *
216 * @param string $entity
217 * Ex: 'domain' or 'contact'.
218 * @return array
219 * Array(string $settingName => mixed $value).
220 */
221 protected function getDefaults($entity) {
222 if (!$this->useDefaults) {
223 return self::getSystemDefaults($entity);
224 }
225
226 $cacheKey = 'defaults_' . $entity;
227 $defaults = $this->cache->get($cacheKey);
228 if (!is_array($defaults)) {
229 $specs = SettingsMetadata::getMetadata([
230 'is_contact' => ($entity === 'contact' ? 1 : 0),
231 ]);
232 $defaults = [];
233 foreach ($specs as $key => $spec) {
234 $defaults[$key] = \CRM_Utils_Array::value('default', $spec);
235 }
236 \CRM_Utils_Array::extend($defaults, self::getSystemDefaults($entity));
237 $this->cache->set($cacheKey, $defaults);
238 }
239 return $defaults;
240 }
241
242 /**
243 * Get a list of mandatory/overriden settings.
244 *
245 * @param string $entity
246 * Ex: 'domain' or 'contact'.
247 * @return array
248 * Array(string $settingName => mixed $value).
249 */
250 protected function getMandatory($entity) {
251 if ($this->mandatory === NULL) {
252 $this->mandatory = self::parseMandatorySettings(\CRM_Utils_Array::value('civicrm_setting', $GLOBALS));
253 }
254 return $this->mandatory[$entity];
255 }
256
257 /**
258 * Parse mandatory settings.
259 *
260 * In previous versions, settings were broken down into verbose+dynamic group names, e.g.
261 *
262 * $civicrm_settings['Foo Bar Preferences']['foo'] = 'bar';
263 *
264 * We now simplify to two simple groups, 'domain' and 'contact'.
265 *
266 * $civicrm_settings['domain']['foo'] = 'bar';
267 *
268 * However, the old groups are grand-fathered in as aliases.
269 *
270 * @param array $civicrm_setting
271 * Ex: $civicrm_setting['Group Name']['field'] = 'value'.
272 * Group names are an historical quirk; ignore them.
273 * @return array
274 */
275 public static function parseMandatorySettings($civicrm_setting) {
276 $result = [
277 'domain' => [],
278 'contact' => [],
279 ];
280
281 $rewriteGroups = [
282 //\CRM_Core_BAO_Setting::ADDRESS_STANDARDIZATION_PREFERENCES_NAME => 'domain',
283 //\CRM_Core_BAO_Setting::CAMPAIGN_PREFERENCES_NAME => 'domain',
284 //\CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME => 'domain',
285 //\CRM_Core_BAO_Setting::DEVELOPER_PREFERENCES_NAME => 'domain',
286 //\CRM_Core_BAO_Setting::DIRECTORY_PREFERENCES_NAME => 'domain',
287 //\CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME => 'domain',
288 //\CRM_Core_BAO_Setting::LOCALIZATION_PREFERENCES_NAME => 'domain',
289 //\CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME => 'domain',
290 //\CRM_Core_BAO_Setting::MAP_PREFERENCES_NAME => 'domain',
291 //\CRM_Core_BAO_Setting::MEMBER_PREFERENCES_NAME => 'domain',
292 //\CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME => 'domain',
293 //\CRM_Core_BAO_Setting::PERSONAL_PREFERENCES_NAME => 'contact',
294 'Personal Preferences' => 'contact',
295 //\CRM_Core_BAO_Setting::SEARCH_PREFERENCES_NAME => 'domain',
296 //\CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME => 'domain',
297 //\CRM_Core_BAO_Setting::URL_PREFERENCES_NAME => 'domain',
298 'domain' => 'domain',
299 'contact' => 'contact',
300 ];
301
302 if (is_array($civicrm_setting)) {
303 foreach ($civicrm_setting as $oldGroup => $values) {
304 $newGroup = isset($rewriteGroups[$oldGroup]) ? $rewriteGroups[$oldGroup] : 'domain';
305 $result[$newGroup] = array_merge($result[$newGroup], $values);
306 }
307 }
308 return $result;
309 }
310
311 /**
312 * Flush all in-memory and persistent caches related to settings.
313 *
314 * @return SettingsManager
315 */
316 public function flush() {
317 $this->mandatory = NULL;
318
319 $this->cache->flush();
320 // SettingsMetadata; not guaranteed to use same cache.
321 \Civi::cache('settings')->flush();
322
323 foreach ($this->bagsByDomain as $bag) {
324 /** @var SettingsBag $bag */
325 $bag->loadValues();
326 $bag->loadDefaults($this->getDefaults('domain'));
327 $bag->loadMandatory($this->getMandatory('domain'));
328 }
329
330 foreach ($this->bagsByContact as $bag) {
331 /** @var SettingsBag $bag */
332 $bag->loadValues();
333 $bag->loadDefaults($this->getDefaults('contact'));
334 $bag->loadMandatory($this->getMandatory('contact'));
335 }
336
337 return $this;
338 }
339
340 /**
341 * Get a list of critical system defaults.
342 *
343 * The setting system can be modified by extensions, which means that it's not fully available
344 * during bootstrap -- in particular, defaults cannot be loaded. For a very small number of settings,
345 * we must define defaults before the system bootstraps.
346 *
347 * @param string $entity
348 *
349 * @return array
350 */
351 private static function getSystemDefaults($entity) {
352 $defaults = [];
353 switch ($entity) {
354 case 'domain':
355 $defaults = [
356 'installed' => FALSE,
357 'enable_components' => ['CiviEvent', 'CiviContribute', 'CiviMember', 'CiviMail', 'CiviReport', 'CiviPledge'],
358 'customFileUploadDir' => '[civicrm.files]/custom/',
359 'imageUploadDir' => '[civicrm.files]/persist/contribute/',
360 'uploadDir' => '[civicrm.files]/upload/',
361 'imageUploadURL' => '[civicrm.files]/persist/contribute/',
362 'extensionsDir' => '[civicrm.files]/ext/',
363 'extensionsURL' => '[civicrm.files]/ext/',
364 'resourceBase' => '[civicrm.root]/',
365 'userFrameworkResourceURL' => '[civicrm.root]/',
366 ];
367 break;
368
369 }
370 return $defaults;
371 }
372
373 }