Merge "Allow maxlength attribute on HTMLSelectAndOtherField"
[lhc/web/wiklou.git] / includes / exception / MWExceptionHandler.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 /**
22 * Handler class for MWExceptions
23 * @ingroup Exception
24 */
25 class MWExceptionHandler {
26
27 /**
28 * Install handlers with PHP.
29 */
30 public static function installHandler() {
31 set_exception_handler( array( 'MWExceptionHandler', 'handleException' ) );
32 set_error_handler( array( 'MWExceptionHandler', 'handleError' ) );
33 }
34
35 /**
36 * Report an exception to the user
37 * @param Exception $e
38 */
39 protected static function report( Exception $e ) {
40 global $wgShowExceptionDetails;
41
42 $cmdLine = MWException::isCommandLine();
43
44 if ( $e instanceof MWException ) {
45 try {
46 // Try and show the exception prettily, with the normal skin infrastructure
47 $e->report();
48 } catch ( Exception $e2 ) {
49 // Exception occurred from within exception handler
50 // Show a simpler message for the original exception,
51 // don't try to invoke report()
52 $message = "MediaWiki internal error.\n\n";
53
54 if ( $wgShowExceptionDetails ) {
55 $message .= 'Original exception: ' . self::getLogMessage( $e ) .
56 "\nBacktrace:\n" . self::getRedactedTraceAsString( $e ) .
57 "\n\nException caught inside exception handler: " . self::getLogMessage( $e2 ) .
58 "\nBacktrace:\n" . self::getRedactedTraceAsString( $e2 );
59 } else {
60 $message .= "Exception caught inside exception handler.\n\n" .
61 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
62 "to show detailed debugging information.";
63 }
64
65 $message .= "\n";
66
67 if ( $cmdLine ) {
68 self::printError( $message );
69 } else {
70 echo nl2br( htmlspecialchars( $message ) ) . "\n";
71 }
72 }
73 } else {
74 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
75 get_class( $e ) . "\"";
76
77 if ( $wgShowExceptionDetails ) {
78 $message .= "\n" . MWExceptionHandler::getLogMessage( $e ) . "\nBacktrace:\n" .
79 self::getRedactedTraceAsString( $e ) . "\n";
80 }
81
82 if ( $cmdLine ) {
83 self::printError( $message );
84 } else {
85 echo nl2br( htmlspecialchars( $message ) ) . "\n";
86 }
87
88 }
89 }
90
91 /**
92 * Print a message, if possible to STDERR.
93 * Use this in command line mode only (see isCommandLine)
94 *
95 * @param string $message Failure text
96 */
97 public static function printError( $message ) {
98 # NOTE: STDERR may not be available, especially if php-cgi is used from the
99 # command line (bug #15602). Try to produce meaningful output anyway. Using
100 # echo may corrupt output to STDOUT though.
101 if ( defined( 'STDERR' ) ) {
102 fwrite( STDERR, $message );
103 } else {
104 echo $message;
105 }
106 }
107
108 /**
109 * If there are any open database transactions, roll them back and log
110 * the stack trace of the exception that should have been caught so the
111 * transaction could be aborted properly.
112 *
113 * @since 1.23
114 * @param Exception $e
115 */
116 public static function rollbackMasterChangesAndLog( Exception $e ) {
117 $factory = wfGetLBFactory();
118 if ( $factory->hasMasterChanges() ) {
119 wfDebugLog( 'Bug56269',
120 'Exception thrown with an uncommited database transaction: ' .
121 MWExceptionHandler::getLogMessage( $e ) . "\n" .
122 $e->getTraceAsString()
123 );
124 $factory->rollbackMasterChanges();
125 }
126 }
127
128 /**
129 * Exception handler which simulates the appropriate catch() handling:
130 *
131 * try {
132 * ...
133 * } catch ( MWException $e ) {
134 * $e->report();
135 * } catch ( Exception $e ) {
136 * echo $e->__toString();
137 * }
138 *
139 * @since 1.25
140 * @param Exception $e
141 */
142 public static function handleException( $e ) {
143 global $wgFullyInitialised;
144
145 self::rollbackMasterChangesAndLog( $e );
146 self::logException( $e );
147 self::report( $e );
148
149 // Final cleanup
150 if ( $wgFullyInitialised ) {
151 try {
152 // uses $wgRequest, hence the $wgFullyInitialised condition
153 wfLogProfilingData();
154 } catch ( Exception $e ) {
155 }
156 }
157
158 // Exit value should be nonzero for the benefit of shell jobs
159 exit( 1 );
160 }
161
162 /**
163 * @since 1.25
164 * @param int $level Error level raised
165 * @param string $message
166 * @param string $file
167 * @param int $line
168 */
169 public static function handleError( $level, $message, $file = null, $line = null ) {
170 $e = new ErrorException( $message, 0, $level, $file, $line );
171 self::logError( $e );
172
173 // This handler is for logging only. Return false will instruct PHP
174 // to continue regular handling.
175 return false;
176 }
177
178 /**
179 * Generate a string representation of an exception's stack trace
180 *
181 * Like Exception::getTraceAsString, but replaces argument values with
182 * argument type or class name.
183 *
184 * @param Exception $e
185 * @return string
186 */
187 public static function getRedactedTraceAsString( Exception $e ) {
188 $text = '';
189
190 foreach ( self::getRedactedTrace( $e ) as $level => $frame ) {
191 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
192 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
193 } else {
194 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
195 // This matches behaviour of Exception::getTraceAsString to instead
196 // display "[internal function]".
197 $text .= "#{$level} [internal function]: ";
198 }
199
200 if ( isset( $frame['class'] ) ) {
201 $text .= $frame['class'] . $frame['type'] . $frame['function'];
202 } else {
203 $text .= $frame['function'];
204 }
205
206 if ( isset( $frame['args'] ) ) {
207 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
208 } else {
209 $text .= "()\n";
210 }
211 }
212
213 $level = $level + 1;
214 $text .= "#{$level} {main}";
215
216 return $text;
217 }
218
219 /**
220 * Return a copy of an exception's backtrace as an array.
221 *
222 * Like Exception::getTrace, but replaces each element in each frame's
223 * argument array with the name of its class (if the element is an object)
224 * or its type (if the element is a PHP primitive).
225 *
226 * @since 1.22
227 * @param Exception $e
228 * @return array
229 */
230 public static function getRedactedTrace( Exception $e ) {
231 return array_map( function ( $frame ) {
232 if ( isset( $frame['args'] ) ) {
233 $frame['args'] = array_map( function ( $arg ) {
234 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
235 }, $frame['args'] );
236 }
237 return $frame;
238 }, $e->getTrace() );
239 }
240
241 /**
242 * Get the ID for this exception.
243 *
244 * The ID is saved so that one can match the one output to the user (when
245 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
246 *
247 * @since 1.22
248 * @param Exception $e
249 * @return string
250 */
251 public static function getLogId( Exception $e ) {
252 if ( !isset( $e->_mwLogId ) ) {
253 $e->_mwLogId = wfRandomString( 8 );
254 }
255 return $e->_mwLogId;
256 }
257
258 /**
259 * If the exception occurred in the course of responding to a request,
260 * returns the requested URL. Otherwise, returns false.
261 *
262 * @since 1.23
263 * @return string|bool
264 */
265 public static function getURL() {
266 global $wgRequest;
267 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
268 return false;
269 }
270 return $wgRequest->getRequestURL();
271 }
272
273 /**
274 * Get a message formatting the exception message and its origin.
275 *
276 * @since 1.22
277 * @param Exception $e
278 * @return string
279 */
280 public static function getLogMessage( Exception $e ) {
281 $id = self::getLogId( $e );
282 $type = get_class( $e );
283 $file = $e->getFile();
284 $line = $e->getLine();
285 $message = $e->getMessage();
286 $url = self::getURL() ?: '[no req]';
287
288 return "[$id] $url $type from line $line of $file: $message";
289 }
290
291 /**
292 * Serialize an Exception object to JSON.
293 *
294 * The JSON object will have keys 'id', 'file', 'line', 'message', and
295 * 'url'. These keys map to string values, with the exception of 'line',
296 * which is a number, and 'url', which may be either a string URL or or
297 * null if the exception did not occur in the context of serving a web
298 * request.
299 *
300 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
301 * key, mapped to the array return value of Exception::getTrace, but with
302 * each element in each frame's "args" array (if set) replaced with the
303 * argument's class name (if the argument is an object) or type name (if
304 * the argument is a PHP primitive).
305 *
306 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
307 * @code
308 * {
309 * "id": "c41fb419",
310 * "type": "MWException",
311 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
312 * "line": 704,
313 * "message": "Non-string key given",
314 * "url": "/wiki/Main_Page"
315 * }
316 * @endcode
317 *
318 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
319 * @code
320 * {
321 * "id": "dc457938",
322 * "type": "MWException",
323 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
324 * "line": 704,
325 * "message": "Non-string key given",
326 * "url": "/wiki/Main_Page",
327 * "backtrace": [{
328 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
329 * "line": 80,
330 * "function": "get",
331 * "class": "MessageCache",
332 * "type": "->",
333 * "args": ["array"]
334 * }]
335 * }
336 * @endcode
337 *
338 * @since 1.23
339 * @param Exception $e
340 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
341 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
342 * @return string|bool JSON string if successful; false upon failure
343 */
344 public static function jsonSerializeException( Exception $e, $pretty = false, $escaping = 0 ) {
345 global $wgLogExceptionBacktrace;
346
347 $exceptionData = array(
348 'id' => self::getLogId( $e ),
349 'type' => get_class( $e ),
350 'file' => $e->getFile(),
351 'line' => $e->getLine(),
352 'message' => $e->getMessage(),
353 );
354
355 // Because MediaWiki is first and foremost a web application, we set a
356 // 'url' key unconditionally, but set it to null if the exception does
357 // not occur in the context of a web request, as a way of making that
358 // fact visible and explicit.
359 $exceptionData['url'] = self::getURL() ?: null;
360
361 if ( $wgLogExceptionBacktrace ) {
362 // Argument values may not be serializable, so redact them.
363 $exceptionData['backtrace'] = self::getRedactedTrace( $e );
364 }
365
366 return FormatJson::encode( $exceptionData, $pretty, $escaping );
367 }
368
369 /**
370 * Log an exception to the exception log (if enabled).
371 *
372 * This method must not assume the exception is an MWException,
373 * it is also used to handle PHP exceptions or exceptions from other libraries.
374 *
375 * @since 1.22
376 * @param Exception $e
377 */
378 public static function logException( Exception $e ) {
379 global $wgLogExceptionBacktrace;
380
381 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
382 $log = self::getLogMessage( $e );
383 if ( $wgLogExceptionBacktrace ) {
384 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() );
385 } else {
386 wfDebugLog( 'exception', $log );
387 }
388
389 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
390 if ( $json !== false ) {
391 wfDebugLog( 'exception-json', $json, 'private' );
392 }
393 }
394 }
395
396 /**
397 * Log an exception that wasn't thrown but made to wrap an error.
398 *
399 * @since 1.25
400 * @param Exception $e
401 */
402 protected static function logError( Exception $e ) {
403 global $wgLogExceptionBacktrace;
404
405 $log = self::getLogMessage( $e );
406 if ( $wgLogExceptionBacktrace ) {
407 wfDebugLog( 'error', $log . "\n" . $e->getTraceAsString() );
408 } else {
409 wfDebugLog( 'error', $log );
410 }
411 }
412 }