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
21 use Wikimedia\Rdbms\DBConnectionError
;
22 use Wikimedia\Rdbms\DBError
;
23 use Wikimedia\Rdbms\DBReadOnlyError
;
24 use Wikimedia\Rdbms\DBExpectedError
;
27 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
30 class MWExceptionRenderer
{
31 const AS_RAW
= 1; // show as text
32 const AS_PRETTY
= 2; // show as HTML
35 * @param Exception|Throwable $e Original exception
36 * @param int $mode MWExceptionExposer::AS_* constant
37 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
39 public static function output( $e, $mode, $eNew = null ) {
42 if ( defined( 'MW_API' ) ) {
43 // Unhandled API exception, we can't be sure that format printer is alive
44 self
::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
45 wfHttpError( 500, 'Internal Server Error', self
::getText( $e ) );
46 } elseif ( self
::isCommandLine() ) {
47 self
::printError( self
::getText( $e ) );
48 } elseif ( $mode === self
::AS_PRETTY
) {
49 self
::statusHeader( 500 );
50 if ( $e instanceof DBConnectionError
) {
51 self
::reportOutageHTML( $e );
53 self
::header( "Content-Type: $wgMimeType; charset=utf-8" );
54 self
::reportHTML( $e );
58 $message = "MediaWiki internal error.\n\n";
59 if ( self
::showBackTrace( $e ) ) {
60 $message .= 'Original exception: ' .
61 MWExceptionHandler
::getLogMessage( $e ) .
62 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $e ) .
63 "\n\nException caught inside exception handler: " .
64 MWExceptionHandler
::getLogMessage( $eNew ) .
65 "\nBacktrace:\n" . MWExceptionHandler
::getRedactedTraceAsString( $eNew );
67 $message .= 'Original exception: ' .
68 MWExceptionHandler
::getPublicLogMessage( $e );
69 $message .= "\n\nException caught inside exception handler.\n\n" .
70 self
::getShowBacktraceError( $e );
74 if ( self
::showBackTrace( $e ) ) {
75 $message = MWExceptionHandler
::getLogMessage( $e ) .
77 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
79 $message = MWExceptionHandler
::getPublicLogMessage( $e );
82 echo nl2br( htmlspecialchars( $message ) ) . "\n";
87 * @param Exception|Throwable $e
88 * @return bool Should the exception use $wgOut to output the error?
90 private static function useOutputPage( $e ) {
91 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
92 foreach ( $e->getTrace() as $frame ) {
93 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
98 // Don't even bother with OutputPage if there's no Title context set,
99 // (e.g. we're in RL code on load.php) - the Skin system (and probably
100 // most of MediaWiki) won't work.
103 !empty( $GLOBALS['wgFullyInitialised'] ) &&
104 !empty( $GLOBALS['wgOut'] ) &&
105 RequestContext
::getMain()->getTitle() &&
106 !defined( 'MEDIAWIKI_INSTALL' )
111 * Output the exception report using HTML
113 * @param Exception|Throwable $e
115 private static function reportHTML( $e ) {
116 global $wgOut, $wgSitename;
118 if ( self
::useOutputPage( $e ) ) {
119 if ( $e instanceof MWException
) {
120 $wgOut->prepareErrorPage( $e->getPageTitle() );
121 } elseif ( $e instanceof DBReadOnlyError
) {
122 $wgOut->prepareErrorPage( self
::msg( 'readonly', 'Database is locked' ) );
123 } elseif ( $e instanceof DBExpectedError
) {
124 $wgOut->prepareErrorPage( self
::msg( 'databaseerror', 'Database error' ) );
126 $wgOut->prepareErrorPage( self
::msg( 'internalerror', 'Internal error' ) );
129 // Show any custom GUI message before the details
130 if ( $e instanceof MessageSpecifier
) {
131 $wgOut->addHTML( Message
::newFromSpecifier( $e )->escaped() );
133 $wgOut->addHTML( self
::getHTML( $e ) );
137 self
::header( 'Content-Type: text/html; charset=utf-8' );
138 $pageTitle = self
::msg( 'internalerror', 'Internal error' );
139 echo "<!DOCTYPE html>\n" .
141 // Mimick OutputPage::setPageTitle behaviour
143 htmlspecialchars( self
::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
145 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
148 echo self
::getHTML( $e );
150 echo "</body></html>\n";
155 * If $wgShowExceptionDetails is true, return a HTML message with a
156 * backtrace to the error, otherwise show a message to ask to set it to true
157 * to show that information.
159 * @param Exception|Throwable $e
160 * @return string Html to output
162 public static function getHTML( $e ) {
163 if ( self
::showBackTrace( $e ) ) {
164 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
165 nl2br( htmlspecialchars( MWExceptionHandler
::getLogMessage( $e ) ) ) .
166 '</p><p>Backtrace:</p><p>' .
167 nl2br( htmlspecialchars( MWExceptionHandler
::getRedactedTraceAsString( $e ) ) ) .
170 $logId = WebRequest
::getRequestId();
171 $html = "<div class=\"errorbox mw-content-ltr\">" .
172 '[' . $logId . '] ' .
173 gmdate( 'Y-m-d H:i:s' ) . ": " .
174 self
::msg( "internalerror-fatal-exception",
175 "Fatal exception of type $1",
178 MWExceptionHandler
::getURL()
180 "<!-- " . wordwrap( self
::getShowBacktraceError( $e ), 50 ) . " -->";
187 * Get a message from i18n
189 * @param string $key Message name
190 * @param string $fallback Default message if the message cache can't be
191 * called by the exception
192 * The function also has other parameters that are arguments for the message
193 * @return string Message with arguments replaced
195 private static function msg( $key, $fallback /*[, params...] */ ) {
196 $args = array_slice( func_get_args(), 2 );
198 return wfMessage( $key, $args )->text();
199 } catch ( Exception
$e ) {
200 return wfMsgReplaceArgs( $fallback, $args );
205 * @param Exception|Throwable $e
208 private static function getText( $e ) {
209 if ( self
::showBackTrace( $e ) ) {
210 return MWExceptionHandler
::getLogMessage( $e ) .
212 MWExceptionHandler
::getRedactedTraceAsString( $e ) . "\n";
214 return self
::getShowBacktraceError( $e ) . "\n";
219 * @param Exception|Throwable $e
222 private static function showBackTrace( $e ) {
223 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
226 $wgShowExceptionDetails &&
227 ( !( $e instanceof DBError
) ||
$wgShowDBErrorBacktrace )
232 * @param Exception|Throwable $e
235 private static function getShowBacktraceError( $e ) {
236 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
238 if ( !$wgShowExceptionDetails ) {
239 $vars[] = '$wgShowExceptionDetails = true;';
241 if ( $e instanceof DBError
&& !$wgShowDBErrorBacktrace ) {
242 $vars[] = '$wgShowDBErrorBacktrace = true;';
244 $vars = implode( ' and ', $vars );
245 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information.";
251 private static function isCommandLine() {
252 return !empty( $GLOBALS['wgCommandLineMode'] );
256 * @param string $header
258 private static function header( $header ) {
259 if ( !headers_sent() ) {
267 private static function statusHeader( $code ) {
268 if ( !headers_sent() ) {
269 HttpStatus
::header( $code );
274 * Print a message, if possible to STDERR.
275 * Use this in command line mode only (see isCommandLine)
277 * @param string $message Failure text
279 private static function printError( $message ) {
280 // NOTE: STDERR may not be available, especially if php-cgi is used from the
281 // command line (bug #15602). Try to produce meaningful output anyway. Using
282 // echo may corrupt output to STDOUT though.
283 if ( defined( 'STDERR' ) ) {
284 fwrite( STDERR
, $message );
291 * @param Exception|Throwable $e
293 private static function reportOutageHTML( $e ) {
294 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
296 $sorry = htmlspecialchars( self
::msg(
298 'Sorry! This site is experiencing technical difficulties.'
300 $again = htmlspecialchars( self
::msg(
302 'Try waiting a few minutes and reloading.'
305 if ( $wgShowHostnames ||
$wgShowSQLErrors ) {
308 Html
::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
309 htmlspecialchars( self
::msg( 'dberr-info', '($1)' ) )
312 $info = htmlspecialchars( self
::msg(
314 '(Cannot access the database)'
318 MessageCache
::singleton()->disable(); // no DB access
320 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
322 if ( $wgShowDBErrorBacktrace ) {
323 $html .= '<p>Backtrace:</p><pre>' .
324 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
328 $html .= self
::googleSearchForm();
336 private static function googleSearchForm() {
337 global $wgSitename, $wgCanonicalServer, $wgRequest;
339 $usegoogle = htmlspecialchars( self
::msg(
341 'You can try searching via Google in the meantime.'
343 $outofdate = htmlspecialchars( self
::msg(
345 'Note that their indexes of our content may be out of date.'
347 $googlesearch = htmlspecialchars( self
::msg( 'searchbutton', 'Search' ) );
348 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
349 $server = htmlspecialchars( $wgCanonicalServer );
350 $sitename = htmlspecialchars( $wgSitename );
352 <div style="margin: 1.5em">$usegoogle<br />
353 <small>$outofdate</small>
355 <form method="get" action="//www.google.com/search" id="googlesearch">
356 <input type="hidden" name="domains" value="$server" />
357 <input type="hidden" name="num" value="50" />
358 <input type="hidden" name="ie" value="UTF-8" />
359 <input type="hidden" name="oe" value="UTF-8" />
360 <input type="text" name="q" size="31" maxlength="255" value="$search" />
361 <input type="submit" name="btnG" value="$googlesearch" />
363 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
364 <label><input type="radio" name="sitesearch" value="" />WWW</label>