5522abda1606af13f9f9a07f84f71be058c67b8f
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.
86 * @param null $package
87 * @param bool $msgCallback
88 * @param bool $contextCallback
89 * @param bool $throwPEAR_Error
90 * @param string $stackClass
95 static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
96 if (self
::$_singleton === NULL) {
97 self
::$_singleton = new CRM_Core_Error('CiviCRM');
99 return self
::$_singleton;
105 function __construct() {
106 parent
::__construct('CiviCRM');
108 $log = CRM_Core_Config
::getLog();
109 $this->setLogger($log);
111 // set up error handling for Pear Error Stack
112 $this->setDefaultCallback(array($this, 'handlePES'));
115 static public function getMessages(&$error, $separator = '<br />') {
116 if (is_a($error, 'CRM_Core_Error')) {
117 $errors = $error->getErrors();
119 foreach ($errors as $e) {
120 $message[] = $e['code'] . ': ' . $e['message'];
122 $message = implode($separator, $message);
129 * Status display function specific to payment processor errors
131 * @param string $separator
133 static function displaySessionError(&$error, $separator = '<br />') {
134 $message = self
::getMessages($error, $separator);
136 $status = ts("Payment Processor Error message") . "{$separator} $message";
137 $session = CRM_Core_Session
::singleton();
138 $session->setStatus($status);
143 * create the main callback method. this method centralizes error processing.
145 * the errors we expect are from the pear modules DB, DB_DataObject
146 * which currently use PEAR::raiseError to notify of error messages.
148 * @param object PEAR_Error
153 public static function handle($pearError) {
155 // setup smarty with config, session and template location.
156 $template = CRM_Core_Smarty
::singleton();
157 $config = CRM_Core_Config
::singleton();
159 if ($config->backtrace
) {
163 // create the error array
165 $error['callback'] = $pearError->getCallback();
166 $error['code'] = $pearError->getCode();
167 $error['message'] = $pearError->getMessage();
168 $error['mode'] = $pearError->getMode();
169 $error['debug_info'] = $pearError->getDebugInfo();
170 $error['type'] = $pearError->getType();
171 $error['user_info'] = $pearError->getUserInfo();
172 $error['to_string'] = $pearError->toString();
173 if (function_exists('mysql_error') &&
176 $mysql_error = mysql_error() . ', ' . mysql_errno();
177 $template->assign_by_ref('mysql_code', $mysql_error);
179 // execute a dummy query to clear error stack
180 mysql_query('select 1');
182 elseif (function_exists('mysqli_error')) {
183 $dao = new CRM_Core_DAO();
185 // we do it this way, since calling the function
186 // getDatabaseConnection could potentially result
187 // in an infinite loop
188 global $_DB_DATAOBJECT;
189 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
190 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
191 $link = $conn->connection
;
193 if (mysqli_error($link)) {
194 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
195 $template->assign_by_ref('mysql_code', $mysql_error);
197 // execute a dummy query to clear error stack
198 mysqli_query($link, 'select 1');
203 $template->assign_by_ref('error', $error);
204 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
205 $template->assign_by_ref('errorDetails', $errorDetails);
207 CRM_Core_Error
::debug_var('Fatal Error Details', $error);
208 CRM_Core_Error
::backtrace('backTrace', TRUE);
210 if ($config->initialized
) {
211 $content = $template->fetch('CRM/common/fatal.tpl');
212 echo CRM_Utils_System
::theme($content);
215 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
216 CRM_Core_Error
::debug(NULL, $error);
218 static $runOnce = FALSE;
226 // this function is used to trap and print errors
227 // during system initialization time. Hence the error
228 // message is quite ugly
229 public static function simpleHandler($pearError) {
231 // create the error array
233 $error['callback'] = $pearError->getCallback();
234 $error['code'] = $pearError->getCode();
235 $error['message'] = $pearError->getMessage();
236 $error['mode'] = $pearError->getMode();
237 $error['debug_info'] = $pearError->getDebugInfo();
238 $error['type'] = $pearError->getType();
239 $error['user_info'] = $pearError->getUserInfo();
240 $error['to_string'] = $pearError->toString();
242 // ensure that debug does not check permissions since we are in bootstrap
243 // mode and need to print a decent message to help the user
244 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
246 // always log the backtrace to a file
247 self
::backtrace('backTrace', TRUE);
253 * Handle errors raised using the PEAR Error Stack.
255 * currently the handler just requests the PES framework
256 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
258 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
260 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
261 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
262 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
265 public static function handlePES($pearError) {
266 return PEAR_ERRORSTACK_PUSH
;
270 * display an error page with an error message describing what happened
272 * @param null $message
277 * @internal param \message $string the error message
278 * @internal param \code $string the error code if any
279 * @internal param \email $string the email address to notify of this situation
285 static function fatal($message = NULL, $code = NULL, $email = NULL) {
287 'message' => $message,
291 if (self
::$modeException) {
293 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
294 CRM_Core_Error
::backtrace('backTrace', TRUE);
296 $details = 'A fatal error was triggered';
298 $details .= ': ' . $message;
300 throw new Exception($details, $code);
304 $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/'));
307 if (php_sapi_name() == "cli") {
308 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
309 debug_print_backtrace();
311 // FIXME: Why doesn't this call abend()?
312 // Difference: abend() will cleanup transaction and (via civiExit) store session state
313 // self::abend(CRM_Core_Error::FATAL_ERROR);
316 $config = CRM_Core_Config
::singleton();
318 if ($config->fatalErrorHandler
&&
319 function_exists($config->fatalErrorHandler
)
321 $name = $config->fatalErrorHandler
;
324 // the call has been successfully handled
326 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
330 // If we are in an ajax callback, format output appropriately
331 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
334 '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>',
336 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
337 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
338 $message .= '<p><em>See console for backtrace</em></p>';
340 CRM_Core_Session
::setStatus($message, ts('Sorry an Error Occured'), 'error');
341 CRM_Core_Transaction
::forceRollbackIfEnabled();
342 CRM_Core_Page_AJAX
::returnJsonResponse($out);
345 if ($config->backtrace
) {
349 $template = CRM_Core_Smarty
::singleton();
350 $template->assign($vars);
352 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
353 CRM_Core_Error
::backtrace('backTrace', TRUE);
354 $content = $template->fetch($config->fatalErrorTemplate
);
355 // JErrorPage exists only in 3.x and not 2.x
357 if ($config->userFramework
== 'Joomla' && class_exists('JErrorPage')) {
358 $error = new Exception($content);
359 JErrorPage
::render($error);
361 else if ($config->userFramework
== 'Joomla' && class_exists('JError')) {
362 JError
::raiseError('CiviCRM-001', $content);
365 echo CRM_Utils_System
::theme($content);
368 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
372 * display an error page with an error message describing what happened
374 * This function is evil -- it largely replicates fatal(). Hopefully the
375 * entire CRM_Core_Error system can be hollowed out and replaced with
376 * something that follows a cleaner separation of concerns.
378 * @param Exception $exception
384 static function handleUnhandledException($exception) {
385 $config = CRM_Core_Config
::singleton();
387 'message' => $exception->getMessage(),
389 'exception' => $exception,
391 if (!$vars['message']) {
392 $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/'));
396 if (php_sapi_name() == "cli") {
397 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
398 print self
::formatTextException($exception);
400 // FIXME: Why doesn't this call abend()?
401 // Difference: abend() will cleanup transaction and (via civiExit) store session state
402 // self::abend(CRM_Core_Error::FATAL_ERROR);
405 // Case B: Custom error handler
406 if ($config->fatalErrorHandler
&&
407 function_exists($config->fatalErrorHandler
)
409 $name = $config->fatalErrorHandler
;
412 // the call has been successfully handled
414 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
418 // Case C: Default error handler
421 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
422 CRM_Core_Error
::backtrace('backTrace', TRUE);
425 $template = CRM_Core_Smarty
::singleton();
426 $template->assign($vars);
427 $content = $template->fetch($config->fatalErrorTemplate
);
428 if ($config->backtrace
) {
429 $content = self
::formatHtmlException($exception) . $content;
431 if ($config->userFramework
== 'Joomla' &&
432 class_exists('JError')
434 JError
::raiseError('CiviCRM-001', $content);
437 echo CRM_Utils_System
::theme($content);
441 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
445 * outputs pre-formatted debug information. Flushes the buffers
446 * so we can interrupt a potential POST/redirect
448 * @param string name of debug section
449 * @param mixed reference to variables that we need a trace of
450 * @param bool should we log or return the output
451 * @param bool whether to generate a HTML-escaped output
452 * @param bool should we check permissions before displaying output
453 * useful when we die during initialization and permissioning
454 * subsystem is not initialized - CRM-13765
456 * @return string the generated output
460 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
461 $error = self
::singleton();
463 if ($variable === NULL) {
468 $out = print_r($variable, TRUE);
471 $out = htmlspecialchars($out);
473 $prefix = "<p>$name</p>";
475 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
479 $prefix = "$name:\n";
481 $out = "{$prefix}$out\n";
485 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
494 * Similar to the function debug. Only difference is
495 * in the formatting of the output.
497 * @param string variable name
498 * @param mixed reference to variables that we need a trace of
499 * @param bool should we use print_r ? (else we use var_dump)
500 * @param bool should we log or return the output
502 * @return string the generated output
508 * @see CRM_Core_Error::debug()
509 * @see CRM_Core_Error::debug_log_message()
511 static function debug_var($variable_name,
517 // check if variable is set
518 if (!isset($variable)) {
519 $out = "\$$variable_name is not set";
523 $out = print_r($variable, TRUE);
524 $out = "\$$variable_name = $out";
530 $dump = ob_get_contents();
532 $out = "\n\$$variable_name = $dump";
534 // reset if it is an array
535 if (is_array($variable)) {
539 return self
::debug_log_message($out, FALSE, $comp);
543 * display the error message on terminal
545 * @param string message to be output
546 * @param bool should we log or return the output
548 * @return string format of the backtrace
554 static function debug_log_message($message, $out = FALSE, $comp = '') {
555 $config = CRM_Core_Config
::singleton();
557 $file_log = self
::createDebugLogger($comp);
558 $file_log->log("$message\n");
559 $str = "<p/><code>$message</code>";
560 if ($out && CRM_Core_Permission
::check('view debug output')) {
565 if ($config->userFrameworkLogging
) {
566 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
567 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG
);
575 * Append to the query log (if enabled)
577 static function debug_query($string) {
578 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
579 if ( CIVICRM_DEBUG_LOG_QUERY
== 'backtrace' ) {
580 CRM_Core_Error
::backtrace( $string, true );
581 } else if ( CIVICRM_DEBUG_LOG_QUERY
) {
582 CRM_Core_Error
::debug_var( 'Query', $string, false, true );
588 * Obtain a reference to the error log
590 * @param string $comp
594 static function createDebugLogger($comp = '') {
595 $config = CRM_Core_Config
::singleton();
601 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn
) . '.log';
603 // Roll log file monthly or if greater than 256M
604 // note that PHP file functions have a limit of 2G and hence
605 // the alternative was introduce
606 if (file_exists($fileName)) {
607 $fileTime = date("Ym", filemtime($fileName));
608 $fileSize = filesize($fileName);
609 if (($fileTime < date('Ym')) ||
610 ($fileSize > 256 * 1024 * 1024) ||
614 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
619 return Log
::singleton('file', $fileName);
622 static function backtrace($msg = 'backTrace', $log = FALSE) {
623 $backTrace = debug_backtrace();
624 $message = self
::formatBacktrace($backTrace);
626 CRM_Core_Error
::debug($msg, $message);
629 CRM_Core_Error
::debug_var($msg, $message);
634 * Render a backtrace array as a string
636 * @param array $backTrace array of stack frames
637 * @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
638 * @param int $maxArgLen maximum number of characters to show from each argument string
639 * @return string printable plain-text
641 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
643 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
644 $message .= sprintf("#%s %s\n", $idx, $trace);
646 $message .= sprintf("#%s {main}\n", 1+
$idx);
651 * Render a backtrace array as an array
653 * @param array $backTrace array of stack frames
654 * @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
655 * @param int $maxArgLen maximum number of characters to show from each argument string
657 * @see debug_backtrace
658 * @see Exception::getTrace()
660 static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
662 foreach ($backTrace as $trace) {
664 $fnName = CRM_Utils_Array
::value('function', $trace);
665 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
667 // do now show args for a few password related functions
668 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
670 foreach ($trace['args'] as $arg) {
671 if (! $showArgs ||
$skipArgs) {
672 $args[] = '(' . gettype($arg) . ')';
675 switch ($type = gettype($arg)) {
677 $args[] = $arg ?
'TRUE' : 'FALSE';
684 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
687 $args[] = '(Array:'.count($arg).')';
690 $args[] = 'Object(' . get_class($arg) . ')';
693 $args[] = 'Resource';
706 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
707 CRM_Utils_Array
::value('line', $trace, ''),
717 * Render an exception as HTML string
719 * @param Exception $e
720 * @return string printable HTML text
722 static function formatHtmlException(Exception
$e) {
725 // Exception metadata
727 // Exception backtrace
728 if ($e instanceof PEAR_Exception
) {
730 while (is_callable(array($ei, 'getCause'))) {
731 if ($ei->getCause() instanceof PEAR_Error
) {
732 $msg .= '<table class="crm-db-error">';
733 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
735 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
736 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
738 $msg .= '</tbody></table>';
740 $ei = $ei->getCause();
742 $msg .= $e->toHtml();
744 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
745 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
751 * Write details of an exception to the log
753 * @param Exception $e
754 * @return string printable plain text
756 static function formatTextException(Exception
$e) {
757 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
760 while (is_callable(array($ei, 'getCause'))) {
761 if ($ei->getCause() instanceof PEAR_Error
) {
762 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
763 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
766 $ei = $ei->getCause();
768 $msg .= self
::formatBacktrace($e->getTrace());
772 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
773 $error = CRM_Core_Error
::singleton();
774 $error->push($code, $level, array($params), $message);
779 * Set a status message in the session, then bounce back to the referrer.
781 * @param string $status The status message to set
787 public static function statusBounce($status, $redirect = NULL, $title = '') {
788 $session = CRM_Core_Session
::singleton();
790 $redirect = $session->readUserContext();
792 $session->setStatus($status, $title);
793 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
794 CRM_Core_Page_AJAX
::returnJsonResponse(array('status' => 'error'));
796 CRM_Utils_System
::redirect($redirect);
800 * Function to reset the error stack
805 public static function reset() {
806 $error = self
::singleton();
807 $error->_errors
= array();
808 $error->_errorsByLevel
= array();
812 * PEAR error-handler which converts errors to exceptions
815 * @throws PEAR_Exception
817 public static function exceptionHandler($pearError) {
818 CRM_Core_Error
::backtrace('backTrace', TRUE);
819 throw new PEAR_Exception($pearError->getMessage(), $pearError);
823 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
825 * @param object $obj The PEAR_ERROR object
826 * @return object $obj
830 public static function nullHandler($obj) {
831 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
832 CRM_Core_Error
::backtrace('backTrace', TRUE);
838 * This function is no longer used by v3 api.
839 * @fixme Some core files call it but it should be re-thought & renamed or removed
841 public static function &createAPIError($msg, $data = NULL) {
842 if (self
::$modeException) {
843 throw new Exception($msg, $data);
848 $values['is_error'] = 1;
849 $values['error_message'] = $msg;
851 $values = array_merge($values, $data);
856 public static function movedSiteError($file) {
857 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
861 echo "We could not write $file. Have you moved your site directory or server?<p>";
862 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
867 * Terminate execution abnormally
869 protected static function abend($code) {
870 // do a hard rollback of any pending transactions
871 // if we've come here, its because of some unexpected PEAR errors
872 CRM_Core_Transaction
::forceRollbackIfEnabled();
873 CRM_Utils_System
::civiExit($code);
876 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
877 if (is_array($error) && !empty($error['is_error'])) {
878 $code = $error['error_message']['code'];
879 if ($code == $type) {
887 $e = new PEAR_ErrorStack('CRM');
888 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');