15ed3cbecdfed1ba05ceeb6d767d319c7ef6a9da
[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 * Log lines
36 *
37 * @var array $log
38 */
39 protected static $log = array();
40
41 /**
42 * Debug messages from wfDebug().
43 *
44 * @var array $debug
45 */
46 protected static $debug = array();
47
48 /**
49 * SQL statements of the databses queries.
50 *
51 * @var array $query
52 */
53 protected static $query = array();
54
55 /**
56 * Is the debugger enabled?
57 *
58 * @var bool $enabled
59 */
60 protected static $enabled = false;
61
62 /**
63 * Array of functions that have already been warned, formatted
64 * function-caller to prevent a buttload of warnings
65 *
66 * @var array $deprecationWarnings
67 */
68 protected static $deprecationWarnings = array();
69
70 /**
71 * Enabled the debugger and load resource module.
72 * This is called by Setup.php when $wgDebugToolbar is true.
73 *
74 * @since 1.19
75 */
76 public static function init() {
77 self::$enabled = true;
78 }
79
80 /**
81 * Add ResourceLoader modules to the OutputPage object if debugging is
82 * enabled.
83 *
84 * @since 1.19
85 * @param $out OutputPage
86 */
87 public static function addModules( OutputPage $out ) {
88 if ( self::$enabled ) {
89 $out->addModules( 'mediawiki.debug.init' );
90 }
91 }
92
93 /**
94 * Adds a line to the log
95 *
96 * @todo Add support for passing objects
97 *
98 * @since 1.19
99 * @param $str string
100 */
101 public static function log( $str ) {
102 if ( !self::$enabled ) {
103 return;
104 }
105
106 self::$log[] = array(
107 'msg' => htmlspecialchars( $str ),
108 'type' => 'log',
109 'caller' => wfGetCaller(),
110 );
111 }
112
113 /**
114 * Returns internal log array
115 * @since 1.19
116 * @return array
117 */
118 public static function getLog() {
119 return self::$log;
120 }
121
122 /**
123 * Clears internal log array and deprecation tracking
124 * @since 1.19
125 */
126 public static function clearLog() {
127 self::$log = array();
128 self::$deprecationWarnings = array();
129 }
130
131 /**
132 * Adds a warning entry to the log
133 *
134 * @since 1.19
135 * @param $msg string
136 * @param $callerOffset int
137 * @param $level int A PHP error level. See sendMessage()
138 * @param $log string: '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).
141 *
142 * @return mixed
143 */
144 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
145 global $wgDevelopmentWarnings;
146
147 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
148 $log = 'debug';
149 }
150
151 if ( $log === 'debug' ) {
152 $level = false;
153 }
154
155 $callerDescription = self::getCallerDescription( $callerOffset );
156
157 self::sendMessage( $msg, $callerDescription, 'warning', $level );
158
159 if ( self::$enabled ) {
160 self::$log[] = array(
161 'msg' => htmlspecialchars( $msg ),
162 'type' => 'warn',
163 'caller' => $callerDescription['func'],
164 );
165 }
166 }
167
168 /**
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
172 * is set to true.
173 * - PHP's error log, with level E_USER_DEPRECATED, if $wgDevelopmentWarnings
174 * is set to true.
175 * - MediaWiki's debug log, if $wgDevelopmentWarnings is set to false.
176 *
177 * @since 1.19
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 $callerOffset integer: 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).
185 * @return mixed
186 */
187 public static function deprecated( $function, $version = false,
188 $component = false, $callerOffset = 2
189 ) {
190 $callerDescription = self::getCallerDescription( $callerOffset );
191 $callerFunc = $callerDescription['func'];
192
193 $sendToLog = true;
194
195 // Check to see if there already was a warning about this function
196 if ( isset( self::$deprecationWarnings[$function][$callerFunc] ) ) {
197 return;
198 } elseif ( isset( self::$deprecationWarnings[$function] ) ) {
199 if ( self::$enabled ) {
200 $sendToLog = false;
201 } else {
202 return;
203 }
204 }
205
206 self::$deprecationWarnings[$function][$callerFunc] = true;
207
208 if ( $version ) {
209 global $wgDeprecationReleaseLimit;
210 if ( $wgDeprecationReleaseLimit && $component === false ) {
211 # Strip -* off the end of $version so that branches can use the
212 # format #.##-branchname to avoid issues if the branch is merged into
213 # a version of MediaWiki later than what it was branched from
214 $comparableVersion = preg_replace( '/-.*$/', '', $version );
215
216 # If the comparableVersion is larger than our release limit then
217 # skip the warning message for the deprecation
218 if ( version_compare( $wgDeprecationReleaseLimit, $comparableVersion, '<' ) ) {
219 $sendToLog = false;
220 }
221 }
222
223 $component = $component === false ? 'MediaWiki' : $component;
224 $msg = "Use of $function was deprecated in $component $version.";
225 } else {
226 $msg = "Use of $function is deprecated.";
227 }
228
229 if ( $sendToLog ) {
230 global $wgDevelopmentWarnings; // we could have a more specific $wgDeprecationWarnings setting.
231 self::sendMessage(
232 $msg,
233 $callerDescription,
234 'deprecated',
235 $wgDevelopmentWarnings ? E_USER_DEPRECATED : false
236 );
237 }
238
239 if ( self::$enabled ) {
240 $logMsg = htmlspecialchars( $msg ) .
241 Html::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
242 Html::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
243 );
244
245 self::$log[] = array(
246 'msg' => $logMsg,
247 'type' => 'deprecated',
248 'caller' => $callerFunc,
249 );
250 }
251 }
252
253 /**
254 * Get an array describing the calling function at a specified offset.
255 *
256 * @param $callerOffset integer: How far up the callstack is the original
257 * caller. 0 = function that called getCallerDescription()
258 * @return array with two keys: 'file' and 'func'
259 */
260 private static function getCallerDescription( $callerOffset ) {
261 $callers = wfDebugBacktrace();
262
263 if ( isset( $callers[$callerOffset] ) ) {
264 $callerfile = $callers[$callerOffset];
265 if ( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
266 $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
267 } else {
268 $file = '(internal function)';
269 }
270 } else {
271 $file = '(unknown location)';
272 }
273
274 if ( isset( $callers[$callerOffset + 1] ) ) {
275 $callerfunc = $callers[$callerOffset + 1];
276 $func = '';
277 if ( isset( $callerfunc['class'] ) ) {
278 $func .= $callerfunc['class'] . '::';
279 }
280 if ( isset( $callerfunc['function'] ) ) {
281 $func .= $callerfunc['function'];
282 }
283 } else {
284 $func = 'unknown';
285 }
286
287 return array( 'file' => $file, 'func' => $func );
288 }
289
290 /**
291 * Send a message to the debug log and optionally also trigger a PHP
292 * error, depending on the $level argument.
293 *
294 * @param $msg string Message to send
295 * @param $caller array caller description get from getCallerDescription()
296 * @param $group string log group on which to send the message
297 * @param $level int|bool error level to use; set to false to not trigger an error
298 */
299 private static function sendMessage( $msg, $caller, $group, $level ) {
300 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
301
302 if ( $level !== false ) {
303 trigger_error( $msg, $level );
304 }
305
306 wfDebugLog( $group, $msg, 'log' );
307 }
308
309 /**
310 * This is a method to pass messages from wfDebug to the pretty debugger.
311 * Do NOT use this method, use MWDebug::log or wfDebug()
312 *
313 * @since 1.19
314 * @param $str string
315 */
316 public static function debugMsg( $str ) {
317 global $wgDebugComments, $wgShowDebug;
318
319 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
320 self::$debug[] = rtrim( UtfNormal::cleanUp( $str ) );
321 }
322 }
323
324 /**
325 * Begins profiling on a database query
326 *
327 * @since 1.19
328 * @param $sql string
329 * @param $function string
330 * @param $isMaster bool
331 * @return int ID number of the query to pass to queryTime or -1 if the
332 * debugger is disabled
333 */
334 public static function query( $sql, $function, $isMaster ) {
335 if ( !self::$enabled ) {
336 return -1;
337 }
338
339 self::$query[] = array(
340 'sql' => $sql,
341 'function' => $function,
342 'master' => (bool)$isMaster,
343 'time' => 0.0,
344 '_start' => microtime( true ),
345 );
346
347 return count( self::$query ) - 1;
348 }
349
350 /**
351 * Calculates how long a query took.
352 *
353 * @since 1.19
354 * @param $id int
355 */
356 public static function queryTime( $id ) {
357 if ( $id === -1 || !self::$enabled ) {
358 return;
359 }
360
361 self::$query[$id]['time'] = microtime( true ) - self::$query[$id]['_start'];
362 unset( self::$query[$id]['_start'] );
363 }
364
365 /**
366 * Returns a list of files included, along with their size
367 *
368 * @param $context IContextSource
369 * @return array
370 */
371 protected static function getFilesIncluded( IContextSource $context ) {
372 $files = get_included_files();
373 $fileList = array();
374 foreach ( $files as $file ) {
375 $size = filesize( $file );
376 $fileList[] = array(
377 'name' => $file,
378 'size' => $context->getLanguage()->formatSize( $size ),
379 );
380 }
381
382 return $fileList;
383 }
384
385 /**
386 * Returns the HTML to add to the page for the toolbar
387 *
388 * @since 1.19
389 * @param $context IContextSource
390 * @return string
391 */
392 public static function getDebugHTML( IContextSource $context ) {
393 global $wgDebugComments;
394
395 $html = '';
396
397 if ( self::$enabled ) {
398 MWDebug::log( 'MWDebug output complete' );
399 $debugInfo = self::getDebugInfo( $context );
400
401 // Cannot use OutputPage::addJsConfigVars because those are already outputted
402 // by the time this method is called.
403 $html = Html::inlineScript(
404 ResourceLoader::makeLoaderConditionalScript(
405 ResourceLoader::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
406 )
407 );
408 }
409
410 if ( $wgDebugComments ) {
411 $html .= "<!-- Debug output:\n" .
412 htmlspecialchars( implode( "\n", self::$debug ) ) .
413 "\n\n-->";
414 }
415
416 return $html;
417 }
418
419 /**
420 * Generate debug log in HTML for displaying at the bottom of the main
421 * content area.
422 * If $wgShowDebug is false, an empty string is always returned.
423 *
424 * @since 1.20
425 * @return string HTML fragment
426 */
427 public static function getHTMLDebugLog() {
428 global $wgDebugTimestamps, $wgShowDebug;
429
430 if ( !$wgShowDebug ) {
431 return '';
432 }
433
434 $curIdent = 0;
435 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
436
437 foreach ( self::$debug as $line ) {
438 $pre = '';
439 if ( $wgDebugTimestamps ) {
440 $matches = array();
441 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
442 $pre = $matches[1];
443 $line = substr( $line, strlen( $pre ) );
444 }
445 }
446 $display = ltrim( $line );
447 $ident = strlen( $line ) - strlen( $display );
448 $diff = $ident - $curIdent;
449
450 $display = $pre . $display;
451 if ( $display == '' ) {
452 $display = "\xc2\xa0";
453 }
454
455 if ( !$ident
456 && $diff < 0
457 && substr( $display, 0, 9 ) != 'Entering '
458 && substr( $display, 0, 8 ) != 'Exiting '
459 ) {
460 $ident = $curIdent;
461 $diff = 0;
462 $display = '<span style="background:yellow;">' .
463 nl2br( htmlspecialchars( $display ) ) . '</span>';
464 } else {
465 $display = nl2br( htmlspecialchars( $display ) );
466 }
467
468 if ( $diff < 0 ) {
469 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
470 } elseif ( $diff == 0 ) {
471 $ret .= "</li><li>\n";
472 } else {
473 $ret .= str_repeat( "<ul><li>\n", $diff );
474 }
475 $ret .= "<code>$display</code>\n";
476
477 $curIdent = $ident;
478 }
479
480 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
481
482 return $ret;
483 }
484
485 /**
486 * Append the debug info to given ApiResult
487 *
488 * @param $context IContextSource
489 * @param $result ApiResult
490 */
491 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
492 if ( !self::$enabled ) {
493 return;
494 }
495
496 // output errors as debug info, when display_errors is on
497 // this is necessary for all non html output of the api, because that clears all errors first
498 $obContents = ob_get_contents();
499 if ( $obContents ) {
500 $obContentArray = explode( '<br />', $obContents );
501 foreach ( $obContentArray as $obContent ) {
502 if ( trim( $obContent ) ) {
503 self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
504 }
505 }
506 }
507
508 MWDebug::log( 'MWDebug output complete' );
509 $debugInfo = self::getDebugInfo( $context );
510
511 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
512 $result->setIndexedTagName( $debugInfo['log'], 'line' );
513 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
514 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
515 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
516 $result->addValue( null, 'debuginfo', $debugInfo );
517 }
518
519 /**
520 * Returns the HTML to add to the page for the toolbar
521 *
522 * @param $context IContextSource
523 * @return array
524 */
525 public static function getDebugInfo( IContextSource $context ) {
526 if ( !self::$enabled ) {
527 return array();
528 }
529
530 global $wgVersion, $wgRequestTime;
531 $request = $context->getRequest();
532
533 return array(
534 'mwVersion' => $wgVersion,
535 'phpVersion' => PHP_VERSION,
536 'gitRevision' => GitInfo::headSHA1(),
537 'gitBranch' => GitInfo::currentBranch(),
538 'gitViewUrl' => GitInfo::headViewUrl(),
539 'time' => microtime( true ) - $wgRequestTime,
540 'log' => self::$log,
541 'debugLog' => self::$debug,
542 'queries' => self::$query,
543 'request' => array(
544 'method' => $request->getMethod(),
545 'url' => $request->getRequestURL(),
546 'headers' => $request->getAllHeaders(),
547 'params' => $request->getValues(),
548 ),
549 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
550 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
551 'includes' => self::getFilesIncluded( $context ),
552 'profile' => Profiler::instance()->getRawData(),
553 );
554 }
555 }