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