Completed
Pull Request — master (#9345)
by Björn
20:43 queued 01:50
created
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 3 patches
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -29,7 +29,6 @@  discard block
 block discarded – undo
29 29
 
30 30
 namespace OCA\FederatedFileSharing\Controller;
31 31
 
32
-use OCA\Files_Sharing\Activity\Providers\RemoteShares;
33 32
 use OCA\FederatedFileSharing\AddressHandler;
34 33
 use OCA\FederatedFileSharing\FederatedShareProvider;
35 34
 use OCA\FederatedFileSharing\Notifications;
@@ -39,7 +38,6 @@  discard block
 block discarded – undo
39 38
 use OCP\AppFramework\OCS\OCSForbiddenException;
40 39
 use OCP\AppFramework\OCS\OCSNotFoundException;
41 40
 use OCP\AppFramework\OCSController;
42
-use OCP\Constants;
43 41
 use OCP\Federation\Exceptions\ProviderCouldNotAddShareException;
44 42
 use OCP\Federation\Exceptions\ProviderDoesNotExistsException;
45 43
 use OCP\Federation\Exceptions\ShareNotFoundException;
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
150 150
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
151 151
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
152
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
152
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
153 153
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
154 154
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
155 155
 
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 		} catch (ProviderCouldNotAddShareException $e) {
185 185
 			throw new OCSException($e->getMessage(), $e->getCode());
186 186
 		} catch (\Exception $e) {
187
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
187
+			throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
188 188
 		}
189 189
 
190 190
 		return new Http\DataResponse();
@@ -206,8 +206,8 @@  discard block
 block discarded – undo
206 206
 
207 207
 		$token = $this->request->getParam('token', null);
208 208
 		$shareWith = $this->request->getParam('shareWith', null);
209
-		$permission = (int)$this->request->getParam('permission', null);
210
-		$remoteId = (int)$this->request->getParam('remoteId', null);
209
+		$permission = (int) $this->request->getParam('permission', null);
210
+		$remoteId = (int) $this->request->getParam('remoteId', null);
211 211
 
212 212
 		if ($id === null ||
213 213
 			$token === null ||
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 		} catch (ProviderDoesNotExistsException $e) {
236 236
 			throw new OCSException('Server does not support federated cloud sharing', 503);
237 237
 		} catch (ShareNotFoundException $e) {
238
-			$this->logger->debug('Share not found: ' . $e->getMessage());
238
+			$this->logger->debug('Share not found: '.$e->getMessage());
239 239
 		} catch (ProviderCouldNotAddShareException $e) {
240
-			$this->logger->debug('Could not add reshare: ' . $e->getMessage());
240
+			$this->logger->debug('Could not add reshare: '.$e->getMessage());
241 241
 			throw new OCSForbiddenException();
242 242
 		} catch (\Exception $e) {
243
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
243
+			$this->logger->debug('internal server error, can not process notification: '.$e->getMessage());
244 244
 		}
245 245
 
246 246
 		throw new OCSBadRequestException();
@@ -274,9 +274,9 @@  discard block
 block discarded – undo
274 274
 		} catch (ProviderDoesNotExistsException $e) {
275 275
 			throw new OCSException('Server does not support federated cloud sharing', 503);
276 276
 		} catch (ShareNotFoundException $e) {
277
-			$this->logger->debug('Share not found: ' . $e->getMessage());
277
+			$this->logger->debug('Share not found: '.$e->getMessage());
278 278
 		} catch (\Exception $e) {
279
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
279
+			$this->logger->debug('internal server error, can not process notification: '.$e->getMessage());
280 280
 		}
281 281
 
282 282
 		return new Http\DataResponse();
@@ -307,9 +307,9 @@  discard block
 block discarded – undo
307 307
 		} catch (ProviderDoesNotExistsException $e) {
308 308
 			throw new OCSException('Server does not support federated cloud sharing', 503);
309 309
 		} catch (ShareNotFoundException $e) {
310
-			$this->logger->debug('Share not found: ' . $e->getMessage());
310
+			$this->logger->debug('Share not found: '.$e->getMessage());
311 311
 		} catch (\Exception $e) {
312
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
312
+			$this->logger->debug('internal server error, can not process notification: '.$e->getMessage());
313 313
 		}
314 314
 
315 315
 		return new Http\DataResponse();
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
 			$notification = ['sharedSecret' => $token];
339 339
 			$provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
340 340
 		} catch (\Exception $e) {
341
-			$this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
341
+			$this->logger->debug('processing unshare notification failed: '.$e->getMessage());
342 342
 		}
343 343
 
344 344
 		return new Http\DataResponse();
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
 		$validPermission = ctype_digit($permissions);
466 466
 		$validToken = $this->verifyShare($share, $token);
467 467
 		if ($validPermission && $validToken) {
468
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
468
+			$this->updatePermissionsInDatabase($share, (int) $permissions);
469 469
 		} else {
470 470
 			throw new OCSBadRequestException();
471 471
 		}
Please login to merge, or discard this patch.
Indentation   +468 added lines, -468 removed lines patch added patch discarded remove patch
@@ -56,472 +56,472 @@
 block discarded – undo
56 56
 
