Completed
Push — antivirus-update ( b6d85d...fcda38 )
by Victor
06:44
created

BackgroundScanner   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 155
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 16
Bugs 7 Features 0
Metric Value
wmc 17
c 16
b 7
f 0
lcom 2
cbo 4
dl 0
loc 155
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B run() 0 61 6
A getOwner() 0 19 4
A getUserFolder() 0 7 2
A initFilesystemForUser() 0 10 3
A check() 0 2 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 OC\Files\View;
13
use OCP\Files\IRootFolder;
14
use OCP\IUser;
15
use OCP\IL10N;
16
17
use OCA\Files_Antivirus\Item;
18
19
class BackgroundScanner {
20
21
	const BATCH_SIZE = 10;
22
23
	/** @var IRootFolder */
24
	protected $rootFolder;
25
26
	/** @var \OCP\Files\Folder[] */
27
	protected $userFolders;
28
29
	/**
30
	 * @var ScannerFactory
31
	 */
32
	private $scannerFactory;
33
34
	
35
	/**
36
	 * @var IL10N
37
	 */
38
	private $l10n;
39
40
	/** @var string */
41
	protected $currentFilesystemUser;
42
43
	/**
44
	 * A constructor
45
	 *
46
	 * @param IRootFolder $rootFolder
47
	 * @param \OCA\Files_Antivirus\ScannerFactory $scannerFactory
48
	 * @param IL10N $l10n
49
	 */
50
	public function __construct(IRootFolder $rootFolder = null, ScannerFactory $scannerFactory, IL10N $l10n){
51
		$this->rootFolder = $rootFolder;
52
		$this->scannerFactory = $scannerFactory;
53
		$this->l10n = $l10n;
54
	}
55
	
56
	/**
57
	 * Background scanner main job
58
	 * @return null
59
	 */
60
	public function run(){
61
		if (!$this->initFS()) {
0 ignored issues
show
Bug introduced by
The method initFS() does not seem to exist on object<OCA\Files_Antivirus\BackgroundScanner>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
62
			return;
63
		}
64
		// locate files that are not checked yet
65
		$dirMimeTypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory');
66
		try {
67
			$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
68
			$qb->select(['fc.fileid'])
69
				->from('filecache', 'fc')
70
				->leftJoin('fc', 'files_antivirus', 'fa', $qb->expr()->eq('fa.fileid', 'fc.fileid'))
71
				->innerJoin(
72
					'fc',
73
					'storages',
74
					'ss',
75
					$qb->expr()->andX(
76
						$qb->expr()->eq('fc.storage', 'ss.numeric_id'),
77
						$qb->expr()->orX(
78
							$qb->expr()->like('ss.id', $qb->expr()->literal('local::%')),
79
							$qb->expr()->like('ss.id', $qb->expr()->literal('home::%'))
80
						)
81
					)
82
				)
83
				->where(
84
					$qb->expr()->neq('fc.mimetype', $qb->expr()->literal($dirMimeTypeId))
85
				)
86
				->andWhere(
87
					$qb->expr()->orX(
88
						$qb->expr()->isNull('fa.fileid'),
89
						$qb->expr()->gt('fc.mtime', 'fa.check_time')
90
					)
91
				)
92
				->andWhere(
93
					$qb->expr()->like('fc.path', $qb->expr()->literal('files/%'))
94
				)
95
				->andWhere(
96
					$qb->expr()->neq('fc.size', '?1')
97
				)
98
				->setMaxResults(self::BATCH_SIZE)
99
			;
100
			$result = $qb->execute([0]);
101
		} catch(\Exception $e) {
102
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
103
			return;
104
		}
105
106
		try {
107
			while ($row = $result->fetch()) {
108
				$path = $view->getPath($row['fileid']);
0 ignored issues
show
Bug introduced by
The variable $view does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
109
				if (!is_null($path)) {
110
					$item = new Item($this->l10n, $view, $path, $row['fileid']);
111
					$scanner = $this->scannerFactory->getScanner();
112
					$status = $scanner->scan($item);
113
					$status->dispatch($item, true);
114
				}
115
			}
116
		} catch (\Exception $e){
117
			\OC::$server->getLogger()->error( __METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']);
118
		}
119
		\OC_Util::tearDownFS();
120
	}
121
122
	protected function getOwner($fileId){
123
		$mountProviderCollection = \OC::$server->getMountProviderCollection();
124
		$mountCache = $mountProviderCollection->getMountCache();
125
		$mounts = $mountCache->getMountsForFileId($fileId);
126
		if (!empty($mounts)) {
127
			$user = $mounts[0]->getUser();
128
			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...
129
				$this->initFilesystemForUser($user);
130
				$userFolder = $this->getUserFolder($user);
131
				$nodes = $userFolder->getById($fileId);
132
				if (!empty($nodes)) {
133
					$nodesToCheck[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$nodesToCheck was never initialized. Although not strictly required by PHP, it is generally a good practice to add $nodesToCheck = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
134
						'node' => array_shift($nodes),
135
						'owner' => $user
136
					];
137
				}
138
			}
139
		}
140
	}
141
142
	/**
143
	 * @param \OCP\IUser $user
144
	 * @return Folder
145
	 */
146
	protected function getUserFolder(IUser $user) {
147
		if (!isset($this->userFolders[$user->getUID()])) {
148
			$userFolder = $this->rootFolder->getUserFolder($user->getUID());
149
			$this->userFolders[$user->getUID()] = $userFolder;
150
		}
151
		return $this->userFolders[$user->getUID()];
152
	}
153
154
	/**
155
	 * @param IUser $user
156
	 */
157
	protected function initFilesystemForUser(IUser $user) {
158
		if ($this->currentFilesystemUser !== $user->getUID()) {
159
			if ($this->currentFilesystemUser !== '') {
160
				Filesystem::tearDown();
161
			}
162
			Filesystem::init($user->getUID(), '/' . $user->getUID() . '/files');
163
			$this->userSession->setUser($user);
0 ignored issues
show
Bug introduced by
The property userSession does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
164
			$this->currentFilesystemUser = $user->getUID();
165
		}
166
	}
167
168
	/**
169
	 * @deprecated since  v8.0.0
170
	 */
171
	public static function check(){
172
	}
173
}
174