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