Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 60
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
OutputHandler
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 4
702
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
110
 findUriExtension
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 handleGzip
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
72
 emitContentLength
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * Functions to be used with PHP's output buffer.
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Output;
10
11use MediaWiki\Logger\LoggerFactory;
12use MediaWiki\MainConfigNames;
13use MediaWiki\MediaWikiServices;
14
15/**
16 * @since 1.31
17 */
18class OutputHandler {
19    /**
20     * Standard output handler for use with ob_start.
21     *
22     * Output buffers using this method should only be started from MW_SETUP_CALLBACK,
23     * and only if there are no parent output buffers.
24     *
25     * @param string $s Web response output
26     * @param int $phase Flags indicating the reason for the call
27     * @return string
28     */
29    public static function handle( $s, $phase ) {
30        $config = MediaWikiServices::getInstance()->getMainConfig();
31        $disableOutputCompression = $config->get( MainConfigNames::DisableOutputCompression );
32        // Don't send headers if output is being discarded (T278579)
33        if ( ( $phase & PHP_OUTPUT_HANDLER_CLEAN ) === PHP_OUTPUT_HANDLER_CLEAN ) {
34            $logger = LoggerFactory::getInstance( 'output' );
35            $logger->debug( __METHOD__ . " entrypoint={entry}; size={size}; phase=$phase", [
36                'entry' => MW_ENTRY_POINT,
37                'size' => strlen( $s ),
38            ] );
39
40            return $s;
41        }
42
43        // Check if a compression output buffer is already enabled via php.ini. Such
44        // buffers exists at the start of the request and are reflected by ob_get_level().
45        $phpHandlesCompression = (
46            ini_get( 'output_handler' ) === 'ob_gzhandler' ||
47            ini_get( 'zlib.output_handler' ) === 'ob_gzhandler' ||
48            !in_array(
49                strtolower( ini_get( 'zlib.output_compression' ) ),
50                [ '', 'off', '0' ]
51            )
52        );
53
54        if (
55            // Compression is not already handled by an internal PHP buffer
56            !$phpHandlesCompression &&
57            // Compression is not disabled by the application entry point
58            !defined( 'MW_NO_OUTPUT_COMPRESSION' ) &&
59            // Compression is not disabled by site configuration
60            !$disableOutputCompression
61        ) {
62            $s = self::handleGzip( $s );
63        }
64
65        if (
66            // Response body length does not depend on internal PHP compression buffer
67            !$phpHandlesCompression &&
68            // Response body length does not depend on mangling by a custom buffer
69            !ini_get( 'output_handler' ) &&
70            !ini_get( 'zlib.output_handler' )
71        ) {
72            self::emitContentLength( strlen( $s ) );
73        }
74
75        return $s;
76    }
77
78    /**
79     * Get the "file extension" that some client apps will estimate from
80     * the currently-requested URL.
81     *
82     * This isn't a WebRequest method, because we need it before the class loads.
83     * @todo As of 2018, this actually runs after autoloader in Setup.php, so
84     * WebRequest seems like a good place for this.
85     *
86     * @return string
87     */
88    private static function findUriExtension() {
89        // @todo FIXME: this sort of dupes some code in WebRequest::getRequestUrl()
90        if ( isset( $_SERVER['REQUEST_URI'] ) ) {
91            // Strip the query string...
92            $path = explode( '?', $_SERVER['REQUEST_URI'], 2 )[0];
93        } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
94            // Probably IIS. QUERY_STRING appears separately.
95            $path = $_SERVER['SCRIPT_NAME'];
96        } else {
97            // Can't get the path from the server? :(
98            return '';
99        }
100
101        $period = strrpos( $path, '.' );
102        if ( $period !== false ) {
103            return strtolower( substr( $path, $period ) );
104        }
105        return '';
106    }
107
108    /**
109     * Handler that compresses data with gzip if allowed by the Accept header.
110     *
111     * Unlike ob_gzhandler, it works for HEAD requests too. This assumes that the application
112     * processes them as normal GET request and that the webserver is tasked with stripping out
113     * the response body before sending the response the client.
114     *
115     * @param string $s Web response output
116     * @return string
117     */
118    private static function handleGzip( $s ) {
119        if ( !function_exists( 'gzencode' ) ) {
120            wfDebug( __METHOD__ . "() skipping compression (gzencode unavailable)" );
121            return $s;
122        }
123        if ( headers_sent() ) {
124            wfDebug( __METHOD__ . "() skipping compression (headers already sent)" );
125            return $s;
126        }
127
128        $ext = self::findUriExtension();
129        if ( $ext == '.gz' || $ext == '.tgz' ) {
130            // Don't do gzip compression if the URL path ends in .gz or .tgz
131            // This confuses Safari and triggers a download of the page,
132            // even though it's pretty clearly labeled as viewable HTML.
133            // Bad Safari! Bad!
134            return $s;
135        }
136
137        if ( $s === '' ) {
138            // Do not gzip empty HTTP responses since that would not only bloat the body
139            // length, but it would result in invalid HTTP responses when the HTTP status code
140            // is one that must not be accompanied by a body (e.g. "204 No Content").
141            return $s;
142        }
143
144        if ( wfClientAcceptsGzip() ) {
145            wfDebug( __METHOD__ . "() is compressing output" );
146            header( 'Content-Encoding: gzip' );
147            $s = gzencode( $s, 6 );
148        }
149
150        // Set vary header if it hasn't been set already
151        if ( !preg_grep( '/^Vary:/i', headers_list() ) ) {
152            header( 'Vary: Accept-Encoding' );
153        }
154        return $s;
155    }
156
157    /**
158     * Set the Content-Length header if possible
159     *
160     * This sets Content-Length for the following cases:
161     *  - When the response body is meaningful (HTTP 200/404).
162     *  - On any HTTP 1.0 request response. This improves cooperation with certain CDNs.
163     *
164     * This assumes that HEAD requests are processed as GET requests by MediaWiki and that
165     * the webserver is tasked with stripping out the body.
166     *
167     * Setting Content-Length can prevent clients from getting stuck waiting on PHP to finish
168     * while deferred updates are running.
169     *
170     * @param int $length
171     */
172    private static function emitContentLength( $length ) {
173        if ( headers_sent() ) {
174            wfDebug( __METHOD__ . "() headers already sent" );
175            return;
176        }
177
178        if (
179            in_array( http_response_code(), [ 200, 404 ], true ) ||
180            ( $_SERVER['SERVER_PROTOCOL'] ?? null ) === 'HTTP/1.0'
181        ) {
182            header( "Content-Length: $length" );
183        }
184    }
185}
186
187/** @deprecated class alias since 1.41 */
188class_alias( OutputHandler::class, 'MediaWiki\\OutputHandler' );