57 57
 class RequestHandlerController extends OCSController {
58 58
 
59
-	/** @var FederatedShareProvider */
60
-	private $federatedShareProvider;
61
-
62
-	/** @var IDBConnection */
63
-	private $connection;
64
-
65
-	/** @var Share\IManager */
66
-	private $shareManager;
67
-
68
-	/** @var Notifications */
69
-	private $notifications;
70
-
71
-	/** @var AddressHandler */
72
-	private $addressHandler;
73
-
74
-	/** @var  IUserManager */
75
-	private $userManager;
76
-
77
-	/** @var string */
78
-	private $shareTable = 'share';
79
-
80
-	/** @var ICloudIdManager */
81
-	private $cloudIdManager;
82
-
83
-	/** @var ILogger */
84
-	private $logger;
85
-
86
-	/** @var ICloudFederationFactory */
87
-	private $cloudFederationFactory;
88
-
89
-	/** @var ICloudFederationProviderManager */
90
-	private $cloudFederationProviderManager;
91
-
92
-	/**
93
-	 * Server2Server constructor.
94
-	 *
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param FederatedShareProvider $federatedShareProvider
98
-	 * @param IDBConnection $connection
99
-	 * @param Share\IManager $shareManager
100
-	 * @param Notifications $notifications
101
-	 * @param AddressHandler $addressHandler
102
-	 * @param IUserManager $userManager
103
-	 * @param ICloudIdManager $cloudIdManager
104
-	 * @param ILogger $logger
105
-	 * @param ICloudFederationFactory $cloudFederationFactory
106
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
107
-	 */
108
-	public function __construct($appName,
109
-								IRequest $request,
110
-								FederatedShareProvider $federatedShareProvider,
111
-								IDBConnection $connection,
112
-								Share\IManager $shareManager,
113
-								Notifications $notifications,
114
-								AddressHandler $addressHandler,
115
-								IUserManager $userManager,
116
-								ICloudIdManager $cloudIdManager,
117
-								ILogger $logger,
118
-								ICloudFederationFactory $cloudFederationFactory,
119
-								ICloudFederationProviderManager $cloudFederationProviderManager
120
-	) {
121
-		parent::__construct($appName, $request);
122
-
123
-		$this->federatedShareProvider = $federatedShareProvider;
124
-		$this->connection = $connection;
125
-		$this->shareManager = $shareManager;
126
-		$this->notifications = $notifications;
127
-		$this->addressHandler = $addressHandler;
128
-		$this->userManager = $userManager;
129
-		$this->cloudIdManager = $cloudIdManager;
130
-		$this->logger = $logger;
131
-		$this->cloudFederationFactory = $cloudFederationFactory;
132
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
133
-	}
134
-
135
-	/**
136
-	 * @NoCSRFRequired
137
-	 * @PublicPage
138
-	 *
139
-	 * create a new share
140
-	 *
141
-	 * @return Http\DataResponse
142
-	 * @throws OCSException
143
-	 */
144
-	public function createShare() {
145
-
146
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
147
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
148
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
149
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
150
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
151
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
152
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
153
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
154
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
155
-
156
-		if ($ownerFederatedId === null) {
157
-			$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
158
-		}
159
-		// if the owner of the share and the initiator are the same user
160
-		// we also complete the federated share ID for the initiator
161
-		if ($sharedByFederatedId === null && $owner === $sharedBy) {
162
-			$sharedByFederatedId = $ownerFederatedId;
163
-		}
164
-
165
-		$share = $this->cloudFederationFactory->getCloudFederationShare(
166
-			$shareWith,
167
-			$name,
168
-			'',
169
-			$remoteId,
170
-			$ownerFederatedId,
171
-			$owner,
172
-			$sharedByFederatedId,
173
-			$sharedBy,
174
-			$token,
175
-			'user',
176
-			'file'
177
-		);
178
-
179
-		try {
180
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
181
-			$provider->shareReceived($share);
182
-		} catch (ProviderDoesNotExistsException $e) {
183
-			throw new OCSException('Server does not support federated cloud sharing', 503);
184
-		} catch (ProviderCouldNotAddShareException $e) {
185
-			throw new OCSException($e->getMessage(), $e->getCode());
186
-		} catch (\Exception $e) {
187
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
188
-		}
189
-
190
-		return new Http\DataResponse();
191
-	}
192
-
193
-	/**
194
-	 * @NoCSRFRequired
195
-	 * @PublicPage
196
-	 *
197
-	 * create re-share on behalf of another user
198
-	 *
199
-	 * @param int $id
200
-	 * @return Http\DataResponse
201
-	 * @throws OCSBadRequestException
202
-	 * @throws OCSForbiddenException
203
-	 * @throws OCSNotFoundException
204
-	 */
205
-	public function reShare($id) {
206
-
207
-		$token = $this->request->getParam('token', null);
208
-		$shareWith = $this->request->getParam('shareWith', null);
209
-		$permission = (int)$this->request->getParam('permission', null);
210
-		$remoteId = (int)$this->request->getParam('remoteId', null);
211
-
212
-		if ($id === null ||
213
-			$token === null ||
214
-			$shareWith === null ||
215
-			$permission === null ||
216
-			$remoteId === null
217
-		) {
218
-			throw new OCSBadRequestException();
219
-		}
220
-
221
-		$notification = [
222
-			'sharedSecret' => $token,
223
-			'shareWith' => $shareWith,
224
-			'senderId' => $remoteId,
225
-			'message' => 'Recipient of a share ask the owner to reshare the file'
226
-		];
227
-
228
-		try {
229
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
230
-			list($newToken, $localId) = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
231
-			return new Http\DataResponse([
232
-				'token' => $newToken,
233
-				'remoteId' => $localId
234
-			]);
235
-		} catch (ProviderDoesNotExistsException $e) {
236
-			throw new OCSException('Server does not support federated cloud sharing', 503);
237
-		} catch (ShareNotFoundException $e) {
238
-			$this->logger->debug('Share not found: ' . $e->getMessage());
239
-		} catch (ProviderCouldNotAddShareException $e) {
240
-			$this->logger->debug('Could not add reshare: ' . $e->getMessage());
241
-			throw new OCSForbiddenException();
242
-		} catch (\Exception $e) {
243
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
244
-		}
245
-
246
-		throw new OCSBadRequestException();
247
-	}
248
-
249
-
250
-	/**
251
-	 * @NoCSRFRequired
252
-	 * @PublicPage
253
-	 *
254
-	 * accept server-to-server share
255
-	 *
256
-	 * @param int $id
257
-	 * @return Http\DataResponse
258
-	 * @throws OCSException
259
-	 * @throws Share\Exceptions\ShareNotFound
260
-	 * @throws \OC\HintException
261
-	 */
262
-	public function acceptShare($id) {
263
-
264
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
265
-
266
-		$notification = [
267
-			'sharedSecret' => $token,
268
-			'message' => 'Recipient accept the share'
269
-		];
270
-
271
-		try {
272
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
273
-			$provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
274
-		} catch (ProviderDoesNotExistsException $e) {
275
-			throw new OCSException('Server does not support federated cloud sharing', 503);
276
-		} catch (ShareNotFoundException $e) {
277
-			$this->logger->debug('Share not found: ' . $e->getMessage());
278
-		} catch (\Exception $e) {
279
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
280
-		}
281
-
282
-		return new Http\DataResponse();
283
-	}
284
-
285
-	/**
286
-	 * @NoCSRFRequired
287
-	 * @PublicPage
288
-	 *
289
-	 * decline server-to-server share
290
-	 *
291
-	 * @param int $id
292
-	 * @return Http\DataResponse
293
-	 * @throws OCSException
294
-	 */
295
-	public function declineShare($id) {
296
-
297
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
298
-
299
-		$notification = [
300
-			'sharedSecret' => $token,
301
-			'message' => 'Recipient declined the share'
302
-		];
303
-
304
-		try {
305
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
306
-			$provider->notificationReceived('SHARE_DECLINED', $id, $notification);
307
-		} catch (ProviderDoesNotExistsException $e) {
308
-			throw new OCSException('Server does not support federated cloud sharing', 503);
309
-		} catch (ShareNotFoundException $e) {
310
-			$this->logger->debug('Share not found: ' . $e->getMessage());
311
-		} catch (\Exception $e) {
312
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
313
-		}
314
-
315
-		return new Http\DataResponse();
316
-	}
317
-
318
-	/**
319
-	 * @NoCSRFRequired
320
-	 * @PublicPage
321
-	 *
322
-	 * remove server-to-server share if it was unshared by the owner
323
-	 *
324
-	 * @param int $id
325
-	 * @return Http\DataResponse
326
-	 * @throws OCSException
327
-	 */
328
-	public function unshare($id) {
329
-
330
-		if (!$this->isS2SEnabled()) {
331
-			throw new OCSException('Server does not support federated cloud sharing', 503);
332
-		}
333
-
334
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
335
-
336
-		try {
337
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
338
-			$notification = ['sharedSecret' => $token];
339
-			$provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
340
-		} catch (\Exception $e) {
341
-			$this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
342
-		}
343
-
344
-		return new Http\DataResponse();
345
-	}
346
-
347
-	private function cleanupRemote($remote) {
348
-		$remote = substr($remote, strpos($remote, '://') + 3);
349
-
350
-		return rtrim($remote, '/');
351
-	}
352
-
353
-
354
-	/**
355
-	 * @NoCSRFRequired
356
-	 * @PublicPage
357
-	 *
358
-	 * federated share was revoked, either by the owner or the re-sharer
359
-	 *
360
-	 * @param int $id
361
-	 * @return Http\DataResponse
362
-	 * @throws OCSBadRequestException
363
-	 */
364
-	public function revoke($id) {
365
-
366
-		$token = $this->request->getParam('token');
367
-
368
-		$notification = $this->cloudFederationFactory->getCloudFederationNotification();
369
-		$notification->setMessage(['sharedSecret' => $token]);
370
-
371
-		try {
372
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
373
-			$provider->notificationReceived('RESHARE_UNDO', $id, $notification);
374
-			return new Http\DataResponse();
375
-		} catch (\Exception $e) {
376
-			throw new OCSBadRequestException();
377
-		}
378
-
379
-	}
380
-
381
-	/**
382
-	 * get share
383
-	 *
384
-	 * @param int $id
385
-	 * @param string $token
386
-	 * @return array|bool
387
-	 */
388
-	protected function getShare($id, $token) {
389
-		$query = $this->connection->getQueryBuilder();
390
-		$query->select('*')->from($this->shareTable)
391
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
392
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
393
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
394
-
395
-		$result = $query->execute()->fetchAll();
396
-
397
-		if (!empty($result) && isset($result[0])) {
398
-			return $result[0];
399
-		}
400
-
401
-		return false;
402
-	}
403
-
404
-	/**
405
-	 * get file
406
-	 *
407
-	 * @param string $user
408
-	 * @param int $fileSource
409
-	 * @return array with internal path of the file and a absolute link to it
410
-	 */
411
-	private function getFile($user, $fileSource) {
412
-		\OC_Util::setupFS($user);
413
-
414
-		try {
415
-			$file = \OC\Files\Filesystem::getPath($fileSource);
416
-		} catch (NotFoundException $e) {
417
-			$file = null;
418
-		}
419
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
420
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
421
-
422
-		return array($file, $link);
423
-
424
-	}
425
-
426
-	/**
427
-	 * check if server-to-server sharing is enabled
428
-	 *
429
-	 * @param bool $incoming
430
-	 * @return bool
431
-	 */
432
-	private function isS2SEnabled($incoming = false) {
433
-
434
-		$result = \OCP\App::isEnabled('files_sharing');
435
-
436
-		if ($incoming) {
437
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
438
-		} else {
439
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
440
-		}
441
-
442
-		return $result;
443
-	}
444
-
445
-	/**
446
-	 * @NoCSRFRequired
447
-	 * @PublicPage
448
-	 *
449
-	 * update share information to keep federated re-shares in sync
450
-	 *
451
-	 * @param int $id
452
-	 * @return Http\DataResponse
453
-	 * @throws OCSBadRequestException
454
-	 */
455
-	public function updatePermissions($id) {
456
-		$token = $this->request->getParam('token', null);
457
-		$permissions = $this->request->getParam('permissions', null);
458
-
459
-		try {
460
-			$share = $this->federatedShareProvider->getShareById($id);
461
-		} catch (Share\Exceptions\ShareNotFound $e) {
462
-			throw new OCSBadRequestException();
463
-		}
464
-
465
-		$validPermission = ctype_digit($permissions);
466
-		$validToken = $this->verifyShare($share, $token);
467
-		if ($validPermission && $validToken) {
468
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
469
-		} else {
470
-			throw new OCSBadRequestException();
471
-		}
472
-
473
-		return new Http\DataResponse();
474
-	}
475
-
476
-	/**
477
-	 * update permissions in database
478
-	 *
479
-	 * @param IShare $share
480
-	 * @param int $permissions
481
-	 */
482
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
483
-		$query = $this->connection->getQueryBuilder();
484
-		$query->update('share')
485
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
486
-			->set('permissions', $query->createNamedParameter($permissions))
487
-			->execute();
488
-	}
489
-
490
-	/**
491
-	 * @NoCSRFRequired
492
-	 * @PublicPage
493
-	 *
494
-	 * change the owner of a server-to-server share
495
-	 *
496
-	 * @param int $id
497
-	 * @return Http\DataResponse
498
-	 * @throws \InvalidArgumentException
499
-	 * @throws OCSException
500
-	 */
501
-	public function move($id) {
502
-
503
-		if (!$this->isS2SEnabled()) {
504
-			throw new OCSException('Server does not support federated cloud sharing', 503);
505
-		}
506
-
507
-		$token = $this->request->getParam('token');
508
-		$remote = $this->request->getParam('remote');
509
-		$newRemoteId = $this->request->getParam('remote_id', $id);
510
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
511
-
512
-		$qb = $this->connection->getQueryBuilder();
513
-		$query = $qb->update('share_external')
514
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
515
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
516
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
517
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
518
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
519
-		$affected = $query->execute();
520
-
521
-		if ($affected > 0) {
522
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
523
-		} else {
524
-			throw new OCSBadRequestException('Share not found or token invalid');
525
-		}
526
-	}
59
+    /** @var FederatedShareProvider */
60
+    private $federatedShareProvider;
61
+
62
+    /** @var IDBConnection */
63
+    private $connection;
64
+
65
+    /** @var Share\IManager */
66
+    private $shareManager;
67
+
68
+    /** @var Notifications */
69
+    private $notifications;
70
+
71
+    /** @var AddressHandler */
72
+    private $addressHandler;
73
+
74
+    /** @var  IUserManager */
75
+    private $userManager;
76
+
77
+    /** @var string */
78
+    private $shareTable = 'share';
79
+
80
+    /** @var ICloudIdManager */
81
+    private $cloudIdManager;
82
+
83
+    /** @var ILogger */
84
+    private $logger;
85
+
86
+    /** @var ICloudFederationFactory */
87
+    private $cloudFederationFactory;
88
+
89
+    /** @var ICloudFederationProviderManager */
90
+    private $cloudFederationProviderManager;
91
+
92
+    /**
93
+     * Server2Server constructor.
94
+     *
95
+     * @param string $appName
96
+     * @param IRequest $request
97
+     * @param FederatedShareProvider $federatedShareProvider
98
+     * @param IDBConnection $connection
99
+     * @param Share\IManager $shareManager
100
+     * @param Notifications $notifications
101
+     * @param AddressHandler $addressHandler
102
+     * @param IUserManager $userManager
103
+     * @param ICloudIdManager $cloudIdManager
104
+     * @param ILogger $logger
105
+     * @param ICloudFederationFactory $cloudFederationFactory
106
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
107
+     */
108
+    public function __construct($appName,
109
+                                IRequest $request,
110
+                                FederatedShareProvider $federatedShareProvider,
111
+                                IDBConnection $connection,
112
+                                Share\IManager $shareManager,
113
+                                Notifications $notifications,
114
+                                AddressHandler $addressHandler,
115
+                                IUserManager $userManager,
116
+                                ICloudIdManager $cloudIdManager,
117
+                                ILogger $logger,
118
+                                ICloudFederationFactory $cloudFederationFactory,
119
+                                ICloudFederationProviderManager $cloudFederationProviderManager
120
+    ) {
121
+        parent::__construct($appName, $request);
122
+
123
+        $this->federatedShareProvider = $federatedShareProvider;
124
+        $this->connection = $connection;
125
+        $this->shareManager = $shareManager;
126
+        $this->notifications = $notifications;
127
+        $this->addressHandler = $addressHandler;
128
+        $this->userManager = $userManager;
129
+        $this->cloudIdManager = $cloudIdManager;
130
+        $this->logger = $logger;
131
+        $this->cloudFederationFactory = $cloudFederationFactory;
132
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
133
+    }
134
+
135
+    /**
136
+     * @NoCSRFRequired
137
+     * @PublicPage
138
+     *
139
+     * create a new share
140
+     *
141
+     * @return Http\DataResponse
142
+     * @throws OCSException
143
+     */
144
+    public function createShare() {
145
+
146
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
147
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
148
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
149
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
150
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
151
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
152
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
153
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
154
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
155
+
156
+        if ($ownerFederatedId === null) {
157
+            $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
158
+        }
159
+        // if the owner of the share and the initiator are the same user
160
+        // we also complete the federated share ID for the initiator
161
+        if ($sharedByFederatedId === null && $owner === $sharedBy) {
162
+            $sharedByFederatedId = $ownerFederatedId;
163
+        }
164
+
165
+        $share = $this->cloudFederationFactory->getCloudFederationShare(
166
+            $shareWith,
167
+            $name,
168
+            '',
169
+            $remoteId,
170
+            $ownerFederatedId,
171
+            $owner,
172
+            $sharedByFederatedId,
173
+            $sharedBy,
174
+            $token,
175
+            'user',
176
+            'file'
177
+        );
178
+
179
+        try {
180
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
181
+            $provider->shareReceived($share);
182
+        } catch (ProviderDoesNotExistsException $e) {
183
+            throw new OCSException('Server does not support federated cloud sharing', 503);
184
+        } catch (ProviderCouldNotAddShareException $e) {
185
+            throw new OCSException($e->getMessage(), $e->getCode());
186
+        } catch (\Exception $e) {
187
+            throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
188
+        }
189
+
190
+        return new Http\DataResponse();
191
+    }
192
+
193
+    /**
194
+     * @NoCSRFRequired
195
+     * @PublicPage
196
+     *
197
+     * create re-share on behalf of another user
198
+     *
199
+     * @param int $id
200
+     * @return Http\DataResponse
201
+     * @throws OCSBadRequestException
202
+     * @throws OCSForbiddenException
203
+     * @throws OCSNotFoundException
204
+     */
205
+    public function reShare($id) {
206
+
207
+        $token = $this->request->getParam('token', null);
208
+        $shareWith = $this->request->getParam('shareWith', null);
209
+        $permission = (int)$this->request->getParam('permission', null);
210
+        $remoteId = (int)$this->request->getParam('remoteId', null);
211
+
212
+        if ($id === null ||
213
+            $token === null ||
214
+            $shareWith === null ||
215
+            $permission === null ||
216
+            $remoteId === null
217
+        ) {
218
+            throw new OCSBadRequestException();
219
+        }
220
+
221
+        $notification = [
222
+            'sharedSecret' => $token,
223
+            'shareWith' => $shareWith,
224
+            'senderId' => $remoteId,
225
+            'message' => 'Recipient of a share ask the owner to reshare the file'
226
+        ];
227
+
228
+        try {
229
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
230
+            list($newToken, $localId) = $provider->notificationReceived('REQUEST_RESHARE', $id, $notification);
231
+            return new Http\DataResponse([
232
+                'token' => $newToken,
233
+                'remoteId' => $localId
234
+            ]);
235
+        } catch (ProviderDoesNotExistsException $e) {
236
+            throw new OCSException('Server does not support federated cloud sharing', 503);
237
+        } catch (ShareNotFoundException $e) {
238
+            $this->logger->debug('Share not found: ' . $e->getMessage());
239
+        } catch (ProviderCouldNotAddShareException $e) {
240
+            $this->logger->debug('Could not add reshare: ' . $e->getMessage());
241
+            throw new OCSForbiddenException();
242
+        } catch (\Exception $e) {
243
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
244
+        }
245
+
246
+        throw new OCSBadRequestException();
247
+    }
248
+
249
+
250
+    /**
251
+     * @NoCSRFRequired
252
+     * @PublicPage
253
+     *
254
+     * accept server-to-server share
255
+     *
256
+     * @param int $id
257
+     * @return Http\DataResponse
258
+     * @throws OCSException
259
+     * @throws Share\Exceptions\ShareNotFound
260
+     * @throws \OC\HintException
261
+     */
262
+    public function acceptShare($id) {
263
+
264
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
265
+
266
+        $notification = [
267
+            'sharedSecret' => $token,
268
+            'message' => 'Recipient accept the share'
269
+        ];
270
+
271
+        try {
272
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
273
+            $provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
274
+        } catch (ProviderDoesNotExistsException $e) {
275
+            throw new OCSException('Server does not support federated cloud sharing', 503);
276
+        } catch (ShareNotFoundException $e) {
277
+            $this->logger->debug('Share not found: ' . $e->getMessage());
278
+        } catch (\Exception $e) {
279
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
280
+        }
281
+
282
+        return new Http\DataResponse();
283
+    }
284
+
285
+    /**
286
+     * @NoCSRFRequired
287
+     * @PublicPage
288
+     *
289
+     * decline server-to-server share
290
+     *
291
+     * @param int $id
292
+     * @return Http\DataResponse
293
+     * @throws OCSException
294
+     */
295
+    public function declineShare($id) {
296
+
297
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
298
+
299
+        $notification = [
300
+            'sharedSecret' => $token,
301
+            'message' => 'Recipient declined the share'
302
+        ];
303
+
304
+        try {
305
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
306
+            $provider->notificationReceived('SHARE_DECLINED', $id, $notification);
307
+        } catch (ProviderDoesNotExistsException $e) {
308
+            throw new OCSException('Server does not support federated cloud sharing', 503);
309
+        } catch (ShareNotFoundException $e) {
310
+            $this->logger->debug('Share not found: ' . $e->getMessage());
311
+        } catch (\Exception $e) {
312
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
313
+        }
314
+
315
+        return new Http\DataResponse();
316
+    }
317
+
318
+    /**
319
+     * @NoCSRFRequired
320
+     * @PublicPage
321
+     *
322
+     * remove server-to-server share if it was unshared by the owner
323
+     *
324
+     * @param int $id
325
+     * @return Http\DataResponse
326
+     * @throws OCSException
327
+     */
328
+    public function unshare($id) {
329
+
330
+        if (!$this->isS2SEnabled()) {
331
+            throw new OCSException('Server does not support federated cloud sharing', 503);
332
+        }
333
+
334
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
335
+
336
+        try {
337
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
338
+            $notification = ['sharedSecret' => $token];
339
+            $provider->notificationReceived('SHARE_UNSHARED', $id, $notification);
340
+        } catch (\Exception $e) {
341
+            $this->logger->debug('processing unshare notification failed: ' . $e->getMessage());
342
+        }
343
+
344
+        return new Http\DataResponse();
345
+    }
346
+
347
+    private function cleanupRemote($remote) {
348
+        $remote = substr($remote, strpos($remote, '://') + 3);
349
+
350
+        return rtrim($remote, '/');
351
+    }
352
+
353
+
354
+    /**
355
+     * @NoCSRFRequired
356
+     * @PublicPage
357
+     *
358
+     * federated share was revoked, either by the owner or the re-sharer
359
+     *
360
+     * @param int $id
361
+     * @return Http\DataResponse
362
+     * @throws OCSBadRequestException
363
+     */
364
+    public function revoke($id) {
365
+
366
+        $token = $this->request->getParam('token');
367
+
368
+        $notification = $this->cloudFederationFactory->getCloudFederationNotification();
369
+        $notification->setMessage(['sharedSecret' => $token]);
370
+
371
+        try {
372
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
373
+            $provider->notificationReceived('RESHARE_UNDO', $id, $notification);
374
+            return new Http\DataResponse();
375
+        } catch (\Exception $e) {
376
+            throw new OCSBadRequestException();
377
+        }
378
+
379
+    }
380
+
381
+    /**
382
+     * get share
383
+     *
384
+     * @param int $id
385
+     * @param string $token
386
+     * @return array|bool
387
+     */
388
+    protected function getShare($id, $token) {
389
+        $query = $this->connection->getQueryBuilder();
390
+        $query->select('*')->from($this->shareTable)
391
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
392
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
393
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
394
+
395
+        $result = $query->execute()->fetchAll();
396
+
397
+        if (!empty($result) && isset($result[0])) {
398
+            return $result[0];
399
+        }
400
+
401
+        return false;
402
+    }
403
+
404
+    /**
405
+     * get file
406
+     *
407
+     * @param string $user
408
+     * @param int $fileSource
409
+     * @return array with internal path of the file and a absolute link to it
410
+     */
411
+    private function getFile($user, $fileSource) {
412
+        \OC_Util::setupFS($user);
413
+
414
+        try {
415
+            $file = \OC\Files\Filesystem::getPath($fileSource);
416
+        } catch (NotFoundException $e) {
417
+            $file = null;
418
+        }
419
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
420
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
421
+
422
+        return array($file, $link);
423
+
424
+    }
425
+
426
+    /**
427
+     * check if server-to-server sharing is enabled
428
+     *
429
+     * @param bool $incoming
430
+     * @return bool
431
+     */
432
+    private function isS2SEnabled($incoming = false) {
433
+
434
+        $result = \OCP\App::isEnabled('files_sharing');
435
+
436
+        if ($incoming) {
437
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
438
+        } else {
439
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
440
+        }
441
+
442
+        return $result;
443
+    }
444
+
445
+    /**
446
+     * @NoCSRFRequired
447
+     * @PublicPage
448
+     *
449
+     * update share information to keep federated re-shares in sync
450
+     *
451
+     * @param int $id
452
+     * @return Http\DataResponse
453
+     * @throws OCSBadRequestException
454
+     */
455
+    public function updatePermissions($id) {
456
+        $token = $this->request->getParam('token', null);
457
+        $permissions = $this->request->getParam('permissions', null);
458
+
459
+        try {
460
+            $share = $this->federatedShareProvider->getShareById($id);
461
+        } catch (Share\Exceptions\ShareNotFound $e) {
462
+            throw new OCSBadRequestException();
463
+        }
464
+
465
+        $validPermission = ctype_digit($permissions);
466
+        $validToken = $this->verifyShare($share, $token);
467
+        if ($validPermission && $validToken) {
468
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
469
+        } else {
470
+            throw new OCSBadRequestException();
471
+        }
472
+
473
+        return new Http\DataResponse();
474
+    }
475
+
476
+    /**
477
+     * update permissions in database
478
+     *
479
+     * @param IShare $share
480
+     * @param int $permissions
481
+     */
482
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
483
+        $query = $this->connection->getQueryBuilder();
484
+        $query->update('share')
485
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
486
+            ->set('permissions', $query->createNamedParameter($permissions))
487
+            ->execute();
488
+    }
489
+
490
+    /**
491
+     * @NoCSRFRequired
492
+     * @PublicPage
493
+     *
494
+     * change the owner of a server-to-server share
495
+     *
496
+     * @param int $id
497
+     * @return Http\DataResponse
498
+     * @throws \InvalidArgumentException
499
+     * @throws OCSException
500
+     */
501
+    public function move($id) {
502
+
503
+        if (!$this->isS2SEnabled()) {
504
+            throw new OCSException('Server does not support federated cloud sharing', 503);
505
+        }
506
+
507
+        $token = $this->request->getParam('token');
508
+        $remote = $this->request->getParam('remote');
509
+        $newRemoteId = $this->request->getParam('remote_id', $id);
510
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
511
+
512
+        $qb = $this->connection->getQueryBuilder();
513
+        $query = $qb->update('share_external')
514
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
515
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
516
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
517
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
518
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
519
+        $affected = $query->execute();
520
+
521
+        if ($affected > 0) {
522
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
523
+        } else {
524
+            throw new OCSBadRequestException('Share not found or token invalid');
525
+        }
526
+    }
527 527
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -27,7 +27,6 @@
 block discarded – undo
