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