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