Completed
Push — master ( efc3d5...9b88e6 )
by Andras
04:40
created

DocumentController::publicPage()   B

Complexity

Conditions 7
Paths 44

Size

Total Lines 55
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 55
ccs 0
cts 51
cp 0
rs 7.8235
cc 7
eloc 42
nc 44
nop 2
crap 56

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
 * ownCloud - Richdocuments App
4
 *
5
 * @author Victor Dubiniuk
6
 * @copyright 2014 Victor Dubiniuk [email protected]
7
 *
8
 * This file is licensed under the Affero General Public License version 3 or
9
 * later.
10
 */
11
12
namespace OCA\Richdocuments\Controller;
13
14
use OCA\Richdocuments\TokenManager;
15
use OCA\Richdocuments\WOPI\Parser;
16
use \OCP\AppFramework\Controller;
17
use OCP\AppFramework\Http\JSONResponse;
18
use OCP\Files\Folder;
19
use OCP\Files\IRootFolder;
20
use OCP\Files\Node;
21
use \OCP\IRequest;
22
use \OCP\IConfig;
23
use \OCP\IL10N;
24
use \OCP\ILogger;
25
use \OCP\AppFramework\Http\ContentSecurityPolicy;
26
use \OCP\AppFramework\Http\TemplateResponse;
27
use \OCA\Richdocuments\AppConfig;
28
use \OCA\Richdocuments\Helper;
29
use \OC\Files\View;
30
use OCP\ISession;
31
use OCP\Share\IManager;
32
33
class DocumentController extends Controller {
34
	/** @var string */
35
	private $uid;
36
	/** @var IL10N */
37
	private $l10n;
38
	/** @var IConfig */
39
	private $settings;
40
	/** @var AppConfig */
41
	private $appConfig;
42
	/** @var ILogger */
43
	private $logger;
44
	/** @var Parser */
45
	private $wopiParser;
46
	/** @var IManager */
47
	private $shareManager;
48
	/** @var TokenManager */
49
	private $tokenManager;
50
	/** @var ISession */
51
	private $session;
52
	/** @var IRootFolder */
53
	private $rootFolder;
54
55
	const ODT_TEMPLATE_PATH = '/assets/odttemplate.odt';
56
57
	/**
58
	 * @param string $appName
59
	 * @param IRequest $request
60
	 * @param IConfig $settings
61
	 * @param AppConfig $appConfig
62
	 * @param IL10N $l10n
63
	 * @param Parser $wopiParser
64
	 * @param IManager $shareManager
65
	 * @param TokenManager $tokenManager
66
	 * @param IRootFolder $rootFolder
67
	 * @param ISession $session
68
	 * @param string $UserId
69
	 */
70
	public function __construct($appName,
71
								IRequest $request,
72
								IConfig $settings,
73
								AppConfig $appConfig,
74
								IL10N $l10n,
75
								Parser $wopiParser,
76
								IManager $shareManager,
77
								TokenManager $tokenManager,
78
								IRootFolder $rootFolder,
79
								ISession $session,
80
								$UserId,
81
								ILogger $logger) {
82
		parent::__construct($appName, $request);
83
		$this->uid = $UserId;
84
		$this->l10n = $l10n;
85
		$this->settings = $settings;
86
		$this->appConfig = $appConfig;
87
		$this->wopiParser = $wopiParser;
88
		$this->shareManager = $shareManager;
89
		$this->tokenManager = $tokenManager;
90
		$this->rootFolder = $rootFolder;
91
		$this->session = $session;
92
		$this->logger = $logger;
93
	}
94
95
	/**
96
	 * @NoAdminRequired
97
	 *
98
	 * @param string $fileId
99
	 * @return TemplateResponse
100
	 */
101
	public function index($fileId) {
102
		try {
103
			$folder = $this->rootFolder->getUserFolder($this->uid);
104
			$item = $folder->getById($fileId)[0];
105
			if(!($item instanceof Node)) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Node 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...
106
				throw new \Exception();
107
			}
108
			list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
109
			$params = [
110
				'permissions' => $item->getPermissions(),
111
				'title' => $item->getName(),
112
				'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
113
				'token' => $token,
114
				'urlsrc' => $urlSrc,
115
				'path' => $folder->getRelativePath($item->getPath()),
116
				'instanceId' => $this->settings->getSystemValue('instanceid'),
117
			];
118
119
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
120
			$policy = new ContentSecurityPolicy();
121
			$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
122
			$policy->allowInlineScript(true);
123
			$response->setContentSecurityPolicy($policy);
124
			return $response;
125
		} catch (\Exception $e) {
126
			$this->logger->logException($e, ['app'=>'richdocuments']);
127
			$params = [
128
				'remoteAddr' => $this->request->getRemoteAddress(),
129
				'requestID' => $this->request->getId(),
130
				'debugMode' => $this->settings->getSystemValue('debug'),
131
				'errorClass' => get_class($e),
132
				'errorCode' => $e->getCode(),
133
				'errorMsg' => $e->getMessage(),
134
				'file' => $e->getFile(),
135
				'line' => $e->getLine(),
136
				'trace' => $e->getTraceAsString()
137
			];
138
			return new TemplateResponse('core', 'exception', $params, 'guest');
139
		}
140
141
		return new TemplateResponse('core', '403', [], 'guest');
0 ignored issues
show
Unused Code introduced by
return new \OCP\AppFrame...03', array(), 'guest'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
142
	}
