|
1
|
|
|
<?php |
|
2
|
|
|
namespace WebPConvert\Serve; |
|
3
|
|
|
|
|
4
|
|
|
//use WebPConvert\Serve\Report; |
|
5
|
|
|
use WebPConvert\Serve\Header; |
|
6
|
|
|
use WebPConvert\Serve\Exceptions\ServeFailedException; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Serve a file (send to standard output) |
|
10
|
|
|
* |
|
11
|
|
|
* @package WebPConvert |
|
12
|
|
|
* @author Bjørn Rosell <[email protected]> |
|
13
|
|
|
* @since Class available since Release 2.0.0 |
|
14
|
|
|
*/ |
|
15
|
|
|
class ServeFile |
|
16
|
|
|
{ |
|
17
|
|
|
|
|
18
|
|
|
public static $defaultOptions = [ |
|
19
|
|
|
'add-vary-accept-header' => true, |
|
20
|
|
|
'set-content-type-header' => true, |
|
21
|
|
|
'set-last-modified-header' => true, |
|
22
|
|
|
'set-cache-control-header' => true, |
|
23
|
|
|
'cache-control-header' => 'public, max-age=86400', |
|
24
|
|
|
]; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Serve existing file |
|
28
|
|
|
* |
|
29
|
|
|
* @throws ServeFailedException if serving failed |
|
30
|
|
|
* @return void |
|
31
|
|
|
*/ |
|
32
|
|
|
public static function serve($filename, $contentType, $options) |
|
33
|
|
|
{ |
|
34
|
|
|
$options = array_merge(self::$defaultOptions, $options); |
|
35
|
|
|
|
|
36
|
|
|
if ($options['set-last-modified-header'] === true) { |
|
37
|
|
|
Header::setHeader("Last-Modified: " . gmdate("D, d M Y H:i:s", @filemtime($filename)) ." GMT"); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
if ($options['set-content-type-header'] === true) { |
|
41
|
|
|
Header::setHeader('Content-type: ' . $contentType); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if ($options['add-vary-accept-header'] === true) { |
|
45
|
|
|
Header::addHeader('Vary: Accept'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
if ($options['set-cache-control-header'] === true) { |
|
49
|
|
|
if (!empty($options['cache-control-header'])) { |
|
50
|
|
|
Header::setHeader('Cache-Control: ' . $options['cache-control-header']); |
|
51
|
|
|
|
|
52
|
|
|
// Add exprires header too (#126) |
|
53
|
|
|
// Check string for something like this: max-age:86400 |
|
54
|
|
|
if (preg_match('#max-age\\s*=\\s*(\\d*)#', $options['cache-control-header'], $matches)) { |
|
55
|
|
|
$seconds = $matches[1]; |
|
56
|
|
|
Header::setHeader('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + intval($seconds))); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
if (@readfile($filename) === false) { |
|
62
|
|
|
Header::addHeader('X-WebP-Convert-Error: Could not read file'); |
|
63
|
|
|
throw new ServeFailedException('Could not read file'); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|