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