MediaWiki  REL1_31
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  self::header( "Content-Type: $wgMimeType; charset=utf-8" );
51  if ( $e instanceof DBConnectionError ) {
53  } else {
55  }
56  } else {
57  self::statusHeader( 500 );
58  self::header( "Content-Type: $wgMimeType; charset=utf-8" );
59  if ( $eNew ) {
60  $message = "MediaWiki internal error.\n\n";
61  if ( self::showBackTrace( $e ) ) {
62  $message .= 'Original exception: ' .
64  "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
65  "\n\nException caught inside exception handler: " .
67  "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
68  } else {
69  $message .= 'Original exception: ' .
71  $message .= "\n\nException caught inside exception handler.\n\n" .
73  }
74  $message .= "\n";
75  } else {
76  if ( self::showBackTrace( $e ) ) {
78  "\nBacktrace:\n" .
80  } else {
82  }
83  }
84  echo nl2br( htmlspecialchars( $message ) ) . "\n";
85  }
86  }
87 
92  private static function useOutputPage( $e ) {
93  // Can the extension use the Message class/wfMessage to get i18n-ed messages?
94  foreach ( $e->getTrace() as $frame ) {
95  if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
96  return false;
97  }
98  }
99 
100  // Don't even bother with OutputPage if there's no Title context set,
101  // (e.g. we're in RL code on load.php) - the Skin system (and probably
102  // most of MediaWiki) won't work.
103 
104  return (
105  !empty( $GLOBALS['wgFullyInitialised'] ) &&
106  !empty( $GLOBALS['wgOut'] ) &&
107  RequestContext::getMain()->getTitle() &&
108  !defined( 'MEDIAWIKI_INSTALL' )
109  );
110  }
111 
117  private static function reportHTML( $e ) {
119 
120  if ( self::useOutputPage( $e ) ) {
121  if ( $e instanceof MWException ) {
122  $wgOut->prepareErrorPage( $e->getPageTitle() );
123  } elseif ( $e instanceof DBReadOnlyError ) {
124  $wgOut->prepareErrorPage( self::msg( 'readonly', 'Database is locked' ) );
125  } elseif ( $e instanceof DBExpectedError ) {
126  $wgOut->prepareErrorPage( self::msg( 'databaseerror', 'Database error' ) );
127  } else {
128  $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
129  }
130 
131  // Show any custom GUI message before the details
132  if ( $e instanceof MessageSpecifier ) {
133  $wgOut->addHTML( Html::element( 'p', [], Message::newFromSpecifier( $e )->text() ) );
134  }
135  $wgOut->addHTML( self::getHTML( $e ) );
136 
137  $wgOut->output();
138  } else {
139  self::header( 'Content-Type: text/html; charset=utf-8' );
140  $pageTitle = self::msg( 'internalerror', 'Internal error' );
141  echo "<!DOCTYPE html>\n" .
142  '<html><head>' .
143  // Mimick OutputPage::setPageTitle behaviour
144  '<title>' .
145  htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
146  '</title>' .
147  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
148  "</head><body>\n";
149 
150  echo self::getHTML( $e );
151 
152  echo "</body></html>\n";
153  }
154  }
155 
164  public static function getHTML( $e ) {
165  if ( self::showBackTrace( $e ) ) {
166  $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
167  nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
168  '</p><p>Backtrace:</p><p>' .
169  nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
170  "</p></div>\n";
171  } else {
172  $logId = WebRequest::getRequestId();
173  $html = "<div class=\"errorbox mw-content-ltr\">" .
174  htmlspecialchars(
175  '[' . $logId . '] ' .
176  gmdate( 'Y-m-d H:i:s' ) . ": " .
177  self::msg( "internalerror-fatal-exception",
178  "Fatal exception of type $1",
179  get_class( $e ),
180  $logId,
182  ) ) . "</div>\n" .
183  "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
184  }
185 
186  return $html;
187  }
188 
198  private static function msg( $key, $fallback /*[, params...] */ ) {
199  $args = array_slice( func_get_args(), 2 );
200  try {
201  return wfMessage( $key, $args )->text();
202  } catch ( Exception $e ) {
203  return wfMsgReplaceArgs( $fallback, $args );
204  }
205  }
206 
211  private static function getText( $e ) {
212  if ( self::showBackTrace( $e ) ) {
214  "\nBacktrace:\n" .
216  } else {
217  return self::getShowBacktraceError( $e ) . "\n";
218  }
219  }
220 
225  private static function showBackTrace( $e ) {
227 
228  return (
230  ( !( $e instanceof DBError ) || $wgShowDBErrorBacktrace )
231  );
232  }
233 
238  private static function getShowBacktraceError( $e ) {
240  $vars = [];
241  if ( !$wgShowExceptionDetails ) {
242  $vars[] = '$wgShowExceptionDetails = true;';
243  }
244  if ( $e instanceof DBError && !$wgShowDBErrorBacktrace ) {
245  $vars[] = '$wgShowDBErrorBacktrace = true;';
246  }
247  $vars = implode( ' and ', $vars );
248  return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information.";
249  }
250 
254  private static function isCommandLine() {
255  return !empty( $GLOBALS['wgCommandLineMode'] );
256  }
257 
261  private static function header( $header ) {
262  if ( !headers_sent() ) {
263  header( $header );
264  }
265  }
266 
270  private static function statusHeader( $code ) {
271  if ( !headers_sent() ) {
273  }
274  }
275 
282  private static function printError( $message ) {
283  // NOTE: STDERR may not be available, especially if php-cgi is used from the
284  // command line (bug #15602). Try to produce meaningful output anyway. Using
285  // echo may corrupt output to STDOUT though.
286  if ( defined( 'STDERR' ) ) {
287  fwrite( STDERR, $message );
288  } else {
289  echo $message;
290  }
291  }
292 
296  private static function reportOutageHTML( $e ) {
298 
299  $sorry = htmlspecialchars( self::msg(
300  'dberr-problems',
301  'Sorry! This site is experiencing technical difficulties.'
302  ) );
303  $again = htmlspecialchars( self::msg(
304  'dberr-again',
305  'Try waiting a few minutes and reloading.'
306  ) );
307 
309  $info = str_replace(
310  '$1',
311  Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
312  htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
313  );
314  } else {
315  $info = htmlspecialchars( self::msg(
316  'dberr-info-hidden',
317  '(Cannot access the database)'
318  ) );
319  }
320 
321  MessageCache::singleton()->disable(); // no DB access
322  $html = "<!DOCTYPE html>\n" .
323  '<html><head>' .
324  '<title>' .
325  htmlspecialchars( $wgSitename ) .
326  '</title>' .
327  '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
328  "</head><body><h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
329 
330  if ( $wgShowDBErrorBacktrace ) {
331  $html .= '<p>Backtrace:</p><pre>' .
332  htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
333  }
334 
335  $html .= '</body></html>';
336  echo $html;
337  }
338 }
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:414
$wgShowSQLErrors
$wgShowSQLErrors
Whether to show "we're sorry, but there has been a database error" pages.
Definition: DefaultSettings.php:6296
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
$wgMimeType
$wgMimeType
The default Content-Type header.
Definition: DefaultSettings.php:3180
$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:2013
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
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:18
$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:6330
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1393
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
MWExceptionRenderer\reportOutageHTML
static reportOutageHTML( $e)
Definition: MWExceptionRenderer.php:296
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:37
MWExceptionHandler\getPublicLogMessage
static getPublicLogMessage( $e)
Definition: MWExceptionHandler.php:498
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:254
MWExceptionRenderer\AS_PRETTY
const AS_PRETTY
Definition: MWExceptionRenderer.php:32
MWExceptionRenderer\showBackTrace
static showBackTrace( $e)
Definition: MWExceptionRenderer.php:225
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
Wikimedia\Rdbms\DBReadOnlyError
Definition: DBReadOnlyError.php:27
$wgShowDBErrorBacktrace
$wgShowDBErrorBacktrace
If true, show a backtrace for database errors.
Definition: DefaultSettings.php:6314
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:113
$header
$header
Definition: updateCredits.php:35
MWExceptionRenderer\useOutputPage
static useOutputPage( $e)
Definition: MWExceptionRenderer.php:92
MWExceptionRenderer\header
static header( $header)
Definition: MWExceptionRenderer.php:261
$wgSitename
$wgSitename
Name of the site.
Definition: DefaultSettings.php:80
MWExceptionRenderer\msg
static msg( $key, $fallback)
Get a message from i18n.
Definition: MWExceptionRenderer.php:198
MWExceptionRenderer\printError
static printError( $message)
Print a message, if possible to STDERR.
Definition: MWExceptionRenderer.php:282
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:434
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:1751
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
$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:865
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:271
$wgShowExceptionDetails
$wgShowExceptionDetails
If set to true, uncaught exceptions will print a complete stack trace to output.
Definition: DefaultSettings.php:6304
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:22
MWExceptionRenderer\statusHeader
static statusHeader( $code)
Definition: MWExceptionRenderer.php:270
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:164
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:56
MWExceptionRenderer\reportHTML
static reportHTML( $e)
Output the exception report using HTML.
Definition: MWExceptionRenderer.php:117
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2228
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:912
MWExceptionRenderer
Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
Definition: MWExceptionRenderer.php:30
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:211
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171
MWExceptionRenderer\getShowBacktraceError
static getShowBacktraceError( $e)
Definition: MWExceptionRenderer.php:238
MWExceptionRenderer\AS_RAW
const AS_RAW
Definition: MWExceptionRenderer.php:31