Completed
Pull Request — master (#133)
by Victor
44:02
created

BackgroundScanner   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 15.73%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 19
c 6
b 1
f 0
lcom 2
cbo 4
dl 0
loc 187
ccs 14
cts 89
cp 0.1573
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getOwner() 0 12 3
A getUserFolder() 0 7 2
A initFilesystemForUser() 0 11 3
A tearDownFilesystem() 0 4 1
A check() 0 2 1
A __construct() 0 12 1
C run() 0 77 8
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 1
	public function __construct(ScannerFactory $scannerFactory,
52
								IL10N $l10n,
53
								AppConfig $appConfig,
54
								IRootFolder $rootFolder,
55
								IUserSession $userSession
56
	){
57 1
		$this->rootFolder = $rootFolder;
58 1
		$this->scannerFactory = $scannerFactory;
59 1
		$this->l10n = $l10n;
60 1
		$this->appConfig = $appConfig;
61 1
		$this->userSession = $userSession;
62 1
	}
63
	
64
	/**
65
	 * Background scanner main job
66
	 * @return null
67
	 */
68 1
	public function run(){
69
		// locate files that are not checked yet
70 1
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory');
71
		try {
72 1
			$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
73
74 1
			$sizeLimit = intval($this->appConfig);
75
			if ( $sizeLimit === -1 ){
76
				$sizeLimitExpr = $qb->expr()->neq('fc.size', $qb->expr()->literal('0'));
77
			} else {
78
				$sizeLimitExpr = $qb->expr()->andX(
79
					$qb->expr()->neq('fc.size', $qb->expr()->literal('0')),
80
					$qb->expr()->lt('fc.size', $qb->expr()->literal((string) $sizeLimit))
81
				);
82
			}
83
84
			$qb->select(['fc.fileid'])
85
				->from('filecache', 'fc')
86
				->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
87
				->innerJoin(
88
					'fc',
89
					'storages',
90
					'ss',
91
					$qb->expr()->andX(
92
						$qb->expr()->eq('fc.storage', 'ss.numeric_id'),
93
						$qb->expr()->orX(
94
							$qb->expr()->like('ss.id', $qb->expr()->literal('local::%')),
95
							$qb->expr()->like('ss.id', $qb->expr()->literal('home::%'))
96
						)
97
					)
98
				)
99
				->where(
100
					$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
101
				)
102
				->andWhere(
103
					$qb->expr()->orX(
104
						$qb->expr()->isNull('fa.fileid'),
105
						$qb->expr()->gt('fc.mtime', 'fa.check_time')
106
					)
107
				)
108
				->andWhere(
109
					$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
110
				)
111
				->andWhere( $sizeLimitExpr )
112
			;
113
			$result = $qb->execute();
114 1
		} catch(\Exception $e) {
115 1
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
116 1
			return;
117
		}
118
119
		$cnt = 0;
120
		while (($row = $result->fetch()) && $cnt < self::BATCH_SIZE) {
121
			try {
122
				$fileId = $row['fileid'];
123
				$owner = $this->getOwner($fileId);
124
				/** @var IUser $owner */
125
				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...
126
					continue;
127
				}
128
				$this->initFilesystemForUser($owner);
129
				$view = Filesystem::getView();
130
				$path = $view->getPath($fileId);
131
				if (!is_null($path)) {
132
					$item = new Item($this->l10n, $view, $path, $fileId);
133
					$scanner = $this->scannerFactory->getScanner();
134
					$status = $scanner->scan($item);
135
					$status->dispatch($item, true);
136
				}
137
				// increased only for successfully scanned files
138
				$cnt = $cnt + 1;
139
			} catch (\Exception $e){
140
				\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
141
			}
142
		}
143
		$this->tearDownFilesystem();
144
	}
145
146
	/**
147
	 * @param int $fileId
148
	 * @return IUser|null
149
	 */
150
	protected function getOwner($fileId){
151
		$mountProviderCollection = \OC::$server->getMountProviderCollection();
152
		$mountCache = $mountProviderCollection->getMountCache();
153
		$mounts = $mountCache->getMountsForFileId($fileId);
154
		if (!empty($mounts)) {
155
			$user = $mounts[0]->getUser();
156
			if ($user 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...
157
				return $user;
158
			}
159
		}
160
		return null;
161
	}
162
163
	/**
164
	 * @param \OCP\IUser $user
165
	 * @return \OCP\Files\Folder
166
	 */
167
	protected function getUserFolder(IUser $user) {
168
		if (!isset($this->userFolders[$user->getUID()])) {
169
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
170
			$this->userFolders[$user->getUID()] = $userFolder;
171
		}
172
		return $this->userFolders[$user->getUID()];
173
	}
174
175
	/**
176
	 * @param IUser $user
177
	 */
178
	protected function initFilesystemForUser(IUser $user) {
179
		if ($this->currentFilesystemUser !== $user->getUID()) {
180
			if ($this->currentFilesystemUser !== '') {
181
				$this->tearDownFilesystem();
182
			}
183
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
184
			$this->userSession->setUser($user);
185
			$this->currentFilesystemUser = $user->getUID();
186
			Filesystem::initMountPoints($user->getUID());
187
		}
188
	}
189
190
	/**
191
	 *
192
	 */
193
	protected function tearDownFilesystem(){
194
		$this->userSession->setUser(null);
195
		\OC_Util::tearDownFS();
196
	}
197
198
	/**
199
	 * @deprecated since  v8.0.0
200
	 */
201
	public static function check(){
202
	}
203
}
204