|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @package CleverStyle Framework |
|
4
|
|
|
* @author Nazar Mokrynskyi <[email protected]> |
|
5
|
|
|
* @copyright Copyright (c) 2016, Nazar Mokrynskyi |
|
6
|
|
|
* @license MIT License, see license.txt |
|
7
|
|
|
*/ |
|
8
|
|
|
namespace cs\Request\Route; |
|
9
|
|
|
use |
|
10
|
|
|
cs\ExitException, |
|
11
|
|
|
cs\Response; |
|
12
|
|
|
|
|
13
|
|
|
trait Static_files { |
|
14
|
|
|
/** |
|
15
|
|
|
* @throws ExitException |
|
16
|
|
|
*/ |
|
17
|
26 |
|
protected function serve_static_files () { |
|
18
|
26 |
|
$path = explode('?', $this->path)[0]; |
|
19
|
|
|
if ( |
|
20
|
26 |
|
$this->method != 'GET' || |
|
21
|
22 |
|
!in_array(PHP_SAPI, ['cli', 'cli-server']) || |
|
22
|
26 |
|
strlen($path) < 2 |
|
23
|
|
|
) { |
|
24
|
24 |
|
return; |
|
25
|
|
|
} |
|
26
|
4 |
|
$path = realpath(DIR.$path); |
|
27
|
|
|
if ( |
|
28
|
4 |
|
strpos($path, DIR) !== 0 || |
|
29
|
4 |
|
strpos(basename($path), '.') === 0 |
|
30
|
|
|
) { |
|
31
|
4 |
|
return; |
|
32
|
|
|
} |
|
33
|
|
|
$path = substr($path, strlen(DIR)); |
|
34
|
|
|
$extension = file_extension($path); |
|
35
|
|
|
if ($extension == 'php') { |
|
36
|
|
|
throw new ExitException(404); |
|
37
|
|
|
} |
|
38
|
|
|
/** |
|
39
|
|
|
* Public cache |
|
40
|
|
|
*/ |
|
41
|
|
|
if (strpos($path, '/storage/pcache') === 0) { |
|
42
|
|
|
if (!in_array($extension, ['css', 'js', 'html'])) { |
|
43
|
|
|
throw new ExitException(403); |
|
44
|
|
|
} |
|
45
|
|
|
$this->serve_static_file($path); |
|
46
|
|
|
} |
|
47
|
|
|
/** |
|
48
|
|
|
* Uploaded files |
|
49
|
|
|
*/ |
|
50
|
|
|
if (strpos($path, '/storage/public') === 0) { |
|
51
|
|
|
$headers = [ |
|
52
|
|
|
'x-frame-options' => 'DENY', |
|
53
|
|
|
'content-type' => 'application/octet-stream' |
|
54
|
|
|
]; |
|
55
|
|
|
$this->serve_static_file($path, $headers); |
|
56
|
|
|
} |
|
57
|
|
|
/** |
|
58
|
|
|
* System, modules and themes includes |
|
59
|
|
|
*/ |
|
60
|
|
|
if (preg_match('#^/((modules/\w+/)?includes|themes/\w+)/.+#', $path)) { |
|
61
|
|
|
$this->serve_static_file($path); |
|
62
|
|
|
} |
|
63
|
|
|
throw new ExitException(404); |
|
64
|
|
|
} |
|
65
|
|
|
/** |
|
66
|
|
|
* @param string $path |
|
67
|
|
|
* @param string[] $headers |
|
68
|
|
|
* |
|
69
|
|
|
* @throws ExitException |
|
70
|
|
|
*/ |
|
71
|
|
|
protected function serve_static_file ($path, $headers = []) { |
|
72
|
|
|
$headers += ['cache-control' => 'max-age=2592000, public']; |
|
73
|
|
|
Response::instance()->init('', fopen(DIR.$path, 'rb'), $headers); |
|
74
|
|
|
throw new ExitException; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|