Completed
Pull Request — master (#9269)
by Morris
19:14
created
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -37,87 +37,87 @@
 block discarded – undo
37 37
 
38 38
 class Application extends App {
39 39
 
40
-	/** @var FederatedShareProvider */
41
-	protected $federatedShareProvider;
40
+    /** @var FederatedShareProvider */
41
+    protected $federatedShareProvider;
42 42
 
43
-	public function __construct() {
44
-		parent::__construct('federatedfilesharing');
43
+    public function __construct() {
44
+        parent::__construct('federatedfilesharing');
45 45
 
46
-		$container = $this->getContainer();
47
-		$server = $container->getServer();
46
+        $container = $this->getContainer();
47
+        $server = $container->getServer();
48 48
 
49
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
50
-			$addressHandler = new AddressHandler(
51
-				$server->getURLGenerator(),
52
-				$server->getL10N('federatedfilesharing'),
53
-				$server->getCloudIdManager()
54
-			);
55
-			$notification = new Notifications(
56
-				$addressHandler,
57
-				$server->getHTTPClientService(),
58
-				$server->query(\OCP\OCS\IDiscoveryService::class),
59
-				\OC::$server->getJobList()
60
-			);
61
-			return new RequestHandlerController(
62
-				$c->query('AppName'),
63
-				$server->getRequest(),
64
-				$this->getFederatedShareProvider(),
65
-				$server->getDatabaseConnection(),
66
-				$server->getShareManager(),
67
-				$notification,
68
-				$addressHandler,
69
-				$server->getUserManager(),
70
-				$server->getCloudIdManager(),
71
-				$server->getLogger()
72
-			);
73
-		});
74
-	}
49
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
50
+            $addressHandler = new AddressHandler(
51
+                $server->getURLGenerator(),
52
+                $server->getL10N('federatedfilesharing'),
53
+                $server->getCloudIdManager()
54
+            );
55
+            $notification = new Notifications(
56
+                $addressHandler,
57
+                $server->getHTTPClientService(),
58
+                $server->query(\OCP\OCS\IDiscoveryService::class),
59
+                \OC::$server->getJobList()
60
+            );
61
+            return new RequestHandlerController(
62
+                $c->query('AppName'),
63
+                $server->getRequest(),
64
+                $this->getFederatedShareProvider(),
65
+                $server->getDatabaseConnection(),
66
+                $server->getShareManager(),
67
+                $notification,
68
+                $addressHandler,
69
+                $server->getUserManager(),
70
+                $server->getCloudIdManager(),
71
+                $server->getLogger()
72
+            );
73
+        });
74
+    }
75 75
 
76
-	/**
77
-	 * get instance of federated share provider
78
-	 *
79
-	 * @return FederatedShareProvider
80
-	 */
81
-	public function getFederatedShareProvider() {
82
-		if ($this->federatedShareProvider === null) {
83
-			$this->initFederatedShareProvider();
84
-		}
85
-		return $this->federatedShareProvider;
86
-	}
76
+    /**
77
+     * get instance of federated share provider
78
+     *
79
+     * @return FederatedShareProvider
80
+     */
81
+    public function getFederatedShareProvider() {
82
+        if ($this->federatedShareProvider === null) {
83
+            $this->initFederatedShareProvider();
84
+        }
85
+        return $this->federatedShareProvider;
86
+    }
87 87
 
88
-	/**
89
-	 * initialize federated share provider
90
-	 */
91
-	protected function initFederatedShareProvider() {
92
-		$c = $this->getContainer();
93
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
94
-			\OC::$server->getURLGenerator(),
95
-			\OC::$server->getL10N('federatedfilesharing'),
96
-			\OC::$server->getCloudIdManager()
97
-		);
98
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
99
-			$addressHandler,
100
-			\OC::$server->getHTTPClientService(),
101
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
102
-			\OC::$server->getJobList()
103
-		);
104
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
105
-			\OC::$server->getSecureRandom()
106
-		);
88
+    /**
89
+     * initialize federated share provider
90
+     */
91
+    protected function initFederatedShareProvider() {
92
+        $c = $this->getContainer();
93
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
94
+            \OC::$server->getURLGenerator(),
95
+            \OC::$server->getL10N('federatedfilesharing'),
96
+            \OC::$server->getCloudIdManager()
97
+        );
98
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
99
+            $addressHandler,
100
+            \OC::$server->getHTTPClientService(),
101
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
102
+            \OC::$server->getJobList()
103
+        );
104
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
105
+            \OC::$server->getSecureRandom()
106
+        );
107 107
 
108
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
109
-			\OC::$server->getDatabaseConnection(),
110
-			$addressHandler,
111
-			$notifications,
112
-			$tokenHandler,
113
-			\OC::$server->getL10N('federatedfilesharing'),
114
-			\OC::$server->getLogger(),
115
-			\OC::$server->getLazyRootFolder(),
116
-			\OC::$server->getConfig(),
117
-			\OC::$server->getUserManager(),
118
-			\OC::$server->getCloudIdManager(),
119
-			$c->query(IConfig::class)
120
-		);
121
-	}
108
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
109
+            \OC::$server->getDatabaseConnection(),
110
+            $addressHandler,
111
+            $notifications,
112
+            $tokenHandler,
113
+            \OC::$server->getL10N('federatedfilesharing'),
114
+            \OC::$server->getLogger(),
115
+            \OC::$server->getLazyRootFolder(),
116
+            \OC::$server->getConfig(),
117
+            \OC::$server->getUserManager(),
118
+            \OC::$server->getCloudIdManager(),
119
+            $c->query(IConfig::class)
120
+        );
121
+    }
122 122
 
123 123
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 2 patches
Indentation   +635 added lines, -635 removed lines patch added patch discarded remove patch
@@ -51,639 +51,639 @@
 block discarded – undo
51 51
 
