3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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
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);
156 * Status display function specific to payment processor errors.
158 * @param string $separator
160 public static function displaySessionError(&$error, $separator = '<br />') {
161 $message = self
::getMessages($error, $separator);
163 $status = ts("Payment Processor Error message") . "{$separator} $message";
164 $session = CRM_Core_Session
::singleton();
165 $session->setStatus($status);
170 * Create the main callback method. this method centralizes error processing.
172 * the errors we expect are from the pear modules DB, DB_DataObject
173 * which currently use PEAR::raiseError to notify of error messages.
175 * @param object $pearError PEAR_Error
177 public static function handle($pearError) {
178 if (defined('CIVICRM_TEST')) {
179 return self
::simpleHandler($pearError);
182 // setup smarty with config, session and template location.
183 $template = CRM_Core_Smarty
::singleton();
184 $config = CRM_Core_Config
::singleton();
186 if ($config->backtrace
) {
190 // create the error array
191 $error = self
::getErrorDetails($pearError);
193 // We access connection info via _DB_DATAOBJECT instead
194 // of, e.g., calling getDatabaseConnection(), so that we
195 // can avoid infinite loops.
196 global $_DB_DATAOBJECT;
198 if (!isset($_DB_DATAOBJECT['CONFIG']['database'])) {
199 // we haven't setup sql, so it's not our sql error...
201 elseif (preg_match('/^mysql:/', $_DB_DATAOBJECT['CONFIG']['database']) &&
204 $mysql_error = mysql_error() . ', ' . mysql_errno();
205 $template->assign_by_ref('mysql_code', $mysql_error);
207 // execute a dummy query to clear error stack
208 mysql_query('select 1');
210 elseif (preg_match('/^mysqli:/', $_DB_DATAOBJECT['CONFIG']['database'])) {
211 $dao = new CRM_Core_DAO();
213 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
])) {
214 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
215 $link = $conn->connection
;
217 if (mysqli_error($link)) {
218 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
219 $template->assign_by_ref('mysql_code', $mysql_error);
221 // execute a dummy query to clear error stack
222 mysqli_query($link, 'select 1');
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.
316 * @param string $message
318 * @param string $code
319 * The error code if any.
320 * @param string $email
321 * The email address to notify of this situation.
325 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
327 'message' => htmlspecialchars($message),
331 if (self
::$modeException) {
333 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
334 CRM_Core_Error
::backtrace('backTrace', TRUE);
336 $details = 'A fatal error was triggered';
338 $details .= ': ' . $message;
340 throw new Exception($details, $code);
344 $message = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/'));
347 if (php_sapi_name() == "cli") {
348 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
350 echo static::formatBacktrace(debug_backtrace());
352 // FIXME: Why doesn't this call abend()?
353 // Difference: abend() will cleanup transaction and (via civiExit) store session state
354 // self::abend(CRM_Core_Error::FATAL_ERROR);
357 $config = CRM_Core_Config
::singleton();
359 if ($config->fatalErrorHandler
&&
360 function_exists($config->fatalErrorHandler
)
362 $name = $config->fatalErrorHandler
;
365 // the call has been successfully handled
367 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
371 if ($config->backtrace
) {
375 CRM_Core_Error
::debug_var('Fatal Error Details', $vars);
376 CRM_Core_Error
::backtrace('backTrace', TRUE);
378 // If we are in an ajax callback, format output appropriately
379 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
382 '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>',
384 if ($config->backtrace
&& CRM_Core_Permission
::check('view debug output')) {
385 $out['backtrace'] = self
::parseBacktrace(debug_backtrace());
386 $message .= '<p><em>See console for backtrace</em></p>';
388 CRM_Core_Session
::setStatus($message, ts('Sorry an error occurred'), 'error');
389 CRM_Core_Transaction
::forceRollbackIfEnabled();
390 CRM_Core_Page_AJAX
::returnJsonResponse($out);
393 $template = CRM_Core_Smarty
::singleton();
394 $template->assign($vars);
395 $config->userSystem
->outputError($template->fetch('CRM/common/fatal.tpl'));
397 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
401 * Display an error page with an error message describing what happened.
403 * This function is evil -- it largely replicates fatal(). Hopefully the
404 * entire CRM_Core_Error system can be hollowed out and replaced with
405 * something that follows a cleaner separation of concerns.
407 * @param Exception $exception
409 public static function handleUnhandledException($exception) {
411 CRM_Utils_Hook
::unhandledException($exception);
413 catch (Exception
$other) {
414 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
415 CRM_Core_Error
::debug_var('handleUnhandledException_nestedException', self
::formatTextException($other));
417 $config = CRM_Core_Config
::singleton();
419 'message' => $exception->getMessage(),
421 'exception' => $exception,
423 if (!$vars['message']) {
424 $vars['message'] = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/'));
428 if (php_sapi_name() == "cli") {
429 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
430 print self
::formatTextException($exception);
432 // FIXME: Why doesn't this call abend()?
433 // Difference: abend() will cleanup transaction and (via civiExit) store session state
434 // self::abend(CRM_Core_Error::FATAL_ERROR);
437 // Case B: Custom error handler
438 if ($config->fatalErrorHandler
&&
439 function_exists($config->fatalErrorHandler
)
441 $name = $config->fatalErrorHandler
;
444 // the call has been successfully handled
446 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
450 // Case C: Default error handler
453 CRM_Core_Error
::debug_var('Fatal Error Details', $vars, FALSE);
454 CRM_Core_Error
::backtrace('backTrace', TRUE);
457 $template = CRM_Core_Smarty
::singleton();
458 $template->assign($vars);
459 $content = $template->fetch('CRM/common/fatal.tpl');
460 if ($config->backtrace
) {
461 $content = self
::formatHtmlException($exception) . $content;
463 if ($config->userFramework
== 'Joomla' &&
464 class_exists('JError')
466 JError
::raiseError('CiviCRM-001', $content);
469 echo CRM_Utils_System
::theme($content);
473 self
::abend(CRM_Core_Error
::FATAL_ERROR
);
477 * Outputs pre-formatted debug information. Flushes the buffers
478 * so we can interrupt a potential POST/redirect
480 * @param string $name name of debug section
481 * @param $variable mixed reference to variables that we need a trace of
482 * @param bool $log should we log or return the output
483 * @param bool $html whether to generate a HTML-escaped output
484 * @param bool $checkPermission should we check permissions before displaying output
485 * useful when we die during initialization and permissioning
486 * subsystem is not initialized - CRM-13765
489 * the generated output
491 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
492 $error = self
::singleton();
494 if ($variable === NULL) {
499 $out = print_r($variable, TRUE);
502 $out = htmlspecialchars($out);
504 $prefix = "<p>$name</p>";
506 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
510 $prefix = "$name:\n";
512 $out = "{$prefix}$out\n";
516 (!$checkPermission || CRM_Core_Permission
::check('view debug output'))
525 * Similar to the function debug. Only difference is
526 * in the formatting of the output.
528 * @param string $variable_name
529 * @param mixed $variable
531 * Should we use print_r ? (else we use var_dump).
533 * Should we log or return the output.
534 * @param string $comp
538 * the generated output
542 * @see CRM_Core_Error::debug()
543 * @see CRM_Core_Error::debug_log_message()
545 public static function debug_var(
552 // check if variable is set
553 if (!isset($variable)) {
554 $out = "\$$variable_name is not set";
558 $out = print_r($variable, TRUE);
559 $out = "\$$variable_name = $out";
565 $dump = ob_get_contents();
567 $out = "\n\$$variable_name = $dump";
569 // reset if it is an array
570 if (is_array($variable)) {
574 return self
::debug_log_message($out, FALSE, $comp);
578 * Display the error message on terminal and append it to the log file.
580 * Provided the user has the 'view debug output' the output should be displayed. In all
581 * cases it should be logged.
583 * @param string $message
585 * Should we log or return the output.
587 * @param string $comp
588 * Message to be output.
589 * @param string $priority
592 * Format of the backtrace
594 public static function debug_log_message($message, $out = FALSE, $comp = '', $priority = NULL) {
595 $config = CRM_Core_Config
::singleton();
597 $file_log = self
::createDebugLogger($comp);
598 $file_log->log("$message\n", $priority);
600 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
601 if ($out && CRM_Core_Permission
::check('view debug output')) {
606 if (!empty($config->userFrameworkLogging
)) {
607 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
608 if ($config->userSystem
->is_drupal
and function_exists('watchdog')) {
609 watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG
);
617 * Append to the query log (if enabled)
619 * @param string $string
621 public static function debug_query($string) {
622 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
623 if (CIVICRM_DEBUG_LOG_QUERY
=== 'backtrace') {
624 CRM_Core_Error
::backtrace($string, TRUE);
626 elseif (CIVICRM_DEBUG_LOG_QUERY
) {
627 CRM_Core_Error
::debug_var('Query', $string, TRUE, TRUE, 'sql_log');
633 * Execute a query and log the results.
635 * @param string $query
637 public static function debug_query_result($query) {
638 $results = CRM_Core_DAO
::executeQuery($query)->fetchAll();
639 CRM_Core_Error
::debug_var('dao result', array('query' => $query, 'results' => $results));
643 * Obtain a reference to the error log.
645 * @param string $prefix
649 public static function createDebugLogger($prefix = '') {
650 self
::generateLogFileName($prefix);
651 return Log
::singleton('file', \Civi
::$statics[__CLASS__
]['logger_file' . $prefix], '');
655 * Generate a hash for the logfile.
658 public static function generateLogFileHash($config) {
659 // Use multiple (but stable) inputs for hash information.
661 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY
: 'NO_SITE_KEY',
662 $config->userFrameworkBaseURL
,
666 // Trim 8 chars off the string, make it slightly easier to find
667 // but reveals less information from the hash.
668 return substr(md5(var_export($md5inputs, 1)), 8);
672 * Generate the name of the logfile to use and store it as a static.
674 * This function includes poor man's log file management and a check as to whether the file exists.
676 * @param string $prefix
678 protected static function generateLogFileName($prefix) {
679 if (!isset(\Civi
::$statics[__CLASS__
]['logger_file' . $prefix])) {
680 $config = CRM_Core_Config
::singleton();
682 $prefixString = $prefix ?
($prefix . '.') : '';
684 $hash = self
::generateLogFileHash($config);
685 $fileName = $config->configAndLogDir
. 'CiviCRM.' . $prefixString . $hash . '.log';
687 // Roll log file monthly or if greater than 256M
688 // note that PHP file functions have a limit of 2G and hence
689 // the alternative was introduce
690 if (file_exists($fileName)) {
691 $fileTime = date("Ym", filemtime($fileName));
692 $fileSize = filesize($fileName);
693 if (($fileTime < date('Ym')) ||
694 ($fileSize > 256 * 1024 * 1024) ||
698 $fileName . '.' . date('YmdHi')
702 \Civi
::$statics[__CLASS__
]['logger_file' . $prefix] = $fileName;
710 public static function backtrace($msg = 'backTrace', $log = FALSE) {
711 $backTrace = debug_backtrace();
712 $message = self
::formatBacktrace($backTrace);
714 CRM_Core_Error
::debug($msg, $message);
717 CRM_Core_Error
::debug_var($msg, $message);
722 * Render a backtrace array as a string.
724 * @param array $backTrace
725 * Array of stack frames.
726 * @param bool $showArgs
727 * 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.
728 * @param int $maxArgLen
729 * Maximum number of characters to show from each argument string.
731 * printable plain-text
733 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
735 foreach (self
::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
736 $message .= sprintf("#%s %s\n", $idx, $trace);
738 $message .= sprintf("#%s {main}\n", 1 +
$idx);
743 * Render a backtrace array as an array.
745 * @param array $backTrace
746 * Array of stack frames.
747 * @param bool $showArgs
748 * 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.
749 * @param int $maxArgLen
750 * Maximum number of characters to show from each argument string.
752 * @see debug_backtrace
753 * @see Exception::getTrace()
755 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
757 foreach ($backTrace as $trace) {
759 $fnName = CRM_Utils_Array
::value('function', $trace);
760 $className = isset($trace['class']) ?
($trace['class'] . $trace['type']) : '';
762 // Do not show args for a few password related functions
763 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ?
TRUE : FALSE;
765 if (!empty($trace['args'])) {
766 foreach ($trace['args'] as $arg) {
767 if (!$showArgs ||
$skipArgs) {
768 $args[] = '(' . gettype($arg) . ')';
771 switch ($type = gettype($arg)) {
773 $args[] = $arg ?
'TRUE' : 'FALSE';
782 $args[] = '"' . CRM_Utils_String
::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
786 $args[] = '(Array:' . count($arg) . ')';
790 $args[] = 'Object(' . get_class($arg) . ')';
794 $args[] = 'Resource';
810 CRM_Utils_Array
::value('file', $trace, '[internal function]'),
811 CRM_Utils_Array
::value('line', $trace, ''),
821 * Render an exception as HTML string.
823 * @param Exception $e
825 * printable HTML text
827 public static function formatHtmlException(Exception
$e) {
830 // Exception metadata
832 // Exception backtrace
833 if ($e instanceof PEAR_Exception
) {
835 while (is_callable(array($ei, 'getCause'))) {
836 if ($ei->getCause() instanceof PEAR_Error
) {
837 $msg .= '<table class="crm-db-error">';
838 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
840 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
841 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
843 $msg .= '</tbody></table>';
845 $ei = $ei->getCause();
847 $msg .= $e->toHtml();
850 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
851 $msg .= '<pre>' . htmlentities(self
::formatBacktrace($e->getTrace())) . '</pre>';
857 * Write details of an exception to the log.
859 * @param Exception $e
861 * printable plain text
863 public static function formatTextException(Exception
$e) {
864 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
867 while (is_callable(array($ei, 'getCause'))) {
868 if ($ei->getCause() instanceof PEAR_Error
) {
869 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
870 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
873 $ei = $ei->getCause();
875 $msg .= self
::formatBacktrace($e->getTrace());
882 * @param string $level
883 * @param array $params
887 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
888 $error = CRM_Core_Error
::singleton();
889 $error->push($code, $level, array($params), $message);
894 * Set a status message in the session, then bounce back to the referrer.
896 * @param string $status
897 * The status message to set.
899 * @param null $redirect
900 * @param string $title
902 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
903 $session = CRM_Core_Session
::singleton();
905 $redirect = $session->readUserContext();
907 if ($title === NULL) {
908 $title = ts('Error');
910 $session->setStatus($status, $title, 'alert', array('expires' => 0));
911 if (CRM_Utils_Array
::value('snippet', $_REQUEST) === CRM_Core_Smarty
::PRINT_JSON
) {
912 CRM_Core_Page_AJAX
::returnJsonResponse(array('status' => 'error'));
914 CRM_Utils_System
::redirect($redirect);
918 * Reset the error stack.
921 public static function reset() {
922 $error = self
::singleton();
923 $error->_errors
= array();
924 $error->_errorsByLevel
= array();
928 * PEAR error-handler which converts errors to exceptions
931 * @throws PEAR_Exception
933 public static function exceptionHandler($pearError) {
934 CRM_Core_Error
::debug_var('Fatal Error Details', self
::getErrorDetails($pearError));
935 CRM_Core_Error
::backtrace('backTrace', TRUE);
936 throw new PEAR_Exception($pearError->getMessage(), $pearError);
940 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
943 * The PEAR_ERROR object.
947 public static function nullHandler($obj) {
948 CRM_Core_Error
::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
949 CRM_Core_Error
::backtrace('backTrace', TRUE);
955 * This function is no longer used by v3 api.
956 * @fixme Some core files call it but it should be re-thought & renamed or removed
964 public static function &createAPIError($msg, $data = NULL) {
965 if (self
::$modeException) {
966 throw new Exception($msg, $data);
971 $values['is_error'] = 1;
972 $values['error_message'] = $msg;
974 $values = array_merge($values, $data);
982 public static function movedSiteError($file) {
983 $url = CRM_Utils_System
::url('civicrm/admin/setting/updateConfigBackend',
987 echo "We could not write $file. Have you moved your site directory or server?<p>";
988 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
993 * Terminate execution abnormally.
995 * @param string $code
997 protected static function abend($code) {
998 // do a hard rollback of any pending transactions
999 // if we've come here, its because of some unexpected PEAR errors
1000 CRM_Core_Transaction
::forceRollbackIfEnabled();
1001 CRM_Utils_System
::civiExit($code);
1005 * @param array $error
1010 public static function isAPIError($error, $type = CRM_Core_Error
::FATAL_ERROR
) {
1011 if (is_array($error) && !empty($error['is_error'])) {
1012 $code = $error['error_message']['code'];
1013 if ($code == $type) {
1022 $e = new PEAR_ErrorStack('CRM');
1023 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');