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