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