Completed
Push — master ( 5fa6d3...7e7cc5 )
by
unknown
03:10
created

BackgroundScanner   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 219
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Test Coverage

Coverage 50.52%

Importance

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

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
B run() 0 38 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
 * 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 Bart Visscher <[email protected]>
9
 * @author Viktar Dubiniuk <[email protected]>
10
 *
11
 * @copyright 2012 Bart Visscher <[email protected]>
12
 * @copyright Viktar Dubiniuk 2014-2018
13
 * @license AGPL-3.0
14
 */
15
16
namespace OCA\Files_Antivirus;
17
18
use Doctrine\DBAL\Platforms\MySqlPlatform;
19
use OC\Files\Filesystem;
20
use OCP\IL10N;
21
use OCP\Files\IRootFolder;
22
use OCP\IUser;
23
use OCP\IUserSession;
24
25
class BackgroundScanner {
26
	const BATCH_SIZE = 10;
27
28
	/**
29
	 * @var IRootFolder
30
	 */
31
	protected $rootFolder;
32
33
	/**
34
	 * @var \OCP\Files\Folder[]
35
	 */
36
	protected $userFolders;
37
38
	/**
39
	 * @var ScannerFactory
40
	 */
41
	private $scannerFactory;
42
43
	/**
44
	 * @var IL10N
45
	 */
46
	private $l10n;
47
48
	/**
49
	 * @var  AppConfig
50
	 */
51
	private $appConfig;
52
53
	/**
54
	 * @var string
55
	 */
56
	protected $currentFilesystemUser;
57
58
	/**
59
	 * @var \OCP\IUserSession
60
	 */
61
	protected $userSession;
62
63
	/**
64
	 * A constructor
65
	 *
66
	 * @param \OCA\Files_Antivirus\ScannerFactory $scannerFactory
67
	 * @param IL10N $l10n
68
	 * @param AppConfig $appConfig
69
	 * @param IRootFolder $rootFolder
70
	 * @param IUserSession $userSession
71
	 */
72 2
	public function __construct(ScannerFactory $scannerFactory,
73
								IL10N $l10n,
74
								AppConfig $appConfig,
75
								IRootFolder $rootFolder,
76
								IUserSession $userSession
77
	) {
78 2
		$this->rootFolder = $rootFolder;
79 2
		$this->scannerFactory = $scannerFactory;
80 2
		$this->l10n = $l10n;
81 2
		$this->appConfig = $appConfig;
82 2
		$this->userSession = $userSession;
83 2
	}
84
	
85
	/**
86
	 * Background scanner main job
87
	 *
88
	 * @return void
89
	 */
90 1
	public function run() {
91 1
		if ($this->appConfig->getAvScanBackground() !== 'true') {
92
			return;
93
		}
94
95
		// locate files that are not checked yet
96
		try {
97 1
			$result = $this->getFilesForScan();
98
		} catch (\Exception $e) {
99
			\OC::$server->getLogger()->error(
100
				__METHOD__ . ', exception: ' . $e->getMessage(),
101
				['app' => 'files_antivirus']
102
			);
103
			return;
104
		}
105
106 1
		$cnt = 0;
107 1
		while (($row = $result->fetch()) && $cnt < self::BATCH_SIZE) {
108
			try {
109
				$fileId = $row['fileid'];
110
				$userId = $row['user_id'];
111
				/** @var IUser $owner */
112
				$owner = \OC::$server->getUserManager()->get($userId);
113
				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...
114
					continue;
115
				}
116
				$this->scanOneFile($owner, $fileId);
117
				// increased only for successfully scanned files
118
				$cnt = $cnt + 1;
119
			} catch (\Exception $e) {
120
				\OC::$server->getLogger()->error(
121
					__METHOD__ . ', exception: ' . $e->getMessage(),
122
					['app' => 'files_antivirus']
123
				);
124
			}
125
		}
126 1
		$this->tearDownFilesystem();
127 1
	}