27 27
 use OCA\FederatedFileSharing\AddressHandler;
28 28
 use OCA\FederatedFileSharing\FederatedShareProvider;
29 29
 use OCP\Activity\IManager as IActivityManager;
30
-use OCP\Activity\IManager;
31 30
 use OCP\App\IAppManager;
32 31
 use OCP\Constants;
33 32
 use OCP\Federation\Exceptions\ActionNotSupportedException;
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -188,16 +188,16 @@  discard block
 block discarded – undo
188 188
 			}
189 189
 
190 190
 			// FIXME this should be a method in the user management instead
191
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
191
+			$this->logger->debug('shareWith before, '.$shareWith, ['app' => 'files_sharing']);
192 192
 			Util::emitHook(
193 193
 				'\OCA\Files_Sharing\API\Server2Server',
194 194
 				'preLoginNameUsedAsUserName',
195 195
 				array('uid' => &$shareWith)
196 196
 			);
197
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
197
+			$this->logger->debug('shareWith after, '.$shareWith, ['app' => 'files_sharing']);
198 198
 
199 199
 			if (!$this->userManager->userExists($shareWith)) {
200
-				throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
200
+				throw new ProviderCouldNotAddShareException('User does not exists', '', Http::STATUS_BAD_REQUEST);
201 201
 			}
202 202
 
203 203
 			\OC_Util::setupFS($shareWith);
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 					->setType('remote_share')
224 224
 					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
225 225
 					->setAffectedUser($shareWith)
226
-					->setObject('remote_share', (int)$shareId, $name);
226
+					->setObject('remote_share', (int) $shareId, $name);
227 227
 				\OC::$server->getActivityManager()->publish($event);
228 228
 
229 229
 				$notification = $this->notificationManager->createNotification();
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 
236 236
 				$declineAction = $notification->createAction();
237 237
 				$declineAction->setLabel('decline')
238
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
238
+					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
239 239
 				$notification->addAction($declineAction);
240 240
 
241 241
 				$acceptAction = $notification->createAction();
242 242
 				$acceptAction->setLabel('accept')
243
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
243
+					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
244 244
 				$notification->addAction($acceptAction);
245 245
 
246 246
 				$this->notificationManager->notify($notification);
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 					'level' => Util::ERROR,
253 253
 					'app' => 'files_sharing'
254 254
 				]);
255
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
255
+				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from '.$remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
256 256
 			}
257 257
 		}
258 258
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 	 */
350 350
 	protected function executeAcceptShare(IShare $share) {
351 351
 		try {
352
-			$fileId = (int)$share->getNode()->getId();
352
+			$fileId = (int) $share->getNode()->getId();
353 353
 			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
354 354
 		} catch (\Exception $e) {
355 355
 			throw new ShareNotFoundException();
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 		$this->federatedShareProvider->removeShareFromTable($share);
429 429
 
430 430
 		try {
431
-			$fileId = (int)$share->getNode()->getId();
431
+			$fileId = (int) $share->getNode()->getId();
432 432
 			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
433 433
 		} catch (\Exception $e) {
434 434
 			throw new ShareNotFoundException();
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 			$notification = $this->notificationManager->createNotification();
523 523
 			$notification->setApp('files_sharing')
524 524
 				->setUser($share['user'])
525
-				->setObject('remote_share', (int)$share['id']);
525
+				->setObject('remote_share', (int) $share['id']);
526 526
 			$this->notificationManager->markProcessed($notification);
527 527
 
528 528
 			$event = $this->activityManager->generateEvent();
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 				->setType('remote_share')
531 531
 				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
532 532
 				->setAffectedUser($user)
533
-				->setObject('remote_share', (int)$share['id'], $path);
533
+				->setObject('remote_share', (int) $share['id'], $path);
534 534
 			\OC::$server->getActivityManager()->publish($event);
535 535
 		}
536 536
 
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 			$owner = $share->getShareOwner();
580 580
 			$currentServer = $this->addressHandler->generateRemoteURL();
581 581
 			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
582
-				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
582
+				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: '.$id);
583 583
 			}
584 584
 		} catch (\Exception $e) {
585 585
 			throw new ProviderCouldNotAddShareException($e->getMessage());
@@ -593,10 +593,10 @@  discard block
 block discarded – undo
593 593
 			$share->setSharedBy($share->getSharedWith());
594 594
 			$share->setSharedWith($shareWith);
595 595
 			$result = $this->federatedShareProvider->create($share);
596
-			$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
596
+			$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $senderId);
597 597
 			return ['token' => $result->getToken(), 'providerId' => $result->getId()];
598 598
 		} else {
599
-			throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
599
+			throw new ProviderCouldNotAddShareException('resharing not allowed for share: '.$id);
600 600
 		}
601 601
 
602 602
 		throw new BadRequestException([]);
Please login to merge, or discard this patch.
Doc Comments   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 * share received from another server
145 145
 	 *
146 146
 	 * @param ICloudFederationShare $share
147
-	 * @return string provider specific unique ID of the share
147
+	 * @return integer provider specific unique ID of the share
148 148
 	 *
149 149
 	 * @throws ProviderCouldNotAddShareException
150 150
 	 * @throws \OCP\AppFramework\QueryException
@@ -468,6 +468,9 @@  discard block
 block discarded – undo
468 468
 		return [];
469 469
 	}
470 470
 
