Completed
Push — master ( fec3a7...a08c0b )
by Andras
02:21
created

DocumentController::index()   A

Complexity

Conditions 4
Paths 24

Size

Total Lines 54
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 54
ccs 0
cts 50
cp 0
rs 9.0306
cc 4
eloc 43
nc 24
nop 1
crap 20

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
	 * @PublicPage
97
	 * @NoCSRFRequired
98
	 *
99
	 * Returns the access_token and urlsrc for WOPI access for given $fileId
100
	 * Requests is accepted only when a secret_token is provided set by admin in
101
	 * settings page
102
	 *
103
	 * @param string $fileId
104
	 * @return access_token, urlsrc
0 ignored issues
show
Documentation introduced by
The doc-type access_token, could not be parsed: Expected "|" or "end of type", but got "," at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
105
	 */
106
	public function extAppGetData($fileId) {
107
		$secretToken = $this->request->getParam('secret_token');
108
		$apps = array_filter(explode(',', $this->appConfig->getAppValue('external_apps')));
109
		foreach($apps as $app) {
110
			if ($app !== '') {
111
				if ($secretToken === $app) {
112
					$appName = explode(':', $app);
113
					\OC::$server->getLogger()->debug('External app "{extApp}" authenticated; issuing access token for fileId {fileId}', [
114
						'app' => $this->appName,
115
						'extApp' => $appName[0],
116
						'fileId' => $fileId
117
					]);
118
					try {
119
						$folder = $this->rootFolder->getUserFolder($this->uid);
120
						$item = $folder->getById($fileId)[0];
121
						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...
122
							throw new \Exception();
123
						}
124
						list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
125
						return array(
126
							'status' => 'success',
127
							'urlsrc' => $urlSrc,
128
							'token' => $token
129
						);
130
					} catch (\Exception $e) {
131
						$this->logger->logException($e, ['app'=>'richdocuments']);
132
						$params = [
133
							'remoteAddr' => $this->request->getRemoteAddress(),
134
							'requestID' => $this->request->getId(),
135
							'debugMode' => $this->settings->getSystemValue('debug'),
136
							'errorClass' => get_class($e),
137
							'errorCode' => $e->getCode(),
138
							'errorMsg' => $e->getMessage(),
139
							'file' => $e->getFile(),
140
							'line' => $e->getLine(),
141
							'trace' => $e->getTraceAsString()
142
						];
143
						return new TemplateResponse('core', 'exception', $params, 'guest');
144
					}
145
				}
146
			}
147
148
			return array(
149
				'status' => 'error',
150
				'message' => 'Permission denied'
151
			);
152
		}
153
	}
154
155
	/**
156
	 * @NoAdminRequired
157
	 *
158
	 * @param string $fileId
159
	 * @return TemplateResponse
160
	 */
161
	public function index($fileId) {
162
		try {
163
			$folder = $this->rootFolder->getUserFolder($this->uid);
164
			$item = $folder->getById($fileId)[0];
165
			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...
166
				throw new \Exception();
167
			}
168
			list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
169
			$params = [
170
				'permissions' => $item->getPermissions(),
171
				'title' => $item->getName(),
172
				'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
173
				'token' => $token,
174
				'urlsrc' => $urlSrc,
175
				'path' => $folder->getRelativePath($item->getPath()),
176
				'instanceId' => $this->settings->getSystemValue('instanceid'),
177
				'canonical_webroot' => $this->appConfig->getAppValue('canonical_webroot'),
178
			];
179
180
			$encryptionManager = \OC::$server->getEncryptionManager();
181
			if ($encryptionManager->isEnabled())
182
			{
183
				// Update the current file to be accessible with system public shared key
184
				$owner = $item->getOwner()->getUID();
185
				$absPath = '/' . $owner . '/' .  $item->getInternalPath();
186
				$accessList = \OC::$server->getEncryptionFilesHelper()->getAccessList($absPath);
187
				$accessList['public'] = true;
188
				$encryptionManager->getEncryptionModule()->update($absPath, $owner, $accessList);
189
			}
190
191
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
192
			$policy = new ContentSecurityPolicy();
193
			$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
194
			$policy->allowInlineScript(true);
195
			$response->setContentSecurityPolicy($policy);
196
			return $response;
197
		} catch (\Exception $e) {
198
			$this->logger->logException($e, ['app'=>'richdocuments']);
199
			$params = [
200
				'remoteAddr' => $this->request->getRemoteAddress(),
201
				'requestID' => $this->request->getId(),
202
				'debugMode' => $this->settings->getSystemValue('debug'),
203
				'errorClass' => get_class($e),
204
				'errorCode' => $e->getCode(),
205
				'errorMsg' => $e->getMessage(),
206
				'file' => $e->getFile(),
207
				'line' => $e->getLine(),
208
				'trace' => $e->getTraceAsString()
209
			];
210
			return new TemplateResponse('core', 'exception', $params, 'guest');
211
		}
