Debian Codegraph @

includes/Request/HeaderCallback.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Request;
4
5 use MediaWiki\Http\Telemetry;
6 use MediaWiki\Logger\LoggerFactory;
7 use RuntimeException;
8
9 /**
10 * @since 1.29
11 */
12 class HeaderCallback {
13 /** @var RuntimeException */
14 private static $headersSentException;
15 /** @var bool */
16 private static $messageSent = false;
17
18 /**
19 * Register a callback to be called when headers are sent. There can only
20 * be one of these handlers active, so all relevant actions have to be in
21 * here.
22 *
23 * @since 1.29
24 */
25 public static function register() {
26 if ( version_compare( PHP_VERSION, '8.6', '<' ) ) {
27 // This bug has been fixed in PHP 8.6:
28 // https://github.com/php/php-src/issues/20619#issuecomment-3828242097
29
30 // T261260 load some classes which will be needed in callback().
31 // Autoloading seems unreliable in header callbacks, and in the case of a web
32 // request (ie. in all cases where the request might be performance-sensitive)
33 // these classes will have to be loaded at some point anyway.
34 class_exists( WebRequest::class );
35 class_exists( LoggerFactory::class );
36 class_exists( Telemetry::class );
37 }
38
39 header_register_callback( [ __CLASS__, 'callback' ] );
40 }
41
42 /**
43 * The callback, which is called by the transport
44 *
45 * @since 1.29
46 */
47 public static function callback() {
48 // Prevent caching of responses with cookies (T127993)
49 $headers = [];
50 foreach ( headers_list() as $header ) {
51 $header = explode( ':', $header, 2 );
52
53 // Note: The code below (currently) does not care about value-less headers
54 if ( isset( $header[1] ) ) {
55 $headers[ strtolower( trim( $header[0] ) ) ][] = trim( $header[1] );
56 }
57 }
58
59 if ( isset( $headers['set-cookie'] ) ) {
60 $cacheControl = isset( $headers['cache-control'] )
61 ? implode( ', ', $headers['cache-control'] )
62 : '';
63
64 if ( !preg_match( '/(?:^|,)\s*(?:private|no-cache|no-store)\s*(?:$|,)/i',
65 $cacheControl )
66 ) {
67 header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' );
68 header( 'Cache-Control: private, max-age=0, s-maxage=0' );
69 \MediaWiki\Logger\LoggerFactory::getInstance( 'cache-cookies' )->warning(
70 'Cookies set on {url} with Cache-Control "{cache-control}"', [
71 'url' => WebRequest::getGlobalRequestURL(),
72 'set-cookie' => self::sanitizeSetCookie( $headers['set-cookie'] ),
73 'cache-control' => $cacheControl ?: '<not set>',
74 ]
75 );
76 }
77 }
78
79 $telemetryHeaders = Telemetry::getInstance()->getRequestHeaders();
80 // Set the request ID/trace prams on the response, so edge infrastructure can log it.
81 // FIXME this is not an ideal place to do it, but the most reliable for now.
82 foreach ( $telemetryHeaders as $header => $value ) {
83 if ( !isset( $headers[strtolower( $header )] ) ) {
84 header( "$header: $value" );
85 }
86 }
87
88 // Save a backtrace for logging in case it turns out that headers were sent prematurely
89 self::$headersSentException = new RuntimeException( 'Headers already sent from this point' );
90 }
91
92 /**
93 * Log a warning message if headers have already been sent. This can be
94 * called before flushing the output.
95 *
96 * @since 1.29
97 */
98 public static function warnIfHeadersSent() {
99 if ( !self::$messageSent && headers_sent( $filename, $line ) ) {
100 self::$messageSent = true;
101 \MediaWiki\Debug\MWDebug::warning( 'Headers already sent, should send headers earlier than ' .
102 wfGetCaller( 3 ) );
103 $logger = \MediaWiki\Logger\LoggerFactory::getInstance( 'headers-sent' );
104 $logger->error( 'Warning: headers were already sent (output started at ' . $filename . ':' . $line . ')', [
105 'exception' => self::$headersSentException,
106 'detection-trace' => new RuntimeException( 'Detected here' ),
107 ] );
108 }
109 }
110
111 /**
112 * Sanitize Set-Cookie headers for logging.
113 * @param array $values List of header values.
114 * @return string
115 */
116 public static function sanitizeSetCookie( array $values ) {
117 $sanitizedValues = [];
118 foreach ( $values as $value ) {
119 // Set-Cookie header format: <cookie-name>=<cookie-value>; <non-sensitive attributes>
120 $parts = explode( ';', $value );
121 [ $name, $value ] = explode( '=', $parts[0], 2 );
122 if ( strlen( $value ) > 8 ) {
123 $value = substr( $value, 0, 8 ) . '...';
124 $parts[0] = "$name=$value";
125 }
126 $sanitizedValues[] = implode( ';', $parts );
127 }
128 return implode( "\n", $sanitizedValues );
129 }
130 }
131
132 /** @deprecated class alias since 1.40 */
133 class_alias( HeaderCallback::class, 'MediaWiki\\HeaderCallback' );