3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Config handles all the run time configuration changes that the system needs to deal with.
31 * Typically we'll have different values for a user's sandbox, a qa sandbox and a production area.
32 * The default values in general, should reflect production values (minimizes chances of screwing up)
35 * @copyright CiviCRM LLC (c) 2004-2017
38 require_once 'Log.php';
39 require_once 'Mail.php';
41 require_once 'api/api.php';
44 * Class CRM_Core_Config
46 * @property CRM_Utils_System_Base $userSystem
47 * @property CRM_Core_Permission_Base $userPermissionClass
48 * @property array $enableComponents
49 * @property array $languageLimit
50 * @property bool $debug
51 * @property bool $doNotResetCache
52 * @property string $maxFileSize
53 * @property string $defaultCurrency
54 * @property string $defaultCurrencySymbol
55 * @property string $lcMessages
56 * @property string $fieldSeparator
57 * @property string $userFramework
58 * @property string $verpSeparator
59 * @property string $dateFormatFull
60 * @property string $resourceBase
61 * @property string $dsn
62 * @property string $customTemplateDir
63 * @property string $defaultContactCountry
64 * @property string $defaultContactStateProvince
65 * @property string $monetaryDecimalPoint
66 * @property string $monetaryThousandSeparator
68 class CRM_Core_Config
extends CRM_Core_Config_MagicMerge
{
71 * The handle to the log that we are using
74 private static $_log = NULL;
77 * We only need one instance of this object. So we use the singleton
78 * pattern and cache the instance in this variable
80 * @var CRM_Core_Config
82 private static $_singleton = NULL;
85 * The constructor. Sets domain id if defined, otherwise assumes
86 * single instance installation.
88 public function __construct() {
89 parent
::__construct();
93 * Singleton function used to manage this object.
95 * @param bool $loadFromDB
96 * whether to load from the database.
98 * whether to force a reconstruction.
100 * @return CRM_Core_Config
102 public static function &singleton($loadFromDB = TRUE, $force = FALSE) {
103 if (self
::$_singleton === NULL ||
$force) {
104 $GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope
::create(array('CRM_Core_Error', 'handle'));
105 $errorScope = CRM_Core_TemporaryErrorScope
::create(array('CRM_Core_Error', 'simpleHandler'));
107 if (defined('E_DEPRECATED')) {
108 error_reporting(error_reporting() & ~E_DEPRECATED
);
111 self
::$_singleton = new CRM_Core_Config();
112 \Civi\Core\Container
::boot($loadFromDB);
113 if ($loadFromDB && self
::$_singleton->dsn
) {
114 $domain = \CRM_Core_BAO_Domain
::getDomain();
115 \CRM_Core_BAO_ConfigSetting
::applyLocale(\Civi
::settings($domain->id
), $domain->locales
);
119 CRM_Utils_Hook
::config(self
::$_singleton);
120 self
::$_singleton->authenticate();
122 // Extreme backward compat: $config binds to active domain at moment of setup.
123 self
::$_singleton->getSettings();
125 Civi
::service('settings_manager')->useDefaults();
127 self
::$_singleton->handleFirstRun();
130 return self
::$_singleton;
134 * Returns the singleton logger for the application.
140 static public function &getLog() {
141 if (!isset(self
::$_log)) {
142 self
::$_log = Log
::singleton('display');
149 * Retrieve a mailer to send any mail from the application.
153 * @see Civi::service()
155 public static function getMailer() {
156 return Civi
::service('pear_mail');
160 * Deletes the web server writable directories.
163 * 1: clean templates_c, 2: clean upload, 3: clean both
166 public function cleanup($value, $rmdir = TRUE) {
167 $value = (int ) $value;
171 CRM_Utils_File
::cleanDir($this->templateCompileDir
, $rmdir);
172 CRM_Utils_File
::createDir($this->templateCompileDir
);
176 CRM_Utils_File
::cleanDir($this->uploadDir
);
177 CRM_Utils_File
::createDir($this->uploadDir
);
180 // Whether we delete/create or simply preserve directories, we should
181 // certainly make sure the restrictions are enforced.
183 $this->templateCompileDir
,
185 $this->configAndLogDir
,
186 $this->customFileUploadDir
,
188 if ($dir && is_dir($dir)) {
189 CRM_Utils_File
::restrictAccess($dir);
195 * Verify that the needed parameters are not null in the config.
197 * @param CRM_Core_Config $config (reference) the system config object
198 * @param array $required (reference) the parameters that need a value
202 public static function check(&$config, &$required) {
203 foreach ($required as $name) {
204 if (CRM_Utils_System
::isNull($config->$name)) {
212 * Reset the serialized array and recompute.
215 public function reset() {
216 $query = "UPDATE civicrm_domain SET config_backend = null";
217 CRM_Core_DAO
::executeQuery($query);
221 * This method should initialize auth sources.
223 public function authenticate() {
224 // make sure session is always initialised
225 $session = CRM_Core_Session
::singleton();
227 // for logging purposes, pass the userID to the db
228 $userID = $session->get('userID');
230 CRM_Core_DAO
::executeQuery('SET @civicrm_user_id = %1',
231 array(1 => array($userID, 'Integer'))
235 if ($session->get('userID') && !$session->get('authSrc')) {
236 $session->set('authSrc', CRM_Core_Permission
::AUTH_SRC_LOGIN
);
240 CRM_Contact_BAO_Contact_Permission
::initChecksumAuthSrc();
244 * One function to get domain ID.
246 * @param int $domainID
251 public static function domainID($domainID = NULL, $reset = FALSE) {
256 if ($reset ||
empty($domain)) {
257 $domain = defined('CIVICRM_DOMAIN_ID') ? CIVICRM_DOMAIN_ID
: 1;
264 * Function to get environment.
271 public static function environment($env = NULL, $reset = FALSE) {
276 if ($reset ||
empty($environment)) {
277 $environment = Civi
::settings()->get('environment');
280 $environment = 'Production';
286 * Do general cleanup of caches, temp directories and temp tables
289 * @param bool $sessionReset
291 public function cleanupCaches($sessionReset = TRUE) {
292 // cleanup templates_c directory
293 $this->cleanup(1, FALSE);
296 self
::clearDBCache();
297 CRM_Utils_System
::flushCache();
300 $session = CRM_Core_Session
::singleton();
306 * Do general cleanup of module permissions.
308 public function cleanupPermissions() {
309 $module_files = CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles();
310 if ($this->userPermissionClass
->isModulePermissionSupported()) {
311 // Can store permissions -- so do it!
312 $this->userPermissionClass
->upgradePermissions(
313 CRM_Core_Permission
::basicPermissions()
317 // Cannot store permissions -- warn if any modules require them
318 $modules_with_perms = array();
319 foreach ($module_files as $module_file) {
320 $perms = $this->userPermissionClass
->getModulePermissions($module_file['prefix']);
321 if (!empty($perms)) {
322 $modules_with_perms[] = $module_file['prefix'];
325 if (!empty($modules_with_perms)) {
326 CRM_Core_Session
::setStatus(
327 ts('Some modules define permissions, but the CMS cannot store them: %1', array(1 => implode(', ', $modules_with_perms))),
328 ts('Permission Error'),
336 * Flush information about loaded modules.
338 public function clearModuleList() {
339 CRM_Extension_System
::singleton()->getCache()->flush();
340 CRM_Utils_Hook
::singleton(TRUE);
341 CRM_Core_PseudoConstant
::getModuleExtensions(TRUE);
342 CRM_Core_Module
::getAll(TRUE);
348 public static function clearDBCache() {
350 'TRUNCATE TABLE civicrm_acl_cache',
351 'TRUNCATE TABLE civicrm_acl_contact_cache',
352 'TRUNCATE TABLE civicrm_cache',
353 'TRUNCATE TABLE civicrm_prevnext_cache',
354 'UPDATE civicrm_group SET cache_date = NULL',
355 'TRUNCATE TABLE civicrm_group_contact_cache',
356 'TRUNCATE TABLE civicrm_menu',
357 'UPDATE civicrm_setting SET value = NULL WHERE name="navigation" AND contact_id IS NOT NULL',
358 'DELETE FROM civicrm_setting WHERE name="modulePaths"', // CRM-10543
361 foreach ($queries as $query) {
362 CRM_Core_DAO
::executeQuery($query);
365 // also delete all the import and export temp tables
366 self
::clearTempTables();
370 * Clear leftover temporary tables.
372 * This is called on upgrade, during tests and site move, from the cron and via clear caches in the UI.
374 * Currently the UI clear caches does not pass a time interval - which may need review as it does risk
375 * ripping the tables out from underneath a current action. This was considered but
376 * out-of-scope for CRM-16167
378 * @param string|bool $timeInterval
379 * Optional time interval for mysql date function.g '2 day'. This can be used to prevent
380 * tables created recently from being deleted.
382 public static function clearTempTables($timeInterval = FALSE) {
384 $dao = new CRM_Core_DAO();
386 SELECT TABLE_NAME as tableName
387 FROM INFORMATION_SCHEMA.TABLES
388 WHERE TABLE_SCHEMA = %1
390 TABLE_NAME LIKE 'civicrm_import_job_%'
391 OR TABLE_NAME LIKE 'civicrm_export_temp%'
392 OR TABLE_NAME LIKE 'civicrm_task_action_temp%'
393 OR TABLE_NAME LIKE 'civicrm_report_temp%'
397 $query .= " AND CREATE_TIME < DATE_SUB(NOW(), INTERVAL {$timeInterval})";
400 $tableDAO = CRM_Core_DAO
::executeQuery($query, array(1 => array($dao->database(), 'String')));
402 while ($tableDAO->fetch()) {
403 $tables[] = $tableDAO->tableName
;
405 if (!empty($tables)) {
406 $table = implode(',', $tables);
407 // drop leftover temporary tables
408 CRM_Core_DAO
::executeQuery("DROP TABLE $table");
413 * Check if running in upgrade mode.
415 * @param string $path
419 public static function isUpgradeMode($path = NULL) {
420 if (defined('CIVICRM_UPGRADE_ACTIVE')) {
425 // note: do not re-initialize config here, since this function is part of
426 // config initialization itself
428 if (defined('CIVICRM_UF') && CIVICRM_UF
== 'Joomla') {
432 $path = CRM_Utils_Array
::value($urlVar, $_GET);
435 if ($path && preg_match('/^civicrm\/upgrade(\/.*)?$/', $path)) {
439 if ($path && preg_match('/^civicrm\/ajax\/l10n-js/', $path)
440 && !empty($_SERVER['HTTP_REFERER'])
442 $ref = parse_url($_SERVER['HTTP_REFERER']);
444 (!empty($ref['path']) && preg_match('/civicrm\/upgrade/', $ref['path'])) ||
445 (!empty($ref['query']) && preg_match('/civicrm\/upgrade/', urldecode($ref['query'])))
455 * Is back office credit card processing enabled for this site - ie are there any installed processors that support
457 * This function is used for determining whether to show the submit credit card link, not for determining which processors to show, hence
461 public static function isEnabledBackOfficeCreditCardPayments() {
462 return CRM_Financial_BAO_PaymentProcessor
::hasPaymentProcessorSupporting(array('BackOffice'));
468 public function addressSequence() {
469 return CRM_Utils_Address
::sequence(Civi
::settings()->get('address_format'));
475 public function defaultContactCountry() {
476 return CRM_Core_BAO_Country
::defaultContactCountry();
482 public function defaultContactCountryName() {
483 return CRM_Core_BAO_Country
::defaultContactCountryName();
489 * @param string $defaultCurrency
493 public function defaultCurrencySymbol($defaultCurrency = NULL) {
494 return CRM_Core_BAO_Country
::defaultCurrencySymbol($defaultCurrency);
498 * Resets the singleton, so that the next call to CRM_Core_Config::singleton()
499 * reloads completely.
501 * While normally we could call the singleton function with $force = TRUE,
502 * this function addresses a very specific use-case in the CiviCRM installer,
503 * where we cannot yet force a reload, but we want to make sure that the next
504 * call to this object gets a fresh start (ex: to initialize the DAO).
506 public function free() {
507 self
::$_singleton = NULL;
511 * Conditionally fire an event during the first page run.
513 * The install system is currently implemented several times, so it's hard to add
514 * new installation logic. We use a makeshift method to detect the first run.
516 * Situations to test:
518 * - Upgrade from an old version (predating first-run tracker)
519 * - Upgrade from an old version (with first-run tracking)
521 public function handleFirstRun() {
522 // Ordinarily, we prefetch settings en masse and find that the system is already installed.
523 // No extra SQL queries required.
524 if (Civi
::settings()->get('installed')) {
528 // Q: How should this behave during testing?
529 if (defined('CIVICRM_TEST')) {
533 // If schema hasn't been loaded yet, then do nothing. Don't want to interfere
534 // with the existing installers. NOTE: If we change the installer pageflow,
535 // then we may want to modify this behavior.
536 if (!CRM_Core_DAO
::checkTableExists('civicrm_domain')) {
540 // If we're handling an upgrade, then the system has already been used, so this
541 // is not the first run.
542 if (CRM_Core_Config
::isUpgradeMode()) {
545 $dao = CRM_Core_DAO
::executeQuery('SELECT version FROM civicrm_domain');
546 while ($dao->fetch()) {
547 if ($dao->version
&& version_compare($dao->version
, CRM_Utils_System
::version(), '<')) {
552 // The installation flag is stored in civicrm_setting, which is domain-aware. The
553 // flag could have been stored under a different domain.
554 $dao = CRM_Core_DAO
::executeQuery('
555 SELECT domain_id, value FROM civicrm_setting
556 WHERE is_domain = 1 AND name = "installed"
558 while ($dao->fetch()) {
559 $value = unserialize($dao->value
);
560 if (!empty($value)) {
561 Civi
::settings()->set('installed', 1);
566 // OK, this looks new.
567 Civi
::service('dispatcher')->dispatch(\Civi\Core\Event\SystemInstallEvent
::EVENT_NAME
, new \Civi\Core\Event\
SystemInstallEvent());
568 Civi
::settings()->set('installed', 1);