Merge pull request #24162 from colemanw/savedSearchLabel
[civicrm-core.git] / CRM / Core / Error.php
... / ...
CommitLineData
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
20require_once 'PEAR/ErrorStack.php';
21require_once 'PEAR/Exception.php';
22require_once 'CRM/Core/Exception.php';
23
24require_once 'Log.php';
25
26/**
27 * Class CRM_Core_Error
28 */
29class 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 $exit = TRUE;
208 if ($config->initialized) {
209 $content = $template->fetch('CRM/common/fatal.tpl');
210 echo CRM_Utils_System::theme($content);
211 $exit = CRM_Utils_System::shouldExitAfterFatal();
212 }
213 else {
214 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
215 CRM_Core_Error::debug(NULL, $error);
216 }
217 static $runOnce = FALSE;
218 if ($runOnce) {
219 exit;
220 }
221 $runOnce = TRUE;
222
223 if ($exit) {
224 self::abend(CRM_Core_Error::FATAL_ERROR);
225 }
226 else {
227 self::inpageExceptionDisplay(CRM_Core_Error::FATAL_ERROR);
228 }
229 }
230
231 /**
232 * this function is used to trap and print errors
233 * during system initialization time. Hence the error
234 * message is quite ugly
235 *
236 * @param $pearError
237 */
238 public static function simpleHandler($pearError) {
239
240 $error = self::getErrorDetails($pearError);
241
242 // ensure that debug does not check permissions since we are in bootstrap
243 // mode and need to print a decent message to help the user
244 CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
245
246 // always log the backtrace to a file
247 self::backtrace('backTrace', TRUE);
248
249 exit(0);
250 }
251
252 /**
253 * This function is used to return error details
254 *
255 * @param PEAR_Error $pearError
256 *
257 * @return array $error
258 */
259 public static function getErrorDetails($pearError) {
260 // create the error array
261 $error = [];
262 $error['callback'] = $pearError->getCallback();
263 $error['code'] = $pearError->getCode();
264 $error['message'] = $pearError->getMessage();
265 $error['mode'] = $pearError->getMode();
266 $error['debug_info'] = $pearError->getDebugInfo();
267 $error['type'] = $pearError->getType();
268 $error['user_info'] = $pearError->getUserInfo();
269 $error['to_string'] = $pearError->toString();
270
271 return $error;
272 }
273
274 /**
275 * Handle errors raised using the PEAR Error Stack.
276 *
277 * currently the handler just requests the PES framework
278 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
279 *
280 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
281 *
282 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
283 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
284 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
285 *
286 * @param mixed $pearError
287 *
288 * @return int
289 */
290 public static function handlePES($pearError) {
291 return PEAR_ERRORSTACK_PUSH;
292 }
293
294 /**
295 * Display an error page with an error message describing what happened.
296 *
297 * @deprecated
298 * This is a really annoying function. We ❤ exceptions. Be exceptional!
299 *
300 * @see CRM-20181
301 *
302 * @param string $message
303 * The error message.
304 * @param string $code
305 * The error code if any.
306 * @param string $email
307 * The email address to notify of this situation.
308 *
309 * @throws Exception
310 */
311 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
312 CRM_Core_Error::deprecatedFunctionWarning('throw new CRM_Core_Exception or use CRM_Core_Error::statusBounce', 'CRM_Core_Error::fatal');
313 $vars = [
314 'message' => $message,
315 'code' => $code,
316 ];
317
318 if (self::$modeException) {
319 // CRM-11043
320 CRM_Core_Error::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR);
321 CRM_Core_Error::backtrace('backTrace', TRUE);
322
323 $details = 'A fatal error was triggered';
324 if ($message) {
325 $details .= ': ' . $message;
326 }
327 throw new Exception($details, $code);
328 }
329
330 if (!$message) {
331 $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']);
332 }
333
334 if (php_sapi_name() == "cli") {
335 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
336 // Fix for CRM-16899
337 echo static::formatBacktrace(debug_backtrace());
338 die("\n");
339 // FIXME: Why doesn't this call abend()?
340 // Difference: abend() will cleanup transaction and (via civiExit) store session state
341 // self::abend(CRM_Core_Error::FATAL_ERROR);
342 }
343
344 $config = CRM_Core_Config::singleton();
345
346 if ($config->fatalErrorHandler &&
347 function_exists($config->fatalErrorHandler)
348 ) {
349 $name = $config->fatalErrorHandler;
350 $ret = $name($vars);
351 if ($ret) {
352 // the call has been successfully handled
353 // so we just exit
354 self::abend(CRM_Core_Error::FATAL_ERROR);
355 }
356 }
357
358 if ($config->backtrace) {
359 self::backtrace();
360 }
361
362 CRM_Core_Error::debug_var('Fatal Error Details', $vars, TRUE, TRUE, '', PEAR_LOG_ERR);
363 CRM_Core_Error::backtrace('backTrace', TRUE);
364
365 // If we are in an ajax callback, format output appropriately
366 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
367 $out = [
368 'status' => 'fatal',
369 'content' => '<div class="messages status no-popup">' . CRM_Core_Page::crmIcon('fa-info-circle') . ' ' . ts('Sorry but we are not able to provide this at the moment.') . '</div>',
370 ];
371 if ($config->backtrace && CRM_Core_Permission::check('view debug output')) {
372 $out['backtrace'] = self::parseBacktrace(debug_backtrace());
373 $message .= '<p><em>See console for backtrace</em></p>';
374 }
375 CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error');
376 CRM_Core_Transaction::forceRollbackIfEnabled();
377 CRM_Core_Page_AJAX::returnJsonResponse($out);
378 }
379
380 $template = CRM_Core_Smarty::singleton();
381 $template->assign($vars);
382 $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl'));
383
384 self::abend(CRM_Core_Error::FATAL_ERROR);
385 }
386
387 /**
388 * Display an error page with an error message describing what happened.
389 *
390 * This function is evil -- it largely replicates fatal(). Hopefully the
391 * entire CRM_Core_Error system can be hollowed out and replaced with
392 * something that follows a cleaner separation of concerns.
393 *
394 * @param Exception $exception
395 */
396 public static function handleUnhandledException($exception) {
397 try {
398 CRM_Utils_Hook::unhandledException($exception);
399 }
400 catch (Exception $other) {
401 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
402 CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other), TRUE, TRUE, '', PEAR_LOG_ERR);
403 }
404 $config = CRM_Core_Config::singleton();
405 $vars = [
406 'message' => $exception->getMessage(),
407 'code' => NULL,
408 'exception' => $exception,
409 ];
410 if (!$vars['message']) {
411 $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']);
412 }
413
414 // Case A: CLI
415 if (php_sapi_name() == "cli") {
416 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
417 print self::formatTextException($exception);
418 die("\n");
419 // FIXME: Why doesn't this call abend()?
420 // Difference: abend() will cleanup transaction and (via civiExit) store session state
421 // self::abend(CRM_Core_Error::FATAL_ERROR);
422 }
423
424 // Case B: Custom error handler
425 if ($config->fatalErrorHandler &&
426 function_exists($config->fatalErrorHandler)
427 ) {
428 $name = $config->fatalErrorHandler;
429 $ret = $name($vars);
430 if ($ret) {
431 // the call has been successfully handled
432 // so we just exit
433 self::abend(CRM_Core_Error::FATAL_ERROR);
434 }
435 }
436
437 // Case C: Default error handler
438
439 // log to file
440 CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE, TRUE, '', PEAR_LOG_ERR);
441 CRM_Core_Error::backtrace('backTrace', TRUE);
442
443 // print to screen
444 $template = CRM_Core_Smarty::singleton();
445 $template->assign($vars);
446 $content = $template->fetch('CRM/common/fatal.tpl');
447
448 if ($config->backtrace) {
449 $content = self::formatHtmlException($exception) . $content;
450 }
451
452 echo CRM_Utils_System::theme($content);
453 $exit = CRM_Utils_System::shouldExitAfterFatal();
454
455 if ($exit) {
456 self::abend(CRM_Core_Error::FATAL_ERROR);
457 }
458 else {
459 self::inpageExceptionDisplay(CRM_Core_Error::FATAL_ERROR);
460 }
461 }
462
463 /**
464 * Outputs pre-formatted debug information. Flushes the buffers
465 * so we can interrupt a potential POST/redirect
466 *
467 * @param string $name name of debug section
468 * @param mixed $variable reference to variables that we need a trace of
469 * @param bool $log should we log or return the output
470 * @param bool $html whether to generate a HTML-escaped output
471 * @param bool $checkPermission should we check permissions before displaying output
472 * useful when we die during initialization and permissioning
473 * subsystem is not initialized - CRM-13765
474 *
475 * @return string
476 * the generated output
477 */
478 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
479 $error = self::singleton();
480
481 if ($variable === NULL) {
482 $variable = $name;
483 $name = NULL;
484 }
485
486 $out = print_r($variable, TRUE);
487 $prefix = NULL;
488 if ($html) {
489 $out = htmlspecialchars($out);
490 if ($name) {
491 $prefix = "<p>$name</p>";
492 }
493 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
494 }
495 else {
496 if ($name) {
497 $prefix = "$name:\n";
498 }
499 $out = "{$prefix}$out\n";
500 }
501 if (
502 $log &&
503 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
504 ) {
505 echo $out;
506 }
507
508 return $out;
509 }
510
511 /**
512 * Similar to the function debug. Only difference is
513 * in the formatting of the output.
514 *
515 * @param string $variable_name
516 * Variable name.
517 * @param mixed $variable
518 * Variable value.
519 * @param bool $print
520 * Use print_r (if true) or var_dump (if false).
521 * @param bool $log
522 * Log or return the output?
523 * @param string $prefix
524 * Prefix for output logfile.
525 * @param int $priority
526 * The log priority level.
527 *
528 * @return string
529 * The generated output
530 *
531 * @see CRM_Core_Error::debug()
532 * @see CRM_Core_Error::debug_log_message()
533 */
534 public static function debug_var($variable_name, $variable, $print = TRUE, $log = TRUE, $prefix = '', $priority = NULL) {
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 Symfony var-dumper to avoid circular references that exhaust
546 // memory when using var_dump().
547 // Use its CliDumper since if we use the simpler `dump()` then it
548 // comes out as some overly decorated html which is hard to read.
549 $dump = (new \Symfony\Component\VarDumper\Dumper\CliDumper('php://output'))
550 ->dump(
551 (new \Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($variable),
552 TRUE);
553 $out = "\n\$$variable_name = $dump";
554 }
555 // reset if it is an array
556 if (is_array($variable)) {
557 reset($variable);
558 }
559 }
560 return self::debug_log_message($out, FALSE, $prefix, $priority);
561 }
562
563 /**
564 * Display the error message on terminal and append it to the log file.
565 *
566 * Provided the user has the 'view debug output' the output should be displayed. In all
567 * cases it should be logged.
568 *
569 * @param string $message
570 * @param bool $out
571 * Should we log or return the output.
572 *
573 * @param string $prefix
574 * Message prefix.
575 * @param string $priority
576 *
577 * @return string
578 * Format of the backtrace
579 */
580 public static function debug_log_message($message, $out = FALSE, $prefix = '', $priority = NULL) {
581 $config = CRM_Core_Config::singleton();
582
583 $file_log = self::createDebugLogger($prefix);
584 $file_log->log("$message\n", $priority);
585
586 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
587 if ($out && CRM_Core_Permission::check('view debug output')) {
588 echo $str;
589 }
590 $file_log->close();
591
592 if (!isset(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) {
593 // Set it to FALSE first & then try to set it. This is to prevent a loop as calling
594 // $config->userFrameworkLogging can trigger DB queries & under log mode this
595 // then gets called again.
596 \Civi::$statics[__CLASS__]['userFrameworkLogging'] = FALSE;
597 \Civi::$statics[__CLASS__]['userFrameworkLogging'] = $config->userFrameworkLogging;
598 }
599
600 if (!empty(\Civi::$statics[__CLASS__]['userFrameworkLogging'])) {
601 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
602 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
603 watchdog('civicrm', '%message', ['%message' => $message], $priority ?? WATCHDOG_DEBUG);
604 }
605 elseif ($config->userSystem->is_drupal and CIVICRM_UF == 'Drupal8') {
606 \Drupal::logger('civicrm')->log($priority ?? \Drupal\Core\Logger\RfcLogLevel::DEBUG, '%message', ['%message' => $message]);
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 $debugLogQuery = CRM_Utils_Constant::value('CIVICRM_DEBUG_LOG_QUERY', FALSE);
620 if ($debugLogQuery === 'backtrace') {
621 CRM_Core_Error::backtrace($string, TRUE);
622 }
623 elseif ($debugLogQuery) {
624 CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log' . $debugLogQuery, PEAR_LOG_DEBUG);
625 }
626 }
627
628 /**
629 * Execute a query and log the results.
630 *
631 * @param string $query
632 */
633 public static function debug_query_result($query) {
634 $results = CRM_Core_DAO::executeQuery($query)->fetchAll();
635 CRM_Core_Error::debug_var('dao result', ['query' => $query, 'results' => $results], TRUE, TRUE, '', PEAR_LOG_DEBUG);
636 }
637
638 /**
639 * Obtain a reference to the error log.
640 *
641 * @param string $prefix
642 *
643 * @return Log_file
644 */
645 public static function createDebugLogger($prefix = '') {
646 self::generateLogFileName($prefix);
647 return Log::singleton('file', \Civi::$statics[__CLASS__]['logger_file' . $prefix], '');
648 }
649
650 /**
651 * Generate a hash for the logfile.
652 *
653 * CRM-13640.
654 *
655 * @param CRM_Core_Config $config
656 *
657 * @return string
658 */
659 public static function generateLogFileHash($config) {
660 // Use multiple (but stable) inputs for hash information.
661 $md5inputs = [
662 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY',
663 CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE),
664 md5($config->dsn),
665 $config->dsn,
666 ];
667 // Trim 8 chars off the string, make it slightly easier to find
668 // but reveals less information from the hash.
669 return substr(md5(var_export($md5inputs, 1)), 8);
670 }
671
672 /**
673 * Generate the name of the logfile to use and store it as a static.
674 *
675 * This function includes simplistic log rotation and a check as to whether
676 * 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 if (CRM_Utils_Constant::value('CIVICRM_LOG_HASH', TRUE)) {
687 $hash = self::generateLogFileHash($config) . '.';
688 }
689 else {
690 $hash = '';
691 }
692 $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . $hash . 'log';
693
694 // Roll log file monthly or if greater than our threshold.
695 // Size-based rotation introduced in response to filesize limits on
696 // certain OS/PHP combos.
697 $maxBytes = CRM_Utils_Constant::value('CIVICRM_LOG_ROTATESIZE', 256 * 1024 * 1024);
698 if ($maxBytes) {
699 if (file_exists($fileName)) {
700 $fileTime = date("Ym", filemtime($fileName));
701 $fileSize = filesize($fileName);
702 if (($fileTime < date('Ym')) ||
703 ($fileSize > $maxBytes) ||
704 ($fileSize < 0)
705 ) {
706 rename($fileName,
707 $fileName . '.' . date('YmdHi')
708 );
709 }
710 }
711 }
712 \Civi::$statics[__CLASS__]['logger_file' . $prefix] = $fileName;
713 }
714 }
715
716 /**
717 * @param string $msg
718 * @param bool $log
719 */
720 public static function backtrace($msg = 'backTrace', $log = FALSE) {
721 $backTrace = debug_backtrace();
722 $message = self::formatBacktrace($backTrace);
723 if (!$log) {
724 CRM_Core_Error::debug($msg, $message);
725 }
726 else {
727 CRM_Core_Error::debug_var($msg, $message, TRUE, TRUE, '', PEAR_LOG_DEBUG);
728 }
729 }
730
731 /**
732 * Render a backtrace array as a string.
733 *
734 * @param array $backTrace
735 * Array of stack frames.
736 * @param bool $showArgs
737 * 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.
738 * @param int $maxArgLen
739 * Maximum number of characters to show from each argument string.
740 * @return string
741 * printable plain-text
742 */
743 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
744 $message = '';
745 foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
746 $message .= sprintf("#%s %s\n", $idx, $trace);
747 }
748 $message .= sprintf("#%s {main}\n", 1 + $idx);
749 return $message;
750 }
751
752 /**
753 * Render a backtrace array as an array.
754 *
755 * @param array $backTrace
756 * Array of stack frames.
757 * @param bool $showArgs
758 * 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.
759 * @param int $maxArgLen
760 * Maximum number of characters to show from each argument string.
761 * @return array
762 * @see debug_backtrace
763 * @see Exception::getTrace()
764 */
765 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
766 $ret = [];
767 foreach ($backTrace as $trace) {
768 $args = [];
769 $fnName = $trace['function'] ?? NULL;
770 $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
771
772 // Do not show args for a few password related functions
773 $skipArgs = $className == 'DB::' && $fnName == 'connect';
774
775 if (!empty($trace['args'])) {
776 foreach ($trace['args'] as $arg) {
777 if (!$showArgs || $skipArgs) {
778 $args[] = '(' . gettype($arg) . ')';
779 continue;
780 }
781 switch ($type = gettype($arg)) {
782 case 'boolean':
783 $args[] = $arg ? 'TRUE' : 'FALSE';
784 break;
785
786 case 'integer':
787 case 'double':
788 $args[] = $arg;
789 break;
790
791 case 'string':
792 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
793 break;
794
795 case 'array':
796 $args[] = '(Array:' . count($arg) . ')';
797 break;
798
799 case 'object':
800 $args[] = 'Object(' . get_class($arg) . ')';
801 break;
802
803 case 'resource':
804 $args[] = 'Resource';
805 break;
806
807 case 'NULL':
808 $args[] = 'NULL';
809 break;
810
811 default:
812 $args[] = "($type)";
813 break;
814 }
815 }
816 }
817
818 $ret[] = sprintf(
819 "%s(%s): %s%s(%s)",
820 CRM_Utils_Array::value('file', $trace, '[internal function]'),
821 CRM_Utils_Array::value('line', $trace, ''),
822 $className,
823 $fnName,
824 implode(", ", $args)
825 );
826 }
827 return $ret;
828 }
829
830 /**
831 * Render an exception as HTML string.
832 *
833 * @param Throwable $e
834 * @return string
835 * printable HTML text
836 */
837 public static function formatHtmlException(Throwable $e) {
838 $msg = '';
839
840 // Exception metadata
841
842 // Exception backtrace
843 if ($e instanceof PEAR_Exception) {
844 $ei = $e;
845 if (is_callable([$ei, 'getCause'])) {
846 // DB_ERROR doesn't have a getCause but does have a __call function which tricks is_callable.
847 if (!$ei instanceof DB_Error) {
848 if ($ei->getCause() instanceof PEAR_Error) {
849 $msg .= '<table class="crm-db-error">';
850 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
851 $msg .= '<tbody>';
852 foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) {
853 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func([$ei->getCause(), "get$f"]));
854 }
855 $msg .= '</tbody></table>';
856 }
857 $ei = $ei->getCause();
858 }
859 }
860 $msg .= $e->toHtml();
861 }
862 else {
863 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
864 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
865 }
866 return $msg;
867 }
868
869 /**
870 * Write details of an exception to the log.
871 *
872 * @param Throwable $e
873 * @return string
874 * printable plain text
875 */
876 public static function formatTextException(Throwable $e) {
877 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
878
879 $ei = $e;
880 while (is_callable([$ei, 'getCause'])) {
881 // DB_ERROR doesn't have a getCause but does have a __call function which tricks is_callable.
882 if (!$ei instanceof DB_Error) {
883 if ($ei->getCause() instanceof PEAR_Error) {
884 foreach (['Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo'] as $f) {
885 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func([$ei->getCause(), "get$f"]));
886 }
887 }
888 $ei = $ei->getCause();
889 }
890 // if we have reached a DB_Error assume that is the end of the road.
891 else {
892 $ei = NULL;
893 }
894 }
895 $msg .= self::formatBacktrace($e->getTrace());
896 return $msg;
897 }
898
899 /**
900 * @param $message
901 * @param int $code
902 * @param string $level
903 * @param array $params
904 *
905 * @return object
906 */
907 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
908 $error = CRM_Core_Error::singleton();
909 $error->push($code, $level, [$params], $message);
910 return $error;
911 }
912
913 /**
914 * Set a status message in the session, then bounce back to the referrer.
915 *
916 * @param string $status
917 * The status message to set.
918 * @param string|null $redirect
919 * @param string|null $title
920 */
921 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
922 $session = CRM_Core_Session::singleton();
923 if (!$redirect) {
924 $redirect = $session->readUserContext();
925 }
926 if ($title === NULL) {
927 $title = ts('Error');
928 }
929 $session->setStatus($status, $title, 'alert', ['expires' => 0]);
930 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
931 CRM_Core_Page_AJAX::returnJsonResponse(['status' => 'error']);
932 }
933 CRM_Utils_System::redirect($redirect);
934 }
935
936 /**
937 * Reset the error stack.
938 *
939 */
940 public static function reset() {
941 $error = self::singleton();
942 $error->_errors = [];
943 $error->_errorsByLevel = [];
944 }
945
946 /**
947 * PEAR error-handler which converts errors to exceptions
948 *
949 * @param PEAR_Error $pearError
950 * @throws PEAR_Exception
951 */
952 public static function exceptionHandler($pearError) {
953 CRM_Core_Error::debug_var('Fatal Error Details', self::getErrorDetails($pearError), TRUE, TRUE, '', PEAR_LOG_ERR);
954 CRM_Core_Error::backtrace('backTrace', TRUE);
955 throw new PEAR_Exception($pearError->getMessage(), $pearError);
956 }
957
958 /**
959 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
960 *
961 * @param object $obj
962 * The PEAR_ERROR object.
963 * @return object
964 * $obj
965 */
966 public static function nullHandler($obj) {
967 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}", FALSE, '', PEAR_LOG_ERR);
968 CRM_Core_Error::backtrace('backTrace', TRUE);
969 return $obj;
970 }
971
972 /**
973 * @deprecated
974 * This function is no longer used by v3 api.
975 * @fixme Some core files call it but it should be re-thought & renamed or removed
976 *
977 * @param $msg
978 * @param null $data
979 *
980 * @return array
981 * @throws Exception
982 */
983 public static function &createAPIError($msg, $data = NULL) {
984 if (self::$modeException) {
985 throw new Exception($msg, $data);
986 }
987
988 $values = [];
989
990 $values['is_error'] = 1;
991 $values['error_message'] = $msg;
992 if (isset($data)) {
993 $values = array_merge($values, $data);
994 }
995 return $values;
996 }
997
998 /**
999 * @param $file
1000 */
1001 public static function movedSiteError($file) {
1002 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
1003 'reset=1',
1004 TRUE
1005 );
1006 echo "We could not write $file. Have you moved your site directory or server?<p>";
1007 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
1008 exit();
1009 }
1010
1011 /**
1012 * Terminate execution abnormally.
1013 *
1014 * @param int $code
1015 */
1016 protected static function abend($code) {
1017 // do a hard rollback of any pending transactions
1018 // if we've come here, its because of some unexpected PEAR errors
1019 CRM_Core_Transaction::forceRollbackIfEnabled();
1020 CRM_Utils_System::civiExit($code);
1021 }
1022
1023 /**
1024 * Show in-page exception
1025 * For situations where where calling abend will block the ability for a branded error screen
1026 *
1027 * Although the host page will run past this point, CiviCRM should not,
1028 * therefore we trigger the civi.exit events
1029 *
1030 * @param string $code
1031 */
1032 protected static function inpageExceptionDisplay($code) {
1033 // do a hard rollback of any pending transactions
1034 // if we've come here, its because of some unexpected PEAR errors
1035 CRM_Core_Transaction::forceRollbackIfEnabled();
1036
1037 if ($code > 0 && !headers_sent()) {
1038 http_response_code(500);
1039 }
1040
1041 // move things to CiviCRM cache as needed
1042 CRM_Core_Session::storeSessionObjects();
1043
1044 if (Civi\Core\Container::isContainerBooted()) {
1045 Civi::dispatcher()->dispatch('civi.core.exit');
1046 }
1047
1048 $userSystem = CRM_Core_Config::singleton()->userSystem;
1049 if (is_callable([$userSystem, 'onCiviExit'])) {
1050 $userSystem->onCiviExit();
1051 }
1052 }
1053
1054 /**
1055 * @param array $error
1056 * @param int $type
1057 *
1058 * @return bool
1059 */
1060 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
1061 if (is_array($error) && !empty($error['is_error'])) {
1062 $code = $error['error_message']['code'];
1063 if ($code == $type) {
1064 return TRUE;
1065 }
1066 }
1067 return FALSE;
1068 }
1069
1070 /**
1071 * Output a deprecated function warning to log file.
1072 *
1073 * Deprecated class:function is automatically generated from calling function.
1074 *
1075 * @param string $newMethod
1076 * description of new method (eg. "buildOptions() method in the appropriate BAO object").
1077 * @param string|null $oldMethod
1078 * optional description of old method (if not the calling method). eg. CRM_MyClass::myOldMethodToGetTheOptions()
1079 */
1080 public static function deprecatedFunctionWarning(string $newMethod, ?string $oldMethod = NULL): void {
1081 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4);
1082 if (!$oldMethod) {
1083 $callerFunction = $backtrace[1]['function'] ?? NULL;
1084 $callerClass = $backtrace[1]['class'] ?? NULL;
1085 $oldMethod = "{$callerClass}::{$callerFunction}";
1086 }
1087 $message = "Deprecated function $oldMethod, use $newMethod.";
1088 // Add a mini backtrace. Just the function is too little to be meaningful but people are
1089 // saying they can't track down where the deprecated calls are coming from.
1090 $miniBacktrace = [];
1091 foreach ($backtrace as $backtraceLine) {
1092 $miniBacktrace[] = ($backtraceLine['class'] ?? '') . '::' . ($backtraceLine['function'] ?? '');
1093 }
1094 Civi::log()->warning($message . "\n" . implode("\n", $miniBacktrace), ['civi.tag' => 'deprecated']);
1095 trigger_error($message, E_USER_DEPRECATED);
1096 }
1097
1098 /**
1099 * Output a deprecated notice about a deprecated call path, rather than deprecating a whole function.
1100 *
1101 * @param string $message
1102 */
1103 public static function deprecatedWarning($message) {
1104 // Even though the tag is no longer used within the log() function,
1105 // \Civi\API\LogObserver instances may still be monitoring it.
1106 $dbt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
1107 $callerFunction = $dbt[2]['function'] ?? NULL;
1108 $callerClass = $dbt[2]['class'] ?? NULL;
1109 $message .= " Caller: {$callerClass}::{$callerFunction}";
1110 Civi::log()->warning($message, ['civi.tag' => 'deprecated']);
1111 trigger_error($message, E_USER_DEPRECATED);
1112 }
1113
1114}
1115
1116$e = new PEAR_ErrorStack('CRM');
1117$e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');