Completed
Push — master ( a7323b...28a033 )
by Roeland
04:33 queued 03:10
created

Item::updateCheckTime()   A

Complexity

Conditions 3
Paths 17

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 0
cts 11
cp 0
rs 9.7
c 0
b 0
f 0
cc 3
nc 17
nop 0
crap 12
1
<?php
2
/**
3
 * Copyright (c) 2015 Victor Dubiniuk <[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 OCA\Files_Antivirus\Activity\Provider;
12
use OCA\Files_Antivirus\AppInfo\Application;
13
use OCA\Files_Antivirus\Db\ItemMapper;
14
use OCP\Activity\IManager as ActivityManager;
15
use OCP\App;
16
use OCP\AppFramework\Db\DoesNotExistException;
17
use OCP\Files\File;
18
use OCP\Files\IRootFolder;
19
use OCA\Files_Trashbin\Trash\ITrashManager;
20
use OCP\ILogger;
21
22
class Item {
23
	/**
24
	 * file handle, user to read from the file
25
	 * @var resource
26
	 */
27
	protected $fileHandle;
28
29
	/** @var AppConfig */
30
	private $config;
31
32
	/** @var ActivityManager */
33
	private $activityManager;
34
35
	/** @var ItemMapper */
36
	private $itemMapper;
37
38
	/** @var ILogger */
39
	private $logger;
40
41
	/** @var IRootFolder */
42
	private $rootFolder;
43
44
	/** @var File */
45
	private $file;
46
	private $isCron;
47
48
	/**
49
	 * Item constructor.
50
	 *
51
	 * @param AppConfig $appConfig
52
	 * @param ActivityManager $activityManager
53
	 * @param ItemMapper $itemMapper
54
	 * @param ILogger $logger
55
	 * @param IRootFolder $rootFolder
56
	 * @param File $file
57
	 * @param bool $isCron
58
	 */
59
	public function __construct(AppConfig $appConfig,
60
								ActivityManager $activityManager,
61
								ItemMapper $itemMapper,
62
								ILogger $logger,
63
								IRootFolder $rootFolder,
64
								File $file,
65
								$isCron) {
66
		$this->config = $appConfig;
67
		$this->activityManager = $activityManager;
68
		$this->itemMapper = $itemMapper;
69
		$this->logger = $logger;
70
		$this->rootFolder = $rootFolder;
71
		$this->file = $file;
72
		$this->isCron = $isCron;
73
	}
74
75
	/**
76
	 * Reads a file portion by portion until the very end
77
	 * @return string|boolean
78
	 */
79
	public function fread() {
80
		if (!($this->file->getSize() > 0)) {
81
			return false;
82
		}
83
84
		if (is_null($this->fileHandle)) {
85
			$this->getFileHandle();
86
		}
87
88
		if (!is_null($this->fileHandle) && !$this->feof()) {
89
			return fread($this->fileHandle, $this->config->getAvChunkSize());
90
		}
91
		return false;
92
	}
93
94
	/**
95
	 * Action to take if this item is infected
96
	 */
97
	public function processInfected(Status $status) {
98
		$infectedAction = $this->config->getAvInfectedAction();
99
100
		$shouldDelete = $infectedAction === 'delete';
101
102
		$message = $shouldDelete ? Provider::MESSAGE_FILE_DELETED : '';
103
104
		$userFolder = $this->rootFolder->getUserFolder($this->file->getOwner()->getUID());
105
		$path = $userFolder->getRelativePath($this->file->getPath());
106
107
		$activity = $this->activityManager->generateEvent();
108
		$activity->setApp(Application::APP_NAME)
109
			->setSubject(Provider::SUBJECT_VIRUS_DETECTED_SCAN, [$status->getDetails()])
110
			->setMessage($message)
111
			->setObject('file', $this->file->getId(), $path)
112
			->setAffectedUser($this->file->getOwner()->getUID())
113
			->setType(Provider::TYPE_VIRUS_DETECTED);
114
		$this->activityManager->publish($activity);
115
116
		if ($shouldDelete) {
117
			if ($this->isCron) {
118
				$msg = 'Infected file deleted (during background scan)';
119
			} else {
120
				$msg = 'Infected file deleted.';
121
			}
122
			$this->logError($msg . ' ' . $status->getDetails());
123
			$this->deleteFile();
124
		} else {
125
			if ($this->isCron) {
126
				$msg = 'Infected file found (during background scan)';
127
			} else {
128
				$msg = 'Infected file found.';
129
			}
130
			$this->logError($msg . ' ' . $status->getDetails());
131
			$this->updateCheckTime();
132
		}
133
	}
