Merge "Customise linktrail for Gujarati (gu)"
[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 * @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).
142 *
143 * @return mixed
144 */
145 public static function warning( $msg, $callerOffset = 1, $level = E_USER_NOTICE, $log = 'auto' ) {
146 global $wgDevelopmentWarnings;
147
148 if ( $log === 'auto' && !$wgDevelopmentWarnings ) {
149 $log = 'debug';
150 }
151
152 if ( $log === 'debug' ) {
153 $level = false;
154 }
155
156 $callerDescription = self::getCallerDescription( $callerOffset );
157
158 self::sendWarning( $msg, $callerDescription, $level );
159
160 if ( self::$enabled ) {
161 self::$log[] = array(
162 'msg' => htmlspecialchars( $msg ),
163 'type' => 'warn',
164 'caller' => $callerDescription['func'],
165 );
166 }
167 }
168
169 /**
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.
177 *
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
187 */
188 public static function deprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
189 $callerDescription = self::getCallerDescription( $callerOffset );
190 $callerFunc = $callerDescription['func'];
191
192 $sendToLog = true;
193
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;
202 }
203 }
204
205 self::$deprecationWarnings[$function][$callerFunc] = true;
206
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 );
214
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;
219 }
220 }
221
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.";
226 }
227
228 if ( $sendToLog ) {
229 global $wgDevelopmentWarnings; // we could have a more specific $wgDeprecationWarnings setting.
230 self::sendWarning( $msg, $callerDescription, $wgDevelopmentWarnings ? E_USER_DEPRECATED : false );
231 }
232
233 if ( self::$enabled ) {
234 $logMsg = htmlspecialchars( $msg ) .
235 Html::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
236 Html::element( 'span', array(), 'Backtrace:' ) . wfBacktrace()
237 );
238
239 self::$log[] = array(
240 'msg' => $logMsg,
241 'type' => 'deprecated',
242 'caller' => $callerFunc,
243 );
244 }
245 }
246
247 /**
248 * Get an array describing the calling function at a specified offset.
249 *
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'
253 */
254 private static function getCallerDescription( $callerOffset ) {
255 $callers = wfDebugBacktrace();
256
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)';
263 }
264 } else {
265 $file = '(unknown location)';
266 }
267
268 if ( isset( $callers[$callerOffset + 1] ) ) {
269 $callerfunc = $callers[$callerOffset + 1];
270 $func = '';
271 if ( isset( $callerfunc['class'] ) ) {
272 $func .= $callerfunc['class'] . '::';
273 }
274 if ( isset( $callerfunc['function'] ) ) {
275 $func .= $callerfunc['function'];
276 }
277 } else {
278 $func = 'unknown';
279 }
280
281 return array( 'file' => $file, 'func' => $func );
282 }
283
284 /**
285 * Send a warning to the debug log and optionally also trigger a PHP
286 * error, depending on the $level argument.
287 *
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
291 */
292 private static function sendWarning( $msg, $caller, $level ) {
293 $msg .= ' [Called from ' . $caller['func'] . ' in ' . $caller['file'] . ']';
294
295 if ( $level !== false ) {
296 trigger_error( $msg, $level );
297 }
298
299 wfDebug( "$msg\n" );
300 }
301
302 /**
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()
305 *
306 * @since 1.19
307 * @param $str string
308 */
309 public static function debugMsg( $str ) {
310 global $wgDebugComments, $wgShowDebug;
311
312 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
313 self::$debug[] = rtrim( $str );
314 }
315 }
316
317 /**
318 * Begins profiling on a database query
319 *
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
326 */
327 public static function query( $sql, $function, $isMaster ) {
328 if ( !self::$enabled ) {
329 return -1;
330 }
331
332 self::$query[] = array(
333 'sql' => $sql,
334 'function' => $function,
335 'master' => (bool) $isMaster,
336 'time' => 0.0,
337 '_start' => microtime( true ),
338 );
339
340 return count( self::$query ) - 1;
341 }
342
343 /**
344 * Calculates how long a query took.
345 *
346 * @since 1.19
347 * @param $id int
348 */
349 public static function queryTime( $id ) {
350 if ( $id === -1 || !self::$enabled ) {
351 return;
352 }
353
354 self::$query[$id]['time'] = microtime( true ) - self::$query[$id]['_start'];
355 unset( self::$query[$id]['_start'] );
356 }
357
358 /**
359 * Returns a list of files included, along with their size
360 *
361 * @param $context IContextSource
362 * @return array
363 */
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 ),
372 );
373 }
374
375 return $fileList;
376 }
377
378 /**
379 * Returns the HTML to add to the page for the toolbar
380 *
381 * @since 1.19
382 * @param $context IContextSource
383 * @return string
384 */
385 public static function getDebugHTML( IContextSource $context ) {
386 global $wgDebugComments;
387
388 $html = '';
389
390 if ( self::$enabled ) {
391 MWDebug::log( 'MWDebug output complete' );
392 $debugInfo = self::getDebugInfo( $context );
393
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 ) )
399 )
400 );
401 }
402
403 if ( $wgDebugComments ) {
404 $html .= "<!-- Debug output:\n" .
405 htmlspecialchars( implode( "\n", self::$debug ) ) .
406 "\n\n-->";
407 }
408
409 return $html;
410 }
411
412 /**
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.
416 *
417 * @since 1.20
418 * @return string HTML fragment
419 */
420 public static function getHTMLDebugLog() {
421 global $wgDebugTimestamps, $wgShowDebug;
422
423 if ( !$wgShowDebug ) {
424 return '';
425 }
426
427 $curIdent = 0;
428 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
429
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 ) );
437 }
438 }
439 $display = ltrim( $line );
440 $ident = strlen( $line ) - strlen( $display );
441 $diff = $ident - $curIdent;
442
443 $display = $pre . $display;
444 if ( $display == '' ) {
445 $display = "\xc2\xa0";
446 }
447
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 ) );
454 }
455
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 );
462 }
463 $ret .= "<tt>$display</tt>\n";
464
465 $curIdent = $ident;
466 }
467
468 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
469
470 return $ret;
471 }
472
473 /**
474 * Append the debug info to given ApiResult
475 *
476 * @param $context IContextSource
477 * @param $result ApiResult
478 */
479 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
480 if ( !self::$enabled ) {
481 return;
482 }
483
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 ) );
492 }
493 }
494 }
495
496 MWDebug::log( 'MWDebug output complete' );
497 $debugInfo = self::getDebugInfo( $context );
498
499 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
500 $result->setIndexedTagName( $debugInfo['log'], 'line' );
501 foreach ( $debugInfo['debugLog'] as $index => $debugLogText ) {
502 $vals = array();
503 ApiResult::setContent( $vals, $debugLogText );
504 $debugInfo['debugLog'][$index] = $vals; //replace
505 }
506 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
507 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
508 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
509 $result->addValue( array(), 'debuginfo', $debugInfo );
510 }
511
512 /**
513 * Returns the HTML to add to the page for the toolbar
514 *
515 * @param $context IContextSource
516 * @return array
517 */
518 public static function getDebugInfo( IContextSource $context ) {
519 if ( !self::$enabled ) {
520 return array();
521 }
522
523 global $wgVersion, $wgRequestTime;
524 $request = $context->getRequest();
525 return array(
526 'mwVersion' => $wgVersion,
527 'phpVersion' => PHP_VERSION,
528 'gitRevision' => GitInfo::headSHA1(),
529 'gitBranch' => GitInfo::currentBranch(),
530 'gitViewUrl' => GitInfo::headViewUrl(),
531 'time' => microtime( true ) - $wgRequestTime,
532 'log' => self::$log,
533 'debugLog' => self::$debug,
534 'queries' => self::$query,
535 'request' => array(
536 'method' => $request->getMethod(),
537 'url' => $request->getRequestURL(),
538 'headers' => $request->getAllHeaders(),
539 'params' => $request->getValues(),
540 ),
541 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
542 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
543 'includes' => self::getFilesIncluded( $context ),
544 );
545 }
546 }