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