Merge "Typo fix"
[mediawiki.git] / includes / debug / Debug.php
blob9f692c8d0b595bfd97190a147bde5bc3b26c1d45
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 $log
40 protected static $log = array();
42 /**
43 * Debug messages from wfDebug().
45 * @var array $debug
47 protected static $debug = array();
49 /**
50 * SQL statements of the databses queries.
52 * @var array $query
54 protected static $query = array();
56 /**
57 * Is the debugger enabled?
59 * @var bool $enabled
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 $deprecationWarnings
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 $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).
143 * @return mixed
145 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
146 global $wgDevelopmentWarnings;
148 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
149 $log = 'debug';
152 if ( $log === 'debug' ) {
153 $level = false;
156 $callerDescription = self::getCallerDescription( $callerOffset );
158 self::sendWarning( $msg, $callerDescription, $level );
160 if ( self::$enabled ) {
161 self::$log[] = array(
162 'msg' => htmlspecialchars( $msg ),
163 'type' => 'warn',
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
173 * is set to true.
174 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
175 * is set to true.
176 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
178 * @since 1.19
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).
186 * @return mixed
188 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
189 $callerDescription = self::getCallerDescription( $callerOffset );
190 $callerFunc = $callerDescription['func'];
192 $sendToLog = true;
194 // Check to see if there already was a warning about this function
195 if ( isset( self::$deprecationWarnings[$function][$callerFunc] ) ) {
196 return;
197 } elseif ( isset( self::$deprecationWarnings[$function] ) ) {
198 if ( self::$enabled ) {
199 $sendToLog = false;
200 } else {
201 return;
205 self::$deprecationWarnings[$function][$callerFunc] = true;
207 if ( $version ) {
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, '<' ) ) {
218 $sendToLog = false;
222 $component = $component === false ? 'MediaWiki' : $component;
223 $msg = "Use of $function was deprecated in $component $version.";
224 } else {
225 $msg = "Use of $function is deprecated.";
228 if ( $sendToLog ) {
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(
240 'msg' => $logMsg,
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'];
261 } else {
262 $file = '(internal function)';
264 } else {
265 $file = '(unknown location)';
268 if ( isset( $callers[$callerOffset + 1] ) ) {
269 $callerfunc = $callers[$callerOffset + 1];
270 $func = '';
271 if ( isset( $callerfunc['class'] ) ) {
272 $func .= $callerfunc['class'] . '::';
274 if ( isset( $callerfunc['function'] ) ) {
275 $func .= $callerfunc['function'];
277 } else {
278 $func = 'unknown';
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 );
299 wfDebug( "$msg\n" );
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()
306 * @since 1.19
307 * @param $str string
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
320 * @since 1.19
321 * @param $sql string
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 ) {
329 return -1;
332 self::$query[] = array(
333 'sql' => $sql,
334 'function' => $function,
335 'master' => (bool) $isMaster,
336 'time' => 0.0,
337 '_start' => microtime( true ),
340 return count( self::$query ) - 1;
344 * Calculates how long a query took.
346 * @since 1.19
347 * @param $id int
349 public static function queryTime( $id ) {
350 if ( $id === -1 || !self::$enabled ) {
351 return;
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
362 * @return array
364 protected static function getFilesIncluded( IContextSource $context ) {
365 $files = get_included_files();
366 $fileList = array();
367 foreach ( $files as $file ) {
368 $size = filesize( $file );
369 $fileList[] = array(
370 'name' => $file,
371 'size' => $context->getLanguage()->formatSize( $size ),
375 return $fileList;
379 * Returns the HTML to add to the page for the toolbar
381 * @since 1.19
382 * @param $context IContextSource
383 * @return string
385 public static function getDebugHTML( IContextSource $context ) {
386 global $wgDebugComments;
388 $html = '';
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 ) ) .
406 "\n\n-->";
409 return $html;
413 * Generate debug log in HTML for displaying at the bottom of the main
414 * content area.
415 * If $wgShowDebug is false, an empty string is always returned.
417 * @since 1.20
418 * @return string HTML fragment
420 public static function getHTMLDebugLog() {
421 global $wgDebugTimestamps, $wgShowDebug;
423 if ( !$wgShowDebug ) {
424 return '';
427 $curIdent = 0;
428 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
430 foreach ( self::$debug as $line ) {
431 $pre = '';
432 if ( $wgDebugTimestamps ) {
433 $matches = array();
434 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
435 $pre = $matches[1];
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 ' ) {
449 $ident = $curIdent;
450 $diff = 0;
451 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
452 } else {
453 $display = nl2br( htmlspecialchars( $display ) );
456 if ( $diff < 0 ) {
457 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
458 } elseif ( $diff == 0 ) {
459 $ret .= "</li><li>\n";
460 } else {
461 $ret .= str_repeat( "<ul><li>\n", $diff );
463 $ret .= "<tt>$display</tt>\n";
465 $curIdent = $ident;
468 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
470 return $ret;
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 ) {
481 return;
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();
487 if ( $obContents ) {
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 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
502 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
503 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
504 $result->addValue( null, 'debuginfo', $debugInfo );
508 * Returns the HTML to add to the page for the toolbar
510 * @param $context IContextSource
511 * @return array
513 public static function getDebugInfo( IContextSource $context ) {
514 if ( !self::$enabled ) {
515 return array();
518 global $wgVersion, $wgRequestTime;
519 $request = $context->getRequest();
520 return array(
521 'mwVersion' => $wgVersion,
522 'phpVersion' => PHP_VERSION,
523 'gitRevision' => GitInfo::headSHA1(),
524 'gitBranch' => GitInfo::currentBranch(),
525 'gitViewUrl' => GitInfo::headViewUrl(),
526 'time' => microtime( true ) - $wgRequestTime,
527 'log' => self::$log,
528 'debugLog' => self::$debug,
529 'queries' => self::$query,
530 'request' => array(
531 'method' => $request->getMethod(),
532 'url' => $request->getRequestURL(),
533 'headers' => $request->getAllHeaders(),
534 'params' => $request->getValues(),
536 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
537 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
538 'includes' => self::getFilesIncluded( $context ),