Completed
Push — master ( 2443a5...30fba1 )
by Julius
23:37 queued 13:34
created

DocumentController   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 547
Duplicated Lines 6.95 %

Coupling/Cohesion

Components 1
Dependencies 24

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 60
lcom 1
cbo 24
dl 38
loc 547
ccs 0
cts 369
cp 0
rs 3.6
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
B extAppGetData() 0 37 6
A domainOnly() 7 7 4
B open() 0 42 6
B index() 5 62 6
A createFromTemplate() 0 43 4
B publicPage() 7 52 10
C remote() 7 61 9
C create() 12 90 14
A __construct() 0 30 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DocumentController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DocumentController, and based on these observations, apply Extract Interface, too.

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\Events\BeforeFederationRedirectEvent;
15
use OCA\Richdocuments\Service\FederationService;
16
use OCA\Richdocuments\TokenManager;
17
use \OCP\AppFramework\Controller;
18
use OCP\AppFramework\Http;
19
use OCP\AppFramework\Http\JSONResponse;
20
use OCP\AppFramework\Http\RedirectResponse;
21
use OCP\Constants;
22
use OCP\Files\File;
23
use OCP\Files\Folder;
24
use OCP\Files\GenericFileException;
25
use OCP\Files\IRootFolder;
26
use OCP\Files\Node;
27
use OCP\Files\NotFoundException;
28
use OCP\Files\NotPermittedException;
29
use \OCP\IRequest;
30
use \OCP\IConfig;
31
use \OCP\IL10N;
32
use \OCP\ILogger;
33
use \OCP\AppFramework\Http\ContentSecurityPolicy;
34
use \OCP\AppFramework\Http\TemplateResponse;
35
use \OCA\Richdocuments\AppConfig;
36
use \OCA\Richdocuments\Helper;
37
use OCP\ISession;
38
use OCP\Share\Exceptions\ShareNotFound;
39
use OCP\Share\IManager;
40
use OC\Files\Type\TemplateManager;
41
42
class DocumentController extends Controller {
43
	/** @var string */
44
	private $uid;
45
	/** @var IL10N */
46
	private $l10n;
47
	/** @var IConfig */
48
	private $settings;
49
	/** @var AppConfig */
50
	private $appConfig;
51
	/** @var ILogger */
52
	private $logger;
53
	/** @var IManager */
54
	private $shareManager;
55
	/** @var TokenManager */
56
	private $tokenManager;
57
	/** @var ISession */
58
	private $session;
59
	/** @var IRootFolder */
60
	private $rootFolder;
61
	/** @var \OCA\Richdocuments\TemplateManager */
62
	private $templateManager;
63
	/** @var FederationService */
64
	private $federationService;
65
	/** @var Helper */
66
	private $helper;
67
68
	const ODT_TEMPLATE_PATH = '/assets/odttemplate.odt';
69
70
	/**
71
	 * @param string $appName
72
	 * @param IRequest $request
73
	 * @param IConfig $settings
74
	 * @param AppConfig $appConfig
75
	 * @param IL10N $l10n
76
	 * @param IManager $shareManager
77
	 * @param TokenManager $tokenManager
78
	 * @param IRootFolder $rootFolder
79
	 * @param ISession $session
80
	 * @param string $UserId
81
	 * @param ILogger $logger
82
	 */
83
	public function __construct(
84
		$appName,
85
		IRequest $request,
86
		IConfig $settings,
87
		AppConfig $appConfig,
88
		IL10N $l10n,
89
		IManager $shareManager,
90
		TokenManager $tokenManager,
91
		IRootFolder $rootFolder,
92
		ISession $session,
93
		$UserId,
94
		ILogger $logger,
95
		\OCA\Richdocuments\TemplateManager $templateManager,
96
		FederationService $federationService,
97
		Helper $helper
98
	) {
99
		parent::__construct($appName, $request);
100
		$this->uid = $UserId;
101
		$this->l10n = $l10n;
102
		$this->settings = $settings;
103
		$this->appConfig = $appConfig;
104
		$this->shareManager = $shareManager;
105
		$this->tokenManager = $tokenManager;
106
		$this->rootFolder = $rootFolder;
107
		$this->session = $session;
108
		$this->logger = $logger;
109
		$this->templateManager = $templateManager;
110
		$this->federationService = $federationService;
111
		$this->helper = $helper;
112
	}
113
114
	/**
115
	 * @PublicPage
116
	 * @NoCSRFRequired
117
	 *
118
	 * Returns the access_token and urlsrc for WOPI access for given $fileId
119
	 * Requests is accepted only when a secret_token is provided set by admin in
120
	 * settings page
121
	 *
122
	 * @param string $fileId
123
	 * @return array access_token, urlsrc
124
	 */
125
	public function extAppGetData($fileId) {
126
		$secretToken = $this->request->getParam('secret_token');
127
		$apps = array_filter(explode(',', $this->appConfig->getAppValue('external_apps')));
128
		foreach($apps as $app) {
129
			if ($app !== '' && $secretToken === $app) {
130
				$appName = explode(':', $app);
131
				$this->logger->debug('External app "{extApp}" authenticated; issuing access token for fileId {fileId}', [
132
					'app' => $this->appName,
133
					'extApp' => $appName[0],
134
					'fileId' => $fileId
135
				]);
136
				try {
137
					$folder = $this->rootFolder->getUserFolder($this->uid);
138
					$item = $folder->getById($fileId)[0];
139
					if(!($item instanceof Node)) {
140
						throw new \Exception();
141
					}
142
					list($urlSrc, $token) = $this->tokenManager->getToken($item->getId());
143
					return [
144
						'status' => 'success',
145
						'urlsrc' => $urlSrc,
146
						'token' => $token
147
					];
148
				} catch (\Exception $e) {
149
					$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
150
					$params = [
151
						'errors' => [['error' => $e->getMessage()]]
152
					];
153
					return new TemplateResponse('core', 'error', $params, 'guest');
154
				}
155
			}
156
		}
157
		return [
158
			'status' => 'error',
159
			'message' => 'Permission denied'
160
		];
161
	}
162
163
	/**
164
	 * Strips the path and query parameters from the URL.
165
	 *
166
	 * @param string $url
167
	 * @return string
168
	 */
169 View Code Duplication
	private function domainOnly($url) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
170
		$parsed_url = parse_url($url);
171
		$scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
172
		$host   = isset($parsed_url['host']) ? $parsed_url['host'] : '';
173
		$port   = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
174
		return "$scheme$host$port";
175
	}
