INFRA-132 - CRM/Core - phpcbf
[civicrm-core.git] / CRM / Core / Error.php
CommitLineData
6a488035
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
39de6fd5 5 | CiviCRM version 4.6 |
6a488035 6 +--------------------------------------------------------------------+
06b69b18 7 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 34 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
35 * $Id$
36 *
37 */
38
39require_once 'PEAR/ErrorStack.php';
40require_once 'PEAR/Exception.php';
dcc4f6a7 41require_once 'CRM/Core/Exception.php';
6a488035
TO
42
43require_once 'Log.php';
28518c90
EM
44
45/**
46 * Class CRM_Exception
47 */
6a488035
TO
48class CRM_Exception extends PEAR_Exception {
49 // Redefine the exception so message isn't optional
b5c2afd0
EM
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);
da3c7979 60 *
b5c2afd0 61 * @param string exception message
da3c7979
EM
62 * @param int $code
63 * @param Exception $previous
b5c2afd0 64 */
6a488035
TO
65 public function __construct($message = NULL, $code = 0, Exception$previous = NULL) {
66 parent::__construct($message, $code, $previous);
67 }
68}
69
a0ee3941
EM
70/**
71 * Class CRM_Core_Error
72 */
6a488035
TO
73class CRM_Core_Error extends PEAR_ErrorStack {
74
75 /**
100fef9d 76 * Status code of various types of errors
6a488035
TO
77 * @var const
78 */
7da04cde
TO
79 const FATAL_ERROR = 2;
80 const DUPLICATE_CONTACT = 8001;
81 const DUPLICATE_CONTRIBUTION = 8002;
82 const DUPLICATE_PARTICIPANT = 8003;
6a488035
TO
83
84 /**
85 * We only need one instance of this object. So we use the singleton
86 * pattern and cache the instance in this variable
87 * @var object
88 * @static
89 */
90 private static $_singleton = NULL;
91
92 /**
93 * The logger object for this application
94 * @var object
95 * @static
96 */
97 private static $_log = NULL;
98
99 /**
100 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
101 * @static
102 */
103 public static $modeException = NULL;
104
105 /**
100fef9d 106 * Singleton function used to manage this object.
6a488035 107 *
dd244018
EM
108 * @param null $package
109 * @param bool $msgCallback
110 * @param bool $contextCallback
111 * @param bool $throwPEAR_Error
112 * @param string $stackClass
113 *
6a488035
TO
114 * @return object
115 * @static
116 */
2aa397bc 117 public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
6a488035
TO
118 if (self::$_singleton === NULL) {
119 self::$_singleton = new CRM_Core_Error('CiviCRM');
120 }
121 return self::$_singleton;
122 }
123
124 /**
100fef9d 125 * Constructor
6a488035 126 */
00be9182 127 public function __construct() {
6a488035
TO
128 parent::__construct('CiviCRM');
129
130 $log = CRM_Core_Config::getLog();
131 $this->setLogger($log);
132
133 // set up error handling for Pear Error Stack
134 $this->setDefaultCallback(array($this, 'handlePES'));
135 }
136
a0ee3941
EM
137 /**
138 * @param $error
139 * @param string $separator
140 *
141 * @return array|null|string
142 */
93a11cd6 143 static public function getMessages(&$error, $separator = '<br />') {
6a488035
TO
144 if (is_a($error, 'CRM_Core_Error')) {
145 $errors = $error->getErrors();
146 $message = array();
147 foreach ($errors as $e) {
148 $message[] = $e['code'] . ': ' . $e['message'];
149 }
150 $message = implode($separator, $message);
151 return $message;
152 }
153 return NULL;
154 }
155
dbddfb08
EM
156 /**
157 * Status display function specific to payment processor errors
158 * @param $error
159 * @param string $separator
160 */
00be9182 161 public static function displaySessionError(&$error, $separator = '<br />') {
6a488035
TO
162 $message = self::getMessages($error, $separator);
163 if ($message) {
164 $status = ts("Payment Processor Error message") . "{$separator} $message";
165 $session = CRM_Core_Session::singleton();
166 $session->setStatus($status);
167 }
168 }
169
170 /**
100fef9d 171 * Create the main callback method. this method centralizes error processing.
6a488035
TO
172 *
173 * the errors we expect are from the pear modules DB, DB_DataObject
174 * which currently use PEAR::raiseError to notify of error messages.
175 *
176 * @param object PEAR_Error
177 *
178 * @return void
6a488035
TO
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 }
3a210ec0
E
245 static $runOnce = FALSE;
246 if ($runOnce) {
247 exit;
248 }
249 $runOnce = TRUE;
6a488035
TO
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
a0ee3941
EM
256 /**
257 * @param $pearError
258 */
6a488035
TO
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
005db542
DL
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
90154ece 274 CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
6a488035
TO
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 /**
100fef9d 300 * Display an error page with an error message describing what happened
6a488035 301 *
6a0b768e
TO
302 * @param string $message
303 * The error message.
304 * @param string $code
305 * The error code if any.
306 * @param string $email
307 * The email address to notify of this situation.
77b97be7
EM
308 *
309 * @throws Exception
6a488035
TO
310 *
311 * @return void
312 * @static
6a488035 313 */
00be9182 314 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
6a488035
TO
315 $vars = array(
316 'message' => $message,
317 'code' => $code,
318 );
319
320 if (self::$modeException) {
321 // CRM-11043
322 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
323 CRM_Core_Error::backtrace('backTrace', TRUE);
324
325 $details = 'A fatal error was triggered';
326 if ($message) {
327 $details .= ': ' . $message;
2aa397bc 328 }
6a488035
TO
329 throw new Exception($details, $code);
330 }
331
332 if (!$message) {
333 $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/'));
334 }
335
336 if (php_sapi_name() == "cli") {
337 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
338 debug_print_backtrace();
339 die("\n");
340 // FIXME: Why doesn't this call abend()?
341 // Difference: abend() will cleanup transaction and (via civiExit) store session state
342 // self::abend(CRM_Core_Error::FATAL_ERROR);
343 }
344
345 $config = CRM_Core_Config::singleton();
346
347 if ($config->fatalErrorHandler &&
348 function_exists($config->fatalErrorHandler)
349 ) {
350 $name = $config->fatalErrorHandler;
351 $ret = $name($vars);
352 if ($ret) {
353 // the call has been successfully handled
354 // so we just exit
355 self::abend(CRM_Core_Error::FATAL_ERROR);
356 }
357 }
358
25dc2153
PH
359 if ($config->backtrace) {
360 self::backtrace();
361 }
362
363 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
364 CRM_Core_Error::backtrace('backTrace', TRUE);
365
34866662
CW
366 // If we are in an ajax callback, format output appropriately
367 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
368 $out = array(
369 'status' => 'fatal',
370 '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>',
371 );
372 if ($config->backtrace && CRM_Core_Permission::check('view debug output')) {
373 $out['backtrace'] = self::parseBacktrace(debug_backtrace());
374 $message .= '<p><em>See console for backtrace</em></p>';
375 }
376 CRM_Core_Session::setStatus($message, ts('Sorry an Error Occured'), 'error');
377 CRM_Core_Transaction::forceRollbackIfEnabled();
378 CRM_Core_Page_AJAX::returnJsonResponse($out);
379 }
380
6a488035
TO
381 $template = CRM_Core_Smarty::singleton();
382 $template->assign($vars);
383
f85b1d20 384 $config->userSystem->outputError($template->fetch($config->fatalErrorTemplate));
6a488035
TO
385
386 self::abend(CRM_Core_Error::FATAL_ERROR);
387 }
388
389 /**
100fef9d 390 * Display an error page with an error message describing what happened
6a488035
TO
391 *
392 * This function is evil -- it largely replicates fatal(). Hopefully the
393 * entire CRM_Core_Error system can be hollowed out and replaced with
394 * something that follows a cleaner separation of concerns.
395 *
396 * @param Exception $exception
397 *
398 * @return void
399 * @static
6a488035 400 */
00be9182 401 public static function handleUnhandledException($exception) {
4b57bc9f
EM
402 try {
403 CRM_Utils_Hook::unhandledException($exception);
404 } catch (Exception $other) {
405 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
4fd5f07e 406 CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other));
4b57bc9f 407 }
6a488035
TO
408 $config = CRM_Core_Config::singleton();
409 $vars = array(
410 'message' => $exception->getMessage(),
411 'code' => NULL,
412 'exception' => $exception,
413 );
414 if (!$vars['message']) {
415 $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/'));
416 }
417
418 // Case A: CLI
419 if (php_sapi_name() == "cli") {
420 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
421 print self::formatTextException($exception);
422 die("\n");
423 // FIXME: Why doesn't this call abend()?
424 // Difference: abend() will cleanup transaction and (via civiExit) store session state
425 // self::abend(CRM_Core_Error::FATAL_ERROR);
426 }
427
428 // Case B: Custom error handler
429 if ($config->fatalErrorHandler &&
430 function_exists($config->fatalErrorHandler)
431 ) {
432 $name = $config->fatalErrorHandler;
433 $ret = $name($vars);
434 if ($ret) {
435 // the call has been successfully handled
436 // so we just exit
437 self::abend(CRM_Core_Error::FATAL_ERROR);
438 }
439 }
440
441 // Case C: Default error handler
442
443 // log to file
444 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
445 CRM_Core_Error::backtrace('backTrace', TRUE);
446
447 // print to screen
448 $template = CRM_Core_Smarty::singleton();
449 $template->assign($vars);
450 $content = $template->fetch($config->fatalErrorTemplate);
451 if ($config->backtrace) {
452 $content = self::formatHtmlException($exception) . $content;
453 }
454 if ($config->userFramework == 'Joomla' &&
455 class_exists('JError')
456 ) {
457 JError::raiseError('CiviCRM-001', $content);
458 }
459 else {
460 echo CRM_Utils_System::theme($content);
461 }
462
463 // fin
464 self::abend(CRM_Core_Error::FATAL_ERROR);
465 }
466
467 /**
100fef9d 468 * Outputs pre-formatted debug information. Flushes the buffers
6a488035
TO
469 * so we can interrupt a potential POST/redirect
470 *
6a0b768e
TO
471 * @param string name of debug section
472 * @param mixed reference to variables that we need a trace of
473 * @param bool should we log or return the output
474 * @param bool whether to generate a HTML-escaped output
475 * @param bool should we check permissions before displaying output
90154ece
DL
476 * useful when we die during initialization and permissioning
477 * subsystem is not initialized - CRM-13765
6a488035
TO
478 *
479 * @return string the generated output
6a488035
TO
480 * @static
481 */
00be9182 482 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
6a488035
TO
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 }
90154ece
DL
505 if (
506 $log &&
507 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
508 ) {
6a488035
TO
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 *
c490a46a
CW
519 * @param string $variable_name
520 * @param mixed $variable
6a0b768e
TO
521 * @param bool $print
522 * Should we use print_r ? (else we use var_dump).
523 * @param bool $log
524 * Should we log or return the output.
525 * @param string $comp
526 * Variable name.
2a6da8d7 527 *
6a488035
TO
528 * @return string the generated output
529 *
6a488035
TO
530 *
531 * @static
532 *
533 * @see CRM_Core_Error::debug()
534 * @see CRM_Core_Error::debug_log_message()
535 */
536 static function debug_var($variable_name,
537 $variable,
538 $print = TRUE,
2aa397bc
TO
539 $log = TRUE,
540 $comp = ''
6a488035
TO
541 ) {
542 // check if variable is set
543 if (!isset($variable)) {
544 $out = "\$$variable_name is not set";
545 }
546 else {
547 if ($print) {
548 $out = print_r($variable, TRUE);
549 $out = "\$$variable_name = $out";
550 }
551 else {
552 // use var_dump
553 ob_start();
554 var_dump($variable);
555 $dump = ob_get_contents();
556 ob_end_clean();
557 $out = "\n\$$variable_name = $dump";
558 }
559 // reset if it is an array
560 if (is_array($variable)) {
561 reset($variable);
562 }
563 }
564 return self::debug_log_message($out, FALSE, $comp);
565 }
566
567 /**
100fef9d 568 * Display the error message on terminal
6a488035 569 *
2a6da8d7 570 * @param $message
6a0b768e
TO
571 * @param bool $out
572 * Should we log or return the output.
6a488035 573 *
6a0b768e
TO
574 * @param string $comp
575 * Message to be output.
6a488035
TO
576 * @return string format of the backtrace
577 *
6a488035
TO
578 *
579 * @static
580 */
00be9182 581 public static function debug_log_message($message, $out = FALSE, $comp = '') {
213a5f19 582 $config = CRM_Core_Config::singleton();
6a488035
TO
583
584 $file_log = self::createDebugLogger($comp);
585 $file_log->log("$message\n");
586 $str = "<p/><code>$message</code>";
587 if ($out && CRM_Core_Permission::check('view debug output')) {
588 echo $str;
589 }
590 $file_log->close();
591
213a5f19 592 if ($config->userFrameworkLogging) {
1fadd891 593 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
213a5f19
EM
594 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
595 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG);
596 }
597 }
6a488035
TO
598
599 return $str;
600 }
601
602 /**
603 * Append to the query log (if enabled)
604 */
00be9182 605 public static function debug_query($string) {
6a488035
TO
606 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
607 if ( CIVICRM_DEBUG_LOG_QUERY == 'backtrace' ) {
2aa397bc 608 CRM_Core_Error::backtrace( $string, TRUE );
6a488035 609 } else if ( CIVICRM_DEBUG_LOG_QUERY ) {
2aa397bc 610 CRM_Core_Error::debug_var( 'Query', $string, FALSE, TRUE );
6a488035
TO
611 }
612 }
613 }
614
d090b80b
TO
615 /**
616 * Execute a query and log the results.
617 *
618 * @param string $query
619 */
00be9182 620 public static function debug_query_result($query) {
d090b80b
TO
621 $dao = CRM_Core_DAO::executeQuery($query);
622 $results = array();
623 while ($dao->fetch()) {
2aa397bc 624 $results[] = (array) $dao;
d090b80b
TO
625 }
626 CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results));
627 }
628
6a488035
TO
629 /**
630 * Obtain a reference to the error log
631 *
77b97be7
EM
632 * @param string $comp
633 *
6a488035
TO
634 * @return Log
635 */
00be9182 636 public static function createDebugLogger($comp = '') {
6a488035
TO
637 $config = CRM_Core_Config::singleton();
638
639 if ($comp) {
640 $comp = $comp . '.';
641 }
642
643 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn) . '.log';
644
645 // Roll log file monthly or if greater than 256M
646 // note that PHP file functions have a limit of 2G and hence
647 // the alternative was introduce
648 if (file_exists($fileName)) {
649 $fileTime = date("Ym", filemtime($fileName));
650 $fileSize = filesize($fileName);
651 if (($fileTime < date('Ym')) ||
652 ($fileSize > 256 * 1024 * 1024) ||
653 ($fileSize < 0)
654 ) {
655 rename($fileName,
656 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
657 );
658 }
659 }
660
661 return Log::singleton('file', $fileName);
662 }
663
a0ee3941
EM
664 /**
665 * @param string $msg
666 * @param bool $log
667 */
00be9182 668 public static function backtrace($msg = 'backTrace', $log = FALSE) {
6a488035
TO
669 $backTrace = debug_backtrace();
670 $message = self::formatBacktrace($backTrace);
671 if (!$log) {
672 CRM_Core_Error::debug($msg, $message);
673 }
674 else {
675 CRM_Core_Error::debug_var($msg, $message);
676 }
677 }
678
679 /**
680 * Render a backtrace array as a string
681 *
6a0b768e
TO
682 * @param array $backTrace
683 * Array of stack frames.
684 * @param bool $showArgs
685 * 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.
686 * @param int $maxArgLen
687 * Maximum number of characters to show from each argument string.
6a488035 688 * @return string printable plain-text
6a488035 689 */
00be9182 690 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
6a488035 691 $message = '';
34866662
CW
692 foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
693 $message .= sprintf("#%s %s\n", $idx, $trace);
694 }
2aa397bc 695 $message .= sprintf("#%s {main}\n", 1 + $idx);
34866662
CW
696 return $message;
697 }
698
699 /**
700 * Render a backtrace array as an array
701 *
6a0b768e
TO
702 * @param array $backTrace
703 * Array of stack frames.
704 * @param bool $showArgs
705 * 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.
706 * @param int $maxArgLen
707 * Maximum number of characters to show from each argument string.
34866662
CW
708 * @return array
709 * @see debug_backtrace
710 * @see Exception::getTrace()
711 */
00be9182 712 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
34866662
CW
713 $ret = array();
714 foreach ($backTrace as $trace) {
6a488035
TO
715 $args = array();
716 $fnName = CRM_Utils_Array::value('function', $trace);
34866662 717 $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
6a488035 718
83e7cba6 719 // Do not show args for a few password related functions
6a488035
TO
720 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
721
83e7cba6
CB
722 if (!empty($trace['args'])) {
723 foreach ($trace['args'] as $arg) {
724 if (! $showArgs || $skipArgs) {
725 $args[] = '(' . gettype($arg) . ')';
726 continue;
727 }
728 switch ($type = gettype($arg)) {
729 case 'boolean':
730 $args[] = $arg ? 'TRUE' : 'FALSE';
731 break;
2aa397bc 732
83e7cba6
CB
733 case 'integer':
734 case 'double':
735 $args[] = $arg;
736 break;
2aa397bc 737
83e7cba6
CB
738 case 'string':
739 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
740 break;
2aa397bc 741
83e7cba6
CB
742 case 'array':
743 $args[] = '(Array:'.count($arg).')';
744 break;
2aa397bc 745
83e7cba6
CB
746 case 'object':
747 $args[] = 'Object(' . get_class($arg) . ')';
748 break;
2aa397bc 749
83e7cba6
CB
750 case 'resource':
751 $args[] = 'Resource';
752 break;
2aa397bc 753
83e7cba6
CB
754 case 'NULL':
755 $args[] = 'NULL';
756 break;
2aa397bc 757
83e7cba6
CB
758 default:
759 $args[] = "($type)";
760 break;
761 }
6a488035
TO
762 }
763 }
764
34866662
CW
765 $ret[] = sprintf(
766 "%s(%s): %s%s(%s)",
6a488035
TO
767 CRM_Utils_Array::value('file', $trace, '[internal function]'),
768 CRM_Utils_Array::value('line', $trace, ''),
769 $className,
770 $fnName,
771 implode(", ", $args)
772 );
773 }
34866662 774 return $ret;
6a488035
TO
775 }
776
777 /**
778 * Render an exception as HTML string
779 *
780 * @param Exception $e
781 * @return string printable HTML text
782 */
00be9182 783 public static function formatHtmlException(Exception $e) {
6a488035
TO
784 $msg = '';
785
786 // Exception metadata
787
788 // Exception backtrace
789 if ($e instanceof PEAR_Exception) {
790 $ei = $e;
791 while (is_callable(array($ei, 'getCause'))) {
792 if ($ei->getCause() instanceof PEAR_Error) {
793 $msg .= '<table class="crm-db-error">';
794 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
795 $msg .= '<tbody>';
796 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
797 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
2aa397bc 798 }
6a488035 799 $msg .= '</tbody></table>';
2aa397bc 800 }
6a488035 801 $ei = $ei->getCause();
2aa397bc 802 }
6a488035
TO
803 $msg .= $e->toHtml();
804 } else {
805 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
806 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
807 }
808 return $msg;
809 }
810
811 /**
812 * Write details of an exception to the log
813 *
814 * @param Exception $e
815 * @return string printable plain text
816 */
00be9182 817 public static function formatTextException(Exception $e) {
6a488035
TO
818 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
819
820 $ei = $e;
821 while (is_callable(array($ei, 'getCause'))) {
822 if ($ei->getCause() instanceof PEAR_Error) {
823 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
824 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
825 }
826 }
827 $ei = $ei->getCause();
828 }
829 $msg .= self::formatBacktrace($e->getTrace());
830 return $msg;
831 }
832
a0ee3941
EM
833 /**
834 * @param $message
835 * @param int $code
836 * @param string $level
100fef9d 837 * @param array $params
a0ee3941
EM
838 *
839 * @return object
840 */
00be9182 841 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
6a488035
TO
842 $error = CRM_Core_Error::singleton();
843 $error->push($code, $level, array($params), $message);
844 return $error;
845 }
846
847 /**
848 * Set a status message in the session, then bounce back to the referrer.
849 *
6a0b768e
TO
850 * @param string $status
851 * The status message to set.
6a488035 852 *
2a6da8d7
EM
853 * @param null $redirect
854 * @param string $title
6a488035 855 * @return void
6a488035
TO
856 * @static
857 */
50ecd413 858 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
6a488035
TO
859 $session = CRM_Core_Session::singleton();
860 if (!$redirect) {
861 $redirect = $session->readUserContext();
862 }
50ecd413
CW
863 if ($title === NULL) {
864 $title = ts('Error');
865 }
866 $session->setStatus($status, $title, 'alert', array('expires' => 0));
34866662
CW
867 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
868 CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error'));
869 }
6a488035
TO
870 CRM_Utils_System::redirect($redirect);
871 }
872
873 /**
100fef9d 874 * Reset the error stack
6a488035 875 *
6a488035
TO
876 * @static
877 */
878 public static function reset() {
879 $error = self::singleton();
880 $error->_errors = array();
881 $error->_errorsByLevel = array();
882 }
883
6a4257d4 884 /**
42c0daee
TO
885 * PEAR error-handler which converts errors to exceptions
886 *
887 * @param $pearError
888 * @throws PEAR_Exception
6a4257d4 889 */
6a488035
TO
890 public static function exceptionHandler($pearError) {
891 CRM_Core_Error::backtrace('backTrace', TRUE);
892 throw new PEAR_Exception($pearError->getMessage(), $pearError);
893 }
894
895 /**
42c0daee 896 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
6a488035 897 *
6a0b768e
TO
898 * @param object $obj
899 * The PEAR_ERROR object.
6a488035 900 * @return object $obj
6a488035
TO
901 * @static
902 */
903 public static function nullHandler($obj) {
904 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
905 CRM_Core_Error::backtrace('backTrace', TRUE);
906 return $obj;
907 }
908
6a488035
TO
909 /*
910 * @deprecated
911 * This function is no longer used by v3 api.
912 * @fixme Some core files call it but it should be re-thought & renamed or removed
913 */
a0ee3941
EM
914 /**
915 * @param $msg
916 * @param null $data
917 *
918 * @return array
919 * @throws Exception
920 */
6a488035
TO
921 public static function &createAPIError($msg, $data = NULL) {
922 if (self::$modeException) {
923 throw new Exception($msg, $data);
924 }
925
926 $values = array();
927
928 $values['is_error'] = 1;
929 $values['error_message'] = $msg;
930 if (isset($data)) {
931 $values = array_merge($values, $data);
932 }
933 return $values;
934 }
935
a0ee3941
EM
936 /**
937 * @param $file
938 */
6a488035
TO
939 public static function movedSiteError($file) {
940 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
941 'reset=1',
942 TRUE
943 );
944 echo "We could not write $file. Have you moved your site directory or server?<p>";
945 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
946 exit();
947 }
948
949 /**
950 * Terminate execution abnormally
951 */
952 protected static function abend($code) {
953 // do a hard rollback of any pending transactions
954 // if we've come here, its because of some unexpected PEAR errors
955 CRM_Core_Transaction::forceRollbackIfEnabled();
956 CRM_Utils_System::civiExit($code);
957 }
958
a0ee3941
EM
959 /**
960 * @param $error
961 * @param const $type
962 *
963 * @return bool
964 */
6a488035 965 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
8cc574cf 966 if (is_array($error) && !empty($error['is_error'])) {
6a488035
TO
967 $code = $error['error_message']['code'];
968 if ($code == $type) {
969 return TRUE;
970 }
971 }
972 return FALSE;
973 }
974}
975
976$e = new PEAR_ErrorStack('CRM');
977$e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');