Completed
Push — master ( 282f25...6bf8e2 )
by
unknown
24:04
created

FileHandlingController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 174
Duplicated Lines 11.49 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 24
c 1
b 0
f 0
lcom 1
cbo 0
dl 20
loc 174
ccs 0
cts 111
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
B load() 6 57 10
C save() 14 64 13

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @author Björn Schießle <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2015, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
23
namespace OCA\FilesTextEditor\Controller;
24
25
26
use OC\HintException;
27
use OCP\AppFramework\Controller;
28
use OCP\AppFramework\Http;
29
use OCP\AppFramework\Http\DataResponse;
30
use OCP\Files\File;
31
use OCP\Files\Folder;
32
use OCP\Files\ForbiddenException;
33
use OCP\Files\GenericFileException;
34
use OCP\IL10N;
35
use OCP\ILogger;
36
use OCP\IRequest;
37
use OCP\Lock\LockedException;
38
39
class FileHandlingController extends Controller{
40
41
	/** @var IL10N */
42
	private $l;
43
44
	/** @var ILogger */
45
	private $logger;
46
47
	/** @var Folder */
48
	private $userFolder;
49
50
	/**
51
	 * @NoAdminRequired
52
	 *
53
	 * @param string $AppName
54
	 * @param IRequest $request
55
	 * @param IL10N $l10n
56
	 * @param ILogger $logger
57
	 * @param Folder $userFolder
58
	 */
59
	public function __construct($AppName,
60
								IRequest $request,
61
								IL10N $l10n,
62
								ILogger $logger,
63
								Folder $userFolder) {
64
		parent::__construct($AppName, $request);
65
		$this->l = $l10n;
66
		$this->logger = $logger;
67
		$this->userFolder = $userFolder;
68
	}
69
70
	/**
71
	 * load text file
72
	 *
73
	 * @NoAdminRequired
74
	 *
75
	 * @param string $dir
76
	 * @param string $filename
77
	 * @return DataResponse
78
	 */
79
	public function load($dir, $filename) {
80
		try {
81
			if (!empty($filename)) {
82
				$path = $dir . '/' . $filename;
83
84
				/** @var File $file */
85
				$file = $this->userFolder->get($path);
86
87 View Code Duplication
				if ($file instanceof Folder) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Folder 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...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
88
					return new DataResponse(['message' => $this->l->t('You can not open a folder')], Http::STATUS_BAD_REQUEST);
89
				}
90
91
				// default of 4MB
92
				$maxSize = 4194304;
93 View Code Duplication
				if ($file->getSize() > $maxSize) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
					return new DataResponse(['message' => (string)$this->l->t('This file is too big to be opened. Please download the file instead.')], Http::STATUS_BAD_REQUEST);
95
				}
96
				$fileContents = $file->getContent();
97
				if ($fileContents !== false) {
98
					$writable = $file->isUpdateable();
99
					$mime = $file->getMimeType();
100
					$mTime = $file->getMTime();
101
					$encoding = mb_detect_encoding($fileContents . 'a', 'UTF-8, WINDOWS-1252, ISO-8859-15, ISO-8859-1, ASCII', true);
102
					if ($encoding === '') {
103
						// set default encoding if it couldn't be detected
104
						$encoding = 'ISO-8859-15';
105
					}
106
					$fileContents = iconv($encoding, 'UTF-8', $fileContents);
107
					return new DataResponse(
108
						[
109
							'filecontents' => $fileContents,
110
							'writeable' => $writable,
111
							'mime' => $mime,
112
							'mtime' => $mTime
113
						],
114
						Http::STATUS_OK
115
					);
116
				} else {
117
					return new DataResponse(['message' => (string)$this->l->t('Cannot read the file.')], Http::STATUS_BAD_REQUEST);
118
				}
119
			} else {
120
				return new DataResponse(['message' => (string)$this->l->t('Invalid file path supplied.')], Http::STATUS_BAD_REQUEST);
121
			}
122
123
		} catch (LockedException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Lock\LockedException 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...
124
			$message = (string) $this->l->t('The file is locked.');
125
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
126
		} catch (ForbiddenException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\ForbiddenException 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...
127
			return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
128
		} catch (HintException $e) {
0 ignored issues
show
Bug introduced by
The class OC\HintException 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...
129
			$message = (string)$e->getHint();
130
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
131
		} catch (\Exception $e) {
132
			$message = (string)$this->l->t('An internal server error occurred.');
133
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
134
		}