176
177
	/**
178
	 * Redirect to the files app with proper CSP headers set for federated editing
179
	 * This is a workaround since we cannot set a nonce for allowing dynamic URLs in the richdocument iframe
180
	 *
181
	 * @NoAdminRequired
182
	 * @NoCSRFRequired
183
	 */
184
	public function open($fileId) {
185
		try {
186
			$folder = $this->rootFolder->getUserFolder($this->uid);
187
			$item = $folder->getById($fileId)[0];
188
			if (!($item instanceof File)) {
189
				throw new \Exception('Node is not a file');
190
			}
191
192
			if ($item->getStorage()->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class)) {
193
				$remote = $item->getStorage()->getRemote();
0 ignored issues
show
Bug introduced by
The method getRemote() does not seem to exist on object<OCP\Files\Storage>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
194
				$remoteCollabora = $this->federationService->getRemoteCollaboraURL($remote);
195
				if ($remoteCollabora !== '') {
196
					$absolute = $item->getParent()->getPath();
197
					$relativeFolderPath = $folder->getRelativePath($absolute);
198
					$relativeFilePath = $folder->getRelativePath($item->getPath());
199
					$url = '/index.php/apps/files/?dir=' . $relativeFolderPath .
200
						'&richdocuments_open=' . $relativeFilePath .
201
						'&richdocuments_fileId=' . $fileId .
202
						'&richdocuments_remote_access=' . $remote;
203
204
						$event = new BeforeFederationRedirectEvent(
205
							$item, $relative, $remote
0 ignored issues
show
Bug introduced by
The variable $relative does not exist. Did you mean $relativeFolderPath?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
206
						);
207
						$eventDispatcher = \OC::$server->getEventDispatcher();
208
						$eventDispatcher->dispatch(BeforeFederationRedirectEvent::class, $event);
209
						if ($event->getRedirectUrl()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $event->getRedirectUrl() of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
210
							$url = $event->getRedirectUrl();
211
						}
212
					return new RedirectResponse($url);
213
				}
214
				$this->logger->warning('Failed to connect to remote collabora instance for ' . $fileId);
215
			}
216
		} catch (\Exception $e) {
217
			$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
218
			$params = [
219
				'errors' => [['error' => $e->getMessage()]]
220
			];
221
			return new TemplateResponse('core', 'error', $params, 'guest');
222
		}