128
129 2
	protected function getFilesForScan() {
130 2
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId(
131 2
			'httpd/unix-directory'
132
		);
133
134 2
		$dbConnection = \OC::$server->getDatabaseConnection();
135 2
		$qb = $dbConnection->getQueryBuilder();
136 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...
137
			$concatFunction = $qb->createFunction(
138
				"CONCAT('/', mnt.user_id, '/')"
139
			);
140
		} else {
141 2
			$concatFunction = $qb->createFunction(
142 2
				"'/' || " . $qb->getColumnName('mnt.user_id') . " || '/'"
143
			);
144
		}
145
146 2
		$sizeLimit = \intval($this->appConfig->getAvMaxFileSize());
147 2
		if ($sizeLimit === -1) {
148 2
			$sizeLimitExpr = $qb->expr()->neq('fc.size', $qb->expr()->literal('0'));
149
		} else {
150
			$sizeLimitExpr = $qb->expr()->andX(
151
				$qb->expr()->neq('fc.size', $qb->expr()->literal('0')),
152
				$qb->expr()->lt('fc.size', $qb->expr()->literal((string) $sizeLimit))
153
			);
154
		}
155
156 2
		$qb->select(['fc.fileid', 'mnt.user_id'])
157 2
			->from('filecache', 'fc')
158 2
			->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
159 2
			->innerJoin(
160 2
				'fc',
161 2
				'mounts',
162 2
				'mnt',
163 2
				$qb->expr()->andX(
164 2
					$qb->expr()->eq('fc.storage', 'mnt.storage_id'),
165 2
					$qb->expr()->eq('mnt.mount_point', $concatFunction)
166
				)
167
			)
168 2
			->where(
169 2
				$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
170
			)
171 2
			->andWhere(
172 2
				$qb->expr()->orX(
173 2
					$qb->expr()->isNull('fa.fileid'),
174 2
					$qb->expr()->gt('fc.mtime', 'fa.check_time')
175
				)
176
			)
177 2
			->andWhere(
178 2
				$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
179
			)
180 2
			->andWhere($sizeLimitExpr);
181 2
		return $qb->execute();
182
	}
183
184
	/**
185
	 * @param IUser $owner
186
	 * @param int $fileId
187
	 */
188
	protected function scanOneFile($owner, $fileId) {
189
		$this->initFilesystemForUser($owner);
190
		$view = Filesystem::getView();
191
		$path = $view->getPath($fileId);
192
		if ($path !== null) {
193
			$item = new Item($this->l10n, $view, $path, $fileId);
194
			$scanner = $this->scannerFactory->getScanner();
195
			$status = $scanner->scan($item);
196
			$status->dispatch($item, true);
197
		}
198
	}
199
200
	/**
201
	 * @param \OCP\IUser $user
202
	 *
203
	 * @return \OCP\Files\Folder
204
	 */
205
	protected function getUserFolder(IUser $user) {
206
		if (!isset($this->userFolders[$user->getUID()])) {
207
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
208
			$this->userFolders[$user->getUID()] = $userFolder;
209
		}
210
		return $this->userFolders[$user->getUID()];
211
	}
212
213
	/**
214
	 * @param IUser $user
215
	 */
216
	protected function initFilesystemForUser(IUser $user) {
217
		if ($this->currentFilesystemUser !== $user->getUID()) {
218
			if ($this->currentFilesystemUser !== '') {
219
				$this->tearDownFilesystem();
220
			}
221
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
222
			$this->userSession->setUser($user);
223
			$this->currentFilesystemUser = $user->getUID();
224
			Filesystem::initMountPoints($user->getUID());
225
		}
226
	}
227
228
	/**
229
	 * @return void
230
	 */
231 1
	protected function tearDownFilesystem() {
232 1
		$this->userSession->setUser(null);
233 1
		\OC_Util::tearDownFS();
234 1
	}
235
236
	/**
237
	 * @deprecated since  v8.0.0
238
	 *
239
	 * @return void
240
	 */
241
	public static function check() {
242
	}
243
}
244