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