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