Merge "[FileBackend] Made Swift clear the auth cache on certain HTTP errors."
[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 * @return mixed
139 */
140 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
141 $callerDescription = self::getCallerDescription( $callerOffset );
142
143 self::sendWarning( $msg, $callerDescription, $level );
144
145 if ( self::$enabled ) {
146 self::$log[] = array(
147 'msg' => htmlspecialchars( $msg ),
148 'type' => 'warn',
149 'caller' => $callerDescription['func'],
150 );
151 }
152 }
153
154 /**
155 * Show a warning that $function is deprecated.
156 * This will send it to the following locations:
157 * - Debug toolbar, with one item per function and caller, if $wgDebugToolbar
158 * is set to true.
159 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
160 * is set to true.
161 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
162 *
163 * @since 1.19
164 * @param $function string: Function that is deprecated.
165 * @param $version string|bool: Version in which the function was deprecated.
166 * @param $component string|bool: Component to which the function belongs.
167 * If false, it is assumbed the function is in MediaWiki core.
168 * @param $callerOffset integer: How far up the callstack is the original
169 * caller. 2 = function that called the function that called
170 * MWDebug::deprecated() (Added in 1.20).
171 * @return mixed
172 */
173 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
174 $callerDescription = self::getCallerDescription( $callerOffset );
175 $callerFunc = $callerDescription['func'];
176
177 $sendToLog = true;
178
179 // Check to see if there already was a warning about this function
180 if ( isset( self::$deprecationWarnings[$function][$callerFunc] ) ) {
181 return;
182 } elseif ( isset( self::$deprecationWarnings[$function] ) ) {
183 if ( self::$enabled ) {
184 $sendToLog = false;
185 } else {
186 return;
187 }
188 }
189
190 self::$deprecationWarnings[$function][$callerFunc] = true;
191
192 if ( $version ) {
193 global $wgDeprecationReleaseLimit;
194 if ( $wgDeprecationReleaseLimit && $component === false ) {
195 # Strip -* off the end of $version so that branches can use the
196 # format #.##-branchname to avoid issues if the branch is merged into
197 # a version of MediaWiki later than what it was branched from
198 $comparableVersion = preg_replace( '/-.*$/', '', $version );
199
200 # If the comparableVersion is larger than our release limit then
201 # skip the warning message for the deprecation
202 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
203 $sendToLog = false;
204 }
205 }
206
207 $component = $component === false ? 'MediaWiki' : $component;
208 $msg = "Use of $function was deprecated in $component $version.";
209 } else {
210 $msg = "Use of $function is deprecated.";
211 }
212
213 if ( $sendToLog ) {
214 self::sendWarning( $msg, $callerDescription, E_USER_DEPRECATED );
215 }
216
217 if ( self::$enabled ) {
218 $logMsg = htmlspecialchars( $msg ) .
219 Html::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
220 Html::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
221 );
222
223 self::$log[] = array(
224 'msg' => $logMsg,
225 'type' => 'deprecated',
226 'caller' => $callerFunc,
227 );
228 }
229 }
230
231 /**
232 * Get an array describing the calling function at a specified offset.
233 *
234 * @param $callerOffset integer: How far up the callstack is the original
235 * caller. 0 = function that called getCallerDescription()
236 * @return array with two keys: 'file' and 'func'
237 */
238 private static function getCallerDescription( $callerOffset ) {
239 $callers = wfDebugBacktrace();
240
241 if ( isset( $callers[$callerOffset] ) ) {
242 $callerfile = $callers[$callerOffset];
243 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
244 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
245 } else {
246 $file = '(internal function)';
247 }
248 } else {
249 $file = '(unknown location)';
250 }
251
252 if ( isset( $callers[$callerOffset + 1] ) ) {
253 $callerfunc = $callers[$callerOffset + 1];
254 $func = '';
255 if ( isset( $callerfunc['class'] ) ) {
256 $func .= $callerfunc['class'] . '::';
257 }
258 if ( isset( $callerfunc['function'] ) ) {
259 $func .= $callerfunc['function'];
260 }
261 } else {
262 $func = 'unknown';
263 }
264
265 return array( 'file' => $file, 'func' => $func );
266 }
267
268 /**
269 * Send a warning either to the debug log or by triggering an user PHP
270 * error depending on $wgDevelopmentWarnings.
271 *
272 * @param $msg string Message to send
273 * @param $caller array caller description get from getCallerDescription()
274 * @param $level error level to use if $wgDevelopmentWarnings is true
275 */
276 private static function sendWarning( $msg, $caller, $level ) {
277 global $wgDevelopmentWarnings;
278
279 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
280
281 if ( $wgDevelopmentWarnings ) {
282 trigger_error( $msg, $level );
283 } else {
284 wfDebug( "$msg\n" );
285 }
286 }
287
288 /**
289 * This is a method to pass messages from wfDebug to the pretty debugger.
290 * Do NOT use this method, use MWDebug::log or wfDebug()
291 *
292 * @since 1.19
293 * @param $str string
294 */
295 public static function debugMsg( $str ) {
296 global $wgDebugComments, $wgShowDebug;
297
298 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
299 self::$debug[] = rtrim( $str );
300 }
301 }
302
303 /**
304 * Begins profiling on a database query
305 *
306 * @since 1.19
307 * @param $sql string
308 * @param $function string
309 * @param $isMaster bool
310 * @return int ID number of the query to pass to queryTime or -1 if the
311 * debugger is disabled
312 */
313 public static function query( $sql, $function, $isMaster ) {
314 if ( !self::$enabled ) {
315 return -1;
316 }
317
318 self::$query[] = array(
319 'sql' => $sql,
320 'function' => $function,
321 'master' => (bool) $isMaster,
322 'time' => 0.0,
323 '_start' => microtime( true ),
324 );
325
326 return count( self::$query ) - 1;
327 }
328
329 /**
330 * Calculates how long a query took.
331 *
332 * @since 1.19
333 * @param $id int
334 */
335 public static function queryTime( $id ) {
336 if ( $id === -1 || !self::$enabled ) {
337 return;
338 }
339
340 self::$query[$id]['time'] = microtime( true ) - self::$query[$id]['_start'];
341 unset( self::$query[$id]['_start'] );
342 }
343
344 /**
345 * Returns a list of files included, along with their size
346 *
347 * @param $context IContextSource
348 * @return array
349 */
350 protected static function getFilesIncluded( IContextSource $context ) {
351 $files = get_included_files();
352 $fileList = array();
353 foreach ( $files as $file ) {
354 $size = filesize( $file );
355 $fileList[] = array(
356 'name' => $file,
357 'size' => $context->getLanguage()->formatSize( $size ),
358 );
359 }
360
361 return $fileList;
362 }
363
364 /**
365 * Returns the HTML to add to the page for the toolbar
366 *
367 * @since 1.19
368 * @param $context IContextSource
369 * @return string
370 */
371 public static function getDebugHTML( IContextSource $context ) {
372 global $wgDebugComments;
373
374 $html = '';
375
376 if ( self::$enabled ) {
377 MWDebug::log( 'MWDebug output complete' );
378 $debugInfo = self::getDebugInfo( $context );
379
380 // Cannot use OutputPage::addJsConfigVars because those are already outputted
381 // by the time this method is called.
382 $html = Html::inlineScript(
383 ResourceLoader::makeLoaderConditionalScript(
384 ResourceLoader::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
385 )
386 );
387 }
388
389 if ( $wgDebugComments ) {
390 $html .= "<!-- Debug output:\n" .
391 htmlspecialchars( implode( "\n", self::$debug ) ) .
392 "\n\n-->";
393 }
394
395 return $html;
396 }
397
398 /**
399 * Generate debug log in HTML for displaying at the bottom of the main
400 * content area.
401 * If $wgShowDebug is false, an empty string is always returned.
402 *
403 * @since 1.20
404 * @return string HTML fragment
405 */
406 public static function getHTMLDebugLog() {
407 global $wgDebugTimestamps, $wgShowDebug;
408
409 if ( !$wgShowDebug ) {
410 return '';
411 }
412
413 $curIdent = 0;
414 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
415
416 foreach ( self::$debug as $line ) {
417 $pre = '';
418 if ( $wgDebugTimestamps ) {
419 $matches = array();
420 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
421 $pre = $matches[1];
422 $line = substr( $line, strlen( $pre ) );
423 }
424 }
425 $display = ltrim( $line );
426 $ident = strlen( $line ) - strlen( $display );
427 $diff = $ident - $curIdent;
428
429 $display = $pre . $display;
430 if ( $display == '' ) {
431 $display = "\xc2\xa0";
432 }
433
434 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
435 $ident = $curIdent;
436 $diff = 0;
437 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
438 } else {
439 $display = nl2br( htmlspecialchars( $display ) );
440 }
441
442 if ( $diff < 0 ) {
443 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
444 } elseif ( $diff == 0 ) {
445 $ret .= "</li><li>\n";
446 } else {
447 $ret .= str_repeat( "<ul><li>\n", $diff );
448 }
449 $ret .= "<tt>$display</tt>\n";
450
451 $curIdent = $ident;
452 }
453
454 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
455
456 return $ret;
457 }
458
459 /**
460 * Append the debug info to given ApiResult
461 *
462 * @param $context IContextSource
463 * @param $result ApiResult
464 */
465 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
466 if ( !self::$enabled ) {
467 return;
468 }
469
470 // output errors as debug info, when display_errors is on
471 // this is necessary for all non html output of the api, because that clears all errors first
472 $obContents = ob_get_contents();
473 if( $obContents ) {
474 $obContentArray = explode( '<br />', $obContents );
475 foreach( $obContentArray as $obContent ) {
476 if( trim( $obContent ) ) {
477 self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
478 }
479 }
480 }
481
482 MWDebug::log( 'MWDebug output complete' );
483 $debugInfo = self::getDebugInfo( $context );
484
485 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
486 $result->setIndexedTagName( $debugInfo['log'], 'line' );
487 foreach( $debugInfo['debugLog'] as $index => $debugLogText ) {
488 $vals = array();
489 ApiResult::setContent( $vals, $debugLogText );
490 $debugInfo['debugLog'][$index] = $vals; //replace
491 }
492 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
493 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
494 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
495 $result->addValue( array(), 'debuginfo', $debugInfo );
496 }
497
498 /**
499 * Returns the HTML to add to the page for the toolbar
500 *
501 * @param $context IContextSource
502 * @return array
503 */
504 public static function getDebugInfo( IContextSource $context ) {
505 if ( !self::$enabled ) {
506 return array();
507 }
508
509 global $wgVersion, $wgRequestTime;
510 $request = $context->getRequest();
511 return array(
512 'mwVersion' => $wgVersion,
513 'phpVersion' => PHP_VERSION,
514 'gitRevision' => GitInfo::headSHA1(),
515 'gitBranch' => GitInfo::currentBranch(),
516 'gitViewUrl' => GitInfo::headViewUrl(),
517 'time' => microtime( true ) - $wgRequestTime,
518 'log' => self::$log,
519 'debugLog' => self::$debug,
520 'queries' => self::$query,
521 'request' => array(
522 'method' => $request->getMethod(),
523 'url' => $request->getRequestURL(),
524 'headers' => $request->getAllHeaders(),
525 'params' => $request->getValues(),
526 ),
527 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
528 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
529 'includes' => self::getFilesIncluded( $context ),
530 );
531 }
532 }