223
224
		return new TemplateResponse('core', '403', [], 'guest');
225
	}
226
227
	/**
228
	 * @NoAdminRequired
229
	 *
230
	 * @param string $fileId
231
	 * @param string|null $path
232
	 * @return RedirectResponse|TemplateResponse
233
	 */
234
	public function index($fileId, $path = null) {
235
		try {
236
			$folder = $this->rootFolder->getUserFolder($this->uid);
237
238
			if ($path !== null) {
239
				$item = $folder->get($path);
240
			} else {
241
				$item = $folder->getById($fileId)[0];
242
			}
243
244
			if(!($item instanceof File)) {
245
				throw new \Exception();
246
			}
247
248
			/** Open file from remote collabora */
249
			$federatedUrl = $this->federationService->getRemoteRedirectURL($item);
250 View Code Duplication
			if ($federatedUrl !== null) {
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...
251
				$response = new RedirectResponse($federatedUrl);
252
				$response->addHeader('X-Frame-Options', 'ALLOW');
253
				return $response;
254
			}
255
256
			list($urlSrc, $token, $wopi) = $this->tokenManager->getToken($item->getId());
0 ignored issues
show
Unused Code introduced by
The assignment to $wopi is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
257
			$params = [
258
				'permissions' => $item->getPermissions(),
259
				'title' => $item->getName(),
260
				'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
261
				'token' => $token,
262
				'urlsrc' => $urlSrc,
263
				'path' => $folder->getRelativePath($item->getPath()),
264
				'instanceId' => $this->settings->getSystemValue('instanceid'),
265
				'canonical_webroot' => $this->appConfig->getAppValue('canonical_webroot'),
266
				'userId' => $this->uid
267
			];
268
269
			$encryptionManager = \OC::$server->getEncryptionManager();
270
			if ($encryptionManager->isEnabled())
271
			{
272
				// Update the current file to be accessible with system public shared key
273
				$owner = $item->getOwner()->getUID();
274
				$absPath = '/' . $owner . '/' .  $item->getInternalPath();
275
				$accessList = \OC::$server->getEncryptionFilesHelper()->getAccessList($absPath);
276
				$accessList['public'] = true;
277
				$encryptionManager->getEncryptionModule()->update($absPath, $owner, $accessList);
278
			}
279
280
			$response = new TemplateResponse('richdocuments', 'documents', $params, 'base');
281
			$policy = new ContentSecurityPolicy();
282
			$policy->addAllowedFrameDomain($this->domainOnly($this->appConfig->getAppValue('public_wopi_url')));
283
			$policy->allowInlineScript(true);
0 ignored issues
show
Deprecated Code introduced by
The method OCP\AppFramework\Http\Em...cy::allowInlineScript() has been deprecated with message: 10.0 CSP tokens are now used

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...
284
			$response->setContentSecurityPolicy($policy);
285
			return $response;
286
		} catch (\Exception $e) {
287
			$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
288
			$params = [
289
				'errors' => [['error' => $e->getMessage()]]
290
			];
291
			return new TemplateResponse('core', 'error', $params, 'guest');
292
		}
293
294
		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...
295
	}
