Update docs/hooks.txt for ShowSearchHitTitle
[mediawiki.git] / includes / libs / filebackend / HTTPFileStreamer.php
blob800fdfad3ee121a1ab344381fc0bc8311f32106a
1 <?php
2 /**
3 * Functions related to the output of file content.
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.
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.
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
20 * @file
23 /**
24 * Functions related to the output of file content
26 * @since 1.28
28 class HTTPFileStreamer {
29 /** @var string */
30 protected $path;
31 /** @var callable */
32 protected $obResetFunc;
33 /** @var callable */
34 protected $streamMimeFunc;
36 // Do not send any HTTP headers unless requested by caller (e.g. body only)
37 const STREAM_HEADLESS = 1;
38 // Do not try to tear down any PHP output buffers
39 const STREAM_ALLOW_OB = 2;
41 /**
42 * @param string $path Local filesystem path to a file
43 * @param array $params Options map, which includes:
44 * - obResetFunc : alternative callback to clear the output buffer
45 * - streamMimeFunc : alternative method to determine the content type from the path
47 public function __construct( $path, array $params = [] ) {
48 $this->path = $path;
49 $this->obResetFunc = isset( $params['obResetFunc'] )
50 ? $params['obResetFunc']
51 : [ __CLASS__, 'resetOutputBuffers' ];
52 $this->streamMimeFunc = isset( $params['streamMimeFunc'] )
53 ? $params['streamMimeFunc']
54 : [ __CLASS__, 'contentTypeFromPath' ];
57 /**
58 * Stream a file to the browser, adding all the headings and fun stuff.
59 * Headers sent include: Content-type, Content-Length, Last-Modified,
60 * and Content-Disposition.
62 * @param array $headers Any additional headers to send if the file exists
63 * @param bool $sendErrors Send error messages if errors occur (like 404)
64 * @param array $optHeaders HTTP request header map (e.g. "range") (use lowercase keys)
65 * @param integer $flags Bitfield of STREAM_* constants
66 * @throws MWException
67 * @return bool Success
69 public function stream(
70 $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
71 ) {
72 // Don't stream it out as text/html if there was a PHP error
73 if ( ( ( $flags & self::STREAM_HEADLESS ) == 0 || $headers ) && headers_sent() ) {
74 echo "Headers already sent, terminating.\n";
75 return false;
78 $headerFunc = ( $flags & self::STREAM_HEADLESS )
79 ? function ( $header ) {
80 // no-op
82 : function ( $header ) {
83 is_int( $header ) ? HttpStatus::header( $header ) : header( $header );
86 MediaWiki\suppressWarnings();
87 $info = stat( $this->path );
88 MediaWiki\restoreWarnings();
90 if ( !is_array( $info ) ) {
91 if ( $sendErrors ) {
92 self::send404Message( $this->path, $flags );
94 return false;
97 // Send Last-Modified HTTP header for client-side caching
98 $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
99 $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822 ) );
101 if ( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
102 call_user_func( $this->obResetFunc );
105 $type = call_user_func( $this->streamMimeFunc, $this->path );
106 if ( $type && $type != 'unknown/unknown' ) {
107 $headerFunc( "Content-type: $type" );
108 } else {
109 // Send a content type which is not known to Internet Explorer, to
110 // avoid triggering IE's content type detection. Sending a standard
111 // unknown content type here essentially gives IE license to apply
112 // whatever content type it likes.
113 $headerFunc( 'Content-type: application/x-wiki' );
116 // Don't send if client has up to date cache
117 if ( isset( $optHeaders['if-modified-since'] ) ) {
118 $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
119 if ( $mtimeCT->getTimestamp( TS_UNIX ) <= strtotime( $modsince ) ) {
120 ini_set( 'zlib.output_compression', 0 );
121 $headerFunc( 304 );
122 return true; // ok
126 // Send additional headers
127 foreach ( $headers as $header ) {
128 header( $header ); // always use header(); specifically requested
131 if ( isset( $optHeaders['range'] ) ) {
132 $range = self::parseRange( $optHeaders['range'], $info['size'] );
133 if ( is_array( $range ) ) {
134 $headerFunc( 206 );
135 $headerFunc( 'Content-Length: ' . $range[2] );
136 $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
137 } elseif ( $range === 'invalid' ) {
138 if ( $sendErrors ) {
139 $headerFunc( 416 );
140 $headerFunc( 'Cache-Control: no-cache' );
141 $headerFunc( 'Content-Type: text/html; charset=utf-8' );
142 $headerFunc( 'Content-Range: bytes */' . $info['size'] );
144 return false;
145 } else { // unsupported Range request (e.g. multiple ranges)
146 $range = null;
147 $headerFunc( 'Content-Length: ' . $info['size'] );
149 } else {
150 $range = null;
151 $headerFunc( 'Content-Length: ' . $info['size'] );
154 if ( is_array( $range ) ) {
155 $handle = fopen( $this->path, 'rb' );
156 if ( $handle ) {
157 $ok = true;
158 fseek( $handle, $range[0] );
159 $remaining = $range[2];
160 while ( $remaining > 0 && $ok ) {
161 $bytes = min( $remaining, 8 * 1024 );
162 $data = fread( $handle, $bytes );
163 $remaining -= $bytes;
164 $ok = ( $data !== false );
165 print $data;
167 } else {
168 return false;
170 } else {
171 return readfile( $this->path ) !== false; // faster
174 return true;
178 * Send out a standard 404 message for a file
180 * @param string $fname Full name and path of the file to stream
181 * @param integer $flags Bitfield of STREAM_* constants
182 * @since 1.24
184 public static function send404Message( $fname, $flags = 0 ) {
185 if ( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
186 HttpStatus::header( 404 );
187 header( 'Cache-Control: no-cache' );
188 header( 'Content-Type: text/html; charset=utf-8' );
190 $encFile = htmlspecialchars( $fname );
191 $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
192 echo "<!DOCTYPE html><html><body>
193 <h1>File not found</h1>
194 <p>Although this PHP script ($encScript) exists, the file requested for output
195 ($encFile) does not.</p>
196 </body></html>
201 * Convert a Range header value to an absolute (start, end) range tuple
203 * @param string $range Range header value
204 * @param integer $size File size
205 * @return array|string Returns error string on failure (start, end, length)
206 * @since 1.24
208 public static function parseRange( $range, $size ) {
209 $m = [];
210 if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
211 list( , $start, $end ) = $m;
212 if ( $start === '' && $end === '' ) {
213 $absRange = [ 0, $size - 1 ];
214 } elseif ( $start === '' ) {
215 $absRange = [ $size - $end, $size - 1 ];
216 } elseif ( $end === '' ) {
217 $absRange = [ $start, $size - 1 ];
218 } else {
219 $absRange = [ $start, $end ];
221 if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
222 if ( $absRange[0] < $size ) {
223 $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
224 $absRange[2] = $absRange[1] - $absRange[0] + 1;
225 return $absRange;
226 } elseif ( $absRange[0] == 0 && $size == 0 ) {
227 return 'unrecognized'; // the whole file should just be sent
230 return 'invalid';
232 return 'unrecognized';
235 protected static function resetOutputBuffers() {
236 while ( ob_get_status() ) {
237 if ( !ob_end_clean() ) {
238 // Could not remove output buffer handler; abort now
239 // to avoid getting in some kind of infinite loop.
240 break;
246 * Determine the file type of a file based on the path
248 * @param string $filename Storage path or file system path
249 * @return null|string
251 protected static function contentTypeFromPath( $filename ) {
252 $ext = strrchr( $filename, '.' );
253 $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
255 switch ( $ext ) {
256 case 'gif':
257 return 'image/gif';
258 case 'png':
259 return 'image/png';
260 case 'jpg':
261 return 'image/jpeg';
262 case 'jpeg':
263 return 'image/jpeg';
266 return 'unknown/unknown';