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