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