3 * Debug toolbar related code
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.
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.
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
24 * New debugger system that outputs a toolbar on page view
26 * By default, most methods do nothing ( self::$enabled = false ). You have
27 * to explicitly call MWDebug::init() to enabled them.
29 * @todo Profiler support
40 protected static $log = array();
43 * Debug messages from wfDebug()
47 protected static $debug = array();
54 protected static $query = array();
57 * Is the debugger enabled?
61 protected static $enabled = false;
64 * Array of functions that have already been warned, formatted
65 * function-caller to prevent a buttload of warnings
69 protected static $deprecationWarnings = array();
72 * Enabled the debugger and load resource module.
73 * This is called by Setup.php when $wgDebugToolbar is true.
77 public static function init() {
78 self
::$enabled = true;
82 * Add ResourceLoader modules to the OutputPage object if debugging is
86 * @param $out OutputPage
88 public static function addModules( OutputPage
$out ) {
89 if ( self
::$enabled ) {
90 $out->addModules( 'mediawiki.debug.init' );
95 * Adds a line to the log
97 * @todo Add support for passing objects
102 public static function log( $str ) {
103 if ( !self
::$enabled ) {
107 self
::$log[] = array(
108 'msg' => htmlspecialchars( $str ),
110 'caller' => wfGetCaller(),
115 * Returns internal log array
119 public static function getLog() {
124 * Clears internal log array and deprecation tracking
127 public static function clearLog() {
128 self
::$log = array();
129 self
::$deprecationWarnings = array();
133 * Adds a warning entry to the log
137 * @param $callerOffset int
140 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
141 $callerDescription = self
::getCallerDescription( $callerOffset );
143 self
::sendWarning( $msg, $callerDescription, $level );
145 if ( self
::$enabled ) {
146 self
::$log[] = array(
147 'msg' => htmlspecialchars( $msg ),
149 'caller' => $callerDescription['func'],
155 * Show a warning that $function is deprecated.
156 * This will send it to the following locations:
157 * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
159 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
161 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
164 * @param $function string: Function that is deprecated.
165 * @param $version string|bool: Version in which the function was deprecated.
166 * @param $component string|bool: Component to which the function belongs.
167 * If false, it is assumbed the function is in MediaWiki core.
168 * @param $callerOffset integer: How far up the callstack is the original
169 * caller. 2 = function that called the function that called
170 * MWDebug::deprecated() (Added in 1.20).
173 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
174 $callerDescription = self
::getCallerDescription( $callerOffset );
175 $callerFunc = $callerDescription['func'];
179 // Check to see if there already was a warning about this function
180 if ( isset( self
::$deprecationWarnings[$function][$callerFunc] ) ) {
182 } elseif ( isset( self
::$deprecationWarnings[$function] ) ) {
183 if ( self
::$enabled ) {
190 self
::$deprecationWarnings[$function][$callerFunc] = true;
193 global $wgDeprecationReleaseLimit;
194 if ( $wgDeprecationReleaseLimit && $component === false ) {
195 # Strip -* off the end of $version so that branches can use the
196 # format #.##-branchname to avoid issues if the branch is merged into
197 # a version of MediaWiki later than what it was branched from
198 $comparableVersion = preg_replace( '/-.*$/', '', $version );
200 # If the comparableVersion is larger than our release limit then
201 # skip the warning message for the deprecation
202 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
207 $component = $component === false ?
'MediaWiki' : $component;
208 $msg = "Use of $function was deprecated in $component $version.";
210 $msg = "Use of $function is deprecated.";
214 self
::sendWarning( $msg, $callerDescription, E_USER_DEPRECATED
);
217 if ( self
::$enabled ) {
218 $logMsg = htmlspecialchars( $msg ) .
219 Html
::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
220 Html
::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
223 self
::$log[] = array(
225 'type' => 'deprecated',
226 'caller' => $callerFunc,
232 * Get an array describing the calling function at a specified offset.
234 * @param $callerOffset integer: How far up the callstack is the original
235 * caller. 0 = function that called getCallerDescription()
236 * @return array with two keys: 'file' and 'func'
238 private static function getCallerDescription( $callerOffset ) {
239 $callers = wfDebugBacktrace();
241 if ( isset( $callers[$callerOffset] ) ) {
242 $callerfile = $callers[$callerOffset];
243 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
244 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
246 $file = '(internal function)';
249 $file = '(unknown location)';
252 if ( isset( $callers[$callerOffset +
1] ) ) {
253 $callerfunc = $callers[$callerOffset +
1];
255 if ( isset( $callerfunc['class'] ) ) {
256 $func .= $callerfunc['class'] . '::';
258 if ( isset( $callerfunc['function'] ) ) {
259 $func .= $callerfunc['function'];
265 return array( 'file' => $file, 'func' => $func );
269 * Send a warning either to the debug log or by triggering an user PHP
270 * error depending on $wgDevelopmentWarnings.
272 * @param $msg string Message to send
273 * @param $caller array caller description get from getCallerDescription()
274 * @param $level error level to use if $wgDevelopmentWarnings is true
276 private static function sendWarning( $msg, $caller, $level ) {
277 global $wgDevelopmentWarnings;
279 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
281 if ( $wgDevelopmentWarnings ) {
282 trigger_error( $msg, $level );
289 * This is a method to pass messages from wfDebug to the pretty debugger.
290 * Do NOT use this method, use MWDebug::log or wfDebug()
295 public static function debugMsg( $str ) {
296 global $wgDebugComments, $wgShowDebug;
298 if ( self
::$enabled ||
$wgDebugComments ||
$wgShowDebug ) {
299 self
::$debug[] = rtrim( $str );
304 * Begins profiling on a database query
308 * @param $function string
309 * @param $isMaster bool
310 * @return int ID number of the query to pass to queryTime or -1 if the
311 * debugger is disabled
313 public static function query( $sql, $function, $isMaster ) {
314 if ( !self
::$enabled ) {
318 self
::$query[] = array(
320 'function' => $function,
321 'master' => (bool) $isMaster,
323 '_start' => microtime( true ),
326 return count( self
::$query ) - 1;
330 * Calculates how long a query took.
335 public static function queryTime( $id ) {
336 if ( $id === -1 ||
!self
::$enabled ) {
340 self
::$query[$id]['time'] = microtime( true ) - self
::$query[$id]['_start'];
341 unset( self
::$query[$id]['_start'] );
345 * Returns a list of files included, along with their size
347 * @param $context IContextSource
350 protected static function getFilesIncluded( IContextSource
$context ) {
351 $files = get_included_files();
353 foreach ( $files as $file ) {
354 $size = filesize( $file );
357 'size' => $context->getLanguage()->formatSize( $size ),
365 * Returns the HTML to add to the page for the toolbar
368 * @param $context IContextSource
371 public static function getDebugHTML( IContextSource
$context ) {
372 global $wgDebugComments;
376 if ( self
::$enabled ) {
377 MWDebug
::log( 'MWDebug output complete' );
378 $debugInfo = self
::getDebugInfo( $context );
380 // Cannot use OutputPage::addJsConfigVars because those are already outputted
381 // by the time this method is called.
382 $html = Html
::inlineScript(
383 ResourceLoader
::makeLoaderConditionalScript(
384 ResourceLoader
::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
389 if ( $wgDebugComments ) {
390 $html .= "<!-- Debug output:\n" .
391 htmlspecialchars( implode( "\n", self
::$debug ) ) .
399 * Generate debug log in HTML for displaying at the bottom of the main
401 * If $wgShowDebug is false, an empty string is always returned.
404 * @return string HTML fragment
406 public static function getHTMLDebugLog() {
407 global $wgDebugTimestamps, $wgShowDebug;
409 if ( !$wgShowDebug ) {
414 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
416 foreach ( self
::$debug as $line ) {
418 if ( $wgDebugTimestamps ) {
420 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
422 $line = substr( $line, strlen( $pre ) );
425 $display = ltrim( $line );
426 $ident = strlen( $line ) - strlen( $display );
427 $diff = $ident - $curIdent;
429 $display = $pre . $display;
430 if ( $display == '' ) {
431 $display = "\xc2\xa0";
434 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
437 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
439 $display = nl2br( htmlspecialchars( $display ) );
443 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
444 } elseif ( $diff == 0 ) {
445 $ret .= "</li><li>\n";
447 $ret .= str_repeat( "<ul><li>\n", $diff );
449 $ret .= "<tt>$display</tt>\n";
454 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
460 * Append the debug info to given ApiResult
462 * @param $context IContextSource
463 * @param $result ApiResult
465 public static function appendDebugInfoToApiResult( IContextSource
$context, ApiResult
$result ) {
466 if ( !self
::$enabled ) {
470 // output errors as debug info, when display_errors is on
471 // this is necessary for all non html output of the api, because that clears all errors first
472 $obContents = ob_get_contents();
474 $obContentArray = explode( '<br />', $obContents );
475 foreach( $obContentArray as $obContent ) {
476 if( trim( $obContent ) ) {
477 self
::debugMsg( Sanitizer
::stripAllTags( $obContent ) );
482 MWDebug
::log( 'MWDebug output complete' );
483 $debugInfo = self
::getDebugInfo( $context );
485 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
486 $result->setIndexedTagName( $debugInfo['log'], 'line' );
487 foreach( $debugInfo['debugLog'] as $index => $debugLogText ) {
489 ApiResult
::setContent( $vals, $debugLogText );
490 $debugInfo['debugLog'][$index] = $vals; //replace
492 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
493 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
494 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
495 $result->addValue( array(), 'debuginfo', $debugInfo );
499 * Returns the HTML to add to the page for the toolbar
501 * @param $context IContextSource
504 public static function getDebugInfo( IContextSource
$context ) {
505 if ( !self
::$enabled ) {
509 global $wgVersion, $wgRequestTime;
510 $request = $context->getRequest();
512 'mwVersion' => $wgVersion,
513 'phpVersion' => PHP_VERSION
,
514 'gitRevision' => GitInfo
::headSHA1(),
515 'gitBranch' => GitInfo
::currentBranch(),
516 'gitViewUrl' => GitInfo
::headViewUrl(),
517 'time' => microtime( true ) - $wgRequestTime,
519 'debugLog' => self
::$debug,
520 'queries' => self
::$query,
522 'method' => $request->getMethod(),
523 'url' => $request->getRequestURL(),
524 'headers' => $request->getAllHeaders(),
525 'params' => $request->getValues(),
527 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
528 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
529 'includes' => self
::getFilesIncluded( $context ),