134
135
	/**
136
	 * Action to take if this item status is unclear
137
	 * @param Status $status
138
	 */
139
	public function processUnchecked(Status $status) {
140
		//TODO: Show warning to the user: The file can not be checked
141
		$this->logError('Not Checked. ' . $status->getDetails());
142
	}
143
144
	/**
145
	 * Action to take if this item status is not infected
146
	 */
147
	public function processClean() {
148
		$this->updateCheckTime();
149
	}
150
151
	/**
152
	 * Update the check-time of this item to current time
153
	 */
154
	private function updateCheckTime() {
155
		try {
156
			try {
157
				$item = $this->itemMapper->findByFileId($this->file->getId());
158
				$this->itemMapper->delete($item);
159
			} catch (DoesNotExistException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\AppFramework\Db\DoesNotExistException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
160
				//Just ignore
161
			}
162
163
			$item = new \OCA\Files_Antivirus\Db\Item();
164
			$item->setFileid($this->file->getId());
165
			$item->setCheckTime(time());
166
			$this->itemMapper->insert($item);
0 ignored issues
show
Deprecated Code introduced by
The method OCA\Files_Antivirus\Db\ItemMapper::insert() has been deprecated with message: 14.0.0 Move over to QBMapper

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
167
		} catch(\Exception $e) {
168
			$this->logger->error(__METHOD__.', exception: '.$e->getMessage(), ['app' => 'files_antivirus']);
169
		}
170
	}
171
172
	/**
173
	 * Check if the end of file is reached
174
	 * @return boolean
175
	 */
176
	private function feof() {
177
		$isDone = feof($this->fileHandle);
178
		if ($isDone) {
179
			$this->logDebug('Scan is done');
180
			fclose($this->fileHandle);
181
			$this->fileHandle = null;
182
		}
183
		return $isDone;
184
	}
185
186
	/**
187
	 * Opens a file for reading
188
	 * @throws \RuntimeException
189
	 */
190
	private function getFileHandle() {
191
		$fileHandle = $this->file->fopen('r');
192
		if ($fileHandle === false) {
193
			$this->logError('Can not open for reading.');
194
			throw new \RuntimeException();
195
		}
196
197
		$this->logDebug('Scan started');
198
		$this->fileHandle = $fileHandle;
199
	}
200
201
	/**
202
	 * Delete infected file
203
	 */
204
	private function deleteFile() {
205
		//prevent from going to trashbin
206
		if (App::isEnabled('files_trashbin')) {
207
			/** @var ITrashManager $trashManager */
208
			$trashManager = \OC::$server->query(ITrashManager::class);
209
			$trashManager->pauseTrash();
210
		}
211
		$this->file->delete();
212
		if (App::isEnabled('files_trashbin')) {
213
			/** @var ITrashManager $trashManager */
214
			$trashManager = \OC::$server->query(ITrashManager::class);
215
			$trashManager->resumeTrash();
216
		}
217
	}
218
219
	private function generateExtraInfo() {
220
		$owner = $this->file->getOwner();
221
222
		if ($owner === null) {
223
			$ownerInfo = ' Account: NO OWNER FOUND';
224
		} else {
225
			$ownerInfo = ' Account: ' . $owner->getUID();
226
		}
227
228
		$extra = ' File: ' . $this->file->getId()
229
			. $ownerInfo
230
			. ' Path: ' . $this->file->getPath();
231
232
		return $extra;
233
	}
234
235
	/**
236
	 * @param string $message
237
	 */
238
	public function logDebug($message) {
239
		$this->logger->debug($message . $this->generateExtraInfo(), ['app' => 'files_antivirus']);
240
	}
241
242
	/**
243
	 * @param string $message
244
	 */
245
	public function logError($message) {
246
		$this->logger->error($message . $this->generateExtraInfo(), ['app' => 'files_antivirus']);
247
	}
248
}
249