296
297
	/**
298
	 * @NoAdminRequired
299
	 *
300
	 * Create a new file from a template
301
	 *
302
	 * @param int $templateId
303
	 * @param string $fileName
304
	 * @param string $dir
305
	 * @return TemplateResponse
306
	 * @throws NotFoundException
307
	 * @throws NotPermittedException
308
	 * @throws \OCP\Files\InvalidPathException
309
	 */
310
	public function createFromTemplate($templateId, $fileName, $dir) {
311
		if (!$this->templateManager->isTemplate($templateId)) {
312
			return new TemplateResponse('core', '403', [], 'guest');
313
		}
314
315
		$userFolder = $this->rootFolder->getUserFolder($this->uid);
316
		try {
317
			$folder = $userFolder->get($dir);
318
		} catch (NotFoundException $e) {
319
			return new TemplateResponse('core', '403', [], 'guest');
320
		}
321
322
		if (!$folder instanceof Folder) {
323
			return new TemplateResponse('core', '403', [], 'guest');
324
		}
325
326
		$file = $folder->newFile($fileName);
327
328
		$template = $this->templateManager->get($templateId);
329
		list($urlSrc, $wopi) = $this->tokenManager->getTokenForTemplate($template, $this->uid, $file->getId());
330
331
		$wopiFileId = $template->getId() . '-' . $file->getId() . '_' . $this->settings->getSystemValue('instanceid');
0 ignored issues
show
Unused Code introduced by
$wopiFileId 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...
332
		$wopiFileId = $wopi->getFileid() . '_' . $this->settings->getSystemValue('instanceid');
333
334
		$params = [
335
			'permissions' => $template->getPermissions(),
336
			'title' => $fileName,
337
			'fileId' => $wopiFileId,
338
			'token' => $wopi->getToken(),
339
			'urlsrc' => $urlSrc,
340
			'path' => $userFolder->getRelativePath($file->getPath()),
341
			'instanceId' => $this->settings->getSystemValue('instanceid'),
342
			'canonical_webroot' => $this->appConfig->getAppValue('canonical_webroot'),
343
			'userId' => $this->uid
344
		];
345
346
		$response = new TemplateResponse('richdocuments', 'documents', $params, 'base');
347
		$policy = new ContentSecurityPolicy();
348
		$policy->addAllowedFrameDomain($this->domainOnly($this->appConfig->getAppValue('public_wopi_url')));
349
		$policy->allowInlineScript(true);
0 ignored issues
show
Deprecated Code introduced by
The method OCP\AppFramework\Http\Em...cy::allowInlineScript() has been deprecated with message: 10.0 CSP tokens are now used

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...
350
		$response->setContentSecurityPolicy($policy);
351
		return $response;
352
	}
353
354
	/**
355
	 * @PublicPage
356
	 * @NoCSRFRequired
357
	 *
358
	 * @param string $shareToken
359
	 * @param string $fileName
360
	 * @return TemplateResponse
361
	 * @throws \Exception
362
	 */
363
	public function publicPage($shareToken, $fileName, $fileId) {
0 ignored issues
show
Unused Code introduced by
The parameter $fileName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
364
		try {
365
			$share = $this->shareManager->getShareByToken($shareToken);
366
			// not authenticated ?
367 View Code Duplication
			if($share->getPassword()){
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...
368
				if (!$this->session->exists('public_link_authenticated')
369
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
370
				) {
371
					throw new \Exception('Invalid password');
372
				}
373
			}
374
375
			$node = $share->getNode();
376
			if($node instanceof Folder) {
377
				$item = $node->getById($fileId)[0];
378
			} else {
379
				$item = $node;
380
			}
381
			if ($item instanceof Node) {
382
				$params = [
383
					'permissions' => $share->getPermissions(),
384
					'title' => $item->getName(),
385
					'fileId' => $item->getId() . '_' . $this->settings->getSystemValue('instanceid'),
386
					'path' => '/',
387
					'instanceId' => $this->settings->getSystemValue('instanceid'),
388
					'canonical_webroot' => $this->appConfig->getAppValue('canonical_webroot'),
389
					'userId' => $this->uid,
390
				];
391
392
				if ($this->uid !== null || ($share->getPermissions() & \OCP\Constants::PERMISSION_UPDATE) === 0 || $this->helper->getGuestName() !== null) {
393
					list($urlSrc, $token) = $this->tokenManager->getToken($item->getId(), $shareToken, $this->uid);
394
					$params['token'] = $token;
395
					$params['urlsrc'] = $urlSrc;
396
				}
397
398
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'base');
399
				$policy = new ContentSecurityPolicy();
400
				$policy->addAllowedFrameDomain($this->domainOnly($this->appConfig->getAppValue('public_wopi_url')));
401
				$policy->allowInlineScript(true);
0 ignored issues
show
Deprecated Code introduced by
The method OCP\AppFramework\Http\Em...cy::allowInlineScript() has been deprecated with message: 10.0 CSP tokens are now used

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...
402
				$response->setContentSecurityPolicy($policy);
403
				return $response;
404
			}
405
		} catch (\Exception $e) {
406
			$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
407
			$params = [
408
				'errors' => [['error' => $e->getMessage()]]
409
			];
410
			return new TemplateResponse('core', 'error', $params, 'guest');
411
		}
