MWDebug.php 15 KB

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