MediaWiki REL1_34
HeaderCallback.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki;
4
9 private static $headersSentException;
10 private static $messageSent = false;
11
19 public static function register() {
20 header_register_callback( [ __CLASS__, 'callback' ] );
21 }
22
28 public static function callback() {
29 // Prevent caching of responses with cookies (T127993)
30 $headers = [];
31 foreach ( headers_list() as $header ) {
32 $header = explode( ':', $header, 2 );
33
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] );
37 }
38 }
39
40 if ( isset( $headers['set-cookie'] ) ) {
41 $cacheControl = isset( $headers['cache-control'] )
42 ? implode( ', ', $headers['cache-control'] )
43 : '';
44
45 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i',
46 $cacheControl )
47 ) {
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>',
55 ]
56 );
57 }
58 }
59
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' );
62 }
63
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 ' .
74 wfGetCaller( 3 ) );
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' ),
79 ] );
80 }
81 }
82}
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
static warnIfHeadersSent()
Log a warning message if headers have already been sent.
static callback()
The callback, which is called by the transport.
A helper class for throttling authentication attempts.
$header