Issues (213)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

lib/Controller/DocumentController.php (30 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 View Code Duplication
	public function __construct(
0 ignored issues
show
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...
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}', [
0 ignored issues
show
Deprecated Code introduced by
The method OCP\ILogger::debug() has been deprecated with message: 20.0.0 use \Psr\Log\LoggerInterface::debug

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...
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
$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...
Deprecated Code introduced by
The method OCP\ILogger::logException() has been deprecated with message: 20.0.0 use the `exception` entry in the context of any method in \Psr\Log\LoggerInterface

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...
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
	private function domainOnly($url) {
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
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, $relativeFolderPath, $remote
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);
0 ignored issues
show
Deprecated Code introduced by
The method OCP\ILogger::warning() has been deprecated with message: 20.0.0 use \Psr\Log\LoggerInterface::warning

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...
215
			}
216
		} catch (\Exception $e) {
217
			$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
$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...
Deprecated Code introduced by
The method OCP\ILogger::logException() has been deprecated with message: 20.0.0 use the `exception` entry in the context of any method in \Psr\Log\LoggerInterface

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...
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
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
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
$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...
Deprecated Code introduced by
The method OCP\ILogger::logException() has been deprecated with message: 20.0.0 use the `exception` entry in the context of any method in \Psr\Log\LoggerInterface

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...
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
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
$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
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
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
$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...
Deprecated Code introduced by
The method OCP\ILogger::logException() has been deprecated with message: 20.0.0 use the `exception` entry in the context of any method in \Psr\Log\LoggerInterface

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...
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
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
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
				if ($remoteWopi === null) {
448
					throw new \Exception('Invalid remote file details for ' . $remoteServerToken);
449
				}
450
				$this->tokenManager->updateToRemoteToken($wopi, $shareToken, $remoteServer, $remoteServerToken, $remoteWopi);
451
452
				$permissions = $share->getPermissions();
453
				if (!$remoteWopi['canwrite']) {
454
					$permissions = $permissions & ~ Constants::PERMISSION_UPDATE;
455
				}
456
457
				$params = [
458
					'permissions' => $permissions,
459
					'title' => $node->getName(),
460
					'fileId' => $node->getId() . '_' . $this->settings->getSystemValue('instanceid'),
461
					'token' => $token,
462
					'urlsrc' => $urlSrc,
463
					'path' => '/',
464
					'instanceId' => $this->settings->getSystemValue('instanceid'),
465
					'canonical_webroot' => $this->appConfig->getAppValue('canonical_webroot'),
466
					'userId' => $remoteWopi['editorUid'] . '@' . $remoteServer
467
				];
468
469
				$response = new TemplateResponse('richdocuments', 'documents', $params, 'base');
470
				$policy = new ContentSecurityPolicy();
471
				$policy->addAllowedFrameDomain($this->domainOnly($this->appConfig->getAppValue('wopi_url')));
472
				$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...
473
				$policy->addAllowedFrameAncestorDomain('https://*');
474
				$response->setContentSecurityPolicy($policy);
475
				$response->addHeader('X-Frame-Options', 'ALLOW');
476
				return $response;
477
			}
478
		} catch (ShareNotFound $e) {
479
			return new TemplateResponse('core', '404', [], 'guest');
480
		} catch (\Exception $e) {
481
			$this->logger->logException($e, ['app'=>'richdocuments']);
0 ignored issues
show
$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...
Deprecated Code introduced by
The method OCP\ILogger::logException() has been deprecated with message: 20.0.0 use the `exception` entry in the context of any method in \Psr\Log\LoggerInterface

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