Completed
Pull Request — master (#32303)
by Victor
09:29
created

RequestHandlerController::createShare()   C

Complexity

Conditions 10
Paths 100

Size

Total Lines 87

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 100
nop 0
dl 0
loc 87
rs 6.4169
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
 * @author Arthur Schiwon <[email protected]>
4
 * @author Björn Schießle <[email protected]>
5
 * @author Joas Schilling <[email protected]>
6
 * @author Lukas Reschke <[email protected]>
7
 * @author Morris Jobke <[email protected]>
8
 * @author Thomas Müller <[email protected]>
9
 *
10
 * @copyright Copyright (c) 2018, ownCloud GmbH
11
 * @license AGPL-3.0
12
 *
13
 * This code is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License, version 3,
15
 * as published by the Free Software Foundation.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License, version 3,
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
24
 *
25
 */
26
27
namespace OCA\FederatedFileSharing\Controller;
28
29
use OC\OCS\Result;
30
use OCA\FederatedFileSharing\Address;
31
use OCA\FederatedFileSharing\AddressHandler;
32
use OCA\FederatedFileSharing\Exception\NotSupportedException;
33
use OCA\FederatedFileSharing\Exception\InvalidShareException;
34
use OCA\FederatedFileSharing\FederatedShareProvider;
35
use OCA\FederatedFileSharing\FedShareManager;
36
use OCP\App\IAppManager;
37
use OCP\AppFramework\Http;
38
use OCP\AppFramework\OCSController;
39
use OCP\Constants;
40
use OCP\IRequest;
41
use OCP\IUserManager;
42
use OCP\Share;
43
use OCP\Share\IShare;
44
45
/**
46
 * Class RequestHandlerController
47
 *
48
 * Handles OCS Request to the federated share API
49
 *
50
 * @package OCA\FederatedFileSharing\API
51
 */
52
class RequestHandlerController extends OCSController {
53
54
	/** @var FederatedShareProvider */
55
	private $federatedShareProvider;
56
57
	/** @var IAppManager */
58
	private $appManager;
59
60
	/** @var IUserManager */
61
	private $userManager;
62
63
	/** @var AddressHandler */
64
	private $addressHandler;
65
66
	/** @var  FedShareManager */
67
	private $fedShareManager;
68
69
	/**
70
	 * Server2Server constructor.
71
	 *
72
	 * @param string $appName
73
	 * @param IRequest $request
74
	 * @param FederatedShareProvider $federatedShareProvider
75
	 * @param IAppManager $appManager
76
	 * @param IUserManager $userManager
77
	 * @param AddressHandler $addressHandler
78
	 * @param FedShareManager $fedShareManager
79
	 */
80 View Code Duplication
	public function __construct($appName,
81
								IRequest $request,
82
								FederatedShareProvider $federatedShareProvider,
83
								IAppManager $appManager,
84
								IUserManager $userManager,
85
								AddressHandler $addressHandler,
86
								FedShareManager $fedShareManager
87
	) {
88
		parent::__construct($appName, $request);
89
90
		$this->federatedShareProvider = $federatedShareProvider;
91
		$this->appManager = $appManager;
92
		$this->userManager = $userManager;
93
		$this->addressHandler = $addressHandler;
94
		$this->fedShareManager = $fedShareManager;
95
	}
96
97
	/**
98
	 * @NoCSRFRequired
99
	 * @PublicPage
100
	 *
101
	 * create a new share
102
	 *
103
	 * @return Result
104
	 */
105
	public function createShare() {
106
		try {
107
			$this->assertIncomingSharingEnabled();
108
			$remote = $this->request->getParam('remote', null);
109
			$token = $this->request->getParam('token', null);
110
			$name = $this->request->getParam('name', null);
111
			$owner = $this->request->getParam('owner', null);
112
			$sharedBy = $this->request->getParam('sharedBy', null);
113
			$shareWith = $this->request->getParam('shareWith', null);
114
			$remoteId = $this->request->getParam('remoteId', null);
115
			$sharedByFederatedId = $this->request->getParam(
116
				'sharedByFederatedId',
117
				null
118
			);
119
			$ownerFederatedId = $this->request->getParam('ownerFederatedId', null);
120
			$hasMissingParams = $this->hasNull(
121
				[$remote, $token, $name, $owner, $remoteId, $shareWith]
122
			);
123
			if ($hasMissingParams) {
124
				throw new InvalidShareException(
125
					'server can not add remote share, missing parameter'
126
				);
127
			}
128
			if (!\OCP\Util::isValidFileName($name)) {
129
				throw new InvalidShareException(
130
					'The mountpoint name contains invalid characters.'
131
				);
132
			}
133
			// FIXME this should be a method in the user management instead
134
			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
135
			\OCP\Util::emitHook(
136
				'\OCA\Files_Sharing\API\Server2Server',
137
				'preLoginNameUsedAsUserName',
138
				['uid' => &$shareWith]
139
			);
140
			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
141
			if (!$this->userManager->userExists($shareWith)) {
142
				throw new InvalidShareException('User does not exist');
143
			}
144
145
			if ($ownerFederatedId === null) {
146
				$ownerFederatedId = $owner . '@' . $this->addressHandler->normalizeRemote($remote);
147
			}
148
			// if the owner of the share and the initiator are the same user
149
			// we also complete the federated share ID for the initiator
150
			if ($sharedByFederatedId === null && $owner === $sharedBy) {
151
				$sharedByFederatedId = $ownerFederatedId;
152
			}
153
154
			$ownerAddress = new Address($ownerFederatedId);
155
			$sharedByAddress = new Address($sharedByFederatedId);
156
157
			$this->fedShareManager->createShare(
158
				$ownerAddress,
159
				$sharedByAddress,
160
				$shareWith,
161
				$remote,
162
				$remoteId,
163
				$name,
164
				$token
165
			);
166
		} catch (InvalidShareException $e) {
167
			return new Result(
168
				null,
169
				Http::STATUS_BAD_REQUEST,
170
				$e->getMessage()
171
			);
172
		} catch (NotSupportedException $e) {
173
			return new Result(
174
				null,
175
				Http::STATUS_SERVICE_UNAVAILABLE,
176
				'Server does not support federated cloud sharing'
177
			);
178
		} catch (\Exception $e) {
179
			\OCP\Util::writeLog(
180
				'files_sharing',
181
				'server can not add remote share, ' . $e->getMessage(),
182
				\OCP\Util::ERROR
183
			);
184
			return new Result(
185
				null,
186
				Http::STATUS_INTERNAL_SERVER_ERROR,
187
				'internal server error, was not able to add share from ' . $remote
0 ignored issues
show
Bug introduced by
The variable $remote does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
188
			);
189
		}
190
		return new Result();
191
	}
192
193
	/**
194
	 * @NoCSRFRequired
195
	 * @PublicPage
196
	 *
197
	 * create re-share on behalf of another user
198
	 *
199
	 * @param int $id
200
	 *
201
	 * @return Result
202
	 */
203
	public function reShare($id) {
204
		$token = $this->request->getParam('token', null);
205
		$shareWith = $this->request->getParam('shareWith', null);
206
		$permission = $this->request->getParam('permission', null);
207
		$remoteId = $this->request->getParam('remoteId', null);
208
209
		if ($this->hasNull([$id, $token, $shareWith, $permission, $remoteId])) {
210
			return new Result(null, Http::STATUS_BAD_REQUEST);
211
		}
212
213
		try {
214
			$permission = (int) $permission;
215
			$remoteId = (int) $remoteId;
216
			$share = $this->getValidShare($id);
217
218
			// don't allow to share a file back to the owner
219
			list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
220
			$owner = $share->getShareOwner();
221
			$currentServer = $this->addressHandler->generateRemoteURL();
222
			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
223
				return new Result(null, Http::STATUS_FORBIDDEN);
224
			}
225
226
			$reSharingAllowed = $share->getPermissions() & Constants::PERMISSION_SHARE;
227
			if (!$reSharingAllowed) {
228
				return new Result(null, Http::STATUS_BAD_REQUEST);
229
			}
230
			$result = $this->fedShareManager->reShare(
231
				$share,
232
				$remoteId,
233
				$shareWith,
234
				$permission
235
			);
236
		} catch (Share\Exceptions\ShareNotFound $e) {
237
			return new Result(null, Http::STATUS_NOT_FOUND);
238
		} catch (InvalidShareException $e) {
239
			return new Result(null, Http::STATUS_FORBIDDEN);
240
		} catch (\Exception $e) {
241
			return new Result(null, Http::STATUS_BAD_REQUEST);
242
		}
243
244
		return new Result(
245
			[
246
				'token' => $result->getToken(),
247
				'remoteId' => $result->getId()
248
			]
249
		);
250
	}
251
252
	/**
253
	 * @NoCSRFRequired
254
	 * @PublicPage
255
	 *
256
	 * accept server-to-server share
257
	 *
258
	 * @param int $id
259
	 *
260
	 * @return Result
261
	 */
262 View Code Duplication
	public function acceptShare($id) {
263
		try {
264
			$this->assertOutgoingSharingEnabled();
265
			$share = $this->getValidShare($id);
266
			$this->fedShareManager->acceptShare($share);
267
		} catch (NotSupportedException $e) {
268
			return new Result(
269
				null,
270
				Http::STATUS_SERVICE_UNAVAILABLE,
271
				'Server does not support federated cloud sharing'
272
			);
273
		} catch (Share\Exceptions\ShareNotFound $e) {
274
			// pass
275
		}
276
		return new Result();
277
	}
278
279
	/**
280
	 * @NoCSRFRequired
281
	 * @PublicPage
282
	 *
283
	 * decline server-to-server share
284
	 *
285
	 * @param int $id
286
	 *
287
	 * @return Result
288
	 */
289 View Code Duplication
	public function declineShare($id) {
290
		try {
291
			$this->assertOutgoingSharingEnabled();
292
			$share = $this->getValidShare($id);
293
			$this->fedShareManager->declineShare($share);
294
		} catch (NotSupportedException $e) {
295
			return new Result(
296
				null,
297
				Http::STATUS_SERVICE_UNAVAILABLE,
298
				'Server does not support federated cloud sharing'
299
			);
300
		} catch (Share\Exceptions\ShareNotFound $e) {
301
			// pass
302
		}
303
304
		return new Result();
305
	}
306
307
	/**
308
	 * @NoCSRFRequired
309
	 * @PublicPage
310
	 *
311
	 * remove server-to-server share if it was unshared by the owner
312
	 *
313
	 * @param int $id
314
	 *
315
	 * @return Result
316
	 */
317
	public function unshare($id) {
318
		try {
319
			$this->assertOutgoingSharingEnabled();
320
			$token = $this->request->getParam('token', null);
321
			if ($token && $id) {
322
				$this->fedShareManager->unshare($id, $token);
323
			}
324
		} catch (NotSupportedException $e) {
325
			return new Result(
326
				null,
327
				Http::STATUS_SERVICE_UNAVAILABLE,
328
				'Server does not support federated cloud sharing'
329
			);
330
		} catch (\Exception $e) {
331
			// pass
332
		}
333
		return new Result();
334
	}
335
336
	/**
337
	 * @NoCSRFRequired
338
	 * @PublicPage
339
	 *
340
	 * federated share was revoked, either by the owner or the re-sharer
341
	 *
342
	 * @param int $id
343
	 *
344
	 * @return Result
345
	 */
346
	public function revoke($id) {
347
		try {
348
			$share = $this->getValidShare($id);
349
			$this->fedShareManager->revoke($share);
350
		} catch (\Exception $e) {
351
			return new Result(null, Http::STATUS_BAD_REQUEST);
352
		}
353
354
		return new Result();
355
	}
356
357
	/**
358
	 * @NoCSRFRequired
359
	 * @PublicPage
360
	 *
361
	 * update share information to keep federated re-shares in sync
362
	 *
363
	 * @param int $id
364
	 *
365
	 * @return Result
366
	 */
367
	public function updatePermissions($id) {
368
		try {
369
			$permissions = $this->request->getParam('permissions', null);
370
371
			$share = $this->getValidShare($id);
372
			$validPermission = \ctype_digit((string)$permissions);
373
			if (!$validPermission) {
374
				throw new \Exception();
375
			}
376
			$this->fedShareManager->updatePermissions($share, (int)$permissions);
377
		} catch (\Exception $e) {
378
			return new Result(null, Http::STATUS_BAD_REQUEST);
379
		}
380
381
		return new Result();
382
	}
383
384
	/**
385
	 * Get share by id, validate it's type and token
386
	 *
387
	 * @param int $id
388
	 *
389
	 * @return IShare
390
	 *
391
	 * @throws Share\Exceptions\ShareNotFound
392
	 * @throws InvalidShareException
393
	 */
394
	protected function getValidShare($id) {
395
		$share = $this->federatedShareProvider->getShareById($id);
396
		$token = $this->request->getParam('token', null);
397
		if ($share->getShareType() !== FederatedShareProvider::SHARE_TYPE_REMOTE
398
			|| $share->getToken() !== $token
399
		) {
400
			throw new InvalidShareException();
401
		}
402
		return $share;
403
	}
404
405
	/**
406
	 * Make sure that incoming shares are enabled
407
	 *
408
	 * @return void
409
	 *
410
	 * @throws NotSupportedException
411
	 */
412
	protected function assertIncomingSharingEnabled() {
413
		if (!$this->appManager->isEnabledForUser('files_sharing')
414
			|| !$this->federatedShareProvider->isIncomingServer2serverShareEnabled()
415
		) {
416
			throw new NotSupportedException();
417
		}
418
	}
419
	
420
	/**
421
	 * Make sure that outgoing shares are enabled
422
	 *
423
	 * @return void
424
	 *
425
	 * @throws NotSupportedException
426
	 */
427
	protected function assertOutgoingSharingEnabled() {
428
		if (!$this->appManager->isEnabledForUser('files_sharing')
429
			|| !$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()
430
		) {
431
			throw new NotSupportedException();
432
		}
433
	}
434
435
	/**
436
	 * Check if value is null or an array has any null item
437
	 *
438
	 * @param mixed $param
439
	 *
440
	 * @return bool
441
	 */
442 View Code Duplication
	protected function hasNull($param) {
443
		if (\is_array($param)) {
444
			return \in_array(null, $param, true);
445
		} else {
446
			return $param === null;
447
		}
448
	}
449
}
450