169fe6d18864e535f3c4c75a0d773dd846864122
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);
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 CRM_Core_Error
::debug('Initialization Error', $error);
233 // always log the backtrace to a file
234 self
::backtrace('backTrace', TRUE);
240 * Handle errors raised using the PEAR Error Stack.
242 * currently the handler just requests the PES framework
243 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
245 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
247 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
248 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
249 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
252 public static function handlePES($pearError) {
253 return PEAR_ERRORSTACK_PUSH
;
257 * display an error page with an error message describing what happened
259 * @param string message the error message
260 * @param string code the error code if any
261 * @param string email the email address to notify of this situation
267 static function fatal($message = NULL, $code = NULL, $email = NULL) {
269 'message' => $message,
273 if (self
::$modeException) {
275 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
276 CRM_Core_Error
::backtrace('backTrace', TRUE);
278 $details = 'A fatal error was triggered';
280 $details .= ': ' . $message;
282 throw new Exception($details, $code);
286 $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/'));
289 if (php_sapi_name() == "cli") {
290 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
291 debug_print_backtrace();
293 // FIXME: Why doesn't this call abend()?
294 // Difference: abend() will cleanup transaction and (via civiExit) store session state
295 // self::abend(CRM_Core_Error::FATAL_ERROR);
298 $config = CRM_Core_Config
::singleton();
300 if ($config->fatalErrorHandler
&&
301 function_exists($config->fatalErrorHandler
)
303 $name = $config->fatalErrorHandler
;
306 // the call has been successfully handled
308 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
312 if ($config->backtrace
) {
316 $template = CRM_Core_Smarty
::singleton();
317 $template->assign($vars);
319 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
320 CRM_Core_Error
::backtrace('backTrace', TRUE);
321 $content = $template->fetch($config->fatalErrorTemplate
);
322 if ($config->userFramework
== 'Joomla') {
323 // JErrorPage exists only in 3.1.x
324 // a bit ugly hack, but want this in for 4.4.1
326 if (class_exists('JError') && !class_exists('JErrorPage')) {
327 JError
::raiseError('CiviCRM-001', $content);
330 echo CRM_Utils_System
::theme($content);
334 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
338 * display an error page with an error message describing what happened
340 * This function is evil -- it largely replicates fatal(). Hopefully the
341 * entire CRM_Core_Error system can be hollowed out and replaced with
342 * something that follows a cleaner separation of concerns.
344 * @param Exception $exception
350 static function handleUnhandledException($exception) {
351 $config = CRM_Core_Config
::singleton();
353 'message' => $exception->getMessage(),
355 'exception' => $exception,
357 if (!$vars['message']) {
358 $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/'));
362 if (php_sapi_name() == "cli") {
363 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
364 print self
::formatTextException($exception);
366 // FIXME: Why doesn't this call abend()?
367 // Difference: abend() will cleanup transaction and (via civiExit) store session state
368 // self::abend(CRM_Core_Error::FATAL_ERROR);
371 // Case B: Custom error handler
372 if ($config->fatalErrorHandler
&&
373 function_exists($config->fatalErrorHandler
)
375 $name = $config->fatalErrorHandler
;
378 // the call has been successfully handled
380 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
384 // Case C: Default error handler
387 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
388 CRM_Core_Error
::backtrace('backTrace', TRUE);
391 $template = CRM_Core_Smarty
::singleton();
392 $template->assign($vars);
393 $content = $template->fetch($config->fatalErrorTemplate
);
394 if ($config->backtrace
) {
395 $content = self
::formatHtmlException($exception) . $content;
397 if ($config->userFramework
== 'Joomla' &&
398 class_exists('JError')
400 JError
::raiseError('CiviCRM-001', $content);
403 echo CRM_Utils_System
::theme($content);
407 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
411 * outputs pre-formatted debug information. Flushes the buffers
412 * so we can interrupt a potential POST/redirect
414 * @param string name of debug section
415 * @param mixed reference to variables that we need a trace of
416 * @param bool should we log or return the output
417 * @param bool whether to generate a HTML-escaped output
419 * @return string the generated output
423 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE) {
424 $error = self
::singleton();
426 if ($variable === NULL) {
431 $out = print_r($variable, TRUE);
434 $out = htmlspecialchars($out);
436 $prefix = "<p>$name</p>";
438 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
442 $prefix = "$name:\n";
444 $out = "{$prefix}$out\n";
446 if ($log && CRM_Core_Permission
::check('view debug output')) {
454 * Similar to the function debug. Only difference is
455 * in the formatting of the output.
457 * @param string variable name
458 * @param mixed reference to variables that we need a trace of
459 * @param bool should we use print_r ? (else we use var_dump)
460 * @param bool should we log or return the output
462 * @return string the generated output
468 * @see CRM_Core_Error::debug()
469 * @see CRM_Core_Error::debug_log_message()
471 static function debug_var($variable_name,
477 // check if variable is set
478 if (!isset($variable)) {
479 $out = "\$$variable_name is not set";
483 $out = print_r($variable, TRUE);
484 $out = "\$$variable_name = $out";
490 $dump = ob_get_contents();
492 $out = "\n\$$variable_name = $dump";
494 // reset if it is an array
495 if (is_array($variable)) {
499 return self
::debug_log_message($out, FALSE, $comp);
503 * display the error message on terminal
505 * @param string message to be output
506 * @param bool should we log or return the output
508 * @return string format of the backtrace
514 static function debug_log_message($message, $out = FALSE, $comp = '') {
515 $config = CRM_Core_Config
::singleton();
517 $file_log = self
::createDebugLogger($comp);
518 $file_log->log("$message\n");
519 $str = "<p/><code>$message</code>";
520 if ($out && CRM_Core_Permission
::check('view debug output')) {
525 if ($config->userFrameworkLogging
) {
526 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
527 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG
);
535 * Append to the query log (if enabled)
537 static function debug_query($string) {
538 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
539 if ( CIVICRM_DEBUG_LOG_QUERY
== 'backtrace' ) {
540 CRM_Core_Error
::backtrace( $string, true );
541 } else if ( CIVICRM_DEBUG_LOG_QUERY
) {
542 CRM_Core_Error
::debug_var( 'Query', $string, false, true );
548 * Obtain a reference to the error log
552 static function createDebugLogger($comp = '') {
553 $config = CRM_Core_Config
::singleton();
559 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn
) . '.log';
561 // Roll log file monthly or if greater than 256M
562 // note that PHP file functions have a limit of 2G and hence
563 // the alternative was introduce
564 if (file_exists($fileName)) {
565 $fileTime = date("Ym", filemtime($fileName));
566 $fileSize = filesize($fileName);
567 if (($fileTime < date('Ym')) ||
568 ($fileSize > 256 * 1024 * 1024) ||
572 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
577 return Log
::singleton('file', $fileName);
580 static function backtrace($msg = 'backTrace', $log = FALSE) {
581 $backTrace = debug_backtrace();
582 $message = self
::formatBacktrace($backTrace);
584 CRM_Core_Error
::debug($msg, $message);
587 CRM_Core_Error
::debug_var($msg, $message);
592 * Render a backtrace array as a string
594 * @param array $backTrace array of stack frames
595 * @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
596 * @param int $maxArgLen maximum number of characters to show from each argument string
597 * @return string printable plain-text
598 * @see debug_backtrace
599 * @see Exception::getTrace()
601 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
603 foreach ($backTrace as $idx => $trace) {
605 $fnName = CRM_Utils_Array
::value('function', $trace);
606 $className = array_key_exists('class', $trace) ?
($trace['class'] . $trace['type']) : '';
608 // do now show args for a few password related functions
609 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
611 foreach ($trace['args'] as $arg) {
612 if (! $showArgs ||
$skipArgs) {
613 $args[] = '(' . gettype($arg) . ')';
616 switch ($type = gettype($arg)) {
618 $args[] = $arg ?
'TRUE' : 'FALSE';
625 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
628 $args[] = '(Array:'.count($arg).')';
631 $args[] = 'Object(' . get_class($arg) . ')';
634 $args[] = 'Resource';
646 "#%s %s(%s): %s%s(%s)\n",
648 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
649 CRM_Utils_Array
::value('line', $trace, ''),
655 $message .= sprintf("#%s {main}\n", 1+
$idx);
660 * Render an exception as HTML string
662 * @param Exception $e
663 * @return string printable HTML text
665 static function formatHtmlException(Exception
$e) {
668 // Exception metadata
670 // Exception backtrace
671 if ($e instanceof PEAR_Exception
) {
673 while (is_callable(array($ei, 'getCause'))) {
674 if ($ei->getCause() instanceof PEAR_Error
) {
675 $msg .= '<table class="crm-db-error">';
676 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
678 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
679 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
681 $msg .= '</tbody></table>';
683 $ei = $ei->getCause();
685 $msg .= $e->toHtml();
687 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
688 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
694 * Write details of an exception to the log
696 * @param Exception $e
697 * @return string printable plain text
699 static function formatTextException(Exception
$e) {
700 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
703 while (is_callable(array($ei, 'getCause'))) {
704 if ($ei->getCause() instanceof PEAR_Error
) {
705 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
706 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
709 $ei = $ei->getCause();
711 $msg .= self
::formatBacktrace($e->getTrace());
715 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
716 $error = CRM_Core_Error
::singleton();
717 $error->push($code, $level, array($params), $message);
722 * Set a status message in the session, then bounce back to the referrer.
724 * @param string $status The status message to set
730 public static function statusBounce($status, $redirect = NULL, $title = '') {
731 $session = CRM_Core_Session
::singleton();
733 $redirect = $session->readUserContext();
735 $session->setStatus($status, $title);
736 CRM_Utils_System
::redirect($redirect);
740 * Function to reset the error stack
745 public static function reset() {
746 $error = self
::singleton();
747 $error->_errors
= array();
748 $error->_errorsByLevel
= array();
751 public static function ignoreException($callback = NULL) {
753 $callback = array('CRM_Core_Error', 'nullHandler');
756 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
757 $GLOBALS['_PEAR_default_error_options'] = $callback;
760 public static function exceptionHandler($pearError) {
761 CRM_Core_Error
::backtrace('backTrace', TRUE);
762 throw new PEAR_Exception($pearError->getMessage(), $pearError);
766 * Error handler to quietly catch otherwise fatal smtp transport errors.
768 * @param object $obj The PEAR_ERROR object
770 * @return object $obj
774 public static function nullHandler($obj) {
775 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
776 CRM_Core_Error
::backtrace('backTrace', TRUE);
781 * (Re)set the default callback method
787 public static function setCallback($callback = NULL) {
789 $callback = array('CRM_Core_Error', 'handle');
791 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK
;
792 $GLOBALS['_PEAR_default_error_options'] = $callback;
797 * This function is no longer used by v3 api.
798 * @fixme Some core files call it but it should be re-thought & renamed or removed
800 public static function &createAPIError($msg, $data = NULL) {
801 if (self
::$modeException) {
802 throw new Exception($msg, $data);
807 $values['is_error'] = 1;
808 $values['error_message'] = $msg;
810 $values = array_merge($values, $data);
815 public static function movedSiteError($file) {
816 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
820 echo "We could not write $file. Have you moved your site directory or server?<p>";
821 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
826 * Terminate execution abnormally
828 protected static function abend($code) {
829 // do a hard rollback of any pending transactions
830 // if we've come here, its because of some unexpected PEAR errors
831 CRM_Core_Transaction
::forceRollbackIfEnabled();
832 CRM_Utils_System
::civiExit($code);
835 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
836 if (is_array($error) && CRM_Utils_Array
::value('is_error', $error)) {
837 $code = $error['error_message']['code'];
838 if ($code == $type) {
846 $e = new PEAR_ErrorStack('CRM');
847 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');