3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Aaron Schulz
22 use Wikimedia\Rdbms\DBConnectionError
;
23 use Wikimedia\Rdbms\DBError
;
24 use Wikimedia\Rdbms\DBReadOnlyError
;
25 use Wikimedia\Rdbms\DBExpectedError
;
28 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
31 class MWExceptionRenderer
{
32 const AS_RAW
= 1; // show as text
33 const AS_PRETTY
= 2; // show as HTML
36 * @param Exception|Throwable $e Original exception
37 * @param integer $mode MWExceptionExposer::AS_* constant
38 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
40 public static function output( $e, $mode, $eNew = null ) {
43 if ( defined( 'MW_API' ) ) {
44 // Unhandled API exception, we can't be sure that format printer is alive
45 self
::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
46 wfHttpError( 500, 'Internal Server Error', self
::getText( $e ) );
47 } elseif ( self
::isCommandLine() ) {
48 self
::printError( self
::getText( $e ) );
49 } elseif ( $mode === self
::AS_PRETTY
) {
50 self
::statusHeader( 500 );
51 if ( $e instanceof DBConnectionError
) {
52 self
::reportOutageHTML( $e );
54 self
::header( "Content-Type: $wgMimeType; charset=utf-8" );
55 self
::reportHTML( $e );
59 $message = "MediaWiki internal error.\n\n";
60 if ( self
::showBackTrace( $e ) ) {
61 $message .= 'Original exception: ' .
62 MWExceptionHandler
::getLogMessage( $e ) .
63 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $e ) .
64 "\n\nException caught inside exception handler: " .
65 MWExceptionHandler
::getLogMessage( $eNew ) .
66 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $eNew );
68 $message .= 'Original exception: ' .
69 MWExceptionHandler
::getPublicLogMessage( $e );
70 $message .= "\n\nException caught inside exception handler.\n\n" .
71 self
::getShowBacktraceError( $e );
75 if ( self
::showBackTrace( $e ) ) {
76 $message = MWExceptionHandler
::getLogMessage( $e ) .
78 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
80 $message = MWExceptionHandler
::getPublicLogMessage( $e );
83 echo nl2br( htmlspecialchars( $message ) ) . "\n";
88 * @param Exception|Throwable $e
89 * @return bool Should the exception use $wgOut to output the error?
91 private static function useOutputPage( $e ) {
92 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
93 foreach ( $e->getTrace() as $frame ) {
94 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
100 !empty( $GLOBALS['wgFullyInitialised'] ) &&
101 !empty( $GLOBALS['wgOut'] ) &&
102 !defined( 'MEDIAWIKI_INSTALL' )
107 * Output the exception report using HTML
109 * @param Exception|Throwable $e
111 private static function reportHTML( $e ) {
112 global $wgOut, $wgSitename;
114 if ( self
::useOutputPage( $e ) ) {
115 if ( $e instanceof MWException
) {
116 $wgOut->prepareErrorPage( $e->getPageTitle() );
117 } elseif ( $e instanceof DBReadOnlyError
) {
118 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
119 } elseif ( $e instanceof DBExpectedError
) {
120 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
122 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
125 // Show any custom GUI message before the details
126 if ( $e instanceof MessageSpecifier
) {
127 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
129 $wgOut->addHTML( self
::getHTML( $e ) );
133 self
::header( 'Content-Type: text/html; charset=utf-8' );
134 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
135 echo "<!DOCTYPE html>\n" .
137 // Mimick OutputPage::setPageTitle behaviour
139 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
141 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
144 echo self
::getHTML( $e );
146 echo "</body></html>\n";
151 * If $wgShowExceptionDetails is true, return a HTML message with a
152 * backtrace to the error, otherwise show a message to ask to set it to true
153 * to show that information.
155 * @param Exception|Throwable $e
156 * @return string Html to output
158 public static function getHTML( $e ) {
159 if ( self
::showBackTrace( $e ) ) {
160 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
161 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
162 '</p><p>Backtrace:</p><p>' .
163 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
166 $logId = WebRequest
::getRequestId();
167 $html = "<div class=\"errorbox mw-content-ltr\">" .
168 '[' . $logId . '] ' .
169 gmdate( 'Y-m-d H:i:s' ) . ": " .
170 self
::msg( "internalerror-fatal-exception",
171 "Fatal exception of type $1",
174 MWExceptionHandler
::getURL()
176 "<!-- " . wordwrap( self
::getShowBacktraceError( $e ), 50 ) . " -->";
183 * Get a message from i18n
185 * @param string $key Message name
186 * @param string $fallback Default message if the message cache can't be
187 * called by the exception
188 * The function also has other parameters that are arguments for the message
189 * @return string Message with arguments replaced
191 private static function msg( $key, $fallback /*[, params...] */ ) {
192 $args = array_slice( func_get_args(), 2 );
194 return wfMessage( $key, $args )->text();
195 } catch ( Exception
$e ) {
196 return wfMsgReplaceArgs( $fallback, $args );
201 * @param Exception|Throwable $e
204 private static function getText( $e ) {
205 if ( self
::showBackTrace( $e ) ) {
206 return MWExceptionHandler
::getLogMessage( $e ) .
208 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
210 return self
::getShowBacktraceError( $e );
215 * @param Exception|Throwable $e
218 private static function showBackTrace( $e ) {
219 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
222 $wgShowExceptionDetails &&
223 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
228 * @param Exception|Throwable $e
231 private static function getShowBacktraceError( $e ) {
232 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
234 if ( !$wgShowExceptionDetails ) {
235 $vars[] = '$wgShowExceptionDetails = true;';
237 if ( $e instanceof DBError
&& !$wgShowDBErrorBacktrace ) {
238 $vars[] = '$wgShowDBErrorBacktrace = true;';
240 $vars = implode( ' and ', $vars );
241 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information\n";
247 private static function isCommandLine() {
248 return !empty( $GLOBALS['wgCommandLineMode'] );
252 * @param string $header
254 private static function header( $header ) {
255 if ( !headers_sent() ) {
261 * @param integer $code
263 private static function statusHeader( $code ) {
264 if ( !headers_sent() ) {
265 HttpStatus
::header( $code );
270 * Print a message, if possible to STDERR.
271 * Use this in command line mode only (see isCommandLine)
273 * @param string $message Failure text
275 private static function printError( $message ) {
276 // NOTE: STDERR may not be available, especially if php-cgi is used from the
277 // command line (bug #15602). Try to produce meaningful output anyway. Using
278 // echo may corrupt output to STDOUT though.
279 if ( defined( 'STDERR' ) ) {
280 fwrite( STDERR
, $message );
287 * @param Exception|Throwable $e
289 private static function reportOutageHTML( $e ) {
290 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
292 $sorry = htmlspecialchars( self
::msg(
294 'Sorry! This site is experiencing technical difficulties.'
296 $again = htmlspecialchars( self
::msg(
298 'Try waiting a few minutes and reloading.'
301 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
304 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
305 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
308 $info = htmlspecialchars( self
::msg(
310 '(Cannot access the database)'
314 MessageCache
::singleton()->disable(); // no DB access
316 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
318 if ( $wgShowDBErrorBacktrace ) {
319 $html .= '<p>Backtrace:</p><pre>' .
320 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
324 $html .= self
::googleSearchForm();
332 private static function googleSearchForm() {
333 global $wgSitename, $wgCanonicalServer, $wgRequest;
335 $usegoogle = htmlspecialchars( self
::msg(
337 'You can try searching via Google in the meantime.'
339 $outofdate = htmlspecialchars( self
::msg(
341 'Note that their indexes of our content may be out of date.'
343 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
344 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
345 $server = htmlspecialchars( $wgCanonicalServer );
346 $sitename = htmlspecialchars( $wgSitename );
348 <div style="margin: 1.5em">$usegoogle<br />
349 <small>$outofdate</small>
351 <form method="get" action="//www.google.com/search" id="googlesearch">
352 <input type="hidden" name="domains" value="$server" />
353 <input type="hidden" name="num" value="50" />
354 <input type="hidden" name="ie" value="UTF-8" />
355 <input type="hidden" name="oe" value="UTF-8" />
356 <input type="text" name="q" size="31" maxlength="255" value="$search" />
357 <input type="submit" name="btnG" value="$googlesearch" />
359 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
360 <label><input type="radio" name="sitesearch" value="" />WWW</label>