52 52
 class RequestHandlerController extends OCSController {
53 53
 
54
-	/** @var FederatedShareProvider */
55
-	private $federatedShareProvider;
56
-
57
-	/** @var IDBConnection */
58
-	private $connection;
59
-
60
-	/** @var Share\IManager */
61
-	private $shareManager;
62
-
63
-	/** @var Notifications */
64
-	private $notifications;
65
-
66
-	/** @var AddressHandler */
67
-	private $addressHandler;
68
-
69
-	/** @var  IUserManager */
70
-	private $userManager;
71
-
72
-	/** @var string */
73
-	private $shareTable = 'share';
74
-
75
-	/** @var ICloudIdManager */
76
-	private $cloudIdManager;
77
-
78
-	/** @var ILogger */
79
-	private $logger;
80
-
81
-	/**
82
-	 * Server2Server constructor.
83
-	 *
84
-	 * @param string $appName
85
-	 * @param IRequest $request
86
-	 * @param FederatedShareProvider $federatedShareProvider
87
-	 * @param IDBConnection $connection
88
-	 * @param Share\IManager $shareManager
89
-	 * @param Notifications $notifications
90
-	 * @param AddressHandler $addressHandler
91
-	 * @param IUserManager $userManager
92
-	 * @param ICloudIdManager $cloudIdManager
93
-	 */
94
-	public function __construct($appName,
95
-								IRequest $request,
96
-								FederatedShareProvider $federatedShareProvider,
97
-								IDBConnection $connection,
98
-								Share\IManager $shareManager,
99
-								Notifications $notifications,
100
-								AddressHandler $addressHandler,
101
-								IUserManager $userManager,
102
-								ICloudIdManager $cloudIdManager,
103
-								ILogger $logger
104
-	) {
105
-		parent::__construct($appName, $request);
106
-
107
-		$this->federatedShareProvider = $federatedShareProvider;
108
-		$this->connection = $connection;
109
-		$this->shareManager = $shareManager;
110
-		$this->notifications = $notifications;
111
-		$this->addressHandler = $addressHandler;
112
-		$this->userManager = $userManager;
113
-		$this->cloudIdManager = $cloudIdManager;
114
-		$this->logger = $logger;
115
-	}
116
-
117
-	/**
118
-	 * @NoCSRFRequired
119
-	 * @PublicPage
120
-	 *
121
-	 * create a new share
122
-	 *
123
-	 * @return Http\DataResponse
124
-	 * @throws OCSException
125
-	 */
126
-	public function createShare() {
127
-
128
-		if (!$this->isS2SEnabled(true)) {
129
-			throw new OCSException('Server does not support federated cloud sharing', 503);
130
-		}
131
-
132
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
133
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
134
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
135
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
136
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
137
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
138
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
139
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
140
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
141
-
142
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
143
-
144
-			if (!\OCP\Util::isValidFileName($name)) {
145
-				throw new OCSException('The mountpoint name contains invalid characters.', 400);
146
-			}
147
-
148
-			// FIXME this should be a method in the user management instead
149
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
150
-			\OCP\Util::emitHook(
151
-				'\OCA\Files_Sharing\API\Server2Server',
152
-				'preLoginNameUsedAsUserName',
153
-				array('uid' => &$shareWith)
154
-			);
155
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
156
-
157
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
158
-				throw new OCSException('User does not exists', 400);
159
-			}
160
-
161
-			\OC_Util::setupFS($shareWith);
162
-
163
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
164
-					\OC::$server->getDatabaseConnection(),
165
-					\OC\Files\Filesystem::getMountManager(),
166
-					\OC\Files\Filesystem::getLoader(),
167
-					\OC::$server->getHTTPClientService(),
168
-					\OC::$server->getNotificationManager(),
169
-					\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
170
-					$shareWith
171
-				);
172
-
173
-			try {
174
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
175
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
176
-
177
-				if ($ownerFederatedId === null) {
178
-					$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
179
-				}
180
-				// if the owner of the share and the initiator are the same user
181
-				// we also complete the federated share ID for the initiator
182
-				if ($sharedByFederatedId === null && $owner === $sharedBy) {
183
-					$sharedByFederatedId = $ownerFederatedId;
184
-				}
185
-
186
-				$event = \OC::$server->getActivityManager()->generateEvent();
187
-				$event->setApp('files_sharing')
188
-					->setType('remote_share')
189
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
190
-					->setAffectedUser($shareWith)
191
-					->setObject('remote_share', (int)$shareId, $name);
192
-				\OC::$server->getActivityManager()->publish($event);
193
-
194
-				$urlGenerator = \OC::$server->getURLGenerator();
195
-
196
-				$notificationManager = \OC::$server->getNotificationManager();
197
-				$notification = $notificationManager->createNotification();
198
-				$notification->setApp('files_sharing')
199
-					->setUser($shareWith)
200
-					->setDateTime(new \DateTime())
201
-					->setObject('remote_share', $shareId)
202
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
203
-
204
-				$declineAction = $notification->createAction();
205
-				$declineAction->setLabel('decline')
206
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
207
-				$notification->addAction($declineAction);
208
-
209
-				$acceptAction = $notification->createAction();
210
-				$acceptAction->setLabel('accept')
211
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
212
-				$notification->addAction($acceptAction);
213
-
214
-				$notificationManager->notify($notification);
215
-
216
-				return new Http\DataResponse();
217
-			} catch (\Exception $e) {
218
-				$this->logger->logException($e, [
219
-					'message' => 'Server can not add remote share.',
220
-					'level' => \OCP\Util::ERROR,
221
-					'app' => 'files_sharing'
222
-				]);
223
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
224
-			}
225
-		}
226
-
227
-		throw new OCSException('server can not add remote share, missing parameter', 400);
228
-	}
229
-
230
-	/**
231
-	 * @NoCSRFRequired
232
-	 * @PublicPage
233
-	 *
234
-	 * create re-share on behalf of another user
235
-	 *
236
-	 * @param int $id
237
-	 * @return Http\DataResponse
238
-	 * @throws OCSBadRequestException
239
-	 * @throws OCSForbiddenException
240
-	 * @throws OCSNotFoundException
241
-	 */
242
-	public function reShare($id) {
243
-
244
-		$token = $this->request->getParam('token', null);
245
-		$shareWith = $this->request->getParam('shareWith', null);
246
-		$permission = (int)$this->request->getParam('permission', null);
247
-		$remoteId = (int)$this->request->getParam('remoteId', null);
248
-
249
-		if ($id === null ||
250
-			$token === null ||
251
-			$shareWith === null ||
252
-			$permission === null ||
253
-			$remoteId === null
254
-		) {
255
-			throw new OCSBadRequestException();
256
-		}
257
-
258
-		try {
259
-			$share = $this->federatedShareProvider->getShareById($id);
260
-		} catch (Share\Exceptions\ShareNotFound $e) {
261
-			throw new OCSNotFoundException();
262
-		}
263
-
264
-		// don't allow to share a file back to the owner
265
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
266
-		$owner = $share->getShareOwner();
267
-		$currentServer = $this->addressHandler->generateRemoteURL();
268
-		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
269
-			throw new OCSForbiddenException();
270
-		}
271
-
272
-		if ($this->verifyShare($share, $token)) {
273
-
274
-			// check if re-sharing is allowed
275
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
276
-				$share->setPermissions($share->getPermissions() & $permission);
277
-				// the recipient of the initial share is now the initiator for the re-share
278
-				$share->setSharedBy($share->getSharedWith());
279
-				$share->setSharedWith($shareWith);
280
-				try {
281
-					$result = $this->federatedShareProvider->create($share);
282
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
283
-					return new Http\DataResponse([
284
-						'token' => $result->getToken(),
285
-						'remoteId' => $result->getId()
286
-					]);
287
-				} catch (\Exception $e) {
288
-					throw new OCSBadRequestException();
289
-				}
290
-			} else {
291
-				throw new OCSForbiddenException();
292
-			}
293
-		}
294
-		throw new OCSBadRequestException();
295
-	}
296
-
297
-	/**
298
-	 * @NoCSRFRequired
299
-	 * @PublicPage
300
-	 *
301
-	 * accept server-to-server share
302
-	 *
303
-	 * @param int $id
304
-	 * @return Http\DataResponse
305
-	 * @throws OCSException
306
-	 */
307
-	public function acceptShare($id) {
308
-
309
-		if (!$this->isS2SEnabled()) {
310
-			throw new OCSException('Server does not support federated cloud sharing', 503);
311
-		}
312
-
313
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
314
-
315
-		try {
316
-			$share = $this->federatedShareProvider->getShareById($id);
317
-		} catch (Share\Exceptions\ShareNotFound $e) {
318
-			return new Http\DataResponse();
319
-		}
320
-
321
-		if ($this->verifyShare($share, $token)) {
322
-			$this->executeAcceptShare($share);
323
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
324
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
325
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
326
-				$this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
327
-			}
328
-		}
329
-
330
-		return new Http\DataResponse();
331
-	}
332
-
333
-	protected function executeAcceptShare(Share\IShare $share) {
334
-		$fileId = (int) $share->getNode()->getId();
335
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
336
-
337
-		$event = \OC::$server->getActivityManager()->generateEvent();
338
-		$event->setApp('files_sharing')
339
-			->setType('remote_share')
340
-			->setAffectedUser($this->getCorrectUid($share))
341
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
342
-			->setObject('files', $fileId, $file)
343
-			->setLink($link);
344
-		\OC::$server->getActivityManager()->publish($event);
345
-	}
346
-
347
-	/**
348
-	 * @NoCSRFRequired
349
-	 * @PublicPage
350
-	 *
351
-	 * decline server-to-server share
352
-	 *
353
-	 * @param int $id
354
-	 * @return Http\DataResponse
355
-	 * @throws OCSException
356
-	 */
357
-	public function declineShare($id) {
358
-
359
-		if (!$this->isS2SEnabled()) {
360
-			throw new OCSException('Server does not support federated cloud sharing', 503);
361
-		}
362
-
363
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
364
-
365
-		try {
366
-			$share = $this->federatedShareProvider->getShareById($id);
367
-		} catch (Share\Exceptions\ShareNotFound $e) {
368
-			return new Http\DataResponse();
369
-		}
370
-
371
-		if ($this->verifyShare($share, $token)) {
372
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
373
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
374
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
375
-				$this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
376
-			}
377
-			$this->executeDeclineShare($share);
378
-		}
379
-
380
-		return new Http\DataResponse();
381
-	}
382
-
383
-	/**
384
-	 * delete declined share and create a activity
385
-	 *
386
-	 * @param Share\IShare $share
387
-	 */
388
-	protected function executeDeclineShare(Share\IShare $share) {
389
-		$this->federatedShareProvider->removeShareFromTable($share);
390
-		$fileId = (int) $share->getNode()->getId();
391
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
392
-
393
-		$event = \OC::$server->getActivityManager()->generateEvent();
394
-		$event->setApp('files_sharing')
395
-			->setType('remote_share')
396
-			->setAffectedUser($this->getCorrectUid($share))
397
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
398
-			->setObject('files', $fileId, $file)
399
-			->setLink($link);
400
-		\OC::$server->getActivityManager()->publish($event);
401
-
402
-	}
403
-
404
-	/**
405
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
406
-	 *
407
-	 * @param Share\IShare $share
408
-	 * @return string
409
-	 */
410
-	protected function getCorrectUid(Share\IShare $share) {
411
-		if ($this->userManager->userExists($share->getShareOwner())) {
412
-			return $share->getShareOwner();
413
-		}
414
-
415
-		return $share->getSharedBy();
416
-	}
417
-
418
-	/**
419
-	 * @NoCSRFRequired
420
-	 * @PublicPage
421
-	 *
422
-	 * remove server-to-server share if it was unshared by the owner
423
-	 *
424
-	 * @param int $id
425
-	 * @return Http\DataResponse
426
-	 * @throws OCSException
427
-	 */
428
-	public function unshare($id) {
429
-
430
-		if (!$this->isS2SEnabled()) {
431
-			throw new OCSException('Server does not support federated cloud sharing', 503);
432
-		}
433
-
434
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
435
-
436
-		$qb = $this->connection->getQueryBuilder();
437
-		$qb->select('*')
438
-			->from('share_external')
439
-			->where(
440
-				$qb->expr()->andX(
441
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
442
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
443
-				)
444
-			);
445
-
446
-		$result = $qb->execute();
447
-		$share = $result->fetch();
448
-		$result->closeCursor();
449
-
450
-		if ($token && $id && !empty($share)) {
451
-
452
-			$remote = $this->cleanupRemote($share['remote']);
453
-
454
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
455
-			$mountpoint = $share['mountpoint'];
456
-			$user = $share['user'];
457
-
458
-			$qb = $this->connection->getQueryBuilder();
459
-			$qb->delete('share_external')
460
-				->where(
461
-					$qb->expr()->andX(
462
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
463
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
464
-					)
465
-				);
466
-
467
-			$result = $qb->execute();
468
-			$result->closeCursor();
469
-
470
-			if ($share['accepted']) {
471
-				$path = trim($mountpoint, '/');
472
-			} else {
473
-				$path = trim($share['name'], '/');
474
-			}
475
-
476
-			$notificationManager = \OC::$server->getNotificationManager();
477
-			$notification = $notificationManager->createNotification();
478
-			$notification->setApp('files_sharing')
479
-				->setUser($share['user'])
480
-				->setObject('remote_share', (int)$share['id']);
481
-			$notificationManager->markProcessed($notification);
482
-
483
-			$event = \OC::$server->getActivityManager()->generateEvent();
484
-			$event->setApp('files_sharing')
485
-				->setType('remote_share')
486
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
487
-				->setAffectedUser($user)
488
-				->setObject('remote_share', (int)$share['id'], $path);
489
-			\OC::$server->getActivityManager()->publish($event);
490
-		}
491
-
492
-		return new Http\DataResponse();
493
-	}
494
-
495
-	private function cleanupRemote($remote) {
496
-		$remote = substr($remote, strpos($remote, '://') + 3);
497
-
498
-		return rtrim($remote, '/');
499
-	}
500
-
501
-
502
-	/**
503
-	 * @NoCSRFRequired
504
-	 * @PublicPage
505
-	 *
506
-	 * federated share was revoked, either by the owner or the re-sharer
507
-	 *
508
-	 * @param int $id
509
-	 * @return Http\DataResponse
510
-	 * @throws OCSBadRequestException
511
-	 */
512
-	public function revoke($id) {
513
-		$token = $this->request->getParam('token');
514
-
515
-		$share = $this->federatedShareProvider->getShareById($id);
516
-
517
-		if ($this->verifyShare($share, $token)) {
518
-			$this->federatedShareProvider->removeShareFromTable($share);
519
-			return new Http\DataResponse();
520
-		}
521
-
522
-		throw new OCSBadRequestException();
523
-	}
524
-
525
-	/**
526
-	 * get share
527
-	 *
528
-	 * @param int $id
529
-	 * @param string $token
530
-	 * @return array|bool
531
-	 */
532
-	protected function getShare($id, $token) {
533
-		$query = $this->connection->getQueryBuilder();
534
-		$query->select('*')->from($this->shareTable)
535
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
536
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
537
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
538
-
539
-		$result = $query->execute()->fetchAll();
540
-
541
-		if (!empty($result) && isset($result[0])) {
542
-			return $result[0];
543
-		}
544
-
545
-		return false;
546
-	}
547
-
548
-	/**
549
-	 * get file
550
-	 *
551
-	 * @param string $user
552
-	 * @param int $fileSource
553
-	 * @return array with internal path of the file and a absolute link to it
554
-	 */
555
-	private function getFile($user, $fileSource) {
556
-		\OC_Util::setupFS($user);
557
-
558
-		try {
559
-			$file = \OC\Files\Filesystem::getPath($fileSource);
560
-		} catch (NotFoundException $e) {
561
-			$file = null;
562
-		}
563
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
564
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
565
-
566
-		return array($file, $link);
567
-
568
-	}
569
-
570
-	/**
571
-	 * check if server-to-server sharing is enabled
572
-	 *
573
-	 * @param bool $incoming
574
-	 * @return bool
575
-	 */
576
-	private function isS2SEnabled($incoming = false) {
577
-
578
-		$result = \OCP\App::isEnabled('files_sharing');
579
-
580
-		if ($incoming) {
581
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
582
-		} else {
583
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
584
-		}
585
-
586
-		return $result;
587
-	}
588
-
589
-	/**
590
-	 * check if we got the right share
591
-	 *
592
-	 * @param Share\IShare $share
593
-	 * @param string $token
594
-	 * @return bool
595
-	 */
596
-	protected function verifyShare(Share\IShare $share, $token) {
597
-		if (
598
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
599
-			$share->getToken() === $token
600
-		) {
601
-			return true;
602
-		}
603
-
604
-		return false;
605
-	}
606
-
607
-	/**
608
-	 * @NoCSRFRequired
609
-	 * @PublicPage
610
-	 *
611
-	 * update share information to keep federated re-shares in sync
612
-	 *
613
-	 * @param int $id
614
-	 * @return Http\DataResponse
615
-	 * @throws OCSBadRequestException
616
-	 */
617
-	public function updatePermissions($id) {
618
-		$token = $this->request->getParam('token', null);
619
-		$permissions = $this->request->getParam('permissions', null);
620
-
621
-		try {
622
-			$share = $this->federatedShareProvider->getShareById($id);
623
-		} catch (Share\Exceptions\ShareNotFound $e) {
624
-			throw new OCSBadRequestException();
625
-		}
626
-
627
-		$validPermission = ctype_digit($permissions);
628
-		$validToken = $this->verifyShare($share, $token);
629
-		if ($validPermission && $validToken) {
630
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
631
-		} else {
632
-			throw new OCSBadRequestException();
633
-		}
634
-
635
-		return new Http\DataResponse();
636
-	}
637
-
638
-	/**
639
-	 * update permissions in database
640
-	 *
641
-	 * @param IShare $share
642
-	 * @param int $permissions
643
-	 */
644
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
645
-		$query = $this->connection->getQueryBuilder();
646
-		$query->update('share')
647
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
648
-			->set('permissions', $query->createNamedParameter($permissions))
649
-			->execute();
650
-	}
651
-
652
-	/**
653
-	 * @NoCSRFRequired
654
-	 * @PublicPage
655
-	 *
656
-	 * change the owner of a server-to-server share
657
-	 *
658
-	 * @param int $id
659
-	 * @return Http\DataResponse
660
-	 * @throws \InvalidArgumentException
661
-	 * @throws OCSException
662
-	 */
663
-	public function move($id) {
664
-
665
-		if (!$this->isS2SEnabled()) {
666
-			throw new OCSException('Server does not support federated cloud sharing', 503);
667
-		}
668
-
669
-		$token = $this->request->getParam('token');
670
-		$remote = $this->request->getParam('remote');
671
-		$newRemoteId = $this->request->getParam('remote_id', $id);
672
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
673
-
674
-		$qb = $this->connection->getQueryBuilder();
675
-		$query = $qb->update('share_external')
676
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
677
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
678
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
679
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
680
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
681
-		$affected = $query->execute();
682
-
683
-		if ($affected > 0) {
684
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
685
-		} else {
686
-			throw new OCSBadRequestException('Share not found or token invalid');
687
-		}
688
-	}
54
+    /** @var FederatedShareProvider */
55
+    private $federatedShareProvider;
56
+
57
+    /** @var IDBConnection */
58
+    private $connection;
59
+
60
+    /** @var Share\IManager */
61
+    private $shareManager;
62
+
63
+    /** @var Notifications */
64
+    private $notifications;
65
+
66
+    /** @var AddressHandler */
67
+    private $addressHandler;
68
+
69
+    /** @var  IUserManager */
70
+    private $userManager;
71
+
72
+    /** @var string */
73
+    private $shareTable = 'share';
74
+
75
+    /** @var ICloudIdManager */
76
+    private $cloudIdManager;
77
+
78
+    /** @var ILogger */
79
+    private $logger;
80
+
81
+    /**
82
+     * Server2Server constructor.
83
+     *
84
+     * @param string $appName
85
+     * @param IRequest $request
86
+     * @param FederatedShareProvider $federatedShareProvider
87
+     * @param IDBConnection $connection
88
+     * @param Share\IManager $shareManager
89
+     * @param Notifications $notifications
90
+     * @param AddressHandler $addressHandler
91
+     * @param IUserManager $userManager
92
+     * @param ICloudIdManager $cloudIdManager
93
+     */
94
+    public function __construct($appName,
95
+                                IRequest $request,
96
+                                FederatedShareProvider $federatedShareProvider,
97
+                                IDBConnection $connection,
98
+                                Share\IManager $shareManager,
99
+                                Notifications $notifications,
100
+                                AddressHandler $addressHandler,
101
+                                IUserManager $userManager,
102
+                                ICloudIdManager $cloudIdManager,
103
+                                ILogger $logger
104
+    ) {
105
+        parent::__construct($appName, $request);
106
+
107
+        $this->federatedShareProvider = $federatedShareProvider;
108
+        $this->connection = $connection;
109
+        $this->shareManager = $shareManager;
110
+        $this->notifications = $notifications;
111
+        $this->addressHandler = $addressHandler;
112
+        $this->userManager = $userManager;
113
+        $this->cloudIdManager = $cloudIdManager;
114
+        $this->logger = $logger;
115
+    }
116
+
117
+    /**
118
+     * @NoCSRFRequired
119
+     * @PublicPage
120
+     *
121
+     * create a new share
122
+     *
123
+     * @return Http\DataResponse
124
+     * @throws OCSException
125
+     */
126
+    public function createShare() {
127
+
128
+        if (!$this->isS2SEnabled(true)) {
129
+            throw new OCSException('Server does not support federated cloud sharing', 503);
130
+        }
131
+
132
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
133
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
134
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
135
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
136
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
137
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
138
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
139
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
140
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
141
+
142
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
143
+
144
+            if (!\OCP\Util::isValidFileName($name)) {
145
+                throw new OCSException('The mountpoint name contains invalid characters.', 400);
146
+            }
147
+
148
+            // FIXME this should be a method in the user management instead
149
+            $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
150
+            \OCP\Util::emitHook(
151
+                '\OCA\Files_Sharing\API\Server2Server',
152
+                'preLoginNameUsedAsUserName',
153
+                array('uid' => &$shareWith)
154
+            );
155
+            $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
156
+
157
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
158
+                throw new OCSException('User does not exists', 400);
159
+            }
160
+
161
+            \OC_Util::setupFS($shareWith);
162
+
163
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
164
+                    \OC::$server->getDatabaseConnection(),
165
+                    \OC\Files\Filesystem::getMountManager(),
166
+                    \OC\Files\Filesystem::getLoader(),
167
+                    \OC::$server->getHTTPClientService(),
168
+                    \OC::$server->getNotificationManager(),
169
+                    \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
170
+                    $shareWith
171
+                );
172
+
173
+            try {
174
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
175
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
176
+
177
+                if ($ownerFederatedId === null) {
178
+                    $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
179
+                }
180
+                // if the owner of the share and the initiator are the same user
181
+                // we also complete the federated share ID for the initiator
182
+                if ($sharedByFederatedId === null && $owner === $sharedBy) {
183
+                    $sharedByFederatedId = $ownerFederatedId;
184
+                }
185
+
186
+                $event = \OC::$server->getActivityManager()->generateEvent();
187
+                $event->setApp('files_sharing')
188
+                    ->setType('remote_share')
189
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
190
+                    ->setAffectedUser($shareWith)
191
+                    ->setObject('remote_share', (int)$shareId, $name);
192
+                \OC::$server->getActivityManager()->publish($event);
193
+
194
+                $urlGenerator = \OC::$server->getURLGenerator();
195
+
196
+                $notificationManager = \OC::$server->getNotificationManager();
197
+                $notification = $notificationManager->createNotification();
198
+                $notification->setApp('files_sharing')
199
+                    ->setUser($shareWith)
200
+                    ->setDateTime(new \DateTime())
201
+                    ->setObject('remote_share', $shareId)
202
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
203
+
204
+                $declineAction = $notification->createAction();
205
+                $declineAction->setLabel('decline')
206
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
207
+                $notification->addAction($declineAction);
208
+
209
+                $acceptAction = $notification->createAction();
210
+                $acceptAction->setLabel('accept')
211
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
212
+                $notification->addAction($acceptAction);
213
+
214
+                $notificationManager->notify($notification);
215
+
216
+                return new Http\DataResponse();
217
+            } catch (\Exception $e) {
218
+                $this->logger->logException($e, [
219
+                    'message' => 'Server can not add remote share.',
220
+                    'level' => \OCP\Util::ERROR,
221
+                    'app' => 'files_sharing'
222
+                ]);
223
+                throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
224
+            }
225
+        }
226
+
227
+        throw new OCSException('server can not add remote share, missing parameter', 400);
228
+    }
229
+
230
+    /**
231
+     * @NoCSRFRequired
232
+     * @PublicPage
233
+     *
234
+     * create re-share on behalf of another user
235
+     *
236
+     * @param int $id
237
+     * @return Http\DataResponse
238
+     * @throws OCSBadRequestException
239
+     * @throws OCSForbiddenException
240
+     * @throws OCSNotFoundException
241
+     */
242
+    public function reShare($id) {
243
+
244
+        $token = $this->request->getParam('token', null);
245
+        $shareWith = $this->request->getParam('shareWith', null);
246
+        $permission = (int)$this->request->getParam('permission', null);
247
+        $remoteId = (int)$this->request->getParam('remoteId', null);
248
+
249
+        if ($id === null ||
250
+            $token === null ||
251
+            $shareWith === null ||
252
+            $permission === null ||
253
+            $remoteId === null
254
+        ) {
255
+            throw new OCSBadRequestException();
256
+        }
257
+
258
+        try {
259
+            $share = $this->federatedShareProvider->getShareById($id);
260
+        } catch (Share\Exceptions\ShareNotFound $e) {
261
+            throw new OCSNotFoundException();
262
+        }
263
+
264
+        // don't allow to share a file back to the owner
265
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
266
+        $owner = $share->getShareOwner();
267
+        $currentServer = $this->addressHandler->generateRemoteURL();
268
+        if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
269
+            throw new OCSForbiddenException();
270
+        }
271
+
272
+        if ($this->verifyShare($share, $token)) {
273
+
274
+            // check if re-sharing is allowed
275
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
276
+                $share->setPermissions($share->getPermissions() & $permission);
277
+                // the recipient of the initial share is now the initiator for the re-share
278
+                $share->setSharedBy($share->getSharedWith());
279
+                $share->setSharedWith($shareWith);
280
+                try {
281
+                    $result = $this->federatedShareProvider->create($share);
282
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
283
+                    return new Http\DataResponse([
284
+                        'token' => $result->getToken(),
285
+                        'remoteId' => $result->getId()
286
+                    ]);
287
+                } catch (\Exception $e) {
288
+                    throw new OCSBadRequestException();
289
+                }
290
+            } else {
291
+                throw new OCSForbiddenException();
292
+            }
293
+        }
294
+        throw new OCSBadRequestException();
295
+    }
296
+
297
+    /**
298
+     * @NoCSRFRequired
299
+     * @PublicPage
300
+     *
301
+     * accept server-to-server share
302
+     *
303
+     * @param int $id
304
+     * @return Http\DataResponse
305
+     * @throws OCSException
306
+     */
307
+    public function acceptShare($id) {
308
+
309
+        if (!$this->isS2SEnabled()) {
310
+            throw new OCSException('Server does not support federated cloud sharing', 503);
311
+        }
312
+
313
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
314
+
315
+        try {
316
+            $share = $this->federatedShareProvider->getShareById($id);
317
+        } catch (Share\Exceptions\ShareNotFound $e) {
318
+            return new Http\DataResponse();
319
+        }
320
+
321
+        if ($this->verifyShare($share, $token)) {
322
+            $this->executeAcceptShare($share);
323
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
324
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
325
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
326
+                $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
327
+            }
328
+        }
329
+
330
+        return new Http\DataResponse();
331
+    }
332
+
333
+    protected function executeAcceptShare(Share\IShare $share) {
334
+        $fileId = (int) $share->getNode()->getId();
335
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
336
+
337
+        $event = \OC::$server->getActivityManager()->generateEvent();
338
+        $event->setApp('files_sharing')
339
+            ->setType('remote_share')
340
+            ->setAffectedUser($this->getCorrectUid($share))
341
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
342
+            ->setObject('files', $fileId, $file)
343
+            ->setLink($link);
344
+        \OC::$server->getActivityManager()->publish($event);
345
+    }
346
+
347
+    /**
348
+     * @NoCSRFRequired
349
+     * @PublicPage
350
+     *
351
+     * decline server-to-server share
352
+     *
353
+     * @param int $id
354
+     * @return Http\DataResponse
355
+     * @throws OCSException
356
+     */
357
+    public function declineShare($id) {
358
+
359
+        if (!$this->isS2SEnabled()) {
360
+            throw new OCSException('Server does not support federated cloud sharing', 503);
361
+        }
362
+
363
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
364
+
365
+        try {
366
+            $share = $this->federatedShareProvider->getShareById($id);
367
+        } catch (Share\Exceptions\ShareNotFound $e) {
368
+            return new Http\DataResponse();
369
+        }
370
+
371
+        if ($this->verifyShare($share, $token)) {
372
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
373
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
374
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
375
+                $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
376
+            }
377
+            $this->executeDeclineShare($share);
378
+        }
379
+
380
+        return new Http\DataResponse();
381
+    }
382
+
383
+    /**
384
+     * delete declined share and create a activity
385
+     *
386
+     * @param Share\IShare $share
387
+     */
388
+    protected function executeDeclineShare(Share\IShare $share) {
389
+        $this->federatedShareProvider->removeShareFromTable($share);
390
+        $fileId = (int) $share->getNode()->getId();
391
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
392
+
393
+        $event = \OC::$server->getActivityManager()->generateEvent();
394
+        $event->setApp('files_sharing')
395
+            ->setType('remote_share')
396
+            ->setAffectedUser($this->getCorrectUid($share))
397
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
398
+            ->setObject('files', $fileId, $file)
399
+            ->setLink($link);
400
+        \OC::$server->getActivityManager()->publish($event);
401
+
402
+    }
403
+
404
+    /**
405
+     * check if we are the initiator or the owner of a re-share and return the correct UID
406
+     *
407
+     * @param Share\IShare $share
408
+     * @return string
409
+     */
410
+    protected function getCorrectUid(Share\IShare $share) {
411
+        if ($this->userManager->userExists($share->getShareOwner())) {
412
+            return $share->getShareOwner();
413
+        }
414
+
415
+        return $share->getSharedBy();
416
+    }
417
+
418
+    /**
419
+     * @NoCSRFRequired
420
+     * @PublicPage
421
+     *
422
+     * remove server-to-server share if it was unshared by the owner
423
+     *
424
+     * @param int $id
425
+     * @return Http\DataResponse
426
+     * @throws OCSException
427
+     */
428
+    public function unshare($id) {
429
+
430
+        if (!$this->isS2SEnabled()) {
431
+            throw new OCSException('Server does not support federated cloud sharing', 503);
432
+        }
433
+
434
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
435
+
436
+        $qb = $this->connection->getQueryBuilder();
437
+        $qb->select('*')
438
+            ->from('share_external')
439
+            ->where(
440
+                $qb->expr()->andX(
441
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
442
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
443
+                )
444
+            );
445
+
446
+        $result = $qb->execute();
447
+        $share = $result->fetch();
448
+        $result->closeCursor();
449
+
450
+        if ($token && $id && !empty($share)) {
451
+
452
+            $remote = $this->cleanupRemote($share['remote']);
453
+
454
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
455
+            $mountpoint = $share['mountpoint'];
456
+            $user = $share['user'];
457
+
458
+            $qb = $this->connection->getQueryBuilder();
459
+            $qb->delete('share_external')
460
+                ->where(
461
+                    $qb->expr()->andX(
462
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
463
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
464
+                    )
465
+                );
466
+
467
+            $result = $qb->execute();
468
+            $result->closeCursor();
469
+
470
+            if ($share['accepted']) {
471
+                $path = trim($mountpoint, '/');
472
+            } else {
473
+                $path = trim($share['name'], '/');
474
+            }
475
+
476
+            $notificationManager = \OC::$server->getNotificationManager();
477
+            $notification = $notificationManager->createNotification();
478
+            $notification->setApp('files_sharing')
479
+                ->setUser($share['user'])
480
+                ->setObject('remote_share', (int)$share['id']);
481
+            $notificationManager->markProcessed($notification);
482
+
483
+            $event = \OC::$server->getActivityManager()->generateEvent();
484
+            $event->setApp('files_sharing')
485
+                ->setType('remote_share')
486
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
487
+                ->setAffectedUser($user)
488
+                ->setObject('remote_share', (int)$share['id'], $path);
489
+            \OC::$server->getActivityManager()->publish($event);
490
+        }
491
+
492
+        return new Http\DataResponse();
493
+    }
494
+
495
+    private function cleanupRemote($remote) {
496
+        $remote = substr($remote, strpos($remote, '://') + 3);
497
+
498
+        return rtrim($remote, '/');
499
+    }
500
+
501
+
502
+    /**
503
+     * @NoCSRFRequired
504
+     * @PublicPage
505
+     *
506
+     * federated share was revoked, either by the owner or the re-sharer
507
+     *
508
+     * @param int $id
509
+     * @return Http\DataResponse
510
+     * @throws OCSBadRequestException
511
+     */
512
+    public function revoke($id) {
513
+        $token = $this->request->getParam('token');
514
+
515
+        $share = $this->federatedShareProvider->getShareById($id);
516
+
517
+        if ($this->verifyShare($share, $token)) {
518
+            $this->federatedShareProvider->removeShareFromTable($share);
519
+            return new Http\DataResponse();
520
+        }
521
+
522
+        throw new OCSBadRequestException();
523
+    }
524
+
525
+    /**
526
+     * get share
527
+     *
528
+     * @param int $id
529
+     * @param string $token
530
+     * @return array|bool
531
+     */
532
+    protected function getShare($id, $token) {
533
+        $query = $this->connection->getQueryBuilder();
534
+        $query->select('*')->from($this->shareTable)
535
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
536
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
537
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
538
+
539
+        $result = $query->execute()->fetchAll();
540
+
541
+        if (!empty($result) && isset($result[0])) {
542
+            return $result[0];
543
+        }
544
+
545
+        return false;
546
+    }
547
+
548
+    /**
549
+     * get file
550
+     *
551
+     * @param string $user
552
+     * @param int $fileSource
553
+     * @return array with internal path of the file and a absolute link to it
554
+     */
555
+    private function getFile($user, $fileSource) {
556
+        \OC_Util::setupFS($user);
557
+
558
+        try {
559
+            $file = \OC\Files\Filesystem::getPath($fileSource);
560
+        } catch (NotFoundException $e) {
561
+            $file = null;
562
+        }
563
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
564
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
565
+
566
+        return array($file, $link);
567
+
568
+    }
569
+
570
+    /**
571
+     * check if server-to-server sharing is enabled
572
+     *
573
+     * @param bool $incoming
574
+     * @return bool
575
+     */
576
+    private function isS2SEnabled($incoming = false) {
577
+
578
+        $result = \OCP\App::isEnabled('files_sharing');
579
+
580
+        if ($incoming) {
581
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
582
+        } else {
583
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
584
+        }
585
+
586
+        return $result;
587
+    }
588
+
589
+    /**
590
+     * check if we got the right share
591
+     *
592
+     * @param Share\IShare $share
593
+     * @param string $token
594
+     * @return bool
595
+     */
596
+    protected function verifyShare(Share\IShare $share, $token) {
597
+        if (
598
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
599
+            $share->getToken() === $token
600
+        ) {
601
+            return true;
602
+        }
603
+
604
+        return false;
605
+    }
606
+
607
+    /**
608
+     * @NoCSRFRequired
609
+     * @PublicPage
610
+     *
611
+     * update share information to keep federated re-shares in sync
612
+     *
613
+     * @param int $id
614
+     * @return Http\DataResponse
615
+     * @throws OCSBadRequestException
616
+     */
617
+    public function updatePermissions($id) {
618
+        $token = $this->request->getParam('token', null);
619
+        $permissions = $this->request->getParam('permissions', null);
620
+
621
+        try {
622
+            $share = $this->federatedShareProvider->getShareById($id);
623
+        } catch (Share\Exceptions\ShareNotFound $e) {
624
+            throw new OCSBadRequestException();
625
+        }
626
+
627
+        $validPermission = ctype_digit($permissions);
628
+        $validToken = $this->verifyShare($share, $token);
629
+        if ($validPermission && $validToken) {
630
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
631
+        } else {
632
+            throw new OCSBadRequestException();
633
+        }
634
+
635
+        return new Http\DataResponse();
636
+    }
637
+
638
+    /**
639
+     * update permissions in database
640
+     *
641
+     * @param IShare $share
642
+     * @param int $permissions
643
+     */
644
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
645
+        $query = $this->connection->getQueryBuilder();
646
+        $query->update('share')
647
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
648
+            ->set('permissions', $query->createNamedParameter($permissions))
649
+            ->execute();
650
+    }
651
+
652
+    /**
653
+     * @NoCSRFRequired
654
+     * @PublicPage
655
+     *
656
+     * change the owner of a server-to-server share
657
+     *
658
+     * @param int $id
659
+     * @return Http\DataResponse
660
+     * @throws \InvalidArgumentException
661
+     * @throws OCSException
662
+     */
663
+    public function move($id) {
664
+
665
+        if (!$this->isS2SEnabled()) {
666
+            throw new OCSException('Server does not support federated cloud sharing', 503);
667
+        }
668
+
669
+        $token = $this->request->getParam('token');
670
+        $remote = $this->request->getParam('remote');
671
+        $newRemoteId = $this->request->getParam('remote_id', $id);
672
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
673
+
674
+        $qb = $this->connection->getQueryBuilder();
675
+        $query = $qb->update('share_external')
676
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
677
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
678
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
679
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
680
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
681
+        $affected = $query->execute();
682
+
683
+        if ($affected > 0) {
684
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
685
+        } else {
686
+            throw new OCSBadRequestException('Share not found or token invalid');
687
+        }
688
+    }
689 689
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
136 136
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
137 137
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
138
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
138
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
139 139
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
140 140
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
141 141
 
