Merge "Combine JavaScript and JSON encoding logic"
[mediawiki.git] / includes / debug / Debug.php
blob8c39e1a1503b5fa71b40994a5d1389a482f38ed9
1 <?php
2 /**
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
20 * @file
23 /**
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
31 * @since 1.19
33 class MWDebug {
35 /**
36 * Log lines
38 * @var array
40 protected static $log = array();
42 /**
43 * Debug messages from wfDebug()
45 * @var array
47 protected static $debug = array();
49 /**
50 * Queries
52 * @var array
54 protected static $query = array();
56 /**
57 * Is the debugger enabled?
59 * @var bool
61 protected static $enabled = false;
63 /**
64 * Array of functions that have already been warned, formatted
65 * function-caller to prevent a buttload of warnings
67 * @var array
69 protected static $deprecationWarnings = array();
71 /**
72 * Enabled the debugger and load resource module.
73 * This is called by Setup.php when $wgDebugToolbar is true.
75 * @since 1.19
77 public static function init() {
78 self::$enabled = true;
81 /**
82 * Add ResourceLoader modules to the OutputPage object if debugging is
83 * enabled.
85 * @since 1.19
86 * @param $out OutputPage
88 public static function addModules( OutputPage $out ) {
89 if ( self::$enabled ) {
90 $out->addModules( 'mediawiki.debug.init' );
94 /**
95 * Adds a line to the log
97 * @todo Add support for passing objects
99 * @since 1.19
100 * @param $str string
102 public static function log( $str ) {
103 if ( !self::$enabled ) {
104 return;
107 self::$log[] = array(
108 'msg' => htmlspecialchars( $str ),
109 'type' => 'log',
110 'caller' => wfGetCaller(),
115 * Returns internal log array
116 * @since 1.19
117 * @return array
119 public static function getLog() {
120 return self::$log;
124 * Clears internal log array and deprecation tracking
125 * @since 1.19
127 public static function clearLog() {
128 self::$log = array();
129 self::$deprecationWarnings = array();
133 * Adds a warning entry to the log
135 * @since 1.19
136 * @param $msg string
137 * @param $callerOffset int
138 * @param int $level A PHP error level. See sendWarning()
139 * @return mixed
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 ),
149 'type' => 'warn',
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
159 * is set to true.
160 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
161 * is set to true.
162 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
164 * @since 1.19
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).
172 * @return mixed
174 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
175 $callerDescription = self::getCallerDescription( $callerOffset );
176 $callerFunc = $callerDescription['func'];
178 $sendToLog = true;
180 // Check to see if there already was a warning about this function
181 if ( isset( self::$deprecationWarnings[$function][$callerFunc] ) ) {
182 return;
183 } elseif ( isset( self::$deprecationWarnings[$function] ) ) {
184 if ( self::$enabled ) {
185 $sendToLog = false;
186 } else {
187 return;
191 self::$deprecationWarnings[$function][$callerFunc] = true;
193 if ( $version ) {
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, '<' ) ) {
204 $sendToLog = false;
208 $component = $component === false ? 'MediaWiki' : $component;
209 $msg = "Use of $function was deprecated in $component $version.";
210 } else {
211 $msg = "Use of $function is deprecated.";
214 if ( $sendToLog ) {
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(
225 'msg' => $logMsg,
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'];
246 } else {
247 $file = '(internal function)';
249 } else {
250 $file = '(unknown location)';
253 if ( isset( $callers[$callerOffset + 1] ) ) {
254 $callerfunc = $callers[$callerOffset + 1];
255 $func = '';
256 if ( isset( $callerfunc['class'] ) ) {
257 $func .= $callerfunc['class'] . '::';
259 if ( isset( $callerfunc['function'] ) ) {
260 $func .= $callerfunc['function'];
262 } else {
263 $func = 'unknown';
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 );
284 } else {
285 wfDebug( "$msg\n" );
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()
293 * @since 1.19
294 * @param $str string
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
307 * @since 1.19
308 * @param $sql string
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 ) {
316 return -1;
319 self::$query[] = array(
320 'sql' => $sql,
321 'function' => $function,
322 'master' => (bool) $isMaster,
323 'time' => 0.0,
324 '_start' => microtime( true ),
327 return count( self::$query ) - 1;
331 * Calculates how long a query took.
333 * @since 1.19
334 * @param $id int
336 public static function queryTime( $id ) {
337 if ( $id === -1 || !self::$enabled ) {
338 return;
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
349 * @return array
351 protected static function getFilesIncluded( IContextSource $context ) {
352 $files = get_included_files();
353 $fileList = array();
354 foreach ( $files as $file ) {
355 $size = filesize( $file );
356 $fileList[] = array(
357 'name' => $file,
358 'size' => $context->getLanguage()->formatSize( $size ),
362 return $fileList;
366 * Returns the HTML to add to the page for the toolbar
368 * @since 1.19
369 * @param $context IContextSource
370 * @return string
372 public static function getDebugHTML( IContextSource $context ) {
373 global $wgDebugComments;
375 $html = '';
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 ) ) .
393 "\n\n-->";
396 return $html;
400 * Generate debug log in HTML for displaying at the bottom of the main
401 * content area.
402 * If $wgShowDebug is false, an empty string is always returned.
404 * @since 1.20
405 * @return string HTML fragment
407 public static function getHTMLDebugLog() {
408 global $wgDebugTimestamps, $wgShowDebug;
410 if ( !$wgShowDebug ) {
411 return '';
414 $curIdent = 0;
415 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
417 foreach ( self::$debug as $line ) {
418 $pre = '';
419 if ( $wgDebugTimestamps ) {
420 $matches = array();
421 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
422 $pre = $matches[1];
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 ' ) {
436 $ident = $curIdent;
437 $diff = 0;
438 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
439 } else {
440 $display = nl2br( htmlspecialchars( $display ) );
443 if ( $diff < 0 ) {
444 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
445 } elseif ( $diff == 0 ) {
446 $ret .= "</li><li>\n";
447 } else {
448 $ret .= str_repeat( "<ul><li>\n", $diff );
450 $ret .= "<tt>$display</tt>\n";
452 $curIdent = $ident;
455 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
457 return $ret;
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 ) {
468 return;
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();
474 if( $obContents ) {
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 ) {
489 $vals = array();
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
503 * @return array
505 public static function getDebugInfo( IContextSource $context ) {
506 if ( !self::$enabled ) {
507 return array();
510 global $wgVersion, $wgRequestTime;
511 $request = $context->getRequest();
512 return array(
513 'mwVersion' => $wgVersion,
514 'phpVersion' => PHP_VERSION,
515 'gitRevision' => GitInfo::headSHA1(),
516 'gitBranch' => GitInfo::currentBranch(),
517 'gitViewUrl' => GitInfo::headViewUrl(),
518 'time' => microtime( true ) - $wgRequestTime,
519 'log' => self::$log,
520 'debugLog' => self::$debug,
521 'queries' => self::$query,
522 'request' => array(
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 ),