MWException.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. * MediaWiki exception
  22. *
  23. * @ingroup Exception
  24. */
  25. class MWException extends Exception {
  26. /**
  27. * Should the exception use $wgOut to output the error?
  28. *
  29. * @return bool
  30. */
  31. public function useOutputPage() {
  32. return $this->useMessageCache() &&
  33. !empty( $GLOBALS['wgFullyInitialised'] ) &&
  34. !empty( $GLOBALS['wgOut'] ) &&
  35. !defined( 'MEDIAWIKI_INSTALL' );
  36. }
  37. /**
  38. * Whether to log this exception in the exception debug log.
  39. *
  40. * @since 1.23
  41. * @return bool
  42. */
  43. public function isLoggable() {
  44. return true;
  45. }
  46. /**
  47. * Can the extension use the Message class/wfMessage to get i18n-ed messages?
  48. *
  49. * @return bool
  50. */
  51. public function useMessageCache() {
  52. global $wgLang;
  53. foreach ( $this->getTrace() as $frame ) {
  54. if ( isset( $frame['class'] ) && $frame['class'] === LocalisationCache::class ) {
  55. return false;
  56. }
  57. }
  58. return $wgLang instanceof Language;
  59. }
  60. /**
  61. * Get a message from i18n
  62. *
  63. * @param string $key Message name
  64. * @param string $fallback Default message if the message cache can't be
  65. * called by the exception
  66. * @param mixed ...$params To pass to wfMessage()
  67. * @return string Message with arguments replaced
  68. */
  69. public function msg( $key, $fallback, ...$params ) {
  70. global $wgSitename;
  71. // FIXME: Keep logic in sync with MWExceptionRenderer::msg.
  72. $res = false;
  73. if ( $this->useMessageCache() ) {
  74. try {
  75. $res = wfMessage( $key, ...$params )->text();
  76. } catch ( Exception $e ) {
  77. }
  78. }
  79. if ( $res === false ) {
  80. $res = wfMsgReplaceArgs( $fallback, $params );
  81. // If an exception happens inside message rendering,
  82. // {{SITENAME}} sometimes won't be replaced.
  83. $res = strtr( $res, [
  84. '{{SITENAME}}' => $wgSitename,
  85. ] );
  86. }
  87. return $res;
  88. }
  89. /**
  90. * If $wgShowExceptionDetails is true, return a HTML message with a
  91. * backtrace to the error, otherwise show a message to ask to set it to true
  92. * to show that information.
  93. *
  94. * @return string Html to output
  95. */
  96. public function getHTML() {
  97. global $wgShowExceptionDetails;
  98. if ( $wgShowExceptionDetails ) {
  99. return '<p>' . nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $this ) ) ) .
  100. '</p><p>Backtrace:</p><p>' .
  101. nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $this ) ) ) .
  102. "</p>\n";
  103. } else {
  104. $logId = WebRequest::getRequestId();
  105. $type = static::class;
  106. return Html::errorBox(
  107. htmlspecialchars(
  108. '[' . $logId . '] ' .
  109. gmdate( 'Y-m-d H:i:s' ) . ": " .
  110. $this->msg( "internalerror-fatal-exception",
  111. "Fatal exception of type $1",
  112. $type,
  113. $logId,
  114. MWExceptionHandler::getURL()
  115. )
  116. ) ) .
  117. "<!-- Set \$wgShowExceptionDetails = true; " .
  118. "at the bottom of LocalSettings.php to show detailed " .
  119. "debugging information. -->";
  120. }
  121. }
  122. /**
  123. * Get the text to display when reporting the error on the command line.
  124. * If $wgShowExceptionDetails is true, return a text message with a
  125. * backtrace to the error.
  126. *
  127. * @return string
  128. */
  129. public function getText() {
  130. global $wgShowExceptionDetails;
  131. if ( $wgShowExceptionDetails ) {
  132. return MWExceptionHandler::getLogMessage( $this ) .
  133. "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $this ) . "\n";
  134. } else {
  135. return "Set \$wgShowExceptionDetails = true; " .
  136. "in LocalSettings.php to show detailed debugging information.\n";
  137. }
  138. }
  139. /**
  140. * Return the title of the page when reporting this error in a HTTP response.
  141. *
  142. * @return string
  143. */
  144. public function getPageTitle() {
  145. return $this->msg( 'internalerror', 'Internal error' );
  146. }
  147. /**
  148. * Output the exception report using HTML.
  149. */
  150. public function reportHTML() {
  151. global $wgOut, $wgSitename;
  152. if ( $this->useOutputPage() ) {
  153. $wgOut->prepareErrorPage( $this->getPageTitle() );
  154. // Manually set the html title, since sometimes
  155. // {{SITENAME}} does not get replaced for exceptions
  156. // happening inside message rendering.
  157. $wgOut->setHTMLTitle(
  158. $this->msg(
  159. 'pagetitle',
  160. "$1 - $wgSitename",
  161. $this->getPageTitle()
  162. )
  163. );
  164. $wgOut->addHTML( $this->getHTML() );
  165. $wgOut->output();
  166. } else {
  167. self::header( 'Content-Type: text/html; charset=utf-8' );
  168. echo "<!DOCTYPE html>\n" .
  169. '<html><head>' .
  170. // Mimick OutputPage::setPageTitle behaviour
  171. '<title>' .
  172. htmlspecialchars( $this->msg( 'pagetitle', "$1 - $wgSitename", $this->getPageTitle() ) ) .
  173. '</title>' .
  174. '<style>body { font-family: sans-serif; margin: 0; padding: 0.5em 2em; }</style>' .
  175. "</head><body>\n";
  176. echo $this->getHTML();
  177. echo "</body></html>\n";
  178. }
  179. }
  180. /**
  181. * Output a report about the exception and takes care of formatting.
  182. * It will be either HTML or plain text based on isCommandLine().
  183. */
  184. public function report() {
  185. global $wgMimeType;
  186. if ( defined( 'MW_API' ) ) {
  187. // Unhandled API exception, we can't be sure that format printer is alive
  188. self::header( 'MediaWiki-API-Error: internal_api_error_' . static::class );
  189. wfHttpError( 500, 'Internal Server Error', $this->getText() );
  190. } elseif ( self::isCommandLine() ) {
  191. $message = $this->getText();
  192. $this->writeToCommandLine( $message );
  193. } else {
  194. self::statusHeader( 500 );
  195. self::header( "Content-Type: $wgMimeType; charset=utf-8" );
  196. $this->reportHTML();
  197. }
  198. }
  199. /**
  200. * Write a message to stderr falling back to stdout if stderr unavailable
  201. *
  202. * @param string $message
  203. * @suppress SecurityCheck-XSS
  204. */
  205. private function writeToCommandLine( $message ) {
  206. // T17602: STDERR may not be available
  207. if ( !defined( 'MW_PHPUNIT_TEST' ) && defined( 'STDERR' ) ) {
  208. fwrite( STDERR, $message );
  209. } else {
  210. echo $message;
  211. }
  212. }
  213. /**
  214. * Check whether we are in command line mode or not to report the exception
  215. * in the correct format.
  216. *
  217. * @return bool
  218. */
  219. public static function isCommandLine() {
  220. return !empty( $GLOBALS['wgCommandLineMode'] );
  221. }
  222. /**
  223. * Send a header, if we haven't already sent them. We shouldn't,
  224. * but sometimes we might in a weird case like Export
  225. * @param string $header
  226. */
  227. private static function header( $header ) {
  228. if ( !headers_sent() ) {
  229. header( $header );
  230. }
  231. }
  232. private static function statusHeader( $code ) {
  233. if ( !headers_sent() ) {
  234. HttpStatus::header( $code );
  235. }
  236. }
  237. }