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