Debian Codegraph @

includes/exception/MWExceptionRenderer.php

raw symbols SCIP
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use MediaWiki\Context\RequestContext;
22 use MediaWiki\Html\Html;
23 use MediaWiki\Language\RawMessage;
24 use MediaWiki\MainConfigNames;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Message\Message;
27 use MediaWiki\Request\WebRequest;
28 use Wikimedia\AtEase;
29 use Wikimedia\Message\MessageSpecifier;
30 use Wikimedia\Rdbms\DBConnectionError;
31 use Wikimedia\Rdbms\DBExpectedError;
32 use Wikimedia\Rdbms\DBReadOnlyError;
33 use Wikimedia\RequestTimeout\RequestTimeoutException;
34
35 /**
36 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
37 * @since 1.28
38 */
39 class MWExceptionRenderer {
40 public const AS_RAW = 1; // show as text
41 public const AS_PRETTY = 2; // show as HTML
42
43 /**
44 * Whether to print exception details.
45 *
46 * The default is configured by $wgShowExceptionDetails.
47 * May be changed at runtime via MWExceptionRenderer::setShowExceptionDetails().
48 *
49 * @see MainConfigNames::ShowExceptionDetails
50 * @var bool
51 */
52 private static $showExceptionDetails = false;
53
54 /**
55 * @internal For use within core wiring only.
56 * @return bool
57 */
58 public static function shouldShowExceptionDetails(): bool {
59 return self::$showExceptionDetails;
60 }
61
62 /**
63 * @param bool $showDetails
64 * @internal For use by Setup.php and other internal use cases.
65 */
66 public static function setShowExceptionDetails( bool $showDetails ): void {
67 self::$showExceptionDetails = $showDetails;
68 }
69
70 /**
71 * @param Throwable $e Original exception
72 * @param int $mode MWExceptionExposer::AS_* constant
73 * @param Throwable|null $eNew New throwable from attempting to show the first
74 */
75 public static function output( Throwable $e, $mode, ?Throwable $eNew = null ) {
76 $showExceptionDetails = self::shouldShowExceptionDetails();
77 if ( $e instanceof RequestTimeoutException && headers_sent() ) {
78 // Excimer's flag check happens on function return, so, a timeout
79 // can be thrown after exiting, say, `doPostOutputShutdown`, where
80 // headers are sent. In which case, it's probably fine not to
81 // report this in any user visible way. The general question of
82 // what to do about reporting an exception when headers have been
83 // sent is still unclear, but you probably don't want to
84 // `useOutputPage`.
85 return;
86 }
87
88 if ( function_exists( 'apache_setenv' ) ) {
89 // The client should not be blocked on "post-send" updates. If apache decides that
90 // a response should be gzipped, it will wait for PHP to finish since it cannot gzip
91 // anything until it has the full response (even with "Transfer-Encoding: chunked").
92 AtEase\AtEase::suppressWarnings();
93 apache_setenv( 'no-gzip', '1' );
94 AtEase\AtEase::restoreWarnings();
95 }
96
97 if ( defined( 'MW_API' ) ) {
98 self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
99 }
100
101 if ( self::isCommandLine() ) {
102 self::printError( self::getText( $e ) );
103 } elseif ( $mode === self::AS_PRETTY ) {
104 self::statusHeader( 500 );
105 ob_start();
106 if ( $e instanceof DBConnectionError ) {
107 self::reportOutageHTML( $e );
108 } else {
109 self::reportHTML( $e );
110 }
111 self::header( "Content-Length: " . ob_get_length() );
112 ob_end_flush();
113 } else {
114 ob_start();
115 self::statusHeader( 500 );
116 self::header( 'Content-Type: text/html; charset=UTF-8' );
117 if ( $eNew ) {
118 $message = "MediaWiki internal error.\n\n";
119 if ( $showExceptionDetails ) {
120 $message .= 'Original exception: ' .
121 MWExceptionHandler::getLogMessage( $e ) .
122 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
123 "\n\nException caught inside exception handler: " .
124 MWExceptionHandler::getLogMessage( $eNew ) .
125 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
126 } else {
127 $message .= 'Original exception: ' .
128 MWExceptionHandler::getPublicLogMessage( $e );
129 $message .= "\n\nException caught inside exception handler.\n\n" .
130 self::getShowBacktraceError();
131 }
132 $message .= "\n";
133 } elseif ( $showExceptionDetails ) {
134 $message = MWExceptionHandler::getLogMessage( $e ) .
135 "\nBacktrace:\n" .
136 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
137 } else {
138 $message = MWExceptionHandler::getPublicLogMessage( $e );
139 }
140 print nl2br( htmlspecialchars( $message ) ) . "\n";
141 self::header( "Content-Length: " . ob_get_length() );
142 ob_end_flush();
143 }
144 }
145
146 /**
147 * @param Throwable $e
148 * @return bool Should the throwable use $wgOut to output the error?
149 */
150 private static function useOutputPage( Throwable $e ) {
151 // Can the exception use the Message class/wfMessage to get i18n-ed messages?
152 foreach ( $e->getTrace() as $frame ) {
153 if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
154 return false;
155 }
156 }
157
158 // Don't even bother with OutputPage if there's no Title context set,
159 // (e.g. we're in RL code on load.php) - the Skin system (and probably
160 // most of MediaWiki) won't work.
161 return (
162 !empty( $GLOBALS['wgFullyInitialised'] ) &&
163 !empty( $GLOBALS['wgOut'] ) &&
164 RequestContext::getMain()->getTitle() &&
165 !defined( 'MEDIAWIKI_INSTALL' ) &&
166 // Don't send a skinned HTTP 500 page to API clients.
167 !defined( 'MW_API' ) &&
168 !defined( 'MW_REST_API' )
169 );
170 }
171
172 /**
173 * Output the throwable report using HTML
174 *
175 * @param Throwable $e
176 */
177 private static function reportHTML( Throwable $e ) {
178 if ( self::useOutputPage( $e ) ) {
179 $out = RequestContext::getMain()->getOutput();
180 $out->prepareErrorPage();
181 $out->setPageTitleMsg( self::getExceptionTitle( $e ) );
182
183 // Show any custom GUI message before the details
184 $customMessage = self::getCustomMessage( $e );
185 if ( $customMessage !== null ) {
186 $out->addHTML( Html::element( 'p', [], $customMessage ) );
187 }
188 $out->addHTML( self::getHTML( $e ) );
189 // Content-Type is set by OutputPage::output
190 $out->output();
191 } else {
192 self::header( 'Content-Type: text/html; charset=UTF-8' );
193 $pageTitle = self::msg( 'internalerror', 'Internal error' );
194 echo "<!DOCTYPE html>\n" .
195 '<html><head>' .
196 // Mimic OutputPage::setPageTitle behaviour
197 '<title>' .
198 htmlspecialchars( self::msg( 'pagetitle', '$1 - MediaWiki', $pageTitle ) ) .
199 '</title>' .
200 '<meta name="color-scheme" content="light dark" />' .
201 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
202 "</head><body>\n";
203
204 echo self::getHTML( $e );
205
206 echo "</body></html>\n";
207 }
208 }
209
210 /**
211 * Format an HTML message for the given exception object.
212 *
213 * @param Throwable $e
214 * @return string Html to output
215 */
216 public static function getHTML( Throwable $e ) {
217 if ( self::shouldShowExceptionDetails() ) {
218 $html = '<div dir=ltr>' . Html::errorBox( "<p>" .
219 nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
220 '</p><p>Backtrace:</p><p>' .
221 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
222 "</p>\n"
223 ) . '</div>';
224 } else {
225 $logId = WebRequest::getRequestId();
226 $html = Html::errorBox(
227 htmlspecialchars(
228 '[' . $logId . '] ' .
229 gmdate( 'Y-m-d H:i:s' ) . ": " .
230 self::msg( "internalerror-fatal-exception",
231 "Fatal exception of type $1",
232 get_class( $e ),
233 $logId,
234 MWExceptionHandler::getURL()
235 ) )
236 ) . "<!-- " . wordwrap( self::getShowBacktraceError(), 50 ) . " -->";
237 }
238
239 return $html;
240 }
241
242 /**
243 * Get a message string from i18n
244 *
245 * @param string $key Message name
246 * @param string $fallback Default message if the message cache can't be
247 * called by the exception
248 * @param mixed ...$params To pass to wfMessage()
249 * @return string Message with arguments replaced
250 */
251 public static function msg( $key, $fallback, ...$params ) {
252 // NOTE: Keep logic in sync with MWException::msg
253 $res = self::msgObj( $key, $fallback, ...$params )->text();
254 return strtr( $res, [
255 '{{SITENAME}}' => 'MediaWiki',
256 ] );
257 }
258
259 /** Get a Message object from i18n.
260 *
261 * @param string $key Message name
262 * @param string $fallback Default message if the message cache can't be
263 * called by the exception
264 * @param mixed ...$params To pass to wfMessage()
265 * @return Message|RawMessage
266 */
267 private static function msgObj( string $key, string $fallback, ...$params ): Message {
268 // NOTE: Keep logic in sync with MWException::msg.
269 try {
270 $res = wfMessage( $key, ...$params );
271 } catch ( Exception $e ) {
272 // Fallback to static message text and generic sitename.
273 // Avoid live config as this must work before Setup/MediaWikiServices finish.
274 $res = new RawMessage( $fallback, $params );
275 }
276 // We are in an error state, best to minimize how much work we do.
277 $res->useDatabase( false );
278 $isSafeToLoad = RequestContext::getMain()->getUser()->isSafeToLoad();
279 if ( !$isSafeToLoad ) {
280 $res->inContentLanguage();
281 }
282 return $res;
283 }
284
285 /**
286 * @param Throwable $e
287 * @return string
288 */
289 private static function getText( Throwable $e ) {
290 // XXX: do we need a parameter to control inclusion of exception details?
291 if ( self::shouldShowExceptionDetails() ) {
292 return MWExceptionHandler::getLogMessage( $e ) .
293 "\nBacktrace:\n" .
294 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
295 } else {
296 return self::getShowBacktraceError() . "\n";
297 }
298 }
299
300 /**
301 * @return string
302 */
303 private static function getShowBacktraceError() {
304 $var = '$wgShowExceptionDetails = true;';
305 return "Set $var at the bottom of LocalSettings.php to show detailed debugging information.";
306 }
307
308 /**
309 * Get the page title to be used for a given exception.
310 *
311 * @param Throwable $e
312 * @return Message
313 */
314 private static function getExceptionTitle( Throwable $e ): Message {
315 if ( $e instanceof DBReadOnlyError ) {
316 return self::msgObj( 'readonly', 'Database is locked' );
317 } elseif ( $e instanceof DBExpectedError ) {
318 return self::msgObj( 'databaseerror', 'Database error' );
319 } elseif ( $e instanceof RequestTimeoutException ) {
320 return self::msgObj( 'timeouterror', 'Request timeout' );
321 } else {
322 return self::msgObj( 'internalerror', 'Internal error' );
323 }
324 }
325
326 /**
327 * Extract an additional user-visible message from an exception, or null if
328 * it has none.
329 *
330 * @param Throwable $e
331 * @return string|null
332 */
333 private static function getCustomMessage( Throwable $e ) {
334 try {
335 if ( $e instanceof MessageSpecifier ) {
336 $msg = Message::newFromSpecifier( $e );
337 } elseif ( $e instanceof RequestTimeoutException ) {
338 $msg = wfMessage( 'timeouterror-text', $e->getLimit() );
339 } else {
340 return null;
341 }
342 $text = $msg->text();
343 } catch ( Exception $e2 ) {
344 return null;
345 }
346 return $text;
347 }
348
349 /**
350 * @return bool
351 */
352 private static function isCommandLine() {
353 return MW_ENTRY_POINT === 'cli';
354 }
355
356 /**
357 * @param string $header
358 */
359 private static function header( $header ) {
360 if ( !headers_sent() ) {
361 header( $header );
362 }
363 }
364
365 /**
366 * @param int $code
367 */
368 private static function statusHeader( $code ) {
369 if ( !headers_sent() ) {
370 HttpStatus::header( $code );
371 }
372 }
373
374 /**
375 * Print a message, if possible to STDERR.
376 * Use this in command line mode only (see isCommandLine)
377 *
378 * @suppress SecurityCheck-XSS
379 * @param string $message Failure text
380 */
381 private static function printError( $message ) {
382 // NOTE: STDERR may not be available, especially if php-cgi is used from the
383 // command line (T17602). Try to produce meaningful output anyway. Using
384 // echo may corrupt output to STDOUT though.
385 if ( !defined( 'MW_PHPUNIT_TEST' ) && defined( 'STDERR' ) ) {
386 fwrite( STDERR, $message );
387 } else {
388 echo $message;
389 }
390 }
391
392 /**
393 * @param Throwable $e
394 */
395 private static function reportOutageHTML( Throwable $e ) {
396 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
397 $showExceptionDetails = $mainConfig->get( MainConfigNames::ShowExceptionDetails );
398 $showHostnames = $mainConfig->get( MainConfigNames::ShowHostnames );
399 $sorry = htmlspecialchars( self::msg(
400 'dberr-problems',
401 'Sorry! This site is experiencing technical difficulties.'
402 ) );
403 $again = htmlspecialchars( self::msg(
404 'dberr-again',
405 'Try waiting a few minutes and reloading.'
406 ) );
407
408 if ( $showHostnames ) {
409 $info = str_replace(
410 '$1',
411 Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
412 htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
413 );
414 } else {
415 $info = htmlspecialchars( self::msg(
416 'dberr-info-hidden',
417 '(Cannot access the database)'
418 ) );
419 }
420
421 MediaWikiServices::getInstance()->getMessageCache()->disable(); // no DB access
422 $html = "<!DOCTYPE html>\n" .
423 '<html><head>' .
424 '<title>MediaWiki</title>' .
425 '<meta name="color-scheme" content="light dark" />' .
426 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
427 "</head><body><h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
428
429 if ( $showExceptionDetails ) {
430 $html .= '<p>Backtrace:</p><pre>' .
431 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
432 }
433
434 $html .= '</body></html>';
435 self::header( 'Content-Type: text/html; charset=UTF-8' );
436 echo $html;
437 }
438 }