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