Merge "Remove not used private member variable mParserWarnings from OutputPage"
[mediawiki.git] / includes / StreamFile.php
blob3f73ae3ccd459eb399138e8788bb70daac692c48
1 <?php
2 /**
3 * Functions related to the output of file content.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Functions related to the output of file content
26 class StreamFile {
27 const READY_STREAM = 1;
28 const NOT_MODIFIED = 2;
30 /**
31 * Stream a file to the browser, adding all the headings and fun stuff.
32 * Headers sent include: Content-type, Content-Length, Last-Modified,
33 * and Content-Disposition.
35 * @param string $fname Full name and path of the file to stream
36 * @param array $headers Any additional headers to send
37 * @param bool $sendErrors Send error messages if errors occur (like 404)
38 * @throws MWException
39 * @return bool Success
41 public static function stream( $fname, $headers = array(), $sendErrors = true ) {
43 if ( FileBackend::isStoragePath( $fname ) ) { // sanity
44 throw new MWException( __FUNCTION__ . " given storage path '$fname'." );
47 MediaWiki\suppressWarnings();
48 $stat = stat( $fname );
49 MediaWiki\restoreWarnings();
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
60 return $ok;
63 /**
64 * Call this function used in preparation before streaming a file.
65 * This function does the following:
66 * (a) sends Last-Modified, Content-type, and Content-Disposition headers
67 * (b) cancels any PHP output buffering and automatic gzipping of output
68 * (c) sends Content-Length header based on HTTP_IF_MODIFIED_SINCE check
70 * @param string $path Storage path or file system path
71 * @param array|bool $info File stat info with 'mtime' and 'size' fields
72 * @param array $headers Additional headers to send
73 * @param bool $sendErrors Send error messages if errors occur (like 404)
74 * @return int|bool READY_STREAM, NOT_MODIFIED, or false on failure
76 public static function prepareForStream(
77 $path, $info, $headers = array(), $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>
93 return false;
96 // Sent Last-Modified HTTP header for client-side caching
97 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $info['mtime'] ) );
99 // Cancel output buffering and gzipping if set
100 wfResetOutputBuffers();
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' );
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;
119 // Send additional headers
120 foreach ( $headers as $header ) {
121 header( $header );
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
134 header( 'Content-Length: ' . $info['size'] );
136 return self::READY_STREAM; // ok
140 * Determine the file type of a file based on the path
142 * @param string $filename Storage path or file system path
143 * @param bool $safe Whether to do retroactive upload blacklist checks
144 * @return null|string
146 public static function contentTypeFromPath( $filename, $safe = true ) {
147 global $wgTrivialMimeDetection;
149 $ext = strrchr( $filename, '.' );
150 $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
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';
166 return 'unknown/unknown';
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 );
176 * Double-check some security settings that were done on upload but might
177 * have changed since.
179 if ( $safe ) {
180 global $wgFileBlacklist, $wgCheckFileExtensions, $wgStrictFileExtensions,
181 $wgFileExtensions, $wgVerifyMimeType, $wgMimeTypeBlacklist;
182 list( , $extList ) = UploadBase::splitExtensions( $filename );
183 if ( UploadBase::checkFileExtensionList( $extList, $wgFileBlacklist ) ) {
184 return 'unknown/unknown';
186 if ( $wgCheckFileExtensions && $wgStrictFileExtensions
187 && !UploadBase::checkFileExtensionList( $extList, $wgFileExtensions )
189 return 'unknown/unknown';
191 if ( $wgVerifyMimeType && in_array( strtolower( $type ), $wgMimeTypeBlacklist ) ) {
192 return 'unknown/unknown';
195 return $type;