MediaWiki 1.40.4
MWDebug.php
Go to the documentation of this file.
1<?php
26use Wikimedia\WrappedString;
27use Wikimedia\WrappedStringList;
28
37class MWDebug {
43 protected static $log = [];
44
50 protected static $debug = [];
51
57 protected static $query = [];
58
64 protected static $enabled = false;
65
72 protected static $deprecationWarnings = [];
73
77 protected static $deprecationFilters = [];
78
82 public static function setup() {
83 global $wgDebugToolbar,
85
86 if (
87 // Easy to forget to falsify $wgDebugToolbar for static caches.
88 // If file cache or CDN cache is on, just disable this (DWIMD).
89 $wgUseCdn ||
91 // Keep MWDebug off on CLI. This prevents MWDebug from eating up
92 // all the memory for logging SQL queries in maintenance scripts.
94 ) {
95 return;
96 }
97
98 if ( $wgDebugToolbar ) {
99 self::init();
100 }
101 }
102
109 public static function init() {
110 self::$enabled = true;
111 }
112
118 public static function deinit() {
119 self::$enabled = false;
120 }
121
129 public static function addModules( OutputPage $out ) {
130 if ( self::$enabled ) {
131 $out->addModules( 'mediawiki.debug' );
132 }
133 }
134
141 public static function log( $str ) {
142 if ( !self::$enabled ) {
143 return;
144 }
145 if ( !is_string( $str ) ) {
146 $str = print_r( $str, true );
147 }
148 self::$log[] = [
149 'msg' => htmlspecialchars( $str ),
150 'type' => 'log',
151 'caller' => wfGetCaller(),
152 ];
153 }
154
160 public static function getLog() {
161 return self::$log;
162 }
163
168 public static function clearLog() {
169 self::$log = [];
170 self::$deprecationWarnings = [];
171 }
172
184 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
186
187 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
188 $log = 'debug';
189 }
190
191 if ( $log === 'debug' ) {
192 $level = false;
193 }
194
195 $callerDescription = self::getCallerDescription( $callerOffset );
196
197 self::sendMessage(
198 self::formatCallerDescription( $msg, $callerDescription ),
199 'warning',
200 $level );
201
202 if ( self::$enabled ) {
203 self::$log[] = [
204 'msg' => htmlspecialchars( $msg ),
205 'type' => 'warn',
206 'caller' => $callerDescription['func'],
207 ];
208 }
209 }
210
225 public static function deprecated( $function, $version = false,
226 $component = false, $callerOffset = 2
227 ) {
228 if ( $version ) {
229 $component = $component ?: 'MediaWiki';
230 $msg = "Use of $function was deprecated in $component $version.";
231 } else {
232 $msg = "Use of $function is deprecated.";
233 }
234 self::deprecatedMsg( $msg, $version, $component, $callerOffset + 1 );
235 }
236
259 public static function detectDeprecatedOverride( $instance, $class, $method, $version = false,
260 $component = false, $callerOffset = 2
261 ) {
262 $reflectionMethod = new ReflectionMethod( $instance, $method );
263 $declaringClass = $reflectionMethod->getDeclaringClass()->getName();
264
265 if ( $declaringClass === $class ) {
266 // not overridden, nothing to do
267 return false;
268 }
269
270 if ( $version ) {
271 $component = $component ?: 'MediaWiki';
272 $msg = "$declaringClass overrides $method which was deprecated in $component $version.";
273 self::deprecatedMsg( $msg, $version, $component, $callerOffset + 1 );
274 }
275
276 return true;
277 }
278
307 public static function deprecatedMsg( $msg, $version = false,
308 $component = false, $callerOffset = 2
309 ) {
310 if ( $callerOffset === false ) {
311 $callerFunc = '';
312 $rawMsg = $msg;
313 } else {
314 $callerDescription = self::getCallerDescription( $callerOffset );
315 $callerFunc = $callerDescription['func'];
316 $rawMsg = self::formatCallerDescription( $msg, $callerDescription );
317 }
318
319 $sendToLog = true;
320
321 // Check to see if there already was a warning about this function
322 if ( isset( self::$deprecationWarnings[$msg][$callerFunc] ) ) {
323 return;
324 } elseif ( isset( self::$deprecationWarnings[$msg] ) ) {
325 if ( self::$enabled ) {
326 $sendToLog = false;
327 } else {
328 return;
329 }
330 }
331
332 self::$deprecationWarnings[$msg][$callerFunc] = true;
333
334 if ( $version ) {
336
337 $component = $component ?: 'MediaWiki';
338 if ( $wgDeprecationReleaseLimit && $component === 'MediaWiki' ) {
339 # Strip -* off the end of $version so that branches can use the
340 # format #.##-branchname to avoid issues if the branch is merged into
341 # a version of MediaWiki later than what it was branched from
342 $comparableVersion = preg_replace( '/-.*$/', '', $version );
343
344 # If the comparableVersion is larger than our release limit then
345 # skip the warning message for the deprecation
346 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
347 $sendToLog = false;
348 }
349 }
350 }
351
352 self::sendRawDeprecated(
353 $rawMsg,
354 $sendToLog,
355 $callerFunc
356 );
357 }
358
371 public static function sendRawDeprecated( $msg, $sendToLog = true, $callerFunc = '' ) {
372 foreach ( self::$deprecationFilters as $filter => $callback ) {
373 if ( preg_match( $filter, $msg ) ) {
374 if ( is_callable( $callback ) ) {
375 $callback();
376 }
377 return;
378 }
379 }
380
381 if ( $sendToLog ) {
382 trigger_error( $msg, E_USER_DEPRECATED );
383 }
384
385 if ( self::$enabled ) {
386 $logMsg = htmlspecialchars( $msg ) .
387 Html::rawElement( 'div', [ 'class' => 'mw-debug-backtrace' ],
388 Html::element( 'span', [], 'Backtrace:' ) . wfBacktrace()
389 );
390
391 self::$log[] = [
392 'msg' => $logMsg,
393 'type' => 'deprecated',
394 'caller' => $callerFunc,
395 ];
396 }
397 }
398
406 public static function filterDeprecationForTest(
407 string $regex, ?callable $callback = null
408 ): void {
409 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
410 throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
411 }
412 self::$deprecationFilters[$regex] = $callback;
413 }
414
418 public static function clearDeprecationFilters() {
419 self::$deprecationFilters = [];
420 }
421
429 private static function getCallerDescription( $callerOffset ) {
430 $callers = wfDebugBacktrace();
431
432 if ( isset( $callers[$callerOffset] ) ) {
433 $callerfile = $callers[$callerOffset];
434 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
435 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
436 } else {
437 $file = '(internal function)';
438 }
439 } else {
440 $file = '(unknown location)';
441 }
442
443 if ( isset( $callers[$callerOffset + 1] ) ) {
444 $callerfunc = $callers[$callerOffset + 1];
445 $func = '';
446 if ( isset( $callerfunc['class'] ) ) {
447 $func .= $callerfunc['class'] . '::';
448 }
449 if ( isset( $callerfunc['function'] ) ) {
450 $func .= $callerfunc['function'];
451 }
452 } else {
453 $func = 'unknown';
454 }
455
456 return [ 'file' => $file, 'func' => $func ];
457 }
458
466 private static function formatCallerDescription( $msg, $caller ) {
467 // When changing this, update the below parseCallerDescription() method as well.
468 return $msg . ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
469 }
470
483 public static function parseCallerDescription( $msg ) {
484 $match = null;
485 preg_match( '/(.*) \[Called from ([^ ]+) in ([^ ]+) at line (\d+)\]$/', $msg, $match );
486 if ( $match ) {
487 return [
488 'message' => "{$match[1]} [Called from {$match[2]}]",
489 'func' => $match[2],
490 'file' => $match[3],
491 'line' => $match[4],
492 ];
493 } else {
494 return null;
495 }
496 }
497
506 private static function sendMessage( $msg, $group, $level ) {
507 if ( $level !== false ) {
508 trigger_error( $msg, $level );
509 }
510
511 wfDebugLog( $group, $msg );
512 }
513
522 public static function debugMsg( $str, $context = [] ) {
524
525 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
526 if ( $context ) {
527 $prefix = '';
528 if ( isset( $context['prefix'] ) ) {
529 $prefix = $context['prefix'];
530 } elseif ( isset( $context['channel'] ) && $context['channel'] !== 'wfDebug' ) {
531 $prefix = "[{$context['channel']}] ";
532 }
533 if ( isset( $context['seconds_elapsed'] ) && isset( $context['memory_used'] ) ) {
534 $prefix .= "{$context['seconds_elapsed']} {$context['memory_used']} ";
535 }
536 $str = LegacyLogger::interpolate( $str, $context );
537 $str = $prefix . $str;
538 }
539 self::$debug[] = rtrim( UtfNormal\Validator::cleanUp( $str ) );
540 }
541 }
542
553 public static function query( $sql, $function, $runTime, $dbhost ) {
554 if ( !self::$enabled ) {
555 return false;
556 }
557
558 // Replace invalid UTF-8 chars with a square UTF-8 character
559 // This prevents json_encode from erroring out due to binary SQL data
560 $sql = preg_replace(
561 '/(
562 [\xC0-\xC1] # Invalid UTF-8 Bytes
563 | [\xF5-\xFF] # Invalid UTF-8 Bytes
564 | \xE0[\x80-\x9F] # Overlong encoding of prior code point
565 | \xF0[\x80-\x8F] # Overlong encoding of prior code point
566 | [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
567 | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
568 | [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
569 | (?<=[\x0-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
570 | (?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF4]
571 | [\xF0-\xF4][\x80-\xBF]|[\xF0-\xF4][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
572 | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
573 | (?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
574 | (?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
575 )/x',
576 '■',
577 $sql
578 );
579
580 // last check for invalid utf8
581 $sql = UtfNormal\Validator::cleanUp( $sql );
582
583 self::$query[] = [
584 'sql' => "$dbhost: $sql",
585 'function' => $function,
586 'time' => $runTime,
587 ];
588
589 return true;
590 }
591
598 protected static function getFilesIncluded( IContextSource $context ) {
599 $files = get_included_files();
600 $fileList = [];
601 foreach ( $files as $file ) {
602 $size = filesize( $file );
603 $fileList[] = [
604 'name' => $file,
605 'size' => $context->getLanguage()->formatSize( $size ),
606 ];
607 }
608
609 return $fileList;
610 }
611
619 public static function getDebugHTML( IContextSource $context ) {
620 global $wgDebugComments;
621
622 $html = [];
623
624 if ( self::$enabled ) {
625 self::log( 'MWDebug output complete' );
626 $debugInfo = self::getDebugInfo( $context );
627
628 // Cannot use OutputPage::addJsConfigVars because those are already outputted
629 // by the time this method is called.
630 $html[] = ResourceLoader::makeInlineScript(
631 ResourceLoader::makeConfigSetScript( [ 'debugInfo' => $debugInfo ] ),
632 $context->getOutput()->getCSP()->getNonce()
633 );
634 }
635
636 if ( $wgDebugComments ) {
637 $html[] = '<!-- Debug output:';
638 foreach ( self::$debug as $line ) {
639 $html[] = htmlspecialchars( $line, ENT_NOQUOTES );
640 }
641 $html[] = '-->';
642 }
643
644 return WrappedString::join( "\n", $html );
645 }
646
655 public static function getHTMLDebugLog() {
656 global $wgShowDebug;
657
658 $html = [];
659 if ( $wgShowDebug ) {
660 $html[] = Html::openElement( 'div', [ 'id' => 'mw-html-debug-log' ] );
661 $html[] = "<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">";
662
663 foreach ( self::$debug as $line ) {
664 $display = nl2br( htmlspecialchars( trim( $line ) ) );
665
666 $html[] = "<li><code>$display</code></li>";
667 }
668
669 $html[] = '</ul>';
670 $html[] = '</div>';
671 }
672 return WrappedString::join( "\n", $html );
673 }
674
681 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
682 if ( !self::$enabled ) {
683 return;
684 }
685
686 // output errors as debug info, when display_errors is on
687 // this is necessary for all non html output of the api, because that clears all errors first
688 $obContents = ob_get_contents();
689 if ( $obContents ) {
690 $obContentArray = explode( '<br />', $obContents );
691 foreach ( $obContentArray as $obContent ) {
692 if ( trim( $obContent ) ) {
693 self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
694 }
695 }
696 }
697
698 self::log( 'MWDebug output complete' );
699 $debugInfo = self::getDebugInfo( $context );
700
701 ApiResult::setIndexedTagName( $debugInfo, 'debuginfo' );
702 ApiResult::setIndexedTagName( $debugInfo['log'], 'line' );
703 ApiResult::setIndexedTagName( $debugInfo['debugLog'], 'msg' );
704 ApiResult::setIndexedTagName( $debugInfo['queries'], 'query' );
705 ApiResult::setIndexedTagName( $debugInfo['includes'], 'queries' );
706 $result->addValue( null, 'debuginfo', $debugInfo );
707 }
708
715 public static function getDebugInfo( IContextSource $context ) {
716 if ( !self::$enabled ) {
717 return [];
718 }
719
720 $request = $context->getRequest();
721
722 $branch = GitInfo::currentBranch();
723 if ( GitInfo::isSHA1( $branch ) ) {
724 // If it's a detached HEAD, the SHA1 will already be
725 // included in the MW version, so don't show it.
726 $branch = false;
727 }
728
729 return [
730 'mwVersion' => MW_VERSION,
731 'phpEngine' => 'PHP',
732 'phpVersion' => PHP_VERSION,
733 'gitRevision' => GitInfo::headSHA1(),
734 'gitBranch' => $branch,
735 'gitViewUrl' => GitInfo::headViewUrl(),
736 'time' => $request->getElapsedTime(),
737 'log' => self::$log,
738 'debugLog' => self::$debug,
739 'queries' => self::$query,
740 'request' => [
741 'method' => $request->getMethod(),
742 'url' => $request->getRequestURL(),
743 'headers' => $request->getAllHeaders(),
744 'params' => $request->getValues(),
745 ],
746 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
747 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
748 'includes' => self::getFilesIncluded( $context ),
749 ];
750 }
751}
const MW_VERSION
The running version of MediaWiki.
Definition Defines.php:36
global $wgCommandLineMode
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
Definition WebStart.php:88
This class represents the result of the API operations.
Definition ApiResult.php:35
addValue( $path, $name, $value, $flags=0)
Add value to the output data at the given path.
static headSHA1()
Definition GitInfo.php:436
static headViewUrl()
Definition GitInfo.php:452
static currentBranch()
Definition GitInfo.php:444
static isSHA1( $str)
Check if a string looks like a hex encoded SHA1 hash.
Definition GitInfo.php:199
New debugger system that outputs a toolbar on page view.
Definition MWDebug.php:37
static warning( $msg, $callerOffset=1, $level=E_USER_NOTICE, $log='auto')
Adds a warning entry to the log.
Definition MWDebug.php:184
static getFilesIncluded(IContextSource $context)
Returns a list of files included, along with their size.
Definition MWDebug.php:598
static array $deprecationFilters
Keys are regexes, values are optional callbacks to call if the filter is hit.
Definition MWDebug.php:77
static bool $enabled
Is the debugger enabled?
Definition MWDebug.php:64
static setup()
Definition MWDebug.php:82
static filterDeprecationForTest(string $regex, ?callable $callback=null)
Deprecation messages matching the supplied regex will be suppressed.
Definition MWDebug.php:406
static addModules(OutputPage $out)
Add ResourceLoader modules to the OutputPage object if debugging is enabled.
Definition MWDebug.php:129
static parseCallerDescription( $msg)
Append a caller description to an error message.
Definition MWDebug.php:483
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition MWDebug.php:681
static array $deprecationWarnings
Array of functions that have already been warned, formatted function-caller to prevent a buttload of ...
Definition MWDebug.php:72
static clearLog()
Clears internal log array and deprecation tracking.
Definition MWDebug.php:168
static sendRawDeprecated( $msg, $sendToLog=true, $callerFunc='')
Send a raw deprecation message to the log and the debug toolbar, without filtering of duplicate messa...
Definition MWDebug.php:371
static deinit()
Disable the debugger.
Definition MWDebug.php:118
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition MWDebug.php:553
static getLog()
Returns internal log array.
Definition MWDebug.php:160
static array $debug
Debug messages from wfDebug().
Definition MWDebug.php:50
static log( $str)
Adds a line to the log.
Definition MWDebug.php:141
static detectDeprecatedOverride( $instance, $class, $method, $version=false, $component=false, $callerOffset=2)
Show a warning if $method declared in $class is overridden in $instance.
Definition MWDebug.php:259
static getDebugInfo(IContextSource $context)
Returns the HTML to add to the page for the toolbar.
Definition MWDebug.php:715
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition MWDebug.php:522
static clearDeprecationFilters()
Clear all deprecation filters.
Definition MWDebug.php:418
static array $log
Log lines.
Definition MWDebug.php:43
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition MWDebug.php:225
static array $query
SQL statements of the database queries.
Definition MWDebug.php:57
static getHTMLDebugLog()
Generate debug log in HTML for displaying at the bottom of the main content area.
Definition MWDebug.php:655
static init()
Enabled the debugger and load resource module.
Definition MWDebug.php:109
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition MWDebug.php:307
static getDebugHTML(IContextSource $context)
Returns the HTML to add to the page for the toolbar.
Definition MWDebug.php:619
This class is a collection of static functions that serve two purposes:
Definition Html.php:55
PSR-3 logger that mimics the historic implementation of MediaWiki's former wfErrorLog logging impleme...
ResourceLoader is a loading system for JavaScript and CSS resources.
This is one of the Core classes and should be read at least once by any new developers.
addModules( $modules)
Load one or more ResourceLoader modules on this page.
$wgUseCdn
Config variable stub for the UseCdn setting, for use by phpdoc and IDEs.
$wgDeprecationReleaseLimit
Config variable stub for the DeprecationReleaseLimit setting, for use by phpdoc and IDEs.
$wgDebugComments
Config variable stub for the DebugComments setting, for use by phpdoc and IDEs.
$wgShowDebug
Config variable stub for the ShowDebug setting, for use by phpdoc and IDEs.
$wgDebugToolbar
Config variable stub for the DebugToolbar setting, for use by phpdoc and IDEs.
$wgDevelopmentWarnings
Config variable stub for the DevelopmentWarnings setting, for use by phpdoc and IDEs.
$wgUseFileCache
Config variable stub for the UseFileCache setting, for use by phpdoc and IDEs.
Interface for objects which can provide a MediaWiki context on request.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42