Remove obvious function-level profiling
[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 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
40 */
41 public static function stream( $fname, $headers = array(), $sendErrors = true ) {
42
43 if ( FileBackend::isStoragePath( $fname ) ) { // sanity
44 throw new MWException( __FUNCTION__ . " given storage path '$fname'." );
45 }
46
47 wfSuppressWarnings();
48 $stat = stat( $fname );
49 wfRestoreWarnings();
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 wfProfileIn( __METHOD__ . '-send' );
56 $ok = readfile( $fname );
57 wfProfileOut( __METHOD__ . '-send' );
58 } else {
59 $ok = false; // failed
60 }
61
62 return $ok;
63 }
64
65 /**
66 * Call this function used in preparation before streaming a file.
67 * This function does the following:
68 * (a) sends Last-Modified, Content-type, and Content-Disposition headers
69 * (b) cancels any PHP output buffering and automatic gzipping of output
70 * (c) sends Content-Length header based on HTTP_IF_MODIFIED_SINCE check
71 *
72 * @param string $path Storage path or file system path
73 * @param array|bool $info File stat info with 'mtime' and 'size' fields
74 * @param array $headers Additional headers to send
75 * @param bool $sendErrors Send error messages if errors occur (like 404)
76 * @return int|bool READY_STREAM, NOT_MODIFIED, or false on failure
77 */
78 public static function prepareForStream(
79 $path, $info, $headers = array(), $sendErrors = true
80 ) {
81 if ( !is_array( $info ) ) {
82 if ( $sendErrors ) {
83 header( 'HTTP/1.0 404 Not Found' );
84 header( 'Cache-Control: no-cache' );
85 header( 'Content-Type: text/html; charset=utf-8' );
86 $encFile = htmlspecialchars( $path );
87 $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
88 echo "<html><body>
89 <h1>File not found</h1>
90 <p>Although this PHP script ($encScript) exists, the file requested for output
91 ($encFile) does not.</p>
92 </body></html>
93 ";
94 }
95 return false;
96 }
97
98 // Sent Last-Modified HTTP header for client-side caching
99 header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $info['mtime'] ) );
100
101 // Cancel output buffering and gzipping if set
102 wfResetOutputBuffers();
103
104 $type = self::contentTypeFromPath( $path );
105 if ( $type && $type != 'unknown/unknown' ) {
106 header( "Content-type: $type" );
107 } else {
108 // Send a content type which is not known to Internet Explorer, to
109 // avoid triggering IE's content type detection. Sending a standard
110 // unknown content type here essentially gives IE license to apply
111 // whatever content type it likes.
112 header( 'Content-type: application/x-wiki' );
113 }
114
115 // Don't stream it out as text/html if there was a PHP error
116 if ( headers_sent() ) {
117 echo "Headers already sent, terminating.\n";
118 return false;
119 }
120
121 // Send additional headers
122 foreach ( $headers as $header ) {
123 header( $header );
124 }
125
126 // Don't send if client has up to date cache
127 if ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
128 $modsince = preg_replace( '/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
129 if ( wfTimestamp( TS_UNIX, $info['mtime'] ) <= strtotime( $modsince ) ) {
130 ini_set( 'zlib.output_compression', 0 );
131 header( "HTTP/1.0 304 Not Modified" );
132 return self::NOT_MODIFIED; // ok
133 }
134 }
135
136 header( 'Content-Length: ' . $info['size'] );
137
138 return self::READY_STREAM; // ok
139 }
140
141 /**
142 * Determine the file type of a file based on the path
143 *
144 * @param string $filename Storage path or file system path
145 * @param bool $safe Whether to do retroactive upload blacklist checks
146 * @return null|string
147 */
148 public static function contentTypeFromPath( $filename, $safe = true ) {
149 global $wgTrivialMimeDetection;
150
151 $ext = strrchr( $filename, '.' );
152 $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
153
154 # trivial detection by file extension,
155 # used for thumbnails (thumb.php)
156 if ( $wgTrivialMimeDetection ) {
157 switch ( $ext ) {
158 case 'gif':
159 return 'image/gif';
160 case 'png':
161 return 'image/png';
162 case 'jpg':
163 return 'image/jpeg';
164 case 'jpeg':
165 return 'image/jpeg';
166 }
167
168 return 'unknown/unknown';
169 }
170
171 $magic = MimeMagic::singleton();
172 // Use the extension only, rather than magic numbers, to avoid opening
173 // up vulnerabilities due to uploads of files with allowed extensions
174 // but disallowed types.
175 $type = $magic->guessTypesForExtension( $ext );
176
177 /**
178 * Double-check some security settings that were done on upload but might
179 * have changed since.
180 */
181 if ( $safe ) {
182 global $wgFileBlacklist, $wgCheckFileExtensions, $wgStrictFileExtensions,
183 $wgFileExtensions, $wgVerifyMimeType, $wgMimeTypeBlacklist;
184 list( , $extList ) = UploadBase::splitExtensions( $filename );
185 if ( UploadBase::checkFileExtensionList( $extList, $wgFileBlacklist ) ) {
186 return 'unknown/unknown';
187 }
188 if ( $wgCheckFileExtensions && $wgStrictFileExtensions
189 && !UploadBase::checkFileExtensionList( $extList, $wgFileExtensions )
190 ) {
191 return 'unknown/unknown';
192 }
193 if ( $wgVerifyMimeType && in_array( strtolower( $type ), $wgMimeTypeBlacklist ) ) {
194 return 'unknown/unknown';
195 }
196 }
197 return $type;
198 }
199 }