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