MediaWiki master
HTTPFileStreamer.php
Go to the documentation of this file.
1<?php
23namespace Wikimedia\FileBackend;
24
25use HttpStatus;
26use Wikimedia\AtEase\AtEase;
27use Wikimedia\Timestamp\ConvertibleTimestamp;
28
36 protected $path;
38 protected $obResetFunc;
40 protected $streamMimeFunc;
42 protected $headerFunc;
43
44 // Do not send any HTTP headers (i.e. body only)
45 public const STREAM_HEADLESS = 1;
46 // Do not try to tear down any PHP output buffers
47 public const STREAM_ALLOW_OB = 2;
48
56 public static function preprocessHeaders( $headers ) {
57 $rawHeaders = [];
58 $optHeaders = [];
59 foreach ( $headers as $name => $header ) {
60 $nameLower = strtolower( $name );
61 if ( in_array( $nameLower, [ 'range', 'if-modified-since' ], true ) ) {
62 $optHeaders[$nameLower] = $header;
63 } else {
64 $rawHeaders[] = "$name: $header";
65 }
66 }
67 return [ $rawHeaders, $optHeaders ];
68 }
69
77 public function __construct( $path, array $params = [] ) {
78 $this->path = $path;
79
80 $this->obResetFunc = $params['obResetFunc'] ??
81 [ __CLASS__, 'resetOutputBuffers' ];
82
83 $this->streamMimeFunc = $params['streamMimeFunc'] ??
84 [ __CLASS__, 'contentTypeFromPath' ];
85
86 $this->headerFunc = $params['headerFunc'] ?? 'header';
87 }
88
100 public function stream(
101 $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
102 ) {
103 $headless = ( $flags & self::STREAM_HEADLESS );
104
105 // Don't stream it out as text/html if there was a PHP error
106 if ( $headers && headers_sent() ) {
107 echo "Headers already sent, terminating.\n";
108 return false;
109 }
110
111 $headerFunc = $headless
112 ? static function ( $header ) {
113 // no-op
114 }
115 : [ $this, 'header' ];
116
117 AtEase::suppressWarnings();
118 $info = stat( $this->path );
119 AtEase::restoreWarnings();
120
121 if ( !is_array( $info ) ) {
122 if ( $sendErrors ) {
123 self::send404Message( $this->path, $flags );
124 }
125 return false;
126 }
127
128 // Send Last-Modified HTTP header for client-side caching
129 $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
130 $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822 ) );
131
132 if ( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
133 ( $this->obResetFunc )();
134 }
135
136 $type = ( $this->streamMimeFunc )( $this->path );
137 if ( $type && $type != 'unknown/unknown' ) {
138 $headerFunc( "Content-type: $type" );
139 } else {
140 // Send a content type which is not known to Internet Explorer, to
141 // avoid triggering IE's content type detection. Sending a standard
142 // unknown content type here essentially gives IE license to apply
143 // whatever content type it likes.
144 $headerFunc( 'Content-type: application/x-wiki' );
145 }
146
147 // Don't send if client has up to date cache
148 if ( isset( $optHeaders['if-modified-since'] ) ) {
149 $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
150 if ( $mtimeCT->getTimestamp( TS_UNIX ) <= strtotime( $modsince ) ) {
151 ini_set( 'zlib.output_compression', 0 );
152 $headerFunc( 304 );
153 return true; // ok
154 }
155 }
156
157 // Send additional headers
158 foreach ( $headers as $header ) {
160 }
161
162 if ( isset( $optHeaders['range'] ) ) {
163 $range = self::parseRange( $optHeaders['range'], $info['size'] );
164 if ( is_array( $range ) ) {
165 $headerFunc( 206 );
166 $headerFunc( 'Content-Length: ' . $range[2] );
167 $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
168 } elseif ( $range === 'invalid' ) {
169 if ( $sendErrors ) {
170 $headerFunc( 416 );
171 $headerFunc( 'Cache-Control: no-cache' );
172 $headerFunc( 'Content-Type: text/html; charset=utf-8' );
173 $headerFunc( 'Content-Range: bytes */' . $info['size'] );
174 }
175 return false;
176 } else { // unsupported Range request (e.g. multiple ranges)
177 $range = null;
178 $headerFunc( 'Content-Length: ' . $info['size'] );
179 }
180 } else {
181 $range = null;
182 $headerFunc( 'Content-Length: ' . $info['size'] );
183 }
184
185 if ( is_array( $range ) ) {
186 $handle = fopen( $this->path, 'rb' );
187 if ( $handle ) {
188 $ok = true;
189 fseek( $handle, $range[0] );
190 $remaining = $range[2];
191 while ( $remaining > 0 && $ok ) {
192 $bytes = min( $remaining, 8 * 1024 );
193 $data = fread( $handle, $bytes );
194 $remaining -= $bytes;
195 $ok = ( $data !== false );
196 print $data;
197 }
198 } else {
199 return false;
200 }
201 } else {
202 return readfile( $this->path ) !== false; // faster
203 }
204
205 return true;
206 }
207
215 public static function send404Message( $fname, $flags = 0 ) {
216 if ( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
217 HttpStatus::header( 404 );
218 header( 'Cache-Control: no-cache' );
219 header( 'Content-Type: text/html; charset=utf-8' );
220 }
221 $encFile = htmlspecialchars( $fname );
222 $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
223 echo "<!DOCTYPE html><html><body>
224 <h1>File not found</h1>
225 <p>Although this PHP script ($encScript) exists, the file requested for output
226 ($encFile) does not.</p>
227 </body></html>
228 ";
229 }
230
239 public static function parseRange( $range, $size ) {
240 $m = [];
241 if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
242 [ , $start, $end ] = $m;
243 if ( $start === '' && $end === '' ) {
244 $absRange = [ 0, $size - 1 ];
245 } elseif ( $start === '' ) {
246 $absRange = [ $size - (int)$end, $size - 1 ];
247 } elseif ( $end === '' ) {
248 $absRange = [ (int)$start, $size - 1 ];
249 } else {
250 $absRange = [ (int)$start, (int)$end ];
251 }
252 if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
253 if ( $absRange[0] < $size ) {
254 $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
255 $absRange[2] = $absRange[1] - $absRange[0] + 1;
256 return $absRange;
257 } elseif ( $absRange[0] == 0 && $size == 0 ) {
258 return 'unrecognized'; // the whole file should just be sent
259 }
260 }
261 return 'invalid';
262 }
263 return 'unrecognized';
264 }
265
266 protected static function resetOutputBuffers() {
267 while ( ob_get_status() ) {
268 if ( !ob_end_clean() ) {
269 // Could not remove output buffer handler; abort now
270 // to avoid getting in some kind of infinite loop.
271 break;
272 }
273 }
274 }
275
282 protected static function contentTypeFromPath( $filename ) {
283 $ext = strrchr( $filename, '.' );
284 $ext = $ext ? strtolower( substr( $ext, 1 ) ) : '';
285
286 switch ( $ext ) {
287 case 'gif':
288 return 'image/gif';
289 case 'png':
290 return 'image/png';
291 case 'jpg':
292 case 'jpeg':
293 return 'image/jpeg';
294 // T366422: Support webp here as well for consistency
295 case 'webp':
296 return 'image/webp';
297 }
298
299 return 'unknown/unknown';
300 }
301
302 private function header( $header ) {
303 if ( is_int( $header ) ) {
304 $header = HttpStatus::getHeader( $header );
305 }
306
308 }
309}
310
312class_alias( HTTPFileStreamer::class, 'HTTPFileStreamer' );
array $params
The job parameters.
Functions related to the output of file content.
stream( $headers=[], $sendErrors=true, $optHeaders=[], $flags=0)
Stream a file to the browser, adding all the headings and fun stuff.
static preprocessHeaders( $headers)
Takes HTTP headers in a name => value format and converts them to the weird format expected by stream...
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
static contentTypeFromPath( $filename)
Determine the file type of a file based on the path.
static parseRange( $range, $size)
Convert a Range header value to an absolute (start, end) range tuple.
$header