Completed
Pull Request — master (#260)
by Victor
06:35 queued 04:45
created

BackgroundScanner::run()   B

Complexity

Conditions 7
Paths 9

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 24.4119

Importance

Changes 0
Metric Value
dl 0
loc 38
ccs 7
cts 24
cp 0.2917
rs 8.3786
c 0
b 0
f 0
cc 7
nc 9
nop 0
crap 24.4119
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
		\OC::$server->getLogger()->info(
193
			"About to scan file of a user {$owner} with id {$fileId} and path {$path}",
194
			['app' => 'files_antivirus']
195
		);
196
		if ($path !== null) {
197
			$item = new Item($this->l10n, $view, $path, $fileId);
198
			$scanner = $this->scannerFactory->getScanner();
199
			$status = $scanner->scan($item);
200
			$status->dispatch($item, true);
201
		}
202
	}
203
204
	/**
205
	 * @param \OCP\IUser $user
206
	 *
207
	 * @return \OCP\Files\Folder
208
	 */
209
	protected function getUserFolder(IUser $user) {
210
		if (!isset($this->userFolders[$user->getUID()])) {
211
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
212
			$this->userFolders[$user->getUID()] = $userFolder;
213
		}
214
		return $this->userFolders[$user->getUID()];
215
	}
216
217
	/**
218
	 * @param IUser $user
219
	 */
220
	protected function initFilesystemForUser(IUser $user) {
221
		if ($this->currentFilesystemUser !== $user->getUID()) {
222
			if ($this->currentFilesystemUser !== '') {
223
				$this->tearDownFilesystem();
224
			}
225
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
226
			$this->userSession->setUser($user);
227
			$this->currentFilesystemUser = $user->getUID();
228
			Filesystem::initMountPoints($user->getUID());
229
		}
230
	}
231
232
	/**
233
	 * @return void
234
	 */
235 1
	protected function tearDownFilesystem() {
236 1
		$this->userSession->setUser(null);
237 1
		\OC_Util::tearDownFS();
238 1
	}
239
240
	/**
241
	 * @deprecated since  v8.0.0
242
	 *
243
	 * @return void
244
	 */
245
	public static function check() {
246
	}
247
}
248