Merge pull request #1962 from dlobo/CRM-13745
[civicrm-core.git] / CRM / Core / Error.php
CommitLineData
6a488035
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
232624b1 5 | CiviCRM version 4.4 |
6a488035
TO
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
39require_once 'PEAR/ErrorStack.php';
40require_once 'PEAR/Exception.php';
dcc4f6a7 41require_once 'CRM/Core/Exception.php';
6a488035
TO
42
43require_once 'Log.php';
44class 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
51class 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 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 }
3a210ec0
E
207 static $runOnce = FALSE;
208 if ($runOnce) {
209 exit;
210 }
211 $runOnce = TRUE;
6a488035
TO
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 CRM_Core_Error::debug('Initialization Error', $error);
232
233 // always log the backtrace to a file
234 self::backtrace('backTrace', TRUE);
235
236 exit(0);
237 }
238
239 /**
240 * Handle errors raised using the PEAR Error Stack.
241 *
242 * currently the handler just requests the PES framework
243 * to push the error to the stack (return value PEAR_ERRORSTACK_PUSH).
244 *
245 * Note: we can do our own error handling here and return PEAR_ERRORSTACK_IGNORE.
246 *
247 * Also, if we do not return any value the PEAR_ErrorStack::push() then does the
248 * action of PEAR_ERRORSTACK_PUSHANDLOG which displays the errors on the screen,
249 * since the logger set for this error stack is 'display' - see CRM_Core_Config::getLog();
250 *
251 */
252 public static function handlePES($pearError) {
253 return PEAR_ERRORSTACK_PUSH;
254 }
255
256 /**
257 * display an error page with an error message describing what happened
258 *
259 * @param string message the error message
260 * @param string code the error code if any
261 * @param string email the email address to notify of this situation
262 *
263 * @return void
264 * @static
265 * @acess public
266 */
267 static function fatal($message = NULL, $code = NULL, $email = NULL) {
268 $vars = array(
269 'message' => $message,
270 'code' => $code,
271 );
272
273 if (self::$modeException) {
274 // CRM-11043
275 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
276 CRM_Core_Error::backtrace('backTrace', TRUE);
277
278 $details = 'A fatal error was triggered';
279 if ($message) {
280 $details .= ': ' . $message;
281 }
282 throw new Exception($details, $code);
283 }
284
285 if (!$message) {
286 $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/'));
287 }
288
289 if (php_sapi_name() == "cli") {
290 print ("Sorry. A non-recoverable error has occurred.\n$message \n$code\n$email\n\n");
291 debug_print_backtrace();
292 die("\n");
293 // FIXME: Why doesn't this call abend()?
294 // Difference: abend() will cleanup transaction and (via civiExit) store session state
295 // self::abend(CRM_Core_Error::FATAL_ERROR);
296 }
297
298 $config = CRM_Core_Config::singleton();
299
300 if ($config->fatalErrorHandler &&
301 function_exists($config->fatalErrorHandler)
302 ) {
303 $name = $config->fatalErrorHandler;
304 $ret = $name($vars);
305 if ($ret) {
306 // the call has been successfully handled
307 // so we just exit
308 self::abend(CRM_Core_Error::FATAL_ERROR);
309 }
310 }
311
312 if ($config->backtrace) {
313 self::backtrace();
314 }
315
316 $template = CRM_Core_Smarty::singleton();
317 $template->assign($vars);
318
319 CRM_Core_Error::debug_var('Fatal Error Details', $vars);
320 CRM_Core_Error::backtrace('backTrace', TRUE);
321 $content = $template->fetch($config->fatalErrorTemplate);
95e86a0e
DL
322 if ($config->userFramework == 'Joomla') {
323 // JErrorPage exists only in 3.1.x
324 // a bit ugly hack, but want this in for 4.4.1
325 // CRM-13714
326 if (class_exists('JError') && !class_exists('JErrorPage')) {
327 JError::raiseError('CiviCRM-001', $content);
328 }
329 else {
330 echo CRM_Utils_System::theme($content);
331 }
6a488035 332 }
28c8781b
DL
333 else {
334 echo CRM_Utils_System::theme($content);
335 }
6a488035
TO
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 *
422 * @return string the generated output
423 * @access public
424 * @static
425 */
426 static function debug($name, $variable = NULL, $log = TRUE, $html = TRUE) {
427 $error = self::singleton();
428
429 if ($variable === NULL) {
430 $variable = $name;
431 $name = NULL;
432 }
433
434 $out = print_r($variable, TRUE);
435 $prefix = NULL;
436 if ($html) {
437 $out = htmlspecialchars($out);
438 if ($name) {
439 $prefix = "<p>$name</p>";
440 }
441 $out = "{$prefix}<p><pre>$out</pre></p><p></p>";
442 }
443 else {
444 if ($name) {
445 $prefix = "$name:\n";
446 }
447 $out = "{$prefix}$out\n";
448 }
449 if ($log && CRM_Core_Permission::check('view debug output')) {
450 echo $out;
451 }
452
453 return $out;
454 }
455
456 /**
457 * Similar to the function debug. Only difference is
458 * in the formatting of the output.
459 *
460 * @param string variable name
461 * @param mixed reference to variables that we need a trace of
462 * @param bool should we use print_r ? (else we use var_dump)
463 * @param bool should we log or return the output
464 *
465 * @return string the generated output
466 *
467 * @access public
468 *
469 * @static
470 *
471 * @see CRM_Core_Error::debug()
472 * @see CRM_Core_Error::debug_log_message()
473 */
474 static function debug_var($variable_name,
475 $variable,
476 $print = TRUE,
477 $log = TRUE,
478 $comp = ''
479 ) {
480 // check if variable is set
481 if (!isset($variable)) {
482 $out = "\$$variable_name is not set";
483 }
484 else {
485 if ($print) {
486 $out = print_r($variable, TRUE);
487 $out = "\$$variable_name = $out";
488 }
489 else {
490 // use var_dump
491 ob_start();
492 var_dump($variable);
493 $dump = ob_get_contents();
494 ob_end_clean();
495 $out = "\n\$$variable_name = $dump";
496 }
497 // reset if it is an array
498 if (is_array($variable)) {
499 reset($variable);
500 }
501 }
502 return self::debug_log_message($out, FALSE, $comp);
503 }
504
505 /**
506 * display the error message on terminal
507 *
508 * @param string message to be output
509 * @param bool should we log or return the output
510 *
511 * @return string format of the backtrace
512 *
513 * @access public
514 *
515 * @static
516 */
517 static function debug_log_message($message, $out = FALSE, $comp = '') {
518 $config = CRM_Core_Config::singleton();
519
520 $file_log = self::createDebugLogger($comp);
521 $file_log->log("$message\n");
522 $str = "<p/><code>$message</code>";
523 if ($out && CRM_Core_Permission::check('view debug output')) {
524 echo $str;
525 }
526 $file_log->close();
527
528 if ($config->userFrameworkLogging) {
529 if ($config->userSystem->is_drupal and function_exists('watchdog')) {
530 watchdog('civicrm', $message, NULL, WATCHDOG_DEBUG);
531 }
532 }
533
534 return $str;
535 }
536
537 /**
538 * Append to the query log (if enabled)
539 */
540 static function debug_query($string) {
541 if ( defined( 'CIVICRM_DEBUG_LOG_QUERY' ) ) {
542 if ( CIVICRM_DEBUG_LOG_QUERY == 'backtrace' ) {
543 CRM_Core_Error::backtrace( $string, true );
544 } else if ( CIVICRM_DEBUG_LOG_QUERY ) {
545 CRM_Core_Error::debug_var( 'Query', $string, false, true );
546 }
547 }
548 }
549
550 /**
551 * Obtain a reference to the error log
552 *
553 * @return Log
554 */
555 static function createDebugLogger($comp = '') {
556 $config = CRM_Core_Config::singleton();
557
558 if ($comp) {
559 $comp = $comp . '.';
560 }
561
562 $fileName = "{$config->configAndLogDir}CiviCRM." . $comp . md5($config->dsn) . '.log';
563
564 // Roll log file monthly or if greater than 256M
565 // note that PHP file functions have a limit of 2G and hence
566 // the alternative was introduce
567 if (file_exists($fileName)) {
568 $fileTime = date("Ym", filemtime($fileName));
569 $fileSize = filesize($fileName);
570 if (($fileTime < date('Ym')) ||
571 ($fileSize > 256 * 1024 * 1024) ||
572 ($fileSize < 0)
573 ) {
574 rename($fileName,
575 $fileName . '.' . date('Ymdhs', mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")))
576 );
577 }
578 }
579
580 return Log::singleton('file', $fileName);
581 }
582
583 static function backtrace($msg = 'backTrace', $log = FALSE) {
584 $backTrace = debug_backtrace();
585 $message = self::formatBacktrace($backTrace);
586 if (!$log) {
587 CRM_Core_Error::debug($msg, $message);
588 }
589 else {
590 CRM_Core_Error::debug_var($msg, $message);
591 }
592 }
593
594 /**
595 * Render a backtrace array as a string
596 *
597 * @param array $backTrace array of stack frames
598 * @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
599 * @param int $maxArgLen maximum number of characters to show from each argument string
600 * @return string printable plain-text
601 * @see debug_backtrace
602 * @see Exception::getTrace()
603 */
604 static function formatBacktrace($backTrace, $showArgs = TRUE, $maxArgLen = 80) {
605 $message = '';
606 foreach ($backTrace as $idx => $trace) {
607 $args = array();
608 $fnName = CRM_Utils_Array::value('function', $trace);
609 $className = array_key_exists('class', $trace) ? ($trace['class'] . $trace['type']) : '';
610
611 // do now show args for a few password related functions
612 $skipArgs = ($className == 'DB::' && $fnName == 'connect') ? TRUE : FALSE;
613
614 foreach ($trace['args'] as $arg) {
615 if (! $showArgs || $skipArgs) {
616 $args[] = '(' . gettype($arg) . ')';
617 continue;
618 }
619 switch ($type = gettype($arg)) {
620 case 'boolean':
621 $args[] = $arg ? 'TRUE' : 'FALSE';
622 break;
623 case 'integer':
624 case 'double':
625 $args[] = $arg;
626 break;
627 case 'string':
628 $args[] = '"' . CRM_Utils_String::ellipsify(addcslashes((string) $arg, "\r\n\t\""), $maxArgLen). '"';
629 break;
630 case 'array':
631 $args[] = '(Array:'.count($arg).')';
632 break;
633 case 'object':
634 $args[] = 'Object(' . get_class($arg) . ')';
635 break;
636 case 'resource':
637 $args[] = 'Resource';
638 break;
639 case 'NULL':
640 $args[] = 'NULL';
641 break;
642 default:
643 $args[] = "($type)";
644 break;
645 }
646 }
647
648 $message .= sprintf(
649 "#%s %s(%s): %s%s(%s)\n",
650 $idx,
651 CRM_Utils_Array::value('file', $trace, '[internal function]'),
652 CRM_Utils_Array::value('line', $trace, ''),
653 $className,
654 $fnName,
655 implode(", ", $args)
656 );
657 }
658 $message .= sprintf("#%s {main}\n", 1+$idx);
659 return $message;
660 }
661
662 /**
663 * Render an exception as HTML string
664 *
665 * @param Exception $e
666 * @return string printable HTML text
667 */
668 static function formatHtmlException(Exception $e) {
669 $msg = '';
670
671 // Exception metadata
672
673 // Exception backtrace
674 if ($e instanceof PEAR_Exception) {
675 $ei = $e;
676 while (is_callable(array($ei, 'getCause'))) {
677 if ($ei->getCause() instanceof PEAR_Error) {
678 $msg .= '<table class="crm-db-error">';
679 $msg .= sprintf('<thead><tr><th>%s</th><th>%s</th></tr></thead>', ts('Error Field'), ts('Error Value'));
680 $msg .= '<tbody>';
681 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
682 $msg .= sprintf('<tr><td>%s</td><td>%s</td></tr>', $f, call_user_func(array($ei->getCause(), "get$f")));
683 }
684 $msg .= '</tbody></table>';
685 }
686 $ei = $ei->getCause();
687 }
688 $msg .= $e->toHtml();
689 } else {
690 $msg .= '<p><b>' . get_class($e) . ': "' . htmlentities($e->getMessage()) . '"</b></p>';
691 $msg .= '<pre>' . htmlentities(self::formatBacktrace($e->getTrace())) . '</pre>';
692 }
693 return $msg;
694 }
695
696 /**
697 * Write details of an exception to the log
698 *
699 * @param Exception $e
700 * @return string printable plain text
701 */
702 static function formatTextException(Exception $e) {
703 $msg = get_class($e) . ": \"" . $e->getMessage() . "\"\n";
704
705 $ei = $e;
706 while (is_callable(array($ei, 'getCause'))) {
707 if ($ei->getCause() instanceof PEAR_Error) {
708 foreach (array('Type', 'Code', 'Message', 'Mode', 'UserInfo', 'DebugInfo') as $f) {
709 $msg .= sprintf(" * ERROR %s: %s\n", strtoupper($f), call_user_func(array($ei->getCause(), "get$f")));
710 }
711 }
712 $ei = $ei->getCause();
713 }
714 $msg .= self::formatBacktrace($e->getTrace());
715 return $msg;
716 }
717
718 static function createError($message, $code = 8000, $level = 'Fatal', $params = NULL) {
719 $error = CRM_Core_Error::singleton();
720 $error->push($code, $level, array($params), $message);
721 return $error;
722 }
723
724 /**
725 * Set a status message in the session, then bounce back to the referrer.
726 *
727 * @param string $status The status message to set
728 *
729 * @return void
730 * @access public
731 * @static
732 */
dcc4f6a7 733 public static function statusBounce($status, $redirect = NULL, $title = '') {
6a488035
TO
734 $session = CRM_Core_Session::singleton();
735 if (!$redirect) {
736 $redirect = $session->readUserContext();
737 }
dcc4f6a7 738 $session->setStatus($status, $title);
6a488035
TO
739 CRM_Utils_System::redirect($redirect);
740 }
741
742 /**
743 * Function to reset the error stack
744 *
745 * @access public
746 * @static
747 */
748 public static function reset() {
749 $error = self::singleton();
750 $error->_errors = array();
751 $error->_errorsByLevel = array();
752 }
753
754 public static function ignoreException($callback = NULL) {
755 if (!$callback) {
756 $callback = array('CRM_Core_Error', 'nullHandler');
757 }
758
759 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
760 $GLOBALS['_PEAR_default_error_options'] = $callback;
761 }
762
763 public static function exceptionHandler($pearError) {
764 CRM_Core_Error::backtrace('backTrace', TRUE);
765 throw new PEAR_Exception($pearError->getMessage(), $pearError);
766 }
767
768 /**
769 * Error handler to quietly catch otherwise fatal smtp transport errors.
770 *
771 * @param object $obj The PEAR_ERROR object
772 *
773 * @return object $obj
774 * @access public
775 * @static
776 */
777 public static function nullHandler($obj) {
778 CRM_Core_Error::debug_log_message("Ignoring exception thrown by nullHandler: {$obj->code}, {$obj->message}");
779 CRM_Core_Error::backtrace('backTrace', TRUE);
780 return $obj;
781 }
782
783 /**
784 * (Re)set the default callback method
785 *
786 * @return void
787 * @access public
788 * @static
789 */
790 public static function setCallback($callback = NULL) {
791 if (!$callback) {
792 $callback = array('CRM_Core_Error', 'handle');
793 }
794 $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_CALLBACK;
795 $GLOBALS['_PEAR_default_error_options'] = $callback;
796 }
797
798 /*
799 * @deprecated
800 * This function is no longer used by v3 api.
801 * @fixme Some core files call it but it should be re-thought & renamed or removed
802 */
803 public static function &createAPIError($msg, $data = NULL) {
804 if (self::$modeException) {
805 throw new Exception($msg, $data);
806 }
807
808 $values = array();
809
810 $values['is_error'] = 1;
811 $values['error_message'] = $msg;
812 if (isset($data)) {
813 $values = array_merge($values, $data);
814 }
815 return $values;
816 }
817
818 public static function movedSiteError($file) {
819 $url = CRM_Utils_System::url('civicrm/admin/setting/updateConfigBackend',
820 'reset=1',
821 TRUE
822 );
823 echo "We could not write $file. Have you moved your site directory or server?<p>";
824 echo "Please fix the setting by running the <a href=\"$url\">update config script</a>";
825 exit();
826 }
827
828 /**
829 * Terminate execution abnormally
830 */
831 protected static function abend($code) {
832 // do a hard rollback of any pending transactions
833 // if we've come here, its because of some unexpected PEAR errors
834 CRM_Core_Transaction::forceRollbackIfEnabled();
835 CRM_Utils_System::civiExit($code);
836 }
837
838 public static function isAPIError($error, $type = CRM_Core_Error::FATAL_ERROR) {
839 if (is_array($error) && CRM_Utils_Array::value('is_error', $error)) {
840 $code = $error['error_message']['code'];
841 if ($code == $type) {
842 return TRUE;
843 }
844 }
845 return FALSE;
846 }
847}
848
849$e = new PEAR_ErrorStack('CRM');
850$e->singleton('CRM', FALSE, NULL, 'CRM_Core_Error');