@@ -146,13 +146,13 @@  discard block
 block discarded – undo
146 146
 			}
147 147
 
148 148
 			// FIXME this should be a method in the user management instead
149
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
149
+			$this->logger->debug('shareWith before, '.$shareWith, ['app' => 'files_sharing']);
150 150
 			\OCP\Util::emitHook(
151 151
 				'\OCA\Files_Sharing\API\Server2Server',
152 152
 				'preLoginNameUsedAsUserName',
153 153
 				array('uid' => &$shareWith)
154 154
 			);
155
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
155
+			$this->logger->debug('shareWith after, '.$shareWith, ['app' => 'files_sharing']);
156 156
 
157 157
 			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
158 158
 				throw new OCSException('User does not exists', 400);
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 					->setType('remote_share')
189 189
 					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
190 190
 					->setAffectedUser($shareWith)
191
-					->setObject('remote_share', (int)$shareId, $name);
191
+					->setObject('remote_share', (int) $shareId, $name);
192 192
 				\OC::$server->getActivityManager()->publish($event);
193 193
 
194 194
 				$urlGenerator = \OC::$server->getURLGenerator();
@@ -203,12 +203,12 @@  discard block
 block discarded – undo
203 203
 
204 204
 				$declineAction = $notification->createAction();
205 205
 				$declineAction->setLabel('decline')
