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