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
39 protected static $log = array();
42 * Debug messages from wfDebug().
46 protected static $debug = array();
49 * SQL statements of the databses queries.
53 protected static $query = array();
56 * Is the debugger enabled?
60 protected static $enabled = false;
63 * Array of functions that have already been warned, formatted
64 * function-caller to prevent a buttload of warnings
66 * @var array $deprecationWarnings
68 protected static $deprecationWarnings = array();
71 * Enabled the debugger and load resource module.
72 * This is called by Setup.php when $wgDebugToolbar is true.
76 public static function init() {
77 self
::$enabled = true;
81 * Add ResourceLoader modules to the OutputPage object if debugging is
85 * @param OutputPage $out
87 public static function addModules( OutputPage
$out ) {
88 if ( self
::$enabled ) {
89 $out->addModules( 'mediawiki.debug.init' );
94 * Adds a line to the log
96 * @todo Add support for passing objects
101 public static function log( $str ) {
102 if ( !self
::$enabled ) {
106 self
::$log[] = array(
107 'msg' => htmlspecialchars( $str ),
109 'caller' => wfGetCaller(),
114 * Returns internal log array
118 public static function getLog() {
123 * Clears internal log array and deprecation tracking
126 public static function clearLog() {
127 self
::$log = array();
128 self
::$deprecationWarnings = array();
132 * Adds a warning entry to the log
136 * @param int $callerOffset
137 * @param int $level A PHP error level. See sendMessage()
138 * @param string $log 'production' will always trigger a php error, 'auto'
139 * will trigger an error if $wgDevelopmentWarnings is true, and 'debug'
140 * will only write to the debug log(s).
144 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE
, $log = 'auto' ) {
145 global $wgDevelopmentWarnings;
147 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
151 if ( $log === 'debug' ) {
155 $callerDescription = self
::getCallerDescription( $callerOffset );
157 self
::sendMessage( $msg, $callerDescription, 'warning', $level );
159 if ( self
::$enabled ) {
160 self
::$log[] = array(
161 'msg' => htmlspecialchars( $msg ),
163 'caller' => $callerDescription['func'],
169 * Show a warning that $function is deprecated.
170 * This will send it to the following locations:
171 * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
173 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
175 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
178 * @param string $function Function that is deprecated.
179 * @param string|bool $version Version in which the function was deprecated.
180 * @param string|bool $component Component to which the function belongs.
181 * If false, it is assumbed the function is in MediaWiki core.
182 * @param int $callerOffset How far up the callstack is the original
183 * caller. 2 = function that called the function that called
184 * MWDebug::deprecated() (Added in 1.20).
186 public static function deprecated( $function, $version = false,
187 $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.
234 $wgDevelopmentWarnings ? E_USER_DEPRECATED
: false
238 if ( self
::$enabled ) {
239 $logMsg = htmlspecialchars( $msg ) .
240 Html
::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
241 Html
::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
244 self
::$log[] = array(
246 'type' => 'deprecated',
247 'caller' => $callerFunc,
253 * Get an array describing the calling function at a specified offset.
255 * @param int $callerOffset How far up the callstack is the original
256 * caller. 0 = function that called getCallerDescription()
257 * @return array Array with two keys: 'file' and 'func'
259 private static function getCallerDescription( $callerOffset ) {
260 $callers = wfDebugBacktrace();
262 if ( isset( $callers[$callerOffset] ) ) {
263 $callerfile = $callers[$callerOffset];
264 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
265 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
267 $file = '(internal function)';
270 $file = '(unknown location)';
273 if ( isset( $callers[$callerOffset +
1] ) ) {
274 $callerfunc = $callers[$callerOffset +
1];
276 if ( isset( $callerfunc['class'] ) ) {
277 $func .= $callerfunc['class'] . '::';
279 if ( isset( $callerfunc['function'] ) ) {
280 $func .= $callerfunc['function'];
286 return array( 'file' => $file, 'func' => $func );
290 * Send a message to the debug log and optionally also trigger a PHP
291 * error, depending on the $level argument.
293 * @param string $msg Message to send
294 * @param array $caller Caller description get from getCallerDescription()
295 * @param string $group Log group on which to send the message
296 * @param int|bool $level Error level to use; set to false to not trigger an error
298 private static function sendMessage( $msg, $caller, $group, $level ) {
299 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
301 if ( $level !== false ) {
302 trigger_error( $msg, $level );
305 wfDebugLog( $group, $msg, 'log' );
309 * This is a method to pass messages from wfDebug to the pretty debugger.
310 * Do NOT use this method, use MWDebug::log or wfDebug()
315 public static function debugMsg( $str ) {
316 global $wgDebugComments, $wgShowDebug;
318 if ( self
::$enabled ||
$wgDebugComments ||
$wgShowDebug ) {
319 self
::$debug[] = rtrim( UtfNormal
::cleanUp( $str ) );
324 * Begins profiling on a database query
328 * @param string $function
329 * @param bool $isMaster
330 * @return int ID number of the query to pass to queryTime or -1 if the
331 * debugger is disabled
333 public static function query( $sql, $function, $isMaster ) {
334 if ( !self
::$enabled ) {
338 self
::$query[] = array(
340 'function' => $function,
341 'master' => (bool)$isMaster,
343 '_start' => microtime( true ),
346 return count( self
::$query ) - 1;
350 * Calculates how long a query took.
355 public static function queryTime( $id ) {
356 if ( $id === -1 ||
!self
::$enabled ) {
360 self
::$query[$id]['time'] = microtime( true ) - self
::$query[$id]['_start'];
361 unset( self
::$query[$id]['_start'] );
365 * Returns a list of files included, along with their size
367 * @param IContextSource $context
370 protected static function getFilesIncluded( IContextSource
$context ) {
371 $files = get_included_files();
373 foreach ( $files as $file ) {
374 $size = filesize( $file );
377 'size' => $context->getLanguage()->formatSize( $size ),
385 * Returns the HTML to add to the page for the toolbar
388 * @param IContextSource $context
391 public static function getDebugHTML( IContextSource
$context ) {
392 global $wgDebugComments;
396 if ( self
::$enabled ) {
397 MWDebug
::log( 'MWDebug output complete' );
398 $debugInfo = self
::getDebugInfo( $context );
400 // Cannot use OutputPage::addJsConfigVars because those are already outputted
401 // by the time this method is called.
402 $html = Html
::inlineScript(
403 ResourceLoader
::makeLoaderConditionalScript(
404 ResourceLoader
::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
409 if ( $wgDebugComments ) {
410 $html .= "<!-- Debug output:\n" .
411 htmlspecialchars( implode( "\n", self
::$debug ) ) .
419 * Generate debug log in HTML for displaying at the bottom of the main
421 * If $wgShowDebug is false, an empty string is always returned.
424 * @return string HTML fragment
426 public static function getHTMLDebugLog() {
427 global $wgDebugTimestamps, $wgShowDebug;
429 if ( !$wgShowDebug ) {
434 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
436 foreach ( self
::$debug as $line ) {
438 if ( $wgDebugTimestamps ) {
440 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
442 $line = substr( $line, strlen( $pre ) );
445 $display = ltrim( $line );
446 $ident = strlen( $line ) - strlen( $display );
447 $diff = $ident - $curIdent;
449 $display = $pre . $display;
450 if ( $display == '' ) {
451 $display = "\xc2\xa0";
456 && substr( $display, 0, 9 ) != 'Entering '
457 && substr( $display, 0, 8 ) != 'Exiting '
461 $display = '<span style="background:yellow;">' .
462 nl2br( htmlspecialchars( $display ) ) . '</span>';
464 $display = nl2br( htmlspecialchars( $display ) );
468 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
469 } elseif ( $diff == 0 ) {
470 $ret .= "</li><li>\n";
472 $ret .= str_repeat( "<ul><li>\n", $diff );
474 $ret .= "<code>$display</code>\n";
479 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
485 * Append the debug info to given ApiResult
487 * @param IContextSource $context
488 * @param ApiResult $result
490 public static function appendDebugInfoToApiResult( IContextSource
$context, ApiResult
$result ) {
491 if ( !self
::$enabled ) {
495 // output errors as debug info, when display_errors is on
496 // this is necessary for all non html output of the api, because that clears all errors first
497 $obContents = ob_get_contents();
499 $obContentArray = explode( '<br />', $obContents );
500 foreach ( $obContentArray as $obContent ) {
501 if ( trim( $obContent ) ) {
502 self
::debugMsg( Sanitizer
::stripAllTags( $obContent ) );
507 MWDebug
::log( 'MWDebug output complete' );
508 $debugInfo = self
::getDebugInfo( $context );
510 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
511 $result->setIndexedTagName( $debugInfo['log'], 'line' );
512 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
513 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
514 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
515 $result->setIndexedTagName( $debugInfo['profile'], 'function' );
516 $result->addValue( null, 'debuginfo', $debugInfo );
520 * Returns the HTML to add to the page for the toolbar
522 * @param IContextSource $context
525 public static function getDebugInfo( IContextSource
$context ) {
526 if ( !self
::$enabled ) {
530 global $wgVersion, $wgRequestTime;
531 $request = $context->getRequest();
533 // HHVM's reported memory usage from memory_get_peak_usage()
534 // is not useful when passing false, but we continue passing
535 // false for consistency of historical data in zend.
536 // see: https://github.com/facebook/hhvm/issues/2257#issuecomment-39362246
537 $realMemoryUsage = wfIsHHVM();
540 'mwVersion' => $wgVersion,
541 'phpEngine' => wfIsHHVM() ?
'HHVM' : 'PHP',
542 'phpVersion' => wfIsHHVM() ? HHVM_VERSION
: PHP_VERSION
,
543 'gitRevision' => GitInfo
::headSHA1(),
544 'gitBranch' => GitInfo
::currentBranch(),
545 'gitViewUrl' => GitInfo
::headViewUrl(),
546 'time' => microtime( true ) - $wgRequestTime,
548 'debugLog' => self
::$debug,
549 'queries' => self
::$query,
551 'method' => $request->getMethod(),
552 'url' => $request->getRequestURL(),
553 'headers' => $request->getAllHeaders(),
554 'params' => $request->getValues(),
556 'memory' => $context->getLanguage()->formatSize( memory_get_usage( $realMemoryUsage ) ),
557 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage( $realMemoryUsage ) ),
558 'includes' => self
::getFilesIncluded( $context ),
559 'profile' => Profiler
::instance()->getRawData(),