Merge pull request #3580 from monishdeb/CRM-14701
[civicrm-core.git] / CRM / Core / Error.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.4 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 * Start of the Error framework. We should check out and inherit from
31 * PEAR_ErrorStack and use that framework
32 *
33 * @package CRM
34 * @copyright CiviCRM LLC (c) 2004-2013
35 * $Id$
36 *
37 */
38
39 require_once 'PEAR/ErrorStack.php';
40 require_once 'PEAR/Exception.php';
41 require_once 'CRM/Core/Exception.php';
42
43 require_once 'Log.php';
44 class CRM_Exception extends PEAR_Exception {
45 // Redefine the exception so message isn't optional
46 public function __construct($message = NULL, $code = 0, Exception$previous = NULL) {
47 parent::__construct($message, $code, $previous);
48 }
49 }
50
51 class CRM_Core_Error extends PEAR_ErrorStack {
52
53 /**
54 * status code of various types of errors
55 * @var const
56 */
57 CONST FATAL_ERROR = 2;
58 CONST DUPLICATE_CONTACT = 8001;
59 CONST DUPLICATE_CONTRIBUTION = 8002;
60 CONST DUPLICATE_PARTICIPANT = 8003;
61
62 /**
63 * We only need one instance of this object. So we use the singleton
64 * pattern and cache the instance in this variable
65 * @var object
66 * @static
67 */
68 private static $_singleton = NULL;
69
70 /**
71 * The logger object for this application
72 * @var object
73 * @static
74 */
75 private static $_log = NULL;
76
77 /**
78 * If modeException == true, errors are raised as exception instead of returning civicrm_errors
79 * @static
80 */
81 public static $modeException = NULL;
82
83 /**
84 * singleton function used to manage this object.
85 *
86 * @return object
87 * @static
88 */
89 static function &singleton($package = NULL, $msgCallback = FALSE, $contextCallback = FALSE, $throwPEAR_Error = FALSE, $stackClass = 'PEAR_ErrorStack') {
90 if (self::$_singleton === NULL) {
91 self::$_singleton = new CRM_Core_Error('CiviCRM');
92 }
93 return self::$_singleton;
94 }
95
96 /**
97 * construcor
98 */
99 function __construct() {
100 parent::__construct('CiviCRM');
101
102 $log = CRM_Core_Config::getLog();
103 $this->setLogger($log);
104
105 // set up error handling for Pear Error Stack
106 $this->setDefaultCallback(array($this, 'handlePES'));
107 }
108
109 static public function getMessages(&$error, $separator = '<br />') {
110 if (is_a($error, 'CRM_Core_Error')) {
111 $errors = $error->getErrors();
112 $message = array();
113 foreach ($errors as $e) {
114 $message[] = $e['code'] . ': ' . $e['message'];
115 }
116 $message = implode($separator, $message);
117 return $message;
118 }
119 return NULL;
120 }
121
122 function displaySessionError(&$error, $separator = '<br />') {
123 $message = self::getMessages($error, $separator);
124 if ($message) {
125 $status = ts("Payment Processor Error message") . "{$separator} $message";
126 $session = CRM_Core_Session::singleton();
127 $session->setStatus($status);
128 }
129 }
130
131 /**
132 * create the main callback method. this method centralizes error processing.
133 *
134 * the errors we expect are from the pear modules DB, DB_DataObject
135 * which currently use PEAR::raiseError to notify of error messages.
136 *
137 * @param object PEAR_Error
138 *
139 * @return void
140 * @access public
141 */
142 public static function handle($pearError) {
143
144 // setup smarty with config, session and template location.
145 $template = CRM_Core_Smarty::singleton();
146 $config = CRM_Core_Config::singleton();
147
148 if ($config->backtrace) {
149 self::backtrace();
150 }
151
152 // create the error array
153 $error = array();
154 $error['callback'] = $pearError->getCallback();
155 $error['code'] = $pearError->getCode();
156 $error['message'] = $pearError->getMessage();
157 $error['mode'] = $pearError->getMode();
158 $error['debug_info'] = $pearError->getDebugInfo();
159 $error['type'] = $pearError->getType();
160 $error['user_info'] = $pearError->getUserInfo();
161 $error['to_string'] = $pearError->toString();
162 if (function_exists('mysql_error') &&
163 mysql_error()
164 ) {
165 $mysql_error = mysql_error() . ', ' . mysql_errno();
166 $template->assign_by_ref('mysql_code', $mysql_error);
167
168 // execute a dummy query to clear error stack
169 mysql_query('select 1');
170 }
171 elseif (function_exists('mysqli_error')) {
172 $dao = new CRM_Core_DAO();
173
174 // we do it this way, since calling the function
175 // getDatabaseConnection could potentially result
176 // in an infinite loop
177 global $_DB_DATAOBJECT;
178 if (isset($_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5])) {
179 $conn = $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
180 $link = $conn->connection;
181
182 if (mysqli_error($link)) {
183 $mysql_error = mysqli_error($link) . ', ' . mysqli_errno($link);
184 $template->assign_by_ref('mysql_code', $mysql_error);
185
186 // execute a dummy query to clear error stack
187 mysqli_query($link, 'select 1');
188 }
189 }
190 }
191
192 $template->assign_by_ref('error', $error);
193 $errorDetails = CRM_Core_Error::debug('', $error, FALSE);
194 $template->assign_by_ref('errorDetails', $errorDetails);
195
196 CRM_Core_Error::debug_var('Fatal Error Details', $error);
197 CRM_Core_Error::backtrace('backTrace', TRUE);
198
199 if ($config->initialized) {
200 $content = $template->fetch('CRM/common/fatal.tpl');
201 echo CRM_Utils_System::theme($content);
202 }
203 else {
204 echo "Sorry. A non-recoverable error has occurred. The error trace below might help to resolve the issue<p>";
205 CRM_Core_Error::debug(NULL, $error);
206 }
207 static $runOnce = FALSE;
208 if ($runOnce) {
209 exit;
210 }
211 $runOnce = TRUE;
212 self::abend(1);
213 }
214
215 // this function is used to trap and print errors
216 // during system initialization time. Hence the error
217 // message is quite ugly
218 public static function simpleHandler($pearError) {
219
220 // create the error array
221 $error = array();
222 $error['callback'] = $pearError->getCallback();
223 $error['code'] = $pearError->getCode();
224 $error['message'] = $pearError->getMessage();
225 $error['mode'] = $pearError->getMode();
226 $error['debug_info'] = $pearError->getDebugInfo();
227 $error['type'] = $pearError->getType();
228 $error['user_info'] = $pearError->getUserInfo();
229 $error['to_string'] = $pearError->toString();
230
231 // ensure that debug does not check permissions since we are in bootstrap
232 // mode and need to print a decent message to help the user
233 CRM_Core_Error::debug('Initialization Error', $error, TRUE, TRUE, FALSE);
234
235 // always log the backtrace to a file
236 self::backtrace('backTrace', TRUE);
237
238 exit(0);
239 }
240
241 /**
242 * Handle errors raised using the PEAR Error Stack.
243 *
244 * currently the handler just requests the PES framework
245 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
246 *
247 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
248 *
249 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
250 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
251 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
252 *
253 */
254 public static function handlePES($pearError) {
255 return PEAR_ERRORSTACK_PUSH;
256 }
257
258 /**
259 * display an error page with an error message describing what happened
260 *
261 * @param string message the error message
262 * @param string code the error code if any
263 * @param string email the email address to notify of this situation
264 *
265 * @return void
266 * @static
267 * @acess public
268 */
269 static function fatal($message = NULL, $code = NULL, $email = NULL) {
270 $vars = array(
271 'message' => $message,
272 'code' => $code,
273 );
274
275 if (self::$modeException) {
276 // CRM-11043
277 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
278 CRM_Core_Error::backtrace('backTrace', TRUE);
279
280 $details = 'A fatal error was triggered';
281 if ($message) {
282 $details .= ': ' . $message;
283 }
284 throw new Exception($details, $code);
285 }
286
287 if (!$message) {
288 $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/'));
289 }
290
291 if (php_sapi_name() == "cli") {
292 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
293 debug_print_backtrace();
294 die("\n");
295 // FIXME: Why doesn't this call abend()?
296 // Difference: abend() will cleanup transaction and (via civiExit) store session state
297 // self::abend(CRM_Core_Error::FATAL_ERROR);
298 }
299
300 $config = CRM_Core_Config::singleton();
301
302 if ($config->fatalErrorHandler &&
303 function_exists($config->fatalErrorHandler)
304 ) {
305 $name = $config->fatalErrorHandler;
306 $ret = $name($vars);
307 if ($ret) {
308 // the call has been successfully handled
309 // so we just exit
310 self::abend(CRM_Core_Error::FATAL_ERROR);
311 }
312 }
313
314 if ($config->backtrace) {
315 self::backtrace();
316 }
317
318 $template = CRM_Core_Smarty::singleton();
319 $template->assign($vars);
320
321 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
322 CRM_Core_Error::backtrace('backTrace', TRUE);
323 $content = $template->fetch($config->fatalErrorTemplate);
324 // JErrorPage exists only in 3.x and not 2.x
325 // CRM-13714
326 if ($config->userFramework == 'Joomla' && class_exists('JErrorPage')) {
327 $error = new Exception($content);
328 JErrorPage::render($error);
329 }
330 else if ($config->userFramework == 'Joomla' && class_exists('JError')) {
331 JError::raiseError('CiviCRM-001', $content);
332 }
333 else {
334 echo CRM_Utils_System::theme($content);
335 }
336
337 self::abend(CRM_Core_Error::FATAL_ERROR);
338 }
339
340 /**
341 * display an error page with an error message describing what happened
342 *
343 * This function is evil -- it largely replicates fatal(). Hopefully the
344 * entire CRM_Core_Error system can be hollowed out and replaced with
345 * something that follows a cleaner separation of concerns.
346 *
347 * @param Exception $exception
348 *
349 * @return void
350 * @static
351 * @acess public
352 */
353 static function handleUnhandledException($exception) {
354 $config = CRM_Core_Config::singleton();
355 $vars = array(
356 'message' => $exception->getMessage(),
357 'code' => NULL,
358 'exception' => $exception,
359 );
360 if (!$vars['message']) {
361 $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/'));
362 }
363
364 // Case A: CLI
365 if (php_sapi_name() == "cli") {
366 printf("Sorry. A non-recoverable error has occurred.\n%s\n", $vars['message']);
367 print self::formatTextException($exception);
368 die("\n");
369 // FIXME: Why doesn't this call abend()?
370 // Difference: abend() will cleanup transaction and (via civiExit) store session state
371 // self::abend(CRM_Core_Error::FATAL_ERROR);
372 }
373
374 // Case B: Custom error handler
375 if ($config->fatalErrorHandler &&
376 function_exists($config->fatalErrorHandler)
377 ) {
378 $name = $config->fatalErrorHandler;
379 $ret = $name($vars);
380 if ($ret) {
381 // the call has been successfully handled
382 // so we just exit
383 self::abend(CRM_Core_Error::FATAL_ERROR);
384 }
385 }
386
387 // Case C: Default error handler
388
389 // log to file
390 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
391 CRM_Core_Error::backtrace('backTrace', TRUE);
392
393 // print to screen
394 $template = CRM_Core_Smarty::singleton();
395 $template->assign($vars);
396 $content = $template->fetch($config->fatalErrorTemplate);
397 if ($config->backtrace) {
398 $content = self::formatHtmlException($exception) . $content;
399 }
400 if ($config->userFramework == 'Joomla' &&
401 class_exists('JError')
402 ) {
403 JError::raiseError('CiviCRM-001', $content);
404 }
405 else {
406 echo CRM_Utils_System::theme($content);
407 }
408
409 // fin
410 self::abend(CRM_Core_Error::FATAL_ERROR);
411 }
412
413 /**
414 * outputs pre-formatted debug information. Flushes the buffers
415 * so we can interrupt a potential POST/redirect
416 *
417 * @param string name of debug section
418 * @param mixed reference to variables that we need a trace of
419 * @param bool should we log or return the output
420 * @param bool whether to generate a HTML-escaped output
421 * @param bool should we check permissions before displaying output
422 * useful when we die during initialization and permissioning
423 * subsystem is not initialized - CRM-13765
424 *
425 * @return string the generated output
426 * @access public
427 * @static
428 */
429 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE, $checkPermission = TRUE) {
430 $error = self::singleton();
431
432 if ($variable === NULL) {
433 $variable = $name;
434 $name = NULL;
435 }
436
437 $out = print_r($variable, TRUE);
438 $prefix = NULL;
439 if ($html) {
440 $out = htmlspecialchars($out);
441 if ($name) {
442 $prefix = "<p>$name</p>";
443 }
444 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
445 }
446 else {
447 if ($name) {
448 $prefix = "$name:\n";
449 }
450 $out = "{$prefix}$out\n";
451 }
452 if (
453 $log &&
454 (!$checkPermission || CRM_Core_Permission::check('view debug output'))
455 ) {
456 echo $out;
457 }
458
459 return $out;
460 }
461
462 /**
463 * Similar to the function debug. Only difference is
464 * in the formatting of the output.
465 *
466 * @param string variable name
467 * @param mixed reference to variables that we need a trace of
468 * @param bool should we use print_r ? (else we use var_dump)
469 * @param bool should we log or return the output
470 *
471 * @return string the generated output
472 *
473 * @access public
474 *
475 * @static
476 *
477 * @see CRM_Core_Error::debug()
478 * @see CRM_Core_Error::debug_log_message()
479 */
480 static function debug_var($variable_name,
481 $variable,
482 $print = TRUE,
483 $log = TRUE,
484 $comp = ''
485 ) {
486 // check if variable is set
487 if (!isset($variable)) {
488 $out = "\$$variable_name is not set";
489 }
490 else {
491 if ($print) {
492 $out = print_r($variable, TRUE);
493 $out = "\$$variable_name = $out";
494 }
495 else {
496 // use var_dump
497 ob_start();
498 var_dump($variable);
499 $dump = ob_get_contents();
500 ob_end_clean();
501 $out = "\n\$$variable_name = $dump";
502 }
503 // reset if it is an array
504 if (is_array($variable)) {
505 reset($variable);
506 }
507 }
508 return self::debug_log_message($out, FALSE, $comp);
509 }
510
511 /**
512 * display the error message on terminal
513 *
514 * @param string message to be output
515 * @param bool should we log or return the output
516 *
517 * @return string format of the backtrace
518 *
519 * @access public
520 *
521 * @static
522 */
523 static function debug_log_message($message, $out = FALSE, $comp = '') {
524 $config = CRM_Core_Config::singleton();
525
526 $file_log = self::createDebugLogger($comp);
527 $file_log->log("$message\n");
528 $str = "<p/><code>$message</code>";
529 if ($out && CRM_Core_Permission::check('view debug output')) {
530 echo $str;
531 }
532 $file_log->close();
533
534 if ($config->userFrameworkLogging) {
535 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
536 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG);
537 }
538 }
539
540 return $str;
541 }
542
543 /**
544 * Append to the query log (if enabled)
545 */
546 static function debug_query($string) {
547 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
548 if ( CIVICRM_DEBUG_LOG_QUERY == 'backtrace' ) {
549 CRM_Core_Error::backtrace( $string, true );
550 } else if ( CIVICRM_DEBUG_LOG_QUERY ) {
551 CRM_Core_Error::debug_var( 'Query', $string, false, true );
552 }
553 }
554 }
555
556 /**
557 * Obtain a reference to the error log
558 *
559 * @return Log
560 */
561 static function createDebugLogger($comp = '') {
562 $config = CRM_Core_Config::singleton();
563
564 if ($comp) {
565 $comp = $comp . '.';
566 }
567
568 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn) . '.log';
569
570 // Roll log file monthly or if greater than 256M
571 // note that PHP file functions have a limit of 2G and hence
572 // the alternative was introduce
573 if (file_exists($fileName)) {
574 $fileTime = date("Ym", filemtime($fileName));
575 $fileSize = filesize($fileName);
576 if (($fileTime < date('Ym')) ||
577 ($fileSize > 256 * 1024 * 1024) ||
578 ($fileSize < 0)
579 ) {
580 rename($fileName,
581 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
582 );
583 }
584 }
585
586 return Log::singleton('file', $fileName);
587 }
588
589 static function backtrace($msg = 'backTrace', $log = FALSE) {
590 $backTrace = debug_backtrace();
591 $message = self::formatBacktrace($backTrace);
592 if (!$log) {
593 CRM_Core_Error::debug($msg, $message);
594 }
595 else {
596 CRM_Core_Error::debug_var($msg, $message);
597 }
598 }
599
600 /**
601 * Render a backtrace array as a string
602 *
603 * @param array $backTrace array of stack frames
604 * @param boolean $showArgs 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
605 * @param int $maxArgLen maximum number of characters to show from each argument string
606 * @return string printable plain-text
607 * @see debug_backtrace
608 * @see Exception::getTrace()
609 */
610 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
611 $message = '';
612 foreach ($backTrace as $idx => $trace) {
613 $args = array();
614 $fnName = CRM_Utils_Array::value('function', $trace);
615 $className = array_key_exists('class', $trace) ? ($trace['class'] . $trace['type']) : '';
616
617 // do now show args for a few password related functions
618 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
619
620 foreach ($trace['args'] as $arg) {
621 if (! $showArgs || $skipArgs) {
622 $args[] = '(' . gettype($arg) . ')';
623 continue;
624 }
625 switch ($type = gettype($arg)) {
626 case 'boolean':
627 $args[] = $arg ? 'TRUE' : 'FALSE';
628 break;
629 case 'integer':
630 case 'double':
631 $args[] = $arg;
632 break;
633 case 'string':
634 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
635 break;
636 case 'array':
637 $args[] = '(Array:'.count($arg).')';
638 break;
639 case 'object':
640 $args[] = 'Object(' . get_class($arg) . ')';
641 break;
642 case 'resource':
643 $args[] = 'Resource';
644 break;
645 case 'NULL':
646 $args[] = 'NULL';
647 break;
648 default:
649 $args[] = "($type)";
650 break;
651 }
652 }
653
654 $message .= sprintf(
655 "#%s %s(%s): %s%s(%s)\n",
656 $idx,
657 CRM_Utils_Array::value('file', $trace, '[internal function]'),
658 CRM_Utils_Array::value('line', $trace, ''),
659 $className,
660 $fnName,
661 implode(", ", $args)
662 );
663 }
664 $message .= sprintf("#%s {main}\n", 1+$idx);
665 return $message;
666 }
667
668 /**
669 * Render an exception as HTML string
670 *
671 * @param Exception $e
672 * @return string printable HTML text
673 */
674 static function formatHtmlException(Exception $e) {
675 $msg = '';
676
677 // Exception metadata
678
679 // Exception backtrace
680 if ($e instanceof PEAR_Exception) {
681 $ei = $e;
682 while (is_callable(array($ei, 'getCause'))) {
683 if ($ei->getCause() instanceof PEAR_Error) {
684 $msg .= '<table class="crm-db-error">';
685 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
686 $msg .= '<tbody>';
687 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
688 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
689 }
690 $msg .= '</tbody></table>';
691 }
692 $ei = $ei->getCause();
693 }
694 $msg .= $e->toHtml();
695 } else {
696 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
697 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
698 }
699 return $msg;
700 }
701
702 /**
703 * Write details of an exception to the log
704 *
705 * @param Exception $e
706 * @return string printable plain text
707 */
708 static function formatTextException(Exception $e) {
709 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
710
711 $ei = $e;
712 while (is_callable(array($ei, 'getCause'))) {
713 if ($ei->getCause() instanceof PEAR_Error) {
714 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
715 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
716 }
717 }
718 $ei = $ei->getCause();
719 }
720 $msg .= self::formatBacktrace($e->getTrace());
721 return $msg;
722 }
723
724 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
725 $error = CRM_Core_Error::singleton();
726 $error->push($code, $level, array($params), $message);
727 return $error;
728 }
729
730 /**
731 * Set a status message in the session, then bounce back to the referrer.
732 *
733 * @param string $status The status message to set
734 *
735 * @return void
736 * @access public
737 * @static
738 */
739 public static function statusBounce($status, $redirect = NULL, $title = '') {
740 $session = CRM_Core_Session::singleton();
741 if (!$redirect) {
742 $redirect = $session->readUserContext();
743 }
744 $session->setStatus($status, $title);
745 CRM_Utils_System::redirect($redirect);
746 }
747
748 /**
749 * Function to reset the error stack
750 *
751 * @access public
752 * @static
753 */
754 public static function reset() {
755 $error = self::singleton();
756 $error->_errors = array();
757 $error->_errorsByLevel = array();
758 }
759
760 public static function ignoreException($callback = NULL) {
761 if (!$callback) {
762 $callback = array('CRM_Core_Error', 'nullHandler');
763 }
764
765 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
766 $GLOBALS['_PEAR_default_error_options'] = $callback;
767 }
768
769 public static function exceptionHandler($pearError) {
770 CRM_Core_Error::backtrace('backTrace', TRUE);
771 throw new PEAR_Exception($pearError->getMessage(), $pearError);
772 }
773
774 /**
775 * Error handler to quietly catch otherwise fatal smtp transport errors.
776 *
777 * @param object $obj The PEAR_ERROR object
778 *
779 * @return object $obj
780 * @access public
781 * @static
782 */
783 public static function nullHandler($obj) {
784 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
785 CRM_Core_Error::backtrace('backTrace', TRUE);
786 return $obj;
787 }
788
789 /**
790 * (Re)set the default callback method
791 *
792 * @return void
793 * @access public
794 * @static
795 */
796 public static function setCallback($callback = NULL) {
797 if (!$callback) {
798 $callback = array('CRM_Core_Error', 'handle');
799 }
800 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
801 $GLOBALS['_PEAR_default_error_options'] = $callback;
802 }
803
804 /*
805 * @deprecated
806 * This function is no longer used by v3 api.
807 * @fixme Some core files call it but it should be re-thought & renamed or removed
808 */
809 public static function &createAPIError($msg, $data = NULL) {
810 if (self::$modeException) {
811 throw new Exception($msg, $data);
812 }
813
814 $values = array();
815
816 $values['is_error'] = 1;
817 $values['error_message'] = $msg;
818 if (isset($data)) {
819 $values = array_merge($values, $data);
820 }
821 return $values;
822 }
823
824 public static function movedSiteError($file) {
825 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
826 'reset=1',
827 TRUE
828 );
829 echo "We could not write $file. Have you moved your site directory or server?<p>";
830 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
831 exit();
832 }
833
834 /**
835 * Terminate execution abnormally
836 */
837 protected static function abend($code) {
838 // do a hard rollback of any pending transactions
839 // if we've come here, its because of some unexpected PEAR errors
840 CRM_Core_Transaction::forceRollbackIfEnabled();
841 CRM_Utils_System::civiExit($code);
842 }
843
844 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
845 if (is_array($error) && CRM_Utils_Array::value('is_error', $error)) {
846 $code = $error['error_message']['code'];
847 if ($code == $type) {
848 return TRUE;
849 }
850 }
851 return FALSE;
852 }
853 }
854
855 $e = new PEAR_ErrorStack('CRM');
856 $e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');