471
+	/**
472
+	 * @param string $id
473
+	 */
471 474
 	private function unshare($id, $notification) {
472 475
 
473 476
 		if (!$this->isS2SEnabled(true)) {
@@ -545,7 +548,7 @@  discard block
 block discarded – undo
545 548
 	/**
546 549
 	 * recipient of a share request to re-share the file with another user
547 550
 	 *
548
-	 * @param $id
551
+	 * @param string $id
549 552
 	 * @param $notification
550 553
 	 * @return array
551 554
 	 * @throws AuthenticationFailedException
Please login to merge, or discard this patch.
Indentation   +626 added lines, -626 removed lines patch added patch discarded remove patch
@@ -52,632 +52,632 @@
 block discarded – undo
52 52
 
53 53
 class CloudFederationProviderFiles implements ICloudFederationProvider {
54 54
 
55
-	/** @var IAppManager */
56
-	private $appManager;
57
-
58
-	/** @var FederatedShareProvider */
59
-	private $federatedShareProvider;
60
-
61
-	/** @var AddressHandler */
62
-	private $addressHandler;
63
-
64
-	/** @var ILogger */
65
-	private $logger;
66
-
67
-	/** @var IUserManager */
68
-	private $userManager;
69
-
70
-	/** @var ICloudIdManager */
71
-	private $cloudIdManager;
72
-
73
-	/** @var IActivityManager */
74
-	private $activityManager;
75
-
76
-	/** @var INotificationManager */
77
-	private $notificationManager;
78
-
79
-	/** @var IURLGenerator */
80
-	private $urlGenerator;
81
-
82
-	/** @var ICloudFederationFactory */
83
-	private $cloudFederationFactory;
84
-
85
-	/** @var ICloudFederationProviderManager */
86
-	private $cloudFederationProviderManager;
87
-
88
-	/** @var IDBConnection */
89
-	private $connection;
90
-
91
-	/**
92
-	 * CloudFederationProvider constructor.
93
-	 *
94
-	 * @param IAppManager $appManager
95
-	 * @param FederatedShareProvider $federatedShareProvider
96
-	 * @param AddressHandler $addressHandler
97
-	 * @param ILogger $logger
98
-	 * @param IUserManager $userManager
99
-	 * @param ICloudIdManager $cloudIdManager
100
-	 * @param IActivityManager $activityManager
101
-	 * @param INotificationManager $notificationManager
102
-	 * @param IURLGenerator $urlGenerator
103
-	 * @param ICloudFederationFactory $cloudFederationFactory
104
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
105
-	 * @param IDBConnection $connection
106
-	 */
107
-	public function __construct(IAppManager $appManager,
108
-								FederatedShareProvider $federatedShareProvider,
109
-								AddressHandler $addressHandler,
110
-								ILogger $logger,
111
-								IUserManager $userManager,
112
-								ICloudIdManager $cloudIdManager,
113
-								IActivityManager $activityManager,
114
-								INotificationManager $notificationManager,
115
-								IURLGenerator $urlGenerator,
116
-								ICloudFederationFactory $cloudFederationFactory,
117
-								ICloudFederationProviderManager $cloudFederationProviderManager,
118
-								IDBConnection $connection
119
-	) {
120
-		$this->appManager = $appManager;
121
-		$this->federatedShareProvider = $federatedShareProvider;
122
-		$this->addressHandler = $addressHandler;
123
-		$this->logger = $logger;
124
-		$this->userManager = $userManager;
125
-		$this->cloudIdManager = $cloudIdManager;
126
-		$this->activityManager = $activityManager;
127
-		$this->notificationManager = $notificationManager;
128
-		$this->urlGenerator = $urlGenerator;
129
-		$this->cloudFederationFactory = $cloudFederationFactory;
130
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
131
-		$this->connection = $connection;
132
-	}
133
-
134
-
135
-
136
-	/**
137
-	 * @return string
138
-	 */
139
-	public function getShareType() {
140
-		return 'file';
141
-	}
142
-
143
-	/**
144
-	 * share received from another server
145
-	 *
146
-	 * @param ICloudFederationShare $share
147
-	 * @return string provider specific unique ID of the share
148
-	 *
149
-	 * @throws ProviderCouldNotAddShareException
150
-	 * @throws \OCP\AppFramework\QueryException
151
-	 * @throws \OC\HintException
152
-	 * @since 14.0.0
153
-	 */
154
-	public function shareReceived(ICloudFederationShare $share) {
155
-
156
-		if (!$this->isS2SEnabled(true)) {
157
-			throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
158
-		}
159
-
160
-		$protocol = $share->getProtocol();
161
-		if ($protocol['name'] !== 'webdav') {
162
-			throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
163
-		}
164
-
165
-		list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
166
-
167
-		$remote = $remote;
168
-		$token = $share->getShareSecret();
169
-		$name = $share->getResourceName();
170
-		$owner = $share->getOwnerDisplayName();
171
-		$sharedBy = $share->getSharedByDisplayName();
172
-		$shareWith = $share->getShareWith();
173
-		$remoteId = $share->getProviderId();
174
-		$sharedByFederatedId = $share->getSharedBy();
175
-		$ownerFederatedId = $share->getOwner();
176
-
177
-		// if no explicit information about the person who created the share was send
178
-		// we assume that the share comes from the owner
179
-		if ($sharedByFederatedId === null) {
180
-			$sharedBy = $owner;
181
-			$sharedByFederatedId = $ownerFederatedId;
182
-		}
183
-
184
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
185
-
186
-			if (!Util::isValidFileName($name)) {
187
-				throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
188
-			}
189
-
190
-			// FIXME this should be a method in the user management instead
191
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
192
-			Util::emitHook(
193
-				'\OCA\Files_Sharing\API\Server2Server',
194
-				'preLoginNameUsedAsUserName',
195
-				array('uid' => &$shareWith)
196
-			);
197
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
198
-
199
-			if (!$this->userManager->userExists($shareWith)) {
200
-				throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
201
-			}
202
-
203
-			\OC_Util::setupFS($shareWith);
204
-
205
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
206
-				\OC::$server->getDatabaseConnection(),
207
-				Filesystem::getMountManager(),
208
-				Filesystem::getLoader(),
209
-				\OC::$server->getHTTPClientService(),
210
-				\OC::$server->getNotificationManager(),
211
-				\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
212
-				\OC::$server->getCloudFederationProviderManager(),
213
-				\OC::$server->getCloudFederationFactory(),
214
-				$shareWith
215
-			);
216
-
217
-			try {
218
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
219
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
220
-
221
-				$event = $this->activityManager->generateEvent();
222
-				$event->setApp('files_sharing')
223
-					->setType('remote_share')
224
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
225
-					->setAffectedUser($shareWith)
226
-					->setObject('remote_share', (int)$shareId, $name);
227
-				\OC::$server->getActivityManager()->publish($event);
228
-
229
-				$notification = $this->notificationManager->createNotification();
230
-				$notification->setApp('files_sharing')
231
-					->setUser($shareWith)
232
-					->setDateTime(new \DateTime())
233
-					->setObject('remote_share', $shareId)
234
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
235
-
236
-				$declineAction = $notification->createAction();
237
-				$declineAction->setLabel('decline')
238
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
239
-				$notification->addAction($declineAction);
240
-
241
-				$acceptAction = $notification->createAction();
242
-				$acceptAction->setLabel('accept')
243
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
244
-				$notification->addAction($acceptAction);
245
-
246
-				$this->notificationManager->notify($notification);
247
-
248
-				return $shareId;
249
-			} catch (\Exception $e) {
250
-				$this->logger->logException($e, [
251
-					'message' => 'Server can not add remote share.',
252
-					'level' => Util::ERROR,
253
-					'app' => 'files_sharing'
254
-				]);
255
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
256
-			}
257
-		}
258
-
259
-		throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
260
-
261
-	}
262
-
263
-	/**
264
-	 * notification received from another server
265
-	 *
266
-	 * @param string $notificationType (e.g. SHARE_ACCEPTED)
267
-	 * @param string $providerId id of the share
268
-	 * @param array $notification payload of the notification
269
-	 * @return array data send back to the sender
270
-	 *
271
-	 * @throws ActionNotSupportedException
272
-	 * @throws AuthenticationFailedException
273
-	 * @throws BadRequestException
274
-	 * @throws ShareNotFoundException
275
-	 * @throws \OC\HintException
276
-	 * @since 14.0.0
277
-	 */
278
-	public function notificationReceived($notificationType, $providerId, array $notification) {
279
-
280
-		switch ($notificationType) {
281
-			case 'SHARE_ACCEPTED':
282
-				return $this->shareAccepted($providerId, $notification);
283
-			case 'SHARE_DECLINED':
284
-				return $this->shareDeclined($providerId, $notification);
285
-			case 'SHARE_UNSHARED':
286
-				return $this->unshare($providerId, $notification);
287
-			case 'REQUEST_RESHARE':
288
-				return $this->reshareRequested($providerId, $notification);
289
-			case 'RESHARE_UNDO':
290
-				return $this->undoReshare($providerId, $notification);
291
-		}
292
-
293
-
294
-		throw new BadRequestException([$notificationType]);
295
-	}
296
-
297
-	/**
298
-	 * process notification that the recipient accepted a share
299
-	 *
300
-	 * @param string $id
301
-	 * @param array $notification
302
-	 * @return array
303
-	 * @throws ActionNotSupportedException
304
-	 * @throws AuthenticationFailedException
305
-	 * @throws BadRequestException
306
-	 * @throws ShareNotFoundException
307
-	 * @throws \OC\HintException
308
-	 */
309
-	private function shareAccepted($id, $notification) {
310
-
311
-		if (!$this->isS2SEnabled()) {
312
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
313
-		}
314
-
315
-		if (!isset($notification['sharedSecret'])) {
316
-			throw new BadRequestException(['sharedSecret']);
317
-		}
318
-
319
-		$token = $notification['sharedSecret'];
320
-
321
-		$share = $this->federatedShareProvider->getShareById($id);
322
-
323
-		$this->verifyShare($share, $token);
324
-		$this->executeAcceptShare($share);
325
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
326
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
327
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
328
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
329
-			$notification->setMessage(
330
-				'SHARE_ACCEPTED',
331
-				'file',
332
-				$remoteId,
333
-				[
334
-					'sharedSecret' => $token,
335
-					'message' => 'Recipient accepted the re-share'
336
-				]
337
-
338
-			);
339
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
340
-
341
-		}
342
-
343
-		return [];
344
-	}
345
-
346
-	/**
347
-	 * @param IShare $share
348
-	 * @throws ShareNotFoundException
349
-	 */
350
-	protected function executeAcceptShare(IShare $share) {
351
-		try {
352
-			$fileId = (int)$share->getNode()->getId();
353
-			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
354
-		} catch (\Exception $e) {
355
-			throw new ShareNotFoundException();
356
-		}
357
-
358
-		$event = $this->activityManager->generateEvent();
359
-		$event->setApp('files_sharing')
360
-			->setType('remote_share')
361
-			->setAffectedUser($this->getCorrectUid($share))
362
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
363
-			->setObject('files', $fileId, $file)
364
-			->setLink($link);
365
-		$this->activityManager->publish($event);
366
-	}
367
-
368
-	/**
369
-	 * process notification that the recipient declined a share
370
-	 *
371
-	 * @param string $id
372
-	 * @param array $notification
373
-	 * @return array
374
-	 * @throws ActionNotSupportedException
375
-	 * @throws AuthenticationFailedException
376
-	 * @throws BadRequestException
377
-	 * @throws ShareNotFound
378
-	 * @throws ShareNotFoundException
379
-	 * @throws \OC\HintException
380
-	 *
381
-	 */
382
-	protected function shareDeclined($id, $notification) {
383
-
384
-		if (!$this->isS2SEnabled()) {
385
-			throw new ActionNotSupportedException('Server does not support federated cloud sharing');
386
-		}
387
-
388
-		if (!isset($notification['sharedSecret'])) {
389
-			throw new BadRequestException(['sharedSecret']);
390
-		}
391
-
392
-		$token = $notification['sharedSecret'];
393
-
394
-		$share = $this->federatedShareProvider->getShareById($id);
395
-
396
-		$this->verifyShare($share, $token);
397
-
398
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
399
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
400
-			$remoteId = $this->federatedShareProvider->getRemoteId($share);
401
-			$notification = $this->cloudFederationFactory->getCloudFederationNotification();
402
-			$notification->setMessage(
403
-				'SHARE_DECLINED',
404
-				'file',
405
-				$remoteId,
406
-				[
407
-					'sharedSecret' => $token,
408
-					'message' => 'Recipient declined the re-share'
409
-				]
410
-
411
-			);
412
-			$this->cloudFederationProviderManager->sendNotification($remote, $notification);
413
-		}
414
-
415
-		$this->executeDeclineShare($share);
416
-
417
-		return [];
418
-
419
-	}
420
-
421
-	/**
422
-	 * delete declined share and create a activity
423
-	 *
424
-	 * @param IShare $share
425
-	 * @throws ShareNotFoundException
426
-	 */
427
-	protected function executeDeclineShare(IShare $share) {
428
-		$this->federatedShareProvider->removeShareFromTable($share);
429
-
430
-		try {
431
-			$fileId = (int)$share->getNode()->getId();
432
-			list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
433
-		} catch (\Exception $e) {
434
-			throw new ShareNotFoundException();
435
-		}
436
-
437
-		$event = $this->activityManager->generateEvent();
438
-		$event->setApp('files_sharing')
439
-			->setType('remote_share')
440
-			->setAffectedUser($this->getCorrectUid($share))
441
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
442
-			->setObject('files', $fileId, $file)
443
-			->setLink($link);
444
-		$this->activityManager->publish($event);
445
-
446
-	}
447
-
448
-	/**
449
-	 * received the notification that the owner unshared a file from you
450
-	 *
451
-	 * @param string $id
452
-	 * @param string $notification
453
-	 * @return array
454
-	 * @throws AuthenticationFailedException
455
-	 * @throws BadRequestException
456
-	 * @throws ShareNotFoundException
457
-	 */
458
-	private function undoReshare($id, $notification) {
459
-		if (!isset($notification['sharedSecret'])) {
460
-			throw new BadRequestException(['sharedSecret']);
461
-		}
462
-		$token = $notification['sharedSecret'];
463
-
464
-		$share = $this->federatedShareProvider->getShareById($id);
465
-
466
-		$this->verifyShare($share, $token);
467
-		$this->federatedShareProvider->removeShareFromTable($share);
468
-		return [];
469
-	}
470
-
471
-	private function unshare($id, $notification) {
472
-
473
-		if (!$this->isS2SEnabled(true)) {
474
-			throw new ActionNotSupportedException("incoming shares disabled!");
475
-		}
476
-
477
-		if (!isset($notification['sharedSecret'])) {
478
-			throw new BadRequestException(['sharedSecret']);
479
-		}
480
-		$token = $notification['sharedSecret'];
481
-
482
-		$qb = $this->connection->getQueryBuilder();
483
-		$qb->select('*')
484
-			->from('share_external')
485
-			->where(
486
-				$qb->expr()->andX(
487
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
488
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
489
-				)
490
-			);
491
-
492
-		$result = $qb->execute();
493
-		$share = $result->fetch();
494
-		$result->closeCursor();
495
-
496
-		if ($token && $id && !empty($share)) {
497
-
498
-			$remote = $this->cleanupRemote($share['remote']);
499
-
500
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
501
-			$mountpoint = $share['mountpoint'];
502
-			$user = $share['user'];
503
-
504
-			$qb = $this->connection->getQueryBuilder();
505
-			$qb->delete('share_external')
506
-				->where(
507
-					$qb->expr()->andX(
508
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
509
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
510
-					)
511
-				);
512
-
513
-			$qb->execute();
514
-
515
-			if ($share['accepted']) {
516
-				$path = trim($mountpoint, '/');
517
-			} else {
518
-				$path = trim($share['name'], '/');
519
-			}
520
-
521
-			$notification = $this->notificationManager->createNotification();
522
-			$notification->setApp('files_sharing')
523
-				->setUser($share['user'])
524
-				->setObject('remote_share', (int)$share['id']);
525
-			$this->notificationManager->markProcessed($notification);
526
-
527
-			$event = $this->activityManager->generateEvent();
528
-			$event->setApp('files_sharing')
529
-				->setType('remote_share')
530
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
531
-				->setAffectedUser($user)
532
-				->setObject('remote_share', (int)$share['id'], $path);
533
-			\OC::$server->getActivityManager()->publish($event);
534
-		}
535
-
536
-		return [];
537
-	}
538
-
539
-	private function cleanupRemote($remote) {
540
-		$remote = substr($remote, strpos($remote, '://') + 3);
541
-
542
-		return rtrim($remote, '/');
543
-	}
544
-
545
-	/**
546
-	 * recipient of a share request to re-share the file with another user
547
-	 *
548
-	 * @param $id
549
-	 * @param $notification
550
-	 * @return array
551
-	 * @throws AuthenticationFailedException
552
-	 * @throws BadRequestException
553
-	 * @throws ProviderCouldNotAddShareException
554
-	 * @throws ShareNotFoundException
555
-	 * @throws ShareNotFound
556
-	 */
557
-	protected function reshareRequested($id, $notification) {
558
-
559
-		if (!isset($notification['sharedSecret'])) {
560
-			throw new BadRequestException(['sharedSecret']);
561
-		}
562
-		$token = $notification['sharedSecret'];
563
-
564
-		if (!isset($notification['shareWith'])) {
565
-			throw new BadRequestException(['shareWith']);
566
-		}
567
-		$shareWith = $notification['shareWith'];
568
-
569
-		if (!isset($notification['senderId'])) {
570
-			throw new BadRequestException(['senderId']);
571
-		}
572
-		$senderId = $notification['senderId'];
573
-
574
-		$share = $this->federatedShareProvider->getShareById($id);
575
-		// don't allow to share a file back to the owner
576
-		try {
577
-			list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
578
-			$owner = $share->getShareOwner();
579
-			$currentServer = $this->addressHandler->generateRemoteURL();
580
-			if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
581
-				throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
582
-			}
583
-		} catch (\Exception $e) {
584
-			throw new ProviderCouldNotAddShareException($e->getMessage());
585
-		}
586
-
587
-		$this->verifyShare($share, $token);
588
-
589
-		// check if re-sharing is allowed
590
-		if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
591
-			// the recipient of the initial share is now the initiator for the re-share
592
-			$share->setSharedBy($share->getSharedWith());
593
-			$share->setSharedWith($shareWith);
594
-			$result = $this->federatedShareProvider->create($share);
595
-			$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
596
-			return ['token' => $result->getToken(), 'providerId' => $result->getId()];
597
-		} else {
598
-			throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
599
-		}
600
-
601
-		throw new BadRequestException([]);
602
-	}
603
-
604
-	/**
605
-	 * get file
606
-	 *
607
-	 * @param string $user
608
-	 * @param int $fileSource
609
-	 * @return array with internal path of the file and a absolute link to it
610
-	 */
611
-	private function getFile($user, $fileSource) {
612
-		\OC_Util::setupFS($user);
613
-
614
-		try {
615
-			$file = Filesystem::getPath($fileSource);
616
-		} catch (NotFoundException $e) {
617
-			$file = null;
618
-		}
619
-		$args = Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
620
-		$link = Util::linkToAbsolute('files', 'index.php', $args);
621
-
622
-		return array($file, $link);
623
-
624
-	}
625
-
626
-	/**
627
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
628
-	 *
629
-	 * @param IShare $share
630
-	 * @return string
631
-	 */
632
-	protected function getCorrectUid(IShare $share) {
633
-		if ($this->userManager->userExists($share->getShareOwner())) {
634
-			return $share->getShareOwner();
635
-		}
636
-
637
-		return $share->getSharedBy();
638
-	}
639
-
640
-
641
-
642
-	/**
643
-	 * check if we got the right share
644
-	 *
645
-	 * @param IShare $share
646
-	 * @param string $token
647
-	 * @return bool
648
-	 * @throws AuthenticationFailedException
649
-	 */
650
-	protected function verifyShare(IShare $share, $token) {
651
-		if (
652
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
653
-			$share->getToken() === $token
654
-		) {
655
-			return true;
656
-		}
657
-
658
-		throw new AuthenticationFailedException();
659
-	}
660
-
661
-
662
-
663
-	/**
664
-	 * check if server-to-server sharing is enabled
665
-	 *
666
-	 * @param bool $incoming
667
-	 * @return bool
668
-	 */
669
-	private function isS2SEnabled($incoming = false) {
670
-
671
-		$result = $this->appManager->isEnabledForUser('files_sharing');
672
-
673
-		if ($incoming) {
674
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
675
-		} else {
676
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
677
-		}
678
-
679
-		return $result;
680
-	}
55
+    /** @var IAppManager */
56
+    private $appManager;
57
+
58
+    /** @var FederatedShareProvider */
59
+    private $federatedShareProvider;
60
+
61
+    /** @var AddressHandler */
62
+    private $addressHandler;
63
+
64
+    /** @var ILogger */
65
+    private $logger;
66
+
67
+    /** @var IUserManager */
68
+    private $userManager;
69
+
70
+    /** @var ICloudIdManager */
71
+    private $cloudIdManager;
72
+
73
+    /** @var IActivityManager */
74
+    private $activityManager;
75
+
76
+    /** @var INotificationManager */
77
+    private $notificationManager;
78
+
79
+    /** @var IURLGenerator */
80
+    private $urlGenerator;
81
+
82
+    /** @var ICloudFederationFactory */
83
+    private $cloudFederationFactory;
84
+
85
+    /** @var ICloudFederationProviderManager */
86
+    private $cloudFederationProviderManager;
87
+
88
+    /** @var IDBConnection */
89
+    private $connection;
90
+
91
+    /**
92
+     * CloudFederationProvider constructor.
93
+     *
94
+     * @param IAppManager $appManager
95
+     * @param FederatedShareProvider $federatedShareProvider
96
+     * @param AddressHandler $addressHandler
97
+     * @param ILogger $logger
98
+     * @param IUserManager $userManager
99
+     * @param ICloudIdManager $cloudIdManager
100
+     * @param IActivityManager $activityManager
101
+     * @param INotificationManager $notificationManager
102
+     * @param IURLGenerator $urlGenerator
103
+     * @param ICloudFederationFactory $cloudFederationFactory
104
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
105
+     * @param IDBConnection $connection
106
+     */
107
+    public function __construct(IAppManager $appManager,
108
+                                FederatedShareProvider $federatedShareProvider,
109
+                                AddressHandler $addressHandler,
110
+                                ILogger $logger,
111
+                                IUserManager $userManager,
112
+                                ICloudIdManager $cloudIdManager,
113
+                                IActivityManager $activityManager,
114
+                                INotificationManager $notificationManager,
115
+                                IURLGenerator $urlGenerator,
116
+                                ICloudFederationFactory $cloudFederationFactory,
117
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
118
+                                IDBConnection $connection
119
+    ) {
120
+        $this->appManager = $appManager;
121
+        $this->federatedShareProvider = $federatedShareProvider;
122
+        $this->addressHandler = $addressHandler;
123
+        $this->logger = $logger;
124
+        $this->userManager = $userManager;
125
+        $this->cloudIdManager = $cloudIdManager;
126
+        $this->activityManager = $activityManager;
127
+        $this->notificationManager = $notificationManager;
128
+        $this->urlGenerator = $urlGenerator;
129
+        $this->cloudFederationFactory = $cloudFederationFactory;
130
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
131
+        $this->connection = $connection;
132
+    }
133
+
134
+
135
+
136
+    /**
137
+     * @return string
138
+     */
139
+    public function getShareType() {
140
+        return 'file';
141
+    }
142
+
143
+    /**
144
+     * share received from another server
145
+     *
146
+     * @param ICloudFederationShare $share
147
+     * @return string provider specific unique ID of the share
148
+     *
149
+     * @throws ProviderCouldNotAddShareException
150
+     * @throws \OCP\AppFramework\QueryException
151
+     * @throws \OC\HintException
152
+     * @since 14.0.0
153
+     */
154
+    public function shareReceived(ICloudFederationShare $share) {
155
+
156
+        if (!$this->isS2SEnabled(true)) {
157
+            throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
158
+        }
159
+
160
+        $protocol = $share->getProtocol();
161
+        if ($protocol['name'] !== 'webdav') {
162
+            throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
163
+        }
164
+
165
+        list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
166
+
167
+        $remote = $remote;
168
+        $token = $share->getShareSecret();
169
+        $name = $share->getResourceName();
170
+        $owner = $share->getOwnerDisplayName();
171
+        $sharedBy = $share->getSharedByDisplayName();
172
+        $shareWith = $share->getShareWith();
173
+        $remoteId = $share->getProviderId();
174
+        $sharedByFederatedId = $share->getSharedBy();
175
+        $ownerFederatedId = $share->getOwner();
176
+
177
+        // if no explicit information about the person who created the share was send
178
+        // we assume that the share comes from the owner
179
+        if ($sharedByFederatedId === null) {
180
+            $sharedBy = $owner;
181
+            $sharedByFederatedId = $ownerFederatedId;
182
+        }
183
+
184
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
185
+
186
+            if (!Util::isValidFileName($name)) {
187
+                throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
188
+            }
189
+
190
+            // FIXME this should be a method in the user management instead
191
+            $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
192
+            Util::emitHook(
193
+                '\OCA\Files_Sharing\API\Server2Server',
194
+                'preLoginNameUsedAsUserName',
195
+                array('uid' => &$shareWith)
196
+            );
197
+            $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
198
+
199
+            if (!$this->userManager->userExists($shareWith)) {
200
+                throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
201
+            }
202
+
203
+            \OC_Util::setupFS($shareWith);
204
+
205
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
206
+                \OC::$server->getDatabaseConnection(),
207
+                Filesystem::getMountManager(),
208
+                Filesystem::getLoader(),
209
+                \OC::$server->getHTTPClientService(),
210
+                \OC::$server->getNotificationManager(),
211
+                \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
212
+                \OC::$server->getCloudFederationProviderManager(),
213
+                \OC::$server->getCloudFederationFactory(),
214
+                $shareWith
215
+            );
216
+
217
+            try {
218
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
219
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
220
+
221
+                $event = $this->activityManager->generateEvent();
222
+                $event->setApp('files_sharing')
223
+                    ->setType('remote_share')
224
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
225
+                    ->setAffectedUser($shareWith)
226
+                    ->setObject('remote_share', (int)$shareId, $name);
227
+                \OC::$server->getActivityManager()->publish($event);
228
+
229
+                $notification = $this->notificationManager->createNotification();
230
+                $notification->setApp('files_sharing')
231
+                    ->setUser($shareWith)
232
+                    ->setDateTime(new \DateTime())
233
+                    ->setObject('remote_share', $shareId)
234
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
235
+
236
+                $declineAction = $notification->createAction();
237
+                $declineAction->setLabel('decline')
238
+                    ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
239
+                $notification->addAction($declineAction);
240
+
241
+                $acceptAction = $notification->createAction();
242
+                $acceptAction->setLabel('accept')
243
+                    ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
244
+                $notification->addAction($acceptAction);
245
+
246
+                $this->notificationManager->notify($notification);
247
+
248
+                return $shareId;
249
+            } catch (\Exception $e) {
250
+                $this->logger->logException($e, [
251
+                    'message' => 'Server can not add remote share.',
252
+                    'level' => Util::ERROR,
253
+                    'app' => 'files_sharing'
254
+                ]);
255
+                throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
256
+            }
257
+        }
258
+
259
+        throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
260
+
261
+    }
262
+
263
+    /**
264
+     * notification received from another server
265
+     *
266
+     * @param string $notificationType (e.g. SHARE_ACCEPTED)
267
+     * @param string $providerId id of the share
268
+     * @param array $notification payload of the notification
269
+     * @return array data send back to the sender
270
+     *
271
+     * @throws ActionNotSupportedException
272
+     * @throws AuthenticationFailedException
273
+     * @throws BadRequestException
274
+     * @throws ShareNotFoundException
275
+     * @throws \OC\HintException
276
+     * @since 14.0.0
277
+     */
278
+    public function notificationReceived($notificationType, $providerId, array $notification) {
279
+
280
+        switch ($notificationType) {
281
+            case 'SHARE_ACCEPTED':
282
+                return $this->shareAccepted($providerId, $notification);
283
+            case 'SHARE_DECLINED':
284
+                return $this->shareDeclined($providerId, $notification);
285
+            case 'SHARE_UNSHARED':
286
+                return $this->unshare($providerId, $notification);
287
+            case 'REQUEST_RESHARE':
288
+                return $this->reshareRequested($providerId, $notification);
289
+            case 'RESHARE_UNDO':
290
+                return $this->undoReshare($providerId, $notification);
291
+        }
292
+
293
+
294
+        throw new BadRequestException([$notificationType]);
295
+    }
296
+
297
+    /**
298
+     * process notification that the recipient accepted a share
299
+     *
300
+     * @param string $id
301
+     * @param array $notification
302
+     * @return array
303
+     * @throws ActionNotSupportedException
304
+     * @throws AuthenticationFailedException
305
+     * @throws BadRequestException
306
+     * @throws ShareNotFoundException
307
+     * @throws \OC\HintException
308
+     */
309
+    private function shareAccepted($id, $notification) {
310
+
311
+        if (!$this->isS2SEnabled()) {
312
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
313
+        }
314
+
315
+        if (!isset($notification['sharedSecret'])) {
316
+            throw new BadRequestException(['sharedSecret']);
317
+        }
318
+
319
+        $token = $notification['sharedSecret'];
320
+
321
+        $share = $this->federatedShareProvider->getShareById($id);
322
+
323
+        $this->verifyShare($share, $token);
324
+        $this->executeAcceptShare($share);
325
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
326
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
327
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
328
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
329
+            $notification->setMessage(
330
+                'SHARE_ACCEPTED',
331
+                'file',
332
+                $remoteId,
333
+                [
334
+                    'sharedSecret' => $token,
335
+                    'message' => 'Recipient accepted the re-share'
336
+                ]
337
+
338
+            );
339
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
340
+
341
+        }
342
+
343
+        return [];
344
+    }
345
+
346
+    /**
347
+     * @param IShare $share
348
+     * @throws ShareNotFoundException
349
+     */
350
+    protected function executeAcceptShare(IShare $share) {
351
+        try {
352
+            $fileId = (int)$share->getNode()->getId();
353
+            list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
354
+        } catch (\Exception $e) {
355
+            throw new ShareNotFoundException();
356
+        }
357
+
358
+        $event = $this->activityManager->generateEvent();
359
+        $event->setApp('files_sharing')
360
+            ->setType('remote_share')
361
+            ->setAffectedUser($this->getCorrectUid($share))
362
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
363
+            ->setObject('files', $fileId, $file)
364
+            ->setLink($link);
365
+        $this->activityManager->publish($event);
366
+    }
367
+
368
+    /**
369
+     * process notification that the recipient declined a share
370
+     *
371
+     * @param string $id
372
+     * @param array $notification
373
+     * @return array
374
+     * @throws ActionNotSupportedException
375
+     * @throws AuthenticationFailedException
376
+     * @throws BadRequestException
377
+     * @throws ShareNotFound
378
+     * @throws ShareNotFoundException
379
+     * @throws \OC\HintException
380
+     *
381
+     */
382
+    protected function shareDeclined($id, $notification) {
383
+
384
+        if (!$this->isS2SEnabled()) {
385
+            throw new ActionNotSupportedException('Server does not support federated cloud sharing');
386
+        }
387
+
388
+        if (!isset($notification['sharedSecret'])) {
389
+            throw new BadRequestException(['sharedSecret']);
390
+        }
391
+
392
+        $token = $notification['sharedSecret'];
393
+
394
+        $share = $this->federatedShareProvider->getShareById($id);
395
+
396
+        $this->verifyShare($share, $token);
397
+
398
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
399
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
400
+            $remoteId = $this->federatedShareProvider->getRemoteId($share);
401
+            $notification = $this->cloudFederationFactory->getCloudFederationNotification();
402
+            $notification->setMessage(
403
+                'SHARE_DECLINED',
404
+                'file',
405
+                $remoteId,
406
+                [
407
+                    'sharedSecret' => $token,
408
+                    'message' => 'Recipient declined the re-share'
409
+                ]
410
+
411
+            );
412
+            $this->cloudFederationProviderManager->sendNotification($remote, $notification);
413
+        }
414
+
415
+        $this->executeDeclineShare($share);
416
+
417
+        return [];
418
+
419
+    }
420
+
421
+    /**
422
+     * delete declined share and create a activity
423
+     *
424
+     * @param IShare $share
425
+     * @throws ShareNotFoundException
426
+     */
427
+    protected function executeDeclineShare(IShare $share) {
428
+        $this->federatedShareProvider->removeShareFromTable($share);
429
+
430
+        try {
431
+            $fileId = (int)$share->getNode()->getId();
432
+            list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
433
+        } catch (\Exception $e) {
434
+            throw new ShareNotFoundException();
435
+        }
436
+
437
+        $event = $this->activityManager->generateEvent();
438
+        $event->setApp('files_sharing')
439
+            ->setType('remote_share')
440
+            ->setAffectedUser($this->getCorrectUid($share))
441
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
442
+            ->setObject('files', $fileId, $file)
443
+            ->setLink($link);
444
+        $this->activityManager->publish($event);
445
+
446
+    }
447
+
448
+    /**
449
+     * received the notification that the owner unshared a file from you
450
+     *
451
+     * @param string $id
452
+     * @param string $notification
453
+     * @return array
454
+     * @throws AuthenticationFailedException
455
+     * @throws BadRequestException
456
+     * @throws ShareNotFoundException
457
+     */
458
+    private function undoReshare($id, $notification) {
459
+        if (!isset($notification['sharedSecret'])) {
460
+            throw new BadRequestException(['sharedSecret']);
461
+        }
462
+        $token = $notification['sharedSecret'];
463
+
464
+        $share = $this->federatedShareProvider->getShareById($id);
465
+
466
+        $this->verifyShare($share, $token);
467
+        $this->federatedShareProvider->removeShareFromTable($share);
468
+        return [];
469
+    }
470
+
471
+    private function unshare($id, $notification) {
472
+
473
+        if (!$this->isS2SEnabled(true)) {
474
+            throw new ActionNotSupportedException("incoming shares disabled!");
475
+        }
476
+
477
+        if (!isset($notification['sharedSecret'])) {
478
+            throw new BadRequestException(['sharedSecret']);
479
+        }
480
+        $token = $notification['sharedSecret'];
481
+
482
+        $qb = $this->connection->getQueryBuilder();
483
+        $qb->select('*')
484
+            ->from('share_external')
485
+            ->where(
486
+                $qb->expr()->andX(
487
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
488
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
489
+                )
490
+            );
491
+
492
+        $result = $qb->execute();
493
+        $share = $result->fetch();
494
+        $result->closeCursor();
495
+
496
+        if ($token && $id && !empty($share)) {
497
+
498
+            $remote = $this->cleanupRemote($share['remote']);
499
+
500
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
501
+            $mountpoint = $share['mountpoint'];
502
+            $user = $share['user'];
503
+
504
+            $qb = $this->connection->getQueryBuilder();
505
+            $qb->delete('share_external')
506
+                ->where(
507
+                    $qb->expr()->andX(
508
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
509
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
510
+                    )
511
+                );
512
+
513
+            $qb->execute();
514
+
515
+            if ($share['accepted']) {
516
+                $path = trim($mountpoint, '/');
517
+            } else {
518
+                $path = trim($share['name'], '/');
519
+            }
520
+
521
+            $notification = $this->notificationManager->createNotification();
522
+            $notification->setApp('files_sharing')
523
+                ->setUser($share['user'])
524
+                ->setObject('remote_share', (int)$share['id']);
525
+            $this->notificationManager->markProcessed($notification);
526
+
527
+            $event = $this->activityManager->generateEvent();
528
+            $event->setApp('files_sharing')
529
+                ->setType('remote_share')
530
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
531
+                ->setAffectedUser($user)
532
+                ->setObject('remote_share', (int)$share['id'], $path);
533
+            \OC::$server->getActivityManager()->publish($event);
534
+        }
535
+
536
+        return [];
537
+    }
538
+
539
+    private function cleanupRemote($remote) {
540
+        $remote = substr($remote, strpos($remote, '://') + 3);
541
+
542
+        return rtrim($remote, '/');
543
+    }
544
+
545
+    /**
546
+     * recipient of a share request to re-share the file with another user
547
+     *
548
+     * @param $id
549
+     * @param $notification
550
+     * @return array
551
+     * @throws AuthenticationFailedException
552
+     * @throws BadRequestException
553
+     * @throws ProviderCouldNotAddShareException
554
+     * @throws ShareNotFoundException
555
+     * @throws ShareNotFound
556
+     */
557
+    protected function reshareRequested($id, $notification) {
558
+
559
+        if (!isset($notification['sharedSecret'])) {
560
+            throw new BadRequestException(['sharedSecret']);
561
+        }
562
+        $token = $notification['sharedSecret'];
563
+
564
+        if (!isset($notification['shareWith'])) {
565
+            throw new BadRequestException(['shareWith']);
566
+        }
567
+        $shareWith = $notification['shareWith'];
568
+
569
+        if (!isset($notification['senderId'])) {
570
+            throw new BadRequestException(['senderId']);
571
+        }
572
+        $senderId = $notification['senderId'];
573
+
574
+        $share = $this->federatedShareProvider->getShareById($id);
575
+        // don't allow to share a file back to the owner
576
+        try {
577
+            list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
578
+            $owner = $share->getShareOwner();
579
+            $currentServer = $this->addressHandler->generateRemoteURL();
580
+            if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
581
+                throw new ProviderCouldNotAddShareException('Resharing back to the owner is not allowed: ' . $id);
582
+            }
583
+        } catch (\Exception $e) {
584
+            throw new ProviderCouldNotAddShareException($e->getMessage());
585
+        }
586
+
587
+        $this->verifyShare($share, $token);
588
+
589
+        // check if re-sharing is allowed
590
+        if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
591
+            // the recipient of the initial share is now the initiator for the re-share
592
+            $share->setSharedBy($share->getSharedWith());
593
+            $share->setSharedWith($shareWith);
594
+            $result = $this->federatedShareProvider->create($share);
595
+            $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $senderId);
596
+            return ['token' => $result->getToken(), 'providerId' => $result->getId()];
597
+        } else {
598
+            throw new ProviderCouldNotAddShareException('resharing not allowed for share: ' . $id);
599
+        }
600
+
601
+        throw new BadRequestException([]);
602
+    }
603
+
604
+    /**
605
+     * get file
606
+     *
607
+     * @param string $user
608
+     * @param int $fileSource
609
+     * @return array with internal path of the file and a absolute link to it
610
+     */
611
+    private function getFile($user, $fileSource) {
612
+        \OC_Util::setupFS($user);
613
+
614
+        try {
615
+            $file = Filesystem::getPath($fileSource);
616
+        } catch (NotFoundException $e) {
617
+            $file = null;
618
+        }
619
+        $args = Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
620
+        $link = Util::linkToAbsolute('files', 'index.php', $args);
621
+
622
+        return array($file, $link);
623
+
624
+    }
625
+
626
+    /**
627
+     * check if we are the initiator or the owner of a re-share and return the correct UID
628
+     *
629
+     * @param IShare $share
630
+     * @return string
631
+     */
632
+    protected function getCorrectUid(IShare $share) {
633
+        if ($this->userManager->userExists($share->getShareOwner())) {
634
+            return $share->getShareOwner();
635
+        }
636
+
637
+        return $share->getSharedBy();
638
+    }
639
+
640
+
641
+
642
+    /**
643
+     * check if we got the right share
644
+     *
645
+     * @param IShare $share
646
+     * @param string $token
647
+     * @return bool
648
+     * @throws AuthenticationFailedException
649
+     */
650
+    protected function verifyShare(IShare $share, $token) {
651
+        if (
652
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
653
+            $share->getToken() === $token
654
+        ) {
655
+            return true;
656
+        }
657
+
658
+        throw new AuthenticationFailedException();
659
+    }
660
+
661
+
662
+
663
+    /**
664
+     * check if server-to-server sharing is enabled
665
+     *
666
+     * @param bool $incoming
667
+     * @return bool
668
+     */
669
+    private function isS2SEnabled($incoming = false) {
670
+
671
+        $result = $this->appManager->isEnabledForUser('files_sharing');
672
+
673
+        if ($incoming) {
674
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
675
+        } else {
676
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
677
+        }
678
+
679
+        return $result;
680
+    }
681 681
 
