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