MediaWiki  master
HTTPFileStreamer.php
Go to the documentation of this file.
1 <?php
23 use Wikimedia\AtEase\AtEase;
24 use Wikimedia\Timestamp\ConvertibleTimestamp;
25 
33  protected $path;
35  protected $obResetFunc;
37  protected $streamMimeFunc;
38 
39  // Do not send any HTTP headers unless requested by caller (e.g. body only)
40  public const STREAM_HEADLESS = 1;
41  // Do not try to tear down any PHP output buffers
42  public const STREAM_ALLOW_OB = 2;
43 
51  public static function preprocessHeaders( $headers ) {
52  $rawHeaders = [];
53  $optHeaders = [];
54  foreach ( $headers as $name => $header ) {
55  $nameLower = strtolower( $name );
56  if ( in_array( $nameLower, [ 'range', 'if-modified-since' ], true ) ) {
57  $optHeaders[$nameLower] = $header;
58  } else {
59  $rawHeaders[] = "$name: $header";
60  }
61  }
62  return [ $rawHeaders, $optHeaders ];
63  }
64 
71  public function __construct( $path, array $params = [] ) {
72  $this->path = $path;
73  $this->obResetFunc = $params['obResetFunc'] ?? [ __CLASS__, 'resetOutputBuffers' ];
74  $this->streamMimeFunc = $params['streamMimeFunc'] ?? [ __CLASS__, 'contentTypeFromPath' ];
75  }
76 
88  public function stream(
89  $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
90  ) {
91  // Don't stream it out as text/html if there was a PHP error
92  if ( ( ( $flags & self::STREAM_HEADLESS ) == 0 || $headers ) && headers_sent() ) {
93  echo "Headers already sent, terminating.\n";
94  return false;
95  }
96 
97  $headerFunc = ( $flags & self::STREAM_HEADLESS )
98  ? static function ( $header ) {
99  // no-op
100  }
101  : static function ( $header ) {
102  is_int( $header ) ? HttpStatus::header( $header ) : header( $header );
103  };
104 
105  AtEase::suppressWarnings();
106  $info = stat( $this->path );
107  AtEase::restoreWarnings();
108 
109  if ( !is_array( $info ) ) {
110  if ( $sendErrors ) {
111  self::send404Message( $this->path, $flags );
112  }
113  return false;
114  }
115 
116  // Send Last-Modified HTTP header for client-side caching
117  $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
118  $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822 ) );
119 
120  if ( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
121  call_user_func( $this->obResetFunc );
122  }
123 
124  $type = call_user_func( $this->streamMimeFunc, $this->path );
125  if ( $type && $type != 'unknown/unknown' ) {
126  $headerFunc( "Content-type: $type" );
127  } else {
128  // Send a content type which is not known to Internet Explorer, to
129  // avoid triggering IE's content type detection. Sending a standard
130  // unknown content type here essentially gives IE license to apply
131  // whatever content type it likes.
132  $headerFunc( 'Content-type: application/x-wiki' );
133  }
134 
135  // Don't send if client has up to date cache
136  if ( isset( $optHeaders['if-modified-since'] ) ) {
137  $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
138  if ( $mtimeCT->getTimestamp( TS_UNIX ) <= strtotime( $modsince ) ) {
139  // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
140  ini_set( 'zlib.output_compression', 0 );
141  $headerFunc( 304 );
142  return true; // ok
143  }
144  }
145 
146  // Send additional headers
147  foreach ( $headers as $header ) {
148  header( $header ); // always use header(); specifically requested
149  }
150 
151  if ( isset( $optHeaders['range'] ) ) {
152  $range = self::parseRange( $optHeaders['range'], $info['size'] );
153  if ( is_array( $range ) ) {
154  $headerFunc( 206 );
155  $headerFunc( 'Content-Length: ' . $range[2] );
156  $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
157  } elseif ( $range === 'invalid' ) {
158  if ( $sendErrors ) {
159  $headerFunc( 416 );
160  $headerFunc( 'Cache-Control: no-cache' );
161  $headerFunc( 'Content-Type: text/html; charset=utf-8' );
162  $headerFunc( 'Content-Range: bytes */' . $info['size'] );
163  }
164  return false;
165  } else { // unsupported Range request (e.g. multiple ranges)
166  $range = null;
167  $headerFunc( 'Content-Length: ' . $info['size'] );
168  }
169  } else {
170  $range = null;
171  $headerFunc( 'Content-Length: ' . $info['size'] );
172  }
173 
174  if ( is_array( $range ) ) {
175  $handle = fopen( $this->path, 'rb' );
176  if ( $handle ) {
177  $ok = true;
178  fseek( $handle, $range[0] );
179  $remaining = $range[2];
180  while ( $remaining > 0 && $ok ) {
181  $bytes = min( $remaining, 8 * 1024 );
182  $data = fread( $handle, $bytes );
183  $remaining -= $bytes;
184  $ok = ( $data !== false );
185  print $data;
186  }
187  } else {
188  return false;
189  }
190  } else {
191  return readfile( $this->path ) !== false; // faster
192  }
193 
194  return true;
195  }
196 
204  public static function send404Message( $fname, $flags = 0 ) {
205  if ( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
206  HttpStatus::header( 404 );
207  header( 'Cache-Control: no-cache' );
208  header( 'Content-Type: text/html; charset=utf-8' );
209  }
210  $encFile = htmlspecialchars( $fname );
211  $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
212  echo "<!DOCTYPE html><html><body>
213  <h1>File not found</h1>
214  <p>Although this PHP script ($encScript) exists, the file requested for output
215  ($encFile) does not.</p>
216  </body></html>
217  ";
218  }
219 
228  public static function parseRange( $range, $size ) {
229  $m = [];
230  if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
231  list( , $start, $end ) = $m;
232  if ( $start === '' && $end === '' ) {
233  $absRange = [ 0, $size - 1 ];
234  } elseif ( $start === '' ) {
235  $absRange = [ $size - (int)$end, $size - 1 ];
236  } elseif ( $end === '' ) {
237  $absRange = [ (int)$start, $size - 1 ];
238  } else {
239  $absRange = [ (int)$start, (int)$end ];
240  }
241  if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
242  if ( $absRange[0] < $size ) {
243  $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
244  $absRange[2] = $absRange[1] - $absRange[0] + 1;
245  return $absRange;
246  } elseif ( $absRange[0] == 0 && $size == 0 ) {
247  return 'unrecognized'; // the whole file should just be sent
248  }
249  }
250  return 'invalid';
251  }
252  return 'unrecognized';
253  }
254 
255  protected static function resetOutputBuffers() {
256  while ( ob_get_status() ) {
257  if ( !ob_end_clean() ) {
258  // Could not remove output buffer handler; abort now
259  // to avoid getting in some kind of infinite loop.
260  break;
261  }
262  }
263  }
264 
271  protected static function contentTypeFromPath( $filename ) {
272  $ext = strrchr( $filename, '.' );
273  $ext = $ext ? strtolower( substr( $ext, 1 ) ) : '';
274 
275  switch ( $ext ) {
276  case 'gif':
277  return 'image/gif';
278  case 'png':
279  return 'image/png';
280  case 'jpg':
281  return 'image/jpeg';
282  case 'jpeg':
283  return 'image/jpeg';
284  }
285 
286  return 'unknown/unknown';
287  }
288 }
Functions related to the output of file content.
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.
__construct( $path, array $params=[])
stream( $headers=[], $sendErrors=true, $optHeaders=[], $flags=0)
Stream a file to the browser, adding all the headings and fun stuff.
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
if(!is_readable( $file)) $ext
Definition: router.php:48
$header