MediaWiki  1.33.0
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 ) {
52  } else {
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";
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" .
72  }
73  $message .= "\n";
74  } elseif ( $wgShowExceptionDetails ) {
76  "\nBacktrace:\n" .
78  } else {
80  }
81  echo nl2br( htmlspecialchars( $message ) ) . "\n";
82  }
83  }
84 
89  private static function useOutputPage( $e ) {
90  // Can the extension use the Message class/wfMessage to get i18n-ed messages?
91  foreach ( $e->getTrace() as $frame ) {
92  if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
93  return false;
94  }
95  }
96 
97  // Don't even bother with OutputPage if there's no Title context set,
98  // (e.g. we're in RL code on load.php) - the Skin system (and probably
99  // most of MediaWiki) won't work.
100 
101  return (
102  !empty( $GLOBALS['wgFullyInitialised'] ) &&
103  !empty( $GLOBALS['wgOut'] ) &&
104  RequestContext::getMain()->getTitle() &&
105  !defined( 'MEDIAWIKI_INSTALL' )
106  );
107  }
108 
114  private static function reportHTML( $e ) {
115  global $wgOut, $wgSitename;
116 
117  if ( self::useOutputPage( $e ) ) {
118  if ( $e instanceof MWException ) {
119  $wgOut->prepareErrorPage( $e->getPageTitle() );
120  } elseif ( $e instanceof DBReadOnlyError ) {
121  $wgOut->prepareErrorPage( self::msg( 'readonly', 'Database is locked' ) );
122  } elseif ( $e instanceof DBExpectedError ) {
123  $wgOut->prepareErrorPage( self::msg( 'databaseerror', 'Database error' ) );
124  } else {
125  $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
126  }
127 
128  // Show any custom GUI message before the details
129  if ( $e instanceof MessageSpecifier ) {
130  $wgOut->addHTML( Html::element( 'p', [], Message::newFromSpecifier( $e )->text() ) );
131  }
132  $wgOut->addHTML( self::getHTML( $e ) );
133 
134  $wgOut->output();
135  } else {
136  self::header( 'Content-Type: text/html; charset=utf-8' );
137  $pageTitle = self::msg( 'internalerror', 'Internal error' );
138  echo "<!DOCTYPE html>\n" .
139  '<html><head>' .
140  // Mimick OutputPage::setPageTitle behaviour
141  '<title>' .
142  htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
143  '</title>' .
144  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
145  "</head><body>\n";
146 
147  echo self::getHTML( $e );
148 
149  echo "</body></html>\n";
150  }
151  }
152 
161  public static function getHTML( $e ) {
163 
164  if ( $wgShowExceptionDetails ) {
165  $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
166  nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
167  '</p><p>Backtrace:</p><p>' .
168  nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
169  "</p></div>\n";
170  } else {
171  $logId = WebRequest::getRequestId();
172  $html = "<div class=\"errorbox mw-content-ltr\">" .
173  htmlspecialchars(
174  '[' . $logId . '] ' .
175  gmdate( 'Y-m-d H:i:s' ) . ": " .
176  self::msg( "internalerror-fatal-exception",
177  "Fatal exception of type $1",
178  get_class( $e ),
179  $logId,
181  ) ) . "</div>\n" .
182  "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
183  }
184 
185  return $html;
186  }
187 
197  private static function msg( $key, $fallback /*[, params...] */ ) {
198  global $wgSitename;
199  $args = array_slice( func_get_args(), 2 );
200 
201  // FIXME: Keep logic in sync with MWException::msg.
202  try {
203  $res = wfMessage( $key, $args )->text();
204  } catch ( Exception $e ) {
206  // If an exception happens inside message rendering,
207  // {{SITENAME}} sometimes won't be replaced.
208  $res = strtr( $res, [
209  '{{SITENAME}}' => $wgSitename,
210  ] );
211  }
212  return $res;
213  }
214 
219  private static function getText( $e ) {
221 
222  if ( $wgShowExceptionDetails ) {
224  "\nBacktrace:\n" .
226  } else {
227  return self::getShowBacktraceError( $e ) . "\n";
228  }
229  }
230 
235  private static function getShowBacktraceError( $e ) {
236  $var = '$wgShowExceptionDetails = true;';
237  return "Set $var at the bottom of LocalSettings.php to show detailed debugging information.";
238  }
239 
243  private static function isCommandLine() {
244  return !empty( $GLOBALS['wgCommandLineMode'] );
245  }
246 
250  private static function header( $header ) {
251  if ( !headers_sent() ) {
252  header( $header );
253  }
254  }
255 
259  private static function statusHeader( $code ) {
260  if ( !headers_sent() ) {
262  }
263  }
264 
272  private static function printError( $message ) {
273  // NOTE: STDERR may not be available, especially if php-cgi is used from the
274  // command line (T17602). Try to produce meaningful output anyway. Using
275  // echo may corrupt output to STDOUT though.
276  if ( defined( 'STDERR' ) ) {
277  fwrite( STDERR, $message );
278  } else {
279  echo $message;
280  }
281  }
282 
286  private static function reportOutageHTML( $e ) {
288 
289  $sorry = htmlspecialchars( self::msg(
290  'dberr-problems',
291  'Sorry! This site is experiencing technical difficulties.'
292  ) );
293  $again = htmlspecialchars( self::msg(
294  'dberr-again',
295  'Try waiting a few minutes and reloading.'
296  ) );
297 
298  if ( $wgShowHostnames ) {
299  $info = str_replace(
300  '$1',
301  Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
302  htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
303  );
304  } else {
305  $info = htmlspecialchars( self::msg(
306  'dberr-info-hidden',
307  '(Cannot access the database)'
308  ) );
309  }
310 
311  MessageCache::singleton()->disable(); // no DB access
312  $html = "<!DOCTYPE html>\n" .
313  '<html><head>' .
314  '<title>' .
315  htmlspecialchars( $wgSitename ) .
316  '</title>' .
317  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
318  "</head><body><h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
319 
320  if ( $wgShowExceptionDetails ) {
321  $html .= '<p>Backtrace:</p><pre>' .
322  htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
323  }
324 
325  $html .= '</body></html>';
326  echo $html;
327  }
328 }
$wgMimeType
$wgMimeType
The default Content-Type header.
Definition: DefaultSettings.php:3207
$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:6316
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1325
$res
$res
Definition: database.txt:21
MWExceptionRenderer\reportOutageHTML
static reportOutageHTML( $e)
Definition: MWExceptionRenderer.php:286
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:520
$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:1985
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:472
MWExceptionHandler\getLogMessage
static getLogMessage( $e)
Get a message formatting the exception message and its origin.
Definition: MWExceptionHandler.php:487
MWExceptionRenderer\isCommandLine
static isCommandLine()
Definition: MWExceptionRenderer.php:243
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
$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 When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
MWExceptionRenderer\AS_PRETTY
const AS_PRETTY
Definition: MWExceptionRenderer.php:31
Wikimedia\Rdbms\DBReadOnlyError
Definition: DBReadOnlyError.php:27
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:114
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
$header
$header
Definition: updateCredits.php:41
MWExceptionRenderer\useOutputPage
static useOutputPage( $e)
Definition: MWExceptionRenderer.php:89
MWExceptionRenderer\header
static header( $header)
Definition: MWExceptionRenderer.php:250
$wgSitename
$wgSitename
Name of the site.
Definition: DefaultSettings.php:80
MWExceptionRenderer\msg
static msg( $key, $fallback)
Get a message from i18n.
Definition: MWExceptionRenderer.php:197
MWExceptionRenderer\printError
static printError( $message)
Print a message, if possible to STDERR.
Definition: MWExceptionRenderer.php:272
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
MWExceptionRenderer\output
static output( $e, $mode, $eNew=null)
Definition: MWExceptionRenderer.php:38
text
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
Definition: All_system_messages.txt:1267
$args
if( $line===false) $args
Definition: cdb.php:64
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1685
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
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:275
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
Definition: DefaultSettings.php:6288
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:259
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:161
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:114
$wgOut
$wgOut
Definition: Setup.php:880
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 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
MWExceptionRenderer
Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
Definition: MWExceptionRenderer.php:29
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:381
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
MWExceptionRenderer\getText
static getText( $e)
Definition: MWExceptionRenderer.php:219
MWExceptionRenderer\getShowBacktraceError
static getShowBacktraceError( $e)
Definition: MWExceptionRenderer.php:235
MWExceptionRenderer\AS_RAW
const AS_RAW
Definition: MWExceptionRenderer.php:30