682 682
 
683 683
 }
Please login to merge, or discard this patch.
lib/public/Federation/ICloudFederationProvider.php 1 patch
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -39,42 +39,42 @@
 block discarded – undo
39 39
 
40 40
 interface ICloudFederationProvider {
41 41
 
42
-	/**
43
-	 * get the name of the share type, handled by this provider
44
-	 *
45
-	 * @return string
46
-	 *
47
-	 * @since 14.0.0
48
-	 */
49
-	public function getShareType();
42
+    /**
43
+     * get the name of the share type, handled by this provider
44
+     *
45
+     * @return string
46
+     *
47
+     * @since 14.0.0
48
+     */
49
+    public function getShareType();
50 50
 
51
-	/**
52
-	 * share received from another server
53
-	 *
54
-	 * @param ICloudFederationShare $share
55
-	 * @return string provider specific unique ID of the share
56
-	 *
57
-	 * @throws ProviderCouldNotAddShareException
58
-	 *
59
-	 * @since 14.0.0
60
-	 */
61
-	public function shareReceived(ICloudFederationShare $share);
51
+    /**
52
+     * share received from another server
53
+     *
54
+     * @param ICloudFederationShare $share
55
+     * @return string provider specific unique ID of the share
56
+     *
57
+     * @throws ProviderCouldNotAddShareException
58
+     *
59
+     * @since 14.0.0
60
+     */
61
+    public function shareReceived(ICloudFederationShare $share);
62 62
 
63
-	/**
64
-	 * notification received from another server
65
-	 *
66
-	 * @param string $notificationType (e.g SHARE_ACCEPTED)
67
-	 * @param string $providerId share ID
68
-	 * @param array $notification provider specific notification
69
-	 * @return array $data send back to sender
70
-	 *
71
-	 * @throws ShareNotFoundException
72
-	 * @throws ActionNotSupportedException
73
-	 * @throws BadRequestException
74
-	 * @throws AuthenticationFailedException
75
-	 *
76
-	 * @since 14.0.0
77
-	 */
78
-	public function notificationReceived($notificationType, $providerId, array $notification);
63
+    /**
64
+     * notification received from another server
65
+     *
66
+     * @param string $notificationType (e.g SHARE_ACCEPTED)
67
+     * @param string $providerId share ID
68
+     * @param array $notification provider specific notification
69
+     * @return array $data send back to sender
70
+     *
71
+     * @throws ShareNotFoundException
72
+     * @throws ActionNotSupportedException
73
+     * @throws BadRequestException
74
+     * @throws AuthenticationFailedException
75
+     *
76
+     * @since 14.0.0
77
+     */
78
+    public function notificationReceived($notificationType, $providerId, array $notification);
79 79
 
80 80
 }
