9 private static $headersSentException;
10 private static $messageSent = false;
13 * Register a callback to be called when headers are sent. There can only
14 * be one of these handlers active, so all relevant actions have to be in
19 public static function register() {
20 header_register_callback( [ __CLASS__
, 'callback' ] );
24 * The callback, which is called by the transport
28 public static function callback() {
29 // Prevent caching of responses with cookies (T127993)
31 foreach ( headers_list() as $header ) {
32 $header = explode( ':', $header, 2 );
34 // Note: The code below (currently) does not care about value-less headers
35 if ( isset( $header[1] ) ) {
36 $headers[ strtolower( trim( $header[0] ) ) ][] = trim( $header[1] );
40 if ( isset( $headers['set-cookie'] ) ) {
41 $cacheControl = isset( $headers['cache-control'] )
42 ?
implode( ', ', $headers['cache-control'] )
45 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i',
48 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
49 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
50 \MediaWiki\Logger\LoggerFactory
::getInstance( 'cache-cookies' )->warning(
51 'Cookies set on {url} with Cache-Control "{cache-control}"', [
52 'url' => \WebRequest
::getGlobalRequestURL(),
53 'cookies' => $headers['set-cookie'],
54 'cache-control' => $cacheControl ?
: '<not set>',
60 // Save a backtrace for logging in case it turns out that headers were sent prematurely
61 self
::$headersSentException = new \
Exception( 'Headers already sent from this point' );
65 * Log a warning message if headers have already been sent. This can be
66 * called before flushing the output.
70 public static function warnIfHeadersSent() {
71 if ( headers_sent() && !self
::$messageSent ) {
72 self
::$messageSent = true;
73 \MWDebug
::warning( 'Headers already sent, should send headers earlier than ' .
75 $logger = \MediaWiki\Logger\LoggerFactory
::getInstance( 'headers-sent' );
76 $logger->error( 'Warning: headers were already sent from the location below', [
77 'exception' => self
::$headersSentException,
78 'detection-trace' => new \
Exception( 'Detected here' ),