MediaWiki  master
MWExceptionRenderer.php
Go to the documentation of this file.
1 <?php
24 
30  const AS_RAW = 1; // show as text
31  const AS_PRETTY = 2; // show as HTML
32 
38  public static function output( $e, $mode, $eNew = null ) {
40 
41  if ( defined( 'MW_API' ) ) {
42  // Unhandled API exception, we can't be sure that format printer is alive
43  self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
44  wfHttpError( 500, 'Internal Server Error', self::getText( $e ) );
45  } elseif ( self::isCommandLine() ) {
46  self::printError( self::getText( $e ) );
47  } elseif ( $mode === self::AS_PRETTY ) {
48  self::statusHeader( 500 );
49  self::header( "Content-Type: $wgMimeType; charset=utf-8" );
50  if ( $e instanceof DBConnectionError ) {
51  self::reportOutageHTML( $e );
52  } else {
53  self::reportHTML( $e );
54  }
55  } else {
56  self::statusHeader( 500 );
57  self::header( "Content-Type: $wgMimeType; charset=utf-8" );
58  if ( $eNew ) {
59  $message = "MediaWiki internal error.\n\n";
60  if ( $wgShowExceptionDetails ) {
61  $message .= 'Original exception: ' .
63  "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
64  "\n\nException caught inside exception handler: " .
66  "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
67  } else {
68  $message .= 'Original exception: ' .
70  $message .= "\n\nException caught inside exception handler.\n\n" .
71  self::getShowBacktraceError( $e );
72  }
73  $message .= "\n";
74  } else {
75  if ( $wgShowExceptionDetails ) {
77  "\nBacktrace:\n" .
79  } else {
81  }
82  }
83  echo nl2br( htmlspecialchars( $message ) ) . "\n";
84  }
85  }
86 
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::class ) {
95  return false;
96  }
97  }
98 
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.
102 
103  return (
104  !empty( $GLOBALS['wgFullyInitialised'] ) &&
105  !empty( $GLOBALS['wgOut'] ) &&
106  RequestContext::getMain()->getTitle() &&
107  !defined( 'MEDIAWIKI_INSTALL' )
108  );
109  }
110 
116  private static function reportHTML( $e ) {
117  global $wgOut, $wgSitename;
118 
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' ) );
126  } else {
127  $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
128  }
129 
130  // Show any custom GUI message before the details
131  if ( $e instanceof MessageSpecifier ) {
132  $wgOut->addHTML( Html::element( 'p', [], Message::newFromSpecifier( $e )->text() ) );
133  }
134  $wgOut->addHTML( self::getHTML( $e ) );
135 
136  $wgOut->output();
137  } else {
138  self::header( 'Content-Type: text/html; charset=utf-8' );
139  $pageTitle = self::msg( 'internalerror', 'Internal error' );
140  echo "<!DOCTYPE html>\n" .
141  '<html><head>' .
142  // Mimick OutputPage::setPageTitle behaviour
143  '<title>' .
144  htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
145  '</title>' .
146  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
147  "</head><body>\n";
148 
149  echo self::getHTML( $e );
150 
151  echo "</body></html>\n";
152  }
153  }
154 
163  public static function getHTML( $e ) {
165 
166  if ( $wgShowExceptionDetails ) {
167  $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
168  nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
169  '</p><p>Backtrace:</p><p>' .
170  nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
171  "</p></div>\n";
172  } else {
173  $logId = WebRequest::getRequestId();
174  $html = "<div class=\"errorbox mw-content-ltr\">" .
175  htmlspecialchars(
176  '[' . $logId . '] ' .
177  gmdate( 'Y-m-d H:i:s' ) . ": " .
178  self::msg( "internalerror-fatal-exception",
179  "Fatal exception of type $1",
180  get_class( $e ),
181  $logId,
183  ) ) . "</div>\n" .
184  "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
185  }
186 
187  return $html;
188  }
189 
199  private static function msg( $key, $fallback /*[, params...] */ ) {
200  global $wgSitename;
201  $args = array_slice( func_get_args(), 2 );
202 
203  // FIXME: Keep logic in sync with MWException::msg.
204  try {
205  $res = wfMessage( $key, $args )->text();
206  } catch ( Exception $e ) {
208  // If an exception happens inside message rendering,
209  // {{SITENAME}} sometimes won't be replaced.
210  $res = strtr( $res, [
211  '{{SITENAME}}' => $wgSitename,
212  ] );
213  }
214  return $res;
215  }
216 
221  private static function getText( $e ) {
223 
224  if ( $wgShowExceptionDetails ) {
226  "\nBacktrace:\n" .
228  } else {
229  return self::getShowBacktraceError( $e ) . "\n";
230  }
231  }
232 
237  private static function getShowBacktraceError( $e ) {
238  $var = '$wgShowExceptionDetails = true;';
239  return "Set $var at the bottom of LocalSettings.php to show detailed debugging information.";
240  }
241 
245  private static function isCommandLine() {
246  return !empty( $GLOBALS['wgCommandLineMode'] );
247  }
248 
252  private static function header( $header ) {
253  if ( !headers_sent() ) {
254  header( $header );
255  }
256  }
257 
261  private static function statusHeader( $code ) {
262  if ( !headers_sent() ) {
264  }
265  }
266 
273  private static function printError( $message ) {
274  // NOTE: STDERR may not be available, especially if php-cgi is used from the
275  // command line (T17602). Try to produce meaningful output anyway. Using
276  // echo may corrupt output to STDOUT though.
277  if ( defined( 'STDERR' ) ) {
278  fwrite( STDERR, $message );
279  } else {
280  echo $message;
281  }
282  }
283 
287  private static function reportOutageHTML( $e ) {
289 
290  $sorry = htmlspecialchars( self::msg(
291  'dberr-problems',
292  'Sorry! This site is experiencing technical difficulties.'
293  ) );
294  $again = htmlspecialchars( self::msg(
295  'dberr-again',
296  'Try waiting a few minutes and reloading.'
297  ) );
298 
299  if ( $wgShowHostnames ) {
300  $info = str_replace(
301  '$1',
302  Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
303  htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
304  );
305  } else {
306  $info = htmlspecialchars( self::msg(
307  'dberr-info-hidden',
308  '(Cannot access the database)'
309  ) );
310  }
311 
312  MessageCache::singleton()->disable(); // no DB access
313  $html = "<!DOCTYPE html>\n" .
314  '<html><head>' .
315  '<title>' .
316  htmlspecialchars( $wgSitename ) .
317  '</title>' .
318  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
319  "</head><body><h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
320 
321  if ( $wgShowExceptionDetails ) {
322  $html .= '<p>Backtrace:</p><pre>' .
323  htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
324  }
325 
326  $html .= '</body></html>';
327  echo $html;
328  }
329 }
static getLogMessage( $e)
Get a message formatting the exception message and its origin.
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:1996
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:232
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:275
$wgSitename
Name of the site.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2173
$wgMimeType
The default Content-Type header.
Class to expose exceptions to the client (API bots, users, admins using CLI scripts) ...
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
if( $line===false) $args
Definition: cdb.php:64
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 use $formDescriptor instead 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
static getMain()
Get the RequestContext object associated with the main request.
static getRedactedTraceAsString( $e)
Generate a string representation of an exception&#39;s stack trace.
$res
Definition: database.txt:21
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
static getURL()
If the exception occurred in the course of responding to a request, returns the requested URL...
$GLOBALS['IP']
$header
static msg( $key, $fallback)
Get a message from i18n.
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:785
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
static output( $e, $mode, $eNew=null)
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
$fallback
Definition: MessagesAb.php:11
static getHTML( $e)
If $wgShowExceptionDetails is true, return a HTML message with a backtrace to the error...
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:428
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
static reportHTML( $e)
Output the exception report using HTML.
$wgOut
Definition: Setup.php:907
static getPublicLogMessage( $e)
static singleton()
Get the signleton instance of this class.
Base class for the more common types of database errors.
static printError( $message)
Print a message, if possible to STDERR.
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.