Please login to merge, or discard this patch.
lib/public/Federation/ICloudFederationProviderManager.php 1 patch
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -32,76 +32,76 @@
 block discarded – undo
32 32
  */
33 33
 interface ICloudFederationProviderManager {
34 34
 
35
-	/**
36
-	 * Registers an callback function which must return an cloud federation provider
37
-	 *
38
-	 * @param string $shareType which share type does the provider handles
39
-	 * @param string $displayName user facing name of the federated share provider
40
-	 * @param callable $callback
41
-	 * @throws Exceptions\ProviderAlreadyExistsException
42
-	 *
43
-	 * @since 14.0.0
44
-	 */
45
-	public function addCloudFederationProvider($shareType, $displayName, callable $callback);
35
+    /**
36
+     * Registers an callback function which must return an cloud federation provider
37
+     *
38
+     * @param string $shareType which share type does the provider handles
39
+     * @param string $displayName user facing name of the federated share provider
40
+     * @param callable $callback
41
+     * @throws Exceptions\ProviderAlreadyExistsException
42
+     *
43
+     * @since 14.0.0
44
+     */
45
+    public function addCloudFederationProvider($shareType, $displayName, callable $callback);
46 46
 
47
-	/**
48
-	 * remove cloud federation provider
49
-	 *
50
-	 * @param string $shareType
51
-	 *
52
-	 * @since 14.0.0
53
-	 */
54
-	public function removeCloudFederationProvider($shareType);
47
+    /**
48
+     * remove cloud federation provider
49
+     *
50
+     * @param string $shareType
51
+     *
52
+     * @since 14.0.0
53
+     */
54
+    public function removeCloudFederationProvider($shareType);
55 55
 
56
-	/**
57
-	 * get a list of all cloudFederationProviders
58
-	 *
59
-	 * @return array [id => ['id' => $id, 'displayName' => $displayName, 'callback' => callback]]
60
-	 *
61
-	 * @since 14.0.0
62
-	 */
63
-	public function getAllCloudFederationProviders();
56
+    /**
57
+     * get a list of all cloudFederationProviders
58
+     *
59
+     * @return array [id => ['id' => $id, 'displayName' => $displayName, 'callback' => callback]]
60
+     *
61
+     * @since 14.0.0
62
+     */
63
+    public function getAllCloudFederationProviders();
64 64
 
65
-	/**
66
-	 * get a specific cloud federation provider
67
-	 *
68
-	 * @param string $shareType
69
-	 * @return ICloudFederationProvider
70
-	 * @throws Exceptions\ProviderDoesNotExistsException;
71
-	 *
72
-	 * @since 14.0.0
73
-	 */
74
-	public function getCloudFederationProvider($shareType);
65
+    /**
66
+     * get a specific cloud federation provider
67
+     *
68
+     * @param string $shareType
69
+     * @return ICloudFederationProvider
70
+     * @throws Exceptions\ProviderDoesNotExistsException;
71
+     *
72
+     * @since 14.0.0
73
+     */
74
+    public function getCloudFederationProvider($shareType);
75 75
 
76
-	/**
77
-	 * send federated share
78
-	 *
79
-	 * @param ICloudFederationShare $share
80
-	 * @return bool
81
-	 *
82
-	 * @since 14.0.0
83
-	 */
84
-	public function sendShare(ICloudFederationShare $share);
76
+    /**
77
+     * send federated share
78
+     *
79
+     * @param ICloudFederationShare $share
80
+     * @return bool
81
+     *
82
+     * @since 14.0.0
83
+     */
84
+    public function sendShare(ICloudFederationShare $share);
85 85
 
86
-	/**
87
-	 * send notification about existing share
88
-	 *
89
-	 * @param string $url
90
-	 * @param ICloudFederationNotification $notification
91
-	 * @return mixed
92
-	 *
93
-	 * @since 14.0.0
94
-	 */
95
-	public function sendNotification($url, ICloudFederationNotification $notification);
86
+    /**
87
+     * send notification about existing share
88
+     *
89
+     * @param string $url
90
+     * @param ICloudFederationNotification $notification
91
+     * @return mixed
92
+     *
93
+     * @since 14.0.0
94
+     */
95
+    public function sendNotification($url, ICloudFederationNotification $notification);
96 96
 
97
-	/**
98
-	 * check if the new cloud federation API is ready to be used
99
-	 *
100
-	 * @return bool
101
-	 *
102
-	 * @since 14.0.0
103
-	 */
104
-	public function isReady();
97
+    /**
98
+     * check if the new cloud federation API is ready to be used
99
+     *
100
+     * @return bool
101
+     *
102
+     * @since 14.0.0
103
+     */
104
+    public function isReady();
105 105
 
106 106
 
107 107
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 			$ocsStatus = isset($status['ocs']);
118 118
 			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119 119
 
120
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
120
+			if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
121 121
 				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122 122
 				return true;
123 123
 			}
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 			return [$ocmResult['token'], $ocmResult['providerId']];
161 161
 		}
162 162
 
163
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
163
+		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/'.$id.'/reshare', $fields);
164 164
 		$status = json_decode($result['result'], true);
165 165
 
166 166
 		$httpRequestSuccessful = $result['success'];
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172 172
 			return [
173 173
 				$status['ocs']['data']['token'],
174
-				(int)$status['ocs']['data']['remoteId']
174
+				(int) $status['ocs']['data']['remoteId']
175 175
 			];
176 176
 		}
177 177
 
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			$fields[$key] = $value;
259 259
 		}
260 260
 
261
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
261
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$remoteId.'/'.$action, $fields, $action);
262 262
 		$status = json_decode($result['result'], true);
263 263
 
264 264
 		if ($result['success'] &&
@@ -306,10 +306,10 @@  discard block
 block discarded – undo
306 306
 	 * @return array
307 307
 	 * @throws \Exception
308 308
 	 */
309
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
309
+	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
310 310
 
311 311
 		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
-			$remoteDomain = 'https://' . $remoteDomain;
312
+			$remoteDomain = 'https://'.$remoteDomain;
313 313
 		}
314 314
 
