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