4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
30 * Start of the Error framework. We should check out and inherit from
31 * PEAR_ErrorStack and use that framework
34 * @copyright CiviCRM LLC (c) 2004-2014
39 require_once 'PEAR/ErrorStack.php';
40 require_once 'PEAR/Exception.php';
41 require_once 'CRM/Core/Exception.php';
43 require_once 'Log.php';
44 class CRM_Exception
extends PEAR_Exception
{
45 // Redefine the exception so message isn't optional
47 * Supported signatures:
48 * - PEAR_Exception(string $message);
49 * - PEAR_Exception(string $message, int $code);
50 * - PEAR_Exception(string $message, Exception $cause);
51 * - PEAR_Exception(string $message, Exception $cause, int $code);
52 * - PEAR_Exception(string $message, PEAR_Error $cause);
53 * - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
54 * - PEAR_Exception(string $message, array $causes);
55 * - PEAR_Exception(string $message, array $causes, int $code);
56 * @param string exception message
57 * @param int|Exception|PEAR_Error|array|null exception cause
58 * @param int|null exception code or null
60 public function __construct($message = NULL, $code = 0, Exception
$previous = NULL) {
61 parent
::__construct($message, $code, $previous);
65 class CRM_Core_Error
extends PEAR_ErrorStack
{
68 * status code of various types of errors
71 CONST FATAL_ERROR
= 2;
72 CONST DUPLICATE_CONTACT
= 8001;
73 CONST DUPLICATE_CONTRIBUTION
= 8002;
74 CONST DUPLICATE_PARTICIPANT
= 8003;
77 * We only need one instance of this object. So we use the singleton
78 * pattern and cache the instance in this variable
82 private static $_singleton = NULL;
85 * The logger object for this application
89 private static $_log = NULL;
92 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
95 public static $modeException = NULL;
98 * singleton function used to manage this object.
100 * @param null $package
101 * @param bool $msgCallback
102 * @param bool $contextCallback
103 * @param bool $throwPEAR_Error
104 * @param string $stackClass
109 static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
110 if (self
::$_singleton === NULL) {
111 self
::$_singleton = new CRM_Core_Error('CiviCRM');
113 return self
::$_singleton;
119 function __construct() {
120 parent
::__construct('CiviCRM');
122 $log = CRM_Core_Config
::getLog();
123 $this->setLogger($log);
125 // set up error handling for Pear Error Stack
126 $this->setDefaultCallback(array($this, 'handlePES'));
129 static public function getMessages(&$error, $separator = '<br />') {
130 if (is_a($error, 'CRM_Core_Error')) {
131 $errors = $error->getErrors();
133 foreach ($errors as $e) {
134 $message[] = $e['code'] . ': ' . $e['message'];
136 $message = implode($separator, $message);
143 * Status display function specific to payment processor errors
145 * @param string $separator
147 static function displaySessionError(&$error, $separator = '<br />') {
148 $message = self
::getMessages($error, $separator);
150 $status = ts("Payment Processor Error message") . "{$separator} $message";
151 $session = CRM_Core_Session
::singleton();
152 $session->setStatus($status);
157 * create the main callback method. this method centralizes error processing.
159 * the errors we expect are from the pear modules DB, DB_DataObject
160 * which currently use PEAR::raiseError to notify of error messages.
162 * @param object PEAR_Error
167 public static function handle($pearError) {
169 // setup smarty with config, session and template location.
170 $template = CRM_Core_Smarty
::singleton();
171 $config = CRM_Core_Config
::singleton();
173 if ($config->backtrace
) {
177 // create the error array
179 $error['callback'] = $pearError->getCallback();
180 $error['code'] = $pearError->getCode();
181 $error['message'] = $pearError->getMessage();
182 $error['mode'] = $pearError->getMode();
183 $error['debug_info'] = $pearError->getDebugInfo();
184 $error['type'] = $pearError->getType();
185 $error['user_info'] = $pearError->getUserInfo();
186 $error['to_string'] = $pearError->toString();
187 if (function_exists('mysql_error') &&
190 $mysql_error = mysql_error() . ', ' . mysql_errno();
191 $template->assign_by_ref('mysql_code', $mysql_error);
193 // execute a dummy query to clear error stack
194 mysql_query('select 1');
196 elseif (function_exists('mysqli_error')) {
197 $dao = new CRM_Core_DAO();
199 // we do it this way, since calling the function
200 // getDatabaseConnection could potentially result
201 // in an infinite loop
202 global $_DB_DATAOBJECT;
203 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
204 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
205 $link = $conn->connection
;
207 if (mysqli_error($link)) {
208 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
209 $template->assign_by_ref('mysql_code', $mysql_error);
211 // execute a dummy query to clear error stack
212 mysqli_query($link, 'select 1');
217 $template->assign_by_ref('error', $error);
218 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
219 $template->assign_by_ref('errorDetails', $errorDetails);
221 CRM_Core_Error
::debug_var('Fatal Error Details', $error);
222 CRM_Core_Error
::backtrace('backTrace', TRUE);
224 if ($config->initialized
) {
225 $content = $template->fetch('CRM/common/fatal.tpl');
226 echo CRM_Utils_System
::theme($content);
229 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
230 CRM_Core_Error
::debug(NULL, $error);
232 static $runOnce = FALSE;
240 // this function is used to trap and print errors
241 // during system initialization time. Hence the error
242 // message is quite ugly
243 public static function simpleHandler($pearError) {
245 // create the error array
247 $error['callback'] = $pearError->getCallback();
248 $error['code'] = $pearError->getCode();
249 $error['message'] = $pearError->getMessage();
250 $error['mode'] = $pearError->getMode();
251 $error['debug_info'] = $pearError->getDebugInfo();
252 $error['type'] = $pearError->getType();
253 $error['user_info'] = $pearError->getUserInfo();
254 $error['to_string'] = $pearError->toString();
256 // ensure that debug does not check permissions since we are in bootstrap
257 // mode and need to print a decent message to help the user
258 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
260 // always log the backtrace to a file
261 self
::backtrace('backTrace', TRUE);
267 * Handle errors raised using the PEAR Error Stack.
269 * currently the handler just requests the PES framework
270 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
272 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
274 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
275 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
276 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
279 public static function handlePES($pearError) {
280 return PEAR_ERRORSTACK_PUSH
;
284 * display an error page with an error message describing what happened
286 * @param null $message
291 * @internal param \message $string the error message
292 * @internal param \code $string the error code if any
293 * @internal param \email $string the email address to notify of this situation
299 static function fatal($message = NULL, $code = NULL, $email = NULL) {
301 'message' => $message,
305 if (self
::$modeException) {
307 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
308 CRM_Core_Error
::backtrace('backTrace', TRUE);
310 $details = 'A fatal error was triggered';
312 $details .= ': ' . $message;
314 throw new Exception($details, $code);
318 $message = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/'));
321 if (php_sapi_name() == "cli") {
322 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
323 debug_print_backtrace();
325 // FIXME: Why doesn't this call abend()?
326 // Difference: abend() will cleanup transaction and (via civiExit) store session state
327 // self::abend(CRM_Core_Error::FATAL_ERROR);
330 $config = CRM_Core_Config
::singleton();
332 if ($config->fatalErrorHandler
&&
333 function_exists($config->fatalErrorHandler
)
335 $name = $config->fatalErrorHandler
;
338 // the call has been successfully handled
340 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
344 // If we are in an ajax callback, format output appropriately
345 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
348 'content' => '<div class="messages status no-popup"><div class="icon inform-icon"></div>' . ts('Sorry but we are not able to provide this at the moment.') . '</div>',
350 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
351 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
352 $message .= '<p><em>See console for backtrace</em></p>';
354 CRM_Core_Session
::setStatus($message, ts('Sorry an Error Occured'), 'error');
355 CRM_Core_Transaction
::forceRollbackIfEnabled();
356 CRM_Core_Page_AJAX
::returnJsonResponse($out);
359 if ($config->backtrace
) {
363 $template = CRM_Core_Smarty
::singleton();
364 $template->assign($vars);
366 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
367 CRM_Core_Error
::backtrace('backTrace', TRUE);
368 $content = $template->fetch($config->fatalErrorTemplate
);
369 // JErrorPage exists only in 3.x and not 2.x
371 if ($config->userFramework
== 'Joomla' && class_exists('JErrorPage')) {
372 $error = new Exception($content);
373 JErrorPage
::render($error);
375 else if ($config->userFramework
== 'Joomla' && class_exists('JError')) {
376 JError
::raiseError('CiviCRM-001', $content);
379 echo CRM_Utils_System
::theme($content);
382 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
386 * display an error page with an error message describing what happened
388 * This function is evil -- it largely replicates fatal(). Hopefully the
389 * entire CRM_Core_Error system can be hollowed out and replaced with
390 * something that follows a cleaner separation of concerns.
392 * @param Exception $exception
398 static function handleUnhandledException($exception) {
399 $config = CRM_Core_Config
::singleton();
401 'message' => $exception->getMessage(),
403 'exception' => $exception,
405 if (!$vars['message']) {
406 $vars['message'] = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/'));
410 if (php_sapi_name() == "cli") {
411 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
412 print self
::formatTextException($exception);
414 // FIXME: Why doesn't this call abend()?
415 // Difference: abend() will cleanup transaction and (via civiExit) store session state
416 // self::abend(CRM_Core_Error::FATAL_ERROR);
419 // Case B: Custom error handler
420 if ($config->fatalErrorHandler
&&
421 function_exists($config->fatalErrorHandler
)
423 $name = $config->fatalErrorHandler
;
426 // the call has been successfully handled
428 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
432 // Case C: Default error handler
435 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
436 CRM_Core_Error
::backtrace('backTrace', TRUE);
439 $template = CRM_Core_Smarty
::singleton();
440 $template->assign($vars);
441 $content = $template->fetch($config->fatalErrorTemplate
);
442 if ($config->backtrace
) {
443 $content = self
::formatHtmlException($exception) . $content;
445 if ($config->userFramework
== 'Joomla' &&
446 class_exists('JError')
448 JError
::raiseError('CiviCRM-001', $content);
451 echo CRM_Utils_System
::theme($content);
455 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
459 * outputs pre-formatted debug information. Flushes the buffers
460 * so we can interrupt a potential POST/redirect
462 * @param string name of debug section
463 * @param mixed reference to variables that we need a trace of
464 * @param bool should we log or return the output
465 * @param bool whether to generate a HTML-escaped output
466 * @param bool should we check permissions before displaying output
467 * useful when we die during initialization and permissioning
468 * subsystem is not initialized - CRM-13765
470 * @return string the generated output
474 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
475 $error = self
::singleton();
477 if ($variable === NULL) {
482 $out = print_r($variable, TRUE);
485 $out = htmlspecialchars($out);
487 $prefix = "<p>$name</p>";
489 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
493 $prefix = "$name:\n";
495 $out = "{$prefix}$out\n";
499 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
508 * Similar to the function debug. Only difference is
509 * in the formatting of the output.
511 * @param $variable_name
515 * @param string $comp variable name
517 * @internal param \reference $mixed to variables that we need a trace of
518 * @internal param \should $bool we use print_r ? (else we use var_dump)
519 * @internal param \should $bool we log or return the output
521 * @return string the generated output
527 * @see CRM_Core_Error::debug()
528 * @see CRM_Core_Error::debug_log_message()
530 static function debug_var($variable_name,
536 // check if variable is set
537 if (!isset($variable)) {
538 $out = "\$$variable_name is not set";
542 $out = print_r($variable, TRUE);
543 $out = "\$$variable_name = $out";
549 $dump = ob_get_contents();
551 $out = "\n\$$variable_name = $dump";
553 // reset if it is an array
554 if (is_array($variable)) {
558 return self
::debug_log_message($out, FALSE, $comp);
562 * display the error message on terminal
565 * @param bool $out should we log or return the output
567 * @param string $comp message to be output
568 * @return string format of the backtrace
574 static function debug_log_message($message, $out = FALSE, $comp = '') {
575 $config = CRM_Core_Config
::singleton();
577 $file_log = self
::createDebugLogger($comp);
578 $file_log->log("$message\n");
579 $str = "<p/><code>$message</code>";
580 if ($out && CRM_Core_Permission
::check('view debug output')) {
585 if ($config->userFrameworkLogging
) {
586 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
587 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG
);
595 * Append to the query log (if enabled)
597 static function debug_query($string) {
598 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
599 if ( CIVICRM_DEBUG_LOG_QUERY
== 'backtrace' ) {
600 CRM_Core_Error
::backtrace( $string, true );
601 } else if ( CIVICRM_DEBUG_LOG_QUERY
) {
602 CRM_Core_Error
::debug_var( 'Query', $string, false, true );
608 * Obtain a reference to the error log
610 * @param string $comp
614 static function createDebugLogger($comp = '') {
615 $config = CRM_Core_Config
::singleton();
621 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn
) . '.log';
623 // Roll log file monthly or if greater than 256M
624 // note that PHP file functions have a limit of 2G and hence
625 // the alternative was introduce
626 if (file_exists($fileName)) {
627 $fileTime = date("Ym", filemtime($fileName));
628 $fileSize = filesize($fileName);
629 if (($fileTime < date('Ym')) ||
630 ($fileSize > 256 * 1024 * 1024) ||
634 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
639 return Log
::singleton('file', $fileName);
642 static function backtrace($msg = 'backTrace', $log = FALSE) {
643 $backTrace = debug_backtrace();
644 $message = self
::formatBacktrace($backTrace);
646 CRM_Core_Error
::debug($msg, $message);
649 CRM_Core_Error
::debug_var($msg, $message);
654 * Render a backtrace array as a string
656 * @param array $backTrace array of stack frames
657 * @param boolean $showArgs TRUE if we should try to display content of function arguments (which could be sensitive); FALSE to display only the type of each function argument
658 * @param int $maxArgLen maximum number of characters to show from each argument string
659 * @return string printable plain-text
661 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
663 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
664 $message .= sprintf("#%s %s\n", $idx, $trace);
666 $message .= sprintf("#%s {main}\n", 1+
$idx);
671 * Render a backtrace array as an array
673 * @param array $backTrace array of stack frames
674 * @param boolean $showArgs TRUE if we should try to display content of function arguments (which could be sensitive); FALSE to display only the type of each function argument
675 * @param int $maxArgLen maximum number of characters to show from each argument string
677 * @see debug_backtrace
678 * @see Exception::getTrace()
680 static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
682 foreach ($backTrace as $trace) {
684 $fnName = CRM_Utils_Array
::value('function', $trace);
685 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
687 // do now show args for a few password related functions
688 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
690 foreach ($trace['args'] as $arg) {
691 if (! $showArgs ||
$skipArgs) {
692 $args[] = '(' . gettype($arg) . ')';
695 switch ($type = gettype($arg)) {
697 $args[] = $arg ?
'TRUE' : 'FALSE';
704 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
707 $args[] = '(Array:'.count($arg).')';
710 $args[] = 'Object(' . get_class($arg) . ')';
713 $args[] = 'Resource';
726 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
727 CRM_Utils_Array
::value('line', $trace, ''),
737 * Render an exception as HTML string
739 * @param Exception $e
740 * @return string printable HTML text
742 static function formatHtmlException(Exception
$e) {
745 // Exception metadata
747 // Exception backtrace
748 if ($e instanceof PEAR_Exception
) {
750 while (is_callable(array($ei, 'getCause'))) {
751 if ($ei->getCause() instanceof PEAR_Error
) {
752 $msg .= '<table class="crm-db-error">';
753 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
755 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
756 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
758 $msg .= '</tbody></table>';
760 $ei = $ei->getCause();
762 $msg .= $e->toHtml();
764 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
765 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
771 * Write details of an exception to the log
773 * @param Exception $e
774 * @return string printable plain text
776 static function formatTextException(Exception
$e) {
777 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
780 while (is_callable(array($ei, 'getCause'))) {
781 if ($ei->getCause() instanceof PEAR_Error
) {
782 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
783 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
786 $ei = $ei->getCause();
788 $msg .= self
::formatBacktrace($e->getTrace());
792 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
793 $error = CRM_Core_Error
::singleton();
794 $error->push($code, $level, array($params), $message);
799 * Set a status message in the session, then bounce back to the referrer.
801 * @param string $status The status message to set
803 * @param null $redirect
804 * @param string $title
809 public static function statusBounce($status, $redirect = NULL, $title = '') {
810 $session = CRM_Core_Session
::singleton();
812 $redirect = $session->readUserContext();
814 $session->setStatus($status, $title);
815 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
816 CRM_Core_Page_AJAX
::returnJsonResponse(array('status' => 'error'));
818 CRM_Utils_System
::redirect($redirect);
822 * Function to reset the error stack
827 public static function reset() {
828 $error = self
::singleton();
829 $error->_errors
= array();
830 $error->_errorsByLevel
= array();
834 * PEAR error-handler which converts errors to exceptions
837 * @throws PEAR_Exception
839 public static function exceptionHandler($pearError) {
840 CRM_Core_Error
::backtrace('backTrace', TRUE);
841 throw new PEAR_Exception($pearError->getMessage(), $pearError);
845 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
847 * @param object $obj The PEAR_ERROR object
848 * @return object $obj
852 public static function nullHandler($obj) {
853 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
854 CRM_Core_Error
::backtrace('backTrace', TRUE);
860 * This function is no longer used by v3 api.
861 * @fixme Some core files call it but it should be re-thought & renamed or removed
863 public static function &createAPIError($msg, $data = NULL) {
864 if (self
::$modeException) {
865 throw new Exception($msg, $data);
870 $values['is_error'] = 1;
871 $values['error_message'] = $msg;
873 $values = array_merge($values, $data);
878 public static function movedSiteError($file) {
879 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
883 echo "We could not write $file. Have you moved your site directory or server?<p>";
884 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
889 * Terminate execution abnormally
891 protected static function abend($code) {
892 // do a hard rollback of any pending transactions
893 // if we've come here, its because of some unexpected PEAR errors
894 CRM_Core_Transaction
::forceRollbackIfEnabled();
895 CRM_Utils_System
::civiExit($code);
898 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
899 if (is_array($error) && !empty($error['is_error'])) {
900 $code = $error['error_message']['code'];
901 if ($code == $type) {
909 $e = new PEAR_ErrorStack('CRM');
910 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');