143
144
	/**
145
	 * @PublicPage
146
	 *
147
	 * @param string $shareToken
148
	 * @param string $fileName
149
	 * @return TemplateResponse
150
	 * @throws \Exception
151
	 */
152
	public function publicPage($shareToken, $fileName) {
153
		try {
154
			$share = $this->shareManager->getShareByToken($shareToken);
155
			// not authenticated ?
156
			if($share->getPassword()){
157
				if (!$this->session->exists('public_link_authenticated')
158
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
159
				) {
160
					throw new \Exception('Invalid password');
161
				}
162
			}
163
164
			$node = $share->getNode();
165
			if($node 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...
166
				$item = $node->get($fileName);
167
			} else {
168
				$item = $node;
169
			}
170
			if ($item instanceof Node) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\Node 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...
171
				list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
172
				$params = [
173
					'permissions' => $share->getPermissions(),
174
					'title' => $item->getName(),
175
					'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
176
					'token' => $token,
177
					'urlsrc' => $urlSrc,
178
					'path' => '/',
179
					'instanceId' => $this->settings->getSystemValue('instanceid'),
180
				];
181
182
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
183
				$policy = new ContentSecurityPolicy();
184
				$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
185
				$policy->allowInlineScript(true);
186
				$response->setContentSecurityPolicy($policy);
187
				return $response;
188
			}
189
		} catch (\Exception $e) {
190
			$this->logger->logException($e, ['app'=>'richdocuments']);
191
			$params = [
192
				'remoteAddr' => $this->request->getRemoteAddress(),
193
				'requestID' => $this->request->getId(),
194
				'debugMode' => $this->settings->getSystemValue('debug'),
195
				'errorClass' => get_class($e),
196
				'errorCode' => $e->getCode(),
197
				'errorMsg' => $e->getMessage(),
198
				'file' => $e->getFile(),
199
				'line' => $e->getLine(),
200
				'trace' => $e->getTraceAsString()
201
			];
202
			return new TemplateResponse('core', 'exception', $params, 'guest');
203
		}
204
205
		return new TemplateResponse('core', '403', [], 'guest');
206
	}
207
208
	/**
209
	 * @NoAdminRequired
210
	 *
211
	 * @param string $mimetype
212
	 * @param string $filename
213
	 * @param string $dir
214
	 * @return JSONResponse
215
	 */
216
	public function create($mimetype,
217
						   $filename,
218
						   $dir){
219
220
		$view = new View('/' . $this->uid . '/files');
221
		if (!$dir){
222
			$dir = '/';
223
		}
224
225
		$basename = $this->l10n->t('New Document.odt');
226
		switch ($mimetype) {
227
			case 'application/vnd.oasis.opendocument.spreadsheet':
228
				$basename = $this->l10n->t('New Spreadsheet.ods');
229
				break;
230
			case 'application/vnd.oasis.opendocument.presentation':
231
				$basename = $this->l10n->t('New Presentation.odp');
232
				break;
233
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
234
				$basename = $this->l10n->t('New Document.docx');
235
				break;
236
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
237
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
238
				break;
239
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
240
				$basename = $this->l10n->t('New Presentation.pptx');
241
				break;
242
			default:
243
				// to be safe
244
				$mimetype = 'application/vnd.oasis.opendocument.text';
245
				break;
246
		}
247
248
		if (!$filename){
249
			$path = Helper::getNewFileName($view, $dir . '/' . $basename);
250
		} else {
251
			$path = $dir . '/' . $filename;
252
		}
253
254
		$content = '';
255
		if (class_exists('\OC\Files\Type\TemplateManager')){
256
			$manager = \OC_Helper::getFileTemplateManager();
257
			$content = $manager->getTemplate($mimetype);
258
		}
259
260
		if (!$content){
261
			$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
262
		}
263
264
		if ($content && $view->file_put_contents($path, $content)) {
265
			$info = $view->getFileInfo($path);
266
			$ret = $this->wopiParser->getUrlSrc($mimetype);
0 ignored issues
show
Unused Code introduced by
$ret is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
267
			$response =  array(
268
				'status' => 'success',
269
				'data' => \OCA\Files\Helper::formatFileInfo($info)
270
			);
271
		} else {
272
			$response =  array(
273
				'status' => 'error',
274
				'message' => (string) $this->l10n->t('Can\'t create document')
275
			);
276
		}
277
278
		return $response;
279
	}
280
}
281