315 315
 		$result = [
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
349 349
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
350 350
 		try {
351
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
351
+			$response = $client->post($remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT, [
352 352
 				'body' => $fields,
353 353
 				'timeout' => 10,
354 354
 				'connect_timeout' => 10,
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 		switch ($action) {
406 406
 			case 'share':
407 407
 				$share = $this->cloudFederationFactory->getCloudFederationShare(
408
-					$fields['shareWith'] . '@' . $remoteDomain,
408
+					$fields['shareWith'].'@'.$remoteDomain,
409 409
 					$fields['name'],
410 410
 					'',
411 411
 					$fields['remoteId'],
Please login to merge, or discard this patch.
Indentation   +430 added lines, -430 removed lines patch added patch discarded remove patch
@@ -33,434 +33,434 @@
 block discarded – undo
33 33
 use OCP\OCS\IDiscoveryService;
34 34
 
35 35
 class Notifications {
36
-	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
-
38
-	/** @var AddressHandler */
39
-	private $addressHandler;
40
-
41
-	/** @var IClientService */
42
-	private $httpClientService;
43
-
44
-	/** @var IDiscoveryService */
45
-	private $discoveryService;
46
-
47
-	/** @var IJobList  */
48
-	private $jobList;
49
-
50
-	/** @var ICloudFederationProviderManager */
51
-	private $federationProviderManager;
52
-
53
-	/** @var ICloudFederationFactory */
54
-	private $cloudFederationFactory;
55
-
56
-	/**
57
-	 * @param AddressHandler $addressHandler
58
-	 * @param IClientService $httpClientService
59
-	 * @param IDiscoveryService $discoveryService
60
-	 * @param IJobList $jobList
61
-	 * @param ICloudFederationProviderManager $federationProviderManager
62
-	 * @param ICloudFederationFactory $cloudFederationFactory
63
-	 */
64
-	public function __construct(
65
-		AddressHandler $addressHandler,
66
-		IClientService $httpClientService,
67
-		IDiscoveryService $discoveryService,
68
-		IJobList $jobList,
69
-		ICloudFederationProviderManager $federationProviderManager,
70
-		ICloudFederationFactory $cloudFederationFactory
71
-	) {
72
-		$this->addressHandler = $addressHandler;
73
-		$this->httpClientService = $httpClientService;
74
-		$this->discoveryService = $discoveryService;
75
-		$this->jobList = $jobList;
76
-		$this->federationProviderManager = $federationProviderManager;
77
-		$this->cloudFederationFactory = $cloudFederationFactory;
78
-	}
79
-
80
-	/**
81
-	 * send server-to-server share to remote server
82
-	 *
83
-	 * @param string $token
84
-	 * @param string $shareWith
85
-	 * @param string $name
86
-	 * @param int $remote_id
87
-	 * @param string $owner
88
-	 * @param string $ownerFederatedId
89
-	 * @param string $sharedBy
90
-	 * @param string $sharedByFederatedId
91
-	 * @return bool
92
-	 * @throws \OC\HintException
93
-	 * @throws \OC\ServerNotAvailableException
94
-	 */
95
-	public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
96
-
97
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
98
-
99
-		if ($user && $remote) {
100
-			$local = $this->addressHandler->generateRemoteURL();
101
-
102
-			$fields = array(
103
-				'shareWith' => $user,
104
-				'token' => $token,
105
-				'name' => $name,
106
-				'remoteId' => $remote_id,
107
-				'owner' => $owner,
108
-				'ownerFederatedId' => $ownerFederatedId,
109
-				'sharedBy' => $sharedBy,
110
-				'sharedByFederatedId' => $sharedByFederatedId,
111
-				'remote' => $local,
112
-			);
113
-
114
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
115
-			$status = json_decode($result['result'], true);
116
-
117
-			$ocsStatus = isset($status['ocs']);
118
-			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119
-
120
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
121
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122
-				return true;
123
-			}
124
-
125
-		}
126
-
127
-		return false;
128
-	}
129
-
130
-	/**
131
-	 * ask owner to re-share the file with the given user
132
-	 *
133
-	 * @param string $token
134
-	 * @param int $id remote Id
135
-	 * @param int $shareId internal share Id
136
-	 * @param string $remote remote address of the owner
137
-	 * @param string $shareWith
138
-	 * @param int $permission
139
-	 * @param string $filename
140
-	 * @return bool
141
-	 * @throws \OC\HintException
142
-	 * @throws \OC\ServerNotAvailableException
143
-	 */
144
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
145
-
146
-		$fields = array(
147
-			'shareWith' => $shareWith,
148
-			'token' => $token,
149
-			'permission' => $permission,
150
-			'remoteId' => $shareId,
151
-		);
152
-
153
-		$ocmFields = $fields;
154
-		$ocmFields['remoteId'] = $id;
155
-		$ocmFields['localId'] = $shareId;
156
-		$ocmFields['name'] = $filename;
157
-
158
-		$ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
159
-		if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
160
-			return [$ocmResult['token'], $ocmResult['providerId']];
161
-		}
162
-
163
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
164
-		$status = json_decode($result['result'], true);
165
-
166
-		$httpRequestSuccessful = $result['success'];
167
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
168
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
169
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
170
-
171
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172
-			return [
173
-				$status['ocs']['data']['token'],
174
-				(int)$status['ocs']['data']['remoteId']
175
-			];
176
-		}
177
-
178
-		return false;
179
-	}
180
-
181
-	/**
182
-	 * send server-to-server unshare to remote server
183
-	 *
184
-	 * @param string $remote url
185
-	 * @param int $id share id
186
-	 * @param string $token
187
-	 * @return bool
188
-	 */
189
-	public function sendRemoteUnShare($remote, $id, $token) {
190
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
191
-	}
192
-
193
-	/**
194
-	 * send server-to-server unshare to remote server
195
-	 *
196
-	 * @param string $remote url
197
-	 * @param int $id share id
198
-	 * @param string $token
199
-	 * @return bool
200
-	 */
201
-	public function sendRevokeShare($remote, $id, $token) {
202
-		$this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
203
-	}
204
-
205
-	/**
206
-	 * send notification to remote server if the permissions was changed
207
-	 *
208
-	 * @param string $remote
209
-	 * @param int $remoteId
210
-	 * @param string $token
211
-	 * @param int $permissions
212
-	 * @return bool
213
-	 */
214
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
215
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
216
-	}
217
-
218
-	/**
219
-	 * forward accept reShare to remote server
220
-	 *
221
-	 * @param string $remote
222
-	 * @param int $remoteId
223
-	 * @param string $token
224
-	 */
225
-	public function sendAcceptShare($remote, $remoteId, $token) {
226
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
227
-	}
228
-
229
-	/**
230
-	 * forward decline reShare to remote server
231
-	 *
232
-	 * @param string $remote
233
-	 * @param int $remoteId
234
-	 * @param string $token
235
-	 */
236
-	public function sendDeclineShare($remote, $remoteId, $token) {
237
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
238
-	}
239
-
240
-	/**
241
-	 * inform remote server whether server-to-server share was accepted/declined
242
-	 *
243
-	 * @param string $remote
244
-	 * @param string $token
245
-	 * @param int $remoteId Share id on the remote host
246
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
247
-	 * @param array $data
248
-	 * @param int $try
249
-	 * @return boolean
250
-	 */
251
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
252
-
253
-		$fields = [
254
-			'token' => $token,
255
-			'remoteId' => $remoteId
256
-			];
257
-		foreach ($data as $key => $value) {
258
-			$fields[$key] = $value;
259
-		}
260
-
261
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
262
-		$status = json_decode($result['result'], true);
263
-
264
-		if ($result['success'] &&
265
-			($status['ocs']['meta']['statuscode'] === 100 ||
266
-				$status['ocs']['meta']['statuscode'] === 200
267
-			)
268
-		) {
269
-			return true;
270
-		} elseif ($try === 0) {
271
-			// only add new job on first try
272
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
273
-				[
274
-					'remote' => $remote,
275
-					'remoteId' => $remoteId,
276
-					'token' => $token,
277
-					'action' => $action,
278
-					'data' => json_encode($data),
279
-					'try' => $try,
280
-					'lastRun' => $this->getTimestamp()
281
-				]
282
-			);
283
-		}
284
-
285
-		return false;
286
-	}
287
-
288
-
289
-	/**
290
-	 * return current timestamp
291
-	 *
292
-	 * @return int
293
-	 */
294
-	protected function getTimestamp() {
295
-		return time();
296
-	}
297
-
298
-	/**
299
-	 * try http post with the given protocol, if no protocol is given we pick
300
-	 * the secure one (https)
301
-	 *
302
-	 * @param string $remoteDomain
303
-	 * @param string $urlSuffix
304
-	 * @param array $fields post parameters
305
-	 * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
306
-	 * @return array
307
-	 * @throws \Exception
308
-	 */
309
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
310
-
311
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
-			$remoteDomain = 'https://' . $remoteDomain;
313
-		}
314
-
315
-		$result = [
316
-			'success' => false,
317
-			'result' => '',
318
-		];
319
-
320
-		// if possible we use the new OCM API
321
-		$ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
322
-		if (is_array($ocmResult)) {
323
-			$result['success'] = true;
324
-			$result['result'] = json_encode([
325
-				'ocs' => ['meta' => ['statuscode' => 200]]]);
326
-			return $result;
327
-		}
328
-
329
-		return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
330
-	}
331
-
332
-	/**
333
-	 * try old federated sharing API if the OCM api doesn't work
334
-	 *
335
-	 * @param $remoteDomain
336
-	 * @param $urlSuffix
337
-	 * @param array $fields
338
-	 * @return mixed
339
-	 * @throws \Exception
340
-	 */
341
-	protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
342
-
343
-		$result = [
344
-			'success' => false,
345
-			'result' => '',
346
-		];
347
-
348
-		// Fall back to old API
349
-		$client = $this->httpClientService->newClient();
350
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
351
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
352
-		try {
353
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
354
-				'body' => $fields,
355
-				'timeout' => 10,
356
-				'connect_timeout' => 10,
357
-			]);
358
-			$result['result'] = $response->getBody();
359
-			$result['success'] = true;
360
-		} catch (\Exception $e) {
361
-			// if flat re-sharing is not supported by the remote server
362
-			// we re-throw the exception and fall back to the old behaviour.
363
-			// (flat re-shares has been introduced in Nextcloud 9.1)
364
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
365
-				throw $e;
366
-			}
367
-		}
368
-
369
-		return $result;
370
-
371
-	}
372
-
373
-	/**
374
-	 * check if server supports the new OCM api and ask for the correct end-point
375
-	 *
376
-	 * @param string $url
377
-	 * @return string
378
-	 */
379
-	protected function getOCMEndPoint($url) {
380
-		$client = $this->httpClientService->newClient();
381
-		try {
382
-			$response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 10]);
383
-		} catch (\Exception $e) {
384
-			return '';
385
-		}
386
-
387
-		$result = $response->getBody();
388
-		$result = json_decode($result, true);
389
-
390
-		if (isset($result['end-point'])) {
391
-			return $result['end-point'];
392
-		}
393
-
394
-		return '';
395
-	}
396
-
397
-	/**
398
-	 * send action regarding federated sharing to the remote server using the OCM API
399
-	 *
400
-	 * @param $remoteDomain
401
-	 * @param $fields
402
-	 * @param $action
403
-	 *
404
-	 * @return bool
405
-	 */
406
-	protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
407
-		switch ($action) {
408
-			case 'share':
409
-				$share = $this->cloudFederationFactory->getCloudFederationShare(
410
-					$fields['shareWith'] . '@' . $remoteDomain,
411
-					$fields['name'],
412
-					'',
413
-					$fields['remoteId'],
414
-					$fields['ownerFederatedId'],
415
-					$fields['owner'],
416
-					$fields['sharedByFederatedId'],
417
-					$fields['sharedBy'],
418
-					$fields['token'],
419
-					'user',
420
-					'file'
421
-				);
422
-				return $this->federationProviderManager->sendShare($share);
423
-			case 'reshare':
424
-				// ask owner to reshare a file
425
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
426
-				$notification->setMessage('REQUEST_RESHARE',
427
-					'file',
428
-					$fields['remoteId'],
429
-					[
430
-						'sharedSecret' => $fields['token'],
431
-						'shareWith' => $fields['shareWith'],
432
-						'senderId' => $fields['localId'],
433
-						'message' => 'Ask owner to reshare the file'
434
-					]
435
-				);
436
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
437
-			case 'unshare':
438
-				//owner unshares the file from the recipient again
439
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
440
-				$notification->setMessage('SHARE_UNSHARED',
441
-					'file',
442
-					$fields['remoteId'],
443
-					[
444
-						'sharedSecret' => $fields['token'],
445
-						'messgage' => 'file is no longer shared with you'
446
-					]
447
-				);
448
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
449
-			case 'reshare_undo':
450
-				// if a reshare was unshared we send the information to the initiator/owner
451
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
452
-				$notification->setMessage('RESHARE_UNDO',
453
-					'file',
454
-					$fields['remoteId'],
455
-					[
456
-						'sharedSecret' => $fields['token'],
457
-						'message' => 'reshare was revoked'
458
-					]
459
-				);
460
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
461
-		}
462
-
463
-		return false;
464
-
465
-	}
36
+    const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
+
38
+    /** @var AddressHandler */
39
+    private $addressHandler;
40
+
41
+    /** @var IClientService */
42
+    private $httpClientService;
43
+
44
+    /** @var IDiscoveryService */
45
+    private $discoveryService;
46
+
47
+    /** @var IJobList  */
48
+    private $jobList;
49
+
50
+    /** @var ICloudFederationProviderManager */
51
+    private $federationProviderManager;
52
+
53
+    /** @var ICloudFederationFactory */
54
+    private $cloudFederationFactory;
55
+
56
+    /**
57
+     * @param AddressHandler $addressHandler
58
+     * @param IClientService $httpClientService
59
+     * @param IDiscoveryService $discoveryService
60
+     * @param IJobList $jobList
61
+     * @param ICloudFederationProviderManager $federationProviderManager
62
+     * @param ICloudFederationFactory $cloudFederationFactory
63
+     */
64
+    public function __construct(
65
+        AddressHandler $addressHandler,
66
+        IClientService $httpClientService,
67
+        IDiscoveryService $discoveryService,
68
+        IJobList $jobList,
69
+        ICloudFederationProviderManager $federationProviderManager,
70
+        ICloudFederationFactory $cloudFederationFactory
71
+    ) {
72
+        $this->addressHandler = $addressHandler;
73
+        $this->httpClientService = $httpClientService;
74
+        $this->discoveryService = $discoveryService;
75
+        $this->jobList = $jobList;
76
+        $this->federationProviderManager = $federationProviderManager;
77
+        $this->cloudFederationFactory = $cloudFederationFactory;
78
+    }
79
+
80
+    /**
81
+     * send server-to-server share to remote server
82
+     *
83
+     * @param string $token
84
+     * @param string $shareWith
85
+     * @param string $name
86
+     * @param int $remote_id
87
+     * @param string $owner
88
+     * @param string $ownerFederatedId
89
+     * @param string $sharedBy
90
+     * @param string $sharedByFederatedId
91
+     * @return bool
92
+     * @throws \OC\HintException
93
+     * @throws \OC\ServerNotAvailableException
94
+     */
95
+    public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
96
+
97
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
98
+
99
+        if ($user && $remote) {
100
+            $local = $this->addressHandler->generateRemoteURL();
101
+
102
+            $fields = array(
103
+                'shareWith' => $user,
104
+                'token' => $token,
105
+                'name' => $name,
106
+                'remoteId' => $remote_id,
107
+                'owner' => $owner,
108
+                'ownerFederatedId' => $ownerFederatedId,
109
+                'sharedBy' => $sharedBy,
110
+                'sharedByFederatedId' => $sharedByFederatedId,
111
+                'remote' => $local,
112
+            );
113
+
114
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
115
+            $status = json_decode($result['result'], true);
116
+
117
+            $ocsStatus = isset($status['ocs']);
118
+            $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119
+
120
+            if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
121
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122
+                return true;
123
+            }
124
+
125
+        }
126
+
127
+        return false;
128
+    }
129
+
130
+    /**
131
+     * ask owner to re-share the file with the given user
132
+     *
133
+     * @param string $token
134
+     * @param int $id remote Id
135
+     * @param int $shareId internal share Id
136
+     * @param string $remote remote address of the owner
137
+     * @param string $shareWith
138
+     * @param int $permission
139
+     * @param string $filename
140
+     * @return bool
141
+     * @throws \OC\HintException
142
+     * @throws \OC\ServerNotAvailableException
143
+     */
144
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
145
+
146
+        $fields = array(
147
+            'shareWith' => $shareWith,
148
+            'token' => $token,
149
+            'permission' => $permission,
150
+            'remoteId' => $shareId,
151
+        );
152
+
153
+        $ocmFields = $fields;
154
+        $ocmFields['remoteId'] = $id;
155
+        $ocmFields['localId'] = $shareId;
156
+        $ocmFields['name'] = $filename;
157
+
158
+        $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
159
+        if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
160
+            return [$ocmResult['token'], $ocmResult['providerId']];
161
+        }
162
+
163
+        $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
164
+        $status = json_decode($result['result'], true);
165
+
166
+        $httpRequestSuccessful = $result['success'];
167
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
168
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
169
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
170
+
171
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172
+            return [
173
+                $status['ocs']['data']['token'],
174
+                (int)$status['ocs']['data']['remoteId']
175
+            ];
176
+        }
177
+
178
+        return false;
179
+    }
180
+
181
+    /**
182
+     * send server-to-server unshare to remote server
183
+     *
184
+     * @param string $remote url
185
+     * @param int $id share id
186
+     * @param string $token
187
+     * @return bool
188
+     */
189
+    public function sendRemoteUnShare($remote, $id, $token) {
190
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
191
+    }
192
+
193
+    /**
194
+     * send server-to-server unshare to remote server
195
+     *
196
+     * @param string $remote url
197
+     * @param int $id share id
198
+     * @param string $token
199
+     * @return bool
200
+     */
201
+    public function sendRevokeShare($remote, $id, $token) {
202
+        $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
203
+    }
204
+
205
+    /**
206
+     * send notification to remote server if the permissions was changed
207
+     *
208
+     * @param string $remote
209
+     * @param int $remoteId
210
+     * @param string $token
211
+     * @param int $permissions
212
+     * @return bool
213
+     */
214
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
215
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
216
+    }
217
+
218
+    /**
219
+     * forward accept reShare to remote server
220
+     *
221
+     * @param string $remote
222
+     * @param int $remoteId
223
+     * @param string $token
224
+     */
225
+    public function sendAcceptShare($remote, $remoteId, $token) {
226
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
227
+    }
228
+
229
+    /**
230
+     * forward decline reShare to remote server
231
+     *
232
+     * @param string $remote
233
+     * @param int $remoteId
234
+     * @param string $token
235
+     */
236
+    public function sendDeclineShare($remote, $remoteId, $token) {
237
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
238
+    }
239
+
240
+    /**
241
+     * inform remote server whether server-to-server share was accepted/declined
242
+     *
243
+     * @param string $remote
244
+     * @param string $token
245
+     * @param int $remoteId Share id on the remote host
246
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
247
+     * @param array $data
248
+     * @param int $try
249
+     * @return boolean
250
+     */
251
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
252
+
253
+        $fields = [
254
+            'token' => $token,
255
+            'remoteId' => $remoteId
256
+            ];
257
+        foreach ($data as $key => $value) {
258
+            $fields[$key] = $value;
259
+        }
260
+
261
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
262
+        $status = json_decode($result['result'], true);
263
+
264
+        if ($result['success'] &&
265
+            ($status['ocs']['meta']['statuscode'] === 100 ||
266
+                $status['ocs']['meta']['statuscode'] === 200
267
+            )
268
+        ) {
269
+            return true;
270
+        } elseif ($try === 0) {
271
+            // only add new job on first try
272
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
273
+                [
274
+                    'remote' => $remote,
275
+                    'remoteId' => $remoteId,
276
+                    'token' => $token,
277
+                    'action' => $action,
278
+                    'data' => json_encode($data),
279
+                    'try' => $try,
280
+                    'lastRun' => $this->getTimestamp()
281
+                ]
282
+            );
283
+        }
284
+
285
+        return false;
286
+    }
287
+
288
+
289
+    /**
290
+     * return current timestamp
291
+     *
292
+     * @return int
293
+     */
294
+    protected function getTimestamp() {
295
+        return time();
296
+    }
297
+
298
+    /**
299
+     * try http post with the given protocol, if no protocol is given we pick
300
+     * the secure one (https)
301
+     *
302
+     * @param string $remoteDomain
303
+     * @param string $urlSuffix
304
+     * @param array $fields post parameters
305
+     * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
306
+     * @return array
307
+     * @throws \Exception
308
+     */
309
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
310
+
311
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
+            $remoteDomain = 'https://' . $remoteDomain;
313
+        }
314
+
315
+        $result = [
316
+            'success' => false,
317
+            'result' => '',
318
+        ];
319
+
320
+        // if possible we use the new OCM API
321
+        $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
322
+        if (is_array($ocmResult)) {
323
+            $result['success'] = true;
324
+            $result['result'] = json_encode([
325
+                'ocs' => ['meta' => ['statuscode' => 200]]]);
326
+            return $result;
327
+        }
328
+
329
+        return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
330
+    }
331
+
332
+    /**
333
+     * try old federated sharing API if the OCM api doesn't work
334
+     *
335
+     * @param $remoteDomain
336
+     * @param $urlSuffix
337
+     * @param array $fields
338
+     * @return mixed
339
+     * @throws \Exception
340
+     */
341
+    protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
342
+
343
+        $result = [
344
+            'success' => false,
345
+            'result' => '',
346
+        ];
347
+
348
+        // Fall back to old API
349
+        $client = $this->httpClientService->newClient();
350
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
351
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
352
+        try {
353
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
354
+                'body' => $fields,
355
+                'timeout' => 10,
356
+                'connect_timeout' => 10,
357
+            ]);
358
+            $result['result'] = $response->getBody();
359
+            $result['success'] = true;
360
+        } catch (\Exception $e) {
361
+            // if flat re-sharing is not supported by the remote server
362
+            // we re-throw the exception and fall back to the old behaviour.
363
+            // (flat re-shares has been introduced in Nextcloud 9.1)
364
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
365
+                throw $e;
366
+            }
367
+        }
368
+
369
+        return $result;
370
+
371
+    }
372
+
373
+    /**
374
+     * check if server supports the new OCM api and ask for the correct end-point
375
+     *
376
+     * @param string $url
377
+     * @return string
378
+     */
379
+    protected function getOCMEndPoint($url) {
380
+        $client = $this->httpClientService->newClient();
381
+        try {
382
+            $response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 10]);
383
+        } catch (\Exception $e) {
384
+            return '';
385
+        }
386
+
387
+        $result = $response->getBody();
388
+        $result = json_decode($result, true);
389
+
390
+        if (isset($result['end-point'])) {
391
+            return $result['end-point'];
392
+        }
393
+
394
+        return '';
395
+    }
396
+
397
+    /**
398
+     * send action regarding federated sharing to the remote server using the OCM API
399
+     *
400
+     * @param $remoteDomain
401
+     * @param $fields
402
+     * @param $action
403
+     *
404
+     * @return bool
405
+     */
406
+    protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
407
+        switch ($action) {
408
+            case 'share':
409
+                $share = $this->cloudFederationFactory->getCloudFederationShare(
410
+                    $fields['shareWith'] . '@' . $remoteDomain,
411
+                    $fields['name'],
412
+                    '',
413
+                    $fields['remoteId'],
414
+                    $fields['ownerFederatedId'],
415
+                    $fields['owner'],
416
+                    $fields['sharedByFederatedId'],
417
+                    $fields['sharedBy'],
418
+                    $fields['token'],
419
+                    'user',
420
+                    'file'
421
+                );
422
+                return $this->federationProviderManager->sendShare($share);
423
+            case 'reshare':
424
+                // ask owner to reshare a file
425
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
426
+                $notification->setMessage('REQUEST_RESHARE',
427
+                    'file',
428
+                    $fields['remoteId'],
429
+                    [
430
+                        'sharedSecret' => $fields['token'],
431
+                        'shareWith' => $fields['shareWith'],
432
+                        'senderId' => $fields['localId'],
433
+                        'message' => 'Ask owner to reshare the file'
434
+                    ]
435
+                );
436
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
437
+            case 'unshare':
438
+                //owner unshares the file from the recipient again
439
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
440
+                $notification->setMessage('SHARE_UNSHARED',
441
+                    'file',
442
+                    $fields['remoteId'],
443
+                    [
444
+                        'sharedSecret' => $fields['token'],
445
+                        'messgage' => 'file is no longer shared with you'
446
+                    ]
447
+                );
448
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
449
+            case 'reshare_undo':
450
+                // if a reshare was unshared we send the information to the initiator/owner
451
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
452
+                $notification->setMessage('RESHARE_UNDO',
453
+                    'file',
454
+                    $fields['remoteId'],
455
+                    [
456
+                        'sharedSecret' => $fields['token'],
457
+                        'message' => 'reshare was revoked'
458
+                    ]
459
+                );
460
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
461
+        }
462
+
463
+        return false;
464
+
465
+    }
466 466
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -39,114 +39,114 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/** @var FederatedShareProvider */
43
-	protected $federatedShareProvider;
42
+    /** @var FederatedShareProvider */
43
+    protected $federatedShareProvider;
44 44
 
