Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / exception / MWExceptionRenderer.php
bloba569bcd808ac5d159e0f9024fb5db03926eb740a
1 <?php
2 /**
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
18 * @file
19 * @author Aaron Schulz
22 /**
23 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
24 * @since 1.28
26 class MWExceptionRenderer {
27 const AS_RAW = 1; // show as text
28 const AS_PRETTY = 2; // show as HTML
30 /**
31 * @param Exception|Throwable $e Original exception
32 * @param integer $mode MWExceptionExposer::AS_* constant
33 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
35 public static function output( $e, $mode, $eNew = null ) {
36 global $wgMimeType;
38 if ( defined( 'MW_API' ) ) {
39 // Unhandled API exception, we can't be sure that format printer is alive
40 self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
41 wfHttpError( 500, 'Internal Server Error', self::getText( $e ) );
42 } elseif ( self::isCommandLine() ) {
43 self::printError( self::getText( $e ) );
44 } elseif ( $mode === self::AS_PRETTY ) {
45 if ( $e instanceof DBConnectionError ) {
46 self::reportOutageHTML( $e );
47 } else {
48 self::statusHeader( 500 );
49 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
50 self::reportHTML( $e );
52 } else {
53 if ( $eNew ) {
54 $message = "MediaWiki internal error.\n\n";
55 if ( self::showBackTrace( $e ) ) {
56 $message .= 'Original exception: ' .
57 MWExceptionHandler::getLogMessage( $e ) .
58 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
59 "\n\nException caught inside exception handler: " .
60 MWExceptionHandler::getLogMessage( $eNew ) .
61 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
62 } else {
63 $message .= 'Original exception: ' .
64 MWExceptionHandler::getPublicLogMessage( $e );
65 $message .= "\n\nException caught inside exception handler.\n\n" .
66 self::getShowBacktraceError( $e );
68 $message .= "\n";
69 } else {
70 if ( self::showBackTrace( $e ) ) {
71 $message = MWExceptionHandler::getLogMessage( $e ) .
72 "\nBacktrace:\n" .
73 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
74 } else {
75 $message = MWExceptionHandler::getPublicLogMessage( $e );
78 echo nl2br( htmlspecialchars( $message ) ) . "\n";
82 /**
83 * Run hook to allow extensions to modify the text of the exception
85 * Called by MWException for b/c
87 * @param Exception|Throwable $e
88 * @param string $name Class name of the exception
89 * @param array $args Arguments to pass to the callback functions
90 * @return string|null String to output or null if any hook has been called
92 public static function runHooks( $e, $name, $args = [] ) {
93 global $wgExceptionHooks;
95 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
96 return null; // Just silently ignore
99 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
100 !is_array( $wgExceptionHooks[$name] )
102 return null;
105 $hooks = $wgExceptionHooks[$name];
106 $callargs = array_merge( [ $e ], $args );
108 foreach ( $hooks as $hook ) {
109 if (
110 is_string( $hook ) ||
111 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
113 // 'function' or [ 'class', 'hook' ]
114 $result = call_user_func_array( $hook, $callargs );
115 } else {
116 $result = null;
119 if ( is_string( $result ) ) {
120 return $result;
124 return null;
128 * @param Exception|Throwable $e
129 * @return bool Should the exception use $wgOut to output the error?
131 private static function useOutputPage( $e ) {
132 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
133 foreach ( $e->getTrace() as $frame ) {
134 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
135 return false;
139 return (
140 !empty( $GLOBALS['wgFullyInitialised'] ) &&
141 !empty( $GLOBALS['wgOut'] ) &&
142 !defined( 'MEDIAWIKI_INSTALL' )
147 * Output the exception report using HTML
149 * @param Exception|Throwable $e
151 private static function reportHTML( $e ) {
152 global $wgOut, $wgSitename;
154 if ( self::useOutputPage( $e ) ) {
155 if ( $e instanceof MWException ) {
156 $wgOut->prepareErrorPage( $e->getPageTitle() );
157 } elseif ( $e instanceof DBReadOnlyError ) {
158 $wgOut->prepareErrorPage( self::msg( 'readonly', 'Database is locked' ) );
159 } elseif ( $e instanceof DBExpectedError ) {
160 $wgOut->prepareErrorPage( self::msg( 'databaseerror', 'Database error' ) );
161 } else {
162 $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
165 $hookResult = self::runHooks( $e, get_class( $e ) );
166 if ( $hookResult ) {
167 $wgOut->addHTML( $hookResult );
168 } else {
169 // Show any custom GUI message before the details
170 if ( $e instanceof MessageSpecifier ) {
171 $wgOut->addHTML( Message::newFromSpecifier( $e )->escaped() );
173 $wgOut->addHTML( self::getHTML( $e ) );
176 $wgOut->output();
177 } else {
178 self::header( 'Content-Type: text/html; charset=utf-8' );
179 $pageTitle = self::msg( 'internalerror', 'Internal error' );
180 echo "<!DOCTYPE html>\n" .
181 '<html><head>' .
182 // Mimick OutputPage::setPageTitle behaviour
183 '<title>' .
184 htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
185 '</title>' .
186 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
187 "</head><body>\n";
189 $hookResult = self::runHooks( $e, get_class( $e ) . 'Raw' );
190 if ( $hookResult ) {
191 echo $hookResult;
192 } else {
193 echo self::getHTML( $e );
196 echo "</body></html>\n";
201 * If $wgShowExceptionDetails is true, return a HTML message with a
202 * backtrace to the error, otherwise show a message to ask to set it to true
203 * to show that information.
205 * @param Exception|Throwable $e
206 * @return string Html to output
208 public static function getHTML( $e ) {
209 if ( self::showBackTrace( $e ) ) {
210 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
211 nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
212 '</p><p>Backtrace:</p><p>' .
213 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
214 "</p></div>\n";
215 } else {
216 $logId = WebRequest::getRequestId();
217 $html = "<div class=\"errorbox mw-content-ltr\">" .
218 '[' . $logId . '] ' .
219 gmdate( 'Y-m-d H:i:s' ) . ": " .
220 self::msg( "internalerror-fatal-exception",
221 "Fatal exception of type $1",
222 get_class( $e ),
223 $logId,
224 MWExceptionHandler::getURL()
225 ) . "</div>\n" .
226 "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
229 return $html;
233 * Get a message from i18n
235 * @param string $key Message name
236 * @param string $fallback Default message if the message cache can't be
237 * called by the exception
238 * The function also has other parameters that are arguments for the message
239 * @return string Message with arguments replaced
241 private static function msg( $key, $fallback /*[, params...] */ ) {
242 $args = array_slice( func_get_args(), 2 );
243 try {
244 return wfMessage( $key, $args )->text();
245 } catch ( Exception $e ) {
246 return wfMsgReplaceArgs( $fallback, $args );
251 * @param Exception|Throwable $e
252 * @return string
254 private static function getText( $e ) {
255 if ( self::showBackTrace( $e ) ) {
256 return MWExceptionHandler::getLogMessage( $e ) .
257 "\nBacktrace:\n" .
258 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
259 } else {
260 return self::getShowBacktraceError( $e );
265 * @param Exception|Throwable $e
266 * @return bool
268 private static function showBackTrace( $e ) {
269 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
271 return (
272 $wgShowExceptionDetails &&
273 ( !( $e instanceof DBError ) || $wgShowDBErrorBacktrace )
278 * @param Exception|Throwable $e
279 * @return string
281 private static function getShowBacktraceError( $e ) {
282 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
283 $vars = [];
284 if ( !$wgShowExceptionDetails ) {
285 $vars[] = '$wgShowExceptionDetails = true;';
287 if ( $e instanceof DBError && !$wgShowDBErrorBacktrace ) {
288 $vars[] = '$wgShowDBErrorBacktrace = true;';
290 $vars = implode( ' and ', $vars );
291 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information";
295 * @return bool
297 private static function isCommandLine() {
298 return !empty( $GLOBALS['wgCommandLineMode'] );
302 * @param string $header
304 private static function header( $header ) {
305 if ( !headers_sent() ) {
306 header( $header );
311 * @param integer $code
313 private static function statusHeader( $code ) {
314 if ( !headers_sent() ) {
315 HttpStatus::header( $code );
320 * Print a message, if possible to STDERR.
321 * Use this in command line mode only (see isCommandLine)
323 * @param string $message Failure text
325 private static function printError( $message ) {
326 // NOTE: STDERR may not be available, especially if php-cgi is used from the
327 // command line (bug #15602). Try to produce meaningful output anyway. Using
328 // echo may corrupt output to STDOUT though.
329 if ( defined( 'STDERR' ) ) {
330 fwrite( STDERR, $message );
331 } else {
332 echo $message;
337 * @param Exception|Throwable $e
339 private static function reportOutageHTML( $e ) {
340 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
342 $sorry = htmlspecialchars( self::msg(
343 'dberr-problems',
344 'Sorry! This site is experiencing technical difficulties.'
345 ) );
346 $again = htmlspecialchars( self::msg(
347 'dberr-again',
348 'Try waiting a few minutes and reloading.'
349 ) );
351 if ( $wgShowHostnames || $wgShowSQLErrors ) {
352 $info = str_replace(
353 '$1',
354 Html::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
355 htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
357 } else {
358 $info = htmlspecialchars( self::msg(
359 'dberr-info-hidden',
360 '(Cannot access the database)'
361 ) );
364 MessageCache::singleton()->disable(); // no DB access
366 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
368 if ( $wgShowDBErrorBacktrace ) {
369 $html .= '<p>Backtrace:</p><pre>' .
370 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
373 $html .= '<hr />';
374 $html .= self::googleSearchForm();
376 echo $html;
380 * @return string
382 private static function googleSearchForm() {
383 global $wgSitename, $wgCanonicalServer, $wgRequest;
385 $usegoogle = htmlspecialchars( self::msg(
386 'dberr-usegoogle',
387 'You can try searching via Google in the meantime.'
388 ) );
389 $outofdate = htmlspecialchars( self::msg(
390 'dberr-outofdate',
391 'Note that their indexes of our content may be out of date.'
392 ) );
393 $googlesearch = htmlspecialchars( self::msg( 'searchbutton', 'Search' ) );
394 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
395 $server = htmlspecialchars( $wgCanonicalServer );
396 $sitename = htmlspecialchars( $wgSitename );
397 $trygoogle = <<<EOT
398 <div style="margin: 1.5em">$usegoogle<br />
399 <small>$outofdate</small>
400 </div>
401 <form method="get" action="//www.google.com/search" id="googlesearch">
402 <input type="hidden" name="domains" value="$server" />
403 <input type="hidden" name="num" value="50" />
404 <input type="hidden" name="ie" value="UTF-8" />
405 <input type="hidden" name="oe" value="UTF-8" />
406 <input type="text" name="q" size="31" maxlength="255" value="$search" />
407 <input type="submit" name="btnG" value="$googlesearch" />
409 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
410 <label><input type="radio" name="sitesearch" value="" />WWW</label>
411 </p>
412 </form>
413 EOT;
414 return $trygoogle;