Completed
Pull Request — master (#225)
by Victor
05:30 queued 04:01
created

BackgroundScanner::run()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 24.4119

Importance

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