MediaWiki  master
HTTPFileStreamer.php
Go to the documentation of this file.
1 <?php
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 
48  public function __construct( $path, array $params = [] ) {
49  $this->path = $path;
50  $this->obResetFunc = $params['obResetFunc'] ?? [ __CLASS__, 'resetOutputBuffers' ];
51  $this->streamMimeFunc = $params['streamMimeFunc'] ?? [ __CLASS__, 'contentTypeFromPath' ];
52  }
53 
65  public function stream(
66  $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
67  ) {
68  // Don't stream it out as text/html if there was a PHP error
69  if ( ( ( $flags & self::STREAM_HEADLESS ) == 0 || $headers ) && headers_sent() ) {
70  echo "Headers already sent, terminating.\n";
71  return false;
72  }
73 
74  $headerFunc = ( $flags & self::STREAM_HEADLESS )
75  ? function ( $header ) {
76  // no-op
77  }
78  : function ( $header ) {
79  is_int( $header ) ? HttpStatus::header( $header ) : header( $header );
80  };
81 
82  Wikimedia\suppressWarnings();
83  $info = stat( $this->path );
84  Wikimedia\restoreWarnings();
85 
86  if ( !is_array( $info ) ) {
87  if ( $sendErrors ) {
88  self::send404Message( $this->path, $flags );
89  }
90  return false;
91  }
92 
93  // Send Last-Modified HTTP header for client-side caching
94  $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
95  $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822 ) );
96 
97  if ( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
98  call_user_func( $this->obResetFunc );
99  }
100 
101  $type = call_user_func( $this->streamMimeFunc, $this->path );
102  if ( $type && $type != 'unknown/unknown' ) {
103  $headerFunc( "Content-type: $type" );
104  } else {
105  // Send a content type which is not known to Internet Explorer, to
106  // avoid triggering IE's content type detection. Sending a standard
107  // unknown content type here essentially gives IE license to apply
108  // whatever content type it likes.
109  $headerFunc( 'Content-type: application/x-wiki' );
110  }
111 
112  // Don't send if client has up to date cache
113  if ( isset( $optHeaders['if-modified-since'] ) ) {
114  $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
115  if ( $mtimeCT->getTimestamp( TS_UNIX ) <= strtotime( $modsince ) ) {
116  ini_set( 'zlib.output_compression', 0 );
117  $headerFunc( 304 );
118  return true; // ok
119  }
120  }
121 
122  // Send additional headers
123  foreach ( $headers as $header ) {
124  header( $header ); // always use header(); specifically requested
125  }
126 
127  if ( isset( $optHeaders['range'] ) ) {
128  $range = self::parseRange( $optHeaders['range'], $info['size'] );
129  if ( is_array( $range ) ) {
130  $headerFunc( 206 );
131  $headerFunc( 'Content-Length: ' . $range[2] );
132  $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
133  } elseif ( $range === 'invalid' ) {
134  if ( $sendErrors ) {
135  $headerFunc( 416 );
136  $headerFunc( 'Cache-Control: no-cache' );
137  $headerFunc( 'Content-Type: text/html; charset=utf-8' );
138  $headerFunc( 'Content-Range: bytes */' . $info['size'] );
139  }
140  return false;
141  } else { // unsupported Range request (e.g. multiple ranges)
142  $range = null;
143  $headerFunc( 'Content-Length: ' . $info['size'] );
144  }
145  } else {
146  $range = null;
147  $headerFunc( 'Content-Length: ' . $info['size'] );
148  }
149 
150  if ( is_array( $range ) ) {
151  $handle = fopen( $this->path, 'rb' );
152  if ( $handle ) {
153  $ok = true;
154  fseek( $handle, $range[0] );
155  $remaining = $range[2];
156  while ( $remaining > 0 && $ok ) {
157  $bytes = min( $remaining, 8 * 1024 );
158  $data = fread( $handle, $bytes );
159  $remaining -= $bytes;
160  $ok = ( $data !== false );
161  print $data;
162  }
163  } else {
164  return false;
165  }
166  } else {
167  return readfile( $this->path ) !== false; // faster
168  }
169 
170  return true;
171  }
172 
180  public static function send404Message( $fname, $flags = 0 ) {
181  if ( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
182  HttpStatus::header( 404 );
183  header( 'Cache-Control: no-cache' );
184  header( 'Content-Type: text/html; charset=utf-8' );
185  }
186  $encFile = htmlspecialchars( $fname );
187  $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
188  echo "<!DOCTYPE html><html><body>
189  <h1>File not found</h1>
190  <p>Although this PHP script ($encScript) exists, the file requested for output
191  ($encFile) does not.</p>
192  </body></html>
193  ";
194  }
195 
204  public static function parseRange( $range, $size ) {
205  $m = [];
206  if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
207  list( , $start, $end ) = $m;
208  if ( $start === '' && $end === '' ) {
209  $absRange = [ 0, $size - 1 ];
210  } elseif ( $start === '' ) {
211  $absRange = [ $size - $end, $size - 1 ];
212  } elseif ( $end === '' ) {
213  $absRange = [ $start, $size - 1 ];
214  } else {
215  $absRange = [ $start, $end ];
216  }
217  if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
218  if ( $absRange[0] < $size ) {
219  $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
220  $absRange[2] = $absRange[1] - $absRange[0] + 1;
221  return $absRange;
222  } elseif ( $absRange[0] == 0 && $size == 0 ) {
223  return 'unrecognized'; // the whole file should just be sent
224  }
225  }
226  return 'invalid';
227  }
228  return 'unrecognized';
229  }
230 
231  protected static function resetOutputBuffers() {
232  while ( ob_get_status() ) {
233  if ( !ob_end_clean() ) {
234  // Could not remove output buffer handler; abort now
235  // to avoid getting in some kind of infinite loop.
236  break;
237  }
238  }
239  }
240 
247  protected static function contentTypeFromPath( $filename ) {
248  $ext = strrchr( $filename, '.' );
249  $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
250 
251  switch ( $ext ) {
252  case 'gif':
253  return 'image/gif';
254  case 'png':
255  return 'image/png';
256  case 'jpg':
257  return 'image/jpeg';
258  case 'jpeg':
259  return 'image/jpeg';
260  }
261 
262  return 'unknown/unknown';
263  }
264 }
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))
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
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static parseRange( $range, $size)
Convert a Range header value to an absolute (start, end) range tuple.
Functions related to the output of file content.
static header( $code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
$params
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
$header
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
__construct( $path, array $params=[])
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:121
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
static contentTypeFromPath( $filename)
Determine the file type of a file based on the path.
$ext
Definition: router.php:55
stream( $headers=[], $sendErrors=true, $optHeaders=[], $flags=0)
Stream a file to the browser, adding all the headings and fun stuff.