]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/libs/filebackend/HTTPFileStreamer.php
MediaWiki 1.30.2
[autoinstallsdev/mediawiki.git] / includes / libs / filebackend / HTTPFileStreamer.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 use Wikimedia\Timestamp\ConvertibleTimestamp;
23
24 /**
25  * Functions related to the output of file content
26  *
27  * @since 1.28
28  */
29 class HTTPFileStreamer {
30         /** @var string */
31         protected $path;
32         /** @var callable */
33         protected $obResetFunc;
34         /** @var callable */
35         protected $streamMimeFunc;
36
37         // Do not send any HTTP headers unless requested by caller (e.g. body only)
38         const STREAM_HEADLESS = 1;
39         // Do not try to tear down any PHP output buffers
40         const STREAM_ALLOW_OB = 2;
41
42         /**
43          * @param string $path Local filesystem path to a file
44          * @param array $params Options map, which includes:
45          *   - obResetFunc : alternative callback to clear the output buffer
46          *   - streamMimeFunc : alternative method to determine the content type from the path
47          */
48         public function __construct( $path, array $params = [] ) {
49                 $this->path = $path;
50                 $this->obResetFunc = isset( $params['obResetFunc'] )
51                         ? $params['obResetFunc']
52                         : [ __CLASS__, 'resetOutputBuffers' ];
53                 $this->streamMimeFunc = isset( $params['streamMimeFunc'] )
54                         ? $params['streamMimeFunc']
55                         : [ __CLASS__, 'contentTypeFromPath' ];
56         }
57
58         /**
59          * Stream a file to the browser, adding all the headings and fun stuff.
60          * Headers sent include: Content-type, Content-Length, Last-Modified,
61          * and Content-Disposition.
62          *
63          * @param array $headers Any additional headers to send if the file exists
64          * @param bool $sendErrors Send error messages if errors occur (like 404)
65          * @param array $optHeaders HTTP request header map (e.g. "range") (use lowercase keys)
66          * @param int $flags Bitfield of STREAM_* constants
67          * @throws MWException
68          * @return bool Success
69          */
70         public function stream(
71                 $headers = [], $sendErrors = true, $optHeaders = [], $flags = 0
72         ) {
73                 // Don't stream it out as text/html if there was a PHP error
74                 if ( ( ( $flags & self::STREAM_HEADLESS ) == 0 || $headers ) && headers_sent() ) {
75                         echo "Headers already sent, terminating.\n";
76                         return false;
77                 }
78
79                 $headerFunc = ( $flags & self::STREAM_HEADLESS )
80                         ? function ( $header ) {
81                                 // no-op
82                         }
83                         : function ( $header ) {
84                                 is_int( $header ) ? HttpStatus::header( $header ) : header( $header );
85                         };
86
87                 MediaWiki\suppressWarnings();
88                 $info = stat( $this->path );
89                 MediaWiki\restoreWarnings();
90
91                 if ( !is_array( $info ) ) {
92                         if ( $sendErrors ) {
93                                 self::send404Message( $this->path, $flags );
94                         }
95                         return false;
96                 }
97
98                 // Send Last-Modified HTTP header for client-side caching
99                 $mtimeCT = new ConvertibleTimestamp( $info['mtime'] );
100                 $headerFunc( 'Last-Modified: ' . $mtimeCT->getTimestamp( TS_RFC2822 ) );
101
102                 if ( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
103                         call_user_func( $this->obResetFunc );
104                 }
105
106                 $type = call_user_func( $this->streamMimeFunc, $this->path );
107                 if ( $type && $type != 'unknown/unknown' ) {
108                         $headerFunc( "Content-type: $type" );
109                 } else {
110                         // Send a content type which is not known to Internet Explorer, to
111                         // avoid triggering IE's content type detection. Sending a standard
112                         // unknown content type here essentially gives IE license to apply
113                         // whatever content type it likes.
114                         $headerFunc( 'Content-type: application/x-wiki' );
115                 }
116
117                 // Don't send if client has up to date cache
118                 if ( isset( $optHeaders['if-modified-since'] ) ) {
119                         $modsince = preg_replace( '/;.*$/', '', $optHeaders['if-modified-since'] );
120                         if ( $mtimeCT->getTimestamp( TS_UNIX ) <= strtotime( $modsince ) ) {
121                                 ini_set( 'zlib.output_compression', 0 );
122                                 $headerFunc( 304 );
123                                 return true; // ok
124                         }
125                 }
126
127                 // Send additional headers
128                 foreach ( $headers as $header ) {
129                         header( $header ); // always use header(); specifically requested
130                 }
131
132                 if ( isset( $optHeaders['range'] ) ) {
133                         $range = self::parseRange( $optHeaders['range'], $info['size'] );
134                         if ( is_array( $range ) ) {
135                                 $headerFunc( 206 );
136                                 $headerFunc( 'Content-Length: ' . $range[2] );
137                                 $headerFunc( "Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}" );
138                         } elseif ( $range === 'invalid' ) {
139                                 if ( $sendErrors ) {
140                                         $headerFunc( 416 );
141                                         $headerFunc( 'Cache-Control: no-cache' );
142                                         $headerFunc( 'Content-Type: text/html; charset=utf-8' );
143                                         $headerFunc( 'Content-Range: bytes */' . $info['size'] );
144                                 }
145                                 return false;
146                         } else { // unsupported Range request (e.g. multiple ranges)
147                                 $range = null;
148                                 $headerFunc( 'Content-Length: ' . $info['size'] );
149                         }
150                 } else {
151                         $range = null;
152                         $headerFunc( 'Content-Length: ' . $info['size'] );
153                 }
154
155                 if ( is_array( $range ) ) {
156                         $handle = fopen( $this->path, 'rb' );
157                         if ( $handle ) {
158                                 $ok = true;
159                                 fseek( $handle, $range[0] );
160                                 $remaining = $range[2];
161                                 while ( $remaining > 0 && $ok ) {
162                                         $bytes = min( $remaining, 8 * 1024 );
163                                         $data = fread( $handle, $bytes );
164                                         $remaining -= $bytes;
165                                         $ok = ( $data !== false );
166                                         print $data;
167                                 }
168                         } else {
169                                 return false;
170                         }
171                 } else {
172                         return readfile( $this->path ) !== false; // faster
173                 }
174
175                 return true;
176         }
177
178         /**
179          * Send out a standard 404 message for a file
180          *
181          * @param string $fname Full name and path of the file to stream
182          * @param int $flags Bitfield of STREAM_* constants
183          * @since 1.24
184          */
185         public static function send404Message( $fname, $flags = 0 ) {
186                 if ( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
187                         HttpStatus::header( 404 );
188                         header( 'Cache-Control: no-cache' );
189                         header( 'Content-Type: text/html; charset=utf-8' );
190                 }
191                 $encFile = htmlspecialchars( $fname );
192                 $encScript = htmlspecialchars( $_SERVER['SCRIPT_NAME'] );
193                 echo "<!DOCTYPE html><html><body>
194                         <h1>File not found</h1>
195                         <p>Although this PHP script ($encScript) exists, the file requested for output
196                         ($encFile) does not.</p>
197                         </body></html>
198                         ";
199         }
200
201         /**
202          * Convert a Range header value to an absolute (start, end) range tuple
203          *
204          * @param string $range Range header value
205          * @param int $size File size
206          * @return array|string Returns error string on failure (start, end, length)
207          * @since 1.24
208          */
209         public static function parseRange( $range, $size ) {
210                 $m = [];
211                 if ( preg_match( '#^bytes=(\d*)-(\d*)$#', $range, $m ) ) {
212                         list( , $start, $end ) = $m;
213                         if ( $start === '' && $end === '' ) {
214                                 $absRange = [ 0, $size - 1 ];
215                         } elseif ( $start === '' ) {
216                                 $absRange = [ $size - $end, $size - 1 ];
217                         } elseif ( $end === '' ) {
218                                 $absRange = [ $start, $size - 1 ];
219                         } else {
220                                 $absRange = [ $start, $end ];
221                         }
222                         if ( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
223                                 if ( $absRange[0] < $size ) {
224                                         $absRange[1] = min( $absRange[1], $size - 1 ); // stop at EOF
225                                         $absRange[2] = $absRange[1] - $absRange[0] + 1;
226                                         return $absRange;
227                                 } elseif ( $absRange[0] == 0 && $size == 0 ) {
228                                         return 'unrecognized'; // the whole file should just be sent
229                                 }
230                         }
231                         return 'invalid';
232                 }
233                 return 'unrecognized';
234         }
235
236         protected static function resetOutputBuffers() {
237                 while ( ob_get_status() ) {
238                         if ( !ob_end_clean() ) {
239                                 // Could not remove output buffer handler; abort now
240                                 // to avoid getting in some kind of infinite loop.
241                                 break;
242                         }
243                 }
244         }
245
246         /**
247          * Determine the file type of a file based on the path
248          *
249          * @param string $filename Storage path or file system path
250          * @return null|string
251          */
252         protected static function contentTypeFromPath( $filename ) {
253                 $ext = strrchr( $filename, '.' );
254                 $ext = $ext === false ? '' : strtolower( substr( $ext, 1 ) );
255
256                 switch ( $ext ) {
257                         case 'gif':
258                                 return 'image/gif';
259                         case 'png':
260                                 return 'image/png';
261                         case 'jpg':
262                                 return 'image/jpeg';
263                         case 'jpeg':
264                                 return 'image/jpeg';
265                 }
266
267                 return 'unknown/unknown';
268         }
269 }