3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
36 require_once 'PEAR/ErrorStack.php';
37 require_once 'PEAR/Exception.php';
38 require_once 'CRM/Core/Exception.php';
43 class CRM_Exception
extends PEAR_Exception
{
45 * Redefine the exception so message isn't optional.
47 * Supported signatures:
48 * - PEAR_Exception(string $message);
49 * - PEAR_Exception(string $message, int $code);
50 * - PEAR_Exception(string $message, Exception $cause);
51 * - PEAR_Exception(string $message, Exception $cause, int $code);
52 * - PEAR_Exception(string $message, PEAR_Error $cause);
53 * - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
54 * - PEAR_Exception(string $message, array $causes);
55 * - PEAR_Exception(string $message, array $causes, int $code);
57 * @param string $message exception message
59 * @param Exception $previous
61 public function __construct($message = NULL, $code = 0, Exception
$previous = NULL) {
62 parent
::__construct($message, $code, $previous);
68 * Class CRM_Core_Error
70 class CRM_Core_Error
extends PEAR_ErrorStack
{
73 * Status code of various types of errors.
75 const FATAL_ERROR
= 2;
76 const DUPLICATE_CONTACT
= 8001;
77 const DUPLICATE_CONTRIBUTION
= 8002;
78 const DUPLICATE_PARTICIPANT
= 8003;
81 * We only need one instance of this object. So we use the singleton
82 * pattern and cache the instance in this variable
85 private static $_singleton = NULL;
88 * The logger object for this application.
91 private static $_log = NULL;
94 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
96 public static $modeException = NULL;
99 * Singleton function used to manage this object.
101 * @param null $package
102 * @param bool $msgCallback
103 * @param bool $contextCallback
104 * @param bool $throwPEAR_Error
105 * @param string $stackClass
107 * @return CRM_Core_Error
109 public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
110 if (self
::$_singleton === NULL) {
111 self
::$_singleton = new CRM_Core_Error('CiviCRM');
113 return self
::$_singleton;
119 public function __construct() {
120 parent
::__construct('CiviCRM');
122 $log = CRM_Core_Config
::getLog();
123 $this->setLogger($log);
125 // PEAR<=1.9.0 does not declare "static" properly.
126 if (!is_callable(array('PEAR', '__callStatic'))) {
127 $this->setDefaultCallback(array($this, 'handlePES'));
130 PEAR_ErrorStack
::setDefaultCallback(array($this, 'handlePES'));
136 * @param string $separator
138 * @return array|null|string
140 static public function getMessages(&$error, $separator = '<br />') {
141 if (is_a($error, 'CRM_Core_Error')) {
142 $errors = $error->getErrors();
144 foreach ($errors as $e) {
145 $message[] = $e['code'] . ': ' . $e['message'];
147 $message = implode($separator, $message);
150 elseif (is_a($error, 'Civi\Payment\Exception\PaymentProcessorException')) {
151 return $error->getMessage();
157 * Status display function specific to payment processor errors.
159 * @param string $separator
161 public static function displaySessionError(&$error, $separator = '<br />') {
162 $message = self
::getMessages($error, $separator);
164 $status = ts("Payment Processor Error message") . "{$separator} $message";
165 $session = CRM_Core_Session
::singleton();
166 $session->setStatus($status);
171 * Create the main callback method. this method centralizes error processing.
173 * the errors we expect are from the pear modules DB, DB_DataObject
174 * which currently use PEAR::raiseError to notify of error messages.
176 * @param object $pearError PEAR_Error
178 public static function handle($pearError) {
179 if (defined('CIVICRM_TEST')) {
180 return self
::simpleHandler($pearError);
183 // setup smarty with config, session and template location.
184 $template = CRM_Core_Smarty
::singleton();
185 $config = CRM_Core_Config
::singleton();
187 if ($config->backtrace
) {
191 // create the error array
192 $error = self
::getErrorDetails($pearError);
194 // We access connection info via _DB_DATAOBJECT instead
195 // of, e.g., calling getDatabaseConnection(), so that we
196 // can avoid infinite loops.
197 global $_DB_DATAOBJECT;
199 if (isset($_DB_DATAOBJECT['CONFIG']['database'])) {
200 $dao = new CRM_Core_DAO();
201 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
202 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
204 // FIXME: Polymorphism for the win.
205 if ($conn instanceof DB_mysqli
) {
206 $link = $conn->connection
;
207 if (mysqli_error($link)) {
208 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
209 mysqli_query($link, 'select 1'); // execute a dummy query to clear error stack
212 elseif ($conn instanceof DB_mysql
) {
214 $mysql_error = mysql_error() . ', ' . mysql_errno();
215 mysql_query('select 1'); // execute a dummy query to clear error stack
219 $mysql_error = 'fixme-unknown-db-cxn';
221 $template->assign_by_ref('mysql_code', $mysql_error);
225 $template->assign_by_ref('error', $error);
226 $errorDetails = CRM_Core_Error
::debug('', $error, FALSE);
227 $template->assign_by_ref('errorDetails', $errorDetails);
229 CRM_Core_Error
::debug_var('Fatal Error Details', $error);
230 CRM_Core_Error
::backtrace('backTrace', TRUE);
232 if ($config->initialized
) {
233 $content = $template->fetch('CRM/common/fatal.tpl');
234 echo CRM_Utils_System
::theme($content);
237 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
238 CRM_Core_Error
::debug(NULL, $error);
240 static $runOnce = FALSE;
249 * this function is used to trap and print errors
250 * during system initialization time. Hence the error
251 * message is quite ugly
255 public static function simpleHandler($pearError) {
257 $error = self
::getErrorDetails($pearError);
259 // ensure that debug does not check permissions since we are in bootstrap
260 // mode and need to print a decent message to help the user
261 CRM_Core_Error
::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
263 // always log the backtrace to a file
264 self
::backtrace('backTrace', TRUE);
270 * this function is used to return error details
274 * @return array $error
276 public static function getErrorDetails($pearError) {
277 // create the error array
279 $error['callback'] = $pearError->getCallback();
280 $error['code'] = $pearError->getCode();
281 $error['message'] = $pearError->getMessage();
282 $error['mode'] = $pearError->getMode();
283 $error['debug_info'] = $pearError->getDebugInfo();
284 $error['type'] = $pearError->getType();
285 $error['user_info'] = $pearError->getUserInfo();
286 $error['to_string'] = $pearError->toString();
292 * Handle errors raised using the PEAR Error Stack.
294 * currently the handler just requests the PES framework
295 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
297 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
299 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
300 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
301 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
303 * @param mixed $pearError
307 public static function handlePES($pearError) {
308 return PEAR_ERRORSTACK_PUSH
;
312 * Display an error page with an error message describing what happened.
315 * This is a really annoying function. We ❤ exceptions. Be exceptional!
319 * @param string $message
321 * @param string $code
322 * The error code if any.
323 * @param string $email
324 * The email address to notify of this situation.
328 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
330 'message' => $message,
334 if (self
::$modeException) {
336 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
337 CRM_Core_Error
::backtrace('backTrace', TRUE);
339 $details = 'A fatal error was triggered';
341 $details .= ': ' . $message;
343 throw new Exception($details, $code);
347 $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'));
350 if (php_sapi_name() == "cli") {
351 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
353 echo static::formatBacktrace(debug_backtrace());
355 // FIXME: Why doesn't this call abend()?
356 // Difference: abend() will cleanup transaction and (via civiExit) store session state
357 // self::abend(CRM_Core_Error::FATAL_ERROR);
360 $config = CRM_Core_Config
::singleton();
362 if ($config->fatalErrorHandler
&&
363 function_exists($config->fatalErrorHandler
)
365 $name = $config->fatalErrorHandler
;
368 // the call has been successfully handled
370 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
374 if ($config->backtrace
) {
378 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
379 CRM_Core_Error
::backtrace('backTrace', TRUE);
381 // If we are in an ajax callback, format output appropriately
382 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
385 '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>',
387 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
388 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
389 $message .= '<p><em>See console for backtrace</em></p>';
391 CRM_Core_Session
::setStatus($message, ts('Sorry an error occurred'), 'error');
392 CRM_Core_Transaction
::forceRollbackIfEnabled();
393 CRM_Core_Page_AJAX
::returnJsonResponse($out);
396 $template = CRM_Core_Smarty
::singleton();
397 $template->assign($vars);
398 $config->userSystem
->outputError($template->fetch('CRM/common/fatal.tpl'));
400 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
404 * Display an error page with an error message describing what happened.
406 * This function is evil -- it largely replicates fatal(). Hopefully the
407 * entire CRM_Core_Error system can be hollowed out and replaced with
408 * something that follows a cleaner separation of concerns.
410 * @param Exception $exception
412 public static function handleUnhandledException($exception) {
414 CRM_Utils_Hook
::unhandledException($exception);
416 catch (Exception
$other) {
417 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
418 CRM_Core_Error
::debug_var('handleUnhandledException_nestedException', self
::formatTextException($other));
420 $config = CRM_Core_Config
::singleton();
422 'message' => $exception->getMessage(),
424 'exception' => $exception,
426 if (!$vars['message']) {
427 $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'));
431 if (php_sapi_name() == "cli") {
432 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
433 print self
::formatTextException($exception);
435 // FIXME: Why doesn't this call abend()?
436 // Difference: abend() will cleanup transaction and (via civiExit) store session state
437 // self::abend(CRM_Core_Error::FATAL_ERROR);
440 // Case B: Custom error handler
441 if ($config->fatalErrorHandler
&&
442 function_exists($config->fatalErrorHandler
)
444 $name = $config->fatalErrorHandler
;
447 // the call has been successfully handled
449 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
453 // Case C: Default error handler
456 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, FALSE);
457 CRM_Core_Error
::backtrace('backTrace', TRUE);
460 $template = CRM_Core_Smarty
::singleton();
461 $template->assign($vars);
462 $content = $template->fetch('CRM/common/fatal.tpl');
463 if ($config->backtrace
) {
464 $content = self
::formatHtmlException($exception) . $content;
466 if ($config->userFramework
== 'Joomla' &&
467 class_exists('JError')
469 JError
::raiseError('CiviCRM-001', $content);
472 echo CRM_Utils_System
::theme($content);
476 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
480 * Outputs pre-formatted debug information. Flushes the buffers
481 * so we can interrupt a potential POST/redirect
483 * @param string $name name of debug section
484 * @param $variable mixed reference to variables that we need a trace of
485 * @param bool $log should we log or return the output
486 * @param bool $html whether to generate a HTML-escaped output
487 * @param bool $checkPermission should we check permissions before displaying output
488 * useful when we die during initialization and permissioning
489 * subsystem is not initialized - CRM-13765
492 * the generated output
494 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
495 $error = self
::singleton();
497 if ($variable === NULL) {
502 $out = print_r($variable, TRUE);
505 $out = htmlspecialchars($out);
507 $prefix = "<p>$name</p>";
509 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
513 $prefix = "$name:\n";
515 $out = "{$prefix}$out\n";
519 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
528 * Similar to the function debug. Only difference is
529 * in the formatting of the output.
531 * @param string $variable_name
533 * @param mixed $variable
536 * Use print_r (if true) or var_dump (if false).
538 * Log or return the output?
539 * @param string $prefix
540 * Prefix for output logfile.
543 * The generated output
545 * @see CRM_Core_Error::debug()
546 * @see CRM_Core_Error::debug_log_message()
548 public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '') {
549 // check if variable is set
550 if (!isset($variable)) {
551 $out = "\$$variable_name is not set";
555 $out = print_r($variable, TRUE);
556 $out = "\$$variable_name = $out";
562 $dump = ob_get_contents();
564 $out = "\n\$$variable_name = $dump";
566 // reset if it is an array
567 if (is_array($variable)) {
571 return self
::debug_log_message($out, FALSE, $prefix);
575 * Display the error message on terminal and append it to the log file.
577 * Provided the user has the 'view debug output' the output should be displayed. In all
578 * cases it should be logged.
580 * @param string $message
582 * Should we log or return the output.
584 * @param string $prefix
586 * @param string $priority
589 * Format of the backtrace
591 public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) {
592 $config = CRM_Core_Config
::singleton();
594 $file_log = self
::createDebugLogger($prefix);
595 $file_log->log("$message\n", $priority);
597 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
598 if ($out && CRM_Core_Permission
::check('view debug output')) {
603 if (!isset(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
604 // Set it to FALSE first & then try to set it. This is to prevent a loop as calling
605 // $config->userFrameworkLogging can trigger DB queries & under log mode this
606 // then gets called again.
607 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = FALSE;
608 \Civi
::$statics[__CLASS__
]['userFrameworkLogging'] = $config->userFrameworkLogging
;
611 if (!empty(\Civi
::$statics[__CLASS__
]['userFrameworkLogging'])) {
612 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
613 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
614 watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG
);
622 * Append to the query log (if enabled)
624 * @param string $string
626 public static function debug_query($string) {
627 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
628 if (CIVICRM_DEBUG_LOG_QUERY
=== 'backtrace') {
629 CRM_Core_Error
::backtrace($string, TRUE);
631 elseif (CIVICRM_DEBUG_LOG_QUERY
) {
632 CRM_Core_Error
::debug_var('Query', $string, TRUE, TRUE, 'sql_log');
638 * Execute a query and log the results.
640 * @param string $query
642 public static function debug_query_result($query) {
643 $results = CRM_Core_DAO
::executeQuery($query)->fetchAll();
644 CRM_Core_Error
::debug_var('dao result', array('query' => $query, 'results' => $results));
648 * Obtain a reference to the error log.
650 * @param string $prefix
654 public static function createDebugLogger($prefix = '') {
655 self
::generateLogFileName($prefix);
656 return Log
::singleton('file', \Civi
::$statics[__CLASS__
]['logger_file' . $prefix], '');
660 * Generate a hash for the logfile.
664 * @param CRM_Core_Config $config
668 public static function generateLogFileHash($config) {
669 // Use multiple (but stable) inputs for hash information.
671 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: 'NO_SITE_KEY',
672 $config->userFrameworkBaseURL
,
676 // Trim 8 chars off the string, make it slightly easier to find
677 // but reveals less information from the hash.
678 return substr(md5(var_export($md5inputs, 1)), 8);
682 * Generate the name of the logfile to use and store it as a static.
684 * This function includes simplistic log rotation and a check as to whether
687 * @param string $prefix
689 protected static function generateLogFileName($prefix) {
690 if (!isset(\Civi
::$statics[__CLASS__
]['logger_file' . $prefix])) {
691 $config = CRM_Core_Config
::singleton();
693 $prefixString = $prefix ?
($prefix . '.') : '';
695 $hash = self
::generateLogFileHash($config);
696 $fileName = $config->configAndLogDir
. 'CiviCRM.' . $prefixString . $hash . '.log';
698 // Roll log file monthly or if greater than 256M.
699 // Size-based rotation introduced in response to filesize limits on
700 // certain OS/PHP combos.
701 if (file_exists($fileName)) {
702 $fileTime = date("Ym", filemtime($fileName));
703 $fileSize = filesize($fileName);
704 if (($fileTime < date('Ym')) ||
705 ($fileSize > 256 * 1024 * 1024) ||
709 $fileName . '.' . date('YmdHi')
713 \Civi
::$statics[__CLASS__
]['logger_file' . $prefix] = $fileName;
721 public static function backtrace($msg = 'backTrace', $log = FALSE) {
722 $backTrace = debug_backtrace();
723 $message = self
::formatBacktrace($backTrace);
725 CRM_Core_Error
::debug($msg, $message);
728 CRM_Core_Error
::debug_var($msg, $message);
733 * Render a backtrace array as a string.
735 * @param array $backTrace
736 * Array of stack frames.
737 * @param bool $showArgs
738 * 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.
739 * @param int $maxArgLen
740 * Maximum number of characters to show from each argument string.
742 * printable plain-text
744 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
746 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
747 $message .= sprintf("#%s %s\n", $idx, $trace);
749 $message .= sprintf("#%s {main}\n", 1 +
$idx);
754 * Render a backtrace array as an array.
756 * @param array $backTrace
757 * Array of stack frames.
758 * @param bool $showArgs
759 * 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.
760 * @param int $maxArgLen
761 * Maximum number of characters to show from each argument string.
763 * @see debug_backtrace
764 * @see Exception::getTrace()
766 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
768 foreach ($backTrace as $trace) {
770 $fnName = CRM_Utils_Array
::value('function', $trace);
771 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
773 // Do not show args for a few password related functions
774 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
776 if (!empty($trace['args'])) {
777 foreach ($trace['args'] as $arg) {
778 if (!$showArgs ||
$skipArgs) {
779 $args[] = '(' . gettype($arg) . ')';
782 switch ($type = gettype($arg)) {
784 $args[] = $arg ?
'TRUE' : 'FALSE';
793 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
797 $args[] = '(Array:' . count($arg) . ')';
801 $args[] = 'Object(' . get_class($arg) . ')';
805 $args[] = 'Resource';
821 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
822 CRM_Utils_Array
::value('line', $trace, ''),
832 * Render an exception as HTML string.
834 * @param Exception $e
836 * printable HTML text
838 public static function formatHtmlException(Exception
$e) {
841 // Exception metadata
843 // Exception backtrace
844 if ($e instanceof PEAR_Exception
) {
846 while (is_callable(array($ei, 'getCause'))) {
847 if ($ei->getCause() instanceof PEAR_Error
) {
848 $msg .= '<table class="crm-db-error">';
849 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
851 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
852 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
854 $msg .= '</tbody></table>';
856 $ei = $ei->getCause();
858 $msg .= $e->toHtml();
861 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
862 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
868 * Write details of an exception to the log.
870 * @param Exception $e
872 * printable plain text
874 public static function formatTextException(Exception
$e) {
875 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
878 while (is_callable(array($ei, 'getCause'))) {
879 if ($ei->getCause() instanceof PEAR_Error
) {
880 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
881 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
884 $ei = $ei->getCause();
886 $msg .= self
::formatBacktrace($e->getTrace());
893 * @param string $level
894 * @param array $params
898 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
899 $error = CRM_Core_Error
::singleton();
900 $error->push($code, $level, array($params), $message);
905 * Set a status message in the session, then bounce back to the referrer.
907 * @param string $status
908 * The status message to set.
910 * @param null $redirect
911 * @param string $title
913 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
914 $session = CRM_Core_Session
::singleton();
916 $redirect = $session->readUserContext();
918 if ($title === NULL) {
919 $title = ts('Error');
921 $session->setStatus($status, $title, 'alert', array('expires' => 0));
922 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
923 CRM_Core_Page_AJAX
::returnJsonResponse(array('status' => 'error'));
925 CRM_Utils_System
::redirect($redirect);
929 * Reset the error stack.
932 public static function reset() {
933 $error = self
::singleton();
934 $error->_errors
= array();
935 $error->_errorsByLevel
= array();
939 * PEAR error-handler which converts errors to exceptions
942 * @throws PEAR_Exception
944 public static function exceptionHandler($pearError) {
945 CRM_Core_Error
::debug_var('Fatal Error Details', self
::getErrorDetails($pearError));
946 CRM_Core_Error
::backtrace('backTrace', TRUE);
947 throw new PEAR_Exception($pearError->getMessage(), $pearError);
951 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
954 * The PEAR_ERROR object.
958 public static function nullHandler($obj) {
959 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
960 CRM_Core_Error
::backtrace('backTrace', TRUE);
966 * This function is no longer used by v3 api.
967 * @fixme Some core files call it but it should be re-thought & renamed or removed
975 public static function &createAPIError($msg, $data = NULL) {
976 if (self
::$modeException) {
977 throw new Exception($msg, $data);
982 $values['is_error'] = 1;
983 $values['error_message'] = $msg;
985 $values = array_merge($values, $data);
993 public static function movedSiteError($file) {
994 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
998 echo "We could not write $file. Have you moved your site directory or server?<p>";
999 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
1004 * Terminate execution abnormally.
1006 * @param string $code
1008 protected static function abend($code) {
1009 // do a hard rollback of any pending transactions
1010 // if we've come here, its because of some unexpected PEAR errors
1011 CRM_Core_Transaction
::forceRollbackIfEnabled();
1012 CRM_Utils_System
::civiExit($code);
1016 * @param array $error
1021 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
1022 if (is_array($error) && !empty($error['is_error'])) {
1023 $code = $error['error_message']['code'];
1024 if ($code == $type) {
1032 * Output a deprecated function warning to log file. Deprecated class:function is automatically generated from calling function.
1035 * description of new method (eg. "buildOptions() method in the appropriate BAO object").
1037 public static function deprecatedFunctionWarning($newMethod) {
1038 $dbt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
, 2);
1039 $callerFunction = isset($dbt[1]['function']) ?
$dbt[1]['function'] : NULL;
1040 $callerClass = isset($dbt[1]['class']) ?
$dbt[1]['class'] : NULL;
1041 Civi
::log()->warning("Deprecated function $callerClass::$callerFunction, use $newMethod.", array('civi.tag' => 'deprecated'));
1046 $e = new PEAR_ErrorStack('CRM');
1047 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');