4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.3 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
39 require_once 'PEAR/ErrorStack.php';
40 require_once 'PEAR/Exception.php';
42 require_once 'Log.php';
43 class CRM_Exception
extends PEAR_Exception
{
44 // Redefine the exception so message isn't optional
45 public function __construct($message = NULL, $code = 0, Exception
$previous = NULL) {
46 parent
::__construct($message, $code, $previous);
50 class CRM_Core_Error
extends PEAR_ErrorStack
{
53 * status code of various types of errors
56 CONST FATAL_ERROR
= 2;
57 CONST DUPLICATE_CONTACT
= 8001;
58 CONST DUPLICATE_CONTRIBUTION
= 8002;
59 CONST DUPLICATE_PARTICIPANT
= 8003;
62 * We only need one instance of this object. So we use the singleton
63 * pattern and cache the instance in this variable
67 private static $_singleton = NULL;
70 * The logger object for this application
74 private static $_log = NULL;
77 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
80 public static $modeException = NULL;
83 * singleton function used to manage this object.
88 static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
89 if (self
::$_singleton === NULL) {
90 self
::$_singleton = new CRM_Core_Error('CiviCRM');
92 return self
::$_singleton;
98 function __construct() {
99 parent
::__construct('CiviCRM');
101 $log = CRM_Core_Config
::getLog();
102 $this->setLogger($log);
104 // set up error handling for Pear Error Stack
105 $this->setDefaultCallback(array($this, 'handlePES'));
108 function getMessages(&$error, $separator = '<br />') {
109 if (is_a($error, 'CRM_Core_Error')) {
110 $errors = $error->getErrors();
112 foreach ($errors as $e) {
113 $message[] = $e['code'] . ': ' . $e['message'];
115 $message = implode($separator, $message);
121 function displaySessionError(&$error, $separator = '<br />') {
122 $message = self
::getMessages($error, $separator);
124 $status = ts("Payment Processor Error message") . "{$separator} $message";
125 $session = CRM_Core_Session
::singleton();
126 $session->setStatus($status);
131 * create the main callback method. this method centralizes error processing.
133 * the errors we expect are from the pear modules DB, DB_DataObject
134 * which currently use PEAR::raiseError to notify of error messages.
136 * @param object PEAR_Error
141 public static function handle($pearError) {
143 // setup smarty with config, session and template location.
144 $template = CRM_Core_Smarty
::singleton();
145 $config = CRM_Core_Config
::singleton();
147 if ($config->backtrace
) {
151 // create the error array
153 $error['callback'] = $pearError->getCallback();
154 $error['code'] = $pearError->getCode();
155 $error['message'] = $pearError->getMessage();
156 $error['mode'] = $pearError->getMode();
157 $error['debug_info'] = $pearError->getDebugInfo();
158 $error['type'] = $pearError->getType();
159 $error['user_info'] = $pearError->getUserInfo();
160 $error['to_string'] = $pearError->toString();
161 if (function_exists('mysql_error') &&
164 $mysql_error = mysql_error() . ', ' . mysql_errno();
165 $template->assign_by_ref('mysql_code', $mysql_error);
167 // execute a dummy query to clear error stack
168 mysql_query('select 1');
170 elseif (function_exists('mysqli_error')) {
171 $dao = new CRM_Core_DAO();
173 // we do it this way, since calling the function
174 // getDatabaseConnection could potentially result
175 // in an infinite loop
176 global $_DB_DATAOBJECT;
177 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
178 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
179 $link = $conn->connection
;
181 if (mysqli_error($link)) {
182 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
183 $template->assign_by_ref('mysql_code', $mysql_error);
185 // execute a dummy query to clear error stack
186 mysqli_query($link, 'select 1');
191 $template->assign_by_ref('error', $error);
192 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
193 $template->assign_by_ref('errorDetails', $errorDetails);
195 CRM_Core_Error
::debug_var('Fatal Error Details', $error);
196 CRM_Core_Error
::backtrace('backTrace', TRUE);
198 if ($config->initialized
) {
199 $content = $template->fetch('CRM/common/fatal.tpl');
200 echo CRM_Utils_System
::theme($content);
203 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
204 CRM_Core_Error
::debug(NULL, $error);
210 // this function is used to trap and print errors
211 // during system initialization time. Hence the error
212 // message is quite ugly
213 public static function simpleHandler($pearError) {
215 // create the error array
217 $error['callback'] = $pearError->getCallback();
218 $error['code'] = $pearError->getCode();
219 $error['message'] = $pearError->getMessage();
220 $error['mode'] = $pearError->getMode();
221 $error['debug_info'] = $pearError->getDebugInfo();
222 $error['type'] = $pearError->getType();
223 $error['user_info'] = $pearError->getUserInfo();
224 $error['to_string'] = $pearError->toString();
226 CRM_Core_Error
::debug('Initialization Error', $error);
228 // always log the backtrace to a file
229 self
::backtrace('backTrace', TRUE);
235 * Handle errors raised using the PEAR Error Stack.
237 * currently the handler just requests the PES framework
238 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
240 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
242 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
243 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
244 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
247 public static function handlePES($pearError) {
248 return PEAR_ERRORSTACK_PUSH
;
252 * display an error page with an error message describing what happened
254 * @param string message the error message
255 * @param string code the error code if any
256 * @param string email the email address to notify of this situation
262 static function fatal($message = NULL, $code = NULL, $email = NULL) {
264 'message' => $message,
268 if (self
::$modeException) {
270 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
271 CRM_Core_Error
::backtrace('backTrace', TRUE);
273 $details = 'A fatal error was triggered';
275 $details .= ': ' . $message;
277 throw new Exception($details, $code);
281 $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/'));
284 if (php_sapi_name() == "cli") {
285 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
286 debug_print_backtrace();
288 // FIXME: Why doesn't this call abend()?
289 // Difference: abend() will cleanup transaction and (via civiExit) store session state
290 // self::abend(CRM_Core_Error::FATAL_ERROR);
293 $config = CRM_Core_Config
::singleton();
295 if ($config->fatalErrorHandler
&&
296 function_exists($config->fatalErrorHandler
)
298 $name = $config->fatalErrorHandler
;
301 // the call has been successfully handled
303 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
307 if ($config->backtrace
) {
311 $template = CRM_Core_Smarty
::singleton();
312 $template->assign($vars);
314 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
315 CRM_Core_Error
::backtrace('backTrace', TRUE);
316 $content = $template->fetch($config->fatalErrorTemplate
);
317 if ($config->userFramework
== 'Joomla' && class_exists('JError')) {
318 JError
::raiseError('CiviCRM-001', $content);
321 echo CRM_Utils_System
::theme($content);
324 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
328 * display an error page with an error message describing what happened
330 * This function is evil -- it largely replicates fatal(). Hopefully the
331 * entire CRM_Core_Error system can be hollowed out and replaced with
332 * something that follows a cleaner separation of concerns.
334 * @param Exception $exception
340 static function handleUnhandledException($exception) {
341 $config = CRM_Core_Config
::singleton();
343 'message' => $exception->getMessage(),
345 'exception' => $exception,
347 if (!$vars['message']) {
348 $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/'));
352 if (php_sapi_name() == "cli") {
353 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
354 print self
::formatTextException($exception);
356 // FIXME: Why doesn't this call abend()?
357 // Difference: abend() will cleanup transaction and (via civiExit) store session state
358 // self::abend(CRM_Core_Error::FATAL_ERROR);
361 // Case B: Custom error handler
362 if ($config->fatalErrorHandler
&&
363 function_exists($config->fatalErrorHandler
)
365 $name = $config->fatalErrorHandler
;
368 // the call has been successfully handled
370 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
374 // Case C: Default error handler
377 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
378 CRM_Core_Error
::backtrace('backTrace', TRUE);
381 $template = CRM_Core_Smarty
::singleton();
382 $template->assign($vars);
383 $content = $template->fetch($config->fatalErrorTemplate
);
384 if ($config->backtrace
) {
385 $content = self
::formatHtmlException($exception) . $content;
387 if ($config->userFramework
== 'Joomla' &&
388 class_exists('JError')
390 JError
::raiseError('CiviCRM-001', $content);
393 echo CRM_Utils_System
::theme($content);
397 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
401 * outputs pre-formatted debug information. Flushes the buffers
402 * so we can interrupt a potential POST/redirect
404 * @param string name of debug section
405 * @param mixed reference to variables that we need a trace of
406 * @param bool should we log or return the output
407 * @param bool whether to generate a HTML-escaped output
409 * @return string the generated output
413 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE) {
414 $error = self
::singleton();
416 if ($variable === NULL) {
421 $out = print_r($variable, TRUE);
424 $out = htmlspecialchars($out);
426 $prefix = "<p>$name</p>";
428 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
432 $prefix = "$name:\n";
434 $out = "{$prefix}$out\n";
436 if ($log && CRM_Core_Permission
::check('view debug output')) {
444 * Similar to the function debug. Only difference is
445 * in the formatting of the output.
447 * @param string variable name
448 * @param mixed reference to variables that we need a trace of
449 * @param bool should we use print_r ? (else we use var_dump)
450 * @param bool should we log or return the output
452 * @return string the generated output
458 * @see CRM_Core_Error::debug()
459 * @see CRM_Core_Error::debug_log_message()
461 static function debug_var($variable_name,
467 // check if variable is set
468 if (!isset($variable)) {
469 $out = "\$$variable_name is not set";
473 $out = print_r($variable, TRUE);
474 $out = "\$$variable_name = $out";
480 $dump = ob_get_contents();
482 $out = "\n\$$variable_name = $dump";
484 // reset if it is an array
485 if (is_array($variable)) {
489 return self
::debug_log_message($out, FALSE, $comp);
493 * display the error message on terminal
495 * @param string message to be output
496 * @param bool should we log or return the output
498 * @return string format of the backtrace
504 static function debug_log_message($message, $out = FALSE, $comp = '') {
505 $config = CRM_Core_Config
::singleton();
507 $file_log = self
::createDebugLogger($comp);
508 $file_log->log("$message\n");
509 $str = "<p/><code>$message</code>";
510 if ($out && CRM_Core_Permission
::check('view debug output')) {
515 if ($config->userFrameworkLogging
) {
516 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
517 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG
);
525 * Append to the query log (if enabled)
527 static function debug_query($string) {
528 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
529 if ( CIVICRM_DEBUG_LOG_QUERY
== 'backtrace' ) {
530 CRM_Core_Error
::backtrace( $string, true );
531 } else if ( CIVICRM_DEBUG_LOG_QUERY
) {
532 CRM_Core_Error
::debug_var( 'Query', $string, false, true );
538 * Obtain a reference to the error log
542 static function createDebugLogger($comp = '') {
543 $config = CRM_Core_Config
::singleton();
549 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn
) . '.log';
551 // Roll log file monthly or if greater than 256M
552 // note that PHP file functions have a limit of 2G and hence
553 // the alternative was introduce
554 if (file_exists($fileName)) {
555 $fileTime = date("Ym", filemtime($fileName));
556 $fileSize = filesize($fileName);
557 if (($fileTime < date('Ym')) ||
558 ($fileSize > 256 * 1024 * 1024) ||
562 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
567 return Log
::singleton('file', $fileName);
570 static function backtrace($msg = 'backTrace', $log = FALSE) {
571 $backTrace = debug_backtrace();
572 $message = self
::formatBacktrace($backTrace);
574 CRM_Core_Error
::debug($msg, $message);
577 CRM_Core_Error
::debug_var($msg, $message);
582 * Render a backtrace array as a string
584 * @param array $backTrace array of stack frames
585 * @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
586 * @param int $maxArgLen maximum number of characters to show from each argument string
587 * @return string printable plain-text
588 * @see debug_backtrace
589 * @see Exception::getTrace()
591 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
593 foreach ($backTrace as $idx => $trace) {
595 $fnName = CRM_Utils_Array
::value('function', $trace);
596 $className = array_key_exists('class', $trace) ?
($trace['class'] . $trace['type']) : '';
598 // do now show args for a few password related functions
599 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
601 foreach ($trace['args'] as $arg) {
602 if (! $showArgs ||
$skipArgs) {
603 $args[] = '(' . gettype($arg) . ')';
606 switch ($type = gettype($arg)) {
608 $args[] = $arg ?
'TRUE' : 'FALSE';
615 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
618 $args[] = '(Array:'.count($arg).')';
621 $args[] = 'Object(' . get_class($arg) . ')';
624 $args[] = 'Resource';
636 "#%s %s(%s): %s%s(%s)\n",
638 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
639 CRM_Utils_Array
::value('line', $trace, ''),
645 $message .= sprintf("#%s {main}\n", 1+
$idx);
650 * Render an exception as HTML string
652 * @param Exception $e
653 * @return string printable HTML text
655 static function formatHtmlException(Exception
$e) {
658 // Exception metadata
660 // Exception backtrace
661 if ($e instanceof PEAR_Exception
) {
663 while (is_callable(array($ei, 'getCause'))) {
664 if ($ei->getCause() instanceof PEAR_Error
) {
665 $msg .= '<table class="crm-db-error">';
666 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
668 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
669 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
671 $msg .= '</tbody></table>';
673 $ei = $ei->getCause();
675 $msg .= $e->toHtml();
677 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
678 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
684 * Write details of an exception to the log
686 * @param Exception $e
687 * @return string printable plain text
689 static function formatTextException(Exception
$e) {
690 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
693 while (is_callable(array($ei, 'getCause'))) {
694 if ($ei->getCause() instanceof PEAR_Error
) {
695 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
696 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
699 $ei = $ei->getCause();
701 $msg .= self
::formatBacktrace($e->getTrace());
705 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
706 $error = CRM_Core_Error
::singleton();
707 $error->push($code, $level, array($params), $message);
712 * Set a status message in the session, then bounce back to the referrer.
714 * @param string $status The status message to set
720 public static function statusBounce($status, $redirect = NULL) {
721 $session = CRM_Core_Session
::singleton();
723 $redirect = $session->readUserContext();
725 $session->setStatus($status);
726 CRM_Utils_System
::redirect($redirect);
730 * Function to reset the error stack
735 public static function reset() {
736 $error = self
::singleton();
737 $error->_errors
= array();
738 $error->_errorsByLevel
= array();
741 public static function ignoreException($callback = NULL) {
743 $callback = array('CRM_Core_Error', 'nullHandler');
746 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
747 $GLOBALS['_PEAR_default_error_options'] = $callback;
750 public static function exceptionHandler($pearError) {
751 CRM_Core_Error
::backtrace('backTrace', TRUE);
752 throw new PEAR_Exception($pearError->getMessage(), $pearError);
756 * Error handler to quietly catch otherwise fatal smtp transport errors.
758 * @param object $obj The PEAR_ERROR object
760 * @return object $obj
764 public static function nullHandler($obj) {
765 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
766 CRM_Core_Error
::backtrace('backTrace', TRUE);
771 * (Re)set the default callback method
777 public static function setCallback($callback = NULL) {
779 $callback = array('CRM_Core_Error', 'handle');
781 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
782 $GLOBALS['_PEAR_default_error_options'] = $callback;
787 * This function is no longer used by v3 api.
788 * @fixme Some core files call it but it should be re-thought & renamed or removed
790 public static function &createAPIError($msg, $data = NULL) {
791 if (self
::$modeException) {
792 throw new Exception($msg, $data);
797 $values['is_error'] = 1;
798 $values['error_message'] = $msg;
800 $values = array_merge($values, $data);
805 public static function movedSiteError($file) {
806 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
810 echo "We could not write $file. Have you moved your site directory or server?<p>";
811 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
816 * Terminate execution abnormally
818 protected static function abend($code) {
819 // do a hard rollback of any pending transactions
820 // if we've come here, its because of some unexpected PEAR errors
821 CRM_Core_Transaction
::forceRollbackIfEnabled();
822 CRM_Utils_System
::civiExit($code);
825 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
826 if (is_array($error) && CRM_Utils_Array
::value('is_error', $error)) {
827 $code = $error['error_message']['code'];
828 if ($code == $type) {
836 $e = new PEAR_ErrorStack('CRM');
837 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');