MediaWiki  master
MWDebug.php
Go to the documentation of this file.
1 <?php
24 
33 class MWDebug {
39  protected static $log = [];
40 
46  protected static $debug = [];
47 
53  protected static $query = [];
54 
60  protected static $enabled = false;
61 
68  protected static $deprecationWarnings = [];
69 
73  protected static $deprecationFilters = [];
74 
78  public static function setup() {
79  global $wgDebugToolbar,
81 
82  if (
83  // Easy to forget to falsify $wgDebugToolbar for static caches.
84  // If file cache or CDN cache is on, just disable this (DWIMD).
85  $wgUseCdn ||
87  // Keep MWDebug off on CLI. This prevents MWDebug from eating up
88  // all the memory for logging SQL queries in maintenance scripts.
90  ) {
91  return;
92  }
93 
94  if ( $wgDebugToolbar ) {
95  self::init();
96  }
97  }
98 
105  public static function init() {
106  self::$enabled = true;
107  }
108 
114  public static function deinit() {
115  self::$enabled = false;
116  }
117 
125  public static function addModules( OutputPage $out ) {
126  if ( self::$enabled ) {
127  $out->addModules( 'mediawiki.debug' );
128  }
129  }
130 
137  public static function log( $str ) {
138  if ( !self::$enabled ) {
139  return;
140  }
141  if ( !is_string( $str ) ) {
142  $str = print_r( $str, true );
143  }
144  self::$log[] = [
145  'msg' => htmlspecialchars( $str ),
146  'type' => 'log',
147  'caller' => wfGetCaller(),
148  ];
149  }
150 
156  public static function getLog() {
157  return self::$log;
158  }
159 
164  public static function clearLog() {
165  self::$log = [];
166  self::$deprecationWarnings = [];
167  }
168 
180  public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
181  global $wgDevelopmentWarnings;
182 
183  if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
184  $log = 'debug';
185  }
186 
187  if ( $log === 'debug' ) {
188  $level = false;
189  }
190 
191  $callerDescription = self::getCallerDescription( $callerOffset );
192 
194  self::formatCallerDescription( $msg, $callerDescription ),
195  'warning',
196  $level );
197 
198  if ( self::$enabled ) {
199  self::$log[] = [
200  'msg' => htmlspecialchars( $msg ),
201  'type' => 'warn',
202  'caller' => $callerDescription['func'],
203  ];
204  }
205  }
206 
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 
257  public static function deprecatedMsg( $msg, $version = false,
258  $component = false, $callerOffset = 2
259  ) {
260  if ( $callerOffset === false ) {
261  $callerFunc = '';
262  $rawMsg = $msg;
263  } else {
264  $callerDescription = self::getCallerDescription( $callerOffset );
265  $callerFunc = $callerDescription['func'];
266  $rawMsg = self::formatCallerDescription( $msg, $callerDescription );
267  }
268 
269  $sendToLog = true;
270 
271  // Check to see if there already was a warning about this function
272  if ( isset( self::$deprecationWarnings[$msg][$callerFunc] ) ) {
273  return;
274  } elseif ( isset( self::$deprecationWarnings[$msg] ) ) {
275  if ( self::$enabled ) {
276  $sendToLog = false;
277  } else {
278  return;
279  }
280  }
281 
282  self::$deprecationWarnings[$msg][$callerFunc] = true;
283 
284  if ( $version ) {
286 
287  $component = $component ?: 'MediaWiki';
288  if ( $wgDeprecationReleaseLimit && $component === 'MediaWiki' ) {
289  # Strip -* off the end of $version so that branches can use the
290  # format #.##-branchname to avoid issues if the branch is merged into
291  # a version of MediaWiki later than what it was branched from
292  $comparableVersion = preg_replace( '/-.*$/', '', $version );
293 
294  # If the comparableVersion is larger than our release limit then
295  # skip the warning message for the deprecation
296  if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
297  $sendToLog = false;
298  }
299  }
300  }
301 
303  $rawMsg,
304  $sendToLog,
305  $callerFunc
306  );
307  }
308 
321  public static function sendRawDeprecated( $msg, $sendToLog = true, $callerFunc = '' ) {
322  foreach ( self::$deprecationFilters as $filter ) {
323  if ( preg_match( $filter, $msg ) ) {
324  return;
325  }
326  }
327 
328  if ( $sendToLog ) {
329  trigger_error( $msg, E_USER_DEPRECATED );
330  }
331 
332  if ( self::$enabled ) {
333  $logMsg = htmlspecialchars( $msg ) .
334  Html::rawElement( 'div', [ 'class' => 'mw-debug-backtrace' ],
335  Html::element( 'span', [], 'Backtrace:' ) . wfBacktrace()
336  );
337 
338  self::$log[] = [
339  'msg' => $logMsg,
340  'type' => 'deprecated',
341  'caller' => $callerFunc,
342  ];
343  }
344  }
345 
352  public static function filterDeprecationForTest( $regex ) {
353  if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
354  throw new RuntimeException( __METHOD__ . ' can only be used in tests' );
355  }
356  self::$deprecationFilters[] = $regex;
357  }
358 
362  public static function clearDeprecationFilters() {
363  self::$deprecationFilters = [];
364  }
365 
373  private static function getCallerDescription( $callerOffset ) {
374  $callers = wfDebugBacktrace();
375 
376  if ( isset( $callers[$callerOffset] ) ) {
377  $callerfile = $callers[$callerOffset];
378  if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
379  $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
380  } else {
381  $file = '(internal function)';
382  }
383  } else {
384  $file = '(unknown location)';
385  }
386 
387  if ( isset( $callers[$callerOffset + 1] ) ) {
388  $callerfunc = $callers[$callerOffset + 1];
389  $func = '';
390  if ( isset( $callerfunc['class'] ) ) {
391  $func .= $callerfunc['class'] . '::';
392  }
393  if ( isset( $callerfunc['function'] ) ) {
394  $func .= $callerfunc['function'];
395  }
396  } else {
397  $func = 'unknown';
398  }
399 
400  return [ 'file' => $file, 'func' => $func ];
401  }
402 
410  private static function formatCallerDescription( $msg, $caller ) {
411  // When changing this, update the below parseCallerDescription() method as well.
412  return $msg . ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
413  }
414 
427  public static function parseCallerDescription( $msg ) {
428  $match = null;
429  preg_match( '/(.*) \[Called from ([^ ]+) in ([^ ]+) at line (\d+)\]$/', $msg, $match );
430  if ( $match ) {
431  return [
432  'message' => "{$match[1]} [Called from {$match[2]}]",
433  'func' => $match[2],
434  'file' => $match[3],
435  'line' => $match[4],
436  ];
437  } else {
438  return null;
439  }
440  }
441 
450  private static function sendMessage( $msg, $group, $level ) {
451  if ( $level !== false ) {
452  trigger_error( $msg, $level );
453  }
454 
455  wfDebugLog( $group, $msg );
456  }
457 
466  public static function debugMsg( $str, $context = [] ) {
468 
469  if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
470  if ( $context ) {
471  $prefix = '';
472  if ( isset( $context['prefix'] ) ) {
473  $prefix = $context['prefix'];
474  } elseif ( isset( $context['channel'] ) && $context['channel'] !== 'wfDebug' ) {
475  $prefix = "[{$context['channel']}] ";
476  }
477  if ( isset( $context['seconds_elapsed'] ) && isset( $context['memory_used'] ) ) {
478  $prefix .= "{$context['seconds_elapsed']} {$context['memory_used']} ";
479  }
480  $str = LegacyLogger::interpolate( $str, $context );
481  $str = $prefix . $str;
482  }
483  self::$debug[] = rtrim( UtfNormal\Validator::cleanUp( $str ) );
484  }
485  }
486 
497  public static function query( $sql, $function, $runTime, $dbhost ) {
498  if ( !self::$enabled ) {
499  return false;
500  }
501 
502  // Replace invalid UTF-8 chars with a square UTF-8 character
503  // This prevents json_encode from erroring out due to binary SQL data
504  $sql = preg_replace(
505  '/(
506  [\xC0-\xC1] # Invalid UTF-8 Bytes
507  | [\xF5-\xFF] # Invalid UTF-8 Bytes
508  | \xE0[\x80-\x9F] # Overlong encoding of prior code point
509  | \xF0[\x80-\x8F] # Overlong encoding of prior code point
510  | [\xC2-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
511  | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
512  | [\xF0-\xF4](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
513  | (?<=[\x0-\x7F\xF5-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
514  | (?<![\xC2-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF4]
515  | [\xF0-\xF4][\x80-\xBF]|[\xF0-\xF4][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
516  | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
517  | (?<=[\xF0-\xF4])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
518  | (?<=[\xF0-\xF4][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
519  )/x',
520  '■',
521  $sql
522  );
523 
524  // last check for invalid utf8
525  $sql = UtfNormal\Validator::cleanUp( $sql );
526 
527  self::$query[] = [
528  'sql' => "$dbhost: $sql",
529  'function' => $function,
530  'time' => $runTime,
531  ];
532 
533  return true;
534  }
535 
542  protected static function getFilesIncluded( IContextSource $context ) {
543  $files = get_included_files();
544  $fileList = [];
545  foreach ( $files as $file ) {
546  $size = filesize( $file );
547  $fileList[] = [
548  'name' => $file,
549  'size' => $context->getLanguage()->formatSize( $size ),
550  ];
551  }
552 
553  return $fileList;
554  }
555 
563  public static function getDebugHTML( IContextSource $context ) {
564  global $wgDebugComments;
565 
566  $html = '';
567 
568  if ( self::$enabled ) {
569  self::log( 'MWDebug output complete' );
570  $debugInfo = self::getDebugInfo( $context );
571 
572  // Cannot use OutputPage::addJsConfigVars because those are already outputted
573  // by the time this method is called.
575  ResourceLoader::makeConfigSetScript( [ 'debugInfo' => $debugInfo ] ),
576  $context->getOutput()->getCSP()->getNonce()
577  );
578  }
579 
580  if ( $wgDebugComments ) {
581  $html .= "<!-- Debug output:\n" .
582  htmlspecialchars( implode( "\n", self::$debug ), ENT_NOQUOTES ) .
583  "\n\n-->";
584  }
585 
586  return $html;
587  }
588 
597  public static function getHTMLDebugLog() {
598  global $wgShowDebug;
599 
600  if ( !$wgShowDebug ) {
601  return '';
602  }
603 
604  $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n";
605 
606  foreach ( self::$debug as $line ) {
607  $display = nl2br( htmlspecialchars( trim( $line ) ) );
608 
609  $ret .= "<li><code>$display</code></li>\n";
610  }
611 
612  $ret .= '</ul>' . "\n";
613 
614  return Html::rawElement( 'div', [ 'id' => 'mw-html-debug-log' ], $ret );
615  }
616 
623  public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
624  if ( !self::$enabled ) {
625  return;
626  }
627 
628  // output errors as debug info, when display_errors is on
629  // this is necessary for all non html output of the api, because that clears all errors first
630  $obContents = ob_get_contents();
631  if ( $obContents ) {
632  $obContentArray = explode( '<br />', $obContents );
633  foreach ( $obContentArray as $obContent ) {
634  if ( trim( $obContent ) ) {
635  self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
636  }
637  }
638  }
639 
640  self::log( 'MWDebug output complete' );
641  $debugInfo = self::getDebugInfo( $context );
642 
643  ApiResult::setIndexedTagName( $debugInfo, 'debuginfo' );
644  ApiResult::setIndexedTagName( $debugInfo['log'], 'line' );
645  ApiResult::setIndexedTagName( $debugInfo['debugLog'], 'msg' );
646  ApiResult::setIndexedTagName( $debugInfo['queries'], 'query' );
647  ApiResult::setIndexedTagName( $debugInfo['includes'], 'queries' );
648  $result->addValue( null, 'debuginfo', $debugInfo );
649  }
650 
657  public static function getDebugInfo( IContextSource $context ) {
658  if ( !self::$enabled ) {
659  return [];
660  }
661 
662  $request = $context->getRequest();
663 
664  $branch = GitInfo::currentBranch();
665  if ( GitInfo::isSHA1( $branch ) ) {
666  // If it's a detached HEAD, the SHA1 will already be
667  // included in the MW version, so don't show it.
668  $branch = false;
669  }
670 
671  return [
672  'mwVersion' => MW_VERSION,
673  'phpEngine' => 'PHP',
674  'phpVersion' => PHP_VERSION,
675  'gitRevision' => GitInfo::headSHA1(),
676  'gitBranch' => $branch,
677  'gitViewUrl' => GitInfo::headViewUrl(),
678  'time' => $request->getElapsedTime(),
679  'log' => self::$log,
680  'debugLog' => self::$debug,
681  'queries' => self::$query,
682  'request' => [
683  'method' => $request->getMethod(),
684  'url' => $request->getRequestURL(),
685  'headers' => $request->getAllHeaders(),
686  'params' => $request->getValues(),
687  ],
688  'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
689  'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
690  'includes' => self::getFilesIncluded( $context ),
691  ];
692  }
693 }
MWDebug\query
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition: MWDebug.php:497
$wgUseCdn
$wgUseCdn
Enable/disable CDN.
Definition: DefaultSettings.php:2888
MWDebug\getDebugHTML
static getDebugHTML(IContextSource $context)
Returns the HTML to add to the page for the toolbar.
Definition: MWDebug.php:563
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Return JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1670
Sanitizer\stripAllTags
static stripAllTags( $html)
Take a fragment of (potentially invalid) HTML and return a version with any tags removed,...
Definition: Sanitizer.php:1812
MWDebug
New debugger system that outputs a toolbar on page view.
Definition: MWDebug.php:33
GitInfo\isSHA1
static isSHA1( $str)
Check if a string looks like a hex encoded SHA1 hash.
Definition: GitInfo.php:165
wfDebugBacktrace
wfDebugBacktrace( $limit=0)
Safety wrapper for debug_backtrace().
Definition: GlobalFunctions.php:1325
ResourceLoader\makeInlineScript
static makeInlineScript( $script, $nonce=null)
Make an HTML script that runs given JS code after startup and base modules.
Definition: ResourceLoader.php:1643
MW_VERSION
const MW_VERSION
The running version of MediaWiki.
Definition: Defines.php:39
$wgDeprecationReleaseLimit
$wgDeprecationReleaseLimit
Release limitation to wfDeprecated warnings, if set to a release number development warnings will not...
Definition: DefaultSettings.php:6788
GitInfo\headSHA1
static headSHA1()
Definition: GitInfo.php:402
MWDebug\sendMessage
static sendMessage( $msg, $group, $level)
Send a message to the debug log and optionally also trigger a PHP error, depending on the $level argu...
Definition: MWDebug.php:450
MWDebug\getHTMLDebugLog
static getHTMLDebugLog()
Generate debug log in HTML for displaying at the bottom of the main content area.
Definition: MWDebug.php:597
MWDebug\$debug
static $debug
Debug messages from wfDebug().
Definition: MWDebug.php:46
MWDebug\getCallerDescription
static getCallerDescription( $callerOffset)
Get an array describing the calling function at a specified offset.
Definition: MWDebug.php:373
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
GitInfo\headViewUrl
static headViewUrl()
Definition: GitInfo.php:418
MWDebug\getLog
static getLog()
Returns internal log array.
Definition: MWDebug.php:156
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:988
$debug
$debug
Definition: mcc.php:31
$wgShowDebug
$wgShowDebug
Display debug data at the bottom of the main content area.
Definition: DefaultSettings.php:6717
MWDebug\getFilesIncluded
static getFilesIncluded(IContextSource $context)
Returns a list of files included, along with their size.
Definition: MWDebug.php:542
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
$wgUseFileCache
$wgUseFileCache
This will cache static pages for non-logged-in users to reduce database traffic on public sites.
Definition: DefaultSettings.php:2790
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
MWDebug\debugMsg
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition: MWDebug.php:466
MWDebug\clearDeprecationFilters
static clearDeprecationFilters()
Clear all deprecation filters.
Definition: MWDebug.php:362
MWDebug\$deprecationWarnings
static $deprecationWarnings
Array of functions that have already been warned, formatted function-caller to prevent a buttload of ...
Definition: MWDebug.php:68
MWDebug\getDebugInfo
static getDebugInfo(IContextSource $context)
Returns the HTML to add to the page for the toolbar.
Definition: MWDebug.php:657
OutputPage\addModules
addModules( $modules)
Load one or more ResourceLoader modules on this page.
Definition: OutputPage.php:559
MWDebug\clearLog
static clearLog()
Clears internal log array and deprecation tracking.
Definition: MWDebug.php:164
MWDebug\deprecated
static deprecated( $function, $version=false, $component=false, $callerOffset=2)
Show a warning that $function is deprecated.
Definition: MWDebug.php:225
MWDebug\setup
static setup()
Definition: MWDebug.php:78
OutputPage
This is one of the Core classes and should be read at least once by any new developers.
Definition: OutputPage.php:47
ApiResult\addValue
addValue( $path, $name, $value, $flags=0)
Add value to the output data at the given path.
Definition: ApiResult.php:393
MWDebug\log
static log( $str)
Adds a line to the log.
Definition: MWDebug.php:137
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:623
$line
$line
Definition: mcc.php:119
$wgDevelopmentWarnings
$wgDevelopmentWarnings
If set to true MediaWiki will throw notices for some possible error conditions and for deprecated fun...
Definition: DefaultSettings.php:6781
GitInfo\currentBranch
static currentBranch()
Definition: GitInfo.php:410
MWDebug\init
static init()
Enabled the debugger and load resource module.
Definition: MWDebug.php:105
MWDebug\deinit
static deinit()
Disable the debugger.
Definition: MWDebug.php:114
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
MWDebug\filterDeprecationForTest
static filterDeprecationForTest( $regex)
Deprecation messages matching the supplied regex will be suppressed.
Definition: MWDebug.php:352
$wgDebugComments
$wgDebugComments
Send debug data to an HTML comment in the output.
Definition: DefaultSettings.php:6586
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
wfBacktrace
wfBacktrace( $raw=null)
Get a debug backtrace as a string.
Definition: GlobalFunctions.php:1353
MWDebug\addModules
static addModules(OutputPage $out)
Add ResourceLoader modules to the OutputPage object if debugging is enabled.
Definition: MWDebug.php:125
MWDebug\$deprecationFilters
static string[] $deprecationFilters
Deprecation filter regexes.
Definition: MWDebug.php:73
IContextSource\getRequest
getRequest()
MWDebug\formatCallerDescription
static formatCallerDescription( $msg, $caller)
Append a caller description to an error message.
Definition: MWDebug.php:410
MediaWiki\Logger\LegacyLogger
PSR-3 logger that mimics the historic implementation of MediaWiki's former wfErrorLog logging impleme...
Definition: LegacyLogger.php:51
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
MWDebug\warning
static warning( $msg, $callerOffset=1, $level=E_USER_NOTICE, $log='auto')
Adds a warning entry to the log.
Definition: MWDebug.php:180
$wgDebugToolbar
$wgDebugToolbar
Display the new debugging toolbar.
Definition: DefaultSettings.php:6916
MWDebug\parseCallerDescription
static parseCallerDescription( $msg)
Append a caller description to an error message.
Definition: MWDebug.php:427
IContextSource\getOutput
getOutput()
MWDebug\$query
static $query
SQL statements of the database queries.
Definition: MWDebug.php:53
wfGetCaller
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1390
MWDebug\sendRawDeprecated
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:321
MWDebug\deprecatedMsg
static deprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: MWDebug.php:257
IContextSource\getLanguage
getLanguage()
MWDebug\$log
static $log
Log lines.
Definition: MWDebug.php:39
MWDebug\$enabled
static $enabled
Is the debugger enabled?
Definition: MWDebug.php:60