Completed
Pull Request — master (#99)
by Roeland
02:03
created

AvirWrapper::fopen()   C

Complexity

Conditions 10
Paths 5

Size

Total Lines 73

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 69.4611

Importance

Changes 0
Metric Value
dl 0
loc 73
ccs 7
cts 44
cp 0.1591
rs 6.7224
c 0
b 0
f 0
cc 10
nc 5
nop 2
crap 69.4611

How to fix   Long Method    Complexity   

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) 2014 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 Icewind\Streams\CallbackWrapper;
12
use OC\Files\Storage\Wrapper\Wrapper;
13
use OCA\Files_Antivirus\Activity\Provider;
14
use OCA\Files_Antivirus\AppInfo\Application;
15
use OCA\Files_Antivirus\Event\ScanStateEvent;
16
use OCA\Files_Antivirus\Scanner\ScannerFactory;
17
use OCP\Activity\IManager as ActivityManager;
18
use OCP\App;
19
use OCP\Files\InvalidContentException;
20
use OCP\IL10N;
21
use OCP\ILogger;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
24
class AvirWrapper extends Wrapper{
25
	
26
	/**
27
	 * Modes that are used for writing 
28
	 * @var array 
29
	 */
30
	private $writingModes = ['r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+'];
31
	
32
	/** @var ScannerFactory */
33
	protected $scannerFactory;
34
	
35
	/** @var IL10N */
36
	protected $l10n;
37
	
38
	/** @var ILogger */
39
	protected $logger;
40
41
	/** @var ActivityManager */
42
	protected $activityManager;
43
44
	/** @var bool */
45
	protected $isHomeStorage;
46
47
	/** @var bool */
48
	private $shouldScan = true;
49
50
	/**
51
	 * @param array $parameters
52
	 */
53 2
	public function __construct($parameters) {
54 2
		parent::__construct($parameters);
55 2
		$this->scannerFactory = $parameters['scannerFactory'];
56 2
		$this->l10n = $parameters['l10n'];
57 2
		$this->logger = $parameters['logger'];
58 2
		$this->activityManager = $parameters['activityManager'];
59 2
		$this->isHomeStorage = $parameters['isHomeStorage'];
60
61
		/** @var EventDispatcherInterface $eventDispatcher */
62 2
		$eventDispatcher = $parameters['eventDispatcher'];
63 2
		$eventDispatcher->addListener(ScanStateEvent::class, function(ScanStateEvent $event) {
64
			$this->shouldScan = $event->getState();
65 2
		});
66 2
	}
67
	
68
	/**
69
	 * Asynchronously scan data that are written to the file
70
	 * @param string $path
71
	 * @param string $mode
72
	 * @return resource | bool
73
	 */
74 1
	public function fopen($path, $mode) {
75 1
		$stream = $this->storage->fopen($path, $mode);
76
77
		/*
78
		 * Only check when
79
		 *  - it is a resource
80
		 *  - it is a writing mode
81
		 *  - if it is a homestorage it starts with files/
82
		 *  - if it is not a homestorage we always wrap (external storages)
83
		 */
84 1
		if ($this->shouldScan && is_resource($stream) && $this->isWritingMode($mode) && (!$this->isHomeStorage || strpos($path, 'files/') === 0)) {
85
			try {
86 1
				$scanner = $this->scannerFactory->getScanner();
87
				$scanner->initScanner();
88
				return CallbackWrapper::wrap(
89
					$stream,
90
					null,
91
					function ($data) use ($scanner) {
92
						$scanner->onAsyncData($data);
93
					}, 
94
					function () use ($scanner, $path) {
95
						$status = $scanner->completeAsyncScan();
96
						if ((int)$status->getNumericStatus() === Status::SCANRESULT_INFECTED){
97
							//prevent from going to trashbin
98
							if (App::isEnabled('files_trashbin')) {
99
								\OCA\Files_Trashbin\Storage::preRenameHook([
100
									'oldpath' => '',
101
									'newpath' => ''
102
								]);
103
							}
104
							
105
							$owner = $this->getOwner($path);
106
							$this->unlink($path);
107
108
							if (App::isEnabled('files_trashbin')) {
109
								\OCA\Files_Trashbin\Storage::preRenameHook([
110
									'oldpath' => '',
111
									'newpath' => ''
112
								]);
113
							}
114
							$this->logger->warning(
115
								'Infected file deleted. ' . $status->getDetails()
116
								. ' Account: ' . $owner . ' Path: ' . $path,
117
								['app' => 'files_antivirus']
118
							);
119
120
							$activity = $this->activityManager->generateEvent();
121
							$activity->setApp(Application::APP_NAME)
122
								->setSubject(Provider::SUBJECT_VIRUS_DETECTED_UPLOAD, [$status->getDetails()])
123
								->setMessage(Provider::MESSAGE_FILE_DELETED)
124
								->setObject('', 0, $path)
125
								->setAffectedUser($owner)
126
								->setType(Provider::TYPE_VIRUS_DETECTED);
127
							$this->activityManager->publish($activity);
128
129
							$this->logger->error('Infected file deleted. ' . $status->getDetails() . 
130
							' File: ' . $path . ' Acccount: ' . $owner, ['app' => 'files_antivirus']);
131
132
							throw new InvalidContentException(
133
								$this->l10n->t(
134
									'Virus %s is detected in the file. Upload cannot be completed.',
135
									$status->getDetails()
136
								)
137
							);
138
						}
139
					}
140
				);
141 1
			} catch (\Exception $e){
142 1
				$this->logger->logException($e);
143
			}
144
		}
145 1
		return $stream;
146
	}
147
	
148
	/**
149
	 * Checks whether passed mode is suitable for writing 
150
	 * @param string $mode
151
	 * @return bool
152
	 */
153 1
	private function isWritingMode($mode){
154
		// Strip unessential binary/text flags
155 1
		$cleanMode = str_replace(
156 1
			['t', 'b'],
157 1
			['', ''],
158 1
			$mode
159
		);
160 1
		return in_array($cleanMode, $this->writingModes);
161
	}
162
}
163