MediaWiki  1.33.1
HTTPFileStreamer.php
Go to the documentation of this file.
1 <?php
22 use Wikimedia\Timestamp\ConvertibleTimestamp;
23 
31  protected $path;
33  protected $obResetFunc;
35  protected $streamMimeFunc;
36 
37  // Do not send any HTTP headers unless requested by caller (e.g. body only)
38  const STREAM_HEADLESS = 1;
39  // Do not try to tear down any PHP output buffers
40  const STREAM_ALLOW_OB = 2;
41 
49  public static function preprocessHeaders( $headers ) {
50  $rawHeaders = [];
51  $optHeaders = [];
52  foreach ( $headers as $name => $header ) {
53  $nameLower = strtolower( $name );
54  if ( in_array( $nameLower, [ 'range', 'if-modified-since' ], true ) ) {
55  $optHeaders[$nameLower] = $header;
56  } else {
57  $rawHeaders[] = "$name: $header";
58  }
59  }
60  return [ $rawHeaders, $optHeaders ];
61  }
62 
69  public function __construct( $path, array $params = [] ) {
70  $this->path = $path;
71  $this->obResetFunc = $params['obResetFunc'] ?? [ __CLASS__, 'resetOutputBuffers' ];
72  $this->streamMimeFunc = $params['streamMimeFunc'] ?? [ __CLASS__, 'contentTypeFromPath' ];
73  }
74 
86  public function stream(
87  $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
88  ) {
89  // Don't stream it out as text/html if there was a PHP error
90  if ( ( ( $flags & self::STREAM_HEADLESS ) == 0 || $headers ) && headers_sent() ) {
91  echo "Headers already sent, terminating.\n";
92  return false;
93  }
94 
95  $headerFunc = ( $flags & self::STREAM_HEADLESS )
96  ? function ( $header ) {
97  // no-op
98  }
99  : function ( $header ) {
100  is_int( $header ) ? HttpStatus::header( $header ) : header( $header );
101  };
102 
103  Wikimedia\suppressWarnings();
104  $info = stat( $this->path );
105  Wikimedia\restoreWarnings();
106 
107  if ( !is_array( $info ) ) {
108  if ( $sendErrors ) {
109  self::send404Message( $this->path, $flags );
110  }
111  return false;
112  }
113 
114  // Send Last-Modified HTTP header for client-side caching
115  $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
116  $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822 ) );
117 
118  if ( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
119  call_user_func( $this->obResetFunc );
120  }
121 
122  $type = call_user_func( $this->streamMimeFunc, $this->path );
123  if ( $type && $type != 'unknown/unknown' ) {
124  $headerFunc( "Content-type: $type" );
125  } else {
126  // Send a content type which is not known to Internet Explorer, to
127  // avoid triggering IE's content type detection. Sending a standard
128  // unknown content type here essentially gives IE license to apply
129  // whatever content type it likes.
130  $headerFunc( 'Content-type: application/x-wiki' );
131  }
132 
133  // Don't send if client has up to date cache
134  if ( isset( $optHeaders['if-modified-since'] ) ) {
135  $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
136  if ( $mtimeCT->getTimestamp( TS_UNIX ) <= strtotime( $modsince ) ) {
137  ini_set( 'zlib.output_compression', 0 );
138  $headerFunc( 304 );
139  return true; // ok
140  }
141  }
142 
143  // Send additional headers
144  foreach ( $headers as $header ) {
145  header( $header ); // always use header(); specifically requested
146  }
147 
148  if ( isset( $optHeaders['range'] ) ) {
149  $range = self::parseRange( $optHeaders['range'], $info['size'] );
150  if ( is_array( $range ) ) {
151  $headerFunc( 206 );
152  $headerFunc( 'Content-Length: ' . $range[2] );
153  $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
154  } elseif ( $range === 'invalid' ) {
155  if ( $sendErrors ) {
156  $headerFunc( 416 );
157  $headerFunc( 'Cache-Control: no-cache' );
158  $headerFunc( 'Content-Type: text/html; charset=utf-8' );
159  $headerFunc( 'Content-Range: bytes */' . $info['size'] );
160  }
161  return false;
162  } else { // unsupported Range request (e.g. multiple ranges)
163  $range = null;
164  $headerFunc( 'Content-Length: ' . $info['size'] );
165  }
166  } else {
167  $range = null;
168  $headerFunc( 'Content-Length: ' . $info['size'] );
169  }
170 
171  if ( is_array( $range ) ) {
172  $handle = fopen( $this->path, 'rb' );
173  if ( $handle ) {
174  $ok = true;
175  fseek( $handle, $range[0] );
176  $remaining = $range[2];
177  while ( $remaining > 0 && $ok ) {
178  $bytes = min( $remaining, 8 * 1024 );
179  $data = fread( $handle, $bytes );
180  $remaining -= $bytes;
181  $ok = ( $data !== false );
182  print $data;
183  }
184  } else {
185  return false;
186  }
187  } else {
188  return readfile( $this->path ) !== false; // faster
189  }
190 
191  return true;
192  }
193 
201  public static function send404Message( $fname, $flags = 0 ) {
202  if ( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
203  HttpStatus::header( 404 );
204  header( 'Cache-Control: no-cache' );
205  header( 'Content-Type: text/html; charset=utf-8' );
206  }
207  $encFile = htmlspecialchars( $fname );
208  $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
209  echo "<!DOCTYPE html><html><body>
210  <h1>File not found</h1>
211  <p>Although this PHP script ($encScript) exists, the file requested for output
212  ($encFile) does not.</p>
213  </body></html>
214  ";
215  }
216 
225  public static function parseRange( $range, $size ) {
226  $m = [];
227  if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
228  list( , $start, $end ) = $m;
229  if ( $start === '' && $end === '' ) {
230  $absRange = [ 0, $size - 1 ];
231  } elseif ( $start === '' ) {
232  $absRange = [ $size - $end, $size - 1 ];
233  } elseif ( $end === '' ) {
234  $absRange = [ $start, $size - 1 ];
235  } else {
236  $absRange = [ $start, $end ];
237  }
238  if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
239  if ( $absRange[0] < $size ) {
240  $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
241  $absRange[2] = $absRange[1] - $absRange[0] + 1;
242  return $absRange;
243  } elseif ( $absRange[0] == 0 && $size == 0 ) {
244  return 'unrecognized'; // the whole file should just be sent
245  }
246  }
247  return 'invalid';
248  }
249  return 'unrecognized';
250  }
251 
252  protected static function resetOutputBuffers() {
253  while ( ob_get_status() ) {
254  if ( !ob_end_clean() ) {
255  // Could not remove output buffer handler; abort now
256  // to avoid getting in some kind of infinite loop.
257  break;
258  }
259  }
260  }
261 
268  protected static function contentTypeFromPath( $filename ) {
269  $ext = strrchr( $filename, '.' );
270  $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
271 
272  switch ( $ext ) {
273  case 'gif':
274  return 'image/gif';
275  case 'png':
276  return 'image/png';
277  case 'jpg':
278  return 'image/jpeg';
279  case 'jpeg':
280  return 'image/jpeg';
281  }
282 
283  return 'unknown/unknown';
284  }
285 }
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
HTTPFileStreamer\$path
string $path
Definition: HTTPFileStreamer.php:31
$params
$params
Definition: styleTest.css.php:44
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
HTTPFileStreamer
Functions related to the output of file content.
Definition: HTTPFileStreamer.php:29
HTTPFileStreamer\preprocessHeaders
static preprocessHeaders( $headers)
Takes HTTP headers in a name => value format and converts them to the weird format expected by stream...
Definition: HTTPFileStreamer.php:49
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
HTTPFileStreamer\resetOutputBuffers
static resetOutputBuffers()
Definition: HTTPFileStreamer.php:252
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
HTTPFileStreamer\parseRange
static parseRange( $range, $size)
Convert a Range header value to an absolute (start, end) range tuple.
Definition: HTTPFileStreamer.php:225
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
HTTPFileStreamer\STREAM_ALLOW_OB
const STREAM_ALLOW_OB
Definition: HTTPFileStreamer.php:40
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:123
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
HTTPFileStreamer\$streamMimeFunc
callable $streamMimeFunc
Definition: HTTPFileStreamer.php:35
$header
$header
Definition: updateCredits.php:41
HTTPFileStreamer\STREAM_HEADLESS
const STREAM_HEADLESS
Definition: HTTPFileStreamer.php:38
HTTPFileStreamer\send404Message
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Definition: HTTPFileStreamer.php:201
HTTPFileStreamer\__construct
__construct( $path, array $params=[])
Definition: HTTPFileStreamer.php:69
HTTPFileStreamer\contentTypeFromPath
static contentTypeFromPath( $filename)
Determine the file type of a file based on the path.
Definition: HTTPFileStreamer.php:268
HttpStatus\header
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
HTTPFileStreamer\stream
stream( $headers=[], $sendErrors=true, $optHeaders=[], $flags=0)
Stream a file to the browser, adding all the headings and fun stuff.
Definition: HTTPFileStreamer.php:86
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
HTTPFileStreamer\$obResetFunc
callable $obResetFunc
Definition: HTTPFileStreamer.php:33
$type
$type
Definition: testCompression.php:48