412
413
		return new TemplateResponse('core', '403', [], 'guest');
414
	}
415
416
	/**
417
	 * @PublicPage
418
	 * @NoCSRFRequired
419
	 *
420
	 * @param string $shareToken
421
	 * @param $remoteServer
422
	 * @param $remoteServerToken
423
	 * @param null $filePath
424
	 * @return TemplateResponse
425
	 */
426
	public function remote($shareToken, $remoteServer, $remoteServerToken, $filePath = null) {
427
		try {
428
			$share = $this->shareManager->getShareByToken($shareToken);
429
			// not authenticated ?
430 View Code Duplication
			if($share->getPassword()){
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...
431
				if (!$this->session->exists('public_link_authenticated')
432
					|| $this->session->get('public_link_authenticated') !== (string)$share->getId()
433
				) {
434
					throw new \Exception('Invalid password');
435
				}
436
			}
437
438
			$node = $share->getNode();
439
			if ($filePath !== null) {
440
				$node = $node->get($filePath);
0 ignored issues
show
Bug introduced by
The method get does only exist in OCP\Files\Folder, but not in OCP\Files\File.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
441
			}
442
443
			if ($node instanceof Node) {
444
				list($urlSrc, $token, $wopi) = $this->tokenManager->getToken($node->getId(), $shareToken, $this->uid);
445
446
				$remoteWopi = $this->federationService->getRemoteFileDetails($remoteServer, $remoteServerToken);
447
				$this->tokenManager->updateToRemoteToken($wopi, $shareToken, $remoteServer, $remoteServerToken, $remoteWopi);
448
449
				$permissions = $share->getPermissions();
450
				if (!$remoteWopi['canwrite']) {
451
					$permissions = $permissions & ~ Constants::PERMISSION_UPDATE;
452
				}
453
454
				$params = [
455
					'permissions' => $permissions,
456
					'title' => $node->getName(),
457
					'fileId' => $node->getId() . '_' . $this->settings->getSystemValue('instanceid'),
458
					'token' => $token,
459
					'urlsrc' => $urlSrc,
460
					'path' => '/',
461
					'instanceId' => $this->settings->getSystemValue('instanceid'),
462
					'canonical_webroot' => $this->appConfig->getAppValue('canonical_webroot'),
463
					'userId' => $remoteWopi['editorUid'] . '@' . $remoteServer
464
				];
465
466
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'base');
467
				$policy = new ContentSecurityPolicy();
468
				$policy->addAllowedFrameDomain($this->domainOnly($this->appConfig->getAppValue('wopi_url')));
469
				$policy->allowInlineScript(true);
0 ignored issues
show
Deprecated Code introduced by
The method OCP\AppFramework\Http\Em...cy::allowInlineScript() has been deprecated with message: 10.0 CSP tokens are now used

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...
470
				$policy->addAllowedFrameAncestorDomain('https://*');
471
				$response->setContentSecurityPolicy($policy);
472
				$response->addHeader('X-Frame-Options', 'ALLOW');
473
				return $response;
474
			}
475
		} catch (ShareNotFound $e) {
476
			return new TemplateResponse('core', '404', [], 'guest');
477
		} catch (\Exception $e) {
478
			$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
479
			$params = [
480
				'errors' => [['error' => $e->getMessage()]]
481
			];
482
			return new TemplateResponse('core', 'error', $params, 'guest');
483
		}
