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