212
213
		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...
214
	}
215
216
	/**
217
	 * @PublicPage
218
	 *
219
	 * @param string $shareToken
220
	 * @param string $fileName
221
	 * @return TemplateResponse
222
	 * @throws \Exception
223
	 */
224
	public function publicPage($shareToken, $fileName, $fileId) {
225
		try {
226
			$share = $this->shareManager->getShareByToken($shareToken);
227
			// not authenticated ?
228
			if($share->getPassword()){
229
				if (!$this->session->exists('public_link_authenticated')
230
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
231
				) {
232
					throw new \Exception('Invalid password');
233
				}
234
			}
235
236
			$node = $share->getNode();
237
			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...
238
				$item = $node->getById($fileId)[0];
239
			} else {
240
				$item = $node;
241
			}
242
			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...
243
				list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken);
244
				$params = [
245
					'permissions' => $share->getPermissions(),
246
					'title' => $item->getName(),
247
					'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
248
					'token' => $token,
249
					'urlsrc' => $urlSrc,
250
					'path' => '/',
251
					'instanceId' => $this->settings->getSystemValue('instanceid'),
252
				];
253
254
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'empty');
255
				$policy = new ContentSecurityPolicy();
256
				$policy->addAllowedFrameDomain($this->appConfig->getAppValue('wopi_url'));
257
				$policy->allowInlineScript(true);
258
				$response->setContentSecurityPolicy($policy);
259
				return $response;
260
			}
261
		} catch (\Exception $e) {
262
			$this->logger->logException($e, ['app'=>'richdocuments']);
263
			$params = [
264
				'remoteAddr' => $this->request->getRemoteAddress(),
265
				'requestID' => $this->request->getId(),
266
				'debugMode' => $this->settings->getSystemValue('debug'),
267
				'errorClass' => get_class($e),
268
				'errorCode' => $e->getCode(),
269
				'errorMsg' => $e->getMessage(),
270
				'file' => $e->getFile(),
271
				'line' => $e->getLine(),
272
				'trace' => $e->getTraceAsString()
273
			];
274
			return new TemplateResponse('core', 'exception', $params, 'guest');
275
		}
276
277
		return new TemplateResponse('core', '403', [], 'guest');
278
	}
279
280
	/**
281
	 * @NoAdminRequired
282
	 *
283
	 * @param string $mimetype
284
	 * @param string $filename
285
	 * @param string $dir
286
	 * @return JSONResponse
287
	 */
288
	public function create($mimetype,
289
						   $filename,
290
						   $dir){
291
292
		$view = new View('/' . $this->uid . '/files');
293
		if (!$dir){
294
			$dir = '/';
295
		}
296
297
		$basename = $this->l10n->t('New Document.odt');
298
		switch ($mimetype) {
299
			case 'application/vnd.oasis.opendocument.spreadsheet':
300
				$basename = $this->l10n->t('New Spreadsheet.ods');
301
				break;
302
			case 'application/vnd.oasis.opendocument.presentation':
303
				$basename = $this->l10n->t('New Presentation.odp');
304
				break;
305
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
306
				$basename = $this->l10n->t('New Document.docx');
307
				break;
308
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
309
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
310
				break;
311
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
312
				$basename = $this->l10n->t('New Presentation.pptx');
313
				break;
314
			default:
315
				// to be safe
316
				$mimetype = 'application/vnd.oasis.opendocument.text';
317
				break;
318
		}
319
320
		if (!$filename){
321
			$path = Helper::getNewFileName($view, $dir . '/' . $basename);
322
		} else {
323
			$path = $dir . '/' . $filename;
324
		}
325
326
		$content = '';
327
		if (class_exists('\OC\Files\Type\TemplateManager')){
328
			$manager = \OC_Helper::getFileTemplateManager();
329
			$content = $manager->getTemplate($mimetype);
330
		}
331
332
		if (!$content){
333
			$content = file_get_contents(dirname(__DIR__) . self::ODT_TEMPLATE_PATH);
334
		}
335
336
		if ($content && $view->file_put_contents($path, $content)) {
337
			$info = $view->getFileInfo($path);
338
			$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...
339
			$response =  array(
340
				'status' => 'success',
341
				'data' => \OCA\Files\Helper::formatFileInfo($info)
342
			);
343
		} else {
344
			$response =  array(
345
				'status' => 'error',
346
				'message' => (string) $this->l10n->t('Can\'t create document')
347
			);
348
		}
349
350
		return $response;
351
	}
352
}
353