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
46 public function __construct($message = NULL, $code = 0, Exception
$previous = NULL) {
47 parent
::__construct($message, $code, $previous);
51 class CRM_Core_Error
extends PEAR_ErrorStack
{
54 * status code of various types of errors
57 CONST FATAL_ERROR
= 2;
58 CONST DUPLICATE_CONTACT
= 8001;
59 CONST DUPLICATE_CONTRIBUTION
= 8002;
60 CONST DUPLICATE_PARTICIPANT
= 8003;
63 * We only need one instance of this object. So we use the singleton
64 * pattern and cache the instance in this variable
68 private static $_singleton = NULL;
71 * The logger object for this application
75 private static $_log = NULL;
78 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
81 public static $modeException = NULL;
84 * singleton function used to manage this object.
89 static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
90 if (self
::$_singleton === NULL) {
91 self
::$_singleton = new CRM_Core_Error('CiviCRM');
93 return self
::$_singleton;
99 function __construct() {
100 parent
::__construct('CiviCRM');
102 $log = CRM_Core_Config
::getLog();
103 $this->setLogger($log);
105 // set up error handling for Pear Error Stack
106 $this->setDefaultCallback(array($this, 'handlePES'));
109 static public function getMessages(&$error, $separator = '<br />') {
110 if (is_a($error, 'CRM_Core_Error')) {
111 $errors = $error->getErrors();
113 foreach ($errors as $e) {
114 $message[] = $e['code'] . ': ' . $e['message'];
116 $message = implode($separator, $message);
122 function displaySessionError(&$error, $separator = '<br />') {
123 $message = self
::getMessages($error, $separator);
125 $status = ts("Payment Processor Error message") . "{$separator} $message";
126 $session = CRM_Core_Session
::singleton();
127 $session->setStatus($status);
132 * create the main callback method. this method centralizes error processing.
134 * the errors we expect are from the pear modules DB, DB_DataObject
135 * which currently use PEAR::raiseError to notify of error messages.
137 * @param object PEAR_Error
142 public static function handle($pearError) {
144 // setup smarty with config, session and template location.
145 $template = CRM_Core_Smarty
::singleton();
146 $config = CRM_Core_Config
::singleton();
148 if ($config->backtrace
) {
152 // create the error array
154 $error['callback'] = $pearError->getCallback();
155 $error['code'] = $pearError->getCode();
156 $error['message'] = $pearError->getMessage();
157 $error['mode'] = $pearError->getMode();
158 $error['debug_info'] = $pearError->getDebugInfo();
159 $error['type'] = $pearError->getType();
160 $error['user_info'] = $pearError->getUserInfo();
161 $error['to_string'] = $pearError->toString();
162 if (function_exists('mysql_error') &&
165 $mysql_error = mysql_error() . ', ' . mysql_errno();
166 $template->assign_by_ref('mysql_code', $mysql_error);
168 // execute a dummy query to clear error stack
169 mysql_query('select 1');
171 elseif (function_exists('mysqli_error')) {
172 $dao = new CRM_Core_DAO();
174 // we do it this way, since calling the function
175 // getDatabaseConnection could potentially result
176 // in an infinite loop
177 global $_DB_DATAOBJECT;
178 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
179 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
180 $link = $conn->connection
;
182 if (mysqli_error($link)) {
183 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
184 $template->assign_by_ref('mysql_code', $mysql_error);
186 // execute a dummy query to clear error stack
187 mysqli_query($link, 'select 1');
192 $template->assign_by_ref('error', $error);
193 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
194 $template->assign_by_ref('errorDetails', $errorDetails);
196 CRM_Core_Error
::debug_var('Fatal Error Details', $error);
197 CRM_Core_Error
::backtrace('backTrace', TRUE);
199 if ($config->initialized
) {
200 $content = $template->fetch('CRM/common/fatal.tpl');
201 echo CRM_Utils_System
::theme($content);
204 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
205 CRM_Core_Error
::debug(NULL, $error);
207 static $runOnce = FALSE;
215 // this function is used to trap and print errors
216 // during system initialization time. Hence the error
217 // message is quite ugly
218 public static function simpleHandler($pearError) {
220 // create the error array
222 $error['callback'] = $pearError->getCallback();
223 $error['code'] = $pearError->getCode();
224 $error['message'] = $pearError->getMessage();
225 $error['mode'] = $pearError->getMode();
226 $error['debug_info'] = $pearError->getDebugInfo();
227 $error['type'] = $pearError->getType();
228 $error['user_info'] = $pearError->getUserInfo();
229 $error['to_string'] = $pearError->toString();
231 // ensure that debug does not check permissions since we are in bootstrap
232 // mode and need to print a decent message to help the user
233 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
235 // always log the backtrace to a file
236 self
::backtrace('backTrace', TRUE);
242 * Handle errors raised using the PEAR Error Stack.
244 * currently the handler just requests the PES framework
245 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
247 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
249 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
250 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
251 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
254 public static function handlePES($pearError) {
255 return PEAR_ERRORSTACK_PUSH
;
259 * display an error page with an error message describing what happened
261 * @param string message the error message
262 * @param string code the error code if any
263 * @param string email the email address to notify of this situation
269 static function fatal($message = NULL, $code = NULL, $email = NULL) {
271 'message' => $message,
275 if (self
::$modeException) {
277 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
278 CRM_Core_Error
::backtrace('backTrace', TRUE);
280 $details = 'A fatal error was triggered';
282 $details .= ': ' . $message;
284 throw new Exception($details, $code);
288 $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/'));
291 if (php_sapi_name() == "cli") {
292 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
293 debug_print_backtrace();
295 // FIXME: Why doesn't this call abend()?
296 // Difference: abend() will cleanup transaction and (via civiExit) store session state
297 // self::abend(CRM_Core_Error::FATAL_ERROR);
300 $config = CRM_Core_Config
::singleton();
302 if ($config->fatalErrorHandler
&&
303 function_exists($config->fatalErrorHandler
)
305 $name = $config->fatalErrorHandler
;
308 // the call has been successfully handled
310 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
314 // If we are in an ajax callback, format output appropriately
315 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
318 '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>',
320 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
321 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
322 $message .= '<p><em>See console for backtrace</em></p>';
324 CRM_Core_Session
::setStatus($message, ts('Sorry an Error Occured'), 'error');
325 CRM_Core_Transaction
::forceRollbackIfEnabled();
326 CRM_Core_Page_AJAX
::returnJsonResponse($out);
329 if ($config->backtrace
) {
333 $template = CRM_Core_Smarty
::singleton();
334 $template->assign($vars);
336 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
337 CRM_Core_Error
::backtrace('backTrace', TRUE);
338 $content = $template->fetch($config->fatalErrorTemplate
);
339 // JErrorPage exists only in 3.x and not 2.x
341 if ($config->userFramework
== 'Joomla' && class_exists('JErrorPage')) {
342 $error = new Exception($content);
343 JErrorPage
::render($error);
345 else if ($config->userFramework
== 'Joomla' && class_exists('JError')) {
346 JError
::raiseError('CiviCRM-001', $content);
349 echo CRM_Utils_System
::theme($content);
352 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
356 * display an error page with an error message describing what happened
358 * This function is evil -- it largely replicates fatal(). Hopefully the
359 * entire CRM_Core_Error system can be hollowed out and replaced with
360 * something that follows a cleaner separation of concerns.
362 * @param Exception $exception
368 static function handleUnhandledException($exception) {
369 $config = CRM_Core_Config
::singleton();
371 'message' => $exception->getMessage(),
373 'exception' => $exception,
375 if (!$vars['message']) {
376 $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/'));
380 if (php_sapi_name() == "cli") {
381 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
382 print self
::formatTextException($exception);
384 // FIXME: Why doesn't this call abend()?
385 // Difference: abend() will cleanup transaction and (via civiExit) store session state
386 // self::abend(CRM_Core_Error::FATAL_ERROR);
389 // Case B: Custom error handler
390 if ($config->fatalErrorHandler
&&
391 function_exists($config->fatalErrorHandler
)
393 $name = $config->fatalErrorHandler
;
396 // the call has been successfully handled
398 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
402 // Case C: Default error handler
405 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
406 CRM_Core_Error
::backtrace('backTrace', TRUE);
409 $template = CRM_Core_Smarty
::singleton();
410 $template->assign($vars);
411 $content = $template->fetch($config->fatalErrorTemplate
);
412 if ($config->backtrace
) {
413 $content = self
::formatHtmlException($exception) . $content;
415 if ($config->userFramework
== 'Joomla' &&
416 class_exists('JError')
418 JError
::raiseError('CiviCRM-001', $content);
421 echo CRM_Utils_System
::theme($content);
425 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
429 * outputs pre-formatted debug information. Flushes the buffers
430 * so we can interrupt a potential POST/redirect
432 * @param string name of debug section
433 * @param mixed reference to variables that we need a trace of
434 * @param bool should we log or return the output
435 * @param bool whether to generate a HTML-escaped output
436 * @param bool should we check permissions before displaying output
437 * useful when we die during initialization and permissioning
438 * subsystem is not initialized - CRM-13765
440 * @return string the generated output
444 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
445 $error = self
::singleton();
447 if ($variable === NULL) {
452 $out = print_r($variable, TRUE);
455 $out = htmlspecialchars($out);
457 $prefix = "<p>$name</p>";
459 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
463 $prefix = "$name:\n";
465 $out = "{$prefix}$out\n";
469 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
478 * Similar to the function debug. Only difference is
479 * in the formatting of the output.
481 * @param string variable name
482 * @param mixed reference to variables that we need a trace of
483 * @param bool should we use print_r ? (else we use var_dump)
484 * @param bool should we log or return the output
486 * @return string the generated output
492 * @see CRM_Core_Error::debug()
493 * @see CRM_Core_Error::debug_log_message()
495 static function debug_var($variable_name,
501 // check if variable is set
502 if (!isset($variable)) {
503 $out = "\$$variable_name is not set";
507 $out = print_r($variable, TRUE);
508 $out = "\$$variable_name = $out";
514 $dump = ob_get_contents();
516 $out = "\n\$$variable_name = $dump";
518 // reset if it is an array
519 if (is_array($variable)) {
523 return self
::debug_log_message($out, FALSE, $comp);
527 * display the error message on terminal
529 * @param string message to be output
530 * @param bool should we log or return the output
532 * @return string format of the backtrace
538 static function debug_log_message($message, $out = FALSE, $comp = '') {
539 $config = CRM_Core_Config
::singleton();
541 $file_log = self
::createDebugLogger($comp);
542 $file_log->log("$message\n");
543 $str = "<p/><code>$message</code>";
544 if ($out && CRM_Core_Permission
::check('view debug output')) {
549 if ($config->userFrameworkLogging
) {
550 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
551 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG
);
559 * Append to the query log (if enabled)
561 static function debug_query($string) {
562 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
563 if ( CIVICRM_DEBUG_LOG_QUERY
== 'backtrace' ) {
564 CRM_Core_Error
::backtrace( $string, true );
565 } else if ( CIVICRM_DEBUG_LOG_QUERY
) {
566 CRM_Core_Error
::debug_var( 'Query', $string, false, true );
572 * Obtain a reference to the error log
576 static function createDebugLogger($comp = '') {
577 $config = CRM_Core_Config
::singleton();
583 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn
) . '.log';
585 // Roll log file monthly or if greater than 256M
586 // note that PHP file functions have a limit of 2G and hence
587 // the alternative was introduce
588 if (file_exists($fileName)) {
589 $fileTime = date("Ym", filemtime($fileName));
590 $fileSize = filesize($fileName);
591 if (($fileTime < date('Ym')) ||
592 ($fileSize > 256 * 1024 * 1024) ||
596 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
601 return Log
::singleton('file', $fileName);
604 static function backtrace($msg = 'backTrace', $log = FALSE) {
605 $backTrace = debug_backtrace();
606 $message = self
::formatBacktrace($backTrace);
608 CRM_Core_Error
::debug($msg, $message);
611 CRM_Core_Error
::debug_var($msg, $message);
616 * Render a backtrace array as a string
618 * @param array $backTrace array of stack frames
619 * @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
620 * @param int $maxArgLen maximum number of characters to show from each argument string
621 * @return string printable plain-text
623 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
625 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
626 $message .= sprintf("#%s %s\n", $idx, $trace);
628 $message .= sprintf("#%s {main}\n", 1+
$idx);
633 * Render a backtrace array as an array
635 * @param array $backTrace array of stack frames
636 * @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
637 * @param int $maxArgLen maximum number of characters to show from each argument string
639 * @see debug_backtrace
640 * @see Exception::getTrace()
642 static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
644 foreach ($backTrace as $trace) {
646 $fnName = CRM_Utils_Array
::value('function', $trace);
647 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
649 // do now show args for a few password related functions
650 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
652 foreach ($trace['args'] as $arg) {
653 if (! $showArgs ||
$skipArgs) {
654 $args[] = '(' . gettype($arg) . ')';
657 switch ($type = gettype($arg)) {
659 $args[] = $arg ?
'TRUE' : 'FALSE';
666 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
669 $args[] = '(Array:'.count($arg).')';
672 $args[] = 'Object(' . get_class($arg) . ')';
675 $args[] = 'Resource';
688 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
689 CRM_Utils_Array
::value('line', $trace, ''),
699 * Render an exception as HTML string
701 * @param Exception $e
702 * @return string printable HTML text
704 static function formatHtmlException(Exception
$e) {
707 // Exception metadata
709 // Exception backtrace
710 if ($e instanceof PEAR_Exception
) {
712 while (is_callable(array($ei, 'getCause'))) {
713 if ($ei->getCause() instanceof PEAR_Error
) {
714 $msg .= '<table class="crm-db-error">';
715 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
717 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
718 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
720 $msg .= '</tbody></table>';
722 $ei = $ei->getCause();
724 $msg .= $e->toHtml();
726 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
727 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
733 * Write details of an exception to the log
735 * @param Exception $e
736 * @return string printable plain text
738 static function formatTextException(Exception
$e) {
739 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
742 while (is_callable(array($ei, 'getCause'))) {
743 if ($ei->getCause() instanceof PEAR_Error
) {
744 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
745 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
748 $ei = $ei->getCause();
750 $msg .= self
::formatBacktrace($e->getTrace());
754 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
755 $error = CRM_Core_Error
::singleton();
756 $error->push($code, $level, array($params), $message);
761 * Set a status message in the session, then bounce back to the referrer.
763 * @param string $status The status message to set
769 public static function statusBounce($status, $redirect = NULL, $title = '') {
770 $session = CRM_Core_Session
::singleton();
772 $redirect = $session->readUserContext();
774 $session->setStatus($status, $title);
775 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
776 CRM_Core_Page_AJAX
::returnJsonResponse(array('status' => 'error'));
778 CRM_Utils_System
::redirect($redirect);
782 * Function to reset the error stack
787 public static function reset() {
788 $error = self
::singleton();
789 $error->_errors
= array();
790 $error->_errorsByLevel
= array();
794 * PEAR error-handler which converts errors to exceptions
797 * @throws PEAR_Exception
799 public static function exceptionHandler($pearError) {
800 CRM_Core_Error
::backtrace('backTrace', TRUE);
801 throw new PEAR_Exception($pearError->getMessage(), $pearError);
805 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
807 * @param object $obj The PEAR_ERROR object
808 * @return object $obj
812 public static function nullHandler($obj) {
813 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
814 CRM_Core_Error
::backtrace('backTrace', TRUE);
820 * This function is no longer used by v3 api.
821 * @fixme Some core files call it but it should be re-thought & renamed or removed
823 public static function &createAPIError($msg, $data = NULL) {
824 if (self
::$modeException) {
825 throw new Exception($msg, $data);
830 $values['is_error'] = 1;
831 $values['error_message'] = $msg;
833 $values = array_merge($values, $data);
838 public static function movedSiteError($file) {
839 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
843 echo "We could not write $file. Have you moved your site directory or server?<p>";
844 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
849 * Terminate execution abnormally
851 protected static function abend($code) {
852 // do a hard rollback of any pending transactions
853 // if we've come here, its because of some unexpected PEAR errors
854 CRM_Core_Transaction
::forceRollbackIfEnabled();
855 CRM_Utils_System
::civiExit($code);
858 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
859 if (is_array($error) && !empty($error['is_error'])) {
860 $code = $error['error_message']['code'];
861 if ($code == $type) {
869 $e = new PEAR_ErrorStack('CRM');
870 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');