Merge pull request #4013 from colemanw/CRM-15215
[civicrm-core.git] / CRM / Core / Config.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 * Config handles all the run time configuration changes that the system needs to deal with.
30 * Typically we'll have different values for a user's sandbox, a qa sandbox and a production area.
31 * The default values in general, should reflect production values (minimizes chances of screwing up)
32 *
33 * @package CRM
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * $Id$
36 *
37 */
38
39require_once 'Log.php';
40require_once 'Mail.php';
41
42require_once 'api/api.php';
43class CRM_Core_Config extends CRM_Core_Config_Variables {
44 ///
45 /// BASE SYSTEM PROPERTIES (CIVICRM.SETTINGS.PHP)
46 ///
47
48 /**
49 * the dsn of the database connection
50 * @var string
51 */
52 public $dsn;
53
54 /**
55 * the name of user framework
56 * @var string
57 */
58 public $userFramework = 'Drupal';
59
60 /**
61 * the name of user framework url variable name
62 * @var string
63 */
64 public $userFrameworkURLVar = 'q';
65
66 /**
67 * the dsn of the database connection for user framework
68 * @var string
69 */
70 public $userFrameworkDSN = NULL;
71
72 /**
73 * The connector module for the CMS/UF
74 *
75 * @var CRM_Util_System_{$uf}
76 */
77 public $userSystem = NULL;
78
79 /**
80 * The root directory where Smarty should store
81 * compiled files
82 * @var string
83 */
84 public $templateCompileDir = './templates_c/en_US/';
85
86 public $configAndLogDir = NULL;
87
88 // END: BASE SYSTEM PROPERTIES (CIVICRM.SETTINGS.PHP)
89
90 ///
91 /// BEGIN HELPER CLASS PROPERTIES
92 ///
93
94 /**
95 * are we initialized and in a proper state
96 * @var string
97 */
98 public $initialized = 0;
99
100 /**
101 * the factory class used to instantiate our DB objects
102 * @var string
103 */
104 private $DAOFactoryClass = 'CRM_Contact_DAO_Factory';
105
106 /**
107 * The handle to the log that we are using
108 * @var object
109 */
110 private static $_log = NULL;
111
112 /**
113 * the handle on the mail handler that we are using
114 * @var object
115 */
72ad6c1b 116 public static $_mail = NULL;
6a488035
TO
117
118 /**
119 * We only need one instance of this object. So we use the singleton
120 * pattern and cache the instance in this variable
121 * @var object
122 * @static
123 */
124 private static $_singleton = NULL;
125
126 /**
127 * component registry object (of CRM_Core_Component type)
128 */
129 public $componentRegistry = NULL;
130
131 ///
132 /// END HELPER CLASS PROPERTIES
133 ///
134
135 ///
136 /// RUNTIME SET CLASS PROPERTIES
137 ///
138
139 /**
140 * to determine wether the call is from cms or civicrm
141 */
142 public $inCiviCRM = FALSE;
143
144 ///
145 /// END: RUNTIME SET CLASS PROPERTIES
146 ///
147
148 /**
149 * Define recaptcha key
150 */
151
152 public $recaptchaPublicKey;
153
154 /**
155 * The constructor. Sets domain id if defined, otherwise assumes
156 * single instance installation.
157 *
158 * @return void
159 * @access private
160 */
161 private function __construct() {
162 }
163
164 /**
165 * Singleton function used to manage this object.
166 *
167 * @param $loadFromDB boolean whether to load from the database
168 * @param $force boolean whether to force a reconstruction
169 *
170 * @return object
171 * @static
172 */
173 static function &singleton($loadFromDB = TRUE, $force = FALSE) {
174 if (self::$_singleton === NULL || $force) {
175 // goto a simple error handler
176 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
177 $GLOBALS['_PEAR_default_error_options'] = array('CRM_Core_Error', 'simpleHandler');
178
179 // lets ensure we set E_DEPRECATED to minimize errors
180 // CRM-6327
181 if (defined('E_DEPRECATED')) {
182 error_reporting(error_reporting() & ~E_DEPRECATED);
183 }
184
185 // first, attempt to get configuration object from cache
186 $cache = CRM_Utils_Cache::singleton();
0e04f44e 187 self::$_singleton = $cache->get('CRM_Core_Config' . CRM_Core_Config::domainID());
6a488035
TO
188 // if not in cache, fire off config construction
189 if (!self::$_singleton) {
190 self::$_singleton = new CRM_Core_Config;
191 self::$_singleton->_initialize($loadFromDB);
192
193 //initialize variables. for gencode we cannot load from the
194 //db since the db might not be initialized
195 if ($loadFromDB) {
2ba175b6
DL
196 // initialize stuff from the settings file
197 self::$_singleton->setCoreVariables();
198
6a488035
TO
199 self::$_singleton->_initVariables();
200
2ba175b6
DL
201 // I dont think we need to do this twice
202 // however just keeping this commented for now in 4.4
203 // in case we hit any issues - CRM-13064
204 // We can safely delete this once we release 4.4.4
205 // self::$_singleton->setCoreVariables();
6a488035 206 }
0e04f44e 207 $cache->set('CRM_Core_Config' . CRM_Core_Config::domainID(), self::$_singleton);
6a488035
TO
208 }
209 else {
210 // we retrieve the object from memcache, so we now initialize the objects
211 self::$_singleton->_initialize($loadFromDB);
212
213 // CRM-9803, NYSS-4822
214 // this causes various settings to be reset and hence we should
215 // only use the config object that we retrived from memcache
216 }
217
218 self::$_singleton->initialized = 1;
219
220 if (isset(self::$_singleton->customPHPPathDir) &&
221 self::$_singleton->customPHPPathDir
222 ) {
223 $include_path = self::$_singleton->customPHPPathDir . PATH_SEPARATOR . get_include_path();
224 set_include_path($include_path);
225 }
226
227 // set the callback at the very very end, to avoid an infinite loop
228 // set the error callback
229 CRM_Core_Error::setCallback();
230
231 // call the hook so other modules can add to the config
232 // again doing this at the very very end
233 CRM_Utils_Hook::config(self::$_singleton);
234
235 // make sure session is always initialised
236 $session = CRM_Core_Session::singleton();
237
238 // for logging purposes, pass the userID to the db
239 $userID = $session->get('userID');
240 if ($userID) {
241 CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
242 array(1 => array($userID, 'Integer'))
243 );
244 }
e8f14831
DS
245
246 // initialize authentication source
247 self::$_singleton->initAuthSrc();
6a488035
TO
248 }
249 return self::$_singleton;
250 }
251
252
253 private function _setUserFrameworkConfig($userFramework) {
254
255 $this->userFrameworkClass = 'CRM_Utils_System_' . $userFramework;
256 $this->userHookClass = 'CRM_Utils_Hook_' . $userFramework;
257 $userPermissionClass = 'CRM_Core_Permission_' . $userFramework;
258 $this->userPermissionClass = new $userPermissionClass();
259
260 $class = $this->userFrameworkClass;
261 // redundant with _initVariables
262 $userSystem = $this->userSystem = new $class();
263
264 if ($userFramework == 'Joomla') {
265 $this->userFrameworkURLVar = 'task';
266 }
267
268 if (defined('CIVICRM_UF_BASEURL')) {
269 $this->userFrameworkBaseURL = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/');
270
271 //format url for language negotiation, CRM-7803
272 $this->userFrameworkBaseURL = CRM_Utils_System::languageNegotiationURL($this->userFrameworkBaseURL);
273
274 if (CRM_Utils_System::isSSL()) {
275 $this->userFrameworkBaseURL = str_replace('http://', 'https://',
276 $this->userFrameworkBaseURL
277 );
278 }
279 }
280
281 if (defined('CIVICRM_UF_DSN')) {
282 $this->userFrameworkDSN = CIVICRM_UF_DSN;
283 }
284
285 // this is dynamically figured out in the civicrm.settings.php file
286 if (defined('CIVICRM_CLEANURL')) {
287 $this->cleanURL = CIVICRM_CLEANURL;
288 }
289 else {
290 $this->cleanURL = 0;
291 }
292
293 $this->userFrameworkVersion = $userSystem->getVersion();
294
295 if ($userFramework == 'Joomla') {
296 global $mainframe;
297 $dbprefix = $mainframe ? $mainframe->getCfg('dbprefix') : 'jos_';
298 $this->userFrameworkUsersTableName = $dbprefix . 'users';
299 }
300 elseif ($userFramework == 'WordPress') {
301 global $wpdb;
302 $dbprefix = $wpdb ? $wpdb->prefix : '';
303 $this->userFrameworkUsersTableName = $dbprefix . 'users';
304 }
305 }
306
307 /**
308 * Initializes the entire application.
309 * Reads constants defined in civicrm.settings.php and
310 * stores them in config properties.
311 *
312 * @return void
313 * @access public
314 */
315 private function _initialize($loadFromDB = TRUE) {
316
317 // following variables should be set in CiviCRM settings and
318 // as crucial ones, are defined upon initialisation
319 // instead of in CRM_Core_Config_Defaults
320 if (defined('CIVICRM_DSN')) {
321 $this->dsn = CIVICRM_DSN;
322 }
323 elseif ($loadFromDB) {
324 // bypass when calling from gencode
325 echo 'You need to define CIVICRM_DSN in civicrm.settings.php';
326 exit();
327 }
328
329 if (defined('CIVICRM_TEMPLATE_COMPILEDIR')) {
330 $this->templateCompileDir = CRM_Utils_File::addTrailingSlash(CIVICRM_TEMPLATE_COMPILEDIR);
331
332 // also make sure we create the config directory within this directory
333 // the below statement will create both the templates directory and the config and log directory
b597d0b1
DL
334 $this->configAndLogDir =
335 CRM_Utils_File::baseFilePath($this->templateCompileDir) .
336 'ConfigAndLog' . DIRECTORY_SEPARATOR;
6a488035 337 CRM_Utils_File::createDir($this->configAndLogDir);
fea6131e 338 CRM_Utils_File::restrictAccess($this->configAndLogDir);
6a488035
TO
339
340 // we're automatically prefixing compiled templates directories with country/language code
341 global $tsLocale;
342 if (!empty($tsLocale)) {
343 $this->templateCompileDir .= CRM_Utils_File::addTrailingSlash($tsLocale);
344 }
345 elseif (!empty($this->lcMessages)) {
346 $this->templateCompileDir .= CRM_Utils_File::addTrailingSlash($this->lcMessages);
347 }
348
349 CRM_Utils_File::createDir($this->templateCompileDir);
fea6131e 350 CRM_Utils_File::restrictAccess($this->templateCompileDir);
6a488035
TO
351 }
352 elseif ($loadFromDB) {
353 echo 'You need to define CIVICRM_TEMPLATE_COMPILEDIR in civicrm.settings.php';
354 exit();
355 }
356
357 $this->_initDAO();
358
359 if (defined('CIVICRM_UF')) {
360 $this->userFramework = CIVICRM_UF;
361 $this->_setUserFrameworkConfig($this->userFramework);
362 }
363 else {
364 echo 'You need to define CIVICRM_UF in civicrm.settings.php';
365 exit();
366 }
367
368 // also initialize the logger
369 self::$_log = Log::singleton('display');
370
371 // initialize component registry early to avoid "race"
372 // between CRM_Core_Config and CRM_Core_Component (they
373 // are co-dependant)
374 $this->componentRegistry = new CRM_Core_Component();
375 }
376
377 /**
378 * initialize the DataObject framework
379 *
380 * @return void
381 * @access private
382 */
383 private function _initDAO() {
384 CRM_Core_DAO::init($this->dsn);
385
386 $factoryClass = $this->DAOFactoryClass;
387 require_once str_replace('_', DIRECTORY_SEPARATOR, $factoryClass) . '.php';
388 CRM_Core_DAO::setFactory(new $factoryClass());
389 if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
390 CRM_Core_DAO::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
391 }
392 }
393
394 /**
395 * returns the singleton logger for the application
396 *
397 * @param
398 * @access private
399 *
400 * @return object
401 */
402 static public function &getLog() {
403 if (!isset(self::$_log)) {
404 self::$_log = Log::singleton('display');
405 }
406
407 return self::$_log;
408 }
409
410 /**
411 * initialize the config variables
412 *
413 * @return void
414 * @access private
415 */
416 private function _initVariables() {
417 // retrieve serialised settings
418 $variables = array();
419 CRM_Core_BAO_ConfigSetting::retrieve($variables);
420
421 // if settings are not available, go down the full path
422 if (empty($variables)) {
423 // Step 1. get system variables with their hardcoded defaults
424 $variables = get_object_vars($this);
425
426 // Step 2. get default values (with settings file overrides if
427 // available - handled in CRM_Core_Config_Defaults)
428 CRM_Core_Config_Defaults::setValues($variables);
429
430 // retrieve directory and url preferences also
431 CRM_Core_BAO_Setting::retrieveDirectoryAndURLPreferences($variables);
432
433 // add component specific settings
434 $this->componentRegistry->addConfig($this);
435
436 // serialise settings
437 $settings = $variables;
438 CRM_Core_BAO_ConfigSetting::add($settings);
439 }
440
441 $urlArray = array('userFrameworkResourceURL', 'imageUploadURL');
442 $dirArray = array('uploadDir', 'customFileUploadDir');
443
444 foreach ($variables as $key => $value) {
445 if (in_array($key, $urlArray)) {
446 $value = CRM_Utils_File::addTrailingSlash($value, '/');
447 }
448 elseif (in_array($key, $dirArray)) {
449 if ($value) {
450 $value = CRM_Utils_File::addTrailingSlash($value);
451 }
452 if (empty($value) || (CRM_Utils_File::createDir($value, FALSE) === FALSE)) {
453 // seems like we could not create the directories
454 // settings might have changed, lets suppress a message for now
455 // so we can make some more progress and let the user fix their settings
456 // for now we assign it to a know value
457 // CRM-4949
458 $value = $this->templateCompileDir;
459 $url = CRM_Utils_System::url('civicrm/admin/setting/path', 'reset=1');
460 CRM_Core_Session::setStatus(ts('%1 has an incorrect directory path. Please go to the <a href="%2">path setting page</a> and correct it.', array(
461 1 => $key,
462 2 => $url
463 )), ts('Check Settings'), 'alert');
464 }
465 }
466 elseif ($key == 'lcMessages') {
467 // reset the templateCompileDir to locale-specific and make sure it exists
468 if (substr($this->templateCompileDir, -1 * strlen($value) - 1, -1) != $value) {
469 $this->templateCompileDir .= CRM_Utils_File::addTrailingSlash($value);
470 CRM_Utils_File::createDir($this->templateCompileDir);
fea6131e 471 CRM_Utils_File::restrictAccess($this->templateCompileDir);
6a488035
TO
472 }
473 }
474
475 $this->$key = $value;
476 }
477
478 if ($this->userFrameworkResourceURL) {
479 // we need to do this here so all blocks also load from an ssl server
480 if (CRM_Utils_System::isSSL()) {
481 CRM_Utils_System::mapConfigToSSL();
482 }
483 $rrb = parse_url($this->userFrameworkResourceURL);
484 // dont use absolute path if resources are stored on a different server
485 // CRM-4642
486 $this->resourceBase = $this->userFrameworkResourceURL;
487 if (isset($_SERVER['HTTP_HOST']) &&
488 isset($rrb['host'])
489 ) {
490 $this->resourceBase = ($rrb['host'] == $_SERVER['HTTP_HOST']) ? $rrb['path'] : $this->userFrameworkResourceURL;
491 }
492 }
493
494 if (!$this->customFileUploadDir) {
495 $this->customFileUploadDir = $this->uploadDir;
496 }
497
498 if ($this->geoProvider) {
499 $this->geocodeMethod = 'CRM_Utils_Geocode_' . $this->geoProvider;
500 }
501 elseif ($this->mapProvider) {
502 $this->geocodeMethod = 'CRM_Utils_Geocode_' . $this->mapProvider;
503 }
504
505 require_once (str_replace('_', DIRECTORY_SEPARATOR, $this->userFrameworkClass) . '.php');
506 $class = $this->userFrameworkClass;
507 // redundant with _setUserFrameworkConfig
508 $this->userSystem = new $class();
509 }
510
511 /**
3713d69c 512 * Retrieve a mailer to send any mail from the application
6a488035
TO
513 *
514 * @param boolean $persist open a persistent smtp connection, should speed up mailings
6a488035 515 * @access private
6a488035
TO
516 * @return object
517 */
518 static function &getMailer($persist = FALSE) {
519 if (!isset(self::$_mail)) {
520 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
521 'mailing_backend'
522 );
523
524 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB ||
525 (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL)
526 ) {
72ad6c1b 527 self::$_mail = self::_createMailer('CRM_Mailing_BAO_Spool', array());
6a488035
TO
528 }
529 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
530 if ($mailingInfo['smtpServer'] == '' || !$mailingInfo['smtpServer']) {
9327d839
DL
531 CRM_Core_Error::debug_log_message(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
532 CRM_Core_Error::fatal(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
6a488035
TO
533 }
534
535 $params['host'] = $mailingInfo['smtpServer'] ? $mailingInfo['smtpServer'] : 'localhost';
536 $params['port'] = $mailingInfo['smtpPort'] ? $mailingInfo['smtpPort'] : 25;
537
538 if ($mailingInfo['smtpAuth']) {
539 $params['username'] = $mailingInfo['smtpUsername'];
540 $params['password'] = CRM_Utils_Crypt::decrypt($mailingInfo['smtpPassword']);
541 $params['auth'] = TRUE;
542 }
543 else {
544 $params['auth'] = FALSE;
545 }
546
547 // set the localhost value, CRM-3153
548 $params['localhost'] = CRM_Utils_Array::value('SERVER_NAME', $_SERVER, 'localhost');
549
550 // also set the timeout value, lets set it to 30 seconds
551 // CRM-7510
552 $params['timeout'] = 30;
553
554 // CRM-9349
555 $params['persist'] = $persist;
556
72ad6c1b 557 self::$_mail = self::_createMailer('smtp', $params);
6a488035
TO
558 }
559 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
560 if ($mailingInfo['sendmail_path'] == '' ||
561 !$mailingInfo['sendmail_path']
562 ) {
9327d839
DL
563 CRM_Core_Error::debug_log_message(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
564 CRM_Core_Error::fatal(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
6a488035
TO
565 }
566 $params['sendmail_path'] = $mailingInfo['sendmail_path'];
567 $params['sendmail_args'] = $mailingInfo['sendmail_args'];
568
72ad6c1b 569 self::$_mail = self::_createMailer('sendmail', $params);
6a488035
TO
570 }
571 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
72ad6c1b 572 self::$_mail = self::_createMailer('mail', array());
6a488035
TO
573 }
574 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MOCK) {
72ad6c1b 575 self::$_mail = self::_createMailer('mock', array());
6a488035 576 }
72ad6c1b 577 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED) {
9327d839
DL
578 CRM_Core_Error::debug_log_message(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
579 CRM_Core_Session::setStatus(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
4b7d50ce 580 }
c8e4bea0 581 else {
9327d839
DL
582 CRM_Core_Error::debug_log_message(ts('There is no valid SMTP server Setting Or SendMail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
583 CRM_Core_Session::setStatus(ts('There is no valid SMTP server Setting Or sendMail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
4b7d50ce 584 CRM_Core_Error::debug_var('mailing_info', $mailingInfo);
6a488035
TO
585 }
586 }
587 return self::$_mail;
588 }
589
72ad6c1b 590 /**
c8e4bea0
TO
591 * Create a new instance of a PEAR Mail driver
592 *
72ad6c1b
TO
593 * @param string $driver 'CRM_Mailing_BAO_Spool' or a name suitable for Mail::factory()
594 * @param array $params
c8e4bea0 595 * @return Mail (More specifically, a class which implements the "send()" function)
72ad6c1b
TO
596 */
597 public static function _createMailer($driver, $params) {
598 if ($driver == 'CRM_Mailing_BAO_Spool') {
599 $mailer = new CRM_Mailing_BAO_Spool($params);
c8e4bea0
TO
600 }
601 else {
72ad6c1b
TO
602 $mailer = Mail::factory($driver, $params);
603 }
91bff2e5 604 CRM_Utils_Hook::alterMail($mailer, $driver, $params);
72ad6c1b
TO
605 return $mailer;
606 }
607
6a488035
TO
608 /**
609 * delete the web server writable directories
610 *
611 * @param int $value 1 - clean templates_c, 2 - clean upload, 3 - clean both
612 *
613 * @access public
614 *
615 * @return void
616 */
617 public function cleanup($value, $rmdir = TRUE) {
618 $value = (int ) $value;
619
620 if ($value & 1) {
621 // clean templates_c
622 CRM_Utils_File::cleanDir($this->templateCompileDir, $rmdir);
623 CRM_Utils_File::createDir($this->templateCompileDir);
624 }
625 if ($value & 2) {
626 // clean upload dir
627 CRM_Utils_File::cleanDir($this->uploadDir);
628 CRM_Utils_File::createDir($this->uploadDir);
fea6131e
TO
629 }
630
631 // Whether we delete/create or simply preserve directories, we should
632 // certainly make sure the restrictions are enforced.
a738c74c 633 foreach (array($this->templateCompileDir, $this->uploadDir, $this->configAndLogDir, $this->customFileUploadDir) as $dir) {
fea6131e
TO
634 if ($dir && is_dir($dir)) {
635 CRM_Utils_File::restrictAccess($dir);
636 }
6a488035
TO
637 }
638 }
639
640 /**
641 * verify that the needed parameters are not null in the config
642 *
643 * @param CRM_Core_Config (reference ) the system config object
644 * @param array (reference ) the parameters that need a value
645 *
646 * @return boolean
647 * @static
648 * @access public
649 */
650 static function check(&$config, &$required) {
651 foreach ($required as $name) {
652 if (CRM_Utils_System::isNull($config->$name)) {
653 return FALSE;
654 }
655 }
656 return TRUE;
657 }
658
659 /**
660 * reset the serialized array and recompute
661 * use with care
662 */
663 function reset() {
664 $query = "UPDATE civicrm_domain SET config_backend = null";
665 CRM_Core_DAO::executeQuery($query);
666 }
667
e8f14831
DS
668 // This method should initialize auth sources
669 function initAuthSrc() {
670 $session = CRM_Core_Session::singleton();
671 if ($session->get('userID') && !$session->get('authSrc')) {
672 $session->set('authSrc', CRM_Core_Permission::AUTH_SRC_LOGIN);
673 }
674
675 // checksum source
676 CRM_Contact_BAO_Contact_Permission::initChecksumAuthSrc();
677 }
678
6a488035
TO
679 /**
680 * one function to get domain ID
681 */
682 static function domainID($domainID = NULL, $reset = FALSE) {
683 static $domain;
684 if ($domainID) {
685 $domain = $domainID;
686 }
687 if ($reset || empty($domain)) {
688 $domain = defined('CIVICRM_DOMAIN_ID') ? CIVICRM_DOMAIN_ID : 1;
689 }
690
691 return $domain;
692 }
693
694 /**
695 * do general cleanup of caches, temp directories and temp tables
696 * CRM-8739
697 */
698 function cleanupCaches($sessionReset = TRUE) {
699 // cleanup templates_c directory
700 $this->cleanup(1, FALSE);
701
702 // clear db caching
703 self::clearDBCache();
704
705 if ($sessionReset) {
706 $session = CRM_Core_Session::singleton();
707 $session->reset(2);
708 }
709 }
710
711 /**
712 * Do general cleanup of module permissions.
713 */
714 function cleanupPermissions() {
715 $module_files = CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles();
7fccad46
TO
716 if ($this->userPermissionClass->isModulePermissionSupported()) {
717 // Can store permissions -- so do it!
0d8fc497
TO
718 $this->userPermissionClass->upgradePermissions(
719 CRM_Core_Permission::basicPermissions()
720 );
7fccad46
TO
721 } else {
722 // Cannot store permissions -- warn if any modules require them
723 $modules_with_perms = array();
724 foreach ($module_files as $module_file) {
725 $perms = $this->userPermissionClass->getModulePermissions($module_file['prefix']);
726 if (!empty($perms)) {
727 $modules_with_perms[] = $module_file['prefix'];
728 }
729 }
730 if (!empty($modules_with_perms)) {
731 CRM_Core_Session::setStatus(
10a5be27 732 ts('Some modules define permissions, but the CMS cannot store them: %1', array(1 => implode(', ', $modules_with_perms))),
7fccad46
TO
733 ts('Permission Error'),
734 'error'
735 );
736 }
6a488035
TO
737 }
738 }
739
740 /**
741 * Flush information about loaded modules
742 */
743 function clearModuleList() {
744 CRM_Extension_System::singleton()->getCache()->flush();
745 CRM_Utils_Hook::singleton(TRUE);
746 CRM_Core_PseudoConstant::getModuleExtensions(TRUE);
747 CRM_Core_Module::getAll(TRUE);
748 }
749
750 /**
751 * clear db cache
752 */
753 public static function clearDBCache() {
754 $queries = array(
755 'TRUNCATE TABLE civicrm_acl_cache',
756 'TRUNCATE TABLE civicrm_acl_contact_cache',
757 'TRUNCATE TABLE civicrm_cache',
758 'TRUNCATE TABLE civicrm_prevnext_cache',
759 'UPDATE civicrm_group SET cache_date = NULL',
760 'TRUNCATE TABLE civicrm_group_contact_cache',
761 'TRUNCATE TABLE civicrm_menu',
762 'UPDATE civicrm_setting SET value = NULL WHERE name="navigation" AND contact_id IS NOT NULL',
763 'DELETE FROM civicrm_setting WHERE name="modulePaths"', // CRM-10543
764 );
765
766 foreach ($queries as $query) {
767 CRM_Core_DAO::executeQuery($query);
768 }
769
770 // also delete all the import and export temp tables
771 self::clearTempTables();
772 }
773
774 /**
775 * clear leftover temporary tables
776 */
777 public static function clearTempTables() {
778 // CRM-5645
779 $dao = CRM_Core_DAO::executeQuery("SELECT DATABASE();");
780 $query = "
781SELECT TABLE_NAME as tableName
782FROM INFORMATION_SCHEMA.TABLES
783WHERE TABLE_SCHEMA = %1
a3243ca9 784AND
785 ( TABLE_NAME LIKE 'civicrm_import_job_%'
786 OR TABLE_NAME LIKE 'civicrm_export_temp%'
787 OR TABLE_NAME LIKE 'civicrm_task_action_temp%'
788 OR TABLE_NAME LIKE 'civicrm_report_temp%'
789 )
6a488035
TO
790";
791
792 $params = array(1 => array($dao->database(), 'String'));
793 $tableDAO = CRM_Core_DAO::executeQuery($query, $params);
794 $tables = array();
795 while ($tableDAO->fetch()) {
796 $tables[] = $tableDAO->tableName;
797 }
798 if (!empty($tables)) {
799 $table = implode(',', $tables);
800 // drop leftover temporary tables
801 CRM_Core_DAO::executeQuery("DROP TABLE $table");
802 }
803 }
804
805 /**
806 * function to check if running in upgrade mode
807 */
808 static function isUpgradeMode($path = NULL) {
809 if (defined('CIVICRM_UPGRADE_ACTIVE')) {
810 return TRUE;
811 }
812
813 if (!$path) {
814 // note: do not re-initialize config here, since this function is part of
815 // config initialization itself
816 $urlVar = 'q';
817 if (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') {
818 $urlVar = 'task';
819 }
820
821 $path = CRM_Utils_Array::value($urlVar, $_GET);
822 }
823
824 if ($path && preg_match('/^civicrm\/upgrade(\/.*)?$/', $path)) {
825 return TRUE;
826 }
827
828 return FALSE;
829 }
830
831 /**
832 * Wrapper function to allow unit tests to switch user framework on the fly
833 */
834 public function setUserFramework($userFramework = NULL) {
835 $this->userFramework = $userFramework;
836 $this->_setUserFrameworkConfig($userFramework);
837 }
838}
839// end CRM_Core_Config
840