merged master
[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
137 * @param int $callerOffset
138 * @return mixed
139 */
140 public static function warning( $msg, $callerOffset = 1 ) {
141 if ( !self::$enabled ) {
142 return;
143 }
144
145 // Check to see if there was already a deprecation notice, so not to
146 // get a duplicate warning
147 $logCount = count( self::$log );
148 $caller = wfGetCaller( $callerOffset + 1 );
149 if ( $logCount ) {
150 $lastLog = self::$log[ $logCount - 1 ];
151 if ( $lastLog['type'] == 'deprecated' && $lastLog['caller'] == $caller ) {
152 return;
153 }
154 }
155
156 self::$log[] = array(
157 'msg' => htmlspecialchars( $msg ),
158 'type' => 'warn',
159 'caller' => $caller,
160 );
161 }
162
163 /**
164 * Adds a depreciation entry to the log, along with a backtrace
165 *
166 * @since 1.19
167 * @param $function
168 * @param $version
169 * @param $component
170 * @return mixed
171 */
172 public static function deprecated( $function, $version, $component ) {
173 if ( !self::$enabled ) {
174 return;
175 }
176
177 // Chain: This function -> wfDeprecated -> deprecatedFunction -> caller
178 $caller = wfGetCaller( 4 );
179
180 // Check to see if there already was a warning about this function
181 $functionString = "$function-$caller";
182 if ( in_array( $functionString, self::$deprecationWarnings ) ) {
183 return;
184 }
185
186 $version = $version === false ? '(unknown version)' : $version;
187 $component = $component === false ? 'MediaWiki' : $component;
188 $msg = htmlspecialchars( "Use of function $function was deprecated in $component $version" );
189 $msg .= Html::rawElement( 'div', array( 'class' => 'mw-debug-backtrace' ),
190 Html::element( 'span', array(), 'Backtrace:' )
191 . wfBacktrace()
192 );
193
194 self::$deprecationWarnings[] = $functionString;
195 self::$log[] = array(
196 'msg' => $msg,
197 'type' => 'deprecated',
198 'caller' => $caller,
199 );
200 }
201
202 /**
203 * This is a method to pass messages from wfDebug to the pretty debugger.
204 * Do NOT use this method, use MWDebug::log or wfDebug()
205 *
206 * @since 1.19
207 * @param $str string
208 */
209 public static function debugMsg( $str ) {
210 global $wgDebugComments, $wgShowDebug;
211
212 if ( self::$enabled || $wgDebugComments || $wgShowDebug ) {
213 self::$debug[] = rtrim( $str );
214 }
215 }
216
217 /**
218 * Begins profiling on a database query
219 *
220 * @since 1.19
221 * @param $sql string
222 * @param $function string
223 * @param $isMaster bool
224 * @return int ID number of the query to pass to queryTime or -1 if the
225 * debugger is disabled
226 */
227 public static function query( $sql, $function, $isMaster ) {
228 if ( !self::$enabled ) {
229 return -1;
230 }
231
232 self::$query[] = array(
233 'sql' => $sql,
234 'function' => $function,
235 'master' => (bool) $isMaster,
236 'time' => 0.0,
237 '_start' => microtime( true ),
238 );
239
240 return count( self::$query ) - 1;
241 }
242
243 /**
244 * Calculates how long a query took.
245 *
246 * @since 1.19
247 * @param $id int
248 */
249 public static function queryTime( $id ) {
250 if ( $id === -1 || !self::$enabled ) {
251 return;
252 }
253
254 self::$query[$id]['time'] = microtime( true ) - self::$query[$id]['_start'];
255 unset( self::$query[$id]['_start'] );
256 }
257
258 /**
259 * Returns a list of files included, along with their size
260 *
261 * @param $context IContextSource
262 * @return array
263 */
264 protected static function getFilesIncluded( IContextSource $context ) {
265 $files = get_included_files();
266 $fileList = array();
267 foreach ( $files as $file ) {
268 $size = filesize( $file );
269 $fileList[] = array(
270 'name' => $file,
271 'size' => $context->getLanguage()->formatSize( $size ),
272 );
273 }
274
275 return $fileList;
276 }
277
278 /**
279 * Returns the HTML to add to the page for the toolbar
280 *
281 * @since 1.19
282 * @param $context IContextSource
283 * @return string
284 */
285 public static function getDebugHTML( IContextSource $context ) {
286 global $wgDebugComments;
287
288 $html = '';
289
290 if ( self::$enabled ) {
291 MWDebug::log( 'MWDebug output complete' );
292 $debugInfo = self::getDebugInfo( $context );
293
294 // Cannot use OutputPage::addJsConfigVars because those are already outputted
295 // by the time this method is called.
296 $html = Html::inlineScript(
297 ResourceLoader::makeLoaderConditionalScript(
298 ResourceLoader::makeConfigSetScript( array( 'debugInfo' => $debugInfo ) )
299 )
300 );
301 }
302
303 if ( $wgDebugComments ) {
304 $html .= "<!-- Debug output:\n" .
305 htmlspecialchars( implode( "\n", self::$debug ) ) .
306 "\n\n-->";
307 }
308
309 return $html;
310 }
311
312 /**
313 * Generate debug log in HTML for displaying at the bottom of the main
314 * content area.
315 * If $wgShowDebug is false, an empty string is always returned.
316 *
317 * @since 1.20
318 * @return string HTML fragment
319 */
320 public static function getHTMLDebugLog() {
321 global $wgDebugTimestamps, $wgShowDebug;
322
323 if ( !$wgShowDebug ) {
324 return '';
325 }
326
327 $curIdent = 0;
328 $ret = "\n<hr />\n<strong>Debug data:</strong><ul id=\"mw-debug-html\">\n<li>";
329
330 foreach ( self::$debug as $line ) {
331 $pre = '';
332 if ( $wgDebugTimestamps ) {
333 $matches = array();
334 if ( preg_match( '/^(\d+\.\d+ {1,3}\d+.\dM\s{2})/', $line, $matches ) ) {
335 $pre = $matches[1];
336 $line = substr( $line, strlen( $pre ) );
337 }
338 }
339 $display = ltrim( $line );
340 $ident = strlen( $line ) - strlen( $display );
341 $diff = $ident - $curIdent;
342
343 $display = $pre . $display;
344 if ( $display == '' ) {
345 $display = "\xc2\xa0";
346 }
347
348 if ( !$ident && $diff < 0 && substr( $display, 0, 9 ) != 'Entering ' && substr( $display, 0, 8 ) != 'Exiting ' ) {
349 $ident = $curIdent;
350 $diff = 0;
351 $display = '<span style="background:yellow;">' . nl2br( htmlspecialchars( $display ) ) . '</span>';
352 } else {
353 $display = nl2br( htmlspecialchars( $display ) );
354 }
355
356 if ( $diff < 0 ) {
357 $ret .= str_repeat( "</li></ul>\n", -$diff ) . "</li><li>\n";
358 } elseif ( $diff == 0 ) {
359 $ret .= "</li><li>\n";
360 } else {
361 $ret .= str_repeat( "<ul><li>\n", $diff );
362 }
363 $ret .= "<tt>$display</tt>\n";
364
365 $curIdent = $ident;
366 }
367
368 $ret .= str_repeat( '</li></ul>', $curIdent ) . "</li>\n</ul>\n";
369
370 return $ret;
371 }
372
373 /**
374 * Append the debug info to given ApiResult
375 *
376 * @param $context IContextSource
377 * @param $result ApiResult
378 */
379 public static function appendDebugInfoToApiResult( IContextSource $context, ApiResult $result ) {
380 if ( !self::$enabled ) {
381 return;
382 }
383
384 // output errors as debug info, when display_errors is on
385 // this is necessary for all non html output of the api, because that clears all errors first
386 $obContents = ob_get_contents();
387 if( $obContents ) {
388 $obContentArray = explode( '<br />', $obContents );
389 foreach( $obContentArray as $obContent ) {
390 if( trim( $obContent ) ) {
391 self::debugMsg( Sanitizer::stripAllTags( $obContent ) );
392 }
393 }
394 }
395
396 MWDebug::log( 'MWDebug output complete' );
397 $debugInfo = self::getDebugInfo( $context );
398
399 $result->setIndexedTagName( $debugInfo, 'debuginfo' );
400 $result->setIndexedTagName( $debugInfo['log'], 'line' );
401 foreach( $debugInfo['debugLog'] as $index => $debugLogText ) {
402 $vals = array();
403 ApiResult::setContent( $vals, $debugLogText );
404 $debugInfo['debugLog'][$index] = $vals; //replace
405 }
406 $result->setIndexedTagName( $debugInfo['debugLog'], 'msg' );
407 $result->setIndexedTagName( $debugInfo['queries'], 'query' );
408 $result->setIndexedTagName( $debugInfo['includes'], 'queries' );
409 $result->addValue( array(), 'debuginfo', $debugInfo );
410 }
411
412 /**
413 * Returns the HTML to add to the page for the toolbar
414 *
415 * @param $context IContextSource
416 * @return array
417 */
418 public static function getDebugInfo( IContextSource $context ) {
419 if ( !self::$enabled ) {
420 return array();
421 }
422
423 global $wgVersion, $wgRequestTime;
424 $request = $context->getRequest();
425 return array(
426 'mwVersion' => $wgVersion,
427 'phpVersion' => PHP_VERSION,
428 'gitRevision' => GitInfo::headSHA1(),
429 'gitBranch' => GitInfo::currentBranch(),
430 'gitViewUrl' => GitInfo::headViewUrl(),
431 'time' => microtime( true ) - $wgRequestTime,
432 'log' => self::$log,
433 'debugLog' => self::$debug,
434 'queries' => self::$query,
435 'request' => array(
436 'method' => $request->getMethod(),
437 'url' => $request->getRequestURL(),
438 'headers' => $request->getAllHeaders(),
439 'params' => $request->getValues(),
440 ),
441 'memory' => $context->getLanguage()->formatSize( memory_get_usage() ),
442 'memoryPeak' => $context->getLanguage()->formatSize( memory_get_peak_usage() ),
443 'includes' => self::getFilesIncluded( $context ),
444 );
445 }
446 }