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