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