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