3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Start of the Error framework. We should check out and inherit from
30 * PEAR_ErrorStack and use that framework
33 * @copyright CiviCRM LLC (c) 2004-2018
36 require_once 'PEAR/ErrorStack.php';
37 require_once 'PEAR/Exception.php';
38 require_once 'CRM/Core/Exception.php';
40 require_once 'Log.php';
45 class CRM_Exception
extends PEAR_Exception
{
47 * Redefine the exception so message isn't optional.
49 * Supported signatures:
50 * - PEAR_Exception(string $message);
51 * - PEAR_Exception(string $message, int $code);
52 * - PEAR_Exception(string $message, Exception $cause);
53 * - PEAR_Exception(string $message, Exception $cause, int $code);
54 * - PEAR_Exception(string $message, PEAR_Error $cause);
55 * - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
56 * - PEAR_Exception(string $message, array $causes);
57 * - PEAR_Exception(string $message, array $causes, int $code);
59 * @param string $message exception message
61 * @param Exception $previous
63 public function __construct($message = NULL, $code = 0, Exception
$previous = NULL) {
64 parent
::__construct($message, $code, $previous);
70 * Class CRM_Core_Error
72 class CRM_Core_Error
extends PEAR_ErrorStack
{
75 * Status code of various types of errors.
77 const FATAL_ERROR
= 2;
78 const DUPLICATE_CONTACT
= 8001;
79 const DUPLICATE_CONTRIBUTION
= 8002;
80 const DUPLICATE_PARTICIPANT
= 8003;
83 * We only need one instance of this object. So we use the singleton
84 * pattern and cache the instance in this variable
87 private static $_singleton = NULL;
90 * The logger object for this application.
93 private static $_log = NULL;
96 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
98 public static $modeException = NULL;
101 * Singleton function used to manage this object.
103 * @param null $package
104 * @param bool $msgCallback
105 * @param bool $contextCallback
106 * @param bool $throwPEAR_Error
107 * @param string $stackClass
109 * @return CRM_Core_Error
111 public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
112 if (self
::$_singleton === NULL) {
113 self
::$_singleton = new CRM_Core_Error('CiviCRM');
115 return self
::$_singleton;
121 public function __construct() {
122 parent
::__construct('CiviCRM');
124 $log = CRM_Core_Config
::getLog();
125 $this->setLogger($log);
127 // PEAR<=1.9.0 does not declare "static" properly.
128 if (!is_callable(array('PEAR', '__callStatic'))) {
129 $this->setDefaultCallback(array($this, 'handlePES'));
132 PEAR_ErrorStack
::setDefaultCallback(array($this, 'handlePES'));
138 * @param string $separator
140 * @return array|null|string
142 static public function getMessages(&$error, $separator = '<br />') {
143 if (is_a($error, 'CRM_Core_Error')) {
144 $errors = $error->getErrors();
146 foreach ($errors as $e) {
147 $message[] = $e['code'] . ': ' . $e['message'];
149 $message = implode($separator, $message);
152 elseif (is_a($error, 'Civi\Payment\Exception\PaymentProcessorException')) {
153 return $error->getMessage();
159 * Status display function specific to payment processor errors.
161 * @param string $separator
163 public static function displaySessionError(&$error, $separator = '<br />') {
164 $message = self
::getMessages($error, $separator);
166 $status = ts("Payment Processor Error message") . "{$separator} $message";
167 $session = CRM_Core_Session
::singleton();
168 $session->setStatus($status);
173 * Create the main callback method. this method centralizes error processing.
175 * the errors we expect are from the pear modules DB, DB_DataObject
176 * which currently use PEAR::raiseError to notify of error messages.
178 * @param object $pearError PEAR_Error
180 public static function handle($pearError) {
181 if (defined('CIVICRM_TEST')) {
182 return self
::simpleHandler($pearError);
185 // setup smarty with config, session and template location.
186 $template = CRM_Core_Smarty
::singleton();
187 $config = CRM_Core_Config
::singleton();
189 if ($config->backtrace
) {
193 // create the error array
194 $error = self
::getErrorDetails($pearError);
196 // We access connection info via _DB_DATAOBJECT instead
197 // of, e.g., calling getDatabaseConnection(), so that we
198 // can avoid infinite loops.
199 global $_DB_DATAOBJECT;
201 if (isset($_DB_DATAOBJECT['CONFIG']['database'])) {
202 $dao = new CRM_Core_DAO();
203 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
204 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
206 // FIXME: Polymorphism for the win.
207 if ($conn instanceof DB_mysqli
) {
208 $link = $conn->connection
;
209 if (mysqli_error($link)) {
210 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
211 mysqli_query($link, 'select 1'); // execute a dummy query to clear error stack
214 elseif ($conn instanceof DB_mysql
) {
216 $mysql_error = mysql_error() . ', ' . mysql_errno();
217 mysql_query('select 1'); // execute a dummy query to clear error stack
221 $mysql_error = 'fixme-unknown-db-cxn';
223 $template->assign_by_ref('mysql_code', $mysql_error);
227 $template->assign_by_ref('error', $error);
228 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
229 $template->assign_by_ref('errorDetails', $errorDetails);
231 CRM_Core_Error
::debug_var('Fatal Error Details', $error);
232 CRM_Core_Error
::backtrace('backTrace', TRUE);
234 if ($config->initialized
) {
235 $content = $template->fetch('CRM/common/fatal.tpl');
236 echo CRM_Utils_System
::theme($content);
239 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
240 CRM_Core_Error
::debug(NULL, $error);
242 static $runOnce = FALSE;
251 * this function is used to trap and print errors
252 * during system initialization time. Hence the error
253 * message is quite ugly
257 public static function simpleHandler($pearError) {
259 $error = self
::getErrorDetails($pearError);
261 // ensure that debug does not check permissions since we are in bootstrap
262 // mode and need to print a decent message to help the user
263 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
265 // always log the backtrace to a file
266 self
::backtrace('backTrace', TRUE);
272 * this function is used to return error details
276 * @return array $error
278 public static function getErrorDetails($pearError) {
279 // create the error array
281 $error['callback'] = $pearError->getCallback();
282 $error['code'] = $pearError->getCode();
283 $error['message'] = $pearError->getMessage();
284 $error['mode'] = $pearError->getMode();
285 $error['debug_info'] = $pearError->getDebugInfo();
286 $error['type'] = $pearError->getType();
287 $error['user_info'] = $pearError->getUserInfo();
288 $error['to_string'] = $pearError->toString();
294 * Handle errors raised using the PEAR Error Stack.
296 * currently the handler just requests the PES framework
297 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
299 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
301 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
302 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
303 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
305 * @param mixed $pearError
309 public static function handlePES($pearError) {
310 return PEAR_ERRORSTACK_PUSH
;
314 * Display an error page with an error message describing what happened.
317 * This is a really annoying function. We ❤ exceptions. Be exceptional!
321 * @param string $message
323 * @param string $code
324 * The error code if any.
325 * @param string $email
326 * The email address to notify of this situation.
330 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
332 'message' => htmlspecialchars($message),
336 if (self
::$modeException) {
338 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
339 CRM_Core_Error
::backtrace('backTrace', TRUE);
341 $details = 'A fatal error was triggered';
343 $details .= ': ' . $message;
345 throw new Exception($details, $code);
349 $message = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', array(1 => 'https://civicrm.org/bug-reporting'));
352 if (php_sapi_name() == "cli") {
353 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
355 echo static::formatBacktrace(debug_backtrace());
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 $config = CRM_Core_Config
::singleton();
364 if ($config->fatalErrorHandler
&&
365 function_exists($config->fatalErrorHandler
)
367 $name = $config->fatalErrorHandler
;
370 // the call has been successfully handled
372 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
376 if ($config->backtrace
) {
380 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
381 CRM_Core_Error
::backtrace('backTrace', TRUE);
383 // If we are in an ajax callback, format output appropriately
384 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
387 '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>',
389 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
390 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
391 $message .= '<p><em>See console for backtrace</em></p>';
393 CRM_Core_Session
::setStatus($message, ts('Sorry an error occurred'), 'error');
394 CRM_Core_Transaction
::forceRollbackIfEnabled();
395 CRM_Core_Page_AJAX
::returnJsonResponse($out);
398 $template = CRM_Core_Smarty
::singleton();
399 $template->assign($vars);
400 $config->userSystem
->outputError($template->fetch('CRM/common/fatal.tpl'));
402 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
406 * Display an error page with an error message describing what happened.
408 * This function is evil -- it largely replicates fatal(). Hopefully the
409 * entire CRM_Core_Error system can be hollowed out and replaced with
410 * something that follows a cleaner separation of concerns.
412 * @param Exception $exception
414 public static function handleUnhandledException($exception) {
416 CRM_Utils_Hook
::unhandledException($exception);
418 catch (Exception
$other) {
419 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
420 CRM_Core_Error
::debug_var('handleUnhandledException_nestedException', self
::formatTextException($other));
422 $config = CRM_Core_Config
::singleton();
424 'message' => $exception->getMessage(),
426 'exception' => $exception,
428 if (!$vars['message']) {
429 $vars['message'] = ts('We experienced an unexpected error. You may have found a bug. For more information on how to provide a bug report, please read: %1', array(1 => 'https://civicrm.org/bug-reporting'));
433 if (php_sapi_name() == "cli") {
434 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
435 print self
::formatTextException($exception);
437 // FIXME: Why doesn't this call abend()?
438 // Difference: abend() will cleanup transaction and (via civiExit) store session state
439 // self::abend(CRM_Core_Error::FATAL_ERROR);
442 // Case B: Custom error handler
443 if ($config->fatalErrorHandler
&&
444 function_exists($config->fatalErrorHandler
)
446 $name = $config->fatalErrorHandler
;
449 // the call has been successfully handled
451 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
455 // Case C: Default error handler
458 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, FALSE);
459 CRM_Core_Error
::backtrace('backTrace', TRUE);
462 $template = CRM_Core_Smarty
::singleton();
463 $template->assign($vars);
464 $content = $template->fetch('CRM/common/fatal.tpl');
465 if ($config->backtrace
) {
466 $content = self
::formatHtmlException($exception) . $content;
468 if ($config->userFramework
== 'Joomla' &&
469 class_exists('JError')
471 JError
::raiseError('CiviCRM-001', $content);
474 echo CRM_Utils_System
::theme($content);
478 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
482 * Outputs pre-formatted debug information. Flushes the buffers
483 * so we can interrupt a potential POST/redirect
485 * @param string $name name of debug section
486 * @param $variable mixed reference to variables that we need a trace of
487 * @param bool $log should we log or return the output
488 * @param bool $html whether to generate a HTML-escaped output
489 * @param bool $checkPermission should we check permissions before displaying output
490 * useful when we die during initialization and permissioning
491 * subsystem is not initialized - CRM-13765
494 * the generated output
496 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
497 $error = self
::singleton();
499 if ($variable === NULL) {
504 $out = print_r($variable, TRUE);
507 $out = htmlspecialchars($out);
509 $prefix = "<p>$name</p>";
511 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
515 $prefix = "$name:\n";
517 $out = "{$prefix}$out\n";
521 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
530 * Similar to the function debug. Only difference is
531 * in the formatting of the output.
533 * @param string $variable_name
535 * @param mixed $variable
538 * Use print_r (if true) or var_dump (if false).
540 * Log or return the output?
541 * @param string $prefix
542 * Prefix for output logfile.
545 * The generated output
547 * @see CRM_Core_Error::debug()
548 * @see CRM_Core_Error::debug_log_message()
550 public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '') {
551 // check if variable is set
552 if (!isset($variable)) {
553 $out = "\$$variable_name is not set";
557 $out = print_r($variable, TRUE);
558 $out = "\$$variable_name = $out";
564 $dump = ob_get_contents();
566 $out = "\n\$$variable_name = $dump";
568 // reset if it is an array
569 if (is_array($variable)) {
573 return self
::debug_log_message($out, FALSE, $prefix);
577 * Display the error message on terminal and append it to the log file.
579 * Provided the user has the 'view debug output' the output should be displayed. In all
580 * cases it should be logged.
582 * @param string $message
584 * Should we log or return the output.
586 * @param string $prefix
588 * @param string $priority
591 * Format of the backtrace
593 public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) {
594 $config = CRM_Core_Config
::singleton();
596 $file_log = self
::createDebugLogger($prefix);
597 $file_log->log("$message\n", $priority);
599 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
600 if ($out && CRM_Core_Permission
::check('view debug output')) {
605 if (!isset(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
606 // Set it to FALSE first & then try to set it. This is to prevent a loop as calling
607 // $config->userFrameworkLogging can trigger DB queries & under log mode this
608 // then gets called again.
609 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = FALSE;
610 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = $config->userFrameworkLogging
;
613 if (!empty(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
614 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
615 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
616 watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG
);
624 * Append to the query log (if enabled)
626 * @param string $string
628 public static function debug_query($string) {
629 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
630 if (CIVICRM_DEBUG_LOG_QUERY
=== 'backtrace') {
631 CRM_Core_Error
::backtrace($string, TRUE);
633 elseif (CIVICRM_DEBUG_LOG_QUERY
) {
634 CRM_Core_Error
::debug_var('Query', $string, TRUE, TRUE, 'sql_log');
640 * Execute a query and log the results.
642 * @param string $query
644 public static function debug_query_result($query) {
645 $results = CRM_Core_DAO
::executeQuery($query)->fetchAll();
646 CRM_Core_Error
::debug_var('dao result', array('query' => $query, 'results' => $results));
650 * Obtain a reference to the error log.
652 * @param string $prefix
656 public static function createDebugLogger($prefix = '') {
657 self
::generateLogFileName($prefix);
658 return Log
::singleton('file', \Civi
::$statics[__CLASS__
]['logger_file' . $prefix], '');
662 * Generate a hash for the logfile.
666 * @param CRM_Core_Config $config
670 public static function generateLogFileHash($config) {
671 // Use multiple (but stable) inputs for hash information.
673 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: 'NO_SITE_KEY',
674 $config->userFrameworkBaseURL
,
678 // Trim 8 chars off the string, make it slightly easier to find
679 // but reveals less information from the hash.
680 return substr(md5(var_export($md5inputs, 1)), 8);
684 * Generate the name of the logfile to use and store it as a static.
686 * This function includes simplistic log rotation and a check as to whether
689 * @param string $prefix
691 protected static function generateLogFileName($prefix) {
692 if (!isset(\Civi
::$statics[__CLASS__
]['logger_file' . $prefix])) {
693 $config = CRM_Core_Config
::singleton();
695 $prefixString = $prefix ?
($prefix . '.') : '';
697 $hash = self
::generateLogFileHash($config);
698 $fileName = $config->configAndLogDir
. 'CiviCRM.' . $prefixString . $hash . '.log';
700 // Roll log file monthly or if greater than 256M.
701 // Size-based rotation introduced in response to filesize limits on
702 // certain OS/PHP combos.
703 if (file_exists($fileName)) {
704 $fileTime = date("Ym", filemtime($fileName));
705 $fileSize = filesize($fileName);
706 if (($fileTime < date('Ym')) ||
707 ($fileSize > 256 * 1024 * 1024) ||
711 $fileName . '.' . date('YmdHi')
715 \Civi
::$statics[__CLASS__
]['logger_file' . $prefix] = $fileName;
723 public static function backtrace($msg = 'backTrace', $log = FALSE) {
724 $backTrace = debug_backtrace();
725 $message = self
::formatBacktrace($backTrace);
727 CRM_Core_Error
::debug($msg, $message);
730 CRM_Core_Error
::debug_var($msg, $message);
735 * Render a backtrace array as a string.
737 * @param array $backTrace
738 * Array of stack frames.
739 * @param bool $showArgs
740 * 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.
741 * @param int $maxArgLen
742 * Maximum number of characters to show from each argument string.
744 * printable plain-text
746 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
748 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
749 $message .= sprintf("#%s %s\n", $idx, $trace);
751 $message .= sprintf("#%s {main}\n", 1 +
$idx);
756 * Render a backtrace array as an array.
758 * @param array $backTrace
759 * Array of stack frames.
760 * @param bool $showArgs
761 * 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.
762 * @param int $maxArgLen
763 * Maximum number of characters to show from each argument string.
765 * @see debug_backtrace
766 * @see Exception::getTrace()
768 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
770 foreach ($backTrace as $trace) {
772 $fnName = CRM_Utils_Array
::value('function', $trace);
773 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
775 // Do not show args for a few password related functions
776 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
778 if (!empty($trace['args'])) {
779 foreach ($trace['args'] as $arg) {
780 if (!$showArgs ||
$skipArgs) {
781 $args[] = '(' . gettype($arg) . ')';
784 switch ($type = gettype($arg)) {
786 $args[] = $arg ?
'TRUE' : 'FALSE';
795 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
799 $args[] = '(Array:' . count($arg) . ')';
803 $args[] = 'Object(' . get_class($arg) . ')';
807 $args[] = 'Resource';
823 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
824 CRM_Utils_Array
::value('line', $trace, ''),
834 * Render an exception as HTML string.
836 * @param Exception $e
838 * printable HTML text
840 public static function formatHtmlException(Exception
$e) {
843 // Exception metadata
845 // Exception backtrace
846 if ($e instanceof PEAR_Exception
) {
848 while (is_callable(array($ei, 'getCause'))) {
849 if ($ei->getCause() instanceof PEAR_Error
) {
850 $msg .= '<table class="crm-db-error">';
851 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
853 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
854 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
856 $msg .= '</tbody></table>';
858 $ei = $ei->getCause();
860 $msg .= $e->toHtml();
863 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
864 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
870 * Write details of an exception to the log.
872 * @param Exception $e
874 * printable plain text
876 public static function formatTextException(Exception
$e) {
877 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
880 while (is_callable(array($ei, 'getCause'))) {
881 if ($ei->getCause() instanceof PEAR_Error
) {
882 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
883 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
886 $ei = $ei->getCause();
888 $msg .= self
::formatBacktrace($e->getTrace());
895 * @param string $level
896 * @param array $params
900 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
901 $error = CRM_Core_Error
::singleton();
902 $error->push($code, $level, array($params), $message);
907 * Set a status message in the session, then bounce back to the referrer.
909 * @param string $status
910 * The status message to set.
912 * @param null $redirect
913 * @param string $title
915 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
916 $session = CRM_Core_Session
::singleton();
918 $redirect = $session->readUserContext();
920 if ($title === NULL) {
921 $title = ts('Error');
923 $session->setStatus($status, $title, 'alert', array('expires' => 0));
924 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
925 CRM_Core_Page_AJAX
::returnJsonResponse(array('status' => 'error'));
927 CRM_Utils_System
::redirect($redirect);
931 * Reset the error stack.
934 public static function reset() {
935 $error = self
::singleton();
936 $error->_errors
= array();
937 $error->_errorsByLevel
= array();
941 * PEAR error-handler which converts errors to exceptions
944 * @throws PEAR_Exception
946 public static function exceptionHandler($pearError) {
947 CRM_Core_Error
::debug_var('Fatal Error Details', self
::getErrorDetails($pearError));
948 CRM_Core_Error
::backtrace('backTrace', TRUE);
949 throw new PEAR_Exception($pearError->getMessage(), $pearError);
953 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
956 * The PEAR_ERROR object.
960 public static function nullHandler($obj) {
961 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
962 CRM_Core_Error
::backtrace('backTrace', TRUE);
968 * This function is no longer used by v3 api.
969 * @fixme Some core files call it but it should be re-thought & renamed or removed
977 public static function &createAPIError($msg, $data = NULL) {
978 if (self
::$modeException) {
979 throw new Exception($msg, $data);
984 $values['is_error'] = 1;
985 $values['error_message'] = $msg;
987 $values = array_merge($values, $data);
995 public static function movedSiteError($file) {
996 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
1000 echo "We could not write $file. Have you moved your site directory or server?<p>";
1001 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
1006 * Terminate execution abnormally.
1008 * @param string $code
1010 protected static function abend($code) {
1011 // do a hard rollback of any pending transactions
1012 // if we've come here, its because of some unexpected PEAR errors
1013 CRM_Core_Transaction
::forceRollbackIfEnabled();
1014 CRM_Utils_System
::civiExit($code);
1018 * @param array $error
1023 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
1024 if (is_array($error) && !empty($error['is_error'])) {
1025 $code = $error['error_message']['code'];
1026 if ($code == $type) {
1035 $e = new PEAR_ErrorStack('CRM');
1036 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');