MediaWiki  1.27.1
StreamFile.php
Go to the documentation of this file.
1 <?php
26 class StreamFile {
27  const READY_STREAM = 1;
28  const NOT_MODIFIED = 2;
29 
41  public static function stream( $fname, $headers = [], $sendErrors = true ) {
42 
43  if ( FileBackend::isStoragePath( $fname ) ) { // sanity
44  throw new MWException( __FUNCTION__ . " given storage path '$fname'." );
45  }
46 
47  MediaWiki\suppressWarnings();
48  $stat = stat( $fname );
49  MediaWiki\restoreWarnings();
50 
51  $res = self::prepareForStream( $fname, $stat, $headers, $sendErrors );
52  if ( $res == self::NOT_MODIFIED ) {
53  $ok = true; // use client cache
54  } elseif ( $res == self::READY_STREAM ) {
55  $ok = readfile( $fname );
56  } else {
57  $ok = false; // failed
58  }
59 
60  return $ok;
61  }
62 
76  public static function prepareForStream(
77  $path, $info, $headers = [], $sendErrors = true
78  ) {
79  if ( !is_array( $info ) ) {
80  if ( $sendErrors ) {
81  HttpStatus::header( 404 );
82  header( 'Cache-Control: no-cache' );
83  header( 'Content-Type: text/html; charset=utf-8' );
84  $encFile = htmlspecialchars( $path );
85  $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
86  echo "<html><body>
87  <h1>File not found</h1>
88  <p>Although this PHP script ($encScript) exists, the file requested for output
89  ($encFile) does not.</p>
90  </body></html>
91  ";
92  }
93  return false;
94  }
95 
96  // Sent Last-Modified HTTP header for client-side caching
97  header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $info['mtime'] ) );
98 
99  // Cancel output buffering and gzipping if set
101 
102  $type = self::contentTypeFromPath( $path );
103  if ( $type && $type != 'unknown/unknown' ) {
104  header( "Content-type: $type" );
105  } else {
106  // Send a content type which is not known to Internet Explorer, to
107  // avoid triggering IE's content type detection. Sending a standard
108  // unknown content type here essentially gives IE license to apply
109  // whatever content type it likes.
110  header( 'Content-type: application/x-wiki' );
111  }
112 
113  // Don't stream it out as text/html if there was a PHP error
114  if ( headers_sent() ) {
115  echo "Headers already sent, terminating.\n";
116  return false;
117  }
118 
119  // Send additional headers
120  foreach ( $headers as $header ) {
121  header( $header );
122  }
123 
124  // Don't send if client has up to date cache
125  if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
126  $modsince = preg_replace( '/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
127  if ( wfTimestamp( TS_UNIX, $info['mtime'] ) <= strtotime( $modsince ) ) {
128  ini_set( 'zlib.output_compression', 0 );
129  HttpStatus::header( 304 );
130  return self::NOT_MODIFIED; // ok
131  }
132  }
133 
134  header( 'Content-Length: ' . $info['size'] );
135 
136  return self::READY_STREAM; // ok
137  }
138 
146  public static function contentTypeFromPath( $filename, $safe = true ) {
148 
149  $ext = strrchr( $filename, '.' );
150  $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
151 
152  # trivial detection by file extension,
153  # used for thumbnails (thumb.php)
154  if ( $wgTrivialMimeDetection ) {
155  switch ( $ext ) {
156  case 'gif':
157  return 'image/gif';
158  case 'png':
159  return 'image/png';
160  case 'jpg':
161  return 'image/jpeg';
162  case 'jpeg':
163  return 'image/jpeg';
164  }
165 
166  return 'unknown/unknown';
167  }
168 
169  $magic = MimeMagic::singleton();
170  // Use the extension only, rather than magic numbers, to avoid opening
171  // up vulnerabilities due to uploads of files with allowed extensions
172  // but disallowed types.
173  $type = $magic->guessTypesForExtension( $ext );
174 
179  if ( $safe ) {
182  list( , $extList ) = UploadBase::splitExtensions( $filename );
183  if ( UploadBase::checkFileExtensionList( $extList, $wgFileBlacklist ) ) {
184  return 'unknown/unknown';
185  }
186  if ( $wgCheckFileExtensions && $wgStrictFileExtensions
187  && !UploadBase::checkFileExtensionList( $extList, $wgFileExtensions )
188  ) {
189  return 'unknown/unknown';
190  }
191  if ( $wgVerifyMimeType && in_array( strtolower( $type ), $wgMimeTypeBlacklist ) ) {
192  return 'unknown/unknown';
193  }
194  }
195  return $type;
196  }
197 }
$wgStrictFileExtensions
If this is turned off, users may override the warning for files not covered by $wgFileExtensions.
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
static checkFileExtensionList($ext, $list)
Perform case-insensitive match against a list of file extensions.
Functions related to the output of file content.
Definition: StreamFile.php:26
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
static singleton()
Get an instance of this class.
Definition: MimeMagic.php:366
static header($code)
Output an HTTP status code header.
Definition: HttpStatus.php:96
const READY_STREAM
Definition: StreamFile.php:27
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
$wgCheckFileExtensions
This is a flag to determine whether or not to check file extensions on upload.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static prepareForStream($path, $info, $headers=[], $sendErrors=true)
Call this function used in preparation before streaming a file.
Definition: StreamFile.php:76
wfResetOutputBuffers($resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
$res
Definition: database.txt:21
static isStoragePath($path)
Check if a given path is a "mwstore://" path.
static splitExtensions($filename)
Split a file into a base name and all dot-delimited 'extensions' on the end.
Definition: UploadBase.php:993
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
$wgFileExtensions
This is the list of preferred extensions for uploading files.
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, $safe=true)
Determine the file type of a file based on the path.
Definition: StreamFile.php:146
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:35
$wgTrivialMimeDetection
Switch for trivial MIME detection.
const NOT_MODIFIED
Definition: StreamFile.php:28
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
$wgMimeTypeBlacklist
Files with these MIME types will never be allowed as uploads if $wgVerifyMimeType is enabled...
static stream($fname, $headers=[], $sendErrors=true)
Stream a file to the browser, adding all the headings and fun stuff.
Definition: StreamFile.php:41
$wgVerifyMimeType
Determines if the MIME type of uploaded files should be checked.
$wgFileBlacklist
Files with these extensions will never be allowed as uploads.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338