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