CRM-17663 - Dashboard cleanup
[civicrm-core.git] / CRM / Core / Error.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 +--------------------------------------------------------------------+
26 */
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
33 * @copyright CiviCRM LLC (c) 2004-2016
34 */
35
36 require_once 'PEAR/ErrorStack.php';
37 require_once 'PEAR/Exception.php';
38 require_once 'CRM/Core/Exception.php';
39
40 require_once 'Log.php';
41
42 /**
43 * Class CRM_Exception
44 */
45 class CRM_Exception extends PEAR_Exception {
46 /**
47 * Redefine the exception so message isn't optional.
48 *
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);
58 *
59 * @param string $message exception message
60 * @param int $code
61 * @param Exception $previous
62 */
63 public function __construct($message = NULL, $code = 0, Exception $previous = NULL) {
64 parent::__construct($message, $code, $previous);
65 }
66
67 }
68
69 /**
70 * Class CRM_Core_Error
71 */
72 class CRM_Core_Error extends PEAR_ErrorStack {
73
74 /**
75 * Status code of various types of errors.
76 */
77 const FATAL_ERROR = 2;
78 const DUPLICATE_CONTACT = 8001;
79 const DUPLICATE_CONTRIBUTION = 8002;
80 const DUPLICATE_PARTICIPANT = 8003;
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
86 */
87 private static $_singleton = NULL;
88
89 /**
90 * The logger object for this application.
91 * @var object
92 */
93 private static $_log = NULL;
94
95 /**
96 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
97 */
98 public static $modeException = NULL;
99
100 /**
101 * Singleton function used to manage this object.
102 *
103 * @param null $package
104 * @param bool $msgCallback
105 * @param bool $contextCallback
106 * @param bool $throwPEAR_Error
107 * @param string $stackClass
108 *
109 * @return object
110 */
111 public static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
112 if (self::$_singleton === NULL) {
113 self::$_singleton = new CRM_Core_Error('CiviCRM');
114 }
115 return self::$_singleton;
116 }
117
118 /**
119 * Constructor.
120 */
121 public function __construct() {
122 parent::__construct('CiviCRM');
123
124 $log = CRM_Core_Config::getLog();
125 $this->setLogger($log);
126
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 }
134 }
135
136 /**
137 * @param $error
138 * @param string $separator
139 *
140 * @return array|null|string
141 */
142 static public function getMessages(&$error, $separator = '<br />') {
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
155 /**
156 * Status display function specific to payment processor errors.
157 * @param $error
158 * @param string $separator
159 */
160 public static function displaySessionError(&$error, $separator = '<br />') {
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 /**
170 * Create the main callback method. this method centralizes error processing.
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 *
175 * @param object $pearError PEAR_Error
176 */
177 public static function handle($pearError) {
178 if (defined('CIVICRM_TEST')) {
179 return self::simpleHandler($pearError);
180 }
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
191 $error = self::getErrorDetails($pearError);
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']) &&
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 }
210 elseif (preg_match('/^mysqli:/', $_DB_DATAOBJECT['CONFIG']['database'])) {
211 $dao = new CRM_Core_DAO();
212
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 }
242 static $runOnce = FALSE;
243 if ($runOnce) {
244 exit;
245 }
246 $runOnce = TRUE;
247 self::abend(1);
248 }
249
250 /**
251 * this function is used to trap and print errors
252 * during system initialization time. Hence the error
253 * message is quite ugly
254 *
255 * @param $pearError
256 */
257 public static function simpleHandler($pearError) {
258
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) {
279 // create the error array
280 $error = array();
281 $error['callback'] = $pearError->getCallback();
282 $error['code'] = $pearError->getCode();
283 $error['message'] = $pearError->getMessage();
284 $error['mode'] = $pearError->getMode();
285 $error['debug_info'] = $pearError->getDebugInfo();
286 $error['type'] = $pearError->getType();
287 $error['user_info'] = $pearError->getUserInfo();
288 $error['to_string'] = $pearError->toString();
289
290 return $error;
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();
304 *
305 * @param mixed $pearError
306 *
307 * @return int
308 */
309 public static function handlePES($pearError) {
310 return PEAR_ERRORSTACK_PUSH;
311 }
312
313 /**
314 * Display an error page with an error message describing what happened.
315 *
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.
322 *
323 * @throws Exception
324 */
325 public static function fatal($message = NULL, $code = NULL, $email = NULL) {
326 $vars = array(
327 'message' => htmlspecialchars($message),
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;
339 }
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");
349 // Fix for CRM-16899
350 echo static::formatBacktrace(debug_backtrace());
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
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
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 }
388 CRM_Core_Session::setStatus($message, ts('Sorry an error occurred'), 'error');
389 CRM_Core_Transaction::forceRollbackIfEnabled();
390 CRM_Core_Page_AJAX::returnJsonResponse($out);
391 }
392
393 $template = CRM_Core_Smarty::singleton();
394 $template->assign($vars);
395 $config->userSystem->outputError($template->fetch('CRM/common/fatal.tpl'));
396
397 self::abend(CRM_Core_Error::FATAL_ERROR);
398 }
399
400 /**
401 * Display an error page with an error message describing what happened.
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
408 */
409 public static function handleUnhandledException($exception) {
410 try {
411 CRM_Utils_Hook::unhandledException($exception);
412 }
413 catch (Exception $other) {
414 // if the exception-handler generates an exception, then that sucks! oh, well. carry on.
415 CRM_Core_Error::debug_var('handleUnhandledException_nestedException', self::formatTextException($other));
416 }
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
453 CRM_Core_Error::debug_var('Fatal Error Details', $vars, FALSE);
454 CRM_Core_Error::backtrace('backTrace', TRUE);
455
456 // print to screen
457 $template = CRM_Core_Smarty::singleton();
458 $template->assign($vars);
459 $content = $template->fetch('CRM/common/fatal.tpl');
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 /**
477 * Outputs pre-formatted debug information. Flushes the buffers
478 * so we can interrupt a potential POST/redirect
479 *
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
485 * useful when we die during initialization and permissioning
486 * subsystem is not initialized - CRM-13765
487 *
488 * @return string
489 * the generated output
490 */
491 public static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
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 }
514 if (
515 $log &&
516 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
517 ) {
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 *
528 * @param string $variable_name
529 * @param mixed $variable
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.
536 *
537 * @return string
538 * the generated output
539 *
540 *
541 *
542 * @see CRM_Core_Error::debug()
543 * @see CRM_Core_Error::debug_log_message()
544 */
545 public static function debug_var(
546 $variable_name,
547 $variable,
548 $print = TRUE,
549 $log = TRUE,
550 $comp = ''
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 /**
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.
582 *
583 * @param string $message
584 * @param bool $out
585 * Should we log or return the output.
586 *
587 * @param string $comp
588 * Message to be output.
589 * @param string $priority
590 *
591 * @return string
592 * Format of the backtrace
593 */
594 public static function debug_log_message($message, $out = FALSE, $comp = '', $priority = NULL) {
595 $config = CRM_Core_Config::singleton();
596
597 $file_log = self::createDebugLogger($comp);
598 $file_log->log("$message\n", $priority);
599
600 $str = '<p/><code>' . htmlspecialchars($message) . '</code>';
601 if ($out && CRM_Core_Permission::check('view debug output')) {
602 echo $str;
603 }
604 $file_log->close();
605
606 if (!empty($config->userFrameworkLogging)) {
607 // should call $config->userSystem->logger($message) here - but I got a situation where userSystem was not an object - not sure why
608 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
609 watchdog('civicrm', '%message', array('%message' => $message), WATCHDOG_DEBUG);
610 }
611 }
612
613 return $str;
614 }
615
616 /**
617 * Append to the query log (if enabled)
618 *
619 * @param string $string
620 */
621 public static function debug_query($string) {
622 if (defined('CIVICRM_DEBUG_LOG_QUERY')) {
623 if (CIVICRM_DEBUG_LOG_QUERY === 'backtrace') {
624 CRM_Core_Error::backtrace($string, TRUE);
625 }
626 elseif (CIVICRM_DEBUG_LOG_QUERY) {
627 CRM_Core_Error::debug_var('Query', $string, TRUE, TRUE, 'sql_log');
628 }
629 }
630 }
631
632 /**
633 * Execute a query and log the results.
634 *
635 * @param string $query
636 */
637 public static function debug_query_result($query) {
638 $results = CRM_Core_DAO::executeQuery($query)->fetchAll();
639 CRM_Core_Error::debug_var('dao result', array('query' => $query, 'results' => $results));
640 }
641
642 /**
643 * Obtain a reference to the error log.
644 *
645 * @param string $prefix
646 *
647 * @return Log
648 */
649 public static function createDebugLogger($prefix = '') {
650 self::generateLogFileName($prefix);
651 return Log::singleton('file', \Civi::$statics[__CLASS__]['logger_file' . $prefix], '');
652 }
653
654 /**
655 * Generate the name of the logfile to use and store it as a static.
656 *
657 * This function includes poor man's log file management and a check as to whether the file exists.
658 *
659 * @param string $prefix
660 */
661 protected static function generateLogFileName($prefix) {
662 if (!isset(\Civi::$statics[__CLASS__]['logger_file' . $prefix])) {
663 $config = CRM_Core_Config::singleton();
664
665 $prefixString = $prefix ? ($prefix . '.') : '';
666
667 $fileName = $config->configAndLogDir . 'CiviCRM.' . $prefixString . md5($config->dsn) . '.log';
668
669 // Roll log file monthly or if greater than 256M
670 // note that PHP file functions have a limit of 2G and hence
671 // the alternative was introduce
672 if (file_exists($fileName)) {
673 $fileTime = date("Ym", filemtime($fileName));
674 $fileSize = filesize($fileName);
675 if (($fileTime < date('Ym')) ||
676 ($fileSize > 256 * 1024 * 1024) ||
677 ($fileSize < 0)
678 ) {
679 rename($fileName,
680 $fileName . '.' . date('YmdHi')
681 );
682 }
683 }
684 \Civi::$statics[__CLASS__]['logger_file' . $prefix] = $fileName;
685 }
686 }
687
688 /**
689 * @param string $msg
690 * @param bool $log
691 */
692 public static function backtrace($msg = 'backTrace', $log = FALSE) {
693 $backTrace = debug_backtrace();
694 $message = self::formatBacktrace($backTrace);
695 if (!$log) {
696 CRM_Core_Error::debug($msg, $message);
697 }
698 else {
699 CRM_Core_Error::debug_var($msg, $message);
700 }
701 }
702
703 /**
704 * Render a backtrace array as a string.
705 *
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.
712 * @return string
713 * printable plain-text
714 */
715 public static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
716 $message = '';
717 foreach (self::parseBacktrace($backTrace, $showArgs, $maxArgLen) as $idx => $trace) {
718 $message .= sprintf("#%s %s\n", $idx, $trace);
719 }
720 $message .= sprintf("#%s {main}\n", 1 + $idx);
721 return $message;
722 }
723
724 /**
725 * Render a backtrace array as an array.
726 *
727 * @param array $backTrace
728 * Array of stack frames.
729 * @param bool $showArgs
730 * 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.
731 * @param int $maxArgLen
732 * Maximum number of characters to show from each argument string.
733 * @return array
734 * @see debug_backtrace
735 * @see Exception::getTrace()
736 */
737 public static function parseBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
738 $ret = array();
739 foreach ($backTrace as $trace) {
740 $args = array();
741 $fnName = CRM_Utils_Array::value('function', $trace);
742 $className = isset($trace['class']) ? ($trace['class'] . $trace['type']) : '';
743
744 // Do not show args for a few password related functions
745 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
746
747 if (!empty($trace['args'])) {
748 foreach ($trace['args'] as $arg) {
749 if (!$showArgs || $skipArgs) {
750 $args[] = '(' . gettype($arg) . ')';
751 continue;
752 }
753 switch ($type = gettype($arg)) {
754 case 'boolean':
755 $args[] = $arg ? 'TRUE' : 'FALSE';
756 break;
757
758 case 'integer':
759 case 'double':
760 $args[] = $arg;
761 break;
762
763 case 'string':
764 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen) . '"';
765 break;
766
767 case 'array':
768 $args[] = '(Array:' . count($arg) . ')';
769 break;
770
771 case 'object':
772 $args[] = 'Object(' . get_class($arg) . ')';
773 break;
774
775 case 'resource':
776 $args[] = 'Resource';
777 break;
778
779 case 'NULL':
780 $args[] = 'NULL';
781 break;
782
783 default:
784 $args[] = "($type)";
785 break;
786 }
787 }
788 }
789
790 $ret[] = sprintf(
791 "%s(%s): %s%s(%s)",
792 CRM_Utils_Array::value('file', $trace, '[internal function]'),
793 CRM_Utils_Array::value('line', $trace, ''),
794 $className,
795 $fnName,
796 implode(", ", $args)
797 );
798 }
799 return $ret;
800 }
801
802 /**
803 * Render an exception as HTML string.
804 *
805 * @param Exception $e
806 * @return string
807 * printable HTML text
808 */
809 public static function formatHtmlException(Exception $e) {
810 $msg = '';
811
812 // Exception metadata
813
814 // Exception backtrace
815 if ($e instanceof PEAR_Exception) {
816 $ei = $e;
817 while (is_callable(array($ei, 'getCause'))) {
818 if ($ei->getCause() instanceof PEAR_Error) {
819 $msg .= '<table class="crm-db-error">';
820 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
821 $msg .= '<tbody>';
822 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
823 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
824 }
825 $msg .= '</tbody></table>';
826 }
827 $ei = $ei->getCause();
828 }
829 $msg .= $e->toHtml();
830 }
831 else {
832 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
833 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
834 }
835 return $msg;
836 }
837
838 /**
839 * Write details of an exception to the log.
840 *
841 * @param Exception $e
842 * @return string
843 * printable plain text
844 */
845 public static function formatTextException(Exception $e) {
846 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
847
848 $ei = $e;
849 while (is_callable(array($ei, 'getCause'))) {
850 if ($ei->getCause() instanceof PEAR_Error) {
851 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
852 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
853 }
854 }
855 $ei = $ei->getCause();
856 }
857 $msg .= self::formatBacktrace($e->getTrace());
858 return $msg;
859 }
860
861 /**
862 * @param $message
863 * @param int $code
864 * @param string $level
865 * @param array $params
866 *
867 * @return object
868 */
869 public static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
870 $error = CRM_Core_Error::singleton();
871 $error->push($code, $level, array($params), $message);
872 return $error;
873 }
874
875 /**
876 * Set a status message in the session, then bounce back to the referrer.
877 *
878 * @param string $status
879 * The status message to set.
880 *
881 * @param null $redirect
882 * @param string $title
883 */
884 public static function statusBounce($status, $redirect = NULL, $title = NULL) {
885 $session = CRM_Core_Session::singleton();
886 if (!$redirect) {
887 $redirect = $session->readUserContext();
888 }
889 if ($title === NULL) {
890 $title = ts('Error');
891 }
892 $session->setStatus($status, $title, 'alert', array('expires' => 0));
893 if (CRM_Utils_Array::value('snippet', $_REQUEST) === CRM_Core_Smarty::PRINT_JSON) {
894 CRM_Core_Page_AJAX::returnJsonResponse(array('status' => 'error'));
895 }
896 CRM_Utils_System::redirect($redirect);
897 }
898
899 /**
900 * Reset the error stack.
901 *
902 */
903 public static function reset() {
904 $error = self::singleton();
905 $error->_errors = array();
906 $error->_errorsByLevel = array();
907 }
908
909 /**
910 * PEAR error-handler which converts errors to exceptions
911 *
912 * @param $pearError
913 * @throws PEAR_Exception
914 */
915 public static function exceptionHandler($pearError) {
916 CRM_Core_Error::debug_var('Fatal Error Details', self::getErrorDetails($pearError));
917 CRM_Core_Error::backtrace('backTrace', TRUE);
918 throw new PEAR_Exception($pearError->getMessage(), $pearError);
919 }
920
921 /**
922 * PEAR error-handler to quietly catch otherwise fatal errors. Intended for use with smtp transport.
923 *
924 * @param object $obj
925 * The PEAR_ERROR object.
926 * @return object
927 * $obj
928 */
929 public static function nullHandler($obj) {
930 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
931 CRM_Core_Error::backtrace('backTrace', TRUE);
932 return $obj;
933 }
934
935 /**
936 * @deprecated
937 * This function is no longer used by v3 api.
938 * @fixme Some core files call it but it should be re-thought & renamed or removed
939 *
940 * @param $msg
941 * @param null $data
942 *
943 * @return array
944 * @throws Exception
945 */
946 public static function &createAPIError($msg, $data = NULL) {
947 if (self::$modeException) {
948 throw new Exception($msg, $data);
949 }
950
951 $values = array();
952
953 $values['is_error'] = 1;
954 $values['error_message'] = $msg;
955 if (isset($data)) {
956 $values = array_merge($values, $data);
957 }
958 return $values;
959 }
960
961 /**
962 * @param $file
963 */
964 public static function movedSiteError($file) {
965 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
966 'reset=1',
967 TRUE
968 );
969 echo "We could not write $file. Have you moved your site directory or server?<p>";
970 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
971 exit();
972 }
973
974 /**
975 * Terminate execution abnormally.
976 *
977 * @param string $code
978 */
979 protected static function abend($code) {
980 // do a hard rollback of any pending transactions
981 // if we've come here, its because of some unexpected PEAR errors
982 CRM_Core_Transaction::forceRollbackIfEnabled();
983 CRM_Utils_System::civiExit($code);
984 }
985
986 /**
987 * @param array $error
988 * @param int $type
989 *
990 * @return bool
991 */
992 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
993 if (is_array($error) && !empty($error['is_error'])) {
994 $code = $error['error_message']['code'];
995 if ($code == $type) {
996 return TRUE;
997 }
998 }
999 return FALSE;
1000 }
1001
1002 }
1003
1004 $e = new PEAR_ErrorStack('CRM');
1005 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');