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();
50 * SQL statements of the databses queries.
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
67 * @var array $deprecationWarnings
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 $level int A PHP error level. See sendWarning()
139 * @param $log string: 'production' will always trigger a php error, 'auto'
140 * will trigger an error if $wgDevelopmentWarnings is true, and 'debug'
141 * will only write to the debug log(s).
145 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE
, $log = 'auto' ) {
146 global $wgDevelopmentWarnings;
148 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
152 if ( $log === 'debug' ) {
156 $callerDescription = self
::getCallerDescription( $callerOffset );
158 self
::sendWarning( $msg, $callerDescription, $level );
160 if ( self
::$enabled ) {
161 self
::$log[] = array(
162 'msg' => htmlspecialchars( $msg ),
164 'caller' => $callerDescription['func'],
170 * Show a warning that $function is deprecated.
171 * This will send it to the following locations:
172 * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
174 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
176 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
179 * @param string $function Function that is deprecated.
180 * @param string|bool $version Version in which the function was deprecated.
181 * @param string|bool $component Component to which the function belongs.
182 * If false, it is assumbed the function is in MediaWiki core.
183 * @param $callerOffset integer: How far up the callstack is the original
184 * caller. 2 = function that called the function that called
185 * MWDebug::deprecated() (Added in 1.20).
188 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
189 $callerDescription = self
::getCallerDescription( $callerOffset );
190 $callerFunc = $callerDescription['func'];
194 // Check to see if there already was a warning about this function
195 if ( isset( self
::$deprecationWarnings[$function][$callerFunc] ) ) {
197 } elseif ( isset( self
::$deprecationWarnings[$function] ) ) {
198 if ( self
::$enabled ) {
205 self
::$deprecationWarnings[$function][$callerFunc] = true;
208 global $wgDeprecationReleaseLimit;
209 if ( $wgDeprecationReleaseLimit && $component === false ) {
210 # Strip -* off the end of $version so that branches can use the
211 # format #.##-branchname to avoid issues if the branch is merged into
212 # a version of MediaWiki later than what it was branched from
213 $comparableVersion = preg_replace( '/-.*$/', '', $version );
215 # If the comparableVersion is larger than our release limit then
216 # skip the warning message for the deprecation
217 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
222 $component = $component === false ?
'MediaWiki' : $component;
223 $msg = "Use of $function was deprecated in $component $version.";
225 $msg = "Use of $function is deprecated.";
229 global $wgDevelopmentWarnings; // we could have a more specific $wgDeprecationWarnings setting.
230 self
::sendWarning( $msg, $callerDescription, $wgDevelopmentWarnings ? E_USER_DEPRECATED
: false );
233 if ( self
::$enabled ) {
234 $logMsg = htmlspecialchars( $msg ) .
235 Html
::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
236 Html
::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
239 self
::$log[] = array(
241 'type' => 'deprecated',
242 'caller' => $callerFunc,
248 * Get an array describing the calling function at a specified offset.
250 * @param $callerOffset integer: How far up the callstack is the original
251 * caller. 0 = function that called getCallerDescription()
252 * @return array with two keys: 'file' and 'func'
254 private static function getCallerDescription( $callerOffset ) {
255 $callers = wfDebugBacktrace();
257 if ( isset( $callers[$callerOffset] ) ) {
258 $callerfile = $callers[$callerOffset];
259 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
260 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
262 $file = '(internal function)';
265 $file = '(unknown location)';
268 if ( isset( $callers[$callerOffset +
1] ) ) {
269 $callerfunc = $callers[$callerOffset +
1];
271 if ( isset( $callerfunc['class'] ) ) {
272 $func .= $callerfunc['class'] . '::';
274 if ( isset( $callerfunc['function'] ) ) {
275 $func .= $callerfunc['function'];
281 return array( 'file' => $file, 'func' => $func );
285 * Send a warning to the debug log and optionally also trigger a PHP
286 * error, depending on the $level argument.
288 * @param $msg string Message to send
289 * @param $caller array caller description get from getCallerDescription()
290 * @param $level int|bool error level to use; set to false to not trigger an error
292 private static function sendWarning( $msg, $caller, $level ) {
293 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
295 if ( $level !== false ) {
296 trigger_error( $msg, $level );
303 * This is a method to pass messages from wfDebug to the pretty debugger.
304 * Do NOT use this method, use MWDebug::log or wfDebug()
309 public static function debugMsg( $str ) {
310 global $wgDebugComments, $wgShowDebug;
312 if ( self
::$enabled ||
$wgDebugComments ||
$wgShowDebug ) {
313 self
::$debug[] = rtrim( UtfNormal
::cleanUp( $str ) );
318 * Begins profiling on a database query
322 * @param $function string
323 * @param $isMaster bool
324 * @return int ID number of the query to pass to queryTime or -1 if the
325 * debugger is disabled
327 public static function query( $sql, $function, $isMaster ) {
328 if ( !self
::$enabled ) {
332 self
::$query[] = array(
334 'function' => $function,
335 'master' => (bool) $isMaster,
337 '_start' => microtime( true ),
340 return count( self
::$query ) - 1;
344 * Calculates how long a query took.
349 public static function queryTime( $id ) {
350 if ( $id === -1 ||
!self
::$enabled ) {
354 self
::$query[$id]['time'] = microtime( true ) - self
::$query[$id]['_start'];
355 unset( self
::$query[$id]['_start'] );
359 * Returns a list of files included, along with their size
361 * @param $context IContextSource
364 protected static function getFilesIncluded( IContextSource
$context ) {
365 $files = get_included_files();
367 foreach ( $files as $file ) {
368 $size = filesize( $file );
371 'size' => $context->getLanguage()->formatSize( $size ),
379 * Returns the HTML to add to the page for the toolbar
382 * @param $context IContextSource
385 public static function getDebugHTML( IContextSource
$context ) {
386 global $wgDebugComments;
390 if ( self
::$enabled ) {
391 MWDebug
::log( 'MWDebug output complete' );
392 $debugInfo = self
::getDebugInfo( $context );
394 // Cannot use OutputPage::addJsConfigVars because those are already outputted
395 // by the time this method is called.
396 $html = Html
::inlineScript(
397 ResourceLoader
::makeLoaderConditionalScript(
398 ResourceLoader
::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
403 if ( $wgDebugComments ) {
404 $html .= "<!-- Debug output:\n" .
405 htmlspecialchars( implode( "\n", self
::$debug ) ) .
413 * Generate debug log in HTML for displaying at the bottom of the main
415 * If $wgShowDebug is false, an empty string is always returned.
418 * @return string HTML fragment
420 public static function getHTMLDebugLog() {
421 global $wgDebugTimestamps, $wgShowDebug;
423 if ( !$wgShowDebug ) {
428 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
430 foreach ( self
::$debug as $line ) {
432 if ( $wgDebugTimestamps ) {
434 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
436 $line = substr( $line, strlen( $pre ) );
439 $display = ltrim( $line );
440 $ident = strlen( $line ) - strlen( $display );
441 $diff = $ident - $curIdent;
443 $display = $pre . $display;
444 if ( $display == '' ) {
445 $display = "\xc2\xa0";
448 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
451 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
453 $display = nl2br( htmlspecialchars( $display ) );
457 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
458 } elseif ( $diff == 0 ) {
459 $ret .= "</li><li>\n";
461 $ret .= str_repeat( "<ul><li>\n", $diff );
463 $ret .= "<tt>$display</tt>\n";
468 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
474 * Append the debug info to given ApiResult
476 * @param $context IContextSource
477 * @param $result ApiResult
479 public static function appendDebugInfoToApiResult( IContextSource
$context, ApiResult
$result ) {
480 if ( !self
::$enabled ) {
484 // output errors as debug info, when display_errors is on
485 // this is necessary for all non html output of the api, because that clears all errors first
486 $obContents = ob_get_contents();
488 $obContentArray = explode( '<br />', $obContents );
489 foreach ( $obContentArray as $obContent ) {
490 if ( trim( $obContent ) ) {
491 self
::debugMsg( Sanitizer
::stripAllTags( $obContent ) );
496 MWDebug
::log( 'MWDebug output complete' );
497 $debugInfo = self
::getDebugInfo( $context );
499 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
500 $result->setIndexedTagName( $debugInfo['log'], 'line' );
501 foreach ( $debugInfo['debugLog'] as $index => $debugLogText ) {
503 ApiResult
::setContent( $vals, $debugLogText );
504 $debugInfo['debugLog'][$index] = $vals; //replace
506 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
507 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
508 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
509 $result->addValue( array(), 'debuginfo', $debugInfo );
513 * Returns the HTML to add to the page for the toolbar
515 * @param $context IContextSource
518 public static function getDebugInfo( IContextSource
$context ) {
519 if ( !self
::$enabled ) {
523 global $wgVersion, $wgRequestTime;
524 $request = $context->getRequest();
526 'mwVersion' => $wgVersion,
527 'phpVersion' => PHP_VERSION
,
528 'gitRevision' => GitInfo
::headSHA1(),
529 'gitBranch' => GitInfo
::currentBranch(),
530 'gitViewUrl' => GitInfo
::headViewUrl(),
531 'time' => microtime( true ) - $wgRequestTime,
533 'debugLog' => self
::$debug,
534 'queries' => self
::$query,
536 'method' => $request->getMethod(),
537 'url' => $request->getRequestURL(),
538 'headers' => $request->getAllHeaders(),
539 'params' => $request->getValues(),
541 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
542 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
543 'includes' => self
::getFilesIncluded( $context ),