Completed
Push — master ( 50ca39...f3fec3 )
by Nazar
04:46
created

Static_files::serve_static_file()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 1
eloc 5
c 1
b 1
f 1
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 5
cp 0
crap 2
rs 9.4285
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\App;
9
use
10
	cs\ExitException,
11
	cs\Page,
12
	cs\Response;
13
14
trait Static_files {
15
	/**
16
	 * @param \cs\Request $Request
17
	 *
18
	 * @throws ExitException
19
	 */
20 6
	protected function serve_static_files ($Request) {
21 6
		$path = explode('?', $Request->path)[0];
22 6
		if (strlen($path) < 2) {
23 4
			return;
24
		}
25 2
		$path = realpath(DIR.$path);
26
		if (
27 2
			strpos($path, DIR) !== 0 ||
28 2
			strpos(basename($path), '.') === 0
29
		) {
30 2
			return;
31
		}
32
		$Response  = Response::instance();
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
			$Response->header('Content-Type', '');
46
			$this->serve_static_file($Response, $path);
47
		}
48
		/**
49
		 * Uploaded files
50
		 */
51
		if (strpos($path, '/storage/public') === 0) {
52
			$Response->header('X-Frame-Options', 'DENY');
53
			$Response->header('Content-Type', 'application/octet-stream');
54
			$this->serve_static_file($Response, $path);
55
		}
56
		/**
57
		 * System, modules and themes includes
58
		 */
59
		if (preg_match('#^/((modules/\w+/)?includes|themes/\w+)/.+#', $path)) {
60
			$Response->header('Content-Type', '');
61
			$this->serve_static_file($Response, $path);
62
		}
63
		throw new ExitException(404);
64
	}
65
	/**
66
	 * @param Response $Response
67
	 * @param string   $path
68
	 *
69
	 * @throws ExitException
70
	 */
71
	protected function serve_static_file ($Response, $path) {
72
		Page::instance()->interface = false;
73
		$Response->header('Cache-Control', 'max-age=2592000, public');
74
		$Response->body_stream = fopen(DIR.$path, 'rb');
75
		throw new ExitException;
76
	}
77
}
78