Completed
Pull Request — master (#225)
by Victor
11:27 queued 09:57
created

BackgroundScanner   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 221
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Test Coverage

Coverage 50.52%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 20
lcom 2
cbo 5
dl 0
loc 221
ccs 49
cts 97
cp 0.5052
rs 10
c 5
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
C run() 0 39 7
A getFilesForScan() 0 54 3
A scanOneFile() 0 11 2
A getUserFolder() 0 7 2
A initFilesystemForUser() 0 11 3
A tearDownFilesystem() 0 4 1
A check() 0 2 1
1
<?php
2
/**
3
 * Copyright (c) 2012 Bart Visscher <[email protected]>
4
 * This file is licensed under the Affero General Public License version 3 or
5
 * later.
6
 * See the COPYING-README file.
7
 */
8
9
namespace OCA\Files_Antivirus;
10
11
use Doctrine\DBAL\Platforms\MySqlPlatform;
12
use OC\Files\Filesystem;
13
use OCP\IL10N;
14
use OCP\Files\IRootFolder;
15
use OCP\IUser;
16
use OCP\IUserSession;
17
18
class BackgroundScanner {
19
20
	const BATCH_SIZE = 10;
21
22
	/**
23
	 * @var IRootFolder
24
	 */
25
	protected $rootFolder;
26
27
	/**
28
	 * @var \OCP\Files\Folder[]
29
	 */
30
	protected $userFolders;
31
32
	/**
33
	 * @var ScannerFactory
34
	 */
35
	private $scannerFactory;
36
37
	/**
38
	 * @var IL10N
39
	 */
40
	private $l10n;
41
42
	/**
43
	 * @var  AppConfig
44
	 */
45
	private $appConfig;
46
47
	/**
48
	 * @var string
49
	 */
50
	protected $currentFilesystemUser;
51
52
	/**
53
	 * @var \OCP\IUserSession
54
	 */
55
	protected $userSession;
56
57
	/**
58
	 * A constructor
59
	 *
60
	 * @param \OCA\Files_Antivirus\ScannerFactory $scannerFactory
61
	 * @param IL10N $l10n
62
	 * @param AppConfig $appConfig
63
	 * @param IRootFolder $rootFolder
64
	 * @param IUserSession $userSession
65
	 */
66 2
	public function __construct(ScannerFactory $scannerFactory,
67
								IL10N $l10n,
68
								AppConfig $appConfig,
69
								IRootFolder $rootFolder,
70
								IUserSession $userSession
71
	) {
72 2
		$this->rootFolder = $rootFolder;
73 2
		$this->scannerFactory = $scannerFactory;
74 2
		$this->l10n = $l10n;
75 2
		$this->appConfig = $appConfig;
76 2
		$this->userSession = $userSession;
77 2
	}
78
	
79
	/**
80
	 * Background scanner main job
81
	 *
82
	 * @return null
83
	 */
84 1
	public function run() {
85
86 1
		if ($this->appConfig->getAvScanBackground() !== 'true') {
87
			return;
88
		}
89
90
		// locate files that are not checked yet
91
		try {
92 1
			$result = $this->getFilesForScan();
93
		} catch(\Exception $e) {
94
			\OC::$server->getLogger()->error(
95
				__METHOD__ . ', exception: ' . $e->getMessage(),
96
				['app' => 'files_antivirus']
97
			);
98
			return;
99
		}
100
101 1
		$cnt = 0;
102 1
		while (($row = $result->fetch()) && $cnt < self::BATCH_SIZE) {
103
			try {
104
				$fileId = $row['fileid'];
105
				$userId = $row['user_id'];
106
				/** @var IUser $owner */
107
				$owner = \OC::$server->getUserManager()->get($userId);
108
				if (!$owner instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
109
					continue;
110
				}
111
				$this->scanOneFile($owner, $fileId);
112
				// increased only for successfully scanned files
113
				$cnt = $cnt + 1;
114
			} catch (\Exception $e){
115
				\OC::$server->getLogger()->error(
116
					__METHOD__ . ', exception: ' . $e->getMessage(),
117
					['app' => 'files_antivirus']
118
				);
119
			}
120
		}
121 1
		$this->tearDownFilesystem();
122 1
	}
123
124 2
	protected function getFilesForScan() {
125 2
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId(
126 2
			'httpd/unix-directory'
127
		);
128
129 2
		$dbConnection = \OC::$server->getDatabaseConnection();
130 2
		$qb = $dbConnection->getQueryBuilder();
131 2
		if ($dbConnection->getDatabasePlatform() instanceof MySqlPlatform) {
0 ignored issues
show
Bug introduced by
The class Doctrine\DBAL\Platforms\MySqlPlatform does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
132 2
			$concatFunction = $qb->createFunction(
133 2
				"CONCAT('/', mnt.user_id, '/')"
134
			);
135
		} else {
136
			$concatFunction = $qb->createFunction(
137
				"'/' || " . $qb->getColumnName('mnt.user_id') . " || '/'"
138
			);
139
		}
140
141 2
		$sizeLimit = \intval($this->appConfig->getAvMaxFileSize());
142 2
		if ( $sizeLimit === -1 ) {
143 2
			$sizeLimitExpr = $qb->expr()->neq('fc.size', $qb->expr()->literal('0'));
144
		} else {
145
			$sizeLimitExpr = $qb->expr()->andX(
146
				$qb->expr()->neq('fc.size', $qb->expr()->literal('0')),
147
				$qb->expr()->lt('fc.size', $qb->expr()->literal((string) $sizeLimit))
148
			);
149
		}
150
151 2
		$qb->select(['fc.fileid', 'mnt.user_id'])
152 2
			->from('filecache', 'fc')
153 2
			->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
154 2
			->innerJoin(
155 2
				'fc',
156 2
				'mounts',
157 2
				'mnt',
158 2
				$qb->expr()->andX(
159 2
					$qb->expr()->eq('fc.storage', 'mnt.storage_id'),
160 2
					$qb->expr()->eq('mnt.mount_point', $concatFunction)
161
				)
162
			)
163 2
			->where(
164 2
				$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
165
			)
166 2
			->andWhere(
167 2
				$qb->expr()->orX(
168 2
					$qb->expr()->isNull('fa.fileid'),
169 2
					$qb->expr()->gt('fc.mtime', 'fa.check_time')
170
				)
171
			)
172 2
			->andWhere(
173 2
				$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
174
			)
175 2
			->andWhere($sizeLimitExpr);
176 2
		return $qb->execute();
177
	}
178
179
	/**
180
	 * @param IUser $owner
181
	 * @param int $fileId
182
	 */
183
	protected function scanOneFile($owner, $fileId) {
184
		$this->initFilesystemForUser($owner);
185
		$view = Filesystem::getView();
186
		$path = $view->getPath($fileId);
187
		if (!\is_null($path)) {
188
			$item = new Item($this->l10n, $view, $path, $fileId);
189
			$scanner = $this->scannerFactory->getScanner();
190
			$status = $scanner->scan($item);
191
			$status->dispatch($item, true);
192
		}
193
	}
194
195
	/**
196
	 * @param \OCP\IUser $user
197
	 *
198
	 * @return \OCP\Files\Folder
199
	 */
200
	protected function getUserFolder(IUser $user) {
201
		if (!isset($this->userFolders[$user->getUID()])) {
202
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
203
			$this->userFolders[$user->getUID()] = $userFolder;
204
		}
205
		return $this->userFolders[$user->getUID()];
206
	}
207
208
	/**
209
	 * @param IUser $user
210
	 */
211
	protected function initFilesystemForUser(IUser $user) {
212
		if ($this->currentFilesystemUser !== $user->getUID()) {
213
			if ($this->currentFilesystemUser !== '') {
214
				$this->tearDownFilesystem();
215
			}
216
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
217
			$this->userSession->setUser($user);
218
			$this->currentFilesystemUser = $user->getUID();
219
			Filesystem::initMountPoints($user->getUID());
220
		}
221
	}
222
223
	/**
224
	 * @return void
225
	 */
226 1
	protected function tearDownFilesystem() {
227 1
		$this->userSession->setUser(null);
228 1
		\OC_Util::tearDownFS();
229 1
	}
230
231
	/**
232
	 * @deprecated since  v8.0.0
233
	 *
234
	 * @return void
235
	 */
236
	public static function check() {
237
	}
238
}
239