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