Error handling - Replace calls to CRM_Core_Error::ignoreException with CRM_Core_Tempo...
[civicrm-core.git] / CRM / Core / Error.php
CommitLineData
6a488035
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
232624b1 5 | CiviCRM version 4.4 |
6a488035
TO
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27*/
28
29/**
30 * Start of the Error framework. We should check out and inherit from
31 * PEAR_ErrorStack and use that framework
32 *
33 * @package CRM
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * $Id$
36 *
37 */
38
39require_once 'PEAR/ErrorStack.php';
40require_once 'PEAR/Exception.php';
dcc4f6a7 41require_once 'CRM/Core/Exception.php';
6a488035
TO
42
43require_once 'Log.php';
44class CRM_Exception extends PEAR_Exception {
45 // Redefine the exception so message isn't optional
46 public function __construct($message = NULL, $code = 0, Exception$previous = NULL) {
47 parent::__construct($message, $code, $previous);
48 }
49}
50
51class CRM_Core_Error extends PEAR_ErrorStack {
52
53 /**
54 * status code of various types of errors
55 * @var const
56 */
57 CONST FATAL_ERROR = 2;
58 CONST DUPLICATE_CONTACT = 8001;
59 CONST DUPLICATE_CONTRIBUTION = 8002;
60 CONST DUPLICATE_PARTICIPANT = 8003;
61
62 /**
63 * We only need one instance of this object. So we use the singleton
64 * pattern and cache the instance in this variable
65 * @var object
66 * @static
67 */
68 private static $_singleton = NULL;
69
70 /**
71 * The logger object for this application
72 * @var object
73 * @static
74 */
75 private static $_log = NULL;
76
77 /**
78 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
79 * @static
80 */
81 public static $modeException = NULL;
82
83 /**
84 * singleton function used to manage this object.
85 *
86 * @return object
87 * @static
88 */
89 static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
90 if (self::$_singleton === NULL) {
91 self::$_singleton = new CRM_Core_Error('CiviCRM');
92 }
93 return self::$_singleton;
94 }
95
96 /**
97 * construcor
98 */
99 function __construct() {
100 parent::__construct('CiviCRM');
101
102 $log = CRM_Core_Config::getLog();
103 $this->setLogger($log);
104
105 // set up error handling for Pear Error Stack
106 $this->setDefaultCallback(array($this, 'handlePES'));
107 }
108
93a11cd6 109 static public function getMessages(&$error, $separator = '<br />') {
6a488035
TO
110 if (is_a($error, 'CRM_Core_Error')) {
111 $errors = $error->getErrors();
112 $message = array();
113 foreach ($errors as $e) {
114 $message[] = $e['code'] . ': ' . $e['message'];
115 }
116 $message = implode($separator, $message);
117 return $message;
118 }
119 return NULL;
120 }
121
122 function displaySessionError(&$error, $separator = '<br />') {
123 $message = self::getMessages($error, $separator);
124 if ($message) {
125 $status = ts("Payment Processor Error message") . "{$separator} $message";
126 $session = CRM_Core_Session::singleton();
127 $session->setStatus($status);
128 }
129 }
130
131 /**
132 * create the main callback method. this method centralizes error processing.
133 *
134 * the errors we expect are from the pear modules DB, DB_DataObject
135 * which currently use PEAR::raiseError to notify of error messages.
136 *
137 * @param object PEAR_Error
138 *
139 * @return void
140 * @access public
141 */
142 public static function handle($pearError) {
143
144 // setup smarty with config, session and template location.
145 $template = CRM_Core_Smarty::singleton();
146 $config = CRM_Core_Config::singleton();
147
148 if ($config->backtrace) {
149 self::backtrace();
150 }
151
152 // create the error array
153 $error = array();
154 $error['callback'] = $pearError->getCallback();
155 $error['code'] = $pearError->getCode();
156 $error['message'] = $pearError->getMessage();
157 $error['mode'] = $pearError->getMode();
158 $error['debug_info'] = $pearError->getDebugInfo();
159 $error['type'] = $pearError->getType();
160 $error['user_info'] = $pearError->getUserInfo();
161 $error['to_string'] = $pearError->toString();
162 if (function_exists('mysql_error') &&
163 mysql_error()
164 ) {
165 $mysql_error = mysql_error() . ', ' . mysql_errno();
166 $template->assign_by_ref('mysql_code', $mysql_error);
167
168 // execute a dummy query to clear error stack
169 mysql_query('select 1');
170 }
171 elseif (function_exists('mysqli_error')) {
172 $dao = new CRM_Core_DAO();
173
174 // we do it this way, since calling the function
175 // getDatabaseConnection could potentially result
176 // in an infinite loop
177 global $_DB_DATAOBJECT;
178 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) {
179 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
180 $link = $conn->connection;
181
182 if (mysqli_error($link)) {
183 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
184 $template->assign_by_ref('mysql_code', $mysql_error);
185
186 // execute a dummy query to clear error stack
187 mysqli_query($link, 'select 1');
188 }
189 }
190 }
191
192 $template->assign_by_ref('error', $error);
193 $errorDetails = CRM_Core_Error::debug('', $error, FALSE);
194 $template->assign_by_ref('errorDetails', $errorDetails);
195
196 CRM_Core_Error::debug_var('Fatal Error Details', $error);
197 CRM_Core_Error::backtrace('backTrace', TRUE);
198
199 if ($config->initialized) {
200 $content = $template->fetch('CRM/common/fatal.tpl');
201 echo CRM_Utils_System::theme($content);
202 }
203 else {
204 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
205 CRM_Core_Error::debug(NULL, $error);
206 }
3a210ec0
E
207 static $runOnce = FALSE;
208 if ($runOnce) {
209 exit;
210 }
211 $runOnce = TRUE;
6a488035
TO
212 self::abend(1);
213 }
214
215 // this function is used to trap and print errors
216 // during system initialization time. Hence the error
217 // message is quite ugly
218 public static function simpleHandler($pearError) {
219
220 // create the error array
221 $error = array();
222 $error['callback'] = $pearError->getCallback();
223 $error['code'] = $pearError->getCode();
224 $error['message'] = $pearError->getMessage();
225 $error['mode'] = $pearError->getMode();
226 $error['debug_info'] = $pearError->getDebugInfo();
227 $error['type'] = $pearError->getType();
228 $error['user_info'] = $pearError->getUserInfo();
229 $error['to_string'] = $pearError->toString();
230
005db542
DL
231 // ensure that debug does not check permissions since we are in bootstrap
232 // mode and need to print a decent message to help the user
90154ece 233 CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
6a488035
TO
234
235 // always log the backtrace to a file
236 self::backtrace('backTrace', TRUE);
237
238 exit(0);
239 }
240
241 /**
242 * Handle errors raised using the PEAR Error Stack.
243 *
244 * currently the handler just requests the PES framework
245 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
246 *
247 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
248 *
249 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
250 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
251 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
252 *
253 */
254 public static function handlePES($pearError) {
255 return PEAR_ERRORSTACK_PUSH;
256 }
257
258 /**
259 * display an error page with an error message describing what happened
260 *
261 * @param string message the error message
262 * @param string code the error code if any
263 * @param string email the email address to notify of this situation
264 *
265 * @return void
266 * @static
267 * @acess public
268 */
269 static function fatal($message = NULL, $code = NULL, $email = NULL) {
270 $vars = array(
271 'message' => $message,
272 'code' => $code,
273 );
274
275 if (self::$modeException) {
276 // CRM-11043
277 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
278 CRM_Core_Error::backtrace('backTrace', TRUE);
279
280 $details = 'A fatal error was triggered';
281 if ($message) {
282 $details .= ': ' . $message;
283 }
284 throw new Exception($details, $code);
285 }
286
287 if (!$message) {
288 $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/'));
289 }
290
291 if (php_sapi_name() == "cli") {
292 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
293 debug_print_backtrace();
294 die("\n");
295 // FIXME: Why doesn't this call abend()?
296 // Difference: abend() will cleanup transaction and (via civiExit) store session state
297 // self::abend(CRM_Core_Error::FATAL_ERROR);
298 }
299
300 $config = CRM_Core_Config::singleton();
301
302 if ($config->fatalErrorHandler &&
303 function_exists($config->fatalErrorHandler)
304 ) {
305 $name = $config->fatalErrorHandler;
306 $ret = $name($vars);
307 if ($ret) {
308 // the call has been successfully handled
309 // so we just exit
310 self::abend(CRM_Core_Error::FATAL_ERROR);
311 }
312 }
313
34866662
CW
314 // If we are in an ajax callback, format output appropriately
315 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
316 $out = array(
317 'status' => 'fatal',
318 '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>',
319 );
320 if ($config->backtrace && CRM_Core_Permission::check('view debug output')) {
321 $out['backtrace'] = self::parseBacktrace(debug_backtrace());
322 $message .= '<p><em>See console for backtrace</em></p>';
323 }
324 CRM_Core_Session::setStatus($message, ts('Sorry an Error Occured'), 'error');
325 CRM_Core_Transaction::forceRollbackIfEnabled();
326 CRM_Core_Page_AJAX::returnJsonResponse($out);
327 }
328
6a488035
TO
329 if ($config->backtrace) {
330 self::backtrace();
331 }
332
333 $template = CRM_Core_Smarty::singleton();
334 $template->assign($vars);
335
336 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
337 CRM_Core_Error::backtrace('backTrace', TRUE);
338 $content = $template->fetch($config->fatalErrorTemplate);
e8cd958c
DL
339 // JErrorPage exists only in 3.x and not 2.x
340 // CRM-13714
341 if ($config->userFramework == 'Joomla' && class_exists('JErrorPage')) {
342 $error = new Exception($content);
343 JErrorPage::render($error);
344 }
345 else if ($config->userFramework == 'Joomla' && class_exists('JError')) {
346 JError::raiseError('CiviCRM-001', $content);
6a488035 347 }
28c8781b
DL
348 else {
349 echo CRM_Utils_System::theme($content);
350 }
6a488035
TO
351
352 self::abend(CRM_Core_Error::FATAL_ERROR);
353 }
354
355 /**
356 * display an error page with an error message describing what happened
357 *
358 * This function is evil -- it largely replicates fatal(). Hopefully the
359 * entire CRM_Core_Error system can be hollowed out and replaced with
360 * something that follows a cleaner separation of concerns.
361 *
362 * @param Exception $exception
363 *
364 * @return void
365 * @static
366 * @acess public
367 */
368 static function handleUnhandledException($exception) {
369 $config = CRM_Core_Config::singleton();
370 $vars = array(
371 'message' => $exception->getMessage(),
372 'code' => NULL,
373 'exception' => $exception,
374 );
375 if (!$vars['message']) {
376 $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/'));
377 }
378
379 // Case A: CLI
380 if (php_sapi_name() == "cli") {
381 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
382 print self::formatTextException($exception);
383 die("\n");
384 // FIXME: Why doesn't this call abend()?
385 // Difference: abend() will cleanup transaction and (via civiExit) store session state
386 // self::abend(CRM_Core_Error::FATAL_ERROR);
387 }
388
389 // Case B: Custom error handler
390 if ($config->fatalErrorHandler &&
391 function_exists($config->fatalErrorHandler)
392 ) {
393 $name = $config->fatalErrorHandler;
394 $ret = $name($vars);
395 if ($ret) {
396 // the call has been successfully handled
397 // so we just exit
398 self::abend(CRM_Core_Error::FATAL_ERROR);
399 }
400 }
401
402 // Case C: Default error handler
403
404 // log to file
405 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
406 CRM_Core_Error::backtrace('backTrace', TRUE);
407
408 // print to screen
409 $template = CRM_Core_Smarty::singleton();
410 $template->assign($vars);
411 $content = $template->fetch($config->fatalErrorTemplate);
412 if ($config->backtrace) {
413 $content = self::formatHtmlException($exception) . $content;
414 }
415 if ($config->userFramework == 'Joomla' &&
416 class_exists('JError')
417 ) {
418 JError::raiseError('CiviCRM-001', $content);
419 }
420 else {
421 echo CRM_Utils_System::theme($content);
422 }
423
424 // fin
425 self::abend(CRM_Core_Error::FATAL_ERROR);
426 }
427
428 /**
429 * outputs pre-formatted debug information. Flushes the buffers
430 * so we can interrupt a potential POST/redirect
431 *
432 * @param string name of debug section
433 * @param mixed reference to variables that we need a trace of
434 * @param bool should we log or return the output
435 * @param bool whether to generate a HTML-escaped output
90154ece
DL
436 * @param bool should we check permissions before displaying output
437 * useful when we die during initialization and permissioning
438 * subsystem is not initialized - CRM-13765
6a488035
TO
439 *
440 * @return string the generated output
441 * @access public
442 * @static
443 */
90154ece 444 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
6a488035
TO
445 $error = self::singleton();
446
447 if ($variable === NULL) {
448 $variable = $name;
449 $name = NULL;
450 }
451
452 $out = print_r($variable, TRUE);
453 $prefix = NULL;
454 if ($html) {
455 $out = htmlspecialchars($out);
456 if ($name) {
457 $prefix = "<p>$name</p>";
458 }
459 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
460 }
461 else {
462 if ($name) {
463 $prefix = "$name:\n";
464 }
465 $out = "{$prefix}$out\n";
466 }
90154ece
DL
467 if (
468 $log &&
469 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
470 ) {
6a488035
TO
471 echo $out;
472 }
473
474 return $out;
475 }
476
477 /**
478 * Similar to the function debug. Only difference is
479 * in the formatting of the output.
480 *
481 * @param string variable name
482 * @param mixed reference to variables that we need a trace of
483 * @param bool should we use print_r ? (else we use var_dump)
484 * @param bool should we log or return the output
485 *
486 * @return string the generated output
487 *
488 * @access public
489 *
490 * @static
491 *
492 * @see CRM_Core_Error::debug()
493 * @see CRM_Core_Error::debug_log_message()
494 */
495 static function debug_var($variable_name,
496 $variable,
497 $print = TRUE,
498 $log = TRUE,
499 $comp = ''
500 ) {
501 // check if variable is set
502 if (!isset($variable)) {
503 $out = "\$$variable_name is not set";
504 }
505 else {
506 if ($print) {
507 $out = print_r($variable, TRUE);
508 $out = "\$$variable_name = $out";
509 }
510 else {
511 // use var_dump
512 ob_start();
513 var_dump($variable);
514 $dump = ob_get_contents();
515 ob_end_clean();
516 $out = "\n\$$variable_name = $dump";
517 }
518 // reset if it is an array
519 if (is_array($variable)) {
520 reset($variable);
521 }
522 }
523 return self::debug_log_message($out, FALSE, $comp);
524 }
525
526 /**
527 * display the error message on terminal
528 *
529 * @param string message to be output
530 * @param bool should we log or return the output
531 *
532 * @return string format of the backtrace
533 *
534 * @access public
535 *
536 * @static
537 */
538 static function debug_log_message($message, $out = FALSE, $comp = '') {
539 $config = CRM_Core_Config::singleton();
540
541 $file_log = self::createDebugLogger($comp);
542 $file_log->log("$message\n");
543 $str = "<p/><code>$message</code>";
544 if ($out && CRM_Core_Permission::check('view debug output')) {
545 echo $str;
546 }
547 $file_log->close();
548
549 if ($config->userFrameworkLogging) {
550 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
551 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG);
552 }
553 }
554
555 return $str;
556 }
557
558 /**
559 * Append to the query log (if enabled)
560 */
561 static function debug_query($string) {
562 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
563 if ( CIVICRM_DEBUG_LOG_QUERY == 'backtrace' ) {
564 CRM_Core_Error::backtrace( $string, true );
565 } else if ( CIVICRM_DEBUG_LOG_QUERY ) {
566 CRM_Core_Error::debug_var( 'Query', $string, false, true );
567 }
568 }
569 }
570
571 /**
572 * Obtain a reference to the error log
573 *
574 * @return Log
575 */
576 static function createDebugLogger($comp = '') {
577 $config = CRM_Core_Config::singleton();
578
579 if ($comp) {
580 $comp = $comp . '.';
581 }
582
583 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn) . '.log';
584
585 // Roll log file monthly or if greater than 256M
586 // note that PHP file functions have a limit of 2G and hence
587 // the alternative was introduce
588 if (file_exists($fileName)) {
589 $fileTime = date("Ym", filemtime($fileName));
590 $fileSize = filesize($fileName);
591 if (($fileTime < date('Ym')) ||
592 ($fileSize > 256 * 1024 * 1024) ||
593 ($fileSize < 0)
594 ) {
595 rename($fileName,
596 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
597 );
598 }
599 }
600
601 return Log::singleton('file', $fileName);
602 }
603
604 static function backtrace($msg = 'backTrace', $log = FALSE) {
605 $backTrace = debug_backtrace();
606 $message = self::formatBacktrace($backTrace);
607 if (!$log) {
608 CRM_Core_Error::debug($msg, $message);
609 }
610 else {
611 CRM_Core_Error::debug_var($msg, $message);
612 }
613 }
614
615 /**
616 * Render a backtrace array as a string
617 *
618 * @param array $backTrace array of stack frames
619 * @param boolean $showArgs 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
620 * @param int $maxArgLen maximum number of characters to show from each argument string
621 * @return string printable plain-text
6a488035
TO
622 */
623 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
624 $message = '';
34866662
CW
625 foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
626 $message .= sprintf("#%s %s\n", $idx, $trace);
627 }
628 $message .= sprintf("#%s {main}\n", 1+$idx);
629 return $message;
630 }
631
632 /**
633 * Render a backtrace array as an array
634 *
635 * @param array $backTrace array of stack frames
636 * @param boolean $showArgs 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
637 * @param int $maxArgLen maximum number of characters to show from each argument string
638 * @return array
639 * @see debug_backtrace
640 * @see Exception::getTrace()
641 */
642 static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
643 $ret = array();
644 foreach ($backTrace as $trace) {
6a488035
TO
645 $args = array();
646 $fnName = CRM_Utils_Array::value('function', $trace);
34866662 647 $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
6a488035
TO
648
649 // do now show args for a few password related functions
650 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
651
652 foreach ($trace['args'] as $arg) {
653 if (! $showArgs || $skipArgs) {
654 $args[] = '(' . gettype($arg) . ')';
655 continue;
656 }
657 switch ($type = gettype($arg)) {
658 case 'boolean':
659 $args[] = $arg ? 'TRUE' : 'FALSE';
660 break;
661 case 'integer':
662 case 'double':
663 $args[] = $arg;
664 break;
665 case 'string':
666 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
667 break;
668 case 'array':
669 $args[] = '(Array:'.count($arg).')';
670 break;
671 case 'object':
672 $args[] = 'Object(' . get_class($arg) . ')';
673 break;
674 case 'resource':
675 $args[] = 'Resource';
676 break;
677 case 'NULL':
678 $args[] = 'NULL';
679 break;
680 default:
681 $args[] = "($type)";
682 break;
683 }
684 }
685
34866662
CW
686 $ret[] = sprintf(
687 "%s(%s): %s%s(%s)",
6a488035
TO
688 CRM_Utils_Array::value('file', $trace, '[internal function]'),
689 CRM_Utils_Array::value('line', $trace, ''),
690 $className,
691 $fnName,
692 implode(", ", $args)
693 );
694 }
34866662 695 return $ret;
6a488035
TO
696 }
697
698 /**
699 * Render an exception as HTML string
700 *
701 * @param Exception $e
702 * @return string printable HTML text
703 */
704 static function formatHtmlException(Exception $e) {
705 $msg = '';
706
707 // Exception metadata
708
709 // Exception backtrace
710 if ($e instanceof PEAR_Exception) {
711 $ei = $e;
712 while (is_callable(array($ei, 'getCause'))) {
713 if ($ei->getCause() instanceof PEAR_Error) {
714 $msg .= '<table class="crm-db-error">';
715 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
716 $msg .= '<tbody>';
717 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
718 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
719 }
720 $msg .= '</tbody></table>';
721 }
722 $ei = $ei->getCause();
723 }
724 $msg .= $e->toHtml();
725 } else {
726 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
727 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
728 }
729 return $msg;
730 }
731
732 /**
733 * Write details of an exception to the log
734 *
735 * @param Exception $e
736 * @return string printable plain text
737 */
738 static function formatTextException(Exception $e) {
739 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
740
741 $ei = $e;
742 while (is_callable(array($ei, 'getCause'))) {
743 if ($ei->getCause() instanceof PEAR_Error) {
744 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
745 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
746 }
747 }
748 $ei = $ei->getCause();
749 }
750 $msg .= self::formatBacktrace($e->getTrace());
751 return $msg;
752 }
753
754 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
755 $error = CRM_Core_Error::singleton();
756 $error->push($code, $level, array($params), $message);
757 return $error;
758 }
759
760 /**
761 * Set a status message in the session, then bounce back to the referrer.
762 *
763 * @param string $status The status message to set
764 *
765 * @return void
766 * @access public
767 * @static
768 */
dcc4f6a7 769 public static function statusBounce($status, $redirect = NULL, $title = '') {
6a488035
TO
770 $session = CRM_Core_Session::singleton();
771 if (!$redirect) {
772 $redirect = $session->readUserContext();
773 }
dcc4f6a7 774 $session->setStatus($status, $title);
34866662
CW
775 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
776 CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error'));
777 }
6a488035
TO
778 CRM_Utils_System::redirect($redirect);
779 }
780
781 /**
782 * Function to reset the error stack
783 *
784 * @access public
785 * @static
786 */
787 public static function reset() {
788 $error = self::singleton();
789 $error->_errors = array();
790 $error->_errorsByLevel = array();
791 }
792
6a4257d4
TO
793 /**
794 * @deprecated
795 * @see CRM_Core_TemporaryErrorScope::ignoreException
796 */
6a488035
TO
797 public static function ignoreException($callback = NULL) {
798 if (!$callback) {
799 $callback = array('CRM_Core_Error', 'nullHandler');
800 }
801
802 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
803 $GLOBALS['_PEAR_default_error_options'] = $callback;
804 }
805
806 public static function exceptionHandler($pearError) {
807 CRM_Core_Error::backtrace('backTrace', TRUE);
808 throw new PEAR_Exception($pearError->getMessage(), $pearError);
809 }
810
811 /**
812 * Error handler to quietly catch otherwise fatal smtp transport errors.
813 *
814 * @param object $obj The PEAR_ERROR object
815 *
816 * @return object $obj
817 * @access public
818 * @static
819 */
820 public static function nullHandler($obj) {
821 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
822 CRM_Core_Error::backtrace('backTrace', TRUE);
823 return $obj;
824 }
825
826 /**
827 * (Re)set the default callback method
828 *
829 * @return void
830 * @access public
6a4257d4
TO
831 * @deprecated
832 * @see CRM_Core_TemporaryErrorScope::ignoreExxception
6a488035
TO
833 * @static
834 */
835 public static function setCallback($callback = NULL) {
836 if (!$callback) {
837 $callback = array('CRM_Core_Error', 'handle');
838 }
839 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
840 $GLOBALS['_PEAR_default_error_options'] = $callback;
841 }
842
843 /*
844 * @deprecated
845 * This function is no longer used by v3 api.
846 * @fixme Some core files call it but it should be re-thought & renamed or removed
847 */
848 public static function &createAPIError($msg, $data = NULL) {
849 if (self::$modeException) {
850 throw new Exception($msg, $data);
851 }
852
853 $values = array();
854
855 $values['is_error'] = 1;
856 $values['error_message'] = $msg;
857 if (isset($data)) {
858 $values = array_merge($values, $data);
859 }
860 return $values;
861 }
862
863 public static function movedSiteError($file) {
864 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
865 'reset=1',
866 TRUE
867 );
868 echo "We could not write $file. Have you moved your site directory or server?<p>";
869 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
870 exit();
871 }
872
873 /**
874 * Terminate execution abnormally
875 */
876 protected static function abend($code) {
877 // do a hard rollback of any pending transactions
878 // if we've come here, its because of some unexpected PEAR errors
879 CRM_Core_Transaction::forceRollbackIfEnabled();
880 CRM_Utils_System::civiExit($code);
881 }
882
883 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
8cc574cf 884 if (is_array($error) && !empty($error['is_error'])) {
6a488035
TO
885 $code = $error['error_message']['code'];
886 if ($code == $type) {
887 return TRUE;
888 }
889 }
890 return FALSE;
891 }
892}
893
894$e = new PEAR_ErrorStack('CRM');
895$e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');