3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Start of the Error framework. We should check out and inherit from
14 * PEAR_ErrorStack and use that framework
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 require_once 'PEAR/ErrorStack.php';
21 require_once 'PEAR/Exception.php';
22 require_once 'CRM/Core/Exception.php';
24 require_once 'Log.php';
27 * Class CRM_Core_Error
29 class CRM_Core_Error
extends PEAR_ErrorStack
{
32 * Status code of various types of errors.
34 const FATAL_ERROR
= 2;
35 const DUPLICATE_CONTACT
= 8001;
36 const DUPLICATE_CONTRIBUTION
= 8002;
37 const DUPLICATE_PARTICIPANT
= 8003;
40 * We only need one instance of this object. So we use the singleton
41 * pattern and cache the instance in this variable
44 private static $_singleton = NULL;
47 * The logger object for this application.
50 private static $_log = NULL;
53 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
56 public static $modeException = NULL;
59 * Singleton function used to manage this object.
61 * @param null $package
62 * @param bool $msgCallback
63 * @param bool $contextCallback
64 * @param bool $throwPEAR_Error
65 * @param string $stackClass
67 * @return CRM_Core_Error
69 public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
70 if (self
::$_singleton === NULL) {
71 self
::$_singleton = new CRM_Core_Error('CiviCRM');
73 return self
::$_singleton;
79 public function __construct() {
80 parent
::__construct('CiviCRM');
82 $log = CRM_Core_Config
::getLog();
83 $this->setLogger($log);
85 // PEAR<=1.9.0 does not declare "static" properly.
86 if (!is_callable(['PEAR', '__callStatic'])) {
87 $this->setDefaultCallback([$this, 'handlePES']);
90 PEAR_ErrorStack
::setDefaultCallback([$this, 'handlePES']);
96 * @param string $separator
98 * @return array|null|string
100 public static function getMessages(&$error, $separator = '<br />') {
101 if (is_a($error, 'CRM_Core_Error')) {
102 $errors = $error->getErrors();
104 foreach ($errors as $e) {
105 $message[] = $e['code'] . ': ' . $e['message'];
107 $message = implode($separator, $message);
110 elseif (is_a($error, 'Civi\Payment\Exception\PaymentProcessorException')) {
111 return $error->getMessage();
117 * Status display function specific to payment processor errors.
119 * @param string $separator
121 public static function displaySessionError(&$error, $separator = '<br />') {
122 $message = self
::getMessages($error, $separator);
124 $status = ts("Payment Processor Error message") . "{$separator} $message";
125 $session = CRM_Core_Session
::singleton();
126 $session->setStatus($status);
131 * Create the main callback method. this method centralizes error processing.
133 * the errors we expect are from the pear modules DB, DB_DataObject
134 * which currently use PEAR::raiseError to notify of error messages.
136 * @param object $pearError PEAR_Error
138 public static function handle($pearError) {
139 if (defined('CIVICRM_TEST')) {
140 return self
::simpleHandler($pearError);
143 // setup smarty with config, session and template location.
144 $template = CRM_Core_Smarty
::singleton();
145 $config = CRM_Core_Config
::singleton();
147 if ($config->backtrace
) {
151 // create the error array
152 $error = self
::getErrorDetails($pearError);
154 // We access connection info via _DB_DATAOBJECT instead
155 // of, e.g., calling getDatabaseConnection(), so that we
156 // can avoid infinite loops.
157 global $_DB_DATAOBJECT;
159 if (isset($_DB_DATAOBJECT['CONFIG']['database'])) {
160 $dao = new CRM_Core_DAO();
161 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
162 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
164 // FIXME: Polymorphism for the win.
165 if ($conn instanceof DB_mysqli
) {
166 $link = $conn->connection
;
167 if (mysqli_error($link)) {
168 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
169 // execute a dummy query to clear error stack
170 mysqli_query($link, 'select 1');
173 elseif ($conn instanceof DB_mysql
) {
175 $mysql_error = mysql_error() . ', ' . mysql_errno();
176 // execute a dummy query to clear error stack
177 mysql_query('select 1');
181 $mysql_error = 'fixme-unknown-db-cxn';
183 $template->assign_by_ref('mysql_code', $mysql_error);
187 $template->assign_by_ref('error', $error);
188 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
189 $template->assign_by_ref('errorDetails', $errorDetails);
191 CRM_Core_Error
::debug_var('Fatal Error Details', $error, TRUE, TRUE, '', PEAR_LOG_ERR
);
192 CRM_Core_Error
::backtrace('backTrace', TRUE);
194 if ($config->initialized
) {
195 $content = $template->fetch('CRM/common/fatal.tpl');
196 echo CRM_Utils_System
::theme($content);
199 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
200 CRM_Core_Error
::debug(NULL, $error);
202 static $runOnce = FALSE;
211 * this function is used to trap and print errors
212 * during system initialization time. Hence the error
213 * message is quite ugly
217 public static function simpleHandler($pearError) {
219 $error = self
::getErrorDetails($pearError);
221 // ensure that debug does not check permissions since we are in bootstrap
222 // mode and need to print a decent message to help the user
223 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
225 // always log the backtrace to a file
226 self
::backtrace('backTrace', TRUE);
232 * this function is used to return error details
236 * @return array $error
238 public static function getErrorDetails($pearError) {
239 // create the error array
241 $error['callback'] = $pearError->getCallback();
242 $error['code'] = $pearError->getCode();
243 $error['message'] = $pearError->getMessage();
244 $error['mode'] = $pearError->getMode();
245 $error['debug_info'] = $pearError->getDebugInfo();
246 $error['type'] = $pearError->getType();
247 $error['user_info'] = $pearError->getUserInfo();
248 $error['to_string'] = $pearError->toString();
254 * Handle errors raised using the PEAR Error Stack.
256 * currently the handler just requests the PES framework
257 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
259 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
261 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
262 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
263 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
265 * @param mixed $pearError
269 public static function handlePES($pearError) {
270 return PEAR_ERRORSTACK_PUSH
;
274 * Display an error page with an error message describing what happened.
277 * This is a really annoying function. We ❤ exceptions. Be exceptional!
281 * @param string $message
283 * @param string $code
284 * The error code if any.
285 * @param string $email
286 * The email address to notify of this situation.
290 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
292 'message' => $message,
296 if (self
::$modeException) {
298 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR
);
299 CRM_Core_Error
::backtrace('backTrace', TRUE);
301 $details = 'A fatal error was triggered';
303 $details .= ': ' . $message;
305 throw new Exception($details, $code);
309 $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']);
312 if (php_sapi_name() == "cli") {
313 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
315 echo static::formatBacktrace(debug_backtrace());
317 // FIXME: Why doesn't this call abend()?
318 // Difference: abend() will cleanup transaction and (via civiExit) store session state
319 // self::abend(CRM_Core_Error::FATAL_ERROR);
322 $config = CRM_Core_Config
::singleton();
324 if ($config->fatalErrorHandler
&&
325 function_exists($config->fatalErrorHandler
)
327 $name = $config->fatalErrorHandler
;
330 // the call has been successfully handled
332 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
336 if ($config->backtrace
) {
340 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR
);
341 CRM_Core_Error
::backtrace('backTrace', TRUE);
343 // If we are in an ajax callback, format output appropriately
344 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
347 '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>',
349 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
350 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
351 $message .= '<p><em>See console for backtrace</em></p>';
353 CRM_Core_Session
::setStatus($message, ts('Sorry an error occurred'), 'error');
354 CRM_Core_Transaction
::forceRollbackIfEnabled();
355 CRM_Core_Page_AJAX
::returnJsonResponse($out);
358 $template = CRM_Core_Smarty
::singleton();
359 $template->assign($vars);
360 $config->userSystem
->outputError($template->fetch('CRM/common/fatal.tpl'));
362 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
366 * Display an error page with an error message describing what happened.
368 * This function is evil -- it largely replicates fatal(). Hopefully the
369 * entire CRM_Core_Error system can be hollowed out and replaced with
370 * something that follows a cleaner separation of concerns.
372 * @param Exception $exception
374 public static function handleUnhandledException($exception) {
376 CRM_Utils_Hook
::unhandledException($exception);
378 catch (Exception
$other) {
379 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
380 CRM_Core_Error
::debug_var('handleUnhandledException_nestedException', self
::formatTextException($other), TRUE, TRUE, '', PEAR_LOG_ERR
);
382 $config = CRM_Core_Config
::singleton();
384 'message' => $exception->getMessage(),
386 'exception' => $exception,
388 if (!$vars['message']) {
389 $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']);
393 if (php_sapi_name() == "cli") {
394 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
395 print self
::formatTextException($exception);
397 // FIXME: Why doesn't this call abend()?
398 // Difference: abend() will cleanup transaction and (via civiExit) store session state
399 // self::abend(CRM_Core_Error::FATAL_ERROR);
402 // Case B: Custom error handler
403 if ($config->fatalErrorHandler
&&
404 function_exists($config->fatalErrorHandler
)
406 $name = $config->fatalErrorHandler
;
409 // the call has been successfully handled
411 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
415 // Case C: Default error handler
418 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, FALSE, TRUE, '', PEAR_LOG_ERR
);
419 CRM_Core_Error
::backtrace('backTrace', TRUE);
422 $template = CRM_Core_Smarty
::singleton();
423 $template->assign($vars);
424 $content = $template->fetch('CRM/common/fatal.tpl');
426 if ($config->backtrace
) {
427 $content = self
::formatHtmlException($exception) . $content;
430 echo CRM_Utils_System
::theme($content);
433 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
437 * Outputs pre-formatted debug information. Flushes the buffers
438 * so we can interrupt a potential POST/redirect
440 * @param string $name name of debug section
441 * @param $variable mixed reference to variables that we need a trace of
442 * @param bool $log should we log or return the output
443 * @param bool $html whether to generate a HTML-escaped output
444 * @param bool $checkPermission should we check permissions before displaying output
445 * useful when we die during initialization and permissioning
446 * subsystem is not initialized - CRM-13765
449 * the generated output
451 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
452 $error = self
::singleton();
454 if ($variable === NULL) {
459 $out = print_r($variable, TRUE);
462 $out = htmlspecialchars($out);
464 $prefix = "<p>$name</p>";
466 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
470 $prefix = "$name:\n";
472 $out = "{$prefix}$out\n";
476 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
485 * Similar to the function debug. Only difference is
486 * in the formatting of the output.
488 * @param string $variable_name
490 * @param mixed $variable
493 * Use print_r (if true) or var_dump (if false).
495 * Log or return the output?
496 * @param string $prefix
497 * Prefix for output logfile.
498 * @param int $priority
499 * The log priority level.
502 * The generated output
504 * @see CRM_Core_Error::debug()
505 * @see CRM_Core_Error::debug_log_message()
507 public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '', $priority = NULL) {
508 // check if variable is set
509 if (!isset($variable)) {
510 $out = "\$$variable_name is not set";
514 $out = print_r($variable, TRUE);
515 $out = "\$$variable_name = $out";
521 $dump = ob_get_contents();
523 $out = "\n\$$variable_name = $dump";
525 // reset if it is an array
526 if (is_array($variable)) {
530 return self
::debug_log_message($out, FALSE, $prefix, $priority);
534 * Display the error message on terminal and append it to the log file.
536 * Provided the user has the 'view debug output' the output should be displayed. In all
537 * cases it should be logged.
539 * @param string $message
541 * Should we log or return the output.
543 * @param string $prefix
545 * @param string $priority
548 * Format of the backtrace
550 public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) {
551 $config = CRM_Core_Config
::singleton();
553 $file_log = self
::createDebugLogger($prefix);
554 $file_log->log("$message\n", $priority);
556 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
557 if ($out && CRM_Core_Permission
::check('view debug output')) {
562 if (!isset(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
563 // Set it to FALSE first & then try to set it. This is to prevent a loop as calling
564 // $config->userFrameworkLogging can trigger DB queries & under log mode this
565 // then gets called again.
566 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = FALSE;
567 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = $config->userFrameworkLogging
;
570 if (!empty(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
571 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
572 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
573 watchdog('civicrm', '%message', ['%message' => $message], $priority ?? WATCHDOG_DEBUG
);
581 * Append to the query log (if enabled)
583 * @param string $string
585 public static function debug_query($string) {
586 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
587 if (CIVICRM_DEBUG_LOG_QUERY
=== 'backtrace') {
588 CRM_Core_Error
::backtrace($string, TRUE);
590 elseif (CIVICRM_DEBUG_LOG_QUERY
) {
591 CRM_Core_Error
::debug_var('Query', $string, TRUE, TRUE, 'sql_log', PEAR_LOG_DEBUG
);
597 * Execute a query and log the results.
599 * @param string $query
601 public static function debug_query_result($query) {
602 $results = CRM_Core_DAO
::executeQuery($query)->fetchAll();
603 CRM_Core_Error
::debug_var('dao result', ['query' => $query, 'results' => $results], TRUE, TRUE, '', PEAR_LOG_DEBUG
);
607 * Obtain a reference to the error log.
609 * @param string $prefix
613 public static function createDebugLogger($prefix = '') {
614 self
::generateLogFileName($prefix);
615 return Log
::singleton('file', \Civi
::$statics[__CLASS__
]['logger_file' . $prefix], '');
619 * Generate a hash for the logfile.
623 * @param CRM_Core_Config $config
627 public static function generateLogFileHash($config) {
628 // Use multiple (but stable) inputs for hash information.
630 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: 'NO_SITE_KEY',
631 $config->userFrameworkBaseURL
,
635 // Trim 8 chars off the string, make it slightly easier to find
636 // but reveals less information from the hash.
637 return substr(md5(var_export($md5inputs, 1)), 8);
641 * Generate the name of the logfile to use and store it as a static.
643 * This function includes simplistic log rotation and a check as to whether
646 * @param string $prefix
648 protected static function generateLogFileName($prefix) {
649 if (!isset(\Civi
::$statics[__CLASS__
]['logger_file' . $prefix])) {
650 $config = CRM_Core_Config
::singleton();
652 $prefixString = $prefix ?
($prefix . '.') : '';
654 $hash = self
::generateLogFileHash($config);
655 $fileName = $config->configAndLogDir
. 'CiviCRM.' . $prefixString . $hash . '.log';
657 // Roll log file monthly or if greater than 256M.
658 // Size-based rotation introduced in response to filesize limits on
659 // certain OS/PHP combos.
660 if (file_exists($fileName)) {
661 $fileTime = date("Ym", filemtime($fileName));
662 $fileSize = filesize($fileName);
663 if (($fileTime < date('Ym')) ||
664 ($fileSize > 256 * 1024 * 1024) ||
668 $fileName . '.' . date('YmdHi')
672 \Civi
::$statics[__CLASS__
]['logger_file' . $prefix] = $fileName;
680 public static function backtrace($msg = 'backTrace', $log = FALSE) {
681 $backTrace = debug_backtrace();
682 $message = self
::formatBacktrace($backTrace);
684 CRM_Core_Error
::debug($msg, $message);
687 CRM_Core_Error
::debug_var($msg, $message, TRUE, TRUE, '', PEAR_LOG_DEBUG
);
692 * Render a backtrace array as a string.
694 * @param array $backTrace
695 * Array of stack frames.
696 * @param bool $showArgs
697 * 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.
698 * @param int $maxArgLen
699 * Maximum number of characters to show from each argument string.
701 * printable plain-text
703 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
705 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
706 $message .= sprintf("#%s %s\n", $idx, $trace);
708 $message .= sprintf("#%s {main}\n", 1 +
$idx);
713 * Render a backtrace array as an array.
715 * @param array $backTrace
716 * Array of stack frames.
717 * @param bool $showArgs
718 * 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.
719 * @param int $maxArgLen
720 * Maximum number of characters to show from each argument string.
722 * @see debug_backtrace
723 * @see Exception::getTrace()
725 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
727 foreach ($backTrace as $trace) {
729 $fnName = $trace['function'] ??
NULL;
730 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
732 // Do not show args for a few password related functions
733 $skipArgs = $className == 'DB::' && $fnName == 'connect';
735 if (!empty($trace['args'])) {
736 foreach ($trace['args'] as $arg) {
737 if (!$showArgs ||
$skipArgs) {
738 $args[] = '(' . gettype($arg) . ')';
741 switch ($type = gettype($arg)) {
743 $args[] = $arg ?
'TRUE' : 'FALSE';
752 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
756 $args[] = '(Array:' . count($arg) . ')';
760 $args[] = 'Object(' . get_class($arg) . ')';
764 $args[] = 'Resource';
780 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
781 CRM_Utils_Array
::value('line', $trace, ''),
791 * Render an exception as HTML string.
793 * @param Exception $e
795 * printable HTML text
797 public static function formatHtmlException(Exception
$e) {
800 // Exception metadata
802 // Exception backtrace
803 if ($e instanceof PEAR_Exception
) {
805 while (is_callable([$ei, 'getCause'])) {
806 // DB_ERROR doesn't have a getCause but does have a __call function which tricks is_callable.
807 if (!$ei instanceof DB_Error
) {
808 if ($ei->getCause() instanceof PEAR_Error
) {
809 $msg .= '<table class="crm-db-error">';
810 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
812 foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) {
813 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func([$ei->getCause(), "get$f"]));
815 $msg .= '</tbody></table>';
817 $ei = $ei->getCause();
820 $msg .= $e->toHtml();
823 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
824 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
830 * Write details of an exception to the log.
832 * @param Exception $e
834 * printable plain text
836 public static function formatTextException(Exception
$e) {
837 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
840 while (is_callable([$ei, 'getCause'])) {
841 // DB_ERROR doesn't have a getCause but does have a __call function which tricks is_callable.
842 if (!$ei instanceof DB_Error
) {
843 if ($ei->getCause() instanceof PEAR_Error
) {
844 foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) {
845 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func([$ei->getCause(), "get$f"]));
848 $ei = $ei->getCause();
850 // if we have reached a DB_Error assume that is the end of the road.
855 $msg .= self
::formatBacktrace($e->getTrace());
862 * @param string $level
863 * @param array $params
867 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
868 $error = CRM_Core_Error
::singleton();
869 $error->push($code, $level, [$params], $message);
874 * Set a status message in the session, then bounce back to the referrer.
876 * @param string $status
877 * The status message to set.
879 * @param null $redirect
880 * @param string $title
882 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
883 $session = CRM_Core_Session
::singleton();
885 $redirect = $session->readUserContext();
887 if ($title === NULL) {
888 $title = ts('Error');
890 $session->setStatus($status, $title, 'alert', ['expires' => 0]);
891 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
892 CRM_Core_Page_AJAX
::returnJsonResponse(['status' => 'error']);
894 CRM_Utils_System
::redirect($redirect);
898 * Reset the error stack.
901 public static function reset() {
902 $error = self
::singleton();
903 $error->_errors
= [];
904 $error->_errorsByLevel
= [];
908 * PEAR error-handler which converts errors to exceptions
911 * @throws PEAR_Exception
913 public static function exceptionHandler($pearError) {
914 CRM_Core_Error
::debug_var('Fatal Error Details', self
::getErrorDetails($pearError), TRUE, TRUE, '', PEAR_LOG_ERR
);
915 CRM_Core_Error
::backtrace('backTrace', TRUE);
916 throw new PEAR_Exception($pearError->getMessage(), $pearError);
920 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
923 * The PEAR_ERROR object.
927 public static function nullHandler($obj) {
928 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}", FALSE, '', PEAR_LOG_ERR
);
929 CRM_Core_Error
::backtrace('backTrace', TRUE);
935 * This function is no longer used by v3 api.
936 * @fixme Some core files call it but it should be re-thought & renamed or removed
944 public static function &createAPIError($msg, $data = NULL) {
945 if (self
::$modeException) {
946 throw new Exception($msg, $data);
951 $values['is_error'] = 1;
952 $values['error_message'] = $msg;
954 $values = array_merge($values, $data);
962 public static function movedSiteError($file) {
963 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
967 echo "We could not write $file. Have you moved your site directory or server?<p>";
968 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
973 * Terminate execution abnormally.
975 * @param string $code
977 protected static function abend($code) {
978 // do a hard rollback of any pending transactions
979 // if we've come here, its because of some unexpected PEAR errors
980 CRM_Core_Transaction
::forceRollbackIfEnabled();
981 CRM_Utils_System
::civiExit($code);
985 * @param array $error
990 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
991 if (is_array($error) && !empty($error['is_error'])) {
992 $code = $error['error_message']['code'];
993 if ($code == $type) {
1001 * Output a deprecated function warning to log file. Deprecated class:function is automatically generated from calling function.
1004 * description of new method (eg. "buildOptions() method in the appropriate BAO object").
1006 public static function deprecatedFunctionWarning($newMethod) {
1007 $dbt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 2);
1008 $callerFunction = $dbt[1]['function'] ??
NULL;
1009 $callerClass = $dbt[1]['class'] ??
NULL;
1010 Civi
::log()->warning("Deprecated function $callerClass::$callerFunction, use $newMethod.", ['civi.tag' => 'deprecated']);
1015 $e = new PEAR_ErrorStack('CRM');
1016 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');