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