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