135
	}
136
137
	/**
138
	 * save text file
139
	 *
140
	 * @NoAdminRequired
141
	 *
142
	 * @param string $path
143
	 * @param string $filecontents
144
	 * @param integer $mtime
145
	 * @return DataResponse
146
	 */
147
	public function save($path, $filecontents, $mtime) {
148
		try {
149
			if($path !== '' && (is_int($mtime) && $mtime > 0)) {
150
151
				/** @var File $file */
152
				$file = $this->userFolder->get($path);
153
154 View Code Duplication
				if ($file instanceof Folder) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Folder 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...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
					return new DataResponse(['message' => $this->l->t('You can not write to a folder')], Http::STATUS_BAD_REQUEST);
156
				}
157
158
				// Get file mtime
159
				$filemtime = $file->getMTime();
160
				if($mtime !== $filemtime) {
161
					// Then the file has changed since opening
162
					$this->logger->error('File: ' . $path . ' modified since opening.',
163
						['app' => 'files_texteditor']);
164
					return new DataResponse(
165
						['message' => $this->l->t('Cannot save file as it has been modified since opening')],
166
						Http::STATUS_BAD_REQUEST);
167
				} else {
168
					// File same as when opened, save file
169
					if($file->isUpdateable()) {
170
						$filecontents = iconv(mb_detect_encoding($filecontents), 'UTF-8', $filecontents);
171
						try {
172
							$file->putContent($filecontents);
173
						} catch (LockedException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Lock\LockedException 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...
174
							$message = (string) $this->l->t('The file is locked.');
175
							return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
176
						} catch (ForbiddenException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\ForbiddenException 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...
177
							return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
178
						} catch (GenericFileException $e) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\GenericFileException 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...
179
							return new DataResponse(['message' => $this->l->t('Could not write to file.')], Http::STATUS_BAD_REQUEST);
180
						}
181
						// Clear statcache
182
						clearstatcache();
183
						// Get new mtime
184
						$newmtime = $file->getMTime();
185
						$newsize = $file->getSize();
186
						return new DataResponse(['mtime' => $newmtime, 'size' => $newsize], Http::STATUS_OK);
187 View Code Duplication
					} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
						// Not writeable!
189
						$this->logger->error('User does not have permission to write to file: ' . $path,
190
							['app' => 'files_texteditor']);
191
						return new DataResponse([ 'message' => $this->l->t('Insufficient permissions')],
192
							Http::STATUS_BAD_REQUEST);
193
					}
194
				}
195
			} else if ($path === '') {
196
				$this->logger->error('No file path supplied');
197
				return new DataResponse(['message' => $this->l->t('File path not supplied')], Http::STATUS_BAD_REQUEST);
198 View Code Duplication
			} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
199
				$this->logger->error('No file mtime supplied', ['app' => 'files_texteditor']);
200
				return new DataResponse(['message' => $this->l->t('File mtime not supplied')], Http::STATUS_BAD_REQUEST);
201
			}
202
203
		} catch (HintException $e) {
0 ignored issues
show
Bug introduced by
The class OC\HintException 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...
204
			$message = (string)$e->getHint();
205
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
206
		} catch (\Exception $e) {
207
			$message = (string)$this->l->t('An internal server error occurred.');
208
			return new DataResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
209
		}
210
	}
211
212
}
213