Completed
Pull Request — stable9 (#128)
by Victor
03:13
created

BackgroundScanner::tearDownFilesystem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 4
cts 4
cp 1
rs 10
cc 1
eloc 3
nc 1
nop 0
crap 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
	/**
28
	 * @var ScannerFactory
29
	 */
30
	private $scannerFactory;
31
32
	
33
	/**
34
	 * @var IL10N
35
	 */
36
	private $l10n;
37
38
	/** @var string */
39
	protected $currentFilesystemUser;
40
41
	/** @var \OCP\IUserSession */
42
	protected $userSession;
43
44
	/**
45
	 * A constructor
46
	 *
47
	 * @param \OCA\Files_Antivirus\ScannerFactory $scannerFactory
48
	 * @param IL10N $l10n
49
	 * @param IRootFolder $rootFolder
50
	 * @param IUserSession $userSession
51
	 */
52 1
	public function __construct(ScannerFactory $scannerFactory,
53
								IL10N $l10n,
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->userSession = $userSession;
61 1
	}
62
	
63
	/**
64
	 * Background scanner main job
65
	 * @return null
66
	 */
67 1
	public function run(){
68
		// locate files that are not checked yet
69 1
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory');
70
		try {
71 1
			$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
72 1
			$qb->select(['fc.fileid'])
73 1
				->from('filecache', 'fc')
74 1
				->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
75 1
				->innerJoin(
76 1
					'fc',
77 1
					'storages',
78 1
					'ss',
79 1
					$qb->expr()->andX(
80 1
						$qb->expr()->eq('fc.storage', 'ss.numeric_id'),
81 1
						$qb->expr()->orX(
82 1
							$qb->expr()->like('ss.id', $qb->expr()->literal('local::%')),
83 1
							$qb->expr()->like('ss.id', $qb->expr()->literal('home::%'))
84 1
						)
85 1
					)
86 1
				)
87 1
				->where(
88 1
					$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
89 1
				)
90 1
				->andWhere(
91 1
					$qb->expr()->orX(
92 1
						$qb->expr()->isNull('fa.fileid'),
93 1
						$qb->expr()->gt('fc.mtime', 'fa.check_time')
94 1
					)
95 1
				)
96 1
				->andWhere(
97 1
					$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
98 1
				)
99 1
				->andWhere(
100 1
					$qb->expr()->neq('fc.size', $qb->expr()->literal('0'))
101 1
				)
102
			;
103 1
			$result = $qb->execute();
104 1
		} catch(\Exception $e) {
105
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
106
			return;
107
		}
108
109 1
		$cnt = 0;
110 1
		while ($row = $result->fetch() && $cnt < self::BATCH_SIZE) {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $row = ($result->fetch()...cnt < self::BATCH_SIZE), Probably Intended Meaning: ($row = $result->fetch()...$cnt < self::BATCH_SIZE
Loading history...
111
			try {
112 1
				$fileId = $row['fileid'];
113 1
				$owner = $this->getOwner($fileId);
114
				/** @var IUser $owner */
115 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...
116 1
					continue;
117
				}
118
				$this->initFilesystemForUser($owner);
119
				$view = Filesystem::getView();
120
				$path = $view->getPath($fileId);
121
				if (!is_null($path)) {
122
					$item = new Item($this->l10n, $view, $path, $fileId);
123
					$scanner = $this->scannerFactory->getScanner();
124
					$status = $scanner->scan($item);
125
					$status->dispatch($item, true);
126
				}
127
				// increased only for successfully scanned files
128
				$cnt = $cnt + 1;
129
			} catch (\Exception $e){
130
				\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
131
			}
132
		}
133 1
		$this->tearDownFilesystem();
134 1
	}
135
136
	/**
137
	 * @param int $fileId
138
	 * @return IUser|null
139
	 */
140 1
	protected function getOwner($fileId){
141 1
		$mountProviderCollection = \OC::$server->getMountProviderCollection();
142 1
		$mountCache = $mountProviderCollection->getMountCache();
143 1
		$mounts = $mountCache->getMountsForFileId($fileId);
144 1
		if (!empty($mounts)) {
145
			$user = $mounts[0]->getUser();
146
			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...
147
				return $user;
148
			}
149
		}
150 1
		return null;
151
	}
152
153
	/**
154
	 * @param \OCP\IUser $user
155
	 * @return \OCP\Files\Folder
156
	 */
157
	protected function getUserFolder(IUser $user) {
158
		if (!isset($this->userFolders[$user->getUID()])) {
159
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
160
			$this->userFolders[$user->getUID()] = $userFolder;
161
		}
162
		return $this->userFolders[$user->getUID()];
163
	}
164
165
	/**
166
	 * @param IUser $user
167
	 */
168
	protected function initFilesystemForUser(IUser $user) {
169
		if ($this->currentFilesystemUser !== $user->getUID()) {
170
			if ($this->currentFilesystemUser !== '') {
171
				$this->tearDownFilesystem();
172
			}
173
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
174
			$this->userSession->setUser($user);
175
			$this->currentFilesystemUser = $user->getUID();
176
			Filesystem::initMountPoints($user->getUID());
177
		}
178
	}
179
180
	/**
181
	 *
182
	 */
183 1
	protected function tearDownFilesystem(){
184 1
		$this->userSession->setUser(null);
185 1
		\OC_Util::tearDownFS();
186 1
	}
187
188
	/**
189
	 * @deprecated since  v8.0.0
190
	 */
191
	public static function check(){
192
	}
193
}
194