MediaWiki  1.31.0
MWExceptionRenderer.php
Go to the documentation of this file.
1 <?php
25 
31  const AS_RAW = 1; // show as text
32  const AS_PRETTY = 2; // show as HTML
33 
39  public static function output( $e, $mode, $eNew = null ) {
41 
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 ) {
52  } else {
53  self::header( "Content-Type: $wgMimeType; charset=utf-8" );
55  }
56  } else {
57  if ( $eNew ) {
58  $message = "MediaWiki internal error.\n\n";
59  if ( self::showBackTrace( $e ) ) {
60  $message .= 'Original exception: ' .
62  "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
63  "\n\nException caught inside exception handler: " .
65  "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
66  } else {
67  $message .= 'Original exception: ' .
69  $message .= "\n\nException caught inside exception handler.\n\n" .
71  }
72  $message .= "\n";
73  } else {
74  if ( self::showBackTrace( $e ) ) {
76  "\nBacktrace:\n" .
78  } else {
80  }
81  }
82  echo nl2br( htmlspecialchars( $message ) ) . "\n";
83  }
84  }
85 
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::class ) {
94  return false;
95  }
96  }
97 
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.
101 
102  return (
103  !empty( $GLOBALS['wgFullyInitialised'] ) &&
104  !empty( $GLOBALS['wgOut'] ) &&
105  RequestContext::getMain()->getTitle() &&
106  !defined( 'MEDIAWIKI_INSTALL' )
107  );
108  }
109 
115  private static function reportHTML( $e ) {
117 
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' ) );
125  } else {
126  $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
127  }
128 
129  // Show any custom GUI message before the details
130  if ( $e instanceof MessageSpecifier ) {
131  $wgOut->addHTML( Html::element( 'p', [], Message::newFromSpecifier( $e )->text() ) );
132  }
133  $wgOut->addHTML( self::getHTML( $e ) );
134 
135  $wgOut->output();
136  } else {
137  self::header( 'Content-Type: text/html; charset=utf-8' );
138  $pageTitle = self::msg( 'internalerror', 'Internal error' );
139  echo "<!DOCTYPE html>\n" .
140  '<html><head>' .
141  // Mimick OutputPage::setPageTitle behaviour
142  '<title>' .
143  htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
144  '</title>' .
145  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
146  "</head><body>\n";
147 
148  echo self::getHTML( $e );
149 
150  echo "</body></html>\n";
151  }
152  }
153 
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 ) ) ) .
168  "</p></div>\n";
169  } else {
170  $logId = WebRequest::getRequestId();
171  $html = "<div class=\"errorbox mw-content-ltr\">" .
172  htmlspecialchars(
173  '[' . $logId . '] ' .
174  gmdate( 'Y-m-d H:i:s' ) . ": " .
175  self::msg( "internalerror-fatal-exception",
176  "Fatal exception of type $1",
177  get_class( $e ),
178  $logId,
180  ) ) . "</div>\n" .
181  "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
182  }
183 
184  return $html;
185  }
186 
196  private static function msg( $key, $fallback /*[, params...] */ ) {
197  $args = array_slice( func_get_args(), 2 );
198  try {
199  return wfMessage( $key, $args )->text();
200  } catch ( Exception $e ) {
201  return wfMsgReplaceArgs( $fallback, $args );
202  }
203  }
204 
209  private static function getText( $e ) {
210  if ( self::showBackTrace( $e ) ) {
212  "\nBacktrace:\n" .
214  } else {
215  return self::getShowBacktraceError( $e ) . "\n";
216  }
217  }
218 
223  private static function showBackTrace( $e ) {
225 
226  return (
228  ( !( $e instanceof DBError ) || $wgShowDBErrorBacktrace )
229  );
230  }
231 
236  private static function getShowBacktraceError( $e ) {
238  $vars = [];
239  if ( !$wgShowExceptionDetails ) {
240  $vars[] = '$wgShowExceptionDetails = true;';
241  }
242  if ( $e instanceof DBError && !$wgShowDBErrorBacktrace ) {
243  $vars[] = '$wgShowDBErrorBacktrace = true;';
244  }
245  $vars = implode( ' and ', $vars );
246  return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information.";
247  }
248 
252  private static function isCommandLine() {
253  return !empty( $GLOBALS['wgCommandLineMode'] );
254  }
255 
259  private static function header( $header ) {
260  if ( !headers_sent() ) {
261  header( $header );
262  }
263  }
264 
268  private static function statusHeader( $code ) {
269  if ( !headers_sent() ) {
271  }
272  }
273 
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 );
286  } else {
287  echo $message;
288  }
289  }
290 
294  private static function reportOutageHTML( $e ) {
296 
297  $sorry = htmlspecialchars( self::msg(
298  'dberr-problems',
299  'Sorry! This site is experiencing technical difficulties.'
300  ) );
301  $again = htmlspecialchars( self::msg(
302  'dberr-again',
303  'Try waiting a few minutes and reloading.'
304  ) );
305 
307  $info = str_replace(
308  '$1',
309  Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
310  htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
311  );
312  } else {
313  $info = htmlspecialchars( self::msg(
314  'dberr-info-hidden',
315  '(Cannot access the database)'
316  ) );
317  }
318 
319  MessageCache::singleton()->disable(); // no DB access
320 
321  $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
322 
323  if ( $wgShowDBErrorBacktrace ) {
324  $html .= '<p>Backtrace:</p><pre>' .
325  htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
326  }
327 
328  $html .= '<hr />';
330 
331  echo $html;
332  }
333 
337  private static function googleSearchForm() {
339 
340  $usegoogle = htmlspecialchars( self::msg(
341  'dberr-usegoogle',
342  'You can try searching via Google in the meantime.'
343  ) );
344  $outofdate = htmlspecialchars( self::msg(
345  'dberr-outofdate',
346  'Note that their indexes of our content may be out of date.'
347  ) );
348  $googlesearch = htmlspecialchars( self::msg( 'searchbutton', 'Search' ) );
349  $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
350  $server = htmlspecialchars( $wgCanonicalServer );
351  $sitename = htmlspecialchars( $wgSitename );
352  $trygoogle = <<<EOT
353 <div style="margin: 1.5em">$usegoogle<br />
354 <small>$outofdate</small>
355 </div>
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" />
363  <p>
364  <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
365  <label><input type="radio" name="sitesearch" value="" />WWW</label>
366  </p>
367 </form>
368 EOT;
369  return $trygoogle;
370  }
371 }
$wgShowSQLErrors
$wgShowSQLErrors
Whether to show "we're sorry, but there has been a database error" pages.
Definition: DefaultSettings.php:6240
$wgMimeType
$wgMimeType
The default Content-Type header.
Definition: DefaultSettings.php:3159
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
$fallback
$fallback
Definition: MessagesAb.php:11
MessageSpecifier
Definition: MessageSpecifier.php:21
$wgShowHostnames
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
Definition: DefaultSettings.php:6274
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1381
value
if( $inline) $status value
Definition: SyntaxHighlight.php:349
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
MWExceptionRenderer\reportOutageHTML
static reportOutageHTML( $e)
Definition: MWExceptionRenderer.php:294
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
MWExceptionHandler\getPublicLogMessage
static getPublicLogMessage( $e)
Definition: MWExceptionHandler.php:498
$html
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1987
MWException
MediaWiki exception.
Definition: MWException.php:26
MWExceptionHandler\getURL
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL.
Definition: MWExceptionHandler.php:450
MWExceptionHandler\getLogMessage
static getLogMessage( $e)
Get a message formatting the exception message and its origin.
Definition: MWExceptionHandler.php:465
MWExceptionRenderer\isCommandLine
static isCommandLine()
Definition: MWExceptionRenderer.php:252
div
div
Definition: parserTests.txt:6588
form
null means default in associative array form
Definition: hooks.txt:1987
MWExceptionRenderer\AS_PRETTY
const AS_PRETTY
Definition: MWExceptionRenderer.php:32
MWExceptionRenderer\showBackTrace
static showBackTrace( $e)
Definition: MWExceptionRenderer.php:223
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2220
Wikimedia\Rdbms\DBReadOnlyError
Definition: DBReadOnlyError.php:27
$wgShowDBErrorBacktrace
$wgShowDBErrorBacktrace
If true, show a backtrace for database errors.
Definition: DefaultSettings.php:6258
$wgCanonicalServer
$wgCanonicalServer
Canonical URL of the server, to use in IRC feeds and notification e-mails.
Definition: DefaultSettings.php:114
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:113
captcha-old.action
action
Definition: captcha-old.py:212
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2163
$header
$header
Definition: updateCredits.php:35
MWExceptionRenderer\useOutputPage
static useOutputPage( $e)
Definition: MWExceptionRenderer.php:90
MWExceptionRenderer\header
static header( $header)
Definition: MWExceptionRenderer.php:259
$wgSitename
$wgSitename
Name of the site.
Definition: DefaultSettings.php:79
MWExceptionRenderer\msg
static msg( $key, $fallback)
Get a message from i18n.
Definition: MWExceptionRenderer.php:196
MWExceptionRenderer\googleSearchForm
static googleSearchForm()
Definition: MWExceptionRenderer.php:337
captcha-old.p
p
Definition: captcha-old.py:275
MWExceptionRenderer\printError
static printError( $message)
Print a message, if possible to STDERR.
Definition: MWExceptionRenderer.php:280
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:434
style
Bar style
Definition: parserTests.txt:192
MWExceptionRenderer\output
static output( $e, $mode, $eNew=null)
Definition: MWExceptionRenderer.php:39
$args
if( $line===false) $args
Definition: cdb.php:64
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1739
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
Wikimedia\Rdbms\DBExpectedError
Base class for the more common types of database errors.
Definition: DBExpectedError.php:32
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:783
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:271
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print a complete stack trace to output.
Definition: DefaultSettings.php:6248
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MWExceptionRenderer\statusHeader
static statusHeader( $code)
Definition: MWExceptionRenderer.php:268
Wikimedia\Rdbms\DBConnectionError
Definition: DBConnectionError.php:26
MWExceptionRenderer\getHTML
static getHTML( $e)
If $wgShowExceptionDetails is true, return a HTML message with a backtrace to the error,...
Definition: MWExceptionRenderer.php:162
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
name
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
Definition: design.txt:12
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
MWExceptionRenderer\reportHTML
static reportHTML( $e)
Output the exception report using HTML.
Definition: MWExceptionRenderer.php:115
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:737
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
$wgOut
$wgOut
Definition: Setup.php:904
MWExceptionRenderer
Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
Definition: MWExceptionRenderer.php:30
type
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:343
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
MWExceptionRenderer\getText
static getText( $e)
Definition: MWExceptionRenderer.php:209
MWExceptionRenderer\getShowBacktraceError
static getShowBacktraceError( $e)
Definition: MWExceptionRenderer.php:236
MWExceptionRenderer\AS_RAW
const AS_RAW
Definition: MWExceptionRenderer.php:31