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