Merge pull request #9680 from h-c-c/CRM-19881
[civicrm-core.git] / CRM / Core / Error.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 // PEAR<=1.9.0 does not declare "static" properly.
128 if (!is_callable(array('PEAR', '__callStatic'))) {
129 $this->setDefaultCallback(array($this, 'handlePES'));
130 }
131 else {
132 PEAR_ErrorStack::setDefaultCallback(array($this, 'handlePES'));
133 }
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 public 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 $pearError PEAR_Error
176 */
177 public static function handle($pearError) {
178 if (defined('CIVICRM_TEST')) {
179 return self::simpleHandler($pearError);
180 }
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 = self::getErrorDetails($pearError);
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 $dao = new CRM_Core_DAO();
200 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) {
201 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
202
203 // FIXME: Polymorphism for the win.
204 if ($conn instanceof DB_mysqli) {
205 $link = $conn->connection;
206 if (mysqli_error($link)) {
207 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
208 mysqli_query($link, 'select 1'); // execute a dummy query to clear error stack
209 }
210 }
211 elseif ($conn instanceof DB_mysql) {
212 if (mysql_error()) {
213 $mysql_error = mysql_error() . ', ' . mysql_errno();
214 mysql_query('select 1'); // execute a dummy query to clear error stack
215 }
216 }
217 else {
218 $mysql_error = 'fixme-unknown-db-cxn';
219 }
220 $template->assign_by_ref('mysql_code', $mysql_error);
221 }
222 }
223
224 $template->assign_by_ref('error', $error);
225 $errorDetails = CRM_Core_Error::debug('', $error, FALSE);
226 $template->assign_by_ref('errorDetails', $errorDetails);
227
228 CRM_Core_Error::debug_var('Fatal Error Details', $error);
229 CRM_Core_Error::backtrace('backTrace', TRUE);
230
231 if ($config->initialized) {
232 $content = $template->fetch('CRM/common/fatal.tpl');
233 echo CRM_Utils_System::theme($content);
234 }
235 else {
236 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
237 CRM_Core_Error::debug(NULL, $error);
238 }
239 static $runOnce = FALSE;
240 if ($runOnce) {
241 exit;
242 }
243 $runOnce = TRUE;
244 self::abend(1);
245 }
246
247 /**
248 * this function is used to trap and print errors
249 * during system initialization time. Hence the error
250 * message is quite ugly
251 *
252 * @param $pearError
253 */
254 public static function simpleHandler($pearError) {
255
256 $error = self::getErrorDetails($pearError);
257
258 // ensure that debug does not check permissions since we are in bootstrap
259 // mode and need to print a decent message to help the user
260 CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
261
262 // always log the backtrace to a file
263 self::backtrace('backTrace', TRUE);
264
265 exit(0);
266 }
267
268 /**
269 * this function is used to return error details
270 *
271 * @param $pearError
272 *
273 * @return array $error
274 */
275 public static function getErrorDetails($pearError) {
276 // create the error array
277 $error = array();
278 $error['callback'] = $pearError->getCallback();
279 $error['code'] = $pearError->getCode();
280 $error['message'] = $pearError->getMessage();
281 $error['mode'] = $pearError->getMode();
282 $error['debug_info'] = $pearError->getDebugInfo();
283 $error['type'] = $pearError->getType();
284 $error['user_info'] = $pearError->getUserInfo();
285 $error['to_string'] = $pearError->toString();
286
287 return $error;
288 }
289
290 /**
291 * Handle errors raised using the PEAR Error Stack.
292 *
293 * currently the handler just requests the PES framework
294 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
295 *
296 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
297 *
298 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
299 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
300 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
301 *
302 * @param mixed $pearError
303 *
304 * @return int
305 */
306 public static function handlePES($pearError) {
307 return PEAR_ERRORSTACK_PUSH;
308 }
309
310 /**
311 * Display an error page with an error message describing what happened.
312 *
313 * @param string $message
314 * The error message.
315 * @param string $code
316 * The error code if any.
317 * @param string $email
318 * The email address to notify of this situation.
319 *
320 * @throws Exception
321 */
322 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
323 $vars = array(
324 'message' => htmlspecialchars($message),
325 'code' => $code,
326 );
327
328 if (self::$modeException) {
329 // CRM-11043
330 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
331 CRM_Core_Error::backtrace('backTrace', TRUE);
332
333 $details = 'A fatal error was triggered';
334 if ($message) {
335 $details .= ': ' . $message;
336 }
337 throw new Exception($details, $code);
338 }
339
340 if (!$message) {
341 $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/'));
342 }
343
344 if (php_sapi_name() == "cli") {
345 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
346 // Fix for CRM-16899
347 echo static::formatBacktrace(debug_backtrace());
348 die("\n");
349 // FIXME: Why doesn't this call abend()?
350 // Difference: abend() will cleanup transaction and (via civiExit) store session state
351 // self::abend(CRM_Core_Error::FATAL_ERROR);
352 }
353
354 $config = CRM_Core_Config::singleton();
355
356 if ($config->fatalErrorHandler &&
357 function_exists($config->fatalErrorHandler)
358 ) {
359 $name = $config->fatalErrorHandler;
360 $ret = $name($vars);
361 if ($ret) {
362 // the call has been successfully handled
363 // so we just exit
364 self::abend(CRM_Core_Error::FATAL_ERROR);
365 }
366 }
367
368 if ($config->backtrace) {
369 self::backtrace();
370 }
371
372 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
373 CRM_Core_Error::backtrace('backTrace', TRUE);
374
375 // If we are in an ajax callback, format output appropriately
376 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
377 $out = array(
378 'status' => 'fatal',
379 '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>',
380 );
381 if ($config->backtrace && CRM_Core_Permission::check('view debug output')) {
382 $out['backtrace'] = self::parseBacktrace(debug_backtrace());
383 $message .= '<p><em>See console for backtrace</em></p>';
384 }
385 CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error');
386 CRM_Core_Transaction::forceRollbackIfEnabled();
387 CRM_Core_Page_AJAX::returnJsonResponse($out);
388 }
389
390 $template = CRM_Core_Smarty::singleton();
391 $template->assign($vars);
392 $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl'));
393
394 self::abend(CRM_Core_Error::FATAL_ERROR);
395 }
396
397 /**
398 * Display an error page with an error message describing what happened.
399 *
400 * This function is evil -- it largely replicates fatal(). Hopefully the
401 * entire CRM_Core_Error system can be hollowed out and replaced with
402 * something that follows a cleaner separation of concerns.
403 *
404 * @param Exception $exception
405 */
406 public static function handleUnhandledException($exception) {
407 try {
408 CRM_Utils_Hook::unhandledException($exception);
409 }
410 catch (Exception $other) {
411 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
412 CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other));
413 }
414 $config = CRM_Core_Config::singleton();
415 $vars = array(
416 'message' => $exception->getMessage(),
417 'code' => NULL,
418 'exception' => $exception,
419 );
420 if (!$vars['message']) {
421 $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/'));
422 }
423
424 // Case A: CLI
425 if (php_sapi_name() == "cli") {
426 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
427 print self::formatTextException($exception);
428 die("\n");
429 // FIXME: Why doesn't this call abend()?
430 // Difference: abend() will cleanup transaction and (via civiExit) store session state
431 // self::abend(CRM_Core_Error::FATAL_ERROR);
432 }
433
434 // Case B: Custom error handler
435 if ($config->fatalErrorHandler &&
436 function_exists($config->fatalErrorHandler)
437 ) {
438 $name = $config->fatalErrorHandler;
439 $ret = $name($vars);
440 if ($ret) {
441 // the call has been successfully handled
442 // so we just exit
443 self::abend(CRM_Core_Error::FATAL_ERROR);
444 }
445 }
446
447 // Case C: Default error handler
448
449 // log to file
450 CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE);
451 CRM_Core_Error::backtrace('backTrace', TRUE);
452
453 // print to screen
454 $template = CRM_Core_Smarty::singleton();
455 $template->assign($vars);
456 $content = $template->fetch('CRM/common/fatal.tpl');
457 if ($config->backtrace) {
458 $content = self::formatHtmlException($exception) . $content;
459 }
460 if ($config->userFramework == 'Joomla' &&
461 class_exists('JError')
462 ) {
463 JError::raiseError('CiviCRM-001', $content);
464 }
465 else {
466 echo CRM_Utils_System::theme($content);
467 }
468
469 // fin
470 self::abend(CRM_Core_Error::FATAL_ERROR);
471 }
472
473 /**
474 * Outputs pre-formatted debug information. Flushes the buffers
475 * so we can interrupt a potential POST/redirect
476 *
477 * @param string $name name of debug section
478 * @param $variable mixed reference to variables that we need a trace of
479 * @param bool $log should we log or return the output
480 * @param bool $html whether to generate a HTML-escaped output
481 * @param bool $checkPermission should we check permissions before displaying output
482 * useful when we die during initialization and permissioning
483 * subsystem is not initialized - CRM-13765
484 *
485 * @return string
486 * the generated output
487 */
488 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
489 $error = self::singleton();
490
491 if ($variable === NULL) {
492 $variable = $name;
493 $name = NULL;
494 }
495
496 $out = print_r($variable, TRUE);
497 $prefix = NULL;
498 if ($html) {
499 $out = htmlspecialchars($out);
500 if ($name) {
501 $prefix = "<p>$name</p>";
502 }
503 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
504 }
505 else {
506 if ($name) {
507 $prefix = "$name:\n";
508 }
509 $out = "{$prefix}$out\n";
510 }
511 if (
512 $log &&
513 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
514 ) {
515 echo $out;
516 }
517
518 return $out;
519 }
520
521 /**
522 * Similar to the function debug. Only difference is
523 * in the formatting of the output.
524 *
525 * @param string $variable_name
526 * @param mixed $variable
527 * @param bool $print
528 * Should we use print_r ? (else we use var_dump).
529 * @param bool $log
530 * Should we log or return the output.
531 * @param string $comp
532 * Variable name.
533 *
534 * @return string
535 * the generated output
536 *
537 *
538 *
539 * @see CRM_Core_Error::debug()
540 * @see CRM_Core_Error::debug_log_message()
541 */
542 public static function debug_var(
543 $variable_name,
544 $variable,
545 $print = TRUE,
546 $log = TRUE,
547 $comp = ''
548 ) {
549 // check if variable is set
550 if (!isset($variable)) {
551 $out = "\$$variable_name is not set";
552 }
553 else {
554 if ($print) {
555 $out = print_r($variable, TRUE);
556 $out = "\$$variable_name = $out";
557 }
558 else {
559 // use var_dump
560 ob_start();
561 var_dump($variable);
562 $dump = ob_get_contents();
563 ob_end_clean();
564 $out = "\n\$$variable_name = $dump";
565 }
566 // reset if it is an array
567 if (is_array($variable)) {
568 reset($variable);
569 }
570 }
571 return self::debug_log_message($out, FALSE, $comp);
572 }
573
574 /**
575 * Display the error message on terminal and append it to the log file.
576 *
577 * Provided the user has the 'view debug output' the output should be displayed. In all
578 * cases it should be logged.
579 *
580 * @param string $message
581 * @param bool $out
582 * Should we log or return the output.
583 *
584 * @param string $comp
585 * Message to be output.
586 * @param string $priority
587 *
588 * @return string
589 * Format of the backtrace
590 */
591 public static function debug_log_message($message, $out = FALSE, $comp = '', $priority = NULL) {
592 $config = CRM_Core_Config::singleton();
593
594 $file_log = self::createDebugLogger($comp);
595 $file_log->log("$message\n", $priority);
596
597 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
598 if ($out && CRM_Core_Permission::check('view debug output')) {
599 echo $str;
600 }
601 $file_log->close();
602
603 if (!empty($config->userFrameworkLogging)) {
604 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
605 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
606 watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG);
607 }
608 }
609
610 return $str;
611 }
612
613 /**
614 * Append to the query log (if enabled)
615 *
616 * @param string $string
617 */
618 public static function debug_query($string) {
619 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
620 if (CIVICRM_DEBUG_LOG_QUERY === 'backtrace') {
621 CRM_Core_Error::backtrace($string, TRUE);
622 }
623 elseif (CIVICRM_DEBUG_LOG_QUERY) {
624 CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log');
625 }
626 }
627 }
628
629 /**
630 * Execute a query and log the results.
631 *
632 * @param string $query
633 */
634 public static function debug_query_result($query) {
635 $results = CRM_Core_DAO::executeQuery($query)->fetchAll();
636 CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results));
637 }
638
639 /**
640 * Obtain a reference to the error log.
641 *
642 * @param string $prefix
643 *
644 * @return Log
645 */
646 public static function createDebugLogger($prefix = '') {
647 self::generateLogFileName($prefix);
648 return Log::singleton('file', \Civi::$statics[__CLASS__]['logger_file' . $prefix], '');
649 }
650
651 /**
652 * Generate a hash for the logfile.
653 *
654 * CRM-13640.
655 *
656 * @param CRM_Core_Config $config
657 *
658 * @return string
659 */
660 public static function generateLogFileHash($config) {
661 // Use multiple (but stable) inputs for hash information.
662 $md5inputs = array(
663 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY',
664 $config->userFrameworkBaseURL,
665 md5($config->dsn),
666 $config->dsn,
667 );
668 // Trim 8 chars off the string, make it slightly easier to find
669 // but reveals less information from the hash.
670 return substr(md5(var_export($md5inputs, 1)), 8);
671 }
672
673 /**
674 * Generate the name of the logfile to use and store it as a static.
675 *
676 * This function includes poor man's log file management and a check as to whether the file exists.
677 *
678 * @param string $prefix
679 */
680 protected static function generateLogFileName($prefix) {
681 if (!isset(\Civi::$statics[__CLASS__]['logger_file' . $prefix])) {
682 $config = CRM_Core_Config::singleton();
683
684 $prefixString = $prefix ? ($prefix . '.') : '';
685
686 $hash = self::generateLogFileHash($config);
687 $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . $hash . '.log';
688
689 // Roll log file monthly or if greater than 256M
690 // note that PHP file functions have a limit of 2G and hence
691 // the alternative was introduce
692 if (file_exists($fileName)) {
693 $fileTime = date("Ym", filemtime($fileName));
694 $fileSize = filesize($fileName);
695 if (($fileTime < date('Ym')) ||
696 ($fileSize > 256 * 1024 * 1024) ||
697 ($fileSize < 0)
698 ) {
699 rename($fileName,
700 $fileName . '.' . date('YmdHi')
701 );
702 }
703 }
704 \Civi::$statics[__CLASS__]['logger_file' . $prefix] = $fileName;
705 }
706 }
707
708 /**
709 * @param string $msg
710 * @param bool $log
711 */
712 public static function backtrace($msg = 'backTrace', $log = FALSE) {
713 $backTrace = debug_backtrace();
714 $message = self::formatBacktrace($backTrace);
715 if (!$log) {
716 CRM_Core_Error::debug($msg, $message);
717 }
718 else {
719 CRM_Core_Error::debug_var($msg, $message);
720 }
721 }
722
723 /**
724 * Render a backtrace array as a string.
725 *
726 * @param array $backTrace
727 * Array of stack frames.
728 * @param bool $showArgs
729 * 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.
730 * @param int $maxArgLen
731 * Maximum number of characters to show from each argument string.
732 * @return string
733 * printable plain-text
734 */
735 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
736 $message = '';
737 foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
738 $message .= sprintf("#%s %s\n", $idx, $trace);
739 }
740 $message .= sprintf("#%s {main}\n", 1 + $idx);
741 return $message;
742 }
743
744 /**
745 * Render a backtrace array as an array.
746 *
747 * @param array $backTrace
748 * Array of stack frames.
749 * @param bool $showArgs
750 * 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.
751 * @param int $maxArgLen
752 * Maximum number of characters to show from each argument string.
753 * @return array
754 * @see debug_backtrace
755 * @see Exception::getTrace()
756 */
757 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
758 $ret = array();
759 foreach ($backTrace as $trace) {
760 $args = array();
761 $fnName = CRM_Utils_Array::value('function', $trace);
762 $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
763
764 // Do not show args for a few password related functions
765 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
766
767 if (!empty($trace['args'])) {
768 foreach ($trace['args'] as $arg) {
769 if (!$showArgs || $skipArgs) {
770 $args[] = '(' . gettype($arg) . ')';
771 continue;
772 }
773 switch ($type = gettype($arg)) {
774 case 'boolean':
775 $args[] = $arg ? 'TRUE' : 'FALSE';
776 break;
777
778 case 'integer':
779 case 'double':
780 $args[] = $arg;
781 break;
782
783 case 'string':
784 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
785 break;
786
787 case 'array':
788 $args[] = '(Array:' . count($arg) . ')';
789 break;
790
791 case 'object':
792 $args[] = 'Object(' . get_class($arg) . ')';
793 break;
794
795 case 'resource':
796 $args[] = 'Resource';
797 break;
798
799 case 'NULL':
800 $args[] = 'NULL';
801 break;
802
803 default:
804 $args[] = "($type)";
805 break;
806 }
807 }
808 }
809
810 $ret[] = sprintf(
811 "%s(%s): %s%s(%s)",
812 CRM_Utils_Array::value('file', $trace, '[internal function]'),
813 CRM_Utils_Array::value('line', $trace, ''),
814 $className,
815 $fnName,
816 implode(", ", $args)
817 );
818 }
819 return $ret;
820 }
821
822 /**
823 * Render an exception as HTML string.
824 *
825 * @param Exception $e
826 * @return string
827 * printable HTML text
828 */
829 public static function formatHtmlException(Exception $e) {
830 $msg = '';
831
832 // Exception metadata
833
834 // Exception backtrace
835 if ($e instanceof PEAR_Exception) {
836 $ei = $e;
837 while (is_callable(array($ei, 'getCause'))) {
838 if ($ei->getCause() instanceof PEAR_Error) {
839 $msg .= '<table class="crm-db-error">';
840 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
841 $msg .= '<tbody>';
842 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
843 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
844 }
845 $msg .= '</tbody></table>';
846 }
847 $ei = $ei->getCause();
848 }
849 $msg .= $e->toHtml();
850 }
851 else {
852 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
853 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
854 }
855 return $msg;
856 }
857
858 /**
859 * Write details of an exception to the log.
860 *
861 * @param Exception $e
862 * @return string
863 * printable plain text
864 */
865 public static function formatTextException(Exception $e) {
866 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
867
868 $ei = $e;
869 while (is_callable(array($ei, 'getCause'))) {
870 if ($ei->getCause() instanceof PEAR_Error) {
871 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
872 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
873 }
874 }
875 $ei = $ei->getCause();
876 }
877 $msg .= self::formatBacktrace($e->getTrace());
878 return $msg;
879 }
880
881 /**
882 * @param $message
883 * @param int $code
884 * @param string $level
885 * @param array $params
886 *
887 * @return object
888 */
889 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
890 $error = CRM_Core_Error::singleton();
891 $error->push($code, $level, array($params), $message);
892 return $error;
893 }
894
895 /**
896 * Set a status message in the session, then bounce back to the referrer.
897 *
898 * @param string $status
899 * The status message to set.
900 *
901 * @param null $redirect
902 * @param string $title
903 */
904 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
905 $session = CRM_Core_Session::singleton();
906 if (!$redirect) {
907 $redirect = $session->readUserContext();
908 }
909 if ($title === NULL) {
910 $title = ts('Error');
911 }
912 $session->setStatus($status, $title, 'alert', array('expires' => 0));
913 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
914 CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error'));
915 }
916 CRM_Utils_System::redirect($redirect);
917 }
918
919 /**
920 * Reset the error stack.
921 *
922 */
923 public static function reset() {
924 $error = self::singleton();
925 $error->_errors = array();
926 $error->_errorsByLevel = array();
927 }
928
929 /**
930 * PEAR error-handler which converts errors to exceptions
931 *
932 * @param $pearError
933 * @throws PEAR_Exception
934 */
935 public static function exceptionHandler($pearError) {
936 CRM_Core_Error::debug_var('Fatal Error Details', self::getErrorDetails($pearError));
937 CRM_Core_Error::backtrace('backTrace', TRUE);
938 throw new PEAR_Exception($pearError->getMessage(), $pearError);
939 }
940
941 /**
942 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
943 *
944 * @param object $obj
945 * The PEAR_ERROR object.
946 * @return object
947 * $obj
948 */
949 public static function nullHandler($obj) {
950 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
951 CRM_Core_Error::backtrace('backTrace', TRUE);
952 return $obj;
953 }
954
955 /**
956 * @deprecated
957 * This function is no longer used by v3 api.
958 * @fixme Some core files call it but it should be re-thought & renamed or removed
959 *
960 * @param $msg
961 * @param null $data
962 *
963 * @return array
964 * @throws Exception
965 */
966 public static function &createAPIError($msg, $data = NULL) {
967 if (self::$modeException) {
968 throw new Exception($msg, $data);
969 }
970
971 $values = array();
972
973 $values['is_error'] = 1;
974 $values['error_message'] = $msg;
975 if (isset($data)) {
976 $values = array_merge($values, $data);
977 }
978 return $values;
979 }
980
981 /**
982 * @param $file
983 */
984 public static function movedSiteError($file) {
985 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
986 'reset=1',
987 TRUE
988 );
989 echo "We could not write $file. Have you moved your site directory or server?<p>";
990 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
991 exit();
992 }
993
994 /**
995 * Terminate execution abnormally.
996 *
997 * @param string $code
998 */
999 protected static function abend($code) {
1000 // do a hard rollback of any pending transactions
1001 // if we've come here, its because of some unexpected PEAR errors
1002 CRM_Core_Transaction::forceRollbackIfEnabled();
1003 CRM_Utils_System::civiExit($code);
1004 }
1005
1006 /**
1007 * @param array $error
1008 * @param int $type
1009 *
1010 * @return bool
1011 */
1012 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
1013 if (is_array($error) && !empty($error['is_error'])) {
1014 $code = $error['error_message']['code'];
1015 if ($code == $type) {
1016 return TRUE;
1017 }
1018 }
1019 return FALSE;
1020 }
1021
1022 }
1023
1024 $e = new PEAR_ErrorStack('CRM');
1025 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');