Completed
Pull Request — master (#133)
by Victor
03:28
created

BackgroundScanner::getFilesForScan()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 45
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 2.0036

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 28
cts 31
cp 0.9032
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 32
nc 2
nop 0
crap 2.0036
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
		try {
71 1
			$result = $this->getFilesForScan();
72
		} catch(\Exception $e) {
73
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
74
			return;
75
		}
76
77 1
		$cnt = 0;
78 1
		while (($row = $result->fetch()) && $cnt < self::BATCH_SIZE) {
79
			try {
80 1
				$fileId = $row['fileid'];
81 1
				$owner = $this->getOwner($fileId);
82
				/** @var IUser $owner */
83 1
				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...
84 1
					continue;
85
				}
86 1
				$this->scanOneFile($owner, $fileId);
87
				// increased only for successfully scanned files
88 1
				$cnt = $cnt + 1;
89
			} catch (\Exception $e){
90
				\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
91
			}
92
		}
93 1
		$this->tearDownFilesystem();
94 1
	}
95
96 1
	protected function getFilesForScan(){
97 1
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory');
98 1
		$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
99
100 1
		$sizeLimit = intval($this->appConfig->getAvMaxFileSize());
101 1
		if ( $sizeLimit === -1 ){
102 1
			$sizeLimitExpr = $qb->expr()->neq('fc.size', $qb->expr()->literal('0'));
103
		} else {
104
			$sizeLimitExpr = $qb->expr()->andX(
105
				$qb->expr()->neq('fc.size', $qb->expr()->literal('0')),
106
				$qb->expr()->lt('fc.size', $qb->expr()->literal((string) $sizeLimit))
107
			);
108
		}
109
110 1
		$qb->select(['fc.fileid'])
111 1
			->from('filecache', 'fc')
112 1
			->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
113 1
			->innerJoin(
114 1
				'fc',
115 1
				'storages',
116 1
				'ss',
117 1
				$qb->expr()->andX(
118 1
					$qb->expr()->eq('fc.storage', 'ss.numeric_id'),
119 1
					$qb->expr()->orX(
120 1
						$qb->expr()->like('ss.id', $qb->expr()->literal('local::%')),
121 1
						$qb->expr()->like('ss.id', $qb->expr()->literal('home::%'))
122
					)
123
				)
124
			)
125 1
			->where(
126 1
				$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
127
			)
128 1
			->andWhere(
129 1
				$qb->expr()->orX(
130 1
					$qb->expr()->isNull('fa.fileid'),
131 1
					$qb->expr()->gt('fc.mtime', 'fa.check_time')
132
				)
133
			)
134 1
			->andWhere(
135 1
				$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
136
			)
137 1
			->andWhere( $sizeLimitExpr )
138
		;
139 1
		return $qb->execute();
140
	}
141
142
	/**
143
	 * @param IUser $owner
144
	 * @param int $fileId
145
	 */
146 1
	protected function scanOneFile($owner, $fileId){
147 1
		$this->initFilesystemForUser($owner);
148 1
		$view = Filesystem::getView();
149 1
		$path = $view->getPath($fileId);
150 1
		if (!is_null($path)) {
151 1
			$item = new Item($this->l10n, $view, $path, $fileId);
152 1
			$scanner = $this->scannerFactory->getScanner();
153 1
			$status = $scanner->scan($item);
154 1
			$status->dispatch($item, true);
155
		}
156 1
	}
157
158
	/**
159
	 * @param int $fileId
160
	 * @return IUser|null
161
	 */
162 1
	protected function getOwner($fileId){
163 1
		$mountProviderCollection = \OC::$server->getMountProviderCollection();
164 1
		$mountCache = $mountProviderCollection->getMountCache();
165 1
		$mounts = $mountCache->getMountsForFileId($fileId);
166 1
		if (!empty($mounts)) {
167 1
			$user = $mounts[0]->getUser();
168 1
			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...
169 1
				return $user;
170
			}
171
		}
172 1
		return null;
173
	}
174
175
	/**
176
	 * @param \OCP\IUser $user
177
	 * @return \OCP\Files\Folder
178
	 */
179
	protected function getUserFolder(IUser $user) {
180
		if (!isset($this->userFolders[$user->getUID()])) {
181
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
182
			$this->userFolders[$user->getUID()] = $userFolder;
183
		}
184
		return $this->userFolders[$user->getUID()];
185
	}
186
187
	/**
188
	 * @param IUser $user
189
	 */
190 1
	protected function initFilesystemForUser(IUser $user) {
191 1
		if ($this->currentFilesystemUser !== $user->getUID()) {
192 1
			if ($this->currentFilesystemUser !== '') {
193 1
				$this->tearDownFilesystem();
194
			}
195 1
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
196 1
			$this->userSession->setUser($user);
197 1
			$this->currentFilesystemUser = $user->getUID();
198 1
			Filesystem::initMountPoints($user->getUID());
199
		}
200 1
	}
201
202
	/**
203
	 *
204
	 */
205 1
	protected function tearDownFilesystem(){
206 1
		$this->userSession->setUser(null);
207 1
		\OC_Util::tearDownFS();
208 1
	}
209
210
	/**
211
	 * @deprecated since  v8.0.0
212
	 */
213
	public static function check(){
214
	}
215
}
216