RCFilters: Style the Saved Links placeholder and add a title
[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 * @author Aaron Schulz
20 */
21
22 use Wikimedia\Rdbms\DBConnectionError;
23 use Wikimedia\Rdbms\DBError;
24 use Wikimedia\Rdbms\DBReadOnlyError;
25 use Wikimedia\Rdbms\DBExpectedError;
26
27 /**
28 * Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
29 * @since 1.28
30 */
31 class MWExceptionRenderer {
32 const AS_RAW = 1; // show as text
33 const AS_PRETTY = 2; // show as HTML
34
35 /**
36 * @param Exception|Throwable $e Original exception
37 * @param integer $mode MWExceptionExposer::AS_* constant
38 * @param Exception|Throwable|null $eNew New exception from attempting to show the first
39 */
40 public static function output( $e, $mode, $eNew = null ) {
41 global $wgMimeType;
42
43 if ( defined( 'MW_API' ) ) {
44 // Unhandled API exception, we can't be sure that format printer is alive
45 self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $e ) );
46 wfHttpError( 500, 'Internal Server Error', self::getText( $e ) );
47 } elseif ( self::isCommandLine() ) {
48 self::printError( self::getText( $e ) );
49 } elseif ( $mode === self::AS_PRETTY ) {
50 self::statusHeader( 500 );
51 if ( $e instanceof DBConnectionError ) {
52 self::reportOutageHTML( $e );
53 } else {
54 self::header( "Content-Type: $wgMimeType; charset=utf-8" );
55 self::reportHTML( $e );
56 }
57 } else {
58 if ( $eNew ) {
59 $message = "MediaWiki internal error.\n\n";
60 if ( self::showBackTrace( $e ) ) {
61 $message .= 'Original exception: ' .
62 MWExceptionHandler::getLogMessage( $e ) .
63 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $e ) .
64 "\n\nException caught inside exception handler: " .
65 MWExceptionHandler::getLogMessage( $eNew ) .
66 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $eNew );
67 } else {
68 $message .= 'Original exception: ' .
69 MWExceptionHandler::getPublicLogMessage( $e );
70 $message .= "\n\nException caught inside exception handler.\n\n" .
71 self::getShowBacktraceError( $e );
72 }
73 $message .= "\n";
74 } else {
75 if ( self::showBackTrace( $e ) ) {
76 $message = MWExceptionHandler::getLogMessage( $e ) .
77 "\nBacktrace:\n" .
78 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
79 } else {
80 $message = MWExceptionHandler::getPublicLogMessage( $e );
81 }
82 }
83 echo nl2br( htmlspecialchars( $message ) ) . "\n";
84 }
85 }
86
87 /**
88 * Run hook to allow extensions to modify the text of the exception
89 *
90 * Called by MWException for b/c
91 *
92 * @param Exception|Throwable $e
93 * @param string $name Class name of the exception
94 * @param array $args Arguments to pass to the callback functions
95 * @return string|null String to output or null if any hook has been called
96 */
97 public static function runHooks( $e, $name, $args = [] ) {
98 global $wgExceptionHooks;
99
100 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
101 return null; // Just silently ignore
102 }
103
104 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
105 !is_array( $wgExceptionHooks[$name] )
106 ) {
107 return null;
108 }
109
110 $hooks = $wgExceptionHooks[$name];
111 $callargs = array_merge( [ $e ], $args );
112
113 foreach ( $hooks as $hook ) {
114 if (
115 is_string( $hook ) ||
116 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
117 ) {
118 // 'function' or [ 'class', 'hook' ]
119 $result = call_user_func_array( $hook, $callargs );
120 } else {
121 $result = null;
122 }
123
124 if ( is_string( $result ) ) {
125 return $result;
126 }
127 }
128
129 return null;
130 }
131
132 /**
133 * @param Exception|Throwable $e
134 * @return bool Should the exception use $wgOut to output the error?
135 */
136 private static function useOutputPage( $e ) {
137 // Can the extension use the Message class/wfMessage to get i18n-ed messages?
138 foreach ( $e->getTrace() as $frame ) {
139 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
140 return false;
141 }
142 }
143
144 return (
145 !empty( $GLOBALS['wgFullyInitialised'] ) &&
146 !empty( $GLOBALS['wgOut'] ) &&
147 !defined( 'MEDIAWIKI_INSTALL' )
148 );
149 }
150
151 /**
152 * Output the exception report using HTML
153 *
154 * @param Exception|Throwable $e
155 */
156 private static function reportHTML( $e ) {
157 global $wgOut, $wgSitename;
158
159 if ( self::useOutputPage( $e ) ) {
160 if ( $e instanceof MWException ) {
161 $wgOut->prepareErrorPage( $e->getPageTitle() );
162 } elseif ( $e instanceof DBReadOnlyError ) {
163 $wgOut->prepareErrorPage( self::msg( 'readonly', 'Database is locked' ) );
164 } elseif ( $e instanceof DBExpectedError ) {
165 $wgOut->prepareErrorPage( self::msg( 'databaseerror', 'Database error' ) );
166 } else {
167 $wgOut->prepareErrorPage( self::msg( 'internalerror', 'Internal error' ) );
168 }
169
170 $hookResult = self::runHooks( $e, get_class( $e ) );
171 if ( $hookResult ) {
172 $wgOut->addHTML( $hookResult );
173 } else {
174 // Show any custom GUI message before the details
175 if ( $e instanceof MessageSpecifier ) {
176 $wgOut->addHTML( Message::newFromSpecifier( $e )->escaped() );
177 }
178 $wgOut->addHTML( self::getHTML( $e ) );
179 }
180
181 $wgOut->output();
182 } else {
183 self::header( 'Content-Type: text/html; charset=utf-8' );
184 $pageTitle = self::msg( 'internalerror', 'Internal error' );
185 echo "<!DOCTYPE html>\n" .
186 '<html><head>' .
187 // Mimick OutputPage::setPageTitle behaviour
188 '<title>' .
189 htmlspecialchars( self::msg( 'pagetitle', "$1 - $wgSitename", $pageTitle ) ) .
190 '</title>' .
191 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
192 "</head><body>\n";
193
194 $hookResult = self::runHooks( $e, get_class( $e ) . 'Raw' );
195 if ( $hookResult ) {
196 echo $hookResult;
197 } else {
198 echo self::getHTML( $e );
199 }
200
201 echo "</body></html>\n";
202 }
203 }
204
205 /**
206 * If $wgShowExceptionDetails is true, return a HTML message with a
207 * backtrace to the error, otherwise show a message to ask to set it to true
208 * to show that information.
209 *
210 * @param Exception|Throwable $e
211 * @return string Html to output
212 */
213 public static function getHTML( $e ) {
214 if ( self::showBackTrace( $e ) ) {
215 $html = "<div class=\"errorbox mw-content-ltr\"><p>" .
216 nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $e ) ) ) .
217 '</p><p>Backtrace:</p><p>' .
218 nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $e ) ) ) .
219 "</p></div>\n";
220 } else {
221 $logId = WebRequest::getRequestId();
222 $html = "<div class=\"errorbox mw-content-ltr\">" .
223 '[' . $logId . '] ' .
224 gmdate( 'Y-m-d H:i:s' ) . ": " .
225 self::msg( "internalerror-fatal-exception",
226 "Fatal exception of type $1",
227 get_class( $e ),
228 $logId,
229 MWExceptionHandler::getURL()
230 ) . "</div>\n" .
231 "<!-- " . wordwrap( self::getShowBacktraceError( $e ), 50 ) . " -->";
232 }
233
234 return $html;
235 }
236
237 /**
238 * Get a message from i18n
239 *
240 * @param string $key Message name
241 * @param string $fallback Default message if the message cache can't be
242 * called by the exception
243 * The function also has other parameters that are arguments for the message
244 * @return string Message with arguments replaced
245 */
246 private static function msg( $key, $fallback /*[, params...] */ ) {
247 $args = array_slice( func_get_args(), 2 );
248 try {
249 return wfMessage( $key, $args )->text();
250 } catch ( Exception $e ) {
251 return wfMsgReplaceArgs( $fallback, $args );
252 }
253 }
254
255 /**
256 * @param Exception|Throwable $e
257 * @return string
258 */
259 private static function getText( $e ) {
260 if ( self::showBackTrace( $e ) ) {
261 return MWExceptionHandler::getLogMessage( $e ) .
262 "\nBacktrace:\n" .
263 MWExceptionHandler::getRedactedTraceAsString( $e ) . "\n";
264 } else {
265 return self::getShowBacktraceError( $e );
266 }
267 }
268
269 /**
270 * @param Exception|Throwable $e
271 * @return bool
272 */
273 private static function showBackTrace( $e ) {
274 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
275
276 return (
277 $wgShowExceptionDetails &&
278 ( !( $e instanceof DBError ) || $wgShowDBErrorBacktrace )
279 );
280 }
281
282 /**
283 * @param Exception|Throwable $e
284 * @return string
285 */
286 private static function getShowBacktraceError( $e ) {
287 global $wgShowExceptionDetails, $wgShowDBErrorBacktrace;
288 $vars = [];
289 if ( !$wgShowExceptionDetails ) {
290 $vars[] = '$wgShowExceptionDetails = true;';
291 }
292 if ( $e instanceof DBError && !$wgShowDBErrorBacktrace ) {
293 $vars[] = '$wgShowDBErrorBacktrace = true;';
294 }
295 $vars = implode( ' and ', $vars );
296 return "Set $vars at the bottom of LocalSettings.php to show detailed debugging information\n";
297 }
298
299 /**
300 * @return bool
301 */
302 private static function isCommandLine() {
303 return !empty( $GLOBALS['wgCommandLineMode'] );
304 }
305
306 /**
307 * @param string $header
308 */
309 private static function header( $header ) {
310 if ( !headers_sent() ) {
311 header( $header );
312 }
313 }
314
315 /**
316 * @param integer $code
317 */
318 private static function statusHeader( $code ) {
319 if ( !headers_sent() ) {
320 HttpStatus::header( $code );
321 }
322 }
323
324 /**
325 * Print a message, if possible to STDERR.
326 * Use this in command line mode only (see isCommandLine)
327 *
328 * @param string $message Failure text
329 */
330 private static function printError( $message ) {
331 // NOTE: STDERR may not be available, especially if php-cgi is used from the
332 // command line (bug #15602). Try to produce meaningful output anyway. Using
333 // echo may corrupt output to STDOUT though.
334 if ( defined( 'STDERR' ) ) {
335 fwrite( STDERR, $message );
336 } else {
337 echo $message;
338 }
339 }
340
341 /**
342 * @param Exception|Throwable $e
343 */
344 private static function reportOutageHTML( $e ) {
345 global $wgShowDBErrorBacktrace, $wgShowHostnames, $wgShowSQLErrors;
346
347 $sorry = htmlspecialchars( self::msg(
348 'dberr-problems',
349 'Sorry! This site is experiencing technical difficulties.'
350 ) );
351 $again = htmlspecialchars( self::msg(
352 'dberr-again',
353 'Try waiting a few minutes and reloading.'
354 ) );
355
356 if ( $wgShowHostnames || $wgShowSQLErrors ) {
357 $info = str_replace(
358 '$1',
359 Html::element( 'span', [ 'dir' => 'ltr' ], htmlspecialchars( $e->getMessage() ) ),
360 htmlspecialchars( self::msg( 'dberr-info', '($1)' ) )
361 );
362 } else {
363 $info = htmlspecialchars( self::msg(
364 'dberr-info-hidden',
365 '(Cannot access the database)'
366 ) );
367 }
368
369 MessageCache::singleton()->disable(); // no DB access
370
371 $html = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
372
373 if ( $wgShowDBErrorBacktrace ) {
374 $html .= '<p>Backtrace:</p><pre>' .
375 htmlspecialchars( $e->getTraceAsString() ) . '</pre>';
376 }
377
378 $html .= '<hr />';
379 $html .= self::googleSearchForm();
380
381 echo $html;
382 }
383
384 /**
385 * @return string
386 */
387 private static function googleSearchForm() {
388 global $wgSitename, $wgCanonicalServer, $wgRequest;
389
390 $usegoogle = htmlspecialchars( self::msg(
391 'dberr-usegoogle',
392 'You can try searching via Google in the meantime.'
393 ) );
394 $outofdate = htmlspecialchars( self::msg(
395 'dberr-outofdate',
396 'Note that their indexes of our content may be out of date.'
397 ) );
398 $googlesearch = htmlspecialchars( self::msg( 'searchbutton', 'Search' ) );
399 $search = htmlspecialchars( $wgRequest->getVal( 'search' ) );
400 $server = htmlspecialchars( $wgCanonicalServer );
401 $sitename = htmlspecialchars( $wgSitename );
402 $trygoogle = <<<EOT
403 <div style="margin: 1.5em">$usegoogle<br />
404 <small>$outofdate</small>
405 </div>
406 <form method="get" action="//www.google.com/search" id="googlesearch">
407 <input type="hidden" name="domains" value="$server" />
408 <input type="hidden" name="num" value="50" />
409 <input type="hidden" name="ie" value="UTF-8" />
410 <input type="hidden" name="oe" value="UTF-8" />
411 <input type="text" name="q" size="31" maxlength="255" value="$search" />
412 <input type="submit" name="btnG" value="$googlesearch" />
413 <p>
414 <label><input type="radio" name="sitesearch" value="$server" checked="checked" />$sitename</label>
415 <label><input type="radio" name="sitesearch" value="" />WWW</label>
416 </p>
417 </form>
418 EOT;
419 return $trygoogle;
420 }
421 }