Merge pull request #9239 from jitendrapurohit/CRM-19443
[civicrm-core.git] / CRM / Core / Error.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 33 * @copyright CiviCRM LLC (c) 2004-2016
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 *
6a488035 109 * @return object
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 }
152 return NULL;
153 }
154
dbddfb08 155 /**
0880a9d0 156 * Status display function specific to payment processor errors.
dbddfb08
EM
157 * @param $error
158 * @param string $separator
159 */
00be9182 160 public static function displaySessionError(&$error, $separator = '<br />') {
6a488035
TO
161 $message = self::getMessages($error, $separator);
162 if ($message) {
163 $status = ts("Payment Processor Error message") . "{$separator} $message";
164 $session = CRM_Core_Session::singleton();
165 $session->setStatus($status);
166 }
167 }
168
169 /**
100fef9d 170 * Create the main callback method. this method centralizes error processing.
6a488035
TO
171 *
172 * the errors we expect are from the pear modules DB, DB_DataObject
173 * which currently use PEAR::raiseError to notify of error messages.
174 *
3bdca100 175 * @param object $pearError PEAR_Error
6a488035
TO
176 */
177 public static function handle($pearError) {
2b2c4099
TO
178 if (defined('CIVICRM_TEST')) {
179 return self::simpleHandler($pearError);
180 }
6a488035
TO
181
182 // setup smarty with config, session and template location.
183 $template = CRM_Core_Smarty::singleton();
184 $config = CRM_Core_Config::singleton();
185
186 if ($config->backtrace) {
187 self::backtrace();
188 }
189
190 // create the error array
ca8416c8 191 $error = self::getErrorDetails($pearError);
2e4ade96
TO
192
193 // We access connection info via _DB_DATAOBJECT instead
194 // of, e.g., calling getDatabaseConnection(), so that we
195 // can avoid infinite loops.
196 global $_DB_DATAOBJECT;
197
198 if (!isset($_DB_DATAOBJECT['CONFIG']['database'])) {
199 // we haven't setup sql, so it's not our sql error...
200 }
201 elseif (preg_match('/^mysql:/', $_DB_DATAOBJECT['CONFIG']['database']) &&
6a488035
TO
202 mysql_error()
203 ) {
204 $mysql_error = mysql_error() . ', ' . mysql_errno();
205 $template->assign_by_ref('mysql_code', $mysql_error);
206
207 // execute a dummy query to clear error stack
208 mysql_query('select 1');
209 }
2e4ade96 210 elseif (preg_match('/^mysqli:/', $_DB_DATAOBJECT['CONFIG']['database'])) {
6a488035
TO
211 $dao = new CRM_Core_DAO();
212
6a488035
TO
213 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) {
214 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
215 $link = $conn->connection;
216
217 if (mysqli_error($link)) {
218 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
219 $template->assign_by_ref('mysql_code', $mysql_error);
220
221 // execute a dummy query to clear error stack
222 mysqli_query($link, 'select 1');
223 }
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 *
6a0b768e
TO
316 * @param string $message
317 * The error message.
318 * @param string $code
319 * The error code if any.
320 * @param string $email
321 * The email address to notify of this situation.
77b97be7
EM
322 *
323 * @throws Exception
6a488035 324 */
00be9182 325 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
6a488035 326 $vars = array(
0ac9fd52 327 'message' => htmlspecialchars($message),
6a488035
TO
328 'code' => $code,
329 );
330
331 if (self::$modeException) {
332 // CRM-11043
333 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
334 CRM_Core_Error::backtrace('backTrace', TRUE);
335
336 $details = 'A fatal error was triggered';
337 if ($message) {
338 $details .= ': ' . $message;
2aa397bc 339 }
6a488035
TO
340 throw new Exception($details, $code);
341 }
342
343 if (!$message) {
344 $message = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/'));
345 }
346
347 if (php_sapi_name() == "cli") {
348 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
0c4a3d8b 349 // Fix for CRM-16899
4c68cf7b 350 echo static::formatBacktrace(debug_backtrace());
6a488035
TO
351 die("\n");
352 // FIXME: Why doesn't this call abend()?
353 // Difference: abend() will cleanup transaction and (via civiExit) store session state
354 // self::abend(CRM_Core_Error::FATAL_ERROR);
355 }
356
357 $config = CRM_Core_Config::singleton();
358
359 if ($config->fatalErrorHandler &&
360 function_exists($config->fatalErrorHandler)
361 ) {
362 $name = $config->fatalErrorHandler;
363 $ret = $name($vars);
364 if ($ret) {
365 // the call has been successfully handled
366 // so we just exit
367 self::abend(CRM_Core_Error::FATAL_ERROR);
368 }
369 }
370
25dc2153
PH
371 if ($config->backtrace) {
372 self::backtrace();
373 }
374
375 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
376 CRM_Core_Error::backtrace('backTrace', TRUE);
377
34866662
CW
378 // If we are in an ajax callback, format output appropriately
379 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
380 $out = array(
381 'status' => 'fatal',
382 '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>',
383 );
384 if ($config->backtrace && CRM_Core_Permission::check('view debug output')) {
385 $out['backtrace'] = self::parseBacktrace(debug_backtrace());
386 $message .= '<p><em>See console for backtrace</em></p>';
387 }
1528ac1d 388 CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error');
34866662
CW
389 CRM_Core_Transaction::forceRollbackIfEnabled();
390 CRM_Core_Page_AJAX::returnJsonResponse($out);
391 }
392
6a488035
TO
393 $template = CRM_Core_Smarty::singleton();
394 $template->assign($vars);
f431d51f 395 $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl'));
6a488035
TO
396
397 self::abend(CRM_Core_Error::FATAL_ERROR);
398 }
399
400 /**
0880a9d0 401 * Display an error page with an error message describing what happened.
6a488035
TO
402 *
403 * This function is evil -- it largely replicates fatal(). Hopefully the
404 * entire CRM_Core_Error system can be hollowed out and replaced with
405 * something that follows a cleaner separation of concerns.
406 *
407 * @param Exception $exception
6a488035 408 */
00be9182 409 public static function handleUnhandledException($exception) {
4b57bc9f
EM
410 try {
411 CRM_Utils_Hook::unhandledException($exception);
0db6c3e1
TO
412 }
413 catch (Exception $other) {
4b57bc9f 414 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
4fd5f07e 415 CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other));
4b57bc9f 416 }
6a488035
TO
417 $config = CRM_Core_Config::singleton();
418 $vars = array(
419 'message' => $exception->getMessage(),
420 'code' => NULL,
421 'exception' => $exception,
422 );
423 if (!$vars['message']) {
424 $vars['message'] = ts('We experienced an unexpected error. Please post a detailed description and the backtrace on the CiviCRM forums: %1', array(1 => 'http://forum.civicrm.org/'));
425 }
426
427 // Case A: CLI
428 if (php_sapi_name() == "cli") {
429 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
430 print self::formatTextException($exception);
431 die("\n");
432 // FIXME: Why doesn't this call abend()?
433 // Difference: abend() will cleanup transaction and (via civiExit) store session state
434 // self::abend(CRM_Core_Error::FATAL_ERROR);
435 }
436
437 // Case B: Custom error handler
438 if ($config->fatalErrorHandler &&
439 function_exists($config->fatalErrorHandler)
440 ) {
441 $name = $config->fatalErrorHandler;
442 $ret = $name($vars);
443 if ($ret) {
444 // the call has been successfully handled
445 // so we just exit
446 self::abend(CRM_Core_Error::FATAL_ERROR);
447 }
448 }
449
450 // Case C: Default error handler
451
452 // log to file
a3fab31f 453 CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE);
6a488035
TO
454 CRM_Core_Error::backtrace('backTrace', TRUE);
455
456 // print to screen
457 $template = CRM_Core_Smarty::singleton();
458 $template->assign($vars);
f431d51f 459 $content = $template->fetch('CRM/common/fatal.tpl');
6a488035
TO
460 if ($config->backtrace) {
461 $content = self::formatHtmlException($exception) . $content;
462 }
463 if ($config->userFramework == 'Joomla' &&
464 class_exists('JError')
465 ) {
466 JError::raiseError('CiviCRM-001', $content);
467 }
468 else {
469 echo CRM_Utils_System::theme($content);
470 }
471
472 // fin
473 self::abend(CRM_Core_Error::FATAL_ERROR);
474 }
475
476 /**
100fef9d 477 * Outputs pre-formatted debug information. Flushes the buffers
6a488035
TO
478 * so we can interrupt a potential POST/redirect
479 *
3bdca100 480 * @param string $name name of debug section
481 * @param $variable mixed reference to variables that we need a trace of
482 * @param bool $log should we log or return the output
483 * @param bool $html whether to generate a HTML-escaped output
484 * @param bool $checkPermission should we check permissions before displaying output
90154ece
DL
485 * useful when we die during initialization and permissioning
486 * subsystem is not initialized - CRM-13765
6a488035 487 *
a6c01b45
CW
488 * @return string
489 * the generated output
6a488035 490 */
00be9182 491 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
6a488035
TO
492 $error = self::singleton();
493
494 if ($variable === NULL) {
495 $variable = $name;
496 $name = NULL;
497 }
498
499 $out = print_r($variable, TRUE);
500 $prefix = NULL;
501 if ($html) {
502 $out = htmlspecialchars($out);
503 if ($name) {
504 $prefix = "<p>$name</p>";
505 }
506 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
507 }
508 else {
509 if ($name) {
510 $prefix = "$name:\n";
511 }
512 $out = "{$prefix}$out\n";
513 }
90154ece
DL
514 if (
515 $log &&
516 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
517 ) {
6a488035
TO
518 echo $out;
519 }
520
521 return $out;
522 }
523
524 /**
525 * Similar to the function debug. Only difference is
526 * in the formatting of the output.
527 *
c490a46a
CW
528 * @param string $variable_name
529 * @param mixed $variable
6a0b768e
TO
530 * @param bool $print
531 * Should we use print_r ? (else we use var_dump).
532 * @param bool $log
533 * Should we log or return the output.
534 * @param string $comp
535 * Variable name.
2a6da8d7 536 *
a6c01b45
CW
537 * @return string
538 * the generated output
6a488035 539 *
6a488035 540 *
6a488035
TO
541 *
542 * @see CRM_Core_Error::debug()
543 * @see CRM_Core_Error::debug_log_message()
544 */
3bdca100 545 public static function debug_var(
f9f40af3 546 $variable_name,
6a488035
TO
547 $variable,
548 $print = TRUE,
2aa397bc
TO
549 $log = TRUE,
550 $comp = ''
6a488035
TO
551 ) {
552 // check if variable is set
553 if (!isset($variable)) {
554 $out = "\$$variable_name is not set";
555 }
556 else {
557 if ($print) {
558 $out = print_r($variable, TRUE);
559 $out = "\$$variable_name = $out";
560 }
561 else {
562 // use var_dump
563 ob_start();
564 var_dump($variable);
565 $dump = ob_get_contents();
566 ob_end_clean();
567 $out = "\n\$$variable_name = $dump";
568 }
569 // reset if it is an array
570 if (is_array($variable)) {
571 reset($variable);
572 }
573 }
574 return self::debug_log_message($out, FALSE, $comp);
575 }
576
577 /**
edc8adfc 578 * Display the error message on terminal and append it to the log file.
579 *
580 * Provided the user has the 'view debug output' the output should be displayed. In all
581 * cases it should be logged.
6a488035 582 *
ea3ddccf 583 * @param string $message
6a0b768e
TO
584 * @param bool $out
585 * Should we log or return the output.
6a488035 586 *
6a0b768e
TO
587 * @param string $comp
588 * Message to be output.
ea3ddccf 589 * @param string $priority
6a488035 590 *
ea3ddccf 591 * @return string
592 * Format of the backtrace
6a488035 593 */
6e5ad5ee 594 public static function debug_log_message($message, $out = FALSE, $comp = '', $priority = NULL) {
213a5f19 595 $config = CRM_Core_Config::singleton();
6a488035
TO
596
597 $file_log = self::createDebugLogger($comp);
6e5ad5ee 598 $file_log->log("$message\n", $priority);
0ac9fd52
CB
599
600 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
6a488035
TO
601 if ($out && CRM_Core_Permission::check('view debug output')) {
602 echo $str;
603 }
604 $file_log->close();
605
3a036b15 606 if (!empty($config->userFrameworkLogging)) {
1fadd891 607 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
213a5f19 608 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
eb9dd128 609 watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG);
213a5f19
EM
610 }
611 }
6a488035
TO
612
613 return $str;
614 }
615
616 /**
617 * Append to the query log (if enabled)
ad37ac8e 618 *
619 * @param string $string
6a488035 620 */
00be9182 621 public static function debug_query($string) {
481a74f4 622 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
7e7d0323 623 if (CIVICRM_DEBUG_LOG_QUERY === 'backtrace') {
481a74f4 624 CRM_Core_Error::backtrace($string, TRUE);
0db6c3e1 625 }
481a74f4 626 elseif (CIVICRM_DEBUG_LOG_QUERY) {
b0ccde7b 627 CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log');
6a488035
TO
628 }
629 }
630 }
631
d090b80b
TO
632 /**
633 * Execute a query and log the results.
634 *
635 * @param string $query
636 */
00be9182 637 public static function debug_query_result($query) {
7d0b8a47 638 $results = CRM_Core_DAO::executeQuery($query)->fetchAll();
d090b80b
TO
639 CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results));
640 }
641
6a488035 642 /**
0880a9d0 643 * Obtain a reference to the error log.
6a488035 644 *
edc8adfc 645 * @param string $prefix
77b97be7 646 *
6a488035
TO
647 * @return Log
648 */
edc8adfc 649 public static function createDebugLogger($prefix = '') {
650 self::generateLogFileName($prefix);
651 return Log::singleton('file', \Civi::$statics[__CLASS__]['logger_file' . $prefix], '');
652 }
653
44c32d0a
CB
654 /**
655 * Generate a hash for the logfile.
656 * CRM-13640.
657 */
f0f1e508
CB
658 public static function generateLogFileHash($config) {
659 // Use multiple (but stable) inputs for hash information.
44c32d0a 660 $md5inputs = array(
262e9b08
CB
661 defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : 'NO_SITE_KEY',
662 $config->userFrameworkBaseURL,
44c32d0a
CB
663 md5($config->dsn),
664 $config->dsn,
665 );
262e9b08
CB
666 // Trim 8 chars off the string, make it slightly easier to find
667 // but reveals less information from the hash.
315ca480 668 return substr(md5(var_export($md5inputs, 1)), 8);
44c32d0a
CB
669 }
670
edc8adfc 671 /**
672 * Generate the name of the logfile to use and store it as a static.
673 *
674 * This function includes poor man's log file management and a check as to whether the file exists.
675 *
676 * @param string $prefix
677 */
678 protected static function generateLogFileName($prefix) {
679 if (!isset(\Civi::$statics[__CLASS__]['logger_file' . $prefix])) {
931ba0f3 680 $config = CRM_Core_Config::singleton();
6a488035 681
edc8adfc 682 $prefixString = $prefix ? ($prefix . '.') : '';
6a488035 683
44c32d0a
CB
684 $hash = self::generateLogFileHash($config);
685 $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . $hash . '.log';
931ba0f3 686
687 // Roll log file monthly or if greater than 256M
688 // note that PHP file functions have a limit of 2G and hence
689 // the alternative was introduce
690 if (file_exists($fileName)) {
691 $fileTime = date("Ym", filemtime($fileName));
692 $fileSize = filesize($fileName);
693 if (($fileTime < date('Ym')) ||
694 ($fileSize > 256 * 1024 * 1024) ||
695 ($fileSize < 0)
696 ) {
697 rename($fileName,
698 $fileName . '.' . date('YmdHi')
699 );
700 }
701 }
edc8adfc 702 \Civi::$statics[__CLASS__]['logger_file' . $prefix] = $fileName;
931ba0f3 703 }
6a488035
TO
704 }
705
a0ee3941
EM
706 /**
707 * @param string $msg
708 * @param bool $log
709 */
00be9182 710 public static function backtrace($msg = 'backTrace', $log = FALSE) {
6a488035
TO
711 $backTrace = debug_backtrace();
712 $message = self::formatBacktrace($backTrace);
713 if (!$log) {
714 CRM_Core_Error::debug($msg, $message);
715 }
716 else {
717 CRM_Core_Error::debug_var($msg, $message);
718 }
719 }
720
721 /**
0880a9d0 722 * Render a backtrace array as a string.
6a488035 723 *
6a0b768e
TO
724 * @param array $backTrace
725 * Array of stack frames.
726 * @param bool $showArgs
727 * 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.
728 * @param int $maxArgLen
729 * Maximum number of characters to show from each argument string.
a6c01b45
CW
730 * @return string
731 * printable plain-text
6a488035 732 */
00be9182 733 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
6a488035 734 $message = '';
34866662
CW
735 foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
736 $message .= sprintf("#%s %s\n", $idx, $trace);
737 }
2aa397bc 738 $message .= sprintf("#%s {main}\n", 1 + $idx);
34866662
CW
739 return $message;
740 }
741
742 /**
0880a9d0 743 * Render a backtrace array as an array.
34866662 744 *
6a0b768e
TO
745 * @param array $backTrace
746 * Array of stack frames.
747 * @param bool $showArgs
748 * 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.
749 * @param int $maxArgLen
750 * Maximum number of characters to show from each argument string.
34866662
CW
751 * @return array
752 * @see debug_backtrace
753 * @see Exception::getTrace()
754 */
00be9182 755 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
34866662
CW
756 $ret = array();
757 foreach ($backTrace as $trace) {
6a488035
TO
758 $args = array();
759 $fnName = CRM_Utils_Array::value('function', $trace);
34866662 760 $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
6a488035 761
83e7cba6 762 // Do not show args for a few password related functions
6a488035
TO
763 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
764
83e7cba6
CB
765 if (!empty($trace['args'])) {
766 foreach ($trace['args'] as $arg) {
353ffa53 767 if (!$showArgs || $skipArgs) {
83e7cba6
CB
768 $args[] = '(' . gettype($arg) . ')';
769 continue;
770 }
771 switch ($type = gettype($arg)) {
772 case 'boolean':
773 $args[] = $arg ? 'TRUE' : 'FALSE';
774 break;
2aa397bc 775
83e7cba6
CB
776 case 'integer':
777 case 'double':
778 $args[] = $arg;
779 break;
2aa397bc 780
83e7cba6 781 case 'string':
86bfa4f6 782 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
83e7cba6 783 break;
2aa397bc 784
83e7cba6 785 case 'array':
92fcb95f 786 $args[] = '(Array:' . count($arg) . ')';
83e7cba6 787 break;
2aa397bc 788
83e7cba6
CB
789 case 'object':
790 $args[] = 'Object(' . get_class($arg) . ')';
791 break;
2aa397bc 792
83e7cba6
CB
793 case 'resource':
794 $args[] = 'Resource';
795 break;
2aa397bc 796
83e7cba6
CB
797 case 'NULL':
798 $args[] = 'NULL';
799 break;
2aa397bc 800
83e7cba6
CB
801 default:
802 $args[] = "($type)";
803 break;
804 }
6a488035
TO
805 }
806 }
807
34866662
CW
808 $ret[] = sprintf(
809 "%s(%s): %s%s(%s)",
6a488035
TO
810 CRM_Utils_Array::value('file', $trace, '[internal function]'),
811 CRM_Utils_Array::value('line', $trace, ''),
812 $className,
813 $fnName,
814 implode(", ", $args)
815 );
816 }
34866662 817 return $ret;
6a488035
TO
818 }
819
820 /**
0880a9d0 821 * Render an exception as HTML string.
6a488035
TO
822 *
823 * @param Exception $e
a6c01b45
CW
824 * @return string
825 * printable HTML text
6a488035 826 */
00be9182 827 public static function formatHtmlException(Exception $e) {
6a488035
TO
828 $msg = '';
829
830 // Exception metadata
831
832 // Exception backtrace
833 if ($e instanceof PEAR_Exception) {
834 $ei = $e;
835 while (is_callable(array($ei, 'getCause'))) {
836 if ($ei->getCause() instanceof PEAR_Error) {
837 $msg .= '<table class="crm-db-error">';
838 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
839 $msg .= '<tbody>';
840 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
841 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
2aa397bc 842 }
6a488035 843 $msg .= '</tbody></table>';
2aa397bc 844 }
6a488035 845 $ei = $ei->getCause();
2aa397bc 846 }
6a488035 847 $msg .= $e->toHtml();
0db6c3e1
TO
848 }
849 else {
6a488035
TO
850 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
851 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
852 }
853 return $msg;
854 }
855
856 /**
0880a9d0 857 * Write details of an exception to the log.
6a488035
TO
858 *
859 * @param Exception $e
a6c01b45
CW
860 * @return string
861 * printable plain text
6a488035 862 */
00be9182 863 public static function formatTextException(Exception $e) {
6a488035
TO
864 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
865
866 $ei = $e;
867 while (is_callable(array($ei, 'getCause'))) {
868 if ($ei->getCause() instanceof PEAR_Error) {
869 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
870 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
871 }
872 }
873 $ei = $ei->getCause();
874 }
875 $msg .= self::formatBacktrace($e->getTrace());
876 return $msg;
877 }
878
a0ee3941
EM
879 /**
880 * @param $message
881 * @param int $code
882 * @param string $level
100fef9d 883 * @param array $params
a0ee3941
EM
884 *
885 * @return object
886 */
00be9182 887 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
6a488035
TO
888 $error = CRM_Core_Error::singleton();
889 $error->push($code, $level, array($params), $message);
890 return $error;
891 }
892
893 /**
894 * Set a status message in the session, then bounce back to the referrer.
895 *
6a0b768e
TO
896 * @param string $status
897 * The status message to set.
6a488035 898 *
2a6da8d7
EM
899 * @param null $redirect
900 * @param string $title
6a488035 901 */
50ecd413 902 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
6a488035
TO
903 $session = CRM_Core_Session::singleton();
904 if (!$redirect) {
905 $redirect = $session->readUserContext();
906 }
50ecd413
CW
907 if ($title === NULL) {
908 $title = ts('Error');
909 }
910 $session->setStatus($status, $title, 'alert', array('expires' => 0));
34866662
CW
911 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
912 CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error'));
913 }
6a488035
TO
914 CRM_Utils_System::redirect($redirect);
915 }
916
917 /**
0880a9d0 918 * Reset the error stack.
6a488035 919 *
6a488035
TO
920 */
921 public static function reset() {
922 $error = self::singleton();
923 $error->_errors = array();
924 $error->_errorsByLevel = array();
925 }
926
6a4257d4 927 /**
42c0daee
TO
928 * PEAR error-handler which converts errors to exceptions
929 *
930 * @param $pearError
931 * @throws PEAR_Exception
6a4257d4 932 */
6a488035 933 public static function exceptionHandler($pearError) {
ca8416c8 934 CRM_Core_Error::debug_var('Fatal Error Details', self::getErrorDetails($pearError));
6a488035
TO
935 CRM_Core_Error::backtrace('backTrace', TRUE);
936 throw new PEAR_Exception($pearError->getMessage(), $pearError);
937 }
938
939 /**
42c0daee 940 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
6a488035 941 *
6a0b768e
TO
942 * @param object $obj
943 * The PEAR_ERROR object.
a6c01b45
CW
944 * @return object
945 * $obj
6a488035
TO
946 */
947 public static function nullHandler($obj) {
948 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
949 CRM_Core_Error::backtrace('backTrace', TRUE);
950 return $obj;
951 }
952
d424ffde 953 /**
6a488035
TO
954 * @deprecated
955 * This function is no longer used by v3 api.
956 * @fixme Some core files call it but it should be re-thought & renamed or removed
d424ffde 957 *
a0ee3941
EM
958 * @param $msg
959 * @param null $data
960 *
961 * @return array
962 * @throws Exception
963 */
6a488035
TO
964 public static function &createAPIError($msg, $data = NULL) {
965 if (self::$modeException) {
966 throw new Exception($msg, $data);
967 }
968
969 $values = array();
970
971 $values['is_error'] = 1;
972 $values['error_message'] = $msg;
973 if (isset($data)) {
974 $values = array_merge($values, $data);
975 }
976 return $values;
977 }
978
a0ee3941
EM
979 /**
980 * @param $file
981 */
6a488035
TO
982 public static function movedSiteError($file) {
983 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
984 'reset=1',
985 TRUE
986 );
987 echo "We could not write $file. Have you moved your site directory or server?<p>";
988 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
989 exit();
990 }
991
992 /**
0880a9d0 993 * Terminate execution abnormally.
ad37ac8e 994 *
995 * @param string $code
6a488035
TO
996 */
997 protected static function abend($code) {
998 // do a hard rollback of any pending transactions
999 // if we've come here, its because of some unexpected PEAR errors
1000 CRM_Core_Transaction::forceRollbackIfEnabled();
1001 CRM_Utils_System::civiExit($code);
1002 }
1003
a0ee3941 1004 /**
3ab5efa9
EM
1005 * @param array $error
1006 * @param int $type
a0ee3941
EM
1007 *
1008 * @return bool
1009 */
6a488035 1010 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
8cc574cf 1011 if (is_array($error) && !empty($error['is_error'])) {
6a488035
TO
1012 $code = $error['error_message']['code'];
1013 if ($code == $type) {
1014 return TRUE;
1015 }
1016 }
1017 return FALSE;
1018 }
96025800 1019
6a488035
TO
1020}
1021
1022$e = new PEAR_ErrorStack('CRM');
1023$e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');