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