Completed
Pull Request — master (#226)
by Victor
11:30 queued 08:47
created

RequestHelper::setSizeForPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 2
1
<?php
2
/**
3
 * ownCloud - files_antivirus
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Viktar Dubiniuk <[email protected]>
9
 *
10
 * @copyright Viktar Dubiniuk 2017-2018
11
 * @license AGPL-3.0
12
 */
13
14
namespace OCA\Files_Antivirus;
15
16
use OC\Cache\CappedMemoryCache;
17
use \OCP\IRequest;
18
19
/**
20
 * Used to detect the size of the uploaded file
21
 *
22
 * @package OCA\Files_Antivirus
23
 */
24
class RequestHelper {
25
	/**
26
	 * @var  IRequest
27
	 */
28
	private $request;
29
30
	/**
31
	 * @var CappedMemoryCache
32
	 */
33
	private $fileSizeCache;
34
35
	/**
36
	 * RequestHelper constructor.
37
	 *
38
	 * @param IRequest $request
39
	 */
40 4
	public function __construct(IRequest $request) {
41 4
		$this->request = $request;
42 4
		$this->fileSizeCache = new CappedMemoryCache();
43 4
	}
44
45
	/**
46
	 * @param string $path
47
	 * @param string $size
48
	 *
49
	 * @return void
50
	 */
51
	public function setSizeForPath($path, $size) {
52
		$this->fileSizeCache->set($path, $size);
53
	}
54
55
	/**
56
	 * Get current upload size
57
	 * returns null for chunks and when there is no upload
58
	 *
59
	 * @param string $path
60
	 *
61
	 * @return int|null
62
	 */
63 5
	public function getUploadSize($path) {
64 5
		$cachedSize = $this->fileSizeCache->get($path);
65 5
		if ($cachedSize > 0) {
66
			return $cachedSize;
67
		}
68
69 5
		$requestMethod = $this->request->getMethod();
70
		// Are we uploading anything?
71 5
		if ($requestMethod !== 'PUT') {
72 3
			return null;
73
		}
74 2
		$isRemoteScript = $this->isScriptName('remote.php');
75 2
		$isPublicScript = $this->isScriptName('public.php');
76 2
		if (!$isRemoteScript && !$isPublicScript) {
77
			return null;
78
		}
79
80 2
		if ($isRemoteScript) {
81
			// v1 && v2 Chunks are not scanned
82 1
			if (\strpos($path, 'uploads/') === 0) {
83 1
				return null;
84
			}
85
86
			if (\OC_FileChunking::isWebdavChunk()
87
				&& \strpos($path, 'cache/') === 0
88
			) {
89
				return null;
90
			}
91
		}
92 1
		$uploadSize = (int)$this->request->getHeader('CONTENT_LENGTH');
93
94 1
		return $uploadSize;
95
	}
96
97
	/**
98
	 *
99
	 * @param string $string
100
	 *
101
	 * @return bool
102
	 */
103 2
	public function isScriptName($string) {
104 2
		$pattern = \sprintf('|/%s|', \preg_quote($string));
105 2
		return \preg_match($pattern, $this->request->getScriptName()) === 1;
106
	}
107
}
108