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' ) {
99 // Don't even bother with OutputPage if there's no Title context set,
100 // (e.g. we're in RL code on load.php) - the Skin system (and probably
101 // most of MediaWiki) won't work.
104 !empty( $GLOBALS['wgFullyInitialised'] ) &&
105 !empty( $GLOBALS['wgOut'] ) &&
106 RequestContext
::getMain()->getTitle() &&
107 !defined( 'MEDIAWIKI_INSTALL' )
112 * Output the exception report using HTML
114 * @param Exception|Throwable $e
116 private static function reportHTML( $e ) {
117 global $wgOut, $wgSitename;
119 if ( self
::useOutputPage( $e ) ) {
120 if ( $e instanceof MWException
) {
121 $wgOut->prepareErrorPage( $e->getPageTitle() );
122 } elseif ( $e instanceof DBReadOnlyError
) {
123 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
124 } elseif ( $e instanceof DBExpectedError
) {
125 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
127 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
130 // Show any custom GUI message before the details
131 if ( $e instanceof MessageSpecifier
) {
132 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
134 $wgOut->addHTML( self
::getHTML( $e ) );
138 self
::header( 'Content-Type: text/html; charset=utf-8' );
139 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
140 echo "<!DOCTYPE html>\n" .
142 // Mimick OutputPage::setPageTitle behaviour
144 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
146 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
149 echo self
::getHTML( $e );
151 echo "</body></html>\n";
156 * If $wgShowExceptionDetails is true, return a HTML message with a
157 * backtrace to the error, otherwise show a message to ask to set it to true
158 * to show that information.
160 * @param Exception|Throwable $e
161 * @return string Html to output
163 public static function getHTML( $e ) {
164 if ( self
::showBackTrace( $e ) ) {
165 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
166 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
167 '</p><p>Backtrace:</p><p>' .
168 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
171 $logId = WebRequest
::getRequestId();
172 $html = "<div class=\"errorbox mw-content-ltr\">" .
173 '[' . $logId . '] ' .
174 gmdate( 'Y-m-d H:i:s' ) . ": " .
175 self
::msg( "internalerror-fatal-exception",
176 "Fatal exception of type $1",
179 MWExceptionHandler
::getURL()
181 "<!-- " . wordwrap( self
::getShowBacktraceError( $e ), 50 ) . " -->";
188 * Get a message from i18n
190 * @param string $key Message name
191 * @param string $fallback Default message if the message cache can't be
192 * called by the exception
193 * The function also has other parameters that are arguments for the message
194 * @return string Message with arguments replaced
196 private static function msg( $key, $fallback /*[, params...] */ ) {
197 $args = array_slice( func_get_args(), 2 );
199 return wfMessage( $key, $args )->text();
200 } catch ( Exception
$e ) {
201 return wfMsgReplaceArgs( $fallback, $args );
206 * @param Exception|Throwable $e
209 private static function getText( $e ) {
210 if ( self
::showBackTrace( $e ) ) {
211 return MWExceptionHandler
::getLogMessage( $e ) .
213 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
215 return self
::getShowBacktraceError( $e );
220 * @param Exception|Throwable $e
223 private static function showBackTrace( $e ) {
224 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
227 $wgShowExceptionDetails &&
228 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
233 * @param Exception|Throwable $e
236 private static function getShowBacktraceError( $e ) {
237 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
239 if ( !$wgShowExceptionDetails ) {
240 $vars[] = '$wgShowExceptionDetails = true;';
242 if ( $e instanceof DBError
&& !$wgShowDBErrorBacktrace ) {
243 $vars[] = '$wgShowDBErrorBacktrace = true;';
245 $vars = implode( ' and ', $vars );
246 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information\n";
252 private static function isCommandLine() {
253 return !empty( $GLOBALS['wgCommandLineMode'] );
257 * @param string $header
259 private static function header( $header ) {
260 if ( !headers_sent() ) {
266 * @param integer $code
268 private static function statusHeader( $code ) {
269 if ( !headers_sent() ) {
270 HttpStatus
::header( $code );
275 * Print a message, if possible to STDERR.
276 * Use this in command line mode only (see isCommandLine)
278 * @param string $message Failure text
280 private static function printError( $message ) {
281 // NOTE: STDERR may not be available, especially if php-cgi is used from the
282 // command line (bug #15602). Try to produce meaningful output anyway. Using
283 // echo may corrupt output to STDOUT though.
284 if ( defined( 'STDERR' ) ) {
285 fwrite( STDERR
, $message );
292 * @param Exception|Throwable $e
294 private static function reportOutageHTML( $e ) {
295 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
297 $sorry = htmlspecialchars( self
::msg(
299 'Sorry! This site is experiencing technical difficulties.'
301 $again = htmlspecialchars( self
::msg(
303 'Try waiting a few minutes and reloading.'
306 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
309 Html
::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
310 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
313 $info = htmlspecialchars( self
::msg(
315 '(Cannot access the database)'
319 MessageCache
::singleton()->disable(); // no DB access
321 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
323 if ( $wgShowDBErrorBacktrace ) {
324 $html .= '<p>Backtrace:</p><pre>' .
325 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
329 $html .= self
::googleSearchForm();
337 private static function googleSearchForm() {
338 global $wgSitename, $wgCanonicalServer, $wgRequest;
340 $usegoogle = htmlspecialchars( self
::msg(
342 'You can try searching via Google in the meantime.'
344 $outofdate = htmlspecialchars( self
::msg(
346 'Note that their indexes of our content may be out of date.'
348 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
349 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
350 $server = htmlspecialchars( $wgCanonicalServer );
351 $sitename = htmlspecialchars( $wgSitename );
353 <div style="margin: 1.5em">$usegoogle<br />
354 <small>$outofdate</small>
356 <form method="get" action="//www.google.com/search" id="googlesearch">
357 <input type="hidden" name="domains" value="$server" />
358 <input type="hidden" name="num" value="50" />
359 <input type="hidden" name="ie" value="UTF-8" />
360 <input type="hidden" name="oe" value="UTF-8" />
361 <input type="text" name="q" size="31" maxlength="255" value="$search" />
362 <input type="submit" name="btnG" value="$googlesearch" />
364 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
365 <label><input type="radio" name="sitesearch" value="" />WWW</label>