484
485
		return new TemplateResponse('core', '403', [], 'guest');
486
	}
487
488
	/**
489
	 * @NoAdminRequired
490
	 *
491
	 * @param string $mimetype
492
	 * @param string $filename
493
	 * @param string $dir
494
	 * @return JSONResponse
495
	 * @throws NotPermittedException
496
	 * @throws GenericFileException
497
	 */
498
	public function create($mimetype,
499
						   $filename,
500
						   $dir = '/'){
501
502
		$root = $this->rootFolder->getUserFolder($this->uid);
503
		try {
504
			/** @var Folder $folder */
505
			$folder = $root->get($dir);
506
		} catch (NotFoundException $e) {
507
			return new JSONResponse([
508
					'status' => 'error',
509
					'message' => $this->l10n->t('Can\'t create document')
510
			], Http::STATUS_BAD_REQUEST);
511
		}
512
513 View Code Duplication
		if (!($folder instanceof Folder)) {
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...
514
			return new JSONResponse([
515
				'status' => 'error',
516
				'message' => $this->l10n->t('Can\'t create document')
517
			], Http::STATUS_BAD_REQUEST);
518
		}
519
520
		$basename = $this->l10n->t('New Document.odt');
521
		switch ($mimetype) {
522
			case 'application/vnd.oasis.opendocument.spreadsheet':
523
				$basename = $this->l10n->t('New Spreadsheet.ods');
524
				break;
525
			case 'application/vnd.oasis.opendocument.presentation':
526
				$basename = $this->l10n->t('New Presentation.odp');
527
				break;
528
			case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
529
				$basename = $this->l10n->t('New Document.docx');
530
				break;
531
			case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
532
				$basename = $this->l10n->t('New Spreadsheet.xlsx');
533
				break;
534
			case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
535
				$basename = $this->l10n->t('New Presentation.pptx');
536
				break;
537
			default:
538
				// to be safe
539
				$mimetype = 'application/vnd.oasis.opendocument.text';
540
				break;
541
		}
542
543
		if (!$filename){
544
			$filename = Helper::getNewFileName($folder, $basename);
545
		}
546
547 View Code Duplication
		if ($folder->nodeExists($filename)) {
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...
548
			return new JSONResponse([
549
				'status' => 'error',
550
				'message' => $this->l10n->t('Document already exists')
551
			], Http::STATUS_BAD_REQUEST);
552
		}
553
554
		try {
555
			$file = $folder->newFile($filename);
556
		} catch (NotPermittedException $e) {
557
			return new JSONResponse([
558
				'status' => 'error',
559
				'message' => $this->l10n->t('Not allowed to create document')
560
			], Http::STATUS_BAD_REQUEST);
561
		}
562
563
		$content = '';
564
		if (class_exists(TemplateManager::class)){
565
			$manager = \OC_Helper::getFileTemplateManager();
566
			$content = $manager->getTemplate($mimetype);
567
		}
568
569
		if (!$content){
570
			$content = file_get_contents(dirname(dirname(__DIR__)) . self::ODT_TEMPLATE_PATH);
571
		}
572
573
		if ($content) {
574
			$file->putContent($content);
575
576
			return new JSONResponse([
577
				'status' => 'success',
578
				'data' => \OCA\Files\Helper::formatFileInfo($file->getFileInfo())
0 ignored issues
show
Bug introduced by
The method getFileInfo() does not seem to exist on object<OCP\Files\File>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
579
			]);
580
		}
581
582
583
		return new JSONResponse([
584
			'status' => 'error',
585
			'message' => $this->l10n->t('Can\'t create document')
586
		]);
587
	}
588
}
589