206
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
206
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
207 207
 				$notification->addAction($declineAction);
208 208
 
209 209
 				$acceptAction = $notification->createAction();
210 210
 				$acceptAction->setLabel('accept')
211
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
211
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
212 212
 				$notification->addAction($acceptAction);
213 213
 
214 214
 				$notificationManager->notify($notification);
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 					'level' => \OCP\Util::ERROR,
221 221
 					'app' => 'files_sharing'
222 222
 				]);
223
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
223
+				throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
224 224
 			}
225 225
 		}
226 226
 
@@ -243,8 +243,8 @@  discard block
 block discarded – undo
243 243
 
244 244
 		$token = $this->request->getParam('token', null);
245 245
 		$shareWith = $this->request->getParam('shareWith', null);
246
-		$permission = (int)$this->request->getParam('permission', null);
247
-		$remoteId = (int)$this->request->getParam('remoteId', null);
246
+		$permission = (int) $this->request->getParam('permission', null);
247
+		$remoteId = (int) $this->request->getParam('remoteId', null);
248 248
 
249 249
 		if ($id === null ||
250 250
 			$token === null ||
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 				$share->setSharedWith($shareWith);
280 280
 				try {
281 281
 					$result = $this->federatedShareProvider->create($share);
282
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
282
+					$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $remoteId);
283 283
 					return new Http\DataResponse([
284 284
 						'token' => $result->getToken(),
285 285
 						'remoteId' => $result->getId()
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
 			$notification = $notificationManager->createNotification();
478 478
 			$notification->setApp('files_sharing')
479 479
 				->setUser($share['user'])
480
-				->setObject('remote_share', (int)$share['id']);
480
+				->setObject('remote_share', (int) $share['id']);
481 481
 			$notificationManager->markProcessed($notification);
482 482
 
483 483
 			$event = \OC::$server->getActivityManager()->generateEvent();
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 				->setType('remote_share')
486 486
 				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
487 487
 				->setAffectedUser($user)
488
-				->setObject('remote_share', (int)$share['id'], $path);
488
+				->setObject('remote_share', (int) $share['id'], $path);
489 489
 			\OC::$server->getActivityManager()->publish($event);
490 490
 		}
491 491
 
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
 		$validPermission = ctype_digit($permissions);
628 628
 		$validToken = $this->verifyShare($share, $token);
629 629
 		if ($validPermission && $validToken) {
630
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
630
+			$this->updatePermissionsInDatabase($share, (int) $permissions);
631 631
 		} else {
632 632
 			throw new OCSBadRequestException();
633 633
 		}
Please login to merge, or discard this patch.