45
-	public function __construct() {
46
-		parent::__construct('federatedfilesharing');
45
+    public function __construct() {
46
+        parent::__construct('federatedfilesharing');
47 47
 
48
-		$container = $this->getContainer();
49
-		$server = $container->getServer();
48
+        $container = $this->getContainer();
49
+        $server = $container->getServer();
50 50
 
51
-		$cloudFederationManager = $server->getCloudFederationProviderManager();
52
-		$cloudFederationManager->addCloudFederationProvider('file',
53
-			'Federated Files Sharing',
54
-			function() use ($container) {
55
-				$server = $container->getServer();
56
-				return new CloudFederationProviderFiles(
57
-					$server->getAppManager(),
58
-					$server->query(FederatedShareProvider::class),
59
-					$server->query(AddressHandler::class),
60
-					$server->getLogger(),
61
-					$server->getUserManager(),
62
-					$server->getCloudIdManager(),
63
-					$server->getActivityManager(),
64
-					$server->getNotificationManager(),
65
-					$server->getURLGenerator(),
66
-					$server->getCloudFederationFactory(),
67
-					$server->getCloudFederationProviderManager(),
68
-					$server->getDatabaseConnection()
69
-				);
70
-			});
51
+        $cloudFederationManager = $server->getCloudFederationProviderManager();
52
+        $cloudFederationManager->addCloudFederationProvider('file',
53
+            'Federated Files Sharing',
54
+            function() use ($container) {
55
+                $server = $container->getServer();
56
+                return new CloudFederationProviderFiles(
57
+                    $server->getAppManager(),
58
+                    $server->query(FederatedShareProvider::class),
59
+                    $server->query(AddressHandler::class),
60
+                    $server->getLogger(),
61
+                    $server->getUserManager(),
62
+                    $server->getCloudIdManager(),
63
+                    $server->getActivityManager(),
64
+                    $server->getNotificationManager(),
65
+                    $server->getURLGenerator(),
66
+                    $server->getCloudFederationFactory(),
67
+                    $server->getCloudFederationProviderManager(),
68
+                    $server->getDatabaseConnection()
69
+                );
70
+            });
71 71
 
72
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
73
-			$addressHandler = new AddressHandler(
74
-				$server->getURLGenerator(),
75
-				$server->getL10N('federatedfilesharing'),
76
-				$server->getCloudIdManager()
77
-			);
78
-			$notification = new Notifications(
79
-				$addressHandler,
80
-				$server->getHTTPClientService(),
81
-				$server->query(\OCP\OCS\IDiscoveryService::class),
82
-				\OC::$server->getJobList(),
83
-				\OC::$server->getCloudFederationProviderManager(),
84
-				\OC::$server->getCloudFederationFactory()
85
-			);
86
-			return new RequestHandlerController(
87
-				$c->query('AppName'),
88
-				$server->getRequest(),
89
-				$this->getFederatedShareProvider(),
90
-				$server->getDatabaseConnection(),
91
-				$server->getShareManager(),
92
-				$notification,
93
-				$addressHandler,
94
-				$server->getUserManager(),
95
-				$server->getCloudIdManager(),
96
-				$server->getLogger(),
97
-				$server->getCloudFederationFactory(),
98
-				$server->getCloudFederationProviderManager()
99
-			);
100
-		});
101
-	}
72
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
73
+            $addressHandler = new AddressHandler(
74
+                $server->getURLGenerator(),
75
+                $server->getL10N('federatedfilesharing'),
76
+                $server->getCloudIdManager()
77
+            );
78
+            $notification = new Notifications(
79
+                $addressHandler,
80
+                $server->getHTTPClientService(),
81
+                $server->query(\OCP\OCS\IDiscoveryService::class),
82
+                \OC::$server->getJobList(),
83
+                \OC::$server->getCloudFederationProviderManager(),
84
+                \OC::$server->getCloudFederationFactory()
85
+            );
86
+            return new RequestHandlerController(
87
+                $c->query('AppName'),
88
+                $server->getRequest(),
89
+                $this->getFederatedShareProvider(),
90
+                $server->getDatabaseConnection(),
91
+                $server->getShareManager(),
92
+                $notification,
93
+                $addressHandler,
94
+                $server->getUserManager(),
95
+                $server->getCloudIdManager(),
96
+                $server->getLogger(),
97
+                $server->getCloudFederationFactory(),
98
+                $server->getCloudFederationProviderManager()
99
+            );
100
+        });
101
+    }
102 102
 
103
-	/**
104
-	 * get instance of federated share provider
105
-	 *
106
-	 * @return FederatedShareProvider
107
-	 */
108
-	public function getFederatedShareProvider() {
109
-		if ($this->federatedShareProvider === null) {
110
-			$this->initFederatedShareProvider();
111
-		}
112
-		return $this->federatedShareProvider;
113
-	}
103
+    /**
104
+     * get instance of federated share provider
105
+     *
106
+     * @return FederatedShareProvider
107
+     */
108
+    public function getFederatedShareProvider() {
109
+        if ($this->federatedShareProvider === null) {
110
+            $this->initFederatedShareProvider();
111
+        }
112
+        return $this->federatedShareProvider;
113
+    }
114 114
 
115
-	/**
116
-	 * initialize federated share provider
117
-	 */
118
-	protected function initFederatedShareProvider() {
119
-		$c = $this->getContainer();
120
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
121
-			\OC::$server->getURLGenerator(),
122
-			\OC::$server->getL10N('federatedfilesharing'),
123
-			\OC::$server->getCloudIdManager()
124
-		);
125
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
126
-			$addressHandler,
127
-			\OC::$server->getHTTPClientService(),
128
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
129
-			\OC::$server->getJobList(),
130
-			\OC::$server->getCloudFederationProviderManager(),
131
-			\OC::$server->getCloudFederationFactory()
132
-		);
133
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
134
-			\OC::$server->getSecureRandom()
135
-		);
115
+    /**
116
+     * initialize federated share provider
117
+     */
118
+    protected function initFederatedShareProvider() {
119
+        $c = $this->getContainer();
120
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
121
+            \OC::$server->getURLGenerator(),
122
+            \OC::$server->getL10N('federatedfilesharing'),
123
+            \OC::$server->getCloudIdManager()
124
+        );
125
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
126
+            $addressHandler,
127
+            \OC::$server->getHTTPClientService(),
128
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
129
+            \OC::$server->getJobList(),
130
+            \OC::$server->getCloudFederationProviderManager(),
131
+            \OC::$server->getCloudFederationFactory()
132
+        );
133
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
134
+            \OC::$server->getSecureRandom()
135
+        );
136 136
 
137
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
138
-			\OC::$server->getDatabaseConnection(),
139
-			$addressHandler,
140
-			$notifications,
141
-			$tokenHandler,
142
-			\OC::$server->getL10N('federatedfilesharing'),
143
-			\OC::$server->getLogger(),
144
-			\OC::$server->getLazyRootFolder(),
145
-			\OC::$server->getConfig(),
146
-			\OC::$server->getUserManager(),
147
-			\OC::$server->getCloudIdManager(),
148
-			$c->query(IConfig::class)
149
-		);
150
-	}
137
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
138
+            \OC::$server->getDatabaseConnection(),
139
+            $addressHandler,
140
+            $notifications,
141
+            $tokenHandler,
142
+            \OC::$server->getL10N('federatedfilesharing'),
143
+            \OC::$server->getLogger(),
144
+            \OC::$server->getLazyRootFolder(),
145
+            \OC::$server->getConfig(),
146
+            \OC::$server->getUserManager(),
147
+            \OC::$server->getCloudIdManager(),
148
+            $c->query(IConfig::class)
149
+        );
150
+    }
151 151
 
152 152
 }
Please login to merge, or discard this patch.