3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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-2020
36 require_once 'PEAR/ErrorStack.php';
37 require_once 'PEAR/Exception.php';
38 require_once 'CRM/Core/Exception.php';
40 require_once 'Log.php';
43 * Class CRM_Core_Error
45 class CRM_Core_Error
extends PEAR_ErrorStack
{
48 * Status code of various types of errors.
50 const FATAL_ERROR
= 2;
51 const DUPLICATE_CONTACT
= 8001;
52 const DUPLICATE_CONTRIBUTION
= 8002;
53 const DUPLICATE_PARTICIPANT
= 8003;
56 * We only need one instance of this object. So we use the singleton
57 * pattern and cache the instance in this variable
60 private static $_singleton = NULL;
63 * The logger object for this application.
66 private static $_log = NULL;
69 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
72 public static $modeException = NULL;
75 * Singleton function used to manage this object.
77 * @param null $package
78 * @param bool $msgCallback
79 * @param bool $contextCallback
80 * @param bool $throwPEAR_Error
81 * @param string $stackClass
83 * @return CRM_Core_Error
85 public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
86 if (self
::$_singleton === NULL) {
87 self
::$_singleton = new CRM_Core_Error('CiviCRM');
89 return self
::$_singleton;
95 public function __construct() {
96 parent
::__construct('CiviCRM');
98 $log = CRM_Core_Config
::getLog();
99 $this->setLogger($log);
101 // PEAR<=1.9.0 does not declare "static" properly.
102 if (!is_callable(['PEAR', '__callStatic'])) {
103 $this->setDefaultCallback([$this, 'handlePES']);
106 PEAR_ErrorStack
::setDefaultCallback([$this, 'handlePES']);
112 * @param string $separator
114 * @return array|null|string
116 public static function getMessages(&$error, $separator = '<br />') {
117 if (is_a($error, 'CRM_Core_Error')) {
118 $errors = $error->getErrors();
120 foreach ($errors as $e) {
121 $message[] = $e['code'] . ': ' . $e['message'];
123 $message = implode($separator, $message);
126 elseif (is_a($error, 'Civi\Payment\Exception\PaymentProcessorException')) {
127 return $error->getMessage();
133 * Status display function specific to payment processor errors.
135 * @param string $separator
137 public static function displaySessionError(&$error, $separator = '<br />') {
138 $message = self
::getMessages($error, $separator);
140 $status = ts("Payment Processor Error message") . "{$separator} $message";
141 $session = CRM_Core_Session
::singleton();
142 $session->setStatus($status);
147 * Create the main callback method. this method centralizes error processing.
149 * the errors we expect are from the pear modules DB, DB_DataObject
150 * which currently use PEAR::raiseError to notify of error messages.
152 * @param object $pearError PEAR_Error
154 public static function handle($pearError) {
155 if (defined('CIVICRM_TEST')) {
156 return self
::simpleHandler($pearError);
159 // setup smarty with config, session and template location.
160 $template = CRM_Core_Smarty
::singleton();
161 $config = CRM_Core_Config
::singleton();
163 if ($config->backtrace
) {
167 // create the error array
168 $error = self
::getErrorDetails($pearError);
170 // We access connection info via _DB_DATAOBJECT instead
171 // of, e.g., calling getDatabaseConnection(), so that we
172 // can avoid infinite loops.
173 global $_DB_DATAOBJECT;
175 if (isset($_DB_DATAOBJECT['CONFIG']['database'])) {
176 $dao = new CRM_Core_DAO();
177 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
178 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
180 // FIXME: Polymorphism for the win.
181 if ($conn instanceof DB_mysqli
) {
182 $link = $conn->connection
;
183 if (mysqli_error($link)) {
184 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
185 // execute a dummy query to clear error stack
186 mysqli_query($link, 'select 1');
189 elseif ($conn instanceof DB_mysql
) {
191 $mysql_error = mysql_error() . ', ' . mysql_errno();
192 // execute a dummy query to clear error stack
193 mysql_query('select 1');
197 $mysql_error = 'fixme-unknown-db-cxn';
199 $template->assign_by_ref('mysql_code', $mysql_error);
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, TRUE, TRUE, '', PEAR_LOG_ERR
);
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;
227 * this function is used to trap and print errors
228 * during system initialization time. Hence the error
229 * message is quite ugly
233 public static function simpleHandler($pearError) {
235 $error = self
::getErrorDetails($pearError);
237 // ensure that debug does not check permissions since we are in bootstrap
238 // mode and need to print a decent message to help the user
239 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
241 // always log the backtrace to a file
242 self
::backtrace('backTrace', TRUE);
248 * this function is used to return error details
252 * @return array $error
254 public static function getErrorDetails($pearError) {
255 // create the error array
257 $error['callback'] = $pearError->getCallback();
258 $error['code'] = $pearError->getCode();
259 $error['message'] = $pearError->getMessage();
260 $error['mode'] = $pearError->getMode();
261 $error['debug_info'] = $pearError->getDebugInfo();
262 $error['type'] = $pearError->getType();
263 $error['user_info'] = $pearError->getUserInfo();
264 $error['to_string'] = $pearError->toString();
270 * Handle errors raised using the PEAR Error Stack.
272 * currently the handler just requests the PES framework
273 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
275 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
277 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
278 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
279 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
281 * @param mixed $pearError
285 public static function handlePES($pearError) {
286 return PEAR_ERRORSTACK_PUSH
;
290 * Display an error page with an error message describing what happened.
293 * This is a really annoying function. We ❤ exceptions. Be exceptional!
297 * @param string $message
299 * @param string $code
300 * The error code if any.
301 * @param string $email
302 * The email address to notify of this situation.
306 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
308 'message' => $message,
312 if (self
::$modeException) {
314 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR
);
315 CRM_Core_Error
::backtrace('backTrace', TRUE);
317 $details = 'A fatal error was triggered';
319 $details .= ': ' . $message;
321 throw new Exception($details, $code);
325 $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', [1 => 'https://civicrm.org/bug-reporting']);
328 if (php_sapi_name() == "cli") {
329 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
331 echo static::formatBacktrace(debug_backtrace());
333 // FIXME: Why doesn't this call abend()?
334 // Difference: abend() will cleanup transaction and (via civiExit) store session state
335 // self::abend(CRM_Core_Error::FATAL_ERROR);
338 $config = CRM_Core_Config
::singleton();
340 if ($config->fatalErrorHandler
&&
341 function_exists($config->fatalErrorHandler
)
343 $name = $config->fatalErrorHandler
;
346 // the call has been successfully handled
348 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
352 if ($config->backtrace
) {
356 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR
);
357 CRM_Core_Error
::backtrace('backTrace', TRUE);
359 // If we are in an ajax callback, format output appropriately
360 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
363 '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>',
365 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
366 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
367 $message .= '<p><em>See console for backtrace</em></p>';
369 CRM_Core_Session
::setStatus($message, ts('Sorry an error occurred'), 'error');
370 CRM_Core_Transaction
::forceRollbackIfEnabled();
371 CRM_Core_Page_AJAX
::returnJsonResponse($out);
374 $template = CRM_Core_Smarty
::singleton();
375 $template->assign($vars);
376 $config->userSystem
->outputError($template->fetch('CRM/common/fatal.tpl'));
378 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
382 * Display an error page with an error message describing what happened.
384 * This function is evil -- it largely replicates fatal(). Hopefully the
385 * entire CRM_Core_Error system can be hollowed out and replaced with
386 * something that follows a cleaner separation of concerns.
388 * @param Exception $exception
390 public static function handleUnhandledException($exception) {
392 CRM_Utils_Hook
::unhandledException($exception);
394 catch (Exception
$other) {
395 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
396 CRM_Core_Error
::debug_var('handleUnhandledException_nestedException', self
::formatTextException($other), TRUE, TRUE, '', PEAR_LOG_ERR
);
398 $config = CRM_Core_Config
::singleton();
400 'message' => $exception->getMessage(),
402 'exception' => $exception,
404 if (!$vars['message']) {
405 $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', [1 => 'https://civicrm.org/bug-reporting']);
409 if (php_sapi_name() == "cli") {
410 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
411 print self
::formatTextException($exception);
413 // FIXME: Why doesn't this call abend()?
414 // Difference: abend() will cleanup transaction and (via civiExit) store session state
415 // self::abend(CRM_Core_Error::FATAL_ERROR);
418 // Case B: Custom error handler
419 if ($config->fatalErrorHandler
&&
420 function_exists($config->fatalErrorHandler
)
422 $name = $config->fatalErrorHandler
;
425 // the call has been successfully handled
427 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
431 // Case C: Default error handler
434 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, FALSE, TRUE, '', PEAR_LOG_ERR
);
435 CRM_Core_Error
::backtrace('backTrace', TRUE);
438 $template = CRM_Core_Smarty
::singleton();
439 $template->assign($vars);
440 $content = $template->fetch('CRM/common/fatal.tpl');
442 if ($config->backtrace
) {
443 $content = self
::formatHtmlException($exception) . $content;
446 echo CRM_Utils_System
::theme($content);
449 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
453 * Outputs pre-formatted debug information. Flushes the buffers
454 * so we can interrupt a potential POST/redirect
456 * @param string $name name of debug section
457 * @param $variable mixed reference to variables that we need a trace of
458 * @param bool $log should we log or return the output
459 * @param bool $html whether to generate a HTML-escaped output
460 * @param bool $checkPermission should we check permissions before displaying output
461 * useful when we die during initialization and permissioning
462 * subsystem is not initialized - CRM-13765
465 * the generated output
467 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
468 $error = self
::singleton();
470 if ($variable === NULL) {
475 $out = print_r($variable, TRUE);
478 $out = htmlspecialchars($out);
480 $prefix = "<p>$name</p>";
482 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
486 $prefix = "$name:\n";
488 $out = "{$prefix}$out\n";
492 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
501 * Similar to the function debug. Only difference is
502 * in the formatting of the output.
504 * @param string $variable_name
506 * @param mixed $variable
509 * Use print_r (if true) or var_dump (if false).
511 * Log or return the output?
512 * @param string $prefix
513 * Prefix for output logfile.
514 * @param int $priority
515 * The log priority level.
518 * The generated output
520 * @see CRM_Core_Error::debug()
521 * @see CRM_Core_Error::debug_log_message()
523 public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '', $priority = NULL) {
524 // check if variable is set
525 if (!isset($variable)) {
526 $out = "\$$variable_name is not set";
530 $out = print_r($variable, TRUE);
531 $out = "\$$variable_name = $out";
537 $dump = ob_get_contents();
539 $out = "\n\$$variable_name = $dump";
541 // reset if it is an array
542 if (is_array($variable)) {
546 return self
::debug_log_message($out, FALSE, $prefix, $priority);
550 * Display the error message on terminal and append it to the log file.
552 * Provided the user has the 'view debug output' the output should be displayed. In all
553 * cases it should be logged.
555 * @param string $message
557 * Should we log or return the output.
559 * @param string $prefix
561 * @param string $priority
564 * Format of the backtrace
566 public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) {
567 $config = CRM_Core_Config
::singleton();
569 $file_log = self
::createDebugLogger($prefix);
570 $file_log->log("$message\n", $priority);
572 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
573 if ($out && CRM_Core_Permission
::check('view debug output')) {
578 if (!isset(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
579 // Set it to FALSE first & then try to set it. This is to prevent a loop as calling
580 // $config->userFrameworkLogging can trigger DB queries & under log mode this
581 // then gets called again.
582 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = FALSE;
583 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = $config->userFrameworkLogging
;
586 if (!empty(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
587 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
588 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
589 watchdog('civicrm', '%message', ['%message' => $message], isset($priority) ?
$priority : WATCHDOG_DEBUG
);
597 * Append to the query log (if enabled)
599 * @param string $string
601 public static function debug_query($string) {
602 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
603 if (CIVICRM_DEBUG_LOG_QUERY
=== 'backtrace') {
604 CRM_Core_Error
::backtrace($string, TRUE);
606 elseif (CIVICRM_DEBUG_LOG_QUERY
) {
607 CRM_Core_Error
::debug_var('Query', $string, TRUE, TRUE, 'sql_log', PEAR_LOG_DEBUG
);
613 * Execute a query and log the results.
615 * @param string $query
617 public static function debug_query_result($query) {
618 $results = CRM_Core_DAO
::executeQuery($query)->fetchAll();
619 CRM_Core_Error
::debug_var('dao result', ['query' => $query, 'results' => $results], TRUE, TRUE, '', PEAR_LOG_DEBUG
);
623 * Obtain a reference to the error log.
625 * @param string $prefix
629 public static function createDebugLogger($prefix = '') {
630 self
::generateLogFileName($prefix);
631 return Log
::singleton('file', \Civi
::$statics[__CLASS__
]['logger_file' . $prefix], '');
635 * Generate a hash for the logfile.
639 * @param CRM_Core_Config $config
643 public static function generateLogFileHash($config) {
644 // Use multiple (but stable) inputs for hash information.
646 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: 'NO_SITE_KEY',
647 $config->userFrameworkBaseURL
,
651 // Trim 8 chars off the string, make it slightly easier to find
652 // but reveals less information from the hash.
653 return substr(md5(var_export($md5inputs, 1)), 8);
657 * Generate the name of the logfile to use and store it as a static.
659 * This function includes simplistic log rotation and a check as to whether
662 * @param string $prefix
664 protected static function generateLogFileName($prefix) {
665 if (!isset(\Civi
::$statics[__CLASS__
]['logger_file' . $prefix])) {
666 $config = CRM_Core_Config
::singleton();
668 $prefixString = $prefix ?
($prefix . '.') : '';
670 $hash = self
::generateLogFileHash($config);
671 $fileName = $config->configAndLogDir
. 'CiviCRM.' . $prefixString . $hash . '.log';
673 // Roll log file monthly or if greater than 256M.
674 // Size-based rotation introduced in response to filesize limits on
675 // certain OS/PHP combos.
676 if (file_exists($fileName)) {
677 $fileTime = date("Ym", filemtime($fileName));
678 $fileSize = filesize($fileName);
679 if (($fileTime < date('Ym')) ||
680 ($fileSize > 256 * 1024 * 1024) ||
684 $fileName . '.' . date('YmdHi')
688 \Civi
::$statics[__CLASS__
]['logger_file' . $prefix] = $fileName;
696 public static function backtrace($msg = 'backTrace', $log = FALSE) {
697 $backTrace = debug_backtrace();
698 $message = self
::formatBacktrace($backTrace);
700 CRM_Core_Error
::debug($msg, $message);
703 CRM_Core_Error
::debug_var($msg, $message, TRUE, TRUE, '', PEAR_LOG_DEBUG
);
708 * Render a backtrace array as a string.
710 * @param array $backTrace
711 * Array of stack frames.
712 * @param bool $showArgs
713 * 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.
714 * @param int $maxArgLen
715 * Maximum number of characters to show from each argument string.
717 * printable plain-text
719 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
721 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
722 $message .= sprintf("#%s %s\n", $idx, $trace);
724 $message .= sprintf("#%s {main}\n", 1 +
$idx);
729 * Render a backtrace array as an array.
731 * @param array $backTrace
732 * Array of stack frames.
733 * @param bool $showArgs
734 * 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.
735 * @param int $maxArgLen
736 * Maximum number of characters to show from each argument string.
738 * @see debug_backtrace
739 * @see Exception::getTrace()
741 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
743 foreach ($backTrace as $trace) {
745 $fnName = CRM_Utils_Array
::value('function', $trace);
746 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
748 // Do not show args for a few password related functions
749 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
751 if (!empty($trace['args'])) {
752 foreach ($trace['args'] as $arg) {
753 if (!$showArgs ||
$skipArgs) {
754 $args[] = '(' . gettype($arg) . ')';
757 switch ($type = gettype($arg)) {
759 $args[] = $arg ?
'TRUE' : 'FALSE';
768 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
772 $args[] = '(Array:' . count($arg) . ')';
776 $args[] = 'Object(' . get_class($arg) . ')';
780 $args[] = 'Resource';
796 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
797 CRM_Utils_Array
::value('line', $trace, ''),
807 * Render an exception as HTML string.
809 * @param Exception $e
811 * printable HTML text
813 public static function formatHtmlException(Exception
$e) {
816 // Exception metadata
818 // Exception backtrace
819 if ($e instanceof PEAR_Exception
) {
821 while (is_callable([$ei, 'getCause'])) {
822 if ($ei->getCause() instanceof PEAR_Error
) {
823 $msg .= '<table class="crm-db-error">';
824 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
826 foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) {
827 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func([$ei->getCause(), "get$f"]));
829 $msg .= '</tbody></table>';
831 $ei = $ei->getCause();
833 $msg .= $e->toHtml();
836 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
837 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
843 * Write details of an exception to the log.
845 * @param Exception $e
847 * printable plain text
849 public static function formatTextException(Exception
$e) {
850 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
853 while (is_callable([$ei, 'getCause'])) {
854 if ($ei->getCause() instanceof PEAR_Error
) {
855 foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) {
856 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func([$ei->getCause(), "get$f"]));
859 $ei = $ei->getCause();
861 $msg .= self
::formatBacktrace($e->getTrace());
868 * @param string $level
869 * @param array $params
873 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
874 $error = CRM_Core_Error
::singleton();
875 $error->push($code, $level, [$params], $message);
880 * Set a status message in the session, then bounce back to the referrer.
882 * @param string $status
883 * The status message to set.
885 * @param null $redirect
886 * @param string $title
888 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
889 $session = CRM_Core_Session
::singleton();
891 $redirect = $session->readUserContext();
893 if ($title === NULL) {
894 $title = ts('Error');
896 $session->setStatus($status, $title, 'alert', ['expires' => 0]);
897 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
898 CRM_Core_Page_AJAX
::returnJsonResponse(['status' => 'error']);
900 CRM_Utils_System
::redirect($redirect);
904 * Reset the error stack.
907 public static function reset() {
908 $error = self
::singleton();
909 $error->_errors
= [];
910 $error->_errorsByLevel
= [];
914 * PEAR error-handler which converts errors to exceptions
917 * @throws PEAR_Exception
919 public static function exceptionHandler($pearError) {
920 CRM_Core_Error
::debug_var('Fatal Error Details', self
::getErrorDetails($pearError), TRUE, TRUE, '', PEAR_LOG_ERR
);
921 CRM_Core_Error
::backtrace('backTrace', TRUE);
922 throw new PEAR_Exception($pearError->getMessage(), $pearError);
926 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
929 * The PEAR_ERROR object.
933 public static function nullHandler($obj) {
934 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}", FALSE, '', PEAR_LOG_ERR
);
935 CRM_Core_Error
::backtrace('backTrace', TRUE);
941 * This function is no longer used by v3 api.
942 * @fixme Some core files call it but it should be re-thought & renamed or removed
950 public static function &createAPIError($msg, $data = NULL) {
951 if (self
::$modeException) {
952 throw new Exception($msg, $data);
957 $values['is_error'] = 1;
958 $values['error_message'] = $msg;
960 $values = array_merge($values, $data);
968 public static function movedSiteError($file) {
969 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
973 echo "We could not write $file. Have you moved your site directory or server?<p>";
974 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
979 * Terminate execution abnormally.
981 * @param string $code
983 protected static function abend($code) {
984 // do a hard rollback of any pending transactions
985 // if we've come here, its because of some unexpected PEAR errors
986 CRM_Core_Transaction
::forceRollbackIfEnabled();
987 CRM_Utils_System
::civiExit($code);
991 * @param array $error
996 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
997 if (is_array($error) && !empty($error['is_error'])) {
998 $code = $error['error_message']['code'];
999 if ($code == $type) {
1007 * Output a deprecated function warning to log file. Deprecated class:function is automatically generated from calling function.
1010 * description of new method (eg. "buildOptions() method in the appropriate BAO object").
1012 public static function deprecatedFunctionWarning($newMethod) {
1013 $dbt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 2);
1014 $callerFunction = isset($dbt[1]['function']) ?
$dbt[1]['function'] : NULL;
1015 $callerClass = isset($dbt[1]['class']) ?
$dbt[1]['class'] : NULL;
1016 Civi
::log()->warning("Deprecated function $callerClass::$callerFunction, use $newMethod.", ['civi.tag' => 'deprecated']);
1021 $e = new PEAR_ErrorStack('CRM');
1022 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');