Completed
Pull Request — master (#9345)
by Björn
20:43 queued 01:50
created
apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php 1 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.
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 patch
Indentation   +966 added lines, -966 removed lines patch added patch discarded remove patch
@@ -54,980 +54,980 @@
 block discarded – undo
54 54
  */
55 55
 class FederatedShareProvider implements IShareProvider {
56 56
 
57
-	const SHARE_TYPE_REMOTE = 6;
58
-
59
-	/** @var IDBConnection */
60
-	private $dbConnection;
61
-
62
-	/** @var AddressHandler */
63
-	private $addressHandler;
64
-
65
-	/** @var Notifications */
66
-	private $notifications;
67
-
68
-	/** @var TokenHandler */
69
-	private $tokenHandler;
70
-
71
-	/** @var IL10N */
72
-	private $l;
73
-
74
-	/** @var ILogger */
75
-	private $logger;
76
-
77
-	/** @var IRootFolder */
78
-	private $rootFolder;
79
-
80
-	/** @var IConfig */
81
-	private $config;
82
-
83
-	/** @var string */
84
-	private $externalShareTable = 'share_external';
85
-
86
-	/** @var IUserManager */
87
-	private $userManager;
88
-
89
-	/** @var ICloudIdManager */
90
-	private $cloudIdManager;
91
-
92
-	/** @var \OCP\GlobalScale\IConfig */
93
-	private $gsConfig;
94
-
95
-	/**
96
-	 * DefaultShareProvider constructor.
97
-	 *
98
-	 * @param IDBConnection $connection
99
-	 * @param AddressHandler $addressHandler
100
-	 * @param Notifications $notifications
101
-	 * @param TokenHandler $tokenHandler
102
-	 * @param IL10N $l10n
103
-	 * @param ILogger $logger
104
-	 * @param IRootFolder $rootFolder
105
-	 * @param IConfig $config
106
-	 * @param IUserManager $userManager
107
-	 * @param ICloudIdManager $cloudIdManager
108
-	 * @param \OCP\GlobalScale\IConfig $globalScaleConfig
109
-	 */
110
-	public function __construct(
111
-			IDBConnection $connection,
112
-			AddressHandler $addressHandler,
113
-			Notifications $notifications,
114
-			TokenHandler $tokenHandler,
115
-			IL10N $l10n,
116
-			ILogger $logger,
117
-			IRootFolder $rootFolder,
118
-			IConfig $config,
119
-			IUserManager $userManager,
120
-			ICloudIdManager $cloudIdManager,
121
-			\OCP\GlobalScale\IConfig $globalScaleConfig
122
-	) {
123
-		$this->dbConnection = $connection;
124
-		$this->addressHandler = $addressHandler;
125
-		$this->notifications = $notifications;
126
-		$this->tokenHandler = $tokenHandler;
127
-		$this->l = $l10n;
128
-		$this->logger = $logger;
129
-		$this->rootFolder = $rootFolder;
130
-		$this->config = $config;
131
-		$this->userManager = $userManager;
132
-		$this->cloudIdManager = $cloudIdManager;
133
-		$this->gsConfig = $globalScaleConfig;
134
-	}
135
-
136
-	/**
137
-	 * Return the identifier of this provider.
138
-	 *
139
-	 * @return string Containing only [a-zA-Z0-9]
140
-	 */
141
-	public function identifier() {
142
-		return 'ocFederatedSharing';
143
-	}
144
-
145
-	/**
146
-	 * Share a path
147
-	 *
148
-	 * @param IShare $share
149
-	 * @return IShare The share object
150
-	 * @throws ShareNotFound
151
-	 * @throws \Exception
152
-	 */
153
-	public function create(IShare $share) {
154
-
155
-		$shareWith = $share->getSharedWith();
156
-		$itemSource = $share->getNodeId();
157
-		$itemType = $share->getNodeType();
158
-		$permissions = $share->getPermissions();
159
-		$sharedBy = $share->getSharedBy();
160
-
161
-		/*
57
+    const SHARE_TYPE_REMOTE = 6;
58
+
59
+    /** @var IDBConnection */
60
+    private $dbConnection;
61
+
62
+    /** @var AddressHandler */
63
+    private $addressHandler;
64
+
65
+    /** @var Notifications */
66
+    private $notifications;
67
+
68
+    /** @var TokenHandler */
69
+    private $tokenHandler;
70
+
71
+    /** @var IL10N */
72
+    private $l;
73
+
74
+    /** @var ILogger */
75
+    private $logger;
76
+
77
+    /** @var IRootFolder */
78
+    private $rootFolder;
79
+
80
+    /** @var IConfig */
81
+    private $config;
82
+
83
+    /** @var string */
84
+    private $externalShareTable = 'share_external';
85
+
86
+    /** @var IUserManager */
87
+    private $userManager;
88
+
89
+    /** @var ICloudIdManager */
90
+    private $cloudIdManager;
91
+
92
+    /** @var \OCP\GlobalScale\IConfig */
93
+    private $gsConfig;
94
+
95
+    /**
96
+     * DefaultShareProvider constructor.
97
+     *
98
+     * @param IDBConnection $connection
99
+     * @param AddressHandler $addressHandler
100
+     * @param Notifications $notifications
101
+     * @param TokenHandler $tokenHandler
102
+     * @param IL10N $l10n
103
+     * @param ILogger $logger
104
+     * @param IRootFolder $rootFolder
105
+     * @param IConfig $config
106
+     * @param IUserManager $userManager
107
+     * @param ICloudIdManager $cloudIdManager
108
+     * @param \OCP\GlobalScale\IConfig $globalScaleConfig
109
+     */
110
+    public function __construct(
111
+            IDBConnection $connection,
112
+            AddressHandler $addressHandler,
113
+            Notifications $notifications,
114
+            TokenHandler $tokenHandler,
115
+            IL10N $l10n,
116
+            ILogger $logger,
117
+            IRootFolder $rootFolder,
118
+            IConfig $config,
119
+            IUserManager $userManager,
120
+            ICloudIdManager $cloudIdManager,
121
+            \OCP\GlobalScale\IConfig $globalScaleConfig
122
+    ) {
123
+        $this->dbConnection = $connection;
124
+        $this->addressHandler = $addressHandler;
125
+        $this->notifications = $notifications;
126
+        $this->tokenHandler = $tokenHandler;
127
+        $this->l = $l10n;
128
+        $this->logger = $logger;
129
+        $this->rootFolder = $rootFolder;
130
+        $this->config = $config;
131
+        $this->userManager = $userManager;
132
+        $this->cloudIdManager = $cloudIdManager;
133
+        $this->gsConfig = $globalScaleConfig;
134
+    }
135
+
136
+    /**
137
+     * Return the identifier of this provider.
138
+     *
139
+     * @return string Containing only [a-zA-Z0-9]
140
+     */
141
+    public function identifier() {
142
+        return 'ocFederatedSharing';
143
+    }
144
+
145
+    /**
146
+     * Share a path
147
+     *
148
+     * @param IShare $share
149
+     * @return IShare The share object
150
+     * @throws ShareNotFound
151
+     * @throws \Exception
152
+     */
153
+    public function create(IShare $share) {
154
+
155
+        $shareWith = $share->getSharedWith();
156
+        $itemSource = $share->getNodeId();
157
+        $itemType = $share->getNodeType();
158
+        $permissions = $share->getPermissions();
159
+        $sharedBy = $share->getSharedBy();
160
+
161
+        /*
162 162
 		 * Check if file is not already shared with the remote user
163 163
 		 */
164
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
165
-		if (!empty($alreadyShared)) {
166
-			$message = 'Sharing %s failed, because this item is already shared with %s';
167
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
168
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
169
-			throw new \Exception($message_t);
170
-		}
171
-
172
-
173
-		// don't allow federated shares if source and target server are the same
174
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
175
-		$currentServer = $this->addressHandler->generateRemoteURL();
176
-		$currentUser = $sharedBy;
177
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
178
-			$message = 'Not allowed to create a federated share with the same user.';
179
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
180
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
181
-			throw new \Exception($message_t);
182
-		}
183
-
184
-
185
-		$share->setSharedWith($cloudId->getId());
186
-
187
-		try {
188
-			$remoteShare = $this->getShareFromExternalShareTable($share);
189
-		} catch (ShareNotFound $e) {
190
-			$remoteShare = null;
191
-		}
192
-
193
-		if ($remoteShare) {
194
-			try {
195
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
196
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
197
-				$share->setId($shareId);
198
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
199
-				// remote share was create successfully if we get a valid token as return
200
-				$send = is_string($token) && $token !== '';
201
-			} catch (\Exception $e) {
202
-				// fall back to old re-share behavior if the remote server
203
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
204
-				$this->removeShareFromTable($share);
205
-				$shareId = $this->createFederatedShare($share);
206
-			}
207
-			if ($send) {
208
-				$this->updateSuccessfulReshare($shareId, $token);
209
-				$this->storeRemoteId($shareId, $remoteId);
210
-			} else {
211
-				$this->removeShareFromTable($share);
212
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
213
-				throw new \Exception($message_t);
214
-			}
215
-
216
-		} else {
217
-			$shareId = $this->createFederatedShare($share);
218
-		}
219
-
220
-		$data = $this->getRawShare($shareId);
221
-		return $this->createShareObject($data);
222
-	}
223
-
224
-	/**
225
-	 * create federated share and inform the recipient
226
-	 *
227
-	 * @param IShare $share
228
-	 * @return int
229
-	 * @throws ShareNotFound
230
-	 * @throws \Exception
231
-	 */
232
-	protected function createFederatedShare(IShare $share) {
233
-		$token = $this->tokenHandler->generateToken();
234
-		$shareId = $this->addShareToDB(
235
-			$share->getNodeId(),
236
-			$share->getNodeType(),
237
-			$share->getSharedWith(),
238
-			$share->getSharedBy(),
239
-			$share->getShareOwner(),
240
-			$share->getPermissions(),
241
-			$token
242
-		);
243
-
244
-		$failure = false;
245
-
246
-		try {
247
-			$sharedByFederatedId = $share->getSharedBy();
248
-			if ($this->userManager->userExists($sharedByFederatedId)) {
249
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
250
-				$sharedByFederatedId = $cloudId->getId();
251
-			}
252
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
253
-			$send = $this->notifications->sendRemoteShare(
254
-				$token,
255
-				$share->getSharedWith(),
256
-				$share->getNode()->getName(),
257
-				$shareId,
258
-				$share->getShareOwner(),
259
-				$ownerCloudId->getId(),
260
-				$share->getSharedBy(),
261
-				$sharedByFederatedId
262
-			);
263
-
264
-			if ($send === false) {
265
-				$failure = true;
266
-			}
267
-		} catch (\Exception $e) {
268
-			$this->logger->logException($e, [
269
-				'message' => 'Failed to notify remote server of federated share, removing share.',
270
-				'level' => ILogger::ERROR,
271
-				'app' => 'federatedfilesharing',
272
-			]);
273
-			$failure = true;
274
-		}
275
-
276
-		if($failure) {
277
-			$this->removeShareFromTableById($shareId);
278
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
279
-				[$share->getNode()->getName(), $share->getSharedWith()]);
280
-			throw new \Exception($message_t);
281
-		}
282
-
283
-		return $shareId;
284
-
285
-	}
286
-
287
-	/**
288
-	 * @param string $shareWith
289
-	 * @param IShare $share
290
-	 * @param string $shareId internal share Id
291
-	 * @return array
292
-	 * @throws \Exception
293
-	 */
294
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
295
-
296
-		$remoteShare = $this->getShareFromExternalShareTable($share);
297
-		$token = $remoteShare['share_token'];
298
-		$remoteId = $remoteShare['remote_id'];
299
-		$remote = $remoteShare['remote'];
300
-
301
-		list($token, $remoteId) = $this->notifications->requestReShare(
302
-			$token,
303
-			$remoteId,
304
-			$shareId,
305
-			$remote,
306
-			$shareWith,
307
-			$share->getPermissions(),
308
-			$share->getNode()->getName()
309
-		);
310
-
311
-		return [$token, $remoteId];
312
-	}
313
-
314
-	/**
315
-	 * get federated share from the share_external table but exclude mounted link shares
316
-	 *
317
-	 * @param IShare $share
318
-	 * @return array
319
-	 * @throws ShareNotFound
320
-	 */
321
-	protected function getShareFromExternalShareTable(IShare $share) {
322
-		$query = $this->dbConnection->getQueryBuilder();
323
-		$query->select('*')->from($this->externalShareTable)
324
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
325
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
326
-		$result = $query->execute()->fetchAll();
327
-
328
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
329
-			return $result[0];
330
-		}
331
-
332
-		throw new ShareNotFound('share not found in share_external table');
333
-	}
334
-
335
-	/**
336
-	 * add share to the database and return the ID
337
-	 *
338
-	 * @param int $itemSource
339
-	 * @param string $itemType
340
-	 * @param string $shareWith
341
-	 * @param string $sharedBy
342
-	 * @param string $uidOwner
343
-	 * @param int $permissions
344
-	 * @param string $token
345
-	 * @return int
346
-	 */
347
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
348
-		$qb = $this->dbConnection->getQueryBuilder();
349
-		$qb->insert('share')
350
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
351
-			->setValue('item_type', $qb->createNamedParameter($itemType))
352
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
353
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
354
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
355
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
356
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
357
-			->setValue('permissions', $qb->createNamedParameter($permissions))
358
-			->setValue('token', $qb->createNamedParameter($token))
359
-			->setValue('stime', $qb->createNamedParameter(time()));
360
-
361
-		/*
164
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
165
+        if (!empty($alreadyShared)) {
166
+            $message = 'Sharing %s failed, because this item is already shared with %s';
167
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
168
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
169
+            throw new \Exception($message_t);
170
+        }
171
+
172
+
173
+        // don't allow federated shares if source and target server are the same
174
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
175
+        $currentServer = $this->addressHandler->generateRemoteURL();
176
+        $currentUser = $sharedBy;
177
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
178
+            $message = 'Not allowed to create a federated share with the same user.';
179
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
180
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
181
+            throw new \Exception($message_t);
182
+        }
183
+
184
+
185
+        $share->setSharedWith($cloudId->getId());
186
+
187
+        try {
188
+            $remoteShare = $this->getShareFromExternalShareTable($share);
189
+        } catch (ShareNotFound $e) {
190
+            $remoteShare = null;
191
+        }
192
+
193
+        if ($remoteShare) {
194
+            try {
195
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
196
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
197
+                $share->setId($shareId);
198
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
199
+                // remote share was create successfully if we get a valid token as return
200
+                $send = is_string($token) && $token !== '';
201
+            } catch (\Exception $e) {
202
+                // fall back to old re-share behavior if the remote server
203
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
204
+                $this->removeShareFromTable($share);
205
+                $shareId = $this->createFederatedShare($share);
206
+            }
207
+            if ($send) {
208
+                $this->updateSuccessfulReshare($shareId, $token);
209
+                $this->storeRemoteId($shareId, $remoteId);
210
+            } else {
211
+                $this->removeShareFromTable($share);
212
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
213
+                throw new \Exception($message_t);
214
+            }
215
+
216
+        } else {
217
+            $shareId = $this->createFederatedShare($share);
218
+        }
219
+
220
+        $data = $this->getRawShare($shareId);
221
+        return $this->createShareObject($data);
222
+    }
223
+
224
+    /**
225
+     * create federated share and inform the recipient
226
+     *
227
+     * @param IShare $share
228
+     * @return int
229
+     * @throws ShareNotFound
230
+     * @throws \Exception
231
+     */
232
+    protected function createFederatedShare(IShare $share) {
233
+        $token = $this->tokenHandler->generateToken();
234
+        $shareId = $this->addShareToDB(
235
+            $share->getNodeId(),
236
+            $share->getNodeType(),
237
+            $share->getSharedWith(),
238
+            $share->getSharedBy(),
239
+            $share->getShareOwner(),
240
+            $share->getPermissions(),
241
+            $token
242
+        );
243
+
244
+        $failure = false;
245
+
246
+        try {
247
+            $sharedByFederatedId = $share->getSharedBy();
248
+            if ($this->userManager->userExists($sharedByFederatedId)) {
249
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
250
+                $sharedByFederatedId = $cloudId->getId();
251
+            }
252
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
253
+            $send = $this->notifications->sendRemoteShare(
254
+                $token,
255
+                $share->getSharedWith(),
256
+                $share->getNode()->getName(),
257
+                $shareId,
258
+                $share->getShareOwner(),
259
+                $ownerCloudId->getId(),
260
+                $share->getSharedBy(),
261
+                $sharedByFederatedId
262
+            );
263
+
264
+            if ($send === false) {
265
+                $failure = true;
266
+            }
267
+        } catch (\Exception $e) {
268
+            $this->logger->logException($e, [
269
+                'message' => 'Failed to notify remote server of federated share, removing share.',
270
+                'level' => ILogger::ERROR,
271
+                'app' => 'federatedfilesharing',
272
+            ]);
273
+            $failure = true;
274
+        }
275
+
276
+        if($failure) {
277
+            $this->removeShareFromTableById($shareId);
278
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
279
+                [$share->getNode()->getName(), $share->getSharedWith()]);
280
+            throw new \Exception($message_t);
281
+        }
282
+
283
+        return $shareId;
284
+
285
+    }
286
+
287
+    /**
288
+     * @param string $shareWith
289
+     * @param IShare $share
290
+     * @param string $shareId internal share Id
291
+     * @return array
292
+     * @throws \Exception
293
+     */
294
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
295
+
296
+        $remoteShare = $this->getShareFromExternalShareTable($share);
297
+        $token = $remoteShare['share_token'];
298
+        $remoteId = $remoteShare['remote_id'];
299
+        $remote = $remoteShare['remote'];
300
+
301
+        list($token, $remoteId) = $this->notifications->requestReShare(
302
+            $token,
303
+            $remoteId,
304
+            $shareId,
305
+            $remote,
306
+            $shareWith,
307
+            $share->getPermissions(),
308
+            $share->getNode()->getName()
309
+        );
310
+
311
+        return [$token, $remoteId];
312
+    }
313
+
314
+    /**
315
+     * get federated share from the share_external table but exclude mounted link shares
316
+     *
317
+     * @param IShare $share
318
+     * @return array
319
+     * @throws ShareNotFound
320
+     */
321
+    protected function getShareFromExternalShareTable(IShare $share) {
322
+        $query = $this->dbConnection->getQueryBuilder();
323
+        $query->select('*')->from($this->externalShareTable)
324
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
325
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
326
+        $result = $query->execute()->fetchAll();
327
+
328
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
329
+            return $result[0];
330
+        }
331
+
332
+        throw new ShareNotFound('share not found in share_external table');
333
+    }
334
+
335
+    /**
336
+     * add share to the database and return the ID
337
+     *
338
+     * @param int $itemSource
339
+     * @param string $itemType
340
+     * @param string $shareWith
341
+     * @param string $sharedBy
342
+     * @param string $uidOwner
343
+     * @param int $permissions
344
+     * @param string $token
345
+     * @return int
346
+     */
347
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
348
+        $qb = $this->dbConnection->getQueryBuilder();
349
+        $qb->insert('share')
350
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
351
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
352
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
353
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
354
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
355
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
356
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
357
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
358
+            ->setValue('token', $qb->createNamedParameter($token))
359
+            ->setValue('stime', $qb->createNamedParameter(time()));
360
+
361
+        /*
362 362
 		 * Added to fix https://github.com/owncloud/core/issues/22215
363 363
 		 * Can be removed once we get rid of ajax/share.php
364 364
 		 */
