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