4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.4 |
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';
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 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);
211 // this function is used to trap and print errors
212 // during system initialization time. Hence the error
213 // message is quite ugly
214 public static function simpleHandler($pearError) {
216 // create the error array
218 $error['callback'] = $pearError->getCallback();
219 $error['code'] = $pearError->getCode();
220 $error['message'] = $pearError->getMessage();
221 $error['mode'] = $pearError->getMode();
222 $error['debug_info'] = $pearError->getDebugInfo();
223 $error['type'] = $pearError->getType();
224 $error['user_info'] = $pearError->getUserInfo();
225 $error['to_string'] = $pearError->toString();
227 CRM_Core_Error
::debug('Initialization Error', $error);
229 // always log the backtrace to a file
230 self
::backtrace('backTrace', TRUE);
236 * Handle errors raised using the PEAR Error Stack.
238 * currently the handler just requests the PES framework
239 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
241 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
243 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
244 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
245 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
248 public static function handlePES($pearError) {
249 return PEAR_ERRORSTACK_PUSH
;
253 * display an error page with an error message describing what happened
255 * @param string message the error message
256 * @param string code the error code if any
257 * @param string email the email address to notify of this situation
263 static function fatal($message = NULL, $code = NULL, $email = NULL) {
265 'message' => $message,
269 if (self
::$modeException) {
271 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
272 CRM_Core_Error
::backtrace('backTrace', TRUE);
274 $details = 'A fatal error was triggered';
276 $details .= ': ' . $message;
278 throw new Exception($details, $code);
282 $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/'));
285 if (php_sapi_name() == "cli") {
286 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
287 debug_print_backtrace();
289 // FIXME: Why doesn't this call abend()?
290 // Difference: abend() will cleanup transaction and (via civiExit) store session state
291 // self::abend(CRM_Core_Error::FATAL_ERROR);
294 $config = CRM_Core_Config
::singleton();
296 if ($config->fatalErrorHandler
&&
297 function_exists($config->fatalErrorHandler
)
299 $name = $config->fatalErrorHandler
;
302 // the call has been successfully handled
304 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
308 if ($config->backtrace
) {
312 $template = CRM_Core_Smarty
::singleton();
313 $template->assign($vars);
315 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
316 CRM_Core_Error
::backtrace('backTrace', TRUE);
317 $content = $template->fetch($config->fatalErrorTemplate
);
318 if ($config->userFramework
== 'Joomla' && class_exists('JError')) {
319 JError
::raiseError('CiviCRM-001', $content);
322 echo CRM_Utils_System
::theme($content);
325 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
329 * display an error page with an error message describing what happened
331 * This function is evil -- it largely replicates fatal(). Hopefully the
332 * entire CRM_Core_Error system can be hollowed out and replaced with
333 * something that follows a cleaner separation of concerns.
335 * @param Exception $exception
341 static function handleUnhandledException($exception) {
342 $config = CRM_Core_Config
::singleton();
344 'message' => $exception->getMessage(),
346 'exception' => $exception,
348 if (!$vars['message']) {
349 $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/'));
353 if (php_sapi_name() == "cli") {
354 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
355 print self
::formatTextException($exception);
357 // FIXME: Why doesn't this call abend()?
358 // Difference: abend() will cleanup transaction and (via civiExit) store session state
359 // self::abend(CRM_Core_Error::FATAL_ERROR);
362 // Case B: Custom error handler
363 if ($config->fatalErrorHandler
&&
364 function_exists($config->fatalErrorHandler
)
366 $name = $config->fatalErrorHandler
;
369 // the call has been successfully handled
371 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
375 // Case C: Default error handler
378 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
379 CRM_Core_Error
::backtrace('backTrace', TRUE);
382 $template = CRM_Core_Smarty
::singleton();
383 $template->assign($vars);
384 $content = $template->fetch($config->fatalErrorTemplate
);
385 if ($config->backtrace
) {
386 $content = self
::formatHtmlException($exception) . $content;
388 if ($config->userFramework
== 'Joomla' &&
389 class_exists('JError')
391 JError
::raiseError('CiviCRM-001', $content);
394 echo CRM_Utils_System
::theme($content);
398 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
402 * outputs pre-formatted debug information. Flushes the buffers
403 * so we can interrupt a potential POST/redirect
405 * @param string name of debug section
406 * @param mixed reference to variables that we need a trace of
407 * @param bool should we log or return the output
408 * @param bool whether to generate a HTML-escaped output
410 * @return string the generated output
414 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE) {
415 $error = self
::singleton();
417 if ($variable === NULL) {
422 $out = print_r($variable, TRUE);
425 $out = htmlspecialchars($out);
427 $prefix = "<p>$name</p>";
429 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
433 $prefix = "$name:\n";
435 $out = "{$prefix}$out\n";
437 if ($log && CRM_Core_Permission
::check('view debug output')) {
445 * Similar to the function debug. Only difference is
446 * in the formatting of the output.
448 * @param string variable name
449 * @param mixed reference to variables that we need a trace of
450 * @param bool should we use print_r ? (else we use var_dump)
451 * @param bool should we log or return the output
453 * @return string the generated output
459 * @see CRM_Core_Error::debug()
460 * @see CRM_Core_Error::debug_log_message()
462 static function debug_var($variable_name,
468 // check if variable is set
469 if (!isset($variable)) {
470 $out = "\$$variable_name is not set";
474 $out = print_r($variable, TRUE);
475 $out = "\$$variable_name = $out";
481 $dump = ob_get_contents();
483 $out = "\n\$$variable_name = $dump";
485 // reset if it is an array
486 if (is_array($variable)) {
490 return self
::debug_log_message($out, FALSE, $comp);
494 * display the error message on terminal
496 * @param string message to be output
497 * @param bool should we log or return the output
499 * @return string format of the backtrace
505 static function debug_log_message($message, $out = FALSE, $comp = '') {
506 $config = CRM_Core_Config
::singleton();
508 $file_log = self
::createDebugLogger($comp);
509 $file_log->log("$message\n");
510 $str = "<p/><code>$message</code>";
511 if ($out && CRM_Core_Permission
::check('view debug output')) {
516 if ($config->userFrameworkLogging
) {
517 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
518 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG
);
526 * Append to the query log (if enabled)
528 static function debug_query($string) {
529 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
530 if ( CIVICRM_DEBUG_LOG_QUERY
== 'backtrace' ) {
531 CRM_Core_Error
::backtrace( $string, true );
532 } else if ( CIVICRM_DEBUG_LOG_QUERY
) {
533 CRM_Core_Error
::debug_var( 'Query', $string, false, true );
539 * Obtain a reference to the error log
543 static function createDebugLogger($comp = '') {
544 $config = CRM_Core_Config
::singleton();
550 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn
) . '.log';
552 // Roll log file monthly or if greater than 256M
553 // note that PHP file functions have a limit of 2G and hence
554 // the alternative was introduce
555 if (file_exists($fileName)) {
556 $fileTime = date("Ym", filemtime($fileName));
557 $fileSize = filesize($fileName);
558 if (($fileTime < date('Ym')) ||
559 ($fileSize > 256 * 1024 * 1024) ||
563 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
568 return Log
::singleton('file', $fileName);
571 static function backtrace($msg = 'backTrace', $log = FALSE) {
572 $backTrace = debug_backtrace();
573 $message = self
::formatBacktrace($backTrace);
575 CRM_Core_Error
::debug($msg, $message);
578 CRM_Core_Error
::debug_var($msg, $message);
583 * Render a backtrace array as a string
585 * @param array $backTrace array of stack frames
586 * @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
587 * @param int $maxArgLen maximum number of characters to show from each argument string
588 * @return string printable plain-text
589 * @see debug_backtrace
590 * @see Exception::getTrace()
592 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
594 foreach ($backTrace as $idx => $trace) {
596 $fnName = CRM_Utils_Array
::value('function', $trace);
597 $className = array_key_exists('class', $trace) ?
($trace['class'] . $trace['type']) : '';
599 // do now show args for a few password related functions
600 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
602 foreach ($trace['args'] as $arg) {
603 if (! $showArgs ||
$skipArgs) {
604 $args[] = '(' . gettype($arg) . ')';
607 switch ($type = gettype($arg)) {
609 $args[] = $arg ?
'TRUE' : 'FALSE';
616 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
619 $args[] = '(Array:'.count($arg).')';
622 $args[] = 'Object(' . get_class($arg) . ')';
625 $args[] = 'Resource';
637 "#%s %s(%s): %s%s(%s)\n",
639 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
640 CRM_Utils_Array
::value('line', $trace, ''),
646 $message .= sprintf("#%s {main}\n", 1+
$idx);
651 * Render an exception as HTML string
653 * @param Exception $e
654 * @return string printable HTML text
656 static function formatHtmlException(Exception
$e) {
659 // Exception metadata
661 // Exception backtrace
662 if ($e instanceof PEAR_Exception
) {
664 while (is_callable(array($ei, 'getCause'))) {
665 if ($ei->getCause() instanceof PEAR_Error
) {
666 $msg .= '<table class="crm-db-error">';
667 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
669 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
670 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
672 $msg .= '</tbody></table>';
674 $ei = $ei->getCause();
676 $msg .= $e->toHtml();
678 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
679 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
685 * Write details of an exception to the log
687 * @param Exception $e
688 * @return string printable plain text
690 static function formatTextException(Exception
$e) {
691 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
694 while (is_callable(array($ei, 'getCause'))) {
695 if ($ei->getCause() instanceof PEAR_Error
) {
696 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
697 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
700 $ei = $ei->getCause();
702 $msg .= self
::formatBacktrace($e->getTrace());
706 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
707 $error = CRM_Core_Error
::singleton();
708 $error->push($code, $level, array($params), $message);
713 * Set a status message in the session, then bounce back to the referrer.
715 * @param string $status The status message to set
721 public static function statusBounce($status, $redirect = NULL, $title = '') {
722 $session = CRM_Core_Session
::singleton();
724 $redirect = $session->readUserContext();
726 $session->setStatus($status, $title);
727 CRM_Utils_System
::redirect($redirect);
731 * Function to reset the error stack
736 public static function reset() {
737 $error = self
::singleton();
738 $error->_errors
= array();
739 $error->_errorsByLevel
= array();
742 public static function ignoreException($callback = NULL) {
744 $callback = array('CRM_Core_Error', 'nullHandler');
747 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
748 $GLOBALS['_PEAR_default_error_options'] = $callback;
751 public static function exceptionHandler($pearError) {
752 CRM_Core_Error
::backtrace('backTrace', TRUE);
753 throw new PEAR_Exception($pearError->getMessage(), $pearError);
757 * Error handler to quietly catch otherwise fatal smtp transport errors.
759 * @param object $obj The PEAR_ERROR object
761 * @return object $obj
765 public static function nullHandler($obj) {
766 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
767 CRM_Core_Error
::backtrace('backTrace', TRUE);
772 * (Re)set the default callback method
778 public static function setCallback($callback = NULL) {
780 $callback = array('CRM_Core_Error', 'handle');
782 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
783 $GLOBALS['_PEAR_default_error_options'] = $callback;
788 * This function is no longer used by v3 api.
789 * @fixme Some core files call it but it should be re-thought & renamed or removed
791 public static function &createAPIError($msg, $data = NULL) {
792 if (self
::$modeException) {
793 throw new Exception($msg, $data);
798 $values['is_error'] = 1;
799 $values['error_message'] = $msg;
801 $values = array_merge($values, $data);
806 public static function movedSiteError($file) {
807 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
811 echo "We could not write $file. Have you moved your site directory or server?<p>";
812 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
817 * Terminate execution abnormally
819 protected static function abend($code) {
820 // do a hard rollback of any pending transactions
821 // if we've come here, its because of some unexpected PEAR errors
822 CRM_Core_Transaction
::forceRollbackIfEnabled();
823 CRM_Utils_System
::civiExit($code);
826 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
827 if (is_array($error) && CRM_Utils_Array
::value('is_error', $error)) {
828 $code = $error['error_message']['code'];
829 if ($code == $type) {
837 $e = new PEAR_ErrorStack('CRM');
838 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');