365
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
366
-
367
-		$qb->execute();
368
-		$id = $qb->getLastInsertId();
369
-
370
-		return (int)$id;
371
-	}
372
-
373
-	/**
374
-	 * Update a share
375
-	 *
376
-	 * @param IShare $share
377
-	 * @return IShare The share object
378
-	 */
379
-	public function update(IShare $share) {
380
-		/*
365
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
366
+
367
+        $qb->execute();
368
+        $id = $qb->getLastInsertId();
369
+
370
+        return (int)$id;
371
+    }
372
+
373
+    /**
374
+     * Update a share
375
+     *
376
+     * @param IShare $share
377
+     * @return IShare The share object
378
+     */
379
+    public function update(IShare $share) {
380
+        /*
381 381
 		 * We allow updating the permissions of federated shares
382 382
 		 */
383
-		$qb = $this->dbConnection->getQueryBuilder();
384
-			$qb->update('share')
385
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
386
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
387
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
388
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
389
-				->execute();
390
-
391
-		// send the updated permission to the owner/initiator, if they are not the same
392
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
393
-			$this->sendPermissionUpdate($share);
394
-		}
395
-
396
-		return $share;
397
-	}
398
-
399
-	/**
400
-	 * send the updated permission to the owner/initiator, if they are not the same
401
-	 *
402
-	 * @param IShare $share
403
-	 * @throws ShareNotFound
404
-	 * @throws \OC\HintException
405
-	 */
406
-	protected function sendPermissionUpdate(IShare $share) {
407
-		$remoteId = $this->getRemoteId($share);
408
-		// if the local user is the owner we send the permission change to the initiator
409
-		if ($this->userManager->userExists($share->getShareOwner())) {
410
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
411
-		} else { // ... if not we send the permission change to the owner
412
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
413
-		}
414
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
415
-	}
416
-
417
-
418
-	/**
419
-	 * update successful reShare with the correct token
420
-	 *
421
-	 * @param int $shareId
422
-	 * @param string $token
423
-	 */
424
-	protected function updateSuccessfulReShare($shareId, $token) {
425
-		$query = $this->dbConnection->getQueryBuilder();
426
-		$query->update('share')
427
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
428
-			->set('token', $query->createNamedParameter($token))
429
-			->execute();
430
-	}
431
-
432
-	/**
433
-	 * store remote ID in federated reShare table
434
-	 *
435
-	 * @param $shareId
436
-	 * @param $remoteId
437
-	 */
438
-	public function storeRemoteId($shareId, $remoteId) {
439
-		$query = $this->dbConnection->getQueryBuilder();
440
-		$query->insert('federated_reshares')
441
-			->values(
442
-				[
443
-					'share_id' =>  $query->createNamedParameter($shareId),
444
-					'remote_id' => $query->createNamedParameter($remoteId),
445
-				]
446
-			);
447
-		$query->execute();
448
-	}
449
-
450
-	/**
451
-	 * get share ID on remote server for federated re-shares
452
-	 *
453
-	 * @param IShare $share
454
-	 * @return int
455
-	 * @throws ShareNotFound
456
-	 */
457
-	public function getRemoteId(IShare $share) {
458
-		$query = $this->dbConnection->getQueryBuilder();
459
-		$query->select('remote_id')->from('federated_reshares')
460
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
461
-		$data = $query->execute()->fetch();
462
-
463
-		if (!is_array($data) || !isset($data['remote_id'])) {
464
-			throw new ShareNotFound();
465
-		}
466
-
467
-		return (int)$data['remote_id'];
468
-	}
469
-
470
-	/**
471
-	 * @inheritdoc
472
-	 */
473
-	public function move(IShare $share, $recipient) {
474
-		/*
383
+        $qb = $this->dbConnection->getQueryBuilder();
384
+            $qb->update('share')
385
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
386
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
387
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
388
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
389
+                ->execute();
390
+
391
+        // send the updated permission to the owner/initiator, if they are not the same
392
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
393
+            $this->sendPermissionUpdate($share);
394
+        }
395
+
396
+        return $share;
397
+    }
398
+
399
+    /**
400
+     * send the updated permission to the owner/initiator, if they are not the same
401
+     *
402
+     * @param IShare $share
403
+     * @throws ShareNotFound
404
+     * @throws \OC\HintException
405
+     */
406
+    protected function sendPermissionUpdate(IShare $share) {
407
+        $remoteId = $this->getRemoteId($share);
408
+        // if the local user is the owner we send the permission change to the initiator
409
+        if ($this->userManager->userExists($share->getShareOwner())) {
410
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
411
+        } else { // ... if not we send the permission change to the owner
412
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
413
+        }
414
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
415
+    }
416
+
417
+
418
+    /**
419
+     * update successful reShare with the correct token
420
+     *
421
+     * @param int $shareId
422
+     * @param string $token
423
+     */
424
+    protected function updateSuccessfulReShare($shareId, $token) {
425
+        $query = $this->dbConnection->getQueryBuilder();
426
+        $query->update('share')
427
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
428
+            ->set('token', $query->createNamedParameter($token))
429
+            ->execute();
430
+    }
431
+
432
+    /**
433
+     * store remote ID in federated reShare table
434
+     *
435
+     * @param $shareId
436
+     * @param $remoteId
437
+     */
438
+    public function storeRemoteId($shareId, $remoteId) {
439
+        $query = $this->dbConnection->getQueryBuilder();
440
+        $query->insert('federated_reshares')
441
+            ->values(
442
+                [
443
+                    'share_id' =>  $query->createNamedParameter($shareId),
444
+                    'remote_id' => $query->createNamedParameter($remoteId),
445
+                ]
446
+            );
447
+        $query->execute();
448
+    }
449
+
450
+    /**
451
+     * get share ID on remote server for federated re-shares
452
+     *
453
+     * @param IShare $share
454
+     * @return int
455
+     * @throws ShareNotFound
456
+     */
457
+    public function getRemoteId(IShare $share) {
458
+        $query = $this->dbConnection->getQueryBuilder();
459
+        $query->select('remote_id')->from('federated_reshares')
460
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
461
+        $data = $query->execute()->fetch();
462
+
463
+        if (!is_array($data) || !isset($data['remote_id'])) {
464
+            throw new ShareNotFound();
465
+        }
466
+
467
+        return (int)$data['remote_id'];
468
+    }
469
+
470
+    /**
471
+     * @inheritdoc
472
+     */
473
+    public function move(IShare $share, $recipient) {
474
+        /*
475 475
 		 * This function does nothing yet as it is just for outgoing
476 476
 		 * federated shares.
477 477
 		 */
478
-		return $share;
479
-	}
480
-
481
-	/**
482
-	 * Get all children of this share
483
-	 *
484
-	 * @param IShare $parent
485
-	 * @return IShare[]
486
-	 */
487
-	public function getChildren(IShare $parent) {
488
-		$children = [];
489
-
490
-		$qb = $this->dbConnection->getQueryBuilder();
491
-		$qb->select('*')
492
-			->from('share')
493
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
494
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
495
-			->orderBy('id');
496
-
497
-		$cursor = $qb->execute();
498
-		while($data = $cursor->fetch()) {
499
-			$children[] = $this->createShareObject($data);
500
-		}
501
-		$cursor->closeCursor();
502
-
503
-		return $children;
504
-	}
505
-
506
-	/**
507
-	 * Delete a share (owner unShares the file)
508
-	 *
509
-	 * @param IShare $share
510
-	 */
511
-	public function delete(IShare $share) {
512
-
513
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
514
-
515
-		$isOwner = false;
516
-
517
-		// if the local user is the owner we can send the unShare request directly...
518
-		if ($this->userManager->userExists($share->getShareOwner())) {
519
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
520
-			$this->revokeShare($share, true);
521
-		} else { // ... if not we need to correct ID for the unShare request
522
-			$remoteId = $this->getRemoteId($share);
523
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
524
-			$this->revokeShare($share, false);
525
-		}
526
-
527
-		// only remove the share when all messages are send to not lose information
528
-		// about the share to early
529
-		$this->removeShareFromTable($share);
530
-	}
531
-
532
-	/**
533
-	 * in case of a re-share we need to send the other use (initiator or owner)
534
-	 * a message that the file was unshared
535
-	 *
536
-	 * @param IShare $share
537
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
538
-	 * @throws ShareNotFound
539
-	 * @throws \OC\HintException
540
-	 */
541
-	protected function revokeShare($share, $isOwner) {
542
-		// also send a unShare request to the initiator, if this is a different user than the owner
543
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
544
-			if ($isOwner) {
545
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
546
-			} else {
547
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
548
-			}
549
-			$remoteId = $this->getRemoteId($share);
550
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
551
-		}
552
-	}
553
-
554
-	/**
555
-	 * remove share from table
556
-	 *
557
-	 * @param IShare $share
558
-	 */
559
-	public function removeShareFromTable(IShare $share) {
560
-		$this->removeShareFromTableById($share->getId());
561
-	}
562
-
563
-	/**
564
-	 * remove share from table
565
-	 *
566
-	 * @param string $shareId
567
-	 */
568
-	private function removeShareFromTableById($shareId) {
569
-		$qb = $this->dbConnection->getQueryBuilder();
570
-		$qb->delete('share')
571
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
572
-		$qb->execute();
573
-
574
-		$qb->delete('federated_reshares')
575
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
576
-		$qb->execute();
577
-	}
578
-
579
-	/**
580
-	 * @inheritdoc
581
-	 */
582
-	public function deleteFromSelf(IShare $share, $recipient) {
583
-		// nothing to do here. Technically deleteFromSelf in the context of federated
584
-		// shares is a umount of a external storage. This is handled here
585
-		// apps/files_sharing/lib/external/manager.php
586
-		// TODO move this code over to this app
587
-	}
588
-
589
-
590
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
591
-		$qb = $this->dbConnection->getQueryBuilder();
592
-		$qb->select('*')
593
-			->from('share', 's')
594
-			->andWhere($qb->expr()->orX(
595
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
596
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
597
-			))
598
-			->andWhere(
599
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
600
-			);
601
-
602
-		/**
603
-		 * Reshares for this user are shares where they are the owner.
604
-		 */
605
-		if ($reshares === false) {
606
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
607
-		} else {
608
-			$qb->andWhere(
609
-				$qb->expr()->orX(
610
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
611
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
612
-				)
613
-			);
614
-		}
615
-
616
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
617
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
618
-
619
-		$qb->orderBy('id');
620
-
621
-		$cursor = $qb->execute();
622
-		$shares = [];
623
-		while ($data = $cursor->fetch()) {
624
-			$shares[$data['fileid']][] = $this->createShareObject($data);
625
-		}
626
-		$cursor->closeCursor();
627
-
628
-		return $shares;
629
-	}
630
-
631
-	/**
632
-	 * @inheritdoc
633
-	 */
634
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
635
-		$qb = $this->dbConnection->getQueryBuilder();
636
-		$qb->select('*')
637
-			->from('share');
638
-
639
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
640
-
641
-		/**
642
-		 * Reshares for this user are shares where they are the owner.
643
-		 */
644
-		if ($reshares === false) {
645
-			//Special case for old shares created via the web UI
646
-			$or1 = $qb->expr()->andX(
647
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
648
-				$qb->expr()->isNull('uid_initiator')
649
-			);
650
-
651
-			$qb->andWhere(
652
-				$qb->expr()->orX(
653
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
654
-					$or1
655
-				)
656
-			);
657
-		} else {
658
-			$qb->andWhere(
659
-				$qb->expr()->orX(
660
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
661
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
662
-				)
663
-			);
664
-		}
665
-
666
-		if ($node !== null) {
667
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
668
-		}
669
-
670
-		if ($limit !== -1) {
671
-			$qb->setMaxResults($limit);
672
-		}
673
-
674
-		$qb->setFirstResult($offset);
675
-		$qb->orderBy('id');
676
-
677
-		$cursor = $qb->execute();
678
-		$shares = [];
679
-		while($data = $cursor->fetch()) {
680
-			$shares[] = $this->createShareObject($data);
681
-		}
682
-		$cursor->closeCursor();
683
-
684
-		return $shares;
685
-	}
686
-
687
-	/**
688
-	 * @inheritdoc
689
-	 */
690
-	public function getShareById($id, $recipientId = null) {
691
-		$qb = $this->dbConnection->getQueryBuilder();
692
-
693
-		$qb->select('*')
694
-			->from('share')
695
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
696
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
697
-
698
-		$cursor = $qb->execute();
699
-		$data = $cursor->fetch();
700
-		$cursor->closeCursor();
701
-
702
-		if ($data === false) {
703
-			throw new ShareNotFoundException('Can not find share with ID: ' . $id);
704
-		}
705
-
706
-		try {
707
-			$share = $this->createShareObject($data);
708
-		} catch (InvalidShare $e) {
709
-			throw new ShareNotFoundException();
710
-		}
711
-
712
-		return $share;
713
-	}
714
-
715
-	/**
716
-	 * Get shares for a given path
717
-	 *
718
-	 * @param \OCP\Files\Node $path
719
-	 * @return IShare[]
720
-	 */
721
-	public function getSharesByPath(Node $path) {
722
-		$qb = $this->dbConnection->getQueryBuilder();
723
-
724
-		$cursor = $qb->select('*')
725
-			->from('share')
726
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
727
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
728
-			->execute();
729
-
730
-		$shares = [];
731
-		while($data = $cursor->fetch()) {
732
-			$shares[] = $this->createShareObject($data);
733
-		}
734
-		$cursor->closeCursor();
735
-
736
-		return $shares;
737
-	}
738
-
739
-	/**
740
-	 * @inheritdoc
741
-	 */
742
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
743
-		/** @var IShare[] $shares */
744
-		$shares = [];
745
-
746
-		//Get shares directly with this user
747
-		$qb = $this->dbConnection->getQueryBuilder();
748
-		$qb->select('*')
749
-			->from('share');
750
-
751
-		// Order by id
752
-		$qb->orderBy('id');
753
-
754
-		// Set limit and offset
755
-		if ($limit !== -1) {
756
-			$qb->setMaxResults($limit);
757
-		}
758
-		$qb->setFirstResult($offset);
759
-
760
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
761
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
762
-
763
-		// Filter by node if provided
764
-		if ($node !== null) {
765
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
766
-		}
767
-
768
-		$cursor = $qb->execute();
769
-
770
-		while($data = $cursor->fetch()) {
771
-			$shares[] = $this->createShareObject($data);
772
-		}
773
-		$cursor->closeCursor();
774
-
775
-
776
-		return $shares;
777
-	}
778
-
779
-	/**
780
-	 * Get a share by token
781
-	 *
782
-	 * @param string $token
783
-	 * @return IShare
784
-	 * @throws ShareNotFound
785
-	 */
786
-	public function getShareByToken($token) {
787
-		$qb = $this->dbConnection->getQueryBuilder();
788
-
789
-		$cursor = $qb->select('*')
790
-			->from('share')
791
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
792
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
793
-			->execute();
794
-
795
-		$data = $cursor->fetch();
796
-
797
-		if ($data === false) {
798
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
799
-		}
800
-
801
-		try {
802
-			$share = $this->createShareObject($data);
803
-		} catch (InvalidShare $e) {
804
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
805
-		}
806
-
807
-		return $share;
808
-	}
809
-
810
-	/**
811
-	 * get database row of a give share
812
-	 *
813
-	 * @param $id
814
-	 * @return array
815
-	 * @throws ShareNotFound
816
-	 */
817
-	private function getRawShare($id) {
818
-
819
-		// Now fetch the inserted share and create a complete share object
820
-		$qb = $this->dbConnection->getQueryBuilder();
821
-		$qb->select('*')
822
-			->from('share')
823
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
824
-
825
-		$cursor = $qb->execute();
826
-		$data = $cursor->fetch();
827
-		$cursor->closeCursor();
828
-
829
-		if ($data === false) {
830
-			throw new ShareNotFound;
831
-		}
832
-
833
-		return $data;
834
-	}
835
-
836
-	/**
837
-	 * Create a share object from an database row
838
-	 *
839
-	 * @param array $data
840
-	 * @return IShare
841
-	 * @throws InvalidShare
842
-	 * @throws ShareNotFound
843
-	 */
844
-	private function createShareObject($data) {
845
-
846
-		$share = new Share($this->rootFolder, $this->userManager);
847
-		$share->setId((int)$data['id'])
848
-			->setShareType((int)$data['share_type'])
849
-			->setPermissions((int)$data['permissions'])
850
-			->setTarget($data['file_target'])
851
-			->setMailSend((bool)$data['mail_send'])
852
-			->setToken($data['token']);
853
-
854
-		$shareTime = new \DateTime();
855
-		$shareTime->setTimestamp((int)$data['stime']);
856
-		$share->setShareTime($shareTime);
857
-		$share->setSharedWith($data['share_with']);
858
-
859
-		if ($data['uid_initiator'] !== null) {
860
-			$share->setShareOwner($data['uid_owner']);
861
-			$share->setSharedBy($data['uid_initiator']);
862
-		} else {
863
-			//OLD SHARE
864
-			$share->setSharedBy($data['uid_owner']);
865
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
866
-
867
-			$owner = $path->getOwner();
868
-			$share->setShareOwner($owner->getUID());
869
-		}
870
-
871
-		$share->setNodeId((int)$data['file_source']);
872
-		$share->setNodeType($data['item_type']);
873
-
874
-		$share->setProviderId($this->identifier());
875
-
876
-		return $share;
877
-	}
878
-
879
-	/**
880
-	 * Get the node with file $id for $user
881
-	 *
882
-	 * @param string $userId
883
-	 * @param int $id
884
-	 * @return \OCP\Files\File|\OCP\Files\Folder
885
-	 * @throws InvalidShare
886
-	 */
887
-	private function getNode($userId, $id) {
888
-		try {
889
-			$userFolder = $this->rootFolder->getUserFolder($userId);
890
-		} catch (NotFoundException $e) {
891
-			throw new InvalidShare();
892
-		}
893
-
894
-		$nodes = $userFolder->getById($id);
895
-
896
-		if (empty($nodes)) {
897
-			throw new InvalidShare();
898
-		}
899
-
900
-		return $nodes[0];
901
-	}
902
-
903
-	/**
904
-	 * A user is deleted from the system
905
-	 * So clean up the relevant shares.
906
-	 *
907
-	 * @param string $uid
908
-	 * @param int $shareType
909
-	 */
910
-	public function userDeleted($uid, $shareType) {
911
-		//TODO: probabaly a good idea to send unshare info to remote servers
912
-
913
-		$qb = $this->dbConnection->getQueryBuilder();
914
-
915
-		$qb->delete('share')
916
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
917
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
918
-			->execute();
919
-	}
920
-
921
-	/**
922
-	 * This provider does not handle groups
923
-	 *
924
-	 * @param string $gid
925
-	 */
926
-	public function groupDeleted($gid) {
927
-		// We don't handle groups here
928
-	}
929
-
930
-	/**
931
-	 * This provider does not handle groups
932
-	 *
933
-	 * @param string $uid
934
-	 * @param string $gid
935
-	 */
936
-	public function userDeletedFromGroup($uid, $gid) {
937
-		// We don't handle groups here
938
-	}
939
-
940
-	/**
941
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
942
-	 *
943
-	 * @return bool
944
-	 */
945
-	public function isOutgoingServer2serverShareEnabled() {
946
-		if ($this->gsConfig->onlyInternalFederation()) {
947
-			return false;
948
-		}
949
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
950
-		return ($result === 'yes');
951
-	}
952
-
953
-	/**
954
-	 * check if users are allowed to mount public links from other Nextclouds
955
-	 *
956
-	 * @return bool
957
-	 */
958
-	public function isIncomingServer2serverShareEnabled() {
959
-		if ($this->gsConfig->onlyInternalFederation()) {
960
-			return false;
961
-		}
962
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
963
-		return ($result === 'yes');
964
-	}
965
-
966
-	/**
967
-	 * Check if querying sharees on the lookup server is enabled
968
-	 *
969
-	 * @return bool
970
-	 */
971
-	public function isLookupServerQueriesEnabled() {
972
-		// in a global scale setup we should always query the lookup server
973
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
974
-			return true;
975
-		}
976
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
977
-		return ($result === 'yes');
978
-	}
979
-
980
-
981
-	/**
982
-	 * Check if it is allowed to publish user specific data to the lookup server
983
-	 *
984
-	 * @return bool
985
-	 */
986
-	public function isLookupServerUploadEnabled() {
987
-		// in a global scale setup the admin is responsible to keep the lookup server up-to-date
988
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
989
-			return false;
990
-		}
991
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
992
-		return ($result === 'yes');
993
-	}
994
-
995
-	/**
996
-	 * @inheritdoc
997
-	 */
998
-	public function getAccessList($nodes, $currentAccess) {
999
-		$ids = [];
1000
-		foreach ($nodes as $node) {
1001
-			$ids[] = $node->getId();
1002
-		}
1003
-
1004
-		$qb = $this->dbConnection->getQueryBuilder();
1005
-		$qb->select('share_with', 'token', 'file_source')
1006
-			->from('share')
1007
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1008
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1009
-			->andWhere($qb->expr()->orX(
1010
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1011
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1012
-			));
1013
-		$cursor = $qb->execute();
1014
-
1015
-		if ($currentAccess === false) {
1016
-			$remote = $cursor->fetch() !== false;
1017
-			$cursor->closeCursor();
1018
-
1019
-			return ['remote' => $remote];
1020
-		}
1021
-
1022
-		$remote = [];
1023
-		while ($row = $cursor->fetch()) {
1024
-			$remote[$row['share_with']] = [
1025
-				'node_id' => $row['file_source'],
1026
-				'token' => $row['token'],
1027
-			];
1028
-		}
1029
-		$cursor->closeCursor();
1030
-
1031
-		return ['remote' => $remote];
1032
-	}
478
+        return $share;
479
+    }
480
+
481
+    /**
482
+     * Get all children of this share
483
+     *
484
+     * @param IShare $parent
485
+     * @return IShare[]
486
+     */
487
+    public function getChildren(IShare $parent) {
488
+        $children = [];
489
+
490
+        $qb = $this->dbConnection->getQueryBuilder();
491
+        $qb->select('*')
492
+            ->from('share')
493
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
494
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
495
+            ->orderBy('id');
496
+
497
+        $cursor = $qb->execute();
498
+        while($data = $cursor->fetch()) {
499
+            $children[] = $this->createShareObject($data);
500
+        }
501
+        $cursor->closeCursor();
502
+
503
+        return $children;
504
+    }
505
+
506
+    /**
507
+     * Delete a share (owner unShares the file)
508
+     *
509
+     * @param IShare $share
510
+     */
511
+    public function delete(IShare $share) {
512
+
513
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
514
+
515
+        $isOwner = false;
516
+
517
+        // if the local user is the owner we can send the unShare request directly...
518
+        if ($this->userManager->userExists($share->getShareOwner())) {
519
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
520
+            $this->revokeShare($share, true);
521
+        } else { // ... if not we need to correct ID for the unShare request
522
+            $remoteId = $this->getRemoteId($share);
523
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
524
+            $this->revokeShare($share, false);
525
+        }
526
+
527
+        // only remove the share when all messages are send to not lose information
528
+        // about the share to early
529
+        $this->removeShareFromTable($share);
530
+    }
531
+
532
+    /**
533
+     * in case of a re-share we need to send the other use (initiator or owner)
534
+     * a message that the file was unshared
535
+     *
536
+     * @param IShare $share
537
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
538
+     * @throws ShareNotFound
539
+     * @throws \OC\HintException
540
+     */
541
+    protected function revokeShare($share, $isOwner) {
542
+        // also send a unShare request to the initiator, if this is a different user than the owner
543
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
544
+            if ($isOwner) {
545
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
546
+            } else {
547
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
548
+            }
549
+            $remoteId = $this->getRemoteId($share);
550
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
551
+        }
552
+    }
553
+
554
+    /**
555
+     * remove share from table
556
+     *
557
+     * @param IShare $share
558
+     */
559
+    public function removeShareFromTable(IShare $share) {
560
+        $this->removeShareFromTableById($share->getId());
561
+    }
562
+
563
+    /**
564
+     * remove share from table
565
+     *
566
+     * @param string $shareId
567
+     */
568
+    private function removeShareFromTableById($shareId) {
569
+        $qb = $this->dbConnection->getQueryBuilder();
570
+        $qb->delete('share')
571
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
572
+        $qb->execute();
573
+
574
+        $qb->delete('federated_reshares')
575
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
576
+        $qb->execute();
577
+    }
578
+
579
+    /**
580
+     * @inheritdoc
581
+     */
582
+    public function deleteFromSelf(IShare $share, $recipient) {
583
+        // nothing to do here. Technically deleteFromSelf in the context of federated
584
+        // shares is a umount of a external storage. This is handled here
585
+        // apps/files_sharing/lib/external/manager.php
586
+        // TODO move this code over to this app
587
+    }
588
+
589
+
590
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
591
+        $qb = $this->dbConnection->getQueryBuilder();
592
+        $qb->select('*')
593
+            ->from('share', 's')
594
+            ->andWhere($qb->expr()->orX(
595
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
596
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
597
+            ))
598
+            ->andWhere(
599
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
600
+            );
601
+
602
+        /**
603
+         * Reshares for this user are shares where they are the owner.
604
+         */
605
+        if ($reshares === false) {
606
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
607
+        } else {
608
+            $qb->andWhere(
609
+                $qb->expr()->orX(
610
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
611
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
612
+                )
613
+            );
614
+        }
615
+
616
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
617
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
618
+
619
+        $qb->orderBy('id');
620
+
621
+        $cursor = $qb->execute();
622
+        $shares = [];
623
+        while ($data = $cursor->fetch()) {
624
+            $shares[$data['fileid']][] = $this->createShareObject($data);
625
+        }
626
+        $cursor->closeCursor();
627
+
628
+        return $shares;
629
+    }
630
+
631
+    /**
632
+     * @inheritdoc
633
+     */
634
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
635
+        $qb = $this->dbConnection->getQueryBuilder();
636
+        $qb->select('*')
637
+            ->from('share');
638
+
639
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
640
+
641
+        /**
642
+         * Reshares for this user are shares where they are the owner.
643
+         */
644
+        if ($reshares === false) {
645
+            //Special case for old shares created via the web UI
646
+            $or1 = $qb->expr()->andX(
647
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
648
+                $qb->expr()->isNull('uid_initiator')
649
+            );
650
+
651
+            $qb->andWhere(
652
+                $qb->expr()->orX(
653
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
654
+                    $or1
655
+                )
656
+            );
657
+        } else {
658
+            $qb->andWhere(
659
+                $qb->expr()->orX(
660
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
661
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
662
+                )
663
+            );
664
+        }
665
+
666
+        if ($node !== null) {
667
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
668
+        }
669
+
670
+        if ($limit !== -1) {
671
+            $qb->setMaxResults($limit);
672
+        }
673
+
674
+        $qb->setFirstResult($offset);
675
+        $qb->orderBy('id');
676
+
677
+        $cursor = $qb->execute();
678
+        $shares = [];
679
+        while($data = $cursor->fetch()) {
680
+            $shares[] = $this->createShareObject($data);
681
+        }
682
+        $cursor->closeCursor();
683
+
684
+        return $shares;
685
+    }
686
+
687
+    /**
688
+     * @inheritdoc
689
+     */
690
+    public function getShareById($id, $recipientId = null) {
691
+        $qb = $this->dbConnection->getQueryBuilder();
692
+
693
+        $qb->select('*')
694
+            ->from('share')
695
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
696
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
697
+
698
+        $cursor = $qb->execute();
699
+        $data = $cursor->fetch();
700
+        $cursor->closeCursor();
701
+
702
+        if ($data === false) {
703
+            throw new ShareNotFoundException('Can not find share with ID: ' . $id);
704
+        }
705
+
706
+        try {
707
+            $share = $this->createShareObject($data);
708
+        } catch (InvalidShare $e) {
709
+            throw new ShareNotFoundException();
710
+        }
711
+
712
+        return $share;
713
+    }
714
+
715
+    /**
716
+     * Get shares for a given path
717
+     *
718
+     * @param \OCP\Files\Node $path
719
+     * @return IShare[]
720
+     */
721
+    public function getSharesByPath(Node $path) {
722
+        $qb = $this->dbConnection->getQueryBuilder();
723
+
724
+        $cursor = $qb->select('*')
725
+            ->from('share')
726
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
727
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
728
+            ->execute();
729
+
730
+        $shares = [];
731
+        while($data = $cursor->fetch()) {
732
+            $shares[] = $this->createShareObject($data);
733
+        }
734
+        $cursor->closeCursor();
735
+
736
+        return $shares;
737
+    }
738
+
739
+    /**
740
+     * @inheritdoc
741
+     */
742
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
743
+        /** @var IShare[] $shares */
744
+        $shares = [];
745
+
746
+        //Get shares directly with this user
747
+        $qb = $this->dbConnection->getQueryBuilder();
748
+        $qb->select('*')
749
+            ->from('share');
750
+
751
+        // Order by id
752
+        $qb->orderBy('id');
753
+
754
+        // Set limit and offset
755
+        if ($limit !== -1) {
756
+            $qb->setMaxResults($limit);
757
+        }
758
+        $qb->setFirstResult($offset);
759
+
760
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
761
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
762
+
763
+        // Filter by node if provided
764
+        if ($node !== null) {
765
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
766
+        }
767
+
768
+        $cursor = $qb->execute();
769
+
770
+        while($data = $cursor->fetch()) {
771
+            $shares[] = $this->createShareObject($data);
772
+        }
773
+        $cursor->closeCursor();
774
+
775
+
776
+        return $shares;
777
+    }
778
+
779
+    /**
780
+     * Get a share by token
781
+     *
782
+     * @param string $token
783
+     * @return IShare
784
+     * @throws ShareNotFound
785
+     */
786
+    public function getShareByToken($token) {
787
+        $qb = $this->dbConnection->getQueryBuilder();
788
+
789
+        $cursor = $qb->select('*')
790
+            ->from('share')
791
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
792
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
793
+            ->execute();
794
+
795
+        $data = $cursor->fetch();
796
+
797
+        if ($data === false) {
798
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
799
+        }
800
+
801
+        try {
802
+            $share = $this->createShareObject($data);
803
+        } catch (InvalidShare $e) {
804
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
805
+        }
806
+
807
+        return $share;
808
+    }
809
+
810
+    /**
811
+     * get database row of a give share
812
+     *
813
+     * @param $id
814
+     * @return array
815
+     * @throws ShareNotFound
816
+     */
817
+    private function getRawShare($id) {
818
+
819
+        // Now fetch the inserted share and create a complete share object
820
+        $qb = $this->dbConnection->getQueryBuilder();
821
+        $qb->select('*')
822
+            ->from('share')
823
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
824
+
825
+        $cursor = $qb->execute();
826
+        $data = $cursor->fetch();
827
+        $cursor->closeCursor();
828
+
829
+        if ($data === false) {
830
+            throw new ShareNotFound;
831
+        }
832
+
833
+        return $data;
834
+    }
835
+
836
+    /**
837
+     * Create a share object from an database row
838
+     *
839
+     * @param array $data
840
+     * @return IShare
841
+     * @throws InvalidShare
842
+     * @throws ShareNotFound
843
+     */
844
+    private function createShareObject($data) {
845
+
846
+        $share = new Share($this->rootFolder, $this->userManager);
847
+        $share->setId((int)$data['id'])
848
+            ->setShareType((int)$data['share_type'])
849
+            ->setPermissions((int)$data['permissions'])
850
+            ->setTarget($data['file_target'])
851
+            ->setMailSend((bool)$data['mail_send'])
852
+            ->setToken($data['token']);
853
+
854
+        $shareTime = new \DateTime();
855
+        $shareTime->setTimestamp((int)$data['stime']);
856
+        $share->setShareTime($shareTime);
857
+        $share->setSharedWith($data['share_with']);
858
+
859
+        if ($data['uid_initiator'] !== null) {
860
+            $share->setShareOwner($data['uid_owner']);
861
+            $share->setSharedBy($data['uid_initiator']);
862
+        } else {
863
+            //OLD SHARE
864
+            $share->setSharedBy($data['uid_owner']);
865
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
866
+
867
+            $owner = $path->getOwner();
868
+            $share->setShareOwner($owner->getUID());
869
+        }
870
+
871
+        $share->setNodeId((int)$data['file_source']);
872
+        $share->setNodeType($data['item_type']);
873
+
874
+        $share->setProviderId($this->identifier());
875
+
876
+        return $share;
877
+    }
878
+
879
+    /**
880
+     * Get the node with file $id for $user
881
+     *
882
+     * @param string $userId
883
+     * @param int $id
884
+     * @return \OCP\Files\File|\OCP\Files\Folder
885
+     * @throws InvalidShare
886
+     */
887
+    private function getNode($userId, $id) {
888
+        try {
889
+            $userFolder = $this->rootFolder->getUserFolder($userId);
890
+        } catch (NotFoundException $e) {
891
+            throw new InvalidShare();
892
+        }
893
+
894
+        $nodes = $userFolder->getById($id);
895
+
896
+        if (empty($nodes)) {
897
+            throw new InvalidShare();
898
+        }
899
+
900
+        return $nodes[0];
901
+    }
902
+
903
+    /**
904
+     * A user is deleted from the system
905
+     * So clean up the relevant shares.
906
+     *
907
+     * @param string $uid
908
+     * @param int $shareType
909
+     */
910
+    public function userDeleted($uid, $shareType) {
911
+        //TODO: probabaly a good idea to send unshare info to remote servers
912
+
913
+        $qb = $this->dbConnection->getQueryBuilder();
914
+
915
+        $qb->delete('share')
916
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
917
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
918
+            ->execute();
919
+    }
920
+
921
+    /**
922
+     * This provider does not handle groups
923
+     *
924
+     * @param string $gid
925
+     */
926
+    public function groupDeleted($gid) {
927
+        // We don't handle groups here
928
+    }
929
+
930
+    /**
931
+     * This provider does not handle groups
932
+     *
933
+     * @param string $uid
934
+     * @param string $gid
935
+     */
936
+    public function userDeletedFromGroup($uid, $gid) {
937
+        // We don't handle groups here
938
+    }
939
+
940
+    /**
941
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
942
+     *
943
+     * @return bool
944
+     */
945
+    public function isOutgoingServer2serverShareEnabled() {
946
+        if ($this->gsConfig->onlyInternalFederation()) {
947
+            return false;
948
+        }
949
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
950
+        return ($result === 'yes');
951
+    }
952
+
953
+    /**
954
+     * check if users are allowed to mount public links from other Nextclouds
955
+     *
956
+     * @return bool
957
+     */
958
+    public function isIncomingServer2serverShareEnabled() {
959
+        if ($this->gsConfig->onlyInternalFederation()) {
960
+            return false;
961
+        }
962
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
963
+        return ($result === 'yes');
964
+    }
965
+
966
+    /**
967
+     * Check if querying sharees on the lookup server is enabled
968
+     *
969
+     * @return bool
970
+     */
971
+    public function isLookupServerQueriesEnabled() {
972
+        // in a global scale setup we should always query the lookup server
973
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
974
+            return true;
975
+        }
976
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
977
+        return ($result === 'yes');
978
+    }
979
+
980
+
981
+    /**
982
+     * Check if it is allowed to publish user specific data to the lookup server
983
+     *
984
+     * @return bool
985
+     */
986
+    public function isLookupServerUploadEnabled() {
987
+        // in a global scale setup the admin is responsible to keep the lookup server up-to-date
988
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
989
+            return false;
990
+        }
991
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
992
+        return ($result === 'yes');
993
+    }
994
+
995
+    /**
996
+     * @inheritdoc
997
+     */
998
+    public function getAccessList($nodes, $currentAccess) {
999
+        $ids = [];
1000
+        foreach ($nodes as $node) {
1001
+            $ids[] = $node->getId();
1002
+        }
1003
+
1004
+        $qb = $this->dbConnection->getQueryBuilder();
1005
+        $qb->select('share_with', 'token', 'file_source')
1006
+            ->from('share')
1007
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1008
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1009
+            ->andWhere($qb->expr()->orX(
1010
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1011
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1012
+            ));
1013
+        $cursor = $qb->execute();
1014
+
1015
+        if ($currentAccess === false) {
1016
+            $remote = $cursor->fetch() !== false;
1017
+            $cursor->closeCursor();
1018
+
1019
+            return ['remote' => $remote];
1020
+        }
1021
+
1022
+        $remote = [];
1023
+        while ($row = $cursor->fetch()) {
1024
+            $remote[$row['share_with']] = [
1025
+                'node_id' => $row['file_source'],
1026
+                'token' => $row['token'],
1027
+            ];
1028
+        }
1029
+        $cursor->closeCursor();
1030
+
1031
+        return ['remote' => $remote];
1032
+    }
1033 1033
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 1 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/Notifications.php 1 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.