Completed
Push — fix-file-not-found ( 3e2d30...663689 )
by Victor
08:40
created

BackgroundScanner::run()   C

Complexity

Conditions 7
Paths 19

Size

Total Lines 68
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 12
Bugs 5 Features 0
Metric Value
c 12
b 5
f 0
dl 0
loc 68
rs 6.9654
cc 7
eloc 49
nc 19
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\IUser;
14
use OCP\Files\IRootFolder;
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
	public function __construct(ScannerFactory $scannerFactory,
53
								IL10N $l10n,
54
								IRootFolder $rootFolder,
55
								IUserSession $userSession
56
	){
57
		$this->rootFolder = $rootFolder;
58
		$this->scannerFactory = $scannerFactory;
59
		$this->l10n = $l10n;
60
		$this->userSession = $userSession;
61
	}
62
	
63
	/**
64
	 * Background scanner main job
65
	 * @return null
66
	 */
67
	public function run(){
68
		// locate files that are not checked yet
69
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory');
70
		try {
71
			$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
72
			$qb->select(['fc.fileid'])
73
				->from('filecache', 'fc')
74
				->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
75
				->innerJoin(
76
					'fc',
77
					'storages',
78
					'ss',
79
					$qb->expr()->andX(
80
						$qb->expr()->eq('fc.storage', 'ss.numeric_id'),
81
						$qb->expr()->orX(
82
							$qb->expr()->like('ss.id', $qb->expr()->literal('local::%')),
83
							$qb->expr()->like('ss.id', $qb->expr()->literal('home::%'))
84
						)
85
					)
86
				)
87
				->where(
88
					$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
89
				)
90
				->andWhere(
91
					$qb->expr()->orX(
92
						$qb->expr()->isNull('fa.fileid'),
93
						$qb->expr()->gt('fc.mtime', 'fa.check_time')
94
					)
95
				)
96
				->andWhere(
97
					$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
98
				)
99
				->andWhere(
100
					$qb->expr()->neq('fc.size', $qb->expr()->literal('0'))
101
				)
102
			;
103
			$result = $qb->execute();
104
		} catch(\Exception $e) {
105
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
106
			return;
107
		}
108
109
		$cnt = 0;
110
		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
				$fileId = $row['fileid'];
113
				$owner = $this->getOwner($fileId);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $owner is correct as $this->getOwner($fileId) (which targets OCA\Files_Antivirus\BackgroundScanner::getOwner()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
114
				if (!$owner){
115
					continue;
116
				}
117
				$this->initFilesystemForUser($owner);
118
				$view = \OC\Files\Filesystem::getView();
119
				$path = $view->getPath($fileId);
120
				if (!is_null($path)) {
121
					$item = new Item($this->l10n, $view, $path, $fileId);
122
					$scanner = $this->scannerFactory->getScanner();
123
					$status = $scanner->scan($item);
124
					$status->dispatch($item, true);
125
				}
126
				$this->tearDownFilesystem();
127
128
				// increased only for successfully scanned files
129
				$cnt = $cnt + 1;
130
			} catch (\Exception $e){
131
				\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
132
			}
133
		}
134
	}
135
136
	protected function getOwner($fileId){
137
		$mountProviderCollection = \OC::$server->getMountProviderCollection();
138
		$mountCache = $mountProviderCollection->getMountCache();
139
		$mounts = $mountCache->getMountsForFileId($fileId);
140
		if (!empty($mounts)) {
141
			$user = $mounts[0]->getUser();
142
			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...
143
				return $user;
144
			}
145
		}
146
	}
147
148
	/**
149
	 * @param \OCP\IUser $user
150
	 * @return \OCP\Files\Folder
151
	 */
152
	protected function getUserFolder(IUser $user) {
153
		if (!isset($this->userFolders[$user->getUID()])) {
154
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
155
			$this->userFolders[$user->getUID()] = $userFolder;
156
		}
157
		return $this->userFolders[$user->getUID()];
158
	}
159
160
	/**
161
	 * @param IUser $user
162
	 */
163
	protected function initFilesystemForUser(IUser $user) {
164
		if ($this->currentFilesystemUser !== $user->getUID()) {
165
			if ($this->currentFilesystemUser !== '') {
166
				Filesystem::tearDown();
167
			}
168
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
169
			$this->userSession->setUser($user);
170
			$this->currentFilesystemUser = $user->getUID();
171
			\OC\Files\Filesystem::initMountPoints($user->getUID());
172
		}
173
	}
174
175
	/**
176
	 *
177
	 */
178
	protected function tearDownFilesystem(){
179
		$this->userSession->setUser(null);
180
		\OC_Util::tearDownFS();
181
	}
182
183
	/**
184
	 * @deprecated since  v8.0.0
185
	 */
186
	public static function check(){
187
	}
188
}
189