MWException doesn't care about $wgTitle anymore
[lhc/web/wiklou.git] / includes / Exception.php
1 <?php
2 /**
3 * Exception class and handler.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * @defgroup Exception Exception
25 */
26
27 /**
28 * MediaWiki exception
29 *
30 * @ingroup Exception
31 */
32 class MWException extends Exception {
33 /**
34 * Should the exception use $wgOut to output the error?
35 *
36 * @return bool
37 */
38 function useOutputPage() {
39 return $this->useMessageCache() &&
40 !empty( $GLOBALS['wgFullyInitialised'] ) &&
41 !empty( $GLOBALS['wgOut'] );
42 }
43
44 /**
45 * Whether to log this exception in the exception debug log.
46 *
47 * @since 1.23
48 * @return boolean
49 */
50 function isLoggable() {
51 return true;
52 }
53
54 /**
55 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
56 *
57 * @return bool
58 */
59 function useMessageCache() {
60 global $wgLang;
61
62 foreach ( $this->getTrace() as $frame ) {
63 if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
64 return false;
65 }
66 }
67
68 return $wgLang instanceof Language;
69 }
70
71 /**
72 * Run hook to allow extensions to modify the text of the exception
73 *
74 * @param string $name class name of the exception
75 * @param array $args arguments to pass to the callback functions
76 * @return string|null string to output or null if any hook has been called
77 */
78 function runHooks( $name, $args = array() ) {
79 global $wgExceptionHooks;
80
81 if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
82 return null; // Just silently ignore
83 }
84
85 if ( !array_key_exists( $name, $wgExceptionHooks ) ||
86 !is_array( $wgExceptionHooks[$name] )
87 ) {
88 return null;
89 }
90
91 $hooks = $wgExceptionHooks[$name];
92 $callargs = array_merge( array( $this ), $args );
93
94 foreach ( $hooks as $hook ) {
95 if (
96 is_string( $hook ) ||
97 ( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
98 ) {
99 // 'function' or array( 'class', hook' )
100 $result = call_user_func_array( $hook, $callargs );
101 } else {
102 $result = null;
103 }
104
105 if ( is_string( $result ) ) {
106 return $result;
107 }
108 }
109 return null;
110 }
111
112 /**
113 * Get a message from i18n
114 *
115 * @param string $key message name
116 * @param string $fallback default message if the message cache can't be
117 * called by the exception
118 * The function also has other parameters that are arguments for the message
119 * @return string message with arguments replaced
120 */
121 function msg( $key, $fallback /*[, params...] */ ) {
122 $args = array_slice( func_get_args(), 2 );
123
124 if ( $this->useMessageCache() ) {
125 return wfMessage( $key, $args )->plain();
126 } else {
127 return wfMsgReplaceArgs( $fallback, $args );
128 }
129 }
130
131 /**
132 * If $wgShowExceptionDetails is true, return a HTML message with a
133 * backtrace to the error, otherwise show a message to ask to set it to true
134 * to show that information.
135 *
136 * @return string html to output
137 */
138 function getHTML() {
139 global $wgShowExceptionDetails;
140
141 if ( $wgShowExceptionDetails ) {
142 return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $this ) ) ) .
143 '</p><p>Backtrace:</p><p>' . nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $this ) ) ) .
144 "</p>\n";
145 } else {
146 return "<div class=\"errorbox\">" .
147 '[' . MWExceptionHandler::getLogId( $this ) . '] ' .
148 gmdate( 'Y-m-d H:i:s' ) .
149 ": Fatal exception of type " . get_class( $this ) . "</div>\n" .
150 "<!-- Set \$wgShowExceptionDetails = true; " .
151 "at the bottom of LocalSettings.php to show detailed " .
152 "debugging information. -->";
153 }
154 }
155
156 /**
157 * Get the text to display when reporting the error on the command line.
158 * If $wgShowExceptionDetails is true, return a text message with a
159 * backtrace to the error.
160 *
161 * @return string
162 */
163 function getText() {
164 global $wgShowExceptionDetails;
165
166 if ( $wgShowExceptionDetails ) {
167 return MWExceptionHandler::getLogMessage( $this ) .
168 "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $this ) . "\n";
169 } else {
170 return "Set \$wgShowExceptionDetails = true; " .
171 "in LocalSettings.php to show detailed debugging information.\n";
172 }
173 }
174
175 /**
176 * Return the title of the page when reporting this error in a HTTP response.
177 *
178 * @return string
179 */
180 function getPageTitle() {
181 global $wgSitename;
182 return $this->msg( 'pagetitle', "$1 - $wgSitename", $this->msg( 'internalerror', 'Internal error' ) );
183 }
184
185 /**
186 * Get a the ID for this error.
187 *
188 * @since 1.20
189 * @deprecated since 1.22 Use MWExceptionHandler::getLogId instead.
190 * @return string
191 */
192 function getLogId() {
193 wfDeprecated( __METHOD__, '1.22' );
194 return MWExceptionHandler::getLogId( $this );
195 }
196
197 /**
198 * Return the requested URL and point to file and line number from which the
199 * exception occurred
200 *
201 * @since 1.8
202 * @deprecated since 1.22 Use MWExceptionHandler::getLogMessage instead.
203 * @return string
204 */
205 function getLogMessage() {
206 wfDeprecated( __METHOD__, '1.22' );
207 return MWExceptionHandler::getLogMessage( $this );
208 }
209
210 /**
211 * Output the exception report using HTML.
212 */
213 function reportHTML() {
214 global $wgOut;
215 if ( $this->useOutputPage() ) {
216 $wgOut->prepareErrorPage( $this->getPageTitle() );
217
218 $hookResult = $this->runHooks( get_class( $this ) );
219 if ( $hookResult ) {
220 $wgOut->addHTML( $hookResult );
221 } else {
222 $wgOut->addHTML( $this->getHTML() );
223 }
224
225 $wgOut->output();
226 } else {
227 header( 'Content-Type: text/html; charset=utf-8' );
228 echo "<!DOCTYPE html>\n" .
229 '<html><head>' .
230 '<title>' . htmlspecialchars( $this->getPageTitle() ) . '</title>' .
231 '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
232 "</head><body>\n";
233
234 $hookResult = $this->runHooks( get_class( $this ) . 'Raw' );
235 if ( $hookResult ) {
236 echo $hookResult;
237 } else {
238 echo $this->getHTML();
239 }
240
241 echo "</body></html>\n";
242 }
243 }
244
245 /**
246 * Output a report about the exception and takes care of formatting.
247 * It will be either HTML or plain text based on isCommandLine().
248 */
249 function report() {
250 global $wgMimeType;
251
252 MWExceptionHandler::logException( $this );
253
254 if ( defined( 'MW_API' ) ) {
255 // Unhandled API exception, we can't be sure that format printer is alive
256 header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
257 wfHttpError( 500, 'Internal Server Error', $this->getText() );
258 } elseif ( self::isCommandLine() ) {
259 MWExceptionHandler::printError( $this->getText() );
260 } else {
261 header( 'HTTP/1.1 500 MediaWiki exception' );
262 header( 'Status: 500 MediaWiki exception', true );
263 header( "Content-Type: $wgMimeType; charset=utf-8", true );
264
265 $this->reportHTML();
266 }
267 }
268
269 /**
270 * Check whether we are in command line mode or not to report the exception
271 * in the correct format.
272 *
273 * @return bool
274 */
275 static function isCommandLine() {
276 return !empty( $GLOBALS['wgCommandLineMode'] );
277 }
278 }
279
280 /**
281 * Exception class which takes an HTML error message, and does not
282 * produce a backtrace. Replacement for OutputPage::fatalError().
283 *
284 * @since 1.7
285 * @ingroup Exception
286 */
287 class FatalError extends MWException {
288
289 /**
290 * @return string
291 */
292 function getHTML() {
293 return $this->getMessage();
294 }
295
296 /**
297 * @return string
298 */
299 function getText() {
300 return $this->getMessage();
301 }
302 }
303
304 /**
305 * An error page which can definitely be safely rendered using the OutputPage.
306 *
307 * @since 1.7
308 * @ingroup Exception
309 */
310 class ErrorPageError extends MWException {
311 public $title, $msg, $params;
312
313 /**
314 * Note: these arguments are keys into wfMessage(), not text!
315 *
316 * @param string|Message $title Message key (string) for page title, or a Message object
317 * @param string|Message $msg Message key (string) for error text, or a Message object
318 * @param array $params with parameters to wfMessage()
319 */
320 function __construct( $title, $msg, $params = null ) {
321 $this->title = $title;
322 $this->msg = $msg;
323 $this->params = $params;
324
325 // Bug 44111: Messages in the log files should be in English and not
326 // customized by the local wiki. So get the default English version for
327 // passing to the parent constructor. Our overridden report() below
328 // makes sure that the page shown to the user is not forced to English.
329 if ( $msg instanceof Message ) {
330 $enMsg = clone( $msg );
331 } else {
332 $enMsg = wfMessage( $msg, $params );
333 }
334 $enMsg->inLanguage( 'en' )->useDatabase( false );
335 parent::__construct( $enMsg->text() );
336 }
337
338 function report() {
339 global $wgOut;
340
341 $wgOut->showErrorPage( $this->title, $this->msg, $this->params );
342 $wgOut->output();
343 }
344 }
345
346 /**
347 * Show an error page on a badtitle.
348 * Similar to ErrorPage, but emit a 400 HTTP error code to let mobile
349 * browser it is not really a valid content.
350 *
351 * @since 1.19
352 * @ingroup Exception
353 */
354 class BadTitleError extends ErrorPageError {
355 /**
356 * @param string|Message $msg A message key (default: 'badtitletext')
357 * @param array $params parameter to wfMessage()
358 */
359 function __construct( $msg = 'badtitletext', $params = null ) {
360 parent::__construct( 'badtitle', $msg, $params );
361 }
362
363 /**
364 * Just like ErrorPageError::report() but additionally set
365 * a 400 HTTP status code (bug 33646).
366 */
367 function report() {
368 global $wgOut;
369
370 // bug 33646: a badtitle error page need to return an error code
371 // to let mobile browser now that it is not a normal page.
372 $wgOut->setStatusCode( 400 );
373 parent::report();
374 }
375
376 }
377
378 /**
379 * Show an error when a user tries to do something they do not have the necessary
380 * permissions for.
381 *
382 * @since 1.18
383 * @ingroup Exception
384 */
385 class PermissionsError extends ErrorPageError {
386 public $permission, $errors;
387
388 function __construct( $permission, $errors = array() ) {
389 global $wgLang;
390
391 $this->permission = $permission;
392
393 if ( !count( $errors ) ) {
394 $groups = array_map(
395 array( 'User', 'makeGroupLinkWiki' ),
396 User::getGroupsWithPermission( $this->permission )
397 );
398
399 if ( $groups ) {
400 $errors[] = array( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
401 } else {
402 $errors[] = array( 'badaccess-group0' );
403 }
404 }
405
406 $this->errors = $errors;
407 }
408
409 function report() {
410 global $wgOut;
411
412 $wgOut->showPermissionsErrorPage( $this->errors, $this->permission );
413 $wgOut->output();
414 }
415 }
416
417 /**
418 * Show an error when the wiki is locked/read-only and the user tries to do
419 * something that requires write access.
420 *
421 * @since 1.18
422 * @ingroup Exception
423 */
424 class ReadOnlyError extends ErrorPageError {
425 public function __construct() {
426 parent::__construct(
427 'readonly',
428 'readonlytext',
429 wfReadOnlyReason()
430 );
431 }
432 }
433
434 /**
435 * Show an error when the user hits a rate limit.
436 *
437 * @since 1.18
438 * @ingroup Exception
439 */
440 class ThrottledError extends ErrorPageError {
441 public function __construct() {
442 parent::__construct(
443 'actionthrottled',
444 'actionthrottledtext'
445 );
446 }
447
448 public function report() {
449 global $wgOut;
450 $wgOut->setStatusCode( 503 );
451 parent::report();
452 }
453 }
454
455 /**
456 * Show an error when the user tries to do something whilst blocked.
457 *
458 * @since 1.18
459 * @ingroup Exception
460 */
461 class UserBlockedError extends ErrorPageError {
462 public function __construct( Block $block ) {
463 // @todo FIXME: Implement a more proper way to get context here.
464 $params = $block->getPermissionsError( RequestContext::getMain() );
465 parent::__construct( 'blockedtitle', array_shift( $params ), $params );
466 }
467 }
468
469 /**
470 * Shows a generic "user is not logged in" error page.
471 *
472 * This is essentially an ErrorPageError exception which by default uses the
473 * 'exception-nologin' as a title and 'exception-nologin-text' for the message.
474 * @see bug 37627
475 * @since 1.20
476 *
477 * @par Example:
478 * @code
479 * if( $user->isAnon() ) {
480 * throw new UserNotLoggedIn();
481 * }
482 * @endcode
483 *
484 * Note the parameter order differs from ErrorPageError, this allows you to
485 * simply specify a reason without overriding the default title.
486 *
487 * @par Example:
488 * @code
489 * if( $user->isAnon() ) {
490 * throw new UserNotLoggedIn( 'action-require-loggedin' );
491 * }
492 * @endcode
493 *
494 * @ingroup Exception
495 */
496 class UserNotLoggedIn extends ErrorPageError {
497
498 /**
499 * @param string $reasonMsg A message key containing the reason for the error.
500 * Optional, default: 'exception-nologin-text'
501 * @param string $titleMsg A message key to set the page title.
502 * Optional, default: 'exception-nologin'
503 * @param array $params Parameters to wfMessage().
504 * Optional, default: null
505 */
506 public function __construct(
507 $reasonMsg = 'exception-nologin-text',
508 $titleMsg = 'exception-nologin',
509 $params = null
510 ) {
511 parent::__construct( $titleMsg, $reasonMsg, $params );
512 }
513 }
514
515 /**
516 * Show an error that looks like an HTTP server error.
517 * Replacement for wfHttpError().
518 *
519 * @since 1.19
520 * @ingroup Exception
521 */
522 class HttpError extends MWException {
523 private $httpCode, $header, $content;
524
525 /**
526 * Constructor
527 *
528 * @param $httpCode Integer: HTTP status code to send to the client
529 * @param string|Message $content content of the message
530 * @param string|Message $header content of the header (\<title\> and \<h1\>)
531 */
532 public function __construct( $httpCode, $content, $header = null ) {
533 parent::__construct( $content );
534 $this->httpCode = (int)$httpCode;
535 $this->header = $header;
536 $this->content = $content;
537 }
538
539 /**
540 * Returns the HTTP status code supplied to the constructor.
541 *
542 * @return int
543 */
544 public function getStatusCode() {
545 return $this->httpCode;
546 }
547
548 /**
549 * Report the HTTP error.
550 * Sends the appropriate HTTP status code and outputs an
551 * HTML page with an error message.
552 */
553 public function report() {
554 $httpMessage = HttpStatus::getMessage( $this->httpCode );
555
556 header( "Status: {$this->httpCode} {$httpMessage}", true, $this->httpCode );
557 header( 'Content-type: text/html; charset=utf-8' );
558
559 print $this->getHTML();
560 }
561
562 /**
563 * Returns HTML for reporting the HTTP error.
564 * This will be a minimal but complete HTML document.
565 *
566 * @return string HTML
567 */
568 public function getHTML() {
569 if ( $this->header === null ) {
570 $header = HttpStatus::getMessage( $this->httpCode );
571 } elseif ( $this->header instanceof Message ) {
572 $header = $this->header->escaped();
573 } else {
574 $header = htmlspecialchars( $this->header );
575 }
576
577 if ( $this->content instanceof Message ) {
578 $content = $this->content->escaped();
579 } else {
580 $content = htmlspecialchars( $this->content );
581 }
582
583 return "<!DOCTYPE html>\n" .
584 "<html><head><title>$header</title></head>\n" .
585 "<body><h1>$header</h1><p>$content</p></body></html>\n";
586 }
587 }
588
589 /**
590 * Handler class for MWExceptions
591 * @ingroup Exception
592 */
593 class MWExceptionHandler {
594 /**
595 * Install an exception handler for MediaWiki exception types.
596 */
597 public static function installHandler() {
598 set_exception_handler( array( 'MWExceptionHandler', 'handle' ) );
599 }
600
601 /**
602 * Report an exception to the user
603 */
604 protected static function report( Exception $e ) {
605 global $wgShowExceptionDetails;
606
607 $cmdLine = MWException::isCommandLine();
608
609 if ( $e instanceof MWException ) {
610 try {
611 // Try and show the exception prettily, with the normal skin infrastructure
612 $e->report();
613 } catch ( Exception $e2 ) {
614 // Exception occurred from within exception handler
615 // Show a simpler error message for the original exception,
616 // don't try to invoke report()
617 $message = "MediaWiki internal error.\n\n";
618
619 if ( $wgShowExceptionDetails ) {
620 $message .= 'Original exception: ' . self::getLogMessage( $e ) .
621 "\nBacktrace:\n" . self::getRedactedTraceAsString( $e ) .
622 "\n\nException caught inside exception handler: " . self::getLogMessage( $e2 ) .
623 "\nBacktrace:\n" . self::getRedactedTraceAsString( $e2 );
624 } else {
625 $message .= "Exception caught inside exception handler.\n\n" .
626 "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " .
627 "to show detailed debugging information.";
628 }
629
630 $message .= "\n";
631
632 if ( $cmdLine ) {
633 self::printError( $message );
634 } else {
635 echo nl2br( htmlspecialchars( $message ) ) . "\n";
636 }
637 }
638 } else {
639 $message = "Unexpected non-MediaWiki exception encountered, of type \"" .
640 get_class( $e ) . "\"";
641
642 if ( $wgShowExceptionDetails ) {
643 $message .= "\n" . MWExceptionHandler::getLogMessage( $e ) . "\nBacktrace:\n" .
644 self::getRedactedTraceAsString( $e ) . "\n";
645 }
646
647 if ( $cmdLine ) {
648 self::printError( $message );
649 } else {
650 echo nl2br( htmlspecialchars( $message ) ) . "\n";
651 }
652 }
653 }
654
655 /**
656 * Print a message, if possible to STDERR.
657 * Use this in command line mode only (see isCommandLine)
658 *
659 * @param string $message Failure text
660 */
661 public static function printError( $message ) {
662 # NOTE: STDERR may not be available, especially if php-cgi is used from the
663 # command line (bug #15602). Try to produce meaningful output anyway. Using
664 # echo may corrupt output to STDOUT though.
665 if ( defined( 'STDERR' ) ) {
666 fwrite( STDERR, $message );
667 } else {
668 echo $message;
669 }
670 }
671
672 /**
673 * Exception handler which simulates the appropriate catch() handling:
674 *
675 * try {
676 * ...
677 * } catch ( MWException $e ) {
678 * $e->report();
679 * } catch ( Exception $e ) {
680 * echo $e->__toString();
681 * }
682 */
683 public static function handle( $e ) {
684 global $wgFullyInitialised;
685
686 self::report( $e );
687
688 // Final cleanup
689 if ( $wgFullyInitialised ) {
690 try {
691 // uses $wgRequest, hence the $wgFullyInitialised condition
692 wfLogProfilingData();
693 } catch ( Exception $e ) {
694 }
695 }
696
697 // Exit value should be nonzero for the benefit of shell jobs
698 exit( 1 );
699 }
700
701 /**
702 * Generate a string representation of an exception's stack trace
703 *
704 * Like Exception::getTraceAsString, but replaces argument values with
705 * argument type or class name.
706 *
707 * @param Exception $e
708 * @return string
709 */
710 public static function getRedactedTraceAsString( Exception $e ) {
711 $text = '';
712
713 foreach ( self::getRedactedTrace( $e ) as $level => $frame ) {
714 if ( isset( $frame['file'] ) && isset( $frame['line'] ) ) {
715 $text .= "#{$level} {$frame['file']}({$frame['line']}): ";
716 } else {
717 // 'file' and 'line' are unset for calls via call_user_func (bug 55634)
718 // This matches behaviour of Exception::getTraceAsString to instead
719 // display "[internal function]".
720 $text .= "#{$level} [internal function]: ";
721 }
722
723 if ( isset( $frame['class'] ) ) {
724 $text .= $frame['class'] . $frame['type'] . $frame['function'];
725 } else {
726 $text .= $frame['function'];
727 }
728
729 if ( isset( $frame['args'] ) ) {
730 $text .= '(' . implode( ', ', $frame['args'] ) . ")\n";
731 } else {
732 $text .= "()\n";
733 }
734 }
735
736 $level = $level + 1;
737 $text .= "#{$level} {main}";
738
739 return $text;
740 }
741
742 /**
743 * Return a copy of an exception's backtrace as an array.
744 *
745 * Like Exception::getTrace, but replaces each element in each frame's
746 * argument array with the name of its class (if the element is an object)
747 * or its type (if the element is a PHP primitive).
748 *
749 * @since 1.22
750 * @param Exception $e
751 * @return array
752 */
753 public static function getRedactedTrace( Exception $e ) {
754 return array_map( function ( $frame ) {
755 if ( isset( $frame['args'] ) ) {
756 $frame['args'] = array_map( function ( $arg ) {
757 return is_object( $arg ) ? get_class( $arg ) : gettype( $arg );
758 }, $frame['args'] );
759 }
760 return $frame;
761 }, $e->getTrace() );
762 }
763
764 /**
765 * Get the ID for this error.
766 *
767 * The ID is saved so that one can match the one output to the user (when
768 * $wgShowExceptionDetails is set to false), to the entry in the debug log.
769 *
770 * @since 1.22
771 * @param Exception $e
772 * @return string
773 */
774 public static function getLogId( Exception $e ) {
775 if ( !isset( $e->_mwLogId ) ) {
776 $e->_mwLogId = wfRandomString( 8 );
777 }
778 return $e->_mwLogId;
779 }
780
781 /**
782 * If the exception occurred in the course of responding to a request,
783 * returns the requested URL. Otherwise, returns false.
784 *
785 * @since 1.23
786 * @return string|bool
787 */
788 public static function getURL() {
789 global $wgRequest;
790 if ( !isset( $wgRequest ) || $wgRequest instanceof FauxRequest ) {
791 return false;
792 }
793 return $wgRequest->getRequestURL();
794 }
795
796 /**
797 * Return the requested URL and point to file and line number from which the
798 * exception occurred.
799 *
800 * @since 1.22
801 * @param Exception $e
802 * @return string
803 */
804 public static function getLogMessage( Exception $e ) {
805 $id = self::getLogId( $e );
806 $file = $e->getFile();
807 $line = $e->getLine();
808 $message = $e->getMessage();
809 $url = self::getURL() ?: '[no req]';
810
811 return "[$id] $url Exception from line $line of $file: $message";
812 }
813
814 /**
815 * Serialize an Exception object to JSON.
816 *
817 * The JSON object will have keys 'id', 'file', 'line', 'message', and
818 * 'url'. These keys map to string values, with the exception of 'line',
819 * which is a number, and 'url', which may be either a string URL or or
820 * null if the exception did not occur in the context of serving a web
821 * request.
822 *
823 * If $wgLogExceptionBacktrace is true, it will also have a 'backtrace'
824 * key, mapped to the array return value of Exception::getTrace, but with
825 * each element in each frame's "args" array (if set) replaced with the
826 * argument's class name (if the argument is an object) or type name (if
827 * the argument is a PHP primitive).
828 *
829 * @par Sample JSON record ($wgLogExceptionBacktrace = false):
830 * @code
831 * {
832 * "id": "c41fb419",
833 * "file": "/var/www/mediawiki/includes/cache/MessageCache.php",
834 * "line": 704,
835 * "message": "Non-string key given",
836 * "url": "/wiki/Main_Page"
837 * }
838 * @endcode
839 *
840 * @par Sample JSON record ($wgLogExceptionBacktrace = true):
841 * @code
842 * {
843 * "id": "dc457938",
844 * "file": "/vagrant/mediawiki/includes/cache/MessageCache.php",
845 * "line": 704,
846 * "message": "Non-string key given",
847 * "url": "/wiki/Main_Page",
848 * "backtrace": [{
849 * "file": "/vagrant/mediawiki/extensions/VisualEditor/VisualEditor.hooks.php",
850 * "line": 80,
851 * "function": "get",
852 * "class": "MessageCache",
853 * "type": "->",
854 * "args": ["array"]
855 * }]
856 * }
857 * @endcode
858 *
859 * @since 1.23
860 * @param Exception $e
861 * @param bool $pretty Add non-significant whitespace to improve readability (default: false).
862 * @param int $escaping Bitfield consisting of FormatJson::.*_OK class constants.
863 * @return string|bool: JSON string if successful; false upon failure
864 */
865 public static function jsonSerializeException( Exception $e, $pretty = false, $escaping = 0 ) {
866 global $wgLogExceptionBacktrace;
867
868 $exceptionData = array(
869 'id' => self::getLogId( $e ),
870 'file' => $e->getFile(),
871 'line' => $e->getLine(),
872 'message' => $e->getMessage(),
873 );
874
875 // Because MediaWiki is first and foremost a web application, we set a
876 // 'url' key unconditionally, but set it to null if the exception does
877 // not occur in the context of a web request, as a way of making that
878 // fact visible and explicit.
879 $exceptionData['url'] = self::getURL() ?: null;
880
881 if ( $wgLogExceptionBacktrace ) {
882 // Argument values may not be serializable, so redact them.
883 $exceptionData['backtrace'] = self::getRedactedTrace( $e );
884 }
885
886 return FormatJson::encode( $exceptionData, $pretty, $escaping );
887 }
888
889 /**
890 * Log an exception to the exception log (if enabled).
891 *
892 * This method must not assume the exception is an MWException,
893 * it is also used to handle PHP errors or errors from other libraries.
894 *
895 * @since 1.22
896 * @param Exception $e
897 */
898 public static function logException( Exception $e ) {
899 global $wgLogExceptionBacktrace;
900
901 if ( !( $e instanceof MWException ) || $e->isLoggable() ) {
902 $log = self::getLogMessage( $e );
903 if ( $wgLogExceptionBacktrace ) {
904 wfDebugLog( 'exception', $log . "\n" . $e->getTraceAsString() . "\n" );
905 } else {
906 wfDebugLog( 'exception', $log );
907 }
908
909 $json = self::jsonSerializeException( $e, false, FormatJson::ALL_OK );
910 if ( $json !== false ) {
911 wfDebugLog( 'exception-json', $json, false );
912 }
913 }
914
915 }
916
917 }