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