Merge "Special:Newpages feed now shows first revision instead of latest revision"
[lhc/web/wiklou.git] / includes / exception / MWExceptionRenderer.php
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 Wikimedia\Rdbms\DBConnectionError;
22 use Wikimedia\Rdbms\DBError;
23 use Wikimedia\Rdbms\DBReadOnlyError;
24 use Wikimedia\Rdbms\DBExpectedError;
25
26 /**
27 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
28 * @since 1.28
29 */
30 class MWExceptionRenderer {
31 const AS_RAW = 1; // show as text
32 const AS_PRETTY = 2; // show as HTML
33
34 /**
35 * @param Exception|Throwable $e Original exception
36 * @param integer $mode MWExceptionExposer::AS_* constant
37 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
38 */
39 public static function output( $e, $mode, $eNew = null ) {
40 global $wgMimeType;
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 ) {
51 self::reportOutageHTML( $e );
52 } else {
53 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
54 self::reportHTML( $e );
55 }
56 } else {
57 if ( $eNew ) {
58 $message = "MediaWiki internal error.\n\n";
59 if ( self::showBackTrace( $e ) ) {
60 $message .= 'Original exception: ' .
61 MWExceptionHandler::getLogMessage( $e ) .
62 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
63 "\n\nException caught inside exception handler: " .
64 MWExceptionHandler::getLogMessage( $eNew ) .
65 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
66 } else {
67 $message .= 'Original exception: ' .
68 MWExceptionHandler::getPublicLogMessage( $e );
69 $message .= "\n\nException caught inside exception handler.\n\n" .
70 self::getShowBacktraceError( $e );
71 }
72 $message .= "\n";
73 } else {
74 if ( self::showBackTrace( $e ) ) {
75 $message = MWExceptionHandler::getLogMessage( $e ) .
76 "\nBacktrace:\n" .
77 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
78 } else {
79 $message = MWExceptionHandler::getPublicLogMessage( $e );
80 }
81 }
82 echo nl2br( htmlspecialchars( $message ) ) . "\n";
83 }
84 }
85
86 /**
87 * @param Exception|Throwable $e
88 * @return bool Should the exception use $wgOut to output the error?
89 */
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' ) {
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
110 /**
111 * Output the exception report using HTML
112 *
113 * @param Exception|Throwable $e
114 */
115 private static function reportHTML( $e ) {
116 global $wgOut, $wgSitename;
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( Message::newFromSpecifier( $e )->escaped() );
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
154 /**
155 * If $wgShowExceptionDetails is true, return a HTML message with a
156 * backtrace to the error, otherwise show a message to ask to set it to true
157 * to show that information.
158 *
159 * @param Exception|Throwable $e
160 * @return string Html to output
161 */
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 '[' . $logId . '] ' .
173 gmdate( 'Y-m-d H:i:s' ) . ": " .
174 self::msg( "internalerror-fatal-exception",
175 "Fatal exception of type $1",
176 get_class( $e ),
177 $logId,
178 MWExceptionHandler::getURL()
179 ) . "</div>\n" .
180 "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
181 }
182
183 return $html;
184 }
185
186 /**
187 * Get a message from i18n
188 *
189 * @param string $key Message name
190 * @param string $fallback Default message if the message cache can't be
191 * called by the exception
192 * The function also has other parameters that are arguments for the message
193 * @return string Message with arguments replaced
194 */
195 private static function msg( $key, $fallback /*[, params...] */ ) {
196 $args = array_slice( func_get_args(), 2 );
197 try {
198 return wfMessage( $key, $args )->text();
199 } catch ( Exception $e ) {
200 return wfMsgReplaceArgs( $fallback, $args );
201 }
202 }
203
204 /**
205 * @param Exception|Throwable $e
206 * @return string
207 */
208 private static function getText( $e ) {
209 if ( self::showBackTrace( $e ) ) {
210 return MWExceptionHandler::getLogMessage( $e ) .
211 "\nBacktrace:\n" .
212 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
213 } else {
214 return self::getShowBacktraceError( $e ) . "\n";
215 }
216 }
217
218 /**
219 * @param Exception|Throwable $e
220 * @return bool
221 */
222 private static function showBackTrace( $e ) {
223 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
224
225 return (
226 $wgShowExceptionDetails &&
227 ( !( $e instanceof DBError ) || $wgShowDBErrorBacktrace )
228 );
229 }
230
231 /**
232 * @param Exception|Throwable $e
233 * @return string
234 */
235 private static function getShowBacktraceError( $e ) {
236 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
237 $vars = [];
238 if ( !$wgShowExceptionDetails ) {
239 $vars[] = '$wgShowExceptionDetails = true;';
240 }
241 if ( $e instanceof DBError && !$wgShowDBErrorBacktrace ) {
242 $vars[] = '$wgShowDBErrorBacktrace = true;';
243 }
244 $vars = implode( ' and ', $vars );
245 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information.";
246 }
247
248 /**
249 * @return bool
250 */
251 private static function isCommandLine() {
252 return !empty( $GLOBALS['wgCommandLineMode'] );
253 }
254
255 /**
256 * @param string $header
257 */
258 private static function header( $header ) {
259 if ( !headers_sent() ) {
260 header( $header );
261 }
262 }
263
264 /**
265 * @param integer $code
266 */
267 private static function statusHeader( $code ) {
268 if ( !headers_sent() ) {
269 HttpStatus::header( $code );
270 }
271 }
272
273 /**
274 * Print a message, if possible to STDERR.
275 * Use this in command line mode only (see isCommandLine)
276 *
277 * @param string $message Failure text
278 */
279 private static function printError( $message ) {
280 // NOTE: STDERR may not be available, especially if php-cgi is used from the
281 // command line (bug #15602). Try to produce meaningful output anyway. Using
282 // echo may corrupt output to STDOUT though.
283 if ( defined( 'STDERR' ) ) {
284 fwrite( STDERR, $message );
285 } else {
286 echo $message;
287 }
288 }
289
290 /**
291 * @param Exception|Throwable $e
292 */
293 private static function reportOutageHTML( $e ) {
294 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
295
296 $sorry = htmlspecialchars( self::msg(
297 'dberr-problems',
298 'Sorry! This site is experiencing technical difficulties.'
299 ) );
300 $again = htmlspecialchars( self::msg(
301 'dberr-again',
302 'Try waiting a few minutes and reloading.'
303 ) );
304
305 if ( $wgShowHostnames || $wgShowSQLErrors ) {
306 $info = str_replace(
307 '$1',
308 Html::element( 'span', [ 'dir' => 'ltr' ], $e->getMessage() ),
309 htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
310 );
311 } else {
312 $info = htmlspecialchars( self::msg(
313 'dberr-info-hidden',
314 '(Cannot access the database)'
315 ) );
316 }
317
318 MessageCache::singleton()->disable(); // no DB access
319
320 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
321
322 if ( $wgShowDBErrorBacktrace ) {
323 $html .= '<p>Backtrace:</p><pre>' .
324 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
325 }
326
327 $html .= '<hr />';
328 $html .= self::googleSearchForm();
329
330 echo $html;
331 }
332
333 /**
334 * @return string
335 */
336 private static function googleSearchForm() {
337 global $wgSitename, $wgCanonicalServer, $wgRequest;
338
339 $usegoogle = htmlspecialchars( self::msg(
340 'dberr-usegoogle',
341 'You can try searching via Google in the meantime.'
342 ) );
343 $outofdate = htmlspecialchars( self::msg(
344 'dberr-outofdate',
345 'Note that their indexes of our content may be out of date.'
346 ) );
347 $googlesearch = htmlspecialchars( self::msg( 'searchbutton', 'Search' ) );
348 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
349 $server = htmlspecialchars( $wgCanonicalServer );
350 $sitename = htmlspecialchars( $wgSitename );
351 $trygoogle = <<<EOT
352 <div style="margin: 1.5em">$usegoogle<br />
353 <small>$outofdate</small>
354 </div>
355 <form method="get" action="//www.google.com/search" id="googlesearch">
356 <input type="hidden" name="domains" value="$server" />
357 <input type="hidden" name="num" value="50" />
358 <input type="hidden" name="ie" value="UTF-8" />
359 <input type="hidden" name="oe" value="UTF-8" />
360 <input type="text" name="q" size="31" maxlength="255" value="$search" />
361 <input type="submit" name="btnG" value="$googlesearch" />
362 <p>
363 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
364 <label><input type="radio" name="sitesearch" value="" />WWW</label>
365 </p>
366 </form>
367 EOT;
368 return $trygoogle;
369 }
370 }