MediaWiki
master
Toggle main menu visibility
HTTPFileStreamer.php
Go to the documentation of this file.
1
<?php
8
9
namespace
Wikimedia\FileBackend;
10
11
use Wikimedia\Http\HttpHeader;
12
use Wikimedia\Http\HttpStatus;
13
use Wikimedia\Timestamp\ConvertibleTimestamp;
14
use Wikimedia\Timestamp\TimestampFormat as TS;
15
21
class
HTTPFileStreamer
{
23
protected
$path
;
25
protected
$obResetFunc
;
27
protected
$streamMimeFunc
;
29
protected
$headerFunc
;
30
31
// Do not send any HTTP headers (i.e. body only)
32
public
const
STREAM_HEADLESS
= 1;
33
// Do not try to tear down any PHP output buffers
34
public
const
STREAM_ALLOW_OB
= 2;
35
43
public
static
function
preprocessHeaders
( $headers ) {
44
$rawHeaders = [];
45
$optHeaders = [];
46
foreach
( $headers as $name => $header ) {
47
$nameLower = strtolower( $name );
48
if
( in_array( $nameLower, [
'range'
,
'if-modified-since'
],
true
) ) {
49
$optHeaders[$nameLower] = $header;
50
}
else
{
51
$rawHeaders[] =
"$name: $header"
;
52
}
53
}
54
return
[ $rawHeaders, $optHeaders ];
55
}
56
64
public
function
__construct
(
$path
, array $params = [] ) {
65
$this->path =
$path
;
66
$this->obResetFunc = $params[
'obResetFunc'
] ??
self::resetOutputBuffers
( ... );
67
$this->streamMimeFunc = $params[
'streamMimeFunc'
] ??
self::contentTypeFromPath
( ... );
68
$this->headerFunc = $params[
'headerFunc'
] ?? HttpHeader::send( ... );
69
}
70
82
public
function
stream
(
83
$headers = [], $sendErrors =
true
, $optHeaders = [], $flags = 0
84
) {
85
$headless = ( $flags & self::STREAM_HEADLESS );
86
87
// Don't stream it out as text/html if there was a PHP error
88
if
( $headers && HttpHeader::headersSent() ) {
89
echo
"Headers already sent, terminating.\n"
;
90
return
false
;
91
}
92
93
$headerFunc
= $headless
94
?
static
function
( $header ) {
95
// no-op
96
}
97
: $this->header( ... );
98
99
// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
100
$info = @stat( $this->path );
101
102
if
( !is_array( $info ) ) {
103
if
( $sendErrors ) {
104
self::send404Message
( $this->path, $flags );
105
}
106
return
false
;
107
}
108
109
// Send Last-Modified HTTP header for client-side caching
110
$mtimeCT =
new
ConvertibleTimestamp( $info[
'mtime'
] );
111
$headerFunc
(
'Last-Modified: '
. $mtimeCT->getTimestamp( TS::RFC2822 ) );
112
113
if
( ( $flags & self::STREAM_ALLOW_OB ) == 0 ) {
114
(
$this->obResetFunc
)();
115
}
116
117
$type = (
$this->streamMimeFunc
)( $this->path );
118
if
( $type && $type !=
'unknown/unknown'
) {
119
$headerFunc
(
"Content-type: $type"
);
120
}
else
{
121
// Send a content type which is not known to Internet Explorer, to
122
// avoid triggering IE's content type detection. Sending a standard
123
// unknown content type here essentially gives IE license to apply
124
// whatever content type it likes.
125
$headerFunc
(
'Content-type: application/x-wiki'
);
126
}
127
128
// Don't send if client has up to date cache
129
if
( isset( $optHeaders[
'if-modified-since'
] ) ) {
130
$modsince = preg_replace(
'/;.*$/'
,
''
, $optHeaders[
'if-modified-since'
] );
131
if
( $mtimeCT->getTimestamp( TS::UNIX ) <= strtotime( $modsince ) ) {
132
ini_set(
'zlib.output_compression'
, 0 );
133
$headerFunc
( 304 );
134
return
true
;
// ok
135
}
136
}
137
138
// Send additional headers
139
foreach
( $headers as $header ) {
140
$headerFunc
( $header );
141
}
142
143
if
( isset( $optHeaders[
'range'
] ) ) {
144
$range =
self::parseRange
( $optHeaders[
'range'
], $info[
'size'
] );
145
if
( is_array( $range ) ) {
146
$headerFunc
( 206 );
147
$headerFunc
(
'Content-Length: '
. $range[2] );
148
$headerFunc
(
"Content-Range: bytes {$range[0]}-{$range[1]}/{$info['size']}"
);
149
} elseif ( $range ===
'invalid'
) {
150
if
( $sendErrors ) {
151
$headerFunc
( 416 );
152
$headerFunc
(
'Cache-Control: no-cache'
);
153
$headerFunc
(
'Content-Type: text/html; charset=utf-8'
);
154
$headerFunc
(
'Content-Range: bytes */'
. $info[
'size'
] );
155
}
156
return
false
;
157
}
else
{
// unsupported Range request (e.g. multiple ranges)
158
$range =
null
;
159
$headerFunc
(
'Content-Length: '
. $info[
'size'
] );
160
}
161
}
else
{
162
$range =
null
;
163
$headerFunc
(
'Content-Length: '
. $info[
'size'
] );
164
}
165
166
if
( is_array( $range ) ) {
167
$handle = fopen( $this->path,
'rb'
);
168
if
( $handle ) {
169
$ok =
true
;
170
fseek( $handle, $range[0] );
171
$remaining = $range[2];
172
while
( $remaining > 0 && $ok ) {
173
$bytes = min( $remaining, 8 * 1024 );
174
$data = fread( $handle, $bytes );
175
$remaining -= $bytes;
176
$ok = ( $data !== false );
177
print $data;
178
}
179
}
else
{
180
return
false
;
181
}
182
}
else
{
183
return
readfile( $this->path ) !==
false
;
// faster
184
}
185
186
return
true
;
187
}
188
196
public
static
function
send404Message
( $fname, $flags = 0 ) {
197
if
( ( $flags & self::STREAM_HEADLESS ) == 0 ) {
198
HttpStatus::header( 404 );
199
HttpHeader::send(
'Cache-Control: no-cache'
);
200
HttpHeader::send(
'Content-Type: text/html; charset=utf-8'
);
201
}
202
$encFile = htmlspecialchars( $fname );
203
$encScript = htmlspecialchars( $_SERVER[
'SCRIPT_NAME'
] );
204
echo
"<!DOCTYPE html><html><body>
205
<h1>File not found</h1>
206
<p>Although this PHP script ($encScript) exists, the file requested for output
207
($encFile) does not.</p>
208
</body></html>
209
"
;
210
}
211
220
public
static
function
parseRange
( $range, $size ) {
221
$m = [];
222
if
( preg_match(
'#^bytes=(\d*)-(\d*)$#'
, $range, $m ) ) {
223
[ , $start, $end ] = $m;
224
if
( $start ===
''
&& $end ===
''
) {
225
$absRange = [ 0, $size - 1 ];
226
} elseif ( $start ===
''
) {
227
$absRange = [ $size - (int)$end, $size - 1 ];
228
} elseif ( $end ===
''
) {
229
$absRange = [ (int)$start, $size - 1 ];
230
}
else
{
231
$absRange = [ (int)$start, (
int
)$end ];
232
}
233
if
( $absRange[0] >= 0 && $absRange[1] >= $absRange[0] ) {
234
if
( $absRange[0] < $size ) {
235
$absRange[1] = min( $absRange[1], $size - 1 );
// stop at EOF
236
$absRange[2] = $absRange[1] - $absRange[0] + 1;
237
return
$absRange;
238
} elseif ( $absRange[0] == 0 && $size == 0 ) {
239
return
'unrecognized'
;
// the whole file should just be sent
240
}
241
}
242
return
'invalid'
;
243
}
244
return
'unrecognized'
;
245
}
246
247
protected
static
function
resetOutputBuffers
() {
248
while
( ob_get_status() ) {
249
if
( !ob_end_clean() ) {
250
// Could not remove output buffer handler; abort now
251
// to avoid getting in some kind of infinite loop.
252
break
;
253
}
254
}
255
}
256
262
protected
static
function
contentTypeFromPath
(
string
$filename ): string {
263
$ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
264
return
match ( $ext ) {
265
'gif'
=>
'image/gif'
,
266
'png'
=>
'image/png'
,
267
'jpg'
,
268
'jpeg'
=>
'image/jpeg'
,
269
'webp'
=>
'image/webp'
,
270
default
=>
'unknown/unknown'
,
271
};
272
}
273
277
private
function
header( $header ) {
278
if
( is_int( $header ) ) {
279
$header = HttpStatus::getHeader( $header );
280
}
281
282
( $this->headerFunc )( $header );
283
}
284
}
285
287
class_alias( HTTPFileStreamer::class,
'HTTPFileStreamer'
);
Wikimedia\FileBackend\HTTPFileStreamer
Functions related to the output of file content.
Definition
HTTPFileStreamer.php:21
Wikimedia\FileBackend\HTTPFileStreamer\stream
stream( $headers=[], $sendErrors=true, $optHeaders=[], $flags=0)
Stream a file to the browser, adding all the headings and fun stuff.
Definition
HTTPFileStreamer.php:82
Wikimedia\FileBackend\HTTPFileStreamer\$path
string $path
Definition
HTTPFileStreamer.php:23
Wikimedia\FileBackend\HTTPFileStreamer\STREAM_ALLOW_OB
const STREAM_ALLOW_OB
Definition
HTTPFileStreamer.php:34
Wikimedia\FileBackend\HTTPFileStreamer\preprocessHeaders
static preprocessHeaders( $headers)
Takes HTTP headers in a name => value format and converts them to the weird format expected by stream...
Definition
HTTPFileStreamer.php:43
Wikimedia\FileBackend\HTTPFileStreamer\send404Message
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Definition
HTTPFileStreamer.php:196
Wikimedia\FileBackend\HTTPFileStreamer\$streamMimeFunc
callable $streamMimeFunc
Definition
HTTPFileStreamer.php:27
Wikimedia\FileBackend\HTTPFileStreamer\__construct
__construct( $path, array $params=[])
Definition
HTTPFileStreamer.php:64
Wikimedia\FileBackend\HTTPFileStreamer\parseRange
static parseRange( $range, $size)
Convert a Range header value to an absolute (start, end) range tuple.
Definition
HTTPFileStreamer.php:220
Wikimedia\FileBackend\HTTPFileStreamer\contentTypeFromPath
static contentTypeFromPath(string $filename)
Determine the file type of a file based on the path.
Definition
HTTPFileStreamer.php:262
Wikimedia\FileBackend\HTTPFileStreamer\STREAM_HEADLESS
const STREAM_HEADLESS
Definition
HTTPFileStreamer.php:32
Wikimedia\FileBackend\HTTPFileStreamer\$obResetFunc
callable $obResetFunc
Definition
HTTPFileStreamer.php:25
Wikimedia\FileBackend\HTTPFileStreamer\resetOutputBuffers
static resetOutputBuffers()
Definition
HTTPFileStreamer.php:247
Wikimedia\FileBackend\HTTPFileStreamer\$headerFunc
callable $headerFunc
Definition
HTTPFileStreamer.php:29
includes
libs
FileBackend
HTTPFileStreamer.php
Generated on
for MediaWiki by
1.18.0