Merge "Button group adjustments"
[lhc/web/wiklou.git] / includes / profiler / Profiler.php
1 <?php
2 /**
3 * Base class and functions for profiling.
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 * @ingroup Profiler
22 * This file is only included if profiling is enabled
23 */
24
25 /**
26 * @defgroup Profiler Profiler
27 */
28
29 /**
30 * Begin profiling of a function
31 * @param string $functionname name of the function we will profile
32 */
33 function wfProfileIn( $functionname ) {
34 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
35 Profiler::instance();
36 }
37 if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
38 Profiler::$__instance->profileIn( $functionname );
39 }
40 }
41
42 /**
43 * Stop profiling of a function
44 * @param string $functionname name of the function we have profiled
45 */
46 function wfProfileOut( $functionname = 'missing' ) {
47 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
48 Profiler::instance();
49 }
50 if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
51 Profiler::$__instance->profileOut( $functionname );
52 }
53 }
54
55 /**
56 * Class for handling function-scope profiling
57 *
58 * @since 1.22
59 */
60 class ProfileSection {
61 protected $name; // string; method name
62 protected $enabled = false; // boolean; whether profiling is enabled
63
64 /**
65 * Begin profiling of a function and return an object that ends profiling of
66 * the function when that object leaves scope. As long as the object is not
67 * specifically linked to other objects, it will fall out of scope at the same
68 * moment that the function to be profiled terminates.
69 *
70 * This is typically called like:
71 * <code>$section = new ProfileSection( __METHOD__ );</code>
72 *
73 * @param string $name Name of the function to profile
74 */
75 public function __construct( $name ) {
76 $this->name = $name;
77 if ( Profiler::$__instance === null ) { // use this directly to reduce overhead
78 Profiler::instance();
79 }
80 if ( !( Profiler::$__instance instanceof ProfilerStub ) ) {
81 $this->enabled = true;
82 Profiler::$__instance->profileIn( $this->name );
83 }
84 }
85
86 function __destruct() {
87 if ( $this->enabled ) {
88 Profiler::$__instance->profileOut( $this->name );
89 }
90 }
91 }
92
93 /**
94 * @ingroup Profiler
95 * @todo document
96 */
97 class Profiler {
98 protected $mStack = array(), $mWorkStack = array(), $mCollated = array(),
99 $mCalls = array(), $mTotals = array();
100 protected $mTimeMetric = 'wall';
101 protected $mProfileID = false, $mCollateDone = false, $mTemplated = false;
102
103 protected $mDBLockThreshold = 5.0; // float; seconds
104 /** @var Array DB/server name => (active trx count,timestamp) */
105 protected $mDBTrxHoldingLocks = array();
106 /** @var Array DB/server name => list of (method, elapsed time) */
107 protected $mDBTrxMethodTimes = array();
108
109 /** @var Profiler */
110 public static $__instance = null; // do not call this outside Profiler and ProfileSection
111
112 function __construct( $params ) {
113 if ( isset( $params['timeMetric'] ) ) {
114 $this->mTimeMetric = $params['timeMetric'];
115 }
116 if ( isset( $params['profileID'] ) ) {
117 $this->mProfileID = $params['profileID'];
118 }
119
120 $this->addInitialStack();
121 }
122
123 /**
124 * Singleton
125 * @return Profiler
126 */
127 public static function instance() {
128 if ( self::$__instance === null ) {
129 global $wgProfiler;
130 if ( is_array( $wgProfiler ) ) {
131 if ( !isset( $wgProfiler['class'] ) ) {
132 $class = 'ProfilerStub';
133 } else {
134 $class = $wgProfiler['class'];
135 }
136 self::$__instance = new $class( $wgProfiler );
137 } elseif ( $wgProfiler instanceof Profiler ) {
138 self::$__instance = $wgProfiler; // back-compat
139 } else {
140 self::$__instance = new ProfilerStub( $wgProfiler );
141 }
142 }
143 return self::$__instance;
144 }
145
146 /**
147 * Set the profiler to a specific profiler instance. Mostly for dumpHTML
148 * @param $p Profiler object
149 */
150 public static function setInstance( Profiler $p ) {
151 self::$__instance = $p;
152 }
153
154 /**
155 * Return whether this a stub profiler
156 *
157 * @return Boolean
158 */
159 public function isStub() {
160 return false;
161 }
162
163 /**
164 * Return whether this profiler stores data
165 *
166 * @see Profiler::logData()
167 * @return Boolean
168 */
169 public function isPersistent() {
170 return true;
171 }
172
173 public function setProfileID( $id ) {
174 $this->mProfileID = $id;
175 }
176
177 public function getProfileID() {
178 if ( $this->mProfileID === false ) {
179 return wfWikiID();
180 } else {
181 return $this->mProfileID;
182 }
183 }
184
185 /**
186 * Add the inital item in the stack.
187 */
188 protected function addInitialStack() {
189 // Push an entry for the pre-profile setup time onto the stack
190 $initial = $this->getInitialTime();
191 if ( $initial !== null ) {
192 $this->mWorkStack[] = array( '-total', 0, $initial, 0 );
193 $this->mStack[] = array( '-setup', 1, $initial, 0, $this->getTime(), 0 );
194 } else {
195 $this->profileIn( '-total' );
196 }
197 }
198
199 /**
200 * Called by wfProfieIn()
201 *
202 * @param $functionname String
203 */
204 public function profileIn( $functionname ) {
205 global $wgDebugFunctionEntry;
206 if ( $wgDebugFunctionEntry ) {
207 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) ) . 'Entering ' . $functionname . "\n" );
208 }
209
210 $this->mWorkStack[] = array( $functionname, count( $this->mWorkStack ), $this->getTime(), memory_get_usage() );
211 }
212
213 /**
214 * Called by wfProfieOut()
215 *
216 * @param $functionname String
217 */
218 public function profileOut( $functionname ) {
219 global $wgDebugFunctionEntry;
220 $memory = memory_get_usage();
221 $time = $this->getTime();
222
223 if ( $wgDebugFunctionEntry ) {
224 $this->debug( str_repeat( ' ', count( $this->mWorkStack ) - 1 ) . 'Exiting ' . $functionname . "\n" );
225 }
226
227 $bit = array_pop( $this->mWorkStack );
228
229 if ( !$bit ) {
230 $this->debugGroup( 'profileerror', "Profiling error, !\$bit: $functionname" );
231 } else {
232 if ( $functionname == 'close' ) {
233 if ( $bit[0] != '-total' ) {
234 $message = "Profile section ended by close(): {$bit[0]}";
235 $this->debugGroup( 'profileerror', $message );
236 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
237 }
238 } elseif ( $bit[0] != $functionname ) {
239 $message = "Profiling error: in({$bit[0]}), out($functionname)";
240 $this->debugGroup( 'profileerror', $message );
241 $this->mStack[] = array( $message, 0, 0.0, 0, 0.0, 0 );
242 }
243 $bit[] = $time;
244 $bit[] = $memory;
245 $this->mStack[] = $bit;
246 $this->updateTrxProfiling( $functionname, $time );
247 }
248 }
249
250 /**
251 * Close opened profiling sections
252 */
253 public function close() {
254 while ( count( $this->mWorkStack ) ) {
255 $this->profileOut( 'close' );
256 }
257 }
258
259 /**
260 * Mark a DB as in a transaction with one or more writes pending
261 *
262 * Note that there can be multiple connections to a single DB.
263 *
264 * @param string $server DB server
265 * @param string $db DB name
266 */
267 public function transactionWritingIn( $server, $db ) {
268 $name = "{$server} ({$db})";
269 if ( isset( $this->mDBTrxHoldingLocks[$name] ) ) {
270 ++$this->mDBTrxHoldingLocks[$name]['refs'];
271 } else {
272 $this->mDBTrxHoldingLocks[$name] = array( 'refs' => 1, 'start' => microtime( true ) );
273 $this->mDBTrxMethodTimes[$name] = array();
274 }
275 }
276
277 /**
278 * Register the name and time of a method for slow DB trx detection
279 *
280 * @param string $method Function name
281 * @param float $realtime Wal time ellapsed
282 */
283 protected function updateTrxProfiling( $method, $realtime ) {
284 if ( !$this->mDBTrxHoldingLocks ) {
285 return; // short-circuit
286 // @TODO: hardcoded check is a tad janky (what about FOR UPDATE?)
287 } elseif ( !preg_match( '/^query-m: (?!SELECT)/', $method )
288 && $realtime < $this->mDBLockThreshold
289 ) {
290 return; // not a DB master query nor slow enough
291 }
292 $now = microtime( true );
293 foreach ( $this->mDBTrxHoldingLocks as $name => $info ) {
294 // Hacky check to exclude entries from before the first TRX write
295 if ( ( $now - $realtime ) >= $info['start'] ) {
296 $this->mDBTrxMethodTimes[$name][] = array( $method, $realtime );
297 }
298 }
299 }
300
301 /**
302 * Mark a DB as no longer in a transaction
303 *
304 * This will check if locks are possibly held for longer than
305 * needed and log any affected transactions to a special DB log.
306 * Note that there can be multiple connections to a single DB.
307 *
308 * @param string $server DB server
309 * @param string $db DB name
310 */
311 public function transactionWritingOut( $server, $db ) {
312 $name = "{$server} ({$db})";
313 if ( --$this->mDBTrxHoldingLocks[$name]['refs'] <= 0 ) {
314 $slow = false;
315 foreach ( $this->mDBTrxMethodTimes[$name] as $info ) {
316 list( $method, $realtime ) = $info;
317 if ( $realtime >= $this->mDBLockThreshold ) {
318 $slow = true;
319 break;
320 }
321 }
322 if ( $slow ) {
323 $dbs = implode( ', ', array_keys( $this->mDBTrxHoldingLocks ) );
324 $msg = "Sub-optimal transaction on DB(s) {$dbs}:\n";
325 foreach ( $this->mDBTrxMethodTimes[$name] as $i => $info ) {
326 list( $method, $realtime ) = $info;
327 $msg .= sprintf( "%d\t%.6f\t%s\n", $i, $realtime, $method );
328 }
329 $this->debugGroup( 'DBPerformance', $msg );
330 }
331 unset( $this->mDBTrxHoldingLocks[$name] );
332 unset( $this->mDBTrxMethodTimes[$name] );
333 }
334 }
335
336 /**
337 * Mark this call as templated or not
338 *
339 * @param $t Boolean
340 */
341 function setTemplated( $t ) {
342 $this->mTemplated = $t;
343 }
344
345 /**
346 * Returns a profiling output to be stored in debug file
347 *
348 * @return String
349 */
350 public function getOutput() {
351 global $wgDebugFunctionEntry, $wgProfileCallTree;
352 $wgDebugFunctionEntry = false;
353
354 if ( !count( $this->mStack ) && !count( $this->mCollated ) ) {
355 return "No profiling output\n";
356 }
357
358 if ( $wgProfileCallTree ) {
359 return $this->getCallTree();
360 } else {
361 return $this->getFunctionReport();
362 }
363 }
364
365 /**
366 * Returns a tree of function call instead of a list of functions
367 * @return string
368 */
369 function getCallTree() {
370 return implode( '', array_map( array( &$this, 'getCallTreeLine' ), $this->remapCallTree( $this->mStack ) ) );
371 }
372
373 /**
374 * Recursive function the format the current profiling array into a tree
375 *
376 * @param array $stack profiling array
377 * @return array
378 */
379 function remapCallTree( $stack ) {
380 if ( count( $stack ) < 2 ) {
381 return $stack;
382 }
383 $outputs = array();
384 for ( $max = count( $stack ) - 1; $max > 0; ) {
385 /* Find all items under this entry */
386 $level = $stack[$max][1];
387 $working = array();
388 for ( $i = $max -1; $i >= 0; $i-- ) {
389 if ( $stack[$i][1] > $level ) {
390 $working[] = $stack[$i];
391 } else {
392 break;
393 }
394 }
395 $working = $this->remapCallTree( array_reverse( $working ) );
396 $output = array();
397 foreach ( $working as $item ) {
398 array_push( $output, $item );
399 }
400 array_unshift( $output, $stack[$max] );
401 $max = $i;
402
403 array_unshift( $outputs, $output );
404 }
405 $final = array();
406 foreach ( $outputs as $output ) {
407 foreach ( $output as $item ) {
408 $final[] = $item;
409 }
410 }
411 return $final;
412 }
413
414 /**
415 * Callback to get a formatted line for the call tree
416 * @return string
417 */
418 function getCallTreeLine( $entry ) {
419 list( $fname, $level, $start, /* $x */, $end ) = $entry;
420 $delta = $end - $start;
421 $space = str_repeat( ' ', $level );
422 # The ugly double sprintf is to work around a PHP bug,
423 # which has been fixed in recent releases.
424 return sprintf( "%10s %s %s\n", trim( sprintf( "%7.3f", $delta * 1000.0 ) ), $space, $fname );
425 }
426
427 /**
428 * Get the initial time of the request, based either on $wgRequestTime or
429 * $wgRUstart. Will return null if not able to find data.
430 *
431 * @param string|false $metric metric to use, with the following possibilities:
432 * - user: User CPU time (without system calls)
433 * - cpu: Total CPU time (user and system calls)
434 * - wall (or any other string): elapsed time
435 * - false (default): will fall back to default metric
436 * @return float|null
437 */
438 function getTime( $metric = false ) {
439 if ( $metric === false ) {
440 $metric = $this->mTimeMetric;
441 }
442
443 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
444 if ( !function_exists( 'getrusage' ) ) {
445 return 0;
446 }
447 $ru = getrusage();
448 $time = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
449 if ( $metric === 'cpu' ) {
450 # This is the time of system calls, added to the user time
451 # it gives the total CPU time
452 $time += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
453 }
454 return $time;
455 } else {
456 return microtime( true );
457 }
458 }
459
460 /**
461 * Get the initial time of the request, based either on $wgRequestTime or
462 * $wgRUstart. Will return null if not able to find data.
463 *
464 * @param string|false $metric metric to use, with the following possibilities:
465 * - user: User CPU time (without system calls)
466 * - cpu: Total CPU time (user and system calls)
467 * - wall (or any other string): elapsed time
468 * - false (default): will fall back to default metric
469 * @return float|null
470 */
471 protected function getInitialTime( $metric = false ) {
472 global $wgRequestTime, $wgRUstart;
473
474 if ( $metric === false ) {
475 $metric = $this->mTimeMetric;
476 }
477
478 if ( $metric === 'cpu' || $this->mTimeMetric === 'user' ) {
479 if ( !count( $wgRUstart ) ) {
480 return null;
481 }
482
483 $time = $wgRUstart['ru_utime.tv_sec'] + $wgRUstart['ru_utime.tv_usec'] / 1e6;
484 if ( $metric === 'cpu' ) {
485 # This is the time of system calls, added to the user time
486 # it gives the total CPU time
487 $time += $wgRUstart['ru_stime.tv_sec'] + $wgRUstart['ru_stime.tv_usec'] / 1e6;
488 }
489 return $time;
490 } else {
491 if ( empty( $wgRequestTime ) ) {
492 return null;
493 } else {
494 return $wgRequestTime;
495 }
496 }
497 }
498
499 protected function collateData() {
500 if ( $this->mCollateDone ) {
501 return;
502 }
503 $this->mCollateDone = true;
504
505 $this->close();
506
507 $this->mCollated = array();
508 $this->mCalls = array();
509 $this->mMemory = array();
510
511 # Estimate profiling overhead
512 $profileCount = count( $this->mStack );
513 self::calculateOverhead( $profileCount );
514
515 # First, subtract the overhead!
516 $overheadTotal = $overheadMemory = $overheadInternal = array();
517 foreach ( $this->mStack as $entry ) {
518 $fname = $entry[0];
519 $start = $entry[2];
520 $end = $entry[4];
521 $elapsed = $end - $start;
522 $memory = $entry[5] - $entry[3];
523
524 if ( $fname == '-overhead-total' ) {
525 $overheadTotal[] = $elapsed;
526 $overheadMemory[] = $memory;
527 } elseif ( $fname == '-overhead-internal' ) {
528 $overheadInternal[] = $elapsed;
529 }
530 }
531 $overheadTotal = $overheadTotal ? array_sum( $overheadTotal ) / count( $overheadInternal ) : 0;
532 $overheadMemory = $overheadMemory ? array_sum( $overheadMemory ) / count( $overheadInternal ) : 0;
533 $overheadInternal = $overheadInternal ? array_sum( $overheadInternal ) / count( $overheadInternal ) : 0;
534
535 # Collate
536 foreach ( $this->mStack as $index => $entry ) {
537 $fname = $entry[0];
538 $start = $entry[2];
539 $end = $entry[4];
540 $elapsed = $end - $start;
541
542 $memory = $entry[5] - $entry[3];
543 $subcalls = $this->calltreeCount( $this->mStack, $index );
544
545 if ( !preg_match( '/^-overhead/', $fname ) ) {
546 # Adjust for profiling overhead (except special values with elapsed=0
547 if ( $elapsed ) {
548 $elapsed -= $overheadInternal;
549 $elapsed -= ( $subcalls * $overheadTotal );
550 $memory -= ( $subcalls * $overheadMemory );
551 }
552 }
553
554 if ( !array_key_exists( $fname, $this->mCollated ) ) {
555 $this->mCollated[$fname] = 0;
556 $this->mCalls[$fname] = 0;
557 $this->mMemory[$fname] = 0;
558 $this->mMin[$fname] = 1 << 24;
559 $this->mMax[$fname] = 0;
560 $this->mOverhead[$fname] = 0;
561 }
562
563 $this->mCollated[$fname] += $elapsed;
564 $this->mCalls[$fname]++;
565 $this->mMemory[$fname] += $memory;
566 $this->mMin[$fname] = min( $this->mMin[$fname], $elapsed );
567 $this->mMax[$fname] = max( $this->mMax[$fname], $elapsed );
568 $this->mOverhead[$fname] += $subcalls;
569 }
570
571 $this->mCalls['-overhead-total'] = $profileCount;
572 arsort( $this->mCollated, SORT_NUMERIC );
573 }
574
575 /**
576 * Returns a list of profiled functions.
577 *
578 * @return string
579 */
580 function getFunctionReport() {
581 $this->collateData();
582
583 $width = 140;
584 $nameWidth = $width - 65;
585 $format = "%-{$nameWidth}s %6d %13.3f %13.3f %13.3f%% %9d (%13.3f -%13.3f) [%d]\n";
586 $titleFormat = "%-{$nameWidth}s %6s %13s %13s %13s %9s\n";
587 $prof = "\nProfiling data\n";
588 $prof .= sprintf( $titleFormat, 'Name', 'Calls', 'Total', 'Each', '%', 'Mem' );
589
590 $total = isset( $this->mCollated['-total'] ) ? $this->mCollated['-total'] : 0;
591
592 foreach ( $this->mCollated as $fname => $elapsed ) {
593 $calls = $this->mCalls[$fname];
594 $percent = $total ? 100. * $elapsed / $total : 0;
595 $memory = $this->mMemory[$fname];
596 $prof .= sprintf( $format,
597 substr( $fname, 0, $nameWidth ),
598 $calls,
599 (float)( $elapsed * 1000 ),
600 (float)( $elapsed * 1000 ) / $calls,
601 $percent,
602 $memory,
603 ( $this->mMin[$fname] * 1000.0 ),
604 ( $this->mMax[$fname] * 1000.0 ),
605 $this->mOverhead[$fname]
606 );
607 }
608 $prof .= "\nTotal: $total\n\n";
609
610 return $prof;
611 }
612
613 /**
614 * Dummy calls to wfProfileIn/wfProfileOut to calculate its overhead
615 */
616 protected static function calculateOverhead( $profileCount ) {
617 wfProfileIn( '-overhead-total' );
618 for ( $i = 0; $i < $profileCount; $i++ ) {
619 wfProfileIn( '-overhead-internal' );
620 wfProfileOut( '-overhead-internal' );
621 }
622 wfProfileOut( '-overhead-total' );
623 }
624
625 /**
626 * Counts the number of profiled function calls sitting under
627 * the given point in the call graph. Not the most efficient algo.
628 *
629 * @param $stack Array:
630 * @param $start Integer:
631 * @return Integer
632 * @private
633 */
634 function calltreeCount( $stack, $start ) {
635 $level = $stack[$start][1];
636 $count = 0;
637 for ( $i = $start -1; $i >= 0 && $stack[$i][1] > $level; $i-- ) {
638 $count ++;
639 }
640 return $count;
641 }
642
643 /**
644 * Log the whole profiling data into the database.
645 */
646 public function logData() {
647 global $wgProfilePerHost, $wgProfileToDatabase;
648
649 # Do not log anything if database is readonly (bug 5375)
650 if ( wfReadOnly() || !$wgProfileToDatabase ) {
651 return;
652 }
653
654 $dbw = wfGetDB( DB_MASTER );
655 if ( !is_object( $dbw ) ) {
656 return;
657 }
658
659 if ( $wgProfilePerHost ) {
660 $pfhost = wfHostname();
661 } else {
662 $pfhost = '';
663 }
664
665 try {
666 $this->collateData();
667
668 foreach ( $this->mCollated as $name => $elapsed ) {
669 $eventCount = $this->mCalls[$name];
670 $timeSum = (float)( $elapsed * 1000 );
671 $memorySum = (float)$this->mMemory[$name];
672 $name = substr( $name, 0, 255 );
673
674 // Kludge
675 $timeSum = $timeSum >= 0 ? $timeSum : 0;
676 $memorySum = $memorySum >= 0 ? $memorySum : 0;
677
678 $dbw->update( 'profiling',
679 array(
680 "pf_count=pf_count+{$eventCount}",
681 "pf_time=pf_time+{$timeSum}",
682 "pf_memory=pf_memory+{$memorySum}",
683 ),
684 array(
685 'pf_name' => $name,
686 'pf_server' => $pfhost,
687 ),
688 __METHOD__ );
689
690 $rc = $dbw->affectedRows();
691 if ( $rc == 0 ) {
692 $dbw->insert( 'profiling', array( 'pf_name' => $name, 'pf_count' => $eventCount,
693 'pf_time' => $timeSum, 'pf_memory' => $memorySum, 'pf_server' => $pfhost ),
694 __METHOD__, array( 'IGNORE' ) );
695 }
696 // When we upgrade to mysql 4.1, the insert+update
697 // can be merged into just a insert with this construct added:
698 // "ON DUPLICATE KEY UPDATE ".
699 // "pf_count=pf_count + VALUES(pf_count), ".
700 // "pf_time=pf_time + VALUES(pf_time)";
701 }
702 } catch ( DBError $e ) {}
703 }
704
705 /**
706 * Get the function name of the current profiling section
707 * @return
708 */
709 function getCurrentSection() {
710 $elt = end( $this->mWorkStack );
711 return $elt[0];
712 }
713
714 /**
715 * Add an entry in the debug log file
716 *
717 * @param string $s to output
718 */
719 function debug( $s ) {
720 if ( function_exists( 'wfDebug' ) ) {
721 wfDebug( $s );
722 }
723 }
724
725 /**
726 * Add an entry in the debug log group
727 *
728 * @param string $group Group to send the message to
729 * @param string $s to output
730 */
731 function debugGroup( $group, $s ) {
732 if ( function_exists( 'wfDebugLog' ) ) {
733 wfDebugLog( $group, $s );
734 }
735 }
736
737 /**
738 * Get the content type sent out to the client.
739 * Used for profilers that output instead of store data.
740 * @return string
741 */
742 protected function getContentType() {
743 foreach ( headers_list() as $header ) {
744 if ( preg_match( '#^content-type: (\w+/\w+);?#i', $header, $m ) ) {
745 return $m[1];
746 }
747 }
748 return null;
749 }
750 }