Debian Codegraph @

includes/debug/MWDebug.php

raw symbols SCIP
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 namespace MediaWiki\Debug;
22
23 use LogicException;
24 use MediaWiki\Api\ApiResult;
25 use MediaWiki\Context\IContextSource;
26 use MediaWiki\Html\Html;
27 use MediaWiki\Logger\LegacyLogger;
28 use MediaWiki\Output\OutputPage;
29 use MediaWiki\Parser\Sanitizer;
30 use MediaWiki\ResourceLoader\ResourceLoader;
31 use MediaWiki\Utils\GitInfo;
32 use ReflectionMethod;
33 use UtfNormal;
34 use Wikimedia\WrappedString;
35 use Wikimedia\WrappedStringList;
36
37 /**
38 * Debug toolbar.
39 *
40 * By default most of these methods do nothing, as enforced by self::$enabled = false.
41 *
42 * To enable the debug toolbar, use $wgDebugToolbar = true in LocalSettings.php.
43 * That ensures MWDebug::init() is called from Setup.php.
44 *
45 * @since 1.19
46 * @ingroup Debug
47 */
48 class MWDebug {
49 /**
50 * Log lines
51 *
52 * @var array
53 */
54 protected static $log = [];
55
56 /**
57 * Debug messages from wfDebug().
58 *
59 * @var array
60 */
61 protected static $debug = [];
62
63 /**
64 * SQL statements of the database queries.
65 *
66 * @var array
67 */
68 protected static $query = [];
69
70 /**
71 * Is the debugger enabled?
72 *
73 * @var bool
74 */
75 protected static $enabled = false;
76
77 /**
78 * Array of functions that have already been warned, formatted
79 * function-caller to prevent a buttload of warnings
80 *
81 * @var array
82 */
83 protected static $deprecationWarnings = [];
84
85 /**
86 * @var array Keys are regexes, values are optional callbacks to call if the filter is hit
87 */
88 protected static $deprecationFilters = [];
89
90 /**
91 * @internal For use by Setup.php only.
92 */
93 public static function setup() {
94 global $wgDebugToolbar,
95 $wgUseCdn, $wgUseFileCache;
96
97 if (
98 // Easy to forget to falsify $wgDebugToolbar for static caches.
99 // If file cache or CDN cache is on, just disable this (DWIMD).
100 $wgUseCdn ||
101 $wgUseFileCache ||
102 // Keep MWDebug off on CLI. This prevents MWDebug from eating up
103 // all the memory for logging SQL queries in maintenance scripts.
104 MW_ENTRY_POINT === 'cli'
105 ) {
106 return;
107 }
108
109 if ( $wgDebugToolbar ) {
110 self::init();
111 }
112 }
113
114 /**
115 * Enabled the debugger and load resource module.
116 * This is called by Setup.php when $wgDebugToolbar is true.
117 *
118 * @since 1.19
119 */
120 public static function init() {
121 self::$enabled = true;
122 }
123
124 /**
125 * Disable the debugger.
126 *
127 * @since 1.28
128 */
129 public static function deinit() {
130 self::$enabled = false;
131 }
132
133 /**
134 * Add ResourceLoader modules to the OutputPage object if debugging is
135 * enabled.
136 *
137 * @since 1.19
138 * @param OutputPage $out
139 */
140 public static function addModules( OutputPage $out ) {
141 if ( self::$enabled ) {
142 $out->addModules( 'mediawiki.debug' );
143 }
144 }
145
146 /**
147 * Adds a line to the log
148 *
149 * @since 1.19
150 * @param mixed $str
151 */
152 public static function log( $str ) {
153 if ( !self::$enabled ) {
154 return;
155 }
156 if ( !is_string( $str ) ) {
157 $str = print_r( $str, true );
158 }
159 self::$log[] = [
160 'msg' => htmlspecialchars( $str ),
161 'type' => 'log',
162 'caller' => wfGetCaller(),
163 ];
164 }
165
166 /**
167 * Returns internal log array
168 * @since 1.19
169 * @return array
170 */
171 public static function getLog() {
172 return self::$log;
173 }
174
175 /**
176 * Clears internal log array and deprecation tracking
177 * @since 1.19
178 */
179 public static function clearLog() {
180 self::$log = [];
181 self::$deprecationWarnings = [];
182 }
183
184 /**
185 * Adds a warning entry to the log
186 *
187 * @since 1.19
188 * @param string $msg
189 * @param int $callerOffset
190 * @param int $level A PHP error level. See sendMessage()
191 * @param string $log 'production' will always trigger a php error, 'auto'
192 * will trigger an error if $wgDevelopmentWarnings is true, and 'debug'
193 * will only write to the debug log(s).
194 */
195 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
196 global $wgDevelopmentWarnings;
197
198 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
199 $log = 'debug';
200 }
201
202 if ( $log === 'debug' ) {
203 $level = false;
204 }
205
206 $callerDescription = self::getCallerDescription( $callerOffset );
207
208 self::sendMessage(
209 self::formatCallerDescription( $msg, $callerDescription ),
210 'warning',
211 $level );
212 }
213
214 /**
215 * Show a warning that $function is deprecated.
216 *
217 * @see deprecatedMsg()
218 * @since 1.19
219 *
220 * @param string $function Function that is deprecated.
221 * @param string|false $version Version in which the function was deprecated.
222 * @param string|bool $component Component to which the function belongs.
223 * If false, it is assumed the function is in MediaWiki core.
224 * @param int $callerOffset How far up the callstack is the original
225 * caller. 2 = function that called the function that called
226 * MWDebug::deprecated() (Added in 1.20).
227 */
228 public static function deprecated( $function, $version = false,
229 $component = false, $callerOffset = 2
230 ) {
231 if ( $version ) {
232 $component = $component ?: 'MediaWiki';
233 $msg = "Use of $function was deprecated in $component $version.";
234 } else {
235 $msg = "Use of $function is deprecated.";
236 }
237 self::deprecatedMsg( $msg, $version, $component, $callerOffset + 1 );
238 }
239
240 /**
241 * Show a warning if $method declared in $class is overridden in $instance.
242 *
243 * @since 1.36
244 * @see deprecatedMsg()
245 *
246 * phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
247 * @param object $instance Object on which to detect deprecated overrides (typically $this).
248 * @param string $class Class declaring the deprecated method (typically __CLASS__ )
249 * @param string $method The name of the deprecated method.
250 * @param string|false $version Version in which the method was deprecated.
251 * Does not issue deprecation warnings if false.
252 * @param string|bool $component Component to which the class belongs.
253 * If false, it is assumed the class is in MediaWiki core.
254 * @param int $callerOffset How far up the callstack is the original
255 * caller. 2 = function that called the function that called
256 * MWDebug::detectDeprecatedOverride()
257 *
258 * @return bool True if the method was overridden, false otherwise. If the method
259 * was overridden, it should be called. The deprecated method's default
260 * implementation should call MWDebug::deprecated().
261 */
262 public static function detectDeprecatedOverride( $instance, $class, $method, $version = false,
263 $component = false, $callerOffset = 2
264 ) {
265 $reflectionMethod = new ReflectionMethod( $instance, $method );
266 $declaringClass = $reflectionMethod->getDeclaringClass()->getName();
267
268 if ( $declaringClass === $class ) {
269 // not overridden, nothing to do
270 return false;
271 }
272
273 if ( $version ) {
274 $component = $component ?: 'MediaWiki';
275 $msg = "$declaringClass overrides $method which was deprecated in $component $version.";
276 self::deprecatedMsg( $msg, $version, $component, $callerOffset + 1 );
277 }
278
279 return true;
280 }
281
282 /**
283 * Log a deprecation warning with arbitrary message text. A caller
284 * description will be appended. If the message has already been sent for
285 * this caller, it won't be sent again.
286 *
287 * Although there are component and version parameters, they are not
288 * automatically appended to the message. The message text should include
289 * information about when the thing was deprecated.
290 *
291 * The warning will be sent to the following locations:
292 * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
293 * is set to true.
294 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
295 * is set to true. This is the case in phpunit tests by default, and will
296 * cause tests to fail.
297 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
298 *
299 * @since 1.35
300 *
301 * @param string $msg The message
302 * @param string|false $version Version of MediaWiki that the function
303 * was deprecated in.
304 * @param string|bool $component Component to which the function belongs.
305 * If false, it is assumed the function is in MediaWiki core.
306 * @param int|false $callerOffset How far up the call stack is the original
307 * caller. 2 = function that called the function that called us. If false,
308 * the caller description will not be appended.
309 */
310 public static function deprecatedMsg( $msg, $version = false,
311 $component = false, $callerOffset = 2
312 ) {
313 if ( $callerOffset === false ) {
314 $callerFunc = '';
315 $rawMsg = $msg;
316 } else {
317 $callerDescription = self::getCallerDescription( $callerOffset );
318 $callerFunc = $callerDescription['func'];
319 $rawMsg = self::formatCallerDescription( $msg, $callerDescription );
320 }
321
322 $sendToLog = true;
323
324 // Check to see if there already was a warning about this function
325 if ( isset( self::$deprecationWarnings[$msg][$callerFunc] ) ) {
326 return;
327 } elseif ( isset( self::$deprecationWarnings[$msg] ) ) {
328 if ( self::$enabled ) {
329 $sendToLog = false;
330 } else {
331 return;
332 }
333 }
334
335 self::$deprecationWarnings[$msg][$callerFunc] = true;
336
337 if ( $version ) {
338 global $wgDeprecationReleaseLimit;
339
340 $component = $component ?: 'MediaWiki';
341 if ( $wgDeprecationReleaseLimit && $component === 'MediaWiki' ) {
342 # Strip -* off the end of $version so that branches can use the
343 # format #.##-branchname to avoid issues if the branch is merged into
344 # a version of MediaWiki later than what it was branched from
345 $comparableVersion = preg_replace( '/-.*$/', '', $version );
346
347 # If the comparableVersion is larger than our release limit then
348 # skip the warning message for the deprecation
349 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
350 $sendToLog = false;
351 }
352 }
353 }
354
355 self::sendRawDeprecated(
356 $rawMsg,
357 $sendToLog,
358 $callerFunc
359 );
360 }
361
362 /**
363 * Send a raw deprecation message to the log and the debug toolbar,
364 * without filtering of duplicate messages. A caller description will
365 * not be appended.
366 *
367 * @param string $msg The complete message including relevant caller information.
368 * @param bool $sendToLog If true, the message will be sent to the debug
369 * toolbar, the debug log, and raised as a warning to PHP. If false, the message
370 * will only be sent to the debug toolbar.
371 * @param string $callerFunc The caller, for display in the debug toolbar's
372 * caller column.
373 */
374 public static function sendRawDeprecated( $msg, $sendToLog = true, $callerFunc = '' ) {
375 foreach ( self::$deprecationFilters as $filter => $callback ) {
376 if ( preg_match( $filter, $msg ) ) {
377 if ( is_callable( $callback ) ) {
378 $callback();
379 }
380 return;
381 }
382 }
383
384 if ( $sendToLog ) {
385 trigger_error( $msg, E_USER_DEPRECATED );
386 }
387 }
388
389 /**
390 * Deprecation messages matching the supplied regex will be suppressed.
391 * Use this to filter deprecation warnings when testing deprecated code.
392 *
393 * @param string $regex
394 * @param ?callable $callback To call if $regex is hit
395 */
396 public static function filterDeprecationForTest(
397 string $regex, ?callable $callback = null
398 ): void {
399 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
400 throw new LogicException( __METHOD__ . ' can only be used in tests' );
401 }
402 self::$deprecationFilters[$regex] = $callback;
403 }
404
405 /**
406 * Clear all deprecation filters.
407 */
408 public static function clearDeprecationFilters() {
409 self::$deprecationFilters = [];
410 }
411
412 /**
413 * Get an array describing the calling function at a specified offset.
414 *
415 * @param int $callerOffset How far up the callstack is the original
416 * caller. 0 = function that called getCallerDescription()
417 * @return array Array with two keys: 'file' and 'func'
418 */
419 private static function getCallerDescription( $callerOffset ) {
420 $callers = wfDebugBacktrace();
421
422 if ( isset( $callers[$callerOffset] ) ) {
423 $callerfile = $callers[$callerOffset];
424 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
425 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
426 } else {
427 $file = '(internal function)';
428 }
429 } else {
430 $file = '(unknown location)';
431 }
432
433 if ( isset( $callers[$callerOffset + 1] ) ) {
434 $callerfunc = $callers[$callerOffset + 1];
435 $func = '';
436 if ( isset( $callerfunc['class'] ) ) {
437 $func .= $callerfunc['class'] . '::';
438 }
439 if ( isset( $callerfunc['function'] ) ) {
440 $func .= $callerfunc['function'];
441 }
442 } else {
443 $func = 'unknown';
444 }
445
446 return [ 'file' => $file, 'func' => $func ];
447 }
448
449 /**
450 * Append a caller description to an error message
451 *
452 * @param string $msg
453 * @param array $caller Caller description from getCallerDescription()
454 * @return string
455 */
456 private static function formatCallerDescription( $msg, $caller ) {
457 // When changing this, update the below parseCallerDescription() method as well.
458 return $msg . ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
459 }
460
461 /**
462 * Append a caller description to an error message
463 *
464 * @internal For use by MWExceptionHandler to override 'exception.file' in error logs.
465 * @param string $msg Formatted message from formatCallerDescription() and getCallerDescription()
466 * @return null|array<string,string> Null if unable to recognise all parts, or array with:
467 * - 'file': string of file path
468 * - 'line': string of line number
469 * - 'func': string of function or method name
470 * - 'message': Re-formatted version of $msg for use with ErrorException,
471 * so as to not include file/line twice.
472 */
473 public static function parseCallerDescription( $msg ) {
474 $match = null;
475 preg_match( '/(.*) \[Called from ([^ ]+) in ([^ ]+) at line (\d+)\]$/', $msg, $match );
476 if ( $match ) {
477 return [
478 'message' => "{$match[1]} [Called from {$match[2]}]",
479 'func' => $match[2],
480 'file' => $match[3],
481 'line' => $match[4],
482 ];
483 } else {
484 return null;
485 }
486 }
487
488 /**
489 * Send a message to the debug log and optionally also trigger a PHP
490 * error, depending on the $level argument.
491 *
492 * @param string $msg Message to send
493 * @param string $group Log group on which to send the message
494 * @param int|bool $level Error level to use; set to false to not trigger an error
495 */
496 private static function sendMessage( $msg, $group, $level ) {
497 if ( $level !== false ) {
498 trigger_error( $msg, $level );
499 }
500
501 wfDebugLog( $group, $msg );
502 }
503
504 /**
505 * This method receives messages from LoggerFactory, wfDebugLog, and MWExceptionHandler.
506 *
507 * Do NOT call this method directly.
508 *
509 * @internal For use by MWExceptionHandler and LegacyLogger only
510 * @since 1.19
511 * @param string $str
512 * @param array $context
513 */
514 public static function debugMsg( $str, $context = [] ) {
515 global $wgDebugComments, $wgShowDebug;
516
517 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
518 if ( $context ) {
519 $prefix = '';
520 if ( isset( $context['prefix'] ) ) {
521 $prefix = $context['prefix'];
522 } elseif ( isset( $context['channel'] ) && $context['channel'] !== 'wfDebug' ) {
523 $prefix = "[{$context['channel']}] ";
524 }
525 if ( isset( $context['seconds_elapsed'] ) && isset( $context['memory_used'] ) ) {
526 $prefix .= "{$context['seconds_elapsed']} {$context['memory_used']} ";
527 }
528 $str = LegacyLogger::interpolate( $str, $context );
529 $str = $prefix . $str;
530 }
531 $str = rtrim( UtfNormal\Validator::cleanUp( $str ) );
532 self::$debug[] = $str;
533 if ( isset( $context['channel'] ) && $context['channel'] === 'error' ) {
534 $message = isset( $context['exception'] )
535 ? $context['exception']->getMessage()
536 : $str;
537 $real = self::parseCallerDescription( $message );
538 if ( $real ) {
539 // from wfLogWarning()
540 $message = $real['message'];
541 $caller = $real['func'];
542 } else {
543 $trace = isset( $context['exception'] ) ? $context['exception']->getTrace() : [];
544 if ( ( $trace[5]['function'] ?? null ) === 'wfDeprecated' ) {
545 // from MWExceptionHandler/trigger_error/MWDebug/MWDebug/MWDebug/wfDeprecated()
546 $offset = 6;
547 } elseif ( ( $trace[1]['function'] ?? null ) === 'trigger_error' ) {
548 // from trigger_error
549 $offset = 2;
550 } else {
551 // built-in PHP error
552 $offset = 1;
553 }
554 $frame = $trace[$offset] ?? $trace[0];
555 $caller = ( isset( $frame['class'] ) ? $frame['class'] . '::' : '' )
556 . $frame['function'];
557 }
558
559 self::$log[] = [
560 'msg' => htmlspecialchars( $message ),
561 'type' => 'warn',
562 'caller' => $caller,
563 ];
564 }
565 }
566 }
567
568 /**
569 * Begins profiling on a database query
570 *
571 * @since 1.19
572 * @param string $sql
573 * @param string $function
574 * @param float $runTime Query run time
575 * @param string $dbhost
576 * @return bool True if debugger is enabled, false otherwise
577 */
578 public static function query( $sql, $function, $runTime, $dbhost ) {
579 if ( !self::$enabled ) {
580 return false;
581 }
582
583 // Replace invalid UTF-8 chars with a square UTF-8 character
584 // This prevents json_encode from erroring out due to binary SQL data
585 $sql = preg_replace(
586 '/(
587 [\xC0-\xC1] # Invalid UTF-8 Bytes
588 | [\xF5-\xFF] # Invalid UTF-8 Bytes
589 | \xE0[\x80-\x9F] # Overlong encoding of prior code point
590 | \xF0[\x80-\x8F] # Overlong encoding of prior code point
591 | [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
592 | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
593 | [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
594 | (?<=[\x0-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
595 | (?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF4]
596 | [\xF0-\xF4][\x80-\xBF]|[\xF0-\xF4][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
597 | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
598 | (?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
599 | (?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
600 )/x',
601 '■',
602 $sql
603 );
604
605 // last check for invalid utf8
606 $sql = UtfNormal\Validator::cleanUp( $sql );
607
608 self::$query[] = [
609 'sql' => "$dbhost: $sql",
610 'function' => $function,
611 'time' => $runTime,
612 ];
613
614 return true;
615 }
616
617 /**
618 * Returns a list of files included, along with their size
619 *
620 * @param IContextSource $context
621 * @return array
622 */
623 protected static function getFilesIncluded( IContextSource $context ) {
624 $files = get_included_files();
625 $fileList = [];
626 foreach ( $files as $file ) {
627 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
628 $size = @filesize( $file );
629 if ( $size === false ) {
630 // Certain files that have been included might then be deleted. This is especially likely to happen
631 // in tests, see T351986.
632 // Just use a size of 0, but include these files here to try and be as useful as possible.
633 $size = 0;
634 }
635 $fileList[] = [
636 'name' => $file,
637 'size' => $context->getLanguage()->formatSize( $size ),
638 ];
639 }
640
641 return $fileList;
642 }
643
644 /**
645 * Returns the HTML to add to the page for the toolbar
646 *
647 * @since 1.19
648 * @param IContextSource $context
649 * @return WrappedStringList
650 */
651 public static function getDebugHTML( IContextSource $context ) {
652 global $wgDebugComments;
653
654 $html = [];
655
656 if ( self::$enabled ) {
657 self::log( 'MWDebug output complete' );
658 $debugInfo = self::getDebugInfo( $context );
659
660 // Cannot use OutputPage::addJsConfigVars because those are already outputted
661 // by the time this method is called.
662 $html[] = ResourceLoader::makeInlineScript(
663 ResourceLoader::makeConfigSetScript( [ 'debugInfo' => $debugInfo ] )
664 );
665 }
666
667 if ( $wgDebugComments ) {
668 $html[] = '<!-- Debug output:';
669 foreach ( self::$debug as $line ) {
670 $html[] = htmlspecialchars( $line, ENT_NOQUOTES );
671 }
672 $html[] = '-->';
673 }
674
675 return WrappedString::join( "\n", $html );
676 }
677
678 /**
679 * Generate debug log in HTML for displaying at the bottom of the main
680 * content area.
681 * If $wgShowDebug is false, an empty string is always returned.
682 *
683 * @since 1.20
684 * @return WrappedStringList HTML fragment
685 */
686 public static function getHTMLDebugLog() {
687 global $wgShowDebug;
688
689 $html = [];
690 if ( $wgShowDebug ) {
691 $html[] = Html::openElement( 'div', [ 'id' => 'mw-html-debug-log' ] );
692 $html[] = "<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">";
693
694 foreach ( self::$debug as $line ) {
695 $display = nl2br( htmlspecialchars( trim( $line ) ) );
696
697 $html[] = "<li><code>$display</code></li>";
698 }
699
700 $html[] = '</ul>';
701 $html[] = '</div>';
702 }
703 return WrappedString::join( "\n", $html );
704 }
705
706 /**
707 * Append the debug info to given ApiResult
708 *
709 * @param IContextSource $context
710 * @param ApiResult $result
711 */
712 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
713 if ( !self::$enabled ) {
714 return;
715 }
716
717 // output errors as debug info, when display_errors is on
718 // this is necessary for all non html output of the api, because that clears all errors first
719 $obContents = ob_get_contents();
720 if ( $obContents ) {
721 $obContentArray = explode( '<br />', $obContents );
722 foreach ( $obContentArray as $obContent ) {
723 if ( trim( $obContent ) ) {
724 self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
725 }
726 }
727 }
728
729 self::log( 'MWDebug output complete' );
730 $debugInfo = self::getDebugInfo( $context );
731
732 ApiResult::setIndexedTagName( $debugInfo, 'debuginfo' );
733 ApiResult::setIndexedTagName( $debugInfo['log'], 'line' );
734 ApiResult::setIndexedTagName( $debugInfo['debugLog'], 'msg' );
735 ApiResult::setIndexedTagName( $debugInfo['queries'], 'query' );
736 ApiResult::setIndexedTagName( $debugInfo['includes'], 'queries' );
737 $result->addValue( null, 'debuginfo', $debugInfo );
738 }
739
740 /**
741 * Returns the HTML to add to the page for the toolbar
742 *
743 * @param IContextSource $context
744 * @return array
745 */
746 public static function getDebugInfo( IContextSource $context ) {
747 if ( !self::$enabled ) {
748 return [];
749 }
750
751 $request = $context->getRequest();
752
753 $branch = GitInfo::currentBranch();
754 if ( GitInfo::isSHA1( $branch ) ) {
755 // If it's a detached HEAD, the SHA1 will already be
756 // included in the MW version, so don't show it.
757 $branch = false;
758 }
759
760 return [
761 'mwVersion' => MW_VERSION,
762 'phpEngine' => 'PHP',
763 'phpVersion' => PHP_VERSION,
764 'gitRevision' => GitInfo::headSHA1(),
765 'gitBranch' => $branch,
766 'gitViewUrl' => GitInfo::headViewUrl(),
767 'time' => $request->getElapsedTime(),
768 'log' => self::$log,
769 'debugLog' => self::$debug,
770 'queries' => self::$query,
771 'request' => [
772 'method' => $request->getMethod(),
773 'url' => $request->getRequestURL(),
774 'headers' => $request->getAllHeaders(),
775 'params' => $request->getValues(),
776 ],
777 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
778 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
779 'includes' => self::getFilesIncluded( $context ),
780 ];
781 }
782 }
783
784 /** @deprecated class alias since 1.43 */
785 class_alias( MWDebug::class, 'MWDebug' );