Pass objects to methods accepting them instead of relying on global objects.
[lhc/web/wiklou.git] / includes / StreamFile.php
1 <?php
2 /**
3 * Functions related to the output of file content.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * Functions related to the output of file content
25 */
26 class StreamFile {
27 const READY_STREAM = 1;
28 const NOT_MODIFIED = 2;
29
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.
34 *
35 * @param $fname string Full name and path of the file to stream
36 * @param $headers array Any additional headers to send
37 * @param $sendErrors bool Send error messages if errors occur (like 404)
38 * @return bool Success
39 */
40 public static function stream( $fname, $headers = array(), $sendErrors = true ) {
41 wfProfileIn( __METHOD__ );
42
43 wfSuppressWarnings();
44 $stat = stat( $fname );
45 wfRestoreWarnings();
46
47 $res = self::prepareForStream( $fname, $stat, $headers, $sendErrors );
48 if ( $res == self::NOT_MODIFIED ) {
49 $ok = true; // use client cache
50 } elseif ( $res == self::READY_STREAM ) {
51 wfProfileIn( __METHOD__ . '-send' );
52 $ok = readfile( $fname );
53 wfProfileOut( __METHOD__ . '-send' );
54 } else {
55 $ok = false; // failed
56 }
57
58 wfProfileOut( __METHOD__ );
59 return $ok;
60 }
61
62 /**
63 * Call this function used in preparation before streaming a file.
64 * This function does the following:
65 * (a) sends Last-Modified, Content-type, and Content-Disposition headers
66 * (b) cancels any PHP output buffering and automatic gzipping of output
67 * (c) sends Content-Length header based on HTTP_IF_MODIFIED_SINCE check
68 *
69 * @param $path string Storage path or file system path
70 * @param $info Array|bool File stat info with 'mtime' and 'size' fields
71 * @param $headers Array Additional headers to send
72 * @param $sendErrors bool Send error messages if errors occur (like 404)
73 * @return int|bool READY_STREAM, NOT_MODIFIED, or false on failure
74 */
75 public static function prepareForStream(
76 $path, $info, $headers = array(), $sendErrors = true
77 ) {
78 global $wgLanguageCode;
79
80 if ( !is_array( $info ) ) {
81 if ( $sendErrors ) {
82 header( 'HTTP/1.0 404 Not Found' );
83 header( 'Cache-Control: no-cache' );
84 header( 'Content-Type: text/html; charset=utf-8' );
85 $encFile = htmlspecialchars( $path );
86 $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
87 echo "<html><body>
88 <h1>File not found</h1>
89 <p>Although this PHP script ($encScript) exists, the file requested for output
90 ($encFile) does not.</p>
91 </body></html>
92 ";
93 }
94 return false;
95 }
96
97 // Sent Last-Modified HTTP header for client-side caching
98 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $info['mtime'] ) );
99
100 // Cancel output buffering and gzipping if set
101 wfResetOutputBuffers();
102
103 $type = self::contentTypeFromPath( $path );
104 if ( $type && $type != 'unknown/unknown' ) {
105 header( "Content-type: $type" );
106 } else {
107 // Send a content type which is not known to Internet Explorer, to
108 // avoid triggering IE's content type detection. Sending a standard
109 // unknown content type here essentially gives IE license to apply
110 // whatever content type it likes.
111 header( 'Content-type: application/x-wiki' );
112 }
113
114 // Don't stream it out as text/html if there was a PHP error
115 if ( headers_sent() ) {
116 echo "Headers already sent, terminating.\n";
117 return false;
118 }
119
120 header( "Content-Disposition: inline;filename*=utf-8'$wgLanguageCode'" .
121 urlencode( basename( $path ) ) );
122
123 // Send additional headers
124 foreach ( $headers as $header ) {
125 header( $header );
126 }
127
128 // Don't send if client has up to date cache
129 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
130 $modsince = preg_replace( '/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
131 if ( wfTimestamp( TS_UNIX, $info['mtime'] ) <= strtotime( $modsince ) ) {
132 ini_set( 'zlib.output_compression', 0 );
133 header( "HTTP/1.0 304 Not Modified" );
134 return self::NOT_MODIFIED; // ok
135 }
136 }
137
138 header( 'Content-Length: ' . $info['size'] );
139
140 return self::READY_STREAM; // ok
141 }
142
143 /**
144 * Determine the file type of a file based on the path
145 *
146 * @param $filename string Storage path or file system path
147 * @param $safe bool Whether to do retroactive upload blacklist checks
148 * @return null|string
149 */
150 public static function contentTypeFromPath( $filename, $safe = true ) {
151 global $wgTrivialMimeDetection;
152
153 $ext = strrchr( $filename, '.' );
154 $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
155
156 # trivial detection by file extension,
157 # used for thumbnails (thumb.php)
158 if ( $wgTrivialMimeDetection ) {
159 switch ( $ext ) {
160 case 'gif': return 'image/gif';
161 case 'png': return 'image/png';
162 case 'jpg': return 'image/jpeg';
163 case 'jpeg': 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
175 /**
176 * Double-check some security settings that were done on upload but might
177 * have changed since.
178 */
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';
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 }