Completed
Push — fix-137-2 ( e5c888 )
by Victor
10:14
created

BackgroundScanner   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 5

Importance

Changes 8
Bugs 1 Features 0
Metric Value
wmc 18
c 8
b 1
f 0
lcom 2
cbo 5
dl 0
loc 189
rs 10

8 Methods

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