MWDebug.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. /**
  3. * Debug toolbar related code.
  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. use MediaWiki\Logger\LegacyLogger;
  23. /**
  24. * New debugger system that outputs a toolbar on page view.
  25. *
  26. * By default, most methods do nothing ( self::$enabled = false ). You have
  27. * to explicitly call MWDebug::init() to enabled them.
  28. *
  29. * @since 1.19
  30. */
  31. class MWDebug {
  32. /**
  33. * Log lines
  34. *
  35. * @var array $log
  36. */
  37. protected static $log = [];
  38. /**
  39. * Debug messages from wfDebug().
  40. *
  41. * @var array $debug
  42. */
  43. protected static $debug = [];
  44. /**
  45. * SQL statements of the database queries.
  46. *
  47. * @var array $query
  48. */
  49. protected static $query = [];
  50. /**
  51. * Is the debugger enabled?
  52. *
  53. * @var bool $enabled
  54. */
  55. protected static $enabled = false;
  56. /**
  57. * Array of functions that have already been warned, formatted
  58. * function-caller to prevent a buttload of warnings
  59. *
  60. * @var array $deprecationWarnings
  61. */
  62. protected static $deprecationWarnings = [];
  63. /**
  64. * @internal For use by Setup.php only.
  65. */
  66. public static function setup() {
  67. global $wgDebugToolbar,
  68. $wgUseCdn, $wgUseFileCache, $wgCommandLineMode;
  69. if (
  70. // Easy to forget to falsify $wgDebugToolbar for static caches.
  71. // If file cache or CDN cache is on, just disable this (DWIMD).
  72. $wgUseCdn ||
  73. $wgUseFileCache ||
  74. // Keep MWDebug off on CLI. This prevents MWDebug from eating up
  75. // all the memory for logging SQL queries in maintenance scripts.
  76. $wgCommandLineMode
  77. ) {
  78. return;
  79. }
  80. if ( $wgDebugToolbar ) {
  81. self::init();
  82. }
  83. }
  84. /**
  85. * Enabled the debugger and load resource module.
  86. * This is called by Setup.php when $wgDebugToolbar is true.
  87. *
  88. * @since 1.19
  89. */
  90. public static function init() {
  91. self::$enabled = true;
  92. }
  93. /**
  94. * Disable the debugger.
  95. *
  96. * @since 1.28
  97. */
  98. public static function deinit() {
  99. self::$enabled = false;
  100. }
  101. /**
  102. * Add ResourceLoader modules to the OutputPage object if debugging is
  103. * enabled.
  104. *
  105. * @since 1.19
  106. * @param OutputPage $out
  107. */
  108. public static function addModules( OutputPage $out ) {
  109. if ( self::$enabled ) {
  110. $out->addModules( 'mediawiki.debug' );
  111. }
  112. }
  113. /**
  114. * Adds a line to the log
  115. *
  116. * @since 1.19
  117. * @param mixed $str
  118. */
  119. public static function log( $str ) {
  120. if ( !self::$enabled ) {
  121. return;
  122. }
  123. if ( !is_string( $str ) ) {
  124. $str = print_r( $str, true );
  125. }
  126. self::$log[] = [
  127. 'msg' => htmlspecialchars( $str ),
  128. 'type' => 'log',
  129. 'caller' => wfGetCaller(),
  130. ];
  131. }
  132. /**
  133. * Returns internal log array
  134. * @since 1.19
  135. * @return array
  136. */
  137. public static function getLog() {
  138. return self::$log;
  139. }
  140. /**
  141. * Clears internal log array and deprecation tracking
  142. * @since 1.19
  143. */
  144. public static function clearLog() {
  145. self::$log = [];
  146. self::$deprecationWarnings = [];
  147. }
  148. /**
  149. * Adds a warning entry to the log
  150. *
  151. * @since 1.19
  152. * @param string $msg
  153. * @param int $callerOffset
  154. * @param int $level A PHP error level. See sendMessage()
  155. * @param string $log 'production' will always trigger a php error, 'auto'
  156. * will trigger an error if $wgDevelopmentWarnings is true, and 'debug'
  157. * will only write to the debug log(s).
  158. */
  159. public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
  160. global $wgDevelopmentWarnings;
  161. if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
  162. $log = 'debug';
  163. }
  164. if ( $log === 'debug' ) {
  165. $level = false;
  166. }
  167. $callerDescription = self::getCallerDescription( $callerOffset );
  168. self::sendMessage( $msg, $callerDescription, 'warning', $level );
  169. if ( self::$enabled ) {
  170. self::$log[] = [
  171. 'msg' => htmlspecialchars( $msg ),
  172. 'type' => 'warn',
  173. 'caller' => $callerDescription['func'],
  174. ];
  175. }
  176. }
  177. /**
  178. * Show a warning that $function is deprecated.
  179. * This will send it to the following locations:
  180. * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
  181. * is set to true.
  182. * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
  183. * is set to true.
  184. * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
  185. *
  186. * @since 1.19
  187. * @param string $function Function that is deprecated.
  188. * @param string|bool $version Version in which the function was deprecated.
  189. * @param string|bool $component Component to which the function belongs.
  190. * If false, it is assumed the function is in MediaWiki core.
  191. * @param int $callerOffset How far up the callstack is the original
  192. * caller. 2 = function that called the function that called
  193. * MWDebug::deprecated() (Added in 1.20).
  194. */
  195. public static function deprecated( $function, $version = false,
  196. $component = false, $callerOffset = 2
  197. ) {
  198. $callerDescription = self::getCallerDescription( $callerOffset );
  199. $callerFunc = $callerDescription['func'];
  200. $sendToLog = true;
  201. // Check to see if there already was a warning about this function
  202. if ( isset( self::$deprecationWarnings[$function][$callerFunc] ) ) {
  203. return;
  204. } elseif ( isset( self::$deprecationWarnings[$function] ) ) {
  205. if ( self::$enabled ) {
  206. $sendToLog = false;
  207. } else {
  208. return;
  209. }
  210. }
  211. self::$deprecationWarnings[$function][$callerFunc] = true;
  212. if ( $version ) {
  213. global $wgDeprecationReleaseLimit;
  214. if ( $wgDeprecationReleaseLimit && $component === false ) {
  215. # Strip -* off the end of $version so that branches can use the
  216. # format #.##-branchname to avoid issues if the branch is merged into
  217. # a version of MediaWiki later than what it was branched from
  218. $comparableVersion = preg_replace( '/-.*$/', '', $version );
  219. # If the comparableVersion is larger than our release limit then
  220. # skip the warning message for the deprecation
  221. if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
  222. $sendToLog = false;
  223. }
  224. }
  225. $component = $component === false ? 'MediaWiki' : $component;
  226. $msg = "Use of $function was deprecated in $component $version.";
  227. } else {
  228. $msg = "Use of $function is deprecated.";
  229. }
  230. if ( $sendToLog ) {
  231. global $wgDevelopmentWarnings; // we could have a more specific $wgDeprecationWarnings setting.
  232. self::sendMessage(
  233. $msg,
  234. $callerDescription,
  235. 'deprecated',
  236. $wgDevelopmentWarnings ? E_USER_DEPRECATED : false
  237. );
  238. }
  239. if ( self::$enabled ) {
  240. $logMsg = htmlspecialchars( $msg ) .
  241. Html::rawElement( 'div', [ 'class' => 'mw-debug-backtrace' ],
  242. Html::element( 'span', [], 'Backtrace:' ) . wfBacktrace()
  243. );
  244. self::$log[] = [
  245. 'msg' => $logMsg,
  246. 'type' => 'deprecated',
  247. 'caller' => $callerFunc,
  248. ];
  249. }
  250. }
  251. /**
  252. * Get an array describing the calling function at a specified offset.
  253. *
  254. * @param int $callerOffset How far up the callstack is the original
  255. * caller. 0 = function that called getCallerDescription()
  256. * @return array Array with two keys: 'file' and 'func'
  257. */
  258. private static function getCallerDescription( $callerOffset ) {
  259. $callers = wfDebugBacktrace();
  260. if ( isset( $callers[$callerOffset] ) ) {
  261. $callerfile = $callers[$callerOffset];
  262. if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
  263. $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
  264. } else {
  265. $file = '(internal function)';
  266. }
  267. } else {
  268. $file = '(unknown location)';
  269. }
  270. if ( isset( $callers[$callerOffset + 1] ) ) {
  271. $callerfunc = $callers[$callerOffset + 1];
  272. $func = '';
  273. if ( isset( $callerfunc['class'] ) ) {
  274. $func .= $callerfunc['class'] . '::';
  275. }
  276. if ( isset( $callerfunc['function'] ) ) {
  277. $func .= $callerfunc['function'];
  278. }
  279. } else {
  280. $func = 'unknown';
  281. }
  282. return [ 'file' => $file, 'func' => $func ];
  283. }
  284. /**
  285. * Send a message to the debug log and optionally also trigger a PHP
  286. * error, depending on the $level argument.
  287. *
  288. * @param string $msg Message to send
  289. * @param array $caller Caller description get from getCallerDescription()
  290. * @param string $group Log group on which to send the message
  291. * @param int|bool $level Error level to use; set to false to not trigger an error
  292. */
  293. private static function sendMessage( $msg, $caller, $group, $level ) {
  294. $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
  295. if ( $level !== false ) {
  296. trigger_error( $msg, $level );
  297. }
  298. wfDebugLog( $group, $msg, 'private' );
  299. }
  300. /**
  301. * This is a method to pass messages from wfDebug to the pretty debugger.
  302. * Do NOT use this method, use MWDebug::log or wfDebug()
  303. *
  304. * @since 1.19
  305. * @param string $str
  306. * @param array $context
  307. */
  308. public static function debugMsg( $str, $context = [] ) {
  309. global $wgDebugComments, $wgShowDebug;
  310. if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
  311. if ( $context ) {
  312. $prefix = '';
  313. if ( isset( $context['prefix'] ) ) {
  314. $prefix = $context['prefix'];
  315. } elseif ( isset( $context['channel'] ) && $context['channel'] !== 'wfDebug' ) {
  316. $prefix = "[{$context['channel']}] ";
  317. }
  318. if ( isset( $context['seconds_elapsed'] ) && isset( $context['memory_used'] ) ) {
  319. $prefix .= "{$context['seconds_elapsed']} {$context['memory_used']} ";
  320. }
  321. $str = LegacyLogger::interpolate( $str, $context );
  322. $str = $prefix . $str;
  323. }
  324. self::$debug[] = rtrim( UtfNormal\Validator::cleanUp( $str ) );
  325. }
  326. }
  327. /**
  328. * Begins profiling on a database query
  329. *
  330. * @since 1.19
  331. * @param string $sql
  332. * @param string $function
  333. * @param float $runTime Query run time
  334. * @param string $dbhost
  335. * @return bool True if debugger is enabled, false otherwise
  336. */
  337. public static function query( $sql, $function, $runTime, $dbhost ) {
  338. if ( !self::$enabled ) {
  339. return false;
  340. }
  341. // Replace invalid UTF-8 chars with a square UTF-8 character
  342. // This prevents json_encode from erroring out due to binary SQL data
  343. $sql = preg_replace(
  344. '/(
  345. [\xC0-\xC1] # Invalid UTF-8 Bytes
  346. | [\xF5-\xFF] # Invalid UTF-8 Bytes
  347. | \xE0[\x80-\x9F] # Overlong encoding of prior code point
  348. | \xF0[\x80-\x8F] # Overlong encoding of prior code point
  349. | [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
  350. | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
  351. | [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
  352. | (?<=[\x0-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
  353. | (?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF4]
  354. | [\xF0-\xF4][\x80-\xBF]|[\xF0-\xF4][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
  355. | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
  356. | (?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
  357. | (?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
  358. )/x',
  359. '■',
  360. $sql
  361. );
  362. // last check for invalid utf8
  363. $sql = UtfNormal\Validator::cleanUp( $sql );
  364. self::$query[] = [
  365. 'sql' => "$dbhost: $sql",
  366. 'function' => $function,
  367. 'time' => $runTime,
  368. ];
  369. return true;
  370. }
  371. /**
  372. * Returns a list of files included, along with their size
  373. *
  374. * @param IContextSource $context
  375. * @return array
  376. */
  377. protected static function getFilesIncluded( IContextSource $context ) {
  378. $files = get_included_files();
  379. $fileList = [];
  380. foreach ( $files as $file ) {
  381. $size = filesize( $file );
  382. $fileList[] = [
  383. 'name' => $file,
  384. 'size' => $context->getLanguage()->formatSize( $size ),
  385. ];
  386. }
  387. return $fileList;
  388. }
  389. /**
  390. * Returns the HTML to add to the page for the toolbar
  391. *
  392. * @since 1.19
  393. * @param IContextSource $context
  394. * @return string
  395. */
  396. public static function getDebugHTML( IContextSource $context ) {
  397. global $wgDebugComments;
  398. $html = '';
  399. if ( self::$enabled ) {
  400. self::log( 'MWDebug output complete' );
  401. $debugInfo = self::getDebugInfo( $context );
  402. // Cannot use OutputPage::addJsConfigVars because those are already outputted
  403. // by the time this method is called.
  404. $html = ResourceLoader::makeInlineScript(
  405. ResourceLoader::makeConfigSetScript( [ 'debugInfo' => $debugInfo ] ),
  406. $context->getOutput()->getCSPNonce()
  407. );
  408. }
  409. if ( $wgDebugComments ) {
  410. $html .= "<!-- Debug output:\n" .
  411. htmlspecialchars( implode( "\n", self::$debug ), ENT_NOQUOTES ) .
  412. "\n\n-->";
  413. }
  414. return $html;
  415. }
  416. /**
  417. * Generate debug log in HTML for displaying at the bottom of the main
  418. * content area.
  419. * If $wgShowDebug is false, an empty string is always returned.
  420. *
  421. * @since 1.20
  422. * @return string HTML fragment
  423. */
  424. public static function getHTMLDebugLog() {
  425. global $wgShowDebug;
  426. if ( !$wgShowDebug ) {
  427. return '';
  428. }
  429. $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n";
  430. foreach ( self::$debug as $line ) {
  431. $display = nl2br( htmlspecialchars( trim( $line ) ) );
  432. $ret .= "<li><code>$display</code></li>\n";
  433. }
  434. $ret .= '</ul>' . "\n";
  435. return $ret;
  436. }
  437. /**
  438. * Append the debug info to given ApiResult
  439. *
  440. * @param IContextSource $context
  441. * @param ApiResult $result
  442. */
  443. public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
  444. if ( !self::$enabled ) {
  445. return;
  446. }
  447. // output errors as debug info, when display_errors is on
  448. // this is necessary for all non html output of the api, because that clears all errors first
  449. $obContents = ob_get_contents();
  450. if ( $obContents ) {
  451. $obContentArray = explode( '<br />', $obContents );
  452. foreach ( $obContentArray as $obContent ) {
  453. if ( trim( $obContent ) ) {
  454. self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
  455. }
  456. }
  457. }
  458. self::log( 'MWDebug output complete' );
  459. $debugInfo = self::getDebugInfo( $context );
  460. ApiResult::setIndexedTagName( $debugInfo, 'debuginfo' );
  461. ApiResult::setIndexedTagName( $debugInfo['log'], 'line' );
  462. ApiResult::setIndexedTagName( $debugInfo['debugLog'], 'msg' );
  463. ApiResult::setIndexedTagName( $debugInfo['queries'], 'query' );
  464. ApiResult::setIndexedTagName( $debugInfo['includes'], 'queries' );
  465. $result->addValue( null, 'debuginfo', $debugInfo );
  466. }
  467. /**
  468. * Returns the HTML to add to the page for the toolbar
  469. *
  470. * @param IContextSource $context
  471. * @return array
  472. */
  473. public static function getDebugInfo( IContextSource $context ) {
  474. if ( !self::$enabled ) {
  475. return [];
  476. }
  477. global $wgVersion;
  478. $request = $context->getRequest();
  479. // HHVM's reported memory usage from memory_get_peak_usage()
  480. // is not useful when passing false, but we continue passing
  481. // false for consistency of historical data in zend.
  482. // see: https://github.com/facebook/hhvm/issues/2257#issuecomment-39362246
  483. $realMemoryUsage = wfIsHHVM();
  484. $branch = GitInfo::currentBranch();
  485. if ( GitInfo::isSHA1( $branch ) ) {
  486. // If it's a detached HEAD, the SHA1 will already be
  487. // included in the MW version, so don't show it.
  488. $branch = false;
  489. }
  490. return [
  491. 'mwVersion' => $wgVersion,
  492. 'phpEngine' => wfIsHHVM() ? 'HHVM' : 'PHP',
  493. 'phpVersion' => wfIsHHVM() ? HHVM_VERSION : PHP_VERSION,
  494. 'gitRevision' => GitInfo::headSHA1(),
  495. 'gitBranch' => $branch,
  496. 'gitViewUrl' => GitInfo::headViewUrl(),
  497. 'time' => $request->getElapsedTime(),
  498. 'log' => self::$log,
  499. 'debugLog' => self::$debug,
  500. 'queries' => self::$query,
  501. 'request' => [
  502. 'method' => $request->getMethod(),
  503. 'url' => $request->getRequestURL(),
  504. 'headers' => $request->getAllHeaders(),
  505. 'params' => $request->getValues(),
  506. ],
  507. 'memory' => $context->getLanguage()->formatSize( memory_get_usage( $realMemoryUsage ) ),
  508. 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage( $realMemoryUsage ) ),
  509. 'includes' => self::getFilesIncluded( $context ),
  510. ];
  511. }
  512. }