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
138 * @param int $level A PHP error level. See sendWarning()
141 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE
) {
142 $callerDescription = self
::getCallerDescription( $callerOffset );
144 self
::sendWarning( $msg, $callerDescription, $level );
146 if ( self
::$enabled ) {
147 self
::$log[] = array(
148 'msg' => htmlspecialchars( $msg ),
150 'caller' => $callerDescription['func'],
156 * Show a warning that $function is deprecated.
157 * This will send it to the following locations:
158 * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
160 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
162 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
165 * @param string $function Function that is deprecated.
166 * @param string|bool $version Version in which the function was deprecated.
167 * @param string|bool $component Component to which the function belongs.
168 * If false, it is assumbed the function is in MediaWiki core.
169 * @param $callerOffset integer: How far up the callstack is the original
170 * caller. 2 = function that called the function that called
171 * MWDebug::deprecated() (Added in 1.20).
174 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
175 $callerDescription = self
::getCallerDescription( $callerOffset );
176 $callerFunc = $callerDescription['func'];
180 // Check to see if there already was a warning about this function
181 if ( isset( self
::$deprecationWarnings[$function][$callerFunc] ) ) {
183 } elseif ( isset( self
::$deprecationWarnings[$function] ) ) {
184 if ( self
::$enabled ) {
191 self
::$deprecationWarnings[$function][$callerFunc] = true;
194 global $wgDeprecationReleaseLimit;
195 if ( $wgDeprecationReleaseLimit && $component === false ) {
196 # Strip -* off the end of $version so that branches can use the
197 # format #.##-branchname to avoid issues if the branch is merged into
198 # a version of MediaWiki later than what it was branched from
199 $comparableVersion = preg_replace( '/-.*$/', '', $version );
201 # If the comparableVersion is larger than our release limit then
202 # skip the warning message for the deprecation
203 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
208 $component = $component === false ?
'MediaWiki' : $component;
209 $msg = "Use of $function was deprecated in $component $version.";
211 $msg = "Use of $function is deprecated.";
215 self
::sendWarning( $msg, $callerDescription, E_USER_DEPRECATED
);
218 if ( self
::$enabled ) {
219 $logMsg = htmlspecialchars( $msg ) .
220 Html
::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
221 Html
::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
224 self
::$log[] = array(
226 'type' => 'deprecated',
227 'caller' => $callerFunc,
233 * Get an array describing the calling function at a specified offset.
235 * @param $callerOffset integer: How far up the callstack is the original
236 * caller. 0 = function that called getCallerDescription()
237 * @return array with two keys: 'file' and 'func'
239 private static function getCallerDescription( $callerOffset ) {
240 $callers = wfDebugBacktrace();
242 if ( isset( $callers[$callerOffset] ) ) {
243 $callerfile = $callers[$callerOffset];
244 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
245 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
247 $file = '(internal function)';
250 $file = '(unknown location)';
253 if ( isset( $callers[$callerOffset +
1] ) ) {
254 $callerfunc = $callers[$callerOffset +
1];
256 if ( isset( $callerfunc['class'] ) ) {
257 $func .= $callerfunc['class'] . '::';
259 if ( isset( $callerfunc['function'] ) ) {
260 $func .= $callerfunc['function'];
266 return array( 'file' => $file, 'func' => $func );
270 * Send a warning either to the debug log or by triggering an user PHP
271 * error depending on $wgDevelopmentWarnings.
273 * @param string $msg Message to send
274 * @param array $caller caller description get from getCallerDescription()
275 * @param $level error level to use if $wgDevelopmentWarnings is true
277 private static function sendWarning( $msg, $caller, $level ) {
278 global $wgDevelopmentWarnings;
280 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
282 if ( $wgDevelopmentWarnings ) {
283 trigger_error( $msg, $level );
290 * This is a method to pass messages from wfDebug to the pretty debugger.
291 * Do NOT use this method, use MWDebug::log or wfDebug()
296 public static function debugMsg( $str ) {
297 global $wgDebugComments, $wgShowDebug;
299 if ( self
::$enabled ||
$wgDebugComments ||
$wgShowDebug ) {
300 self
::$debug[] = rtrim( $str );
305 * Begins profiling on a database query
309 * @param $function string
310 * @param $isMaster bool
311 * @return int ID number of the query to pass to queryTime or -1 if the
312 * debugger is disabled
314 public static function query( $sql, $function, $isMaster ) {
315 if ( !self
::$enabled ) {
319 self
::$query[] = array(
321 'function' => $function,
322 'master' => (bool) $isMaster,
324 '_start' => microtime( true ),
327 return count( self
::$query ) - 1;
331 * Calculates how long a query took.
336 public static function queryTime( $id ) {
337 if ( $id === -1 ||
!self
::$enabled ) {
341 self
::$query[$id]['time'] = microtime( true ) - self
::$query[$id]['_start'];
342 unset( self
::$query[$id]['_start'] );
346 * Returns a list of files included, along with their size
348 * @param $context IContextSource
351 protected static function getFilesIncluded( IContextSource
$context ) {
352 $files = get_included_files();
354 foreach ( $files as $file ) {
355 $size = filesize( $file );
358 'size' => $context->getLanguage()->formatSize( $size ),
366 * Returns the HTML to add to the page for the toolbar
369 * @param $context IContextSource
372 public static function getDebugHTML( IContextSource
$context ) {
373 global $wgDebugComments;
377 if ( self
::$enabled ) {
378 MWDebug
::log( 'MWDebug output complete' );
379 $debugInfo = self
::getDebugInfo( $context );
381 // Cannot use OutputPage::addJsConfigVars because those are already outputted
382 // by the time this method is called.
383 $html = Html
::inlineScript(
384 ResourceLoader
::makeLoaderConditionalScript(
385 ResourceLoader
::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
390 if ( $wgDebugComments ) {
391 $html .= "<!-- Debug output:\n" .
392 htmlspecialchars( implode( "\n", self
::$debug ) ) .
400 * Generate debug log in HTML for displaying at the bottom of the main
402 * If $wgShowDebug is false, an empty string is always returned.
405 * @return string HTML fragment
407 public static function getHTMLDebugLog() {
408 global $wgDebugTimestamps, $wgShowDebug;
410 if ( !$wgShowDebug ) {
415 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
417 foreach ( self
::$debug as $line ) {
419 if ( $wgDebugTimestamps ) {
421 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
423 $line = substr( $line, strlen( $pre ) );
426 $display = ltrim( $line );
427 $ident = strlen( $line ) - strlen( $display );
428 $diff = $ident - $curIdent;
430 $display = $pre . $display;
431 if ( $display == '' ) {
432 $display = "\xc2\xa0";
435 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
438 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
440 $display = nl2br( htmlspecialchars( $display ) );
444 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
445 } elseif ( $diff == 0 ) {
446 $ret .= "</li><li>\n";
448 $ret .= str_repeat( "<ul><li>\n", $diff );
450 $ret .= "<tt>$display</tt>\n";
455 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
461 * Append the debug info to given ApiResult
463 * @param $context IContextSource
464 * @param $result ApiResult
466 public static function appendDebugInfoToApiResult( IContextSource
$context, ApiResult
$result ) {
467 if ( !self
::$enabled ) {
471 // output errors as debug info, when display_errors is on
472 // this is necessary for all non html output of the api, because that clears all errors first
473 $obContents = ob_get_contents();
475 $obContentArray = explode( '<br />', $obContents );
476 foreach( $obContentArray as $obContent ) {
477 if( trim( $obContent ) ) {
478 self
::debugMsg( Sanitizer
::stripAllTags( $obContent ) );
483 MWDebug
::log( 'MWDebug output complete' );
484 $debugInfo = self
::getDebugInfo( $context );
486 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
487 $result->setIndexedTagName( $debugInfo['log'], 'line' );
488 foreach( $debugInfo['debugLog'] as $index => $debugLogText ) {
490 ApiResult
::setContent( $vals, $debugLogText );
491 $debugInfo['debugLog'][$index] = $vals; //replace
493 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
494 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
495 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
496 $result->addValue( array(), 'debuginfo', $debugInfo );
500 * Returns the HTML to add to the page for the toolbar
502 * @param $context IContextSource
505 public static function getDebugInfo( IContextSource
$context ) {
506 if ( !self
::$enabled ) {
510 global $wgVersion, $wgRequestTime;
511 $request = $context->getRequest();
513 'mwVersion' => $wgVersion,
514 'phpVersion' => PHP_VERSION
,
515 'gitRevision' => GitInfo
::headSHA1(),
516 'gitBranch' => GitInfo
::currentBranch(),
517 'gitViewUrl' => GitInfo
::headViewUrl(),
518 'time' => microtime( true ) - $wgRequestTime,
520 'debugLog' => self
::$debug,
521 'queries' => self
::$query,
523 'method' => $request->getMethod(),
524 'url' => $request->getRequestURL(),
525 'headers' => $request->getAllHeaders(),
526 'params' => $request->getValues(),
528 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
529 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
530 'includes' => self
::getFilesIncluded( $context ),