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