Merge "(bug 37755) Set robot meta tags for 'view source' pages"
[lhc/web/wiklou.git] / includes / debug / Debug.php
1 <?php
2 /**
3 * Debug toolbar related code
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * New debugger system that outputs a toolbar on page view
25 *
26 * By default, most methods do nothing ( self::$enabled = false ). You have
27 * to explicitly call MWDebug::init() to enabled them.
28 *
29 * @todo Profiler support
30 *
31 * @since 1.19
32 */
33 class MWDebug {
34
35 /**
36 * Log lines
37 *
38 * @var array
39 */
40 protected static $log = array();
41
42 /**
43 * Debug messages from wfDebug()
44 *
45 * @var array
46 */
47 protected static $debug = array();
48
49 /**
50 * Queries
51 *
52 * @var array
53 */
54 protected static $query = array();
55
56 /**
57 * Is the debugger enabled?
58 *
59 * @var bool
60 */
61 protected static $enabled = false;
62
63 /**
64 * Array of functions that have already been warned, formatted
65 * function-caller to prevent a buttload of warnings
66 *
67 * @var array
68 */
69 protected static $deprecationWarnings = array();
70
71 /**
72 * Enabled the debugger and load resource module.
73 * This is called by Setup.php when $wgDebugToolbar is true.
74 *
75 * @since 1.19
76 */
77 public static function init() {
78 self::$enabled = true;
79 }
80
81 /**
82 * Add ResourceLoader modules to the OutputPage object if debugging is
83 * enabled.
84 *
85 * @since 1.19
86 * @param $out OutputPage
87 */
88 public static function addModules( OutputPage $out ) {
89 if ( self::$enabled ) {
90 $out->addModules( 'mediawiki.debug.init' );
91 }
92 }
93
94 /**
95 * Adds a line to the log
96 *
97 * @todo Add support for passing objects
98 *
99 * @since 1.19
100 * @param $str string
101 */
102 public static function log( $str ) {
103 if ( !self::$enabled ) {
104 return;
105 }
106
107 self::$log[] = array(
108 'msg' => htmlspecialchars( $str ),
109 'type' => 'log',
110 'caller' => wfGetCaller(),
111 );
112 }
113
114 /**
115 * Returns internal log array
116 * @since 1.19
117 * @return array
118 */
119 public static function getLog() {
120 return self::$log;
121 }
122
123 /**
124 * Clears internal log array and deprecation tracking
125 * @since 1.19
126 */
127 public static function clearLog() {
128 self::$log = array();
129 self::$deprecationWarnings = array();
130 }
131
132 /**
133 * Adds a warning entry to the log
134 *
135 * @since 1.19
136 * @param $msg string
137 * @param $callerOffset int
138 * @param $level int A PHP error level. See sendWarning()
139 * @return mixed
140 */
141 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
142 $callerDescription = self::getCallerDescription( $callerOffset );
143
144 self::sendWarning( $msg, $callerDescription, $level );
145
146 if ( self::$enabled ) {
147 self::$log[] = array(
148 'msg' => htmlspecialchars( $msg ),
149 'type' => 'warn',
150 'caller' => $callerDescription['func'],
151 );
152 }
153 }
154
155 /**
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.
163 *
164 * @since 1.19
165 * @param $function string: Function that is deprecated.
166 * @param $version string|bool: Version in which the function was deprecated.
167 * @param $component string|bool: 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
173 */
174 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
175 $callerDescription = self::getCallerDescription( $callerOffset );
176 $callerFunc = $callerDescription['func'];
177
178 $sendToLog = true;
179
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;
188 }
189 }
190
191 self::$deprecationWarnings[$function][$callerFunc] = true;
192
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 );
200
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;
205 }
206 }
207
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.";
212 }
213
214 if ( $sendToLog ) {
215 self::sendWarning( $msg, $callerDescription, E_USER_DEPRECATED );
216 }
217
218 if ( self::$enabled ) {
219 $logMsg = htmlspecialchars( $msg ) .
220 Html::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
221 Html::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
222 );
223
224 self::$log[] = array(
225 'msg' => $logMsg,
226 'type' => 'deprecated',
227 'caller' => $callerFunc,
228 );
229 }
230 }
231
232 /**
233 * Get an array describing the calling function at a specified offset.
234 *
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'
238 */
239 private static function getCallerDescription( $callerOffset ) {
240 $callers = wfDebugBacktrace();
241
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)';
248 }
249 } else {
250 $file = '(unknown location)';
251 }
252
253 if ( isset( $callers[$callerOffset + 1] ) ) {
254 $callerfunc = $callers[$callerOffset + 1];
255 $func = '';
256 if ( isset( $callerfunc['class'] ) ) {
257 $func .= $callerfunc['class'] . '::';
258 }
259 if ( isset( $callerfunc['function'] ) ) {
260 $func .= $callerfunc['function'];
261 }
262 } else {
263 $func = 'unknown';
264 }
265
266 return array( 'file' => $file, 'func' => $func );
267 }
268
269 /**
270 * Send a warning either to the debug log or by triggering an user PHP
271 * error depending on $wgDevelopmentWarnings.
272 *
273 * @param $msg string Message to send
274 * @param $caller array caller description get from getCallerDescription()
275 * @param $level error level to use if $wgDevelopmentWarnings is true
276 */
277 private static function sendWarning( $msg, $caller, $level ) {
278 global $wgDevelopmentWarnings;
279
280 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
281
282 if ( $wgDevelopmentWarnings ) {
283 trigger_error( $msg, $level );
284 } else {
285 wfDebug( "$msg\n" );
286 }
287 }
288
289 /**
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()
292 *
293 * @since 1.19
294 * @param $str string
295 */
296 public static function debugMsg( $str ) {
297 global $wgDebugComments, $wgShowDebug;
298
299 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
300 self::$debug[] = rtrim( $str );
301 }
302 }
303
304 /**
305 * Begins profiling on a database query
306 *
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
313 */
314 public static function query( $sql, $function, $isMaster ) {
315 if ( !self::$enabled ) {
316 return -1;
317 }
318
319 self::$query[] = array(
320 'sql' => $sql,
321 'function' => $function,
322 'master' => (bool) $isMaster,
323 'time' => 0.0,
324 '_start' => microtime( true ),
325 );
326
327 return count( self::$query ) - 1;
328 }
329
330 /**
331 * Calculates how long a query took.
332 *
333 * @since 1.19
334 * @param $id int
335 */
336 public static function queryTime( $id ) {
337 if ( $id === -1 || !self::$enabled ) {
338 return;
339 }
340
341 self::$query[$id]['time'] = microtime( true ) - self::$query[$id]['_start'];
342 unset( self::$query[$id]['_start'] );
343 }
344
345 /**
346 * Returns a list of files included, along with their size
347 *
348 * @param $context IContextSource
349 * @return array
350 */
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 ),
359 );
360 }
361
362 return $fileList;
363 }
364
365 /**
366 * Returns the HTML to add to the page for the toolbar
367 *
368 * @since 1.19
369 * @param $context IContextSource
370 * @return string
371 */
372 public static function getDebugHTML( IContextSource $context ) {
373 global $wgDebugComments;
374
375 $html = '';
376
377 if ( self::$enabled ) {
378 MWDebug::log( 'MWDebug output complete' );
379 $debugInfo = self::getDebugInfo( $context );
380
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 ) )
386 )
387 );
388 }
389
390 if ( $wgDebugComments ) {
391 $html .= "<!-- Debug output:\n" .
392 htmlspecialchars( implode( "\n", self::$debug ) ) .
393 "\n\n-->";
394 }
395
396 return $html;
397 }
398
399 /**
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.
403 *
404 * @since 1.20
405 * @return string HTML fragment
406 */
407 public static function getHTMLDebugLog() {
408 global $wgDebugTimestamps, $wgShowDebug;
409
410 if ( !$wgShowDebug ) {
411 return '';
412 }
413
414 $curIdent = 0;
415 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
416
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 ) );
424 }
425 }
426 $display = ltrim( $line );
427 $ident = strlen( $line ) - strlen( $display );
428 $diff = $ident - $curIdent;
429
430 $display = $pre . $display;
431 if ( $display == '' ) {
432 $display = "\xc2\xa0";
433 }
434
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 ) );
441 }
442
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 );
449 }
450 $ret .= "<tt>$display</tt>\n";
451
452 $curIdent = $ident;
453 }
454
455 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
456
457 return $ret;
458 }
459
460 /**
461 * Append the debug info to given ApiResult
462 *
463 * @param $context IContextSource
464 * @param $result ApiResult
465 */
466 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
467 if ( !self::$enabled ) {
468 return;
469 }
470
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 ) );
479 }
480 }
481 }
482
483 MWDebug::log( 'MWDebug output complete' );
484 $debugInfo = self::getDebugInfo( $context );
485
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
492 }
493 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
494 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
495 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
496 $result->addValue( array(), 'debuginfo', $debugInfo );
497 }
498
499 /**
500 * Returns the HTML to add to the page for the toolbar
501 *
502 * @param $context IContextSource
503 * @return array
504 */
505 public static function getDebugInfo( IContextSource $context ) {
506 if ( !self::$enabled ) {
507 return array();
508 }
509
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(),
527 ),
528 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
529 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
530 'includes' => self::getFilesIncluded( $context ),
531 );
532 }
533 }