Completed
Pull Request — master (#9345)
by Björn
26:01 queued 08:55
created
ocm-provider/index.php 2 patches
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -29,11 +29,11 @@
 block discarded – undo
29 29
 $isEnabled = $server->getAppManager()->isEnabledForUser('cloud_federation_api');
30 30
 
31 31
 if ($isEnabled) {
32
-	$capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
33
-	header('Content-Type: application/json');
34
-	echo json_encode($capabilities->getCapabilities()['ocm']);
32
+    $capabilities = new OCA\CloudFederationAPI\Capabilities($server->getURLGenerator());
33
+    header('Content-Type: application/json');
34
+    echo json_encode($capabilities->getCapabilities()['ocm']);
35 35
 } else {
36
-	header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
37
-	exit("501 Not Implemented");
36
+    header($_SERVER["SERVER_PROTOCOL"]." 501 Not Implemented", true, 501);
37
+    exit("501 Not Implemented");
38 38
 }
39 39
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@
 block discarded – undo
20 20
  */
21 21
 
22 22
 
23
-require_once __DIR__ . '/../lib/base.php';
23
+require_once __DIR__.'/../lib/base.php';
24 24
 
25 25
 header('Content-Type: application/json');
26 26
 
Please login to merge, or discard this patch.
apps/federatedfilesharing/composer/composer/autoload_static.php 1 patch
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -6,39 +6,39 @@
 block discarded – undo
6 6
 
7 7
 class ComposerStaticInitFederatedFileSharing
8 8
 {
9
-    public static $prefixLengthsPsr4 = array (
9
+    public static $prefixLengthsPsr4 = array(
10 10
         'O' => 
11
-        array (
11
+        array(
12 12
             'OCA\\FederatedFileSharing\\' => 25,
13 13
         ),
14 14
     );
15 15
 
16
-    public static $prefixDirsPsr4 = array (
16
+    public static $prefixDirsPsr4 = array(
17 17
         'OCA\\FederatedFileSharing\\' => 
18
-        array (
19
-            0 => __DIR__ . '/..' . '/../lib',
18
+        array(
19
+            0 => __DIR__.'/..'.'/../lib',
20 20
         ),
21 21
     );
22 22
 
23
-    public static $classMap = array (
24
-        'OCA\\FederatedFileSharing\\AddressHandler' => __DIR__ . '/..' . '/../lib/AddressHandler.php',
25
-        'OCA\\FederatedFileSharing\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
26
-        'OCA\\FederatedFileSharing\\BackgroundJob\\RetryJob' => __DIR__ . '/..' . '/../lib/BackgroundJob/RetryJob.php',
27
-        'OCA\\FederatedFileSharing\\Controller\\MountPublicLinkController' => __DIR__ . '/..' . '/../lib/Controller/MountPublicLinkController.php',
28
-        'OCA\\FederatedFileSharing\\Controller\\RequestHandlerController' => __DIR__ . '/..' . '/../lib/Controller/RequestHandlerController.php',
29
-        'OCA\\FederatedFileSharing\\FederatedShareProvider' => __DIR__ . '/..' . '/../lib/FederatedShareProvider.php',
30
-        'OCA\\FederatedFileSharing\\Notifications' => __DIR__ . '/..' . '/../lib/Notifications.php',
31
-        'OCA\\FederatedFileSharing\\Notifier' => __DIR__ . '/..' . '/../lib/Notifier.php',
32
-        'OCA\\FederatedFileSharing\\OCM\\CloudFederationProviderFiles' => __DIR__ . '/..' . '/../lib/ocm/CloudFederationProviderFiles.php',
33
-        'OCA\\FederatedFileSharing\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php',
34
-        'OCA\\FederatedFileSharing\\Settings\\Personal' => __DIR__ . '/..' . '/../lib/Settings/Personal.php',
35
-        'OCA\\FederatedFileSharing\\Settings\\PersonalSection' => __DIR__ . '/..' . '/../lib/Settings/PersonalSection.php',
36
-        'OCA\\FederatedFileSharing\\TokenHandler' => __DIR__ . '/..' . '/../lib/TokenHandler.php',
23
+    public static $classMap = array(
24
+        'OCA\\FederatedFileSharing\\AddressHandler' => __DIR__.'/..'.'/../lib/AddressHandler.php',
25
+        'OCA\\FederatedFileSharing\\AppInfo\\Application' => __DIR__.'/..'.'/../lib/AppInfo/Application.php',
26
+        'OCA\\FederatedFileSharing\\BackgroundJob\\RetryJob' => __DIR__.'/..'.'/../lib/BackgroundJob/RetryJob.php',
27
+        'OCA\\FederatedFileSharing\\Controller\\MountPublicLinkController' => __DIR__.'/..'.'/../lib/Controller/MountPublicLinkController.php',
28
+        'OCA\\FederatedFileSharing\\Controller\\RequestHandlerController' => __DIR__.'/..'.'/../lib/Controller/RequestHandlerController.php',
29
+        'OCA\\FederatedFileSharing\\FederatedShareProvider' => __DIR__.'/..'.'/../lib/FederatedShareProvider.php',
30
+        'OCA\\FederatedFileSharing\\Notifications' => __DIR__.'/..'.'/../lib/Notifications.php',
31
+        'OCA\\FederatedFileSharing\\Notifier' => __DIR__.'/..'.'/../lib/Notifier.php',
32
+        'OCA\\FederatedFileSharing\\OCM\\CloudFederationProviderFiles' => __DIR__.'/..'.'/../lib/ocm/CloudFederationProviderFiles.php',
33
+        'OCA\\FederatedFileSharing\\Settings\\Admin' => __DIR__.'/..'.'/../lib/Settings/Admin.php',
34
+        'OCA\\FederatedFileSharing\\Settings\\Personal' => __DIR__.'/..'.'/../lib/Settings/Personal.php',
35
+        'OCA\\FederatedFileSharing\\Settings\\PersonalSection' => __DIR__.'/..'.'/../lib/Settings/PersonalSection.php',
36
+        'OCA\\FederatedFileSharing\\TokenHandler' => __DIR__.'/..'.'/../lib/TokenHandler.php',
37 37
     );
38 38
 
39 39
     public static function getInitializer(ClassLoader $loader)
40 40
     {
41
-        return \Closure::bind(function () use ($loader) {
41
+        return \Closure::bind(function() use ($loader) {
42 42
             $loader->prefixLengthsPsr4 = ComposerStaticInitFederatedFileSharing::$prefixLengthsPsr4;
43 43
             $loader->prefixDirsPsr4 = ComposerStaticInitFederatedFileSharing::$prefixDirsPsr4;
44 44
             $loader->classMap = ComposerStaticInitFederatedFileSharing::$classMap;
Please login to merge, or discard this patch.
apps/federatedfilesharing/composer/composer/autoload_classmap.php 1 patch
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -6,17 +6,17 @@
 block discarded – undo
6 6
 $baseDir = $vendorDir;
7 7
 
8 8
 return array(
9
-    'OCA\\FederatedFileSharing\\AddressHandler' => $baseDir . '/../lib/AddressHandler.php',
10
-    'OCA\\FederatedFileSharing\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
11
-    'OCA\\FederatedFileSharing\\BackgroundJob\\RetryJob' => $baseDir . '/../lib/BackgroundJob/RetryJob.php',
12
-    'OCA\\FederatedFileSharing\\Controller\\MountPublicLinkController' => $baseDir . '/../lib/Controller/MountPublicLinkController.php',
13
-    'OCA\\FederatedFileSharing\\Controller\\RequestHandlerController' => $baseDir . '/../lib/Controller/RequestHandlerController.php',
14
-    'OCA\\FederatedFileSharing\\FederatedShareProvider' => $baseDir . '/../lib/FederatedShareProvider.php',
15
-    'OCA\\FederatedFileSharing\\Notifications' => $baseDir . '/../lib/Notifications.php',
16
-    'OCA\\FederatedFileSharing\\Notifier' => $baseDir . '/../lib/Notifier.php',
17
-    'OCA\\FederatedFileSharing\\OCM\\CloudFederationProviderFiles' => $baseDir . '/../lib/ocm/CloudFederationProviderFiles.php',
18
-    'OCA\\FederatedFileSharing\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php',
19
-    'OCA\\FederatedFileSharing\\Settings\\Personal' => $baseDir . '/../lib/Settings/Personal.php',
20
-    'OCA\\FederatedFileSharing\\Settings\\PersonalSection' => $baseDir . '/../lib/Settings/PersonalSection.php',
21
-    'OCA\\FederatedFileSharing\\TokenHandler' => $baseDir . '/../lib/TokenHandler.php',
9
+    'OCA\\FederatedFileSharing\\AddressHandler' => $baseDir.'/../lib/AddressHandler.php',
10
+    'OCA\\FederatedFileSharing\\AppInfo\\Application' => $baseDir.'/../lib/AppInfo/Application.php',
11
+    'OCA\\FederatedFileSharing\\BackgroundJob\\RetryJob' => $baseDir.'/../lib/BackgroundJob/RetryJob.php',
12
+    'OCA\\FederatedFileSharing\\Controller\\MountPublicLinkController' => $baseDir.'/../lib/Controller/MountPublicLinkController.php',
13
+    'OCA\\FederatedFileSharing\\Controller\\RequestHandlerController' => $baseDir.'/../lib/Controller/RequestHandlerController.php',
14
+    'OCA\\FederatedFileSharing\\FederatedShareProvider' => $baseDir.'/../lib/FederatedShareProvider.php',
15
+    'OCA\\FederatedFileSharing\\Notifications' => $baseDir.'/../lib/Notifications.php',
16
+    'OCA\\FederatedFileSharing\\Notifier' => $baseDir.'/../lib/Notifier.php',
17
+    'OCA\\FederatedFileSharing\\OCM\\CloudFederationProviderFiles' => $baseDir.'/../lib/ocm/CloudFederationProviderFiles.php',
18
+    'OCA\\FederatedFileSharing\\Settings\\Admin' => $baseDir.'/../lib/Settings/Admin.php',
19
+    'OCA\\FederatedFileSharing\\Settings\\Personal' => $baseDir.'/../lib/Settings/Personal.php',
20
+    'OCA\\FederatedFileSharing\\Settings\\PersonalSection' => $baseDir.'/../lib/Settings/PersonalSection.php',
21
+    'OCA\\FederatedFileSharing\\TokenHandler' => $baseDir.'/../lib/TokenHandler.php',
22 22
 );
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -165,16 +165,16 @@  discard block
 block discarded – undo
165 165
 			}
166 166
 
167 167
 			// FIXME this should be a method in the user management instead
168
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
168
+			$this->logger->debug('shareWith before, '.$shareWith, ['app' => 'files_sharing']);
169 169
 			\OCP\Util::emitHook(
170 170
 				'\OCA\Files_Sharing\API\Server2Server',
171 171
 				'preLoginNameUsedAsUserName',
172 172
 				array('uid' => &$shareWith)
173 173
 			);
174
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
174
+			$this->logger->debug('shareWith after, '.$shareWith, ['app' => 'files_sharing']);
175 175
 
176 176
 			if (!$this->userManager->userExists($shareWith)) {
177
-				throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
177
+				throw new ProviderCouldNotAddShareException('User does not exists', '', Http::STATUS_BAD_REQUEST);
178 178
 			}
179 179
 
180 180
 			\OC_Util::setupFS($shareWith);
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 					->setType('remote_share')
199 199
 					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
200 200
 					->setAffectedUser($shareWith)
201
-					->setObject('remote_share', (int)$shareId, $name);
201
+					->setObject('remote_share', (int) $shareId, $name);
202 202
 				\OC::$server->getActivityManager()->publish($event);
203 203
 
204 204
 				$notification = $this->notificationManager->createNotification();
@@ -210,12 +210,12 @@  discard block
 block discarded – undo
210 210
 
211 211
 				$declineAction = $notification->createAction();
212 212
 				$declineAction->setLabel('decline')
213
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
213
+					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
214 214
 				$notification->addAction($declineAction);
215 215
 
216 216
 				$acceptAction = $notification->createAction();
217 217
 				$acceptAction->setLabel('accept')
218
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
218
+					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
219 219
 				$notification->addAction($acceptAction);
220 220
 
221 221
 				$this->notificationManager->notify($notification);
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 					'level' => \OCP\Util::ERROR,
228 228
 					'app' => 'files_sharing'
229 229
 				]);
230
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
230
+				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from '.$remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
231 231
 			}
232 232
 		}
233 233
 
Please login to merge, or discard this patch.
Indentation   +229 added lines, -229 removed lines patch added patch discarded remove patch
@@ -40,235 +40,235 @@
 block discarded – undo
40 40
 
41 41
 class CloudFederationProviderFiles implements ICloudFederationProvider {
42 42
 
43
-	/** @var IAppManager */
44
-	private $appManager;
45
-
46
-	/** @var FederatedShareProvider */
47
-	private $federatedShareProvider;
48
-
49
-	/** @var AddressHandler */
50
-	private $addressHandler;
51
-
52
-	/** @var ILogger */
53
-	private $logger;
54
-
55
-	/** @var IUserManager */
56
-	private $userManager;
57
-
58
-	/** @var ICloudIdManager */
59
-	private $cloudIdManager;
60
-
61
-	/** @var IActivityManager */
62
-	private $activityManager;
63
-
64
-	/** @var INotificationManager */
65
-	private $notificationManager;
66
-
67
-	/** @var IURLGenerator */
68
-	private $urlGenerator;
69
-
70
-	/**
71
-	 * CloudFederationProvider constructor.
72
-	 *
73
-	 * @param IAppManager $appManager
74
-	 * @param FederatedShareProvider $federatedShareProvider
75
-	 * @param AddressHandler $addressHandler
76
-	 * @param ILogger $logger
77
-	 * @param IUserManager $userManager
78
-	 * @param ICloudIdManager $cloudIdManager
79
-	 * @param IActivityManager $activityManager
80
-	 * @param INotificationManager $notificationManager
81
-	 * @param IURLGenerator $urlGenerator
82
-	 */
83
-	public function __construct(IAppManager $appManager,
84
-								FederatedShareProvider $federatedShareProvider,
85
-								AddressHandler $addressHandler,
86
-								ILogger $logger,
87
-								IUserManager $userManager,
88
-								ICloudIdManager $cloudIdManager,
89
-								IActivityManager $activityManager,
90
-								INotificationManager $notificationManager,
91
-								IURLGenerator $urlGenerator
92
-	) {
93
-		$this->appManager = $appManager;
94
-		$this->federatedShareProvider = $federatedShareProvider;
95
-		$this->addressHandler = $addressHandler;
96
-		$this->logger = $logger;
97
-		$this->userManager = $userManager;
98
-		$this->cloudIdManager = $cloudIdManager;
99
-		$this->activityManager = $activityManager;
100
-		$this->notificationManager = $notificationManager;
101
-		$this->urlGenerator = $urlGenerator;
102
-	}
103
-
104
-
105
-
106
-	/**
107
-	 * @return string
108
-	 */
109
-	public function getShareType() {
110
-		return 'file';
111
-	}
112
-
113
-	/**
114
-	 * share received from another server
115
-	 *
116
-	 * @param ICloudFederationShare $share
117
-	 * @return string provider specific unique ID of the share
118
-	 *
119
-	 * @throws ProviderCouldNotAddShareException
120
-	 * @throws \OCP\AppFramework\QueryException
121
-	 * @throws \OC\HintException
122
-	 * @since 14.0.0
123
-	 */
124
-	public function shareReceived(ICloudFederationShare $share) {
125
-
126
-		if (!$this->isS2SEnabled(true)) {
127
-			throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
128
-		}
129
-
130
-		$protocol = $share->getProtocol();
131
-		if ($protocol['name'] !== 'webdav') {
132
-			throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
133
-		}
134
-
135
-		list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
136
-
137
-		$remote = $remote;
138
-		$token = isset($protocol['options']['access_token']) ? $protocol['options']['access_token'] : null;
139
-		$name = $share->getResourceName();
140
-		$owner = $share->getOwnerDisplayName();
141
-		$sharedBy = $share->getSharedByDisplayName();
142
-		$shareWith = $share->getShareWith();
143
-		$remoteId = $share->getProviderId();
144
-		$sharedByFederatedId = $share->getSharedBy();
145
-		$ownerFederatedId = $share->getOwner();
146
-
147
-		// if no explicit information about the person who created the share was send
148
-		// we assume that the share comes from the owner
149
-		if ($sharedByFederatedId === null) {
150
-			$sharedBy = $owner;
151
-			$sharedByFederatedId = $ownerFederatedId;
152
-		}
153
-
154
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
155
-
156
-			if (!\OCP\Util::isValidFileName($name)) {
157
-				throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
158
-			}
159
-
160
-			// FIXME this should be a method in the user management instead
161
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
162
-			\OCP\Util::emitHook(
163
-				'\OCA\Files_Sharing\API\Server2Server',
164
-				'preLoginNameUsedAsUserName',
165
-				array('uid' => &$shareWith)
166
-			);
167
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
168
-
169
-			if (!$this->userManager->userExists($shareWith)) {
170
-				throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
171
-			}
172
-
173
-			\OC_Util::setupFS($shareWith);
174
-
175
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
176
-				\OC::$server->getDatabaseConnection(),
177
-				\OC\Files\Filesystem::getMountManager(),
178
-				\OC\Files\Filesystem::getLoader(),
179
-				\OC::$server->getHTTPClientService(),
180
-				\OC::$server->getNotificationManager(),
181
-				\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
182
-				\OC::$server->getCloudFederationProviderManager(),
183
-				\OC::$server->getCloudFederationFactory(),
184
-				$shareWith
185
-			);
186
-
187
-			try {
188
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
189
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
190
-
191
-				$event = $this->activityManager->generateEvent();
192
-				$event->setApp('files_sharing')
193
-					->setType('remote_share')
194
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
195
-					->setAffectedUser($shareWith)
196
-					->setObject('remote_share', (int)$shareId, $name);
197
-				\OC::$server->getActivityManager()->publish($event);
198
-
199
-				$notification = $this->notificationManager->createNotification();
200
-				$notification->setApp('files_sharing')
201
-					->setUser($shareWith)
202
-					->setDateTime(new \DateTime())
203
-					->setObject('remote_share', $shareId)
204
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
205
-
206
-				$declineAction = $notification->createAction();
207
-				$declineAction->setLabel('decline')
208
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
209
-				$notification->addAction($declineAction);
210
-
211
-				$acceptAction = $notification->createAction();
212
-				$acceptAction->setLabel('accept')
213
-					->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
214
-				$notification->addAction($acceptAction);
215
-
216
-				$this->notificationManager->notify($notification);
217
-
218
-				return $shareId;
219
-			} catch (\Exception $e) {
220
-				$this->logger->logException($e, [
221
-					'message' => 'Server can not add remote share.',
222
-					'level' => \OCP\Util::ERROR,
223
-					'app' => 'files_sharing'
224
-				]);
225
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
226
-			}
227
-		}
228
-
229
-		throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
230
-
231
-	}
232
-
233
-	/**
234
-	 * notification received from another server
235
-	 *
236
-	 * @param string $notificationType (e.g. SHARE_ACCEPTED)
237
-	 * @param array $message
238
-	 *
239
-	 * @throws ShareNotFoundException
240
-	 * @throws ActionNotSupportedException
241
-	 *
242
-	 * @since 14.0.0
243
-	 */
244
-	public function notificationReceived($notificationType, array $message) {
245
-		switch ($notificationType) {
246
-			case 'SHARE_ACCEPTED' :
247
-				return;
248
-		}
249
-
250
-
251
-		throw new ActionNotSupportedException($notificationType);
252
-	}
253
-
254
-	/**
255
-	 * check if server-to-server sharing is enabled
256
-	 *
257
-	 * @param bool $incoming
258
-	 * @return bool
259
-	 */
260
-	private function isS2SEnabled($incoming = false) {
261
-
262
-		$result = $this->appManager->isEnabledForUser('files_sharing');
263
-
264
-		if ($incoming) {
265
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
266
-		} else {
267
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
268
-		}
269
-
270
-		return $result;
271
-	}
43
+    /** @var IAppManager */
44
+    private $appManager;
45
+
46
+    /** @var FederatedShareProvider */
47
+    private $federatedShareProvider;
48
+
49
+    /** @var AddressHandler */
50
+    private $addressHandler;
51
+
52
+    /** @var ILogger */
53
+    private $logger;
54
+
55
+    /** @var IUserManager */
56
+    private $userManager;
57
+
58
+    /** @var ICloudIdManager */
59
+    private $cloudIdManager;
60
+
61
+    /** @var IActivityManager */
62
+    private $activityManager;
63
+
64
+    /** @var INotificationManager */
65
+    private $notificationManager;
66
+
67
+    /** @var IURLGenerator */
68
+    private $urlGenerator;
69
+
70
+    /**
71
+     * CloudFederationProvider constructor.
72
+     *
73
+     * @param IAppManager $appManager
74
+     * @param FederatedShareProvider $federatedShareProvider
75
+     * @param AddressHandler $addressHandler
76
+     * @param ILogger $logger
77
+     * @param IUserManager $userManager
78
+     * @param ICloudIdManager $cloudIdManager
79
+     * @param IActivityManager $activityManager
80
+     * @param INotificationManager $notificationManager
81
+     * @param IURLGenerator $urlGenerator
82
+     */
83
+    public function __construct(IAppManager $appManager,
84
+                                FederatedShareProvider $federatedShareProvider,
85
+                                AddressHandler $addressHandler,
86
+                                ILogger $logger,
87
+                                IUserManager $userManager,
88
+                                ICloudIdManager $cloudIdManager,
89
+                                IActivityManager $activityManager,
90
+                                INotificationManager $notificationManager,
91
+                                IURLGenerator $urlGenerator
92
+    ) {
93
+        $this->appManager = $appManager;
94
+        $this->federatedShareProvider = $federatedShareProvider;
95
+        $this->addressHandler = $addressHandler;
96
+        $this->logger = $logger;
97
+        $this->userManager = $userManager;
98
+        $this->cloudIdManager = $cloudIdManager;
99
+        $this->activityManager = $activityManager;
100
+        $this->notificationManager = $notificationManager;
101
+        $this->urlGenerator = $urlGenerator;
102
+    }
103
+
104
+
105
+
106
+    /**
107
+     * @return string
108
+     */
109
+    public function getShareType() {
110
+        return 'file';
111
+    }
112
+
113
+    /**
114
+     * share received from another server
115
+     *
116
+     * @param ICloudFederationShare $share
117
+     * @return string provider specific unique ID of the share
118
+     *
119
+     * @throws ProviderCouldNotAddShareException
120
+     * @throws \OCP\AppFramework\QueryException
121
+     * @throws \OC\HintException
122
+     * @since 14.0.0
123
+     */
124
+    public function shareReceived(ICloudFederationShare $share) {
125
+
126
+        if (!$this->isS2SEnabled(true)) {
127
+            throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
128
+        }
129
+
130
+        $protocol = $share->getProtocol();
131
+        if ($protocol['name'] !== 'webdav') {
132
+            throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
133
+        }
134
+
135
+        list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
136
+
137
+        $remote = $remote;
138
+        $token = isset($protocol['options']['access_token']) ? $protocol['options']['access_token'] : null;
139
+        $name = $share->getResourceName();
140
+        $owner = $share->getOwnerDisplayName();
141
+        $sharedBy = $share->getSharedByDisplayName();
142
+        $shareWith = $share->getShareWith();
143
+        $remoteId = $share->getProviderId();
144
+        $sharedByFederatedId = $share->getSharedBy();
145
+        $ownerFederatedId = $share->getOwner();
146
+
147
+        // if no explicit information about the person who created the share was send
148
+        // we assume that the share comes from the owner
149
+        if ($sharedByFederatedId === null) {
150
+            $sharedBy = $owner;
151
+            $sharedByFederatedId = $ownerFederatedId;
152
+        }
153
+
154
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
155
+
156
+            if (!\OCP\Util::isValidFileName($name)) {
157
+                throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
158
+            }
159
+
160
+            // FIXME this should be a method in the user management instead
161
+            $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
162
+            \OCP\Util::emitHook(
163
+                '\OCA\Files_Sharing\API\Server2Server',
164
+                'preLoginNameUsedAsUserName',
165
+                array('uid' => &$shareWith)
166
+            );
167
+            $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
168
+
169
+            if (!$this->userManager->userExists($shareWith)) {
170
+                throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
171
+            }
172
+
173
+            \OC_Util::setupFS($shareWith);
174
+
175
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
176
+                \OC::$server->getDatabaseConnection(),
177
+                \OC\Files\Filesystem::getMountManager(),
178
+                \OC\Files\Filesystem::getLoader(),
179
+                \OC::$server->getHTTPClientService(),
180
+                \OC::$server->getNotificationManager(),
181
+                \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
182
+                \OC::$server->getCloudFederationProviderManager(),
183
+                \OC::$server->getCloudFederationFactory(),
184
+                $shareWith
185
+            );
186
+
187
+            try {
188
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
189
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
190
+
191
+                $event = $this->activityManager->generateEvent();
192
+                $event->setApp('files_sharing')
193
+                    ->setType('remote_share')
194
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
195
+                    ->setAffectedUser($shareWith)
196
+                    ->setObject('remote_share', (int)$shareId, $name);
197
+                \OC::$server->getActivityManager()->publish($event);
198
+
199
+                $notification = $this->notificationManager->createNotification();
200
+                $notification->setApp('files_sharing')
201
+                    ->setUser($shareWith)
202
+                    ->setDateTime(new \DateTime())
203
+                    ->setObject('remote_share', $shareId)
204
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
205
+
206
+                $declineAction = $notification->createAction();
207
+                $declineAction->setLabel('decline')
208
+                    ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
209
+                $notification->addAction($declineAction);
210
+
211
+                $acceptAction = $notification->createAction();
212
+                $acceptAction->setLabel('accept')
213
+                    ->setLink($this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
214
+                $notification->addAction($acceptAction);
215
+
216
+                $this->notificationManager->notify($notification);
217
+
218
+                return $shareId;
219
+            } catch (\Exception $e) {
220
+                $this->logger->logException($e, [
221
+                    'message' => 'Server can not add remote share.',
222
+                    'level' => \OCP\Util::ERROR,
223
+                    'app' => 'files_sharing'
224
+                ]);
225
+                throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
226
+            }
227
+        }
228
+
229
+        throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
230
+
231
+    }
232
+
233
+    /**
234
+     * notification received from another server
235
+     *
236
+     * @param string $notificationType (e.g. SHARE_ACCEPTED)
237
+     * @param array $message
238
+     *
239
+     * @throws ShareNotFoundException
240
+     * @throws ActionNotSupportedException
241
+     *
242
+     * @since 14.0.0
243
+     */
244
+    public function notificationReceived($notificationType, array $message) {
245
+        switch ($notificationType) {
246
+            case 'SHARE_ACCEPTED' :
247
+                return;
248
+        }
249
+
250
+
251
+        throw new ActionNotSupportedException($notificationType);
252
+    }
253
+
254
+    /**
255
+     * check if server-to-server sharing is enabled
256
+     *
257
+     * @param bool $incoming
258
+     * @return bool
259
+     */
260
+    private function isS2SEnabled($incoming = false) {
261
+
262
+        $result = $this->appManager->isEnabledForUser('files_sharing');
263
+
264
+        if ($incoming) {
265
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
266
+        } else {
267
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
268
+        }
269
+
270
+        return $result;
271
+    }
272 272
 
273 273
 
274 274
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 2 patches
Indentation   +593 added lines, -593 removed lines patch added patch discarded remove patch
@@ -55,597 +55,597 @@
 block discarded – undo
55 55
 
56 56
 class RequestHandlerController extends OCSController {
57 57
 
58
-	/** @var FederatedShareProvider */
59
-	private $federatedShareProvider;
60
-
61
-	/** @var IDBConnection */
62
-	private $connection;
63
-
64
-	/** @var Share\IManager */
65
-	private $shareManager;
66
-
67
-	/** @var Notifications */
68
-	private $notifications;
69
-
70
-	/** @var AddressHandler */
71
-	private $addressHandler;
72
-
73
-	/** @var  IUserManager */
74
-	private $userManager;
75
-
76
-	/** @var string */
77
-	private $shareTable = 'share';
78
-
79
-	/** @var ICloudIdManager */
80
-	private $cloudIdManager;
81
-
82
-	/** @var ILogger */
83
-	private $logger;
84
-
85
-	/** @var ICloudFederationFactory */
86
-	private $cloudFederationFactory;
87
-
88
-	/** @var ICloudFederationProviderManager */
89
-	private $cloudFederationProviderManager;
90
-
91
-	/**
92
-	 * Server2Server constructor.
93
-	 *
94
-	 * @param string $appName
95
-	 * @param IRequest $request
96
-	 * @param FederatedShareProvider $federatedShareProvider
97
-	 * @param IDBConnection $connection
98
-	 * @param Share\IManager $shareManager
99
-	 * @param Notifications $notifications
100
-	 * @param AddressHandler $addressHandler
101
-	 * @param IUserManager $userManager
102
-	 * @param ICloudIdManager $cloudIdManager
103
-	 * @param ILogger $logger
104
-	 * @param ICloudFederationFactory $cloudFederationFactory
105
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
106
-	 */
107
-	public function __construct($appName,
108
-								IRequest $request,
109
-								FederatedShareProvider $federatedShareProvider,
110
-								IDBConnection $connection,
111
-								Share\IManager $shareManager,
112
-								Notifications $notifications,
113
-								AddressHandler $addressHandler,
114
-								IUserManager $userManager,
115
-								ICloudIdManager $cloudIdManager,
116
-								ILogger $logger,
117
-								ICloudFederationFactory $cloudFederationFactory,
118
-								ICloudFederationProviderManager $cloudFederationProviderManager
119
-	) {
120
-		parent::__construct($appName, $request);
121
-
122
-		$this->federatedShareProvider = $federatedShareProvider;
123
-		$this->connection = $connection;
124
-		$this->shareManager = $shareManager;
125
-		$this->notifications = $notifications;
126
-		$this->addressHandler = $addressHandler;
127
-		$this->userManager = $userManager;
128
-		$this->cloudIdManager = $cloudIdManager;
129
-		$this->logger = $logger;
130
-		$this->cloudFederationFactory = $cloudFederationFactory;
131
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
132
-	}
133
-
134
-	/**
135
-	 * @NoCSRFRequired
136
-	 * @PublicPage
137
-	 *
138
-	 * create a new share
139
-	 *
140
-	 * @return Http\DataResponse
141
-	 * @throws OCSException
142
-	 */
143
-	public function createShare() {
144
-
145
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
146
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
147
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
148
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
149
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
150
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
151
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
152
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
153
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
154
-
155
-		if ($ownerFederatedId === null) {
156
-			$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
157
-		}
158
-		// if the owner of the share and the initiator are the same user
159
-		// we also complete the federated share ID for the initiator
160
-		if ($sharedByFederatedId === null && $owner === $sharedBy) {
161
-			$sharedByFederatedId = $ownerFederatedId;
162
-		}
163
-
164
-		$share = $this->cloudFederationFactory->getCloudFederationShare(
165
-			$shareWith,
166
-			$name,
167
-			'',
168
-			$remoteId,
169
-			$ownerFederatedId,
170
-			$owner,
171
-			$sharedByFederatedId,
172
-			$sharedBy,
173
-			['name' => 'webdav', 'options' => ['access_token' => $token]],
174
-			'user',
175
-			'file'
176
-		);
177
-
178
-		try {
179
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
180
-			$provider->shareReceived($share);
181
-		} catch (ProviderDoesNotExistsException $e) {
182
-			throw new OCSException('Server does not support federated cloud sharing', 503);
183
-		} catch (ProviderCouldNotAddShareException $e) {
184
-			throw new OCSException($e->getMessage(), $e->getCode());
185
-		} catch (\Exception $e) {
186
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
187
-		}
188
-
189
-		return new Http\DataResponse();
190
-	}
191
-
192
-	/**
193
-	 * @NoCSRFRequired
194
-	 * @PublicPage
195
-	 *
196
-	 * create re-share on behalf of another user
197
-	 *
198
-	 * @param int $id
199
-	 * @return Http\DataResponse
200
-	 * @throws OCSBadRequestException
201
-	 * @throws OCSForbiddenException
202
-	 * @throws OCSNotFoundException
203
-	 */
204
-	public function reShare($id) {
205
-
206
-		$token = $this->request->getParam('token', null);
207
-		$shareWith = $this->request->getParam('shareWith', null);
208
-		$permission = (int)$this->request->getParam('permission', null);
209
-		$remoteId = (int)$this->request->getParam('remoteId', null);
210
-
211
-		if ($id === null ||
212
-			$token === null ||
213
-			$shareWith === null ||
214
-			$permission === null ||
215
-			$remoteId === null
216
-		) {
217
-			throw new OCSBadRequestException();
218
-		}
219
-
220
-		try {
221
-			$share = $this->federatedShareProvider->getShareById($id);
222
-		} catch (Share\Exceptions\ShareNotFound $e) {
223
-			throw new OCSNotFoundException();
224
-		}
225
-
226
-		// don't allow to share a file back to the owner
227
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
228
-		$owner = $share->getShareOwner();
229
-		$currentServer = $this->addressHandler->generateRemoteURL();
230
-		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
231
-			throw new OCSForbiddenException();
232
-		}
233
-
234
-		if ($this->verifyShare($share, $token)) {
235
-
236
-			// check if re-sharing is allowed
237
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
238
-				$share->setPermissions($share->getPermissions() & $permission);
239
-				// the recipient of the initial share is now the initiator for the re-share
240
-				$share->setSharedBy($share->getSharedWith());
241
-				$share->setSharedWith($shareWith);
242
-				try {
243
-					$result = $this->federatedShareProvider->create($share);
244
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
245
-					return new Http\DataResponse([
246
-						'token' => $result->getToken(),
247
-						'remoteId' => $result->getId()
248
-					]);
249
-				} catch (\Exception $e) {
250
-					throw new OCSBadRequestException();
251
-				}
252
-			} else {
253
-				throw new OCSForbiddenException();
254
-			}
255
-		}
256
-		throw new OCSBadRequestException();
257
-	}
258
-
259
-	/**
260
-	 * @NoCSRFRequired
261
-	 * @PublicPage
262
-	 *
263
-	 * accept server-to-server share
264
-	 *
265
-	 * @param int $id
266
-	 * @return Http\DataResponse
267
-	 * @throws OCSException
268
-	 */
269
-	public function acceptShare($id) {
270
-
271
-		if (!$this->isS2SEnabled()) {
272
-			throw new OCSException('Server does not support federated cloud sharing', 503);
273
-		}
274
-
275
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
276
-
277
-		try {
278
-			$share = $this->federatedShareProvider->getShareById($id);
279
-		} catch (Share\Exceptions\ShareNotFound $e) {
280
-			return new Http\DataResponse();
281
-		}
282
-
283
-		if ($this->verifyShare($share, $token)) {
284
-			$this->executeAcceptShare($share);
285
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
286
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
287
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
288
-				$this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
289
-			}
290
-		}
291
-
292
-		return new Http\DataResponse();
293
-	}
294
-
295
-	protected function executeAcceptShare(Share\IShare $share) {
296
-		$fileId = (int) $share->getNode()->getId();
297
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
298
-
299
-		$event = \OC::$server->getActivityManager()->generateEvent();
300
-		$event->setApp('files_sharing')
301
-			->setType('remote_share')
302
-			->setAffectedUser($this->getCorrectUid($share))
303
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
304
-			->setObject('files', $fileId, $file)
305
-			->setLink($link);
306
-		\OC::$server->getActivityManager()->publish($event);
307
-	}
308
-
309
-	/**
310
-	 * @NoCSRFRequired
311
-	 * @PublicPage
312
-	 *
313
-	 * decline server-to-server share
314
-	 *
315
-	 * @param int $id
316
-	 * @return Http\DataResponse
317
-	 * @throws OCSException
318
-	 */
319
-	public function declineShare($id) {
320
-
321
-		if (!$this->isS2SEnabled()) {
322
-			throw new OCSException('Server does not support federated cloud sharing', 503);
323
-		}
324
-
325
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
326
-
327
-		try {
328
-			$share = $this->federatedShareProvider->getShareById($id);
329
-		} catch (Share\Exceptions\ShareNotFound $e) {
330
-			return new Http\DataResponse();
331
-		}
332
-
333
-		if ($this->verifyShare($share, $token)) {
334
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
335
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
336
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
337
-				$this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
338
-			}
339
-			$this->executeDeclineShare($share);
340
-		}
341
-
342
-		return new Http\DataResponse();
343
-	}
344
-
345
-	/**
346
-	 * delete declined share and create a activity
347
-	 *
348
-	 * @param Share\IShare $share
349
-	 */
350
-	protected function executeDeclineShare(Share\IShare $share) {
351
-		$this->federatedShareProvider->removeShareFromTable($share);
352
-		$fileId = (int) $share->getNode()->getId();
353
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
354
-
355
-		$event = \OC::$server->getActivityManager()->generateEvent();
356
-		$event->setApp('files_sharing')
357
-			->setType('remote_share')
358
-			->setAffectedUser($this->getCorrectUid($share))
359
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
360
-			->setObject('files', $fileId, $file)
361
-			->setLink($link);
362
-		\OC::$server->getActivityManager()->publish($event);
363
-
364
-	}
365
-
366
-	/**
367
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
368
-	 *
369
-	 * @param Share\IShare $share
370
-	 * @return string
371
-	 */
372
-	protected function getCorrectUid(Share\IShare $share) {
373
-		if ($this->userManager->userExists($share->getShareOwner())) {
374
-			return $share->getShareOwner();
375
-		}
376
-
377
-		return $share->getSharedBy();
378
-	}
379
-
380
-	/**
381
-	 * @NoCSRFRequired
382
-	 * @PublicPage
383
-	 *
384
-	 * remove server-to-server share if it was unshared by the owner
385
-	 *
386
-	 * @param int $id
387
-	 * @return Http\DataResponse
388
-	 * @throws OCSException
389
-	 */
390
-	public function unshare($id) {
391
-
392
-		if (!$this->isS2SEnabled()) {
393
-			throw new OCSException('Server does not support federated cloud sharing', 503);
394
-		}
395
-
396
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
397
-
398
-		$qb = $this->connection->getQueryBuilder();
399
-		$qb->select('*')
400
-			->from('share_external')
401
-			->where(
402
-				$qb->expr()->andX(
403
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
404
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
405
-				)
406
-			);
407
-
408
-		$result = $qb->execute();
409
-		$share = $result->fetch();
410
-		$result->closeCursor();
411
-
412
-		if ($token && $id && !empty($share)) {
413
-
414
-			$remote = $this->cleanupRemote($share['remote']);
415
-
416
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
417
-			$mountpoint = $share['mountpoint'];
418
-			$user = $share['user'];
419
-
420
-			$qb = $this->connection->getQueryBuilder();
421
-			$qb->delete('share_external')
422
-				->where(
423
-					$qb->expr()->andX(
424
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
425
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
426
-					)
427
-				);
428
-
429
-			$result = $qb->execute();
430
-			$result->closeCursor();
431
-
432
-			if ($share['accepted']) {
433
-				$path = trim($mountpoint, '/');
434
-			} else {
435
-				$path = trim($share['name'], '/');
436
-			}
437
-
438
-			$notificationManager = \OC::$server->getNotificationManager();
439
-			$notification = $notificationManager->createNotification();
440
-			$notification->setApp('files_sharing')
441
-				->setUser($share['user'])
442
-				->setObject('remote_share', (int)$share['id']);
443
-			$notificationManager->markProcessed($notification);
444
-
445
-			$event = \OC::$server->getActivityManager()->generateEvent();
446
-			$event->setApp('files_sharing')
447
-				->setType('remote_share')
448
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
449
-				->setAffectedUser($user)
450
-				->setObject('remote_share', (int)$share['id'], $path);
451
-			\OC::$server->getActivityManager()->publish($event);
452
-		}
453
-
454
-		return new Http\DataResponse();
455
-	}
456
-
457
-	private function cleanupRemote($remote) {
458
-		$remote = substr($remote, strpos($remote, '://') + 3);
459
-
460
-		return rtrim($remote, '/');
461
-	}
462
-
463
-
464
-	/**
465
-	 * @NoCSRFRequired
466
-	 * @PublicPage
467
-	 *
468
-	 * federated share was revoked, either by the owner or the re-sharer
469
-	 *
470
-	 * @param int $id
471
-	 * @return Http\DataResponse
472
-	 * @throws OCSBadRequestException
473
-	 */
474
-	public function revoke($id) {
475
-		$token = $this->request->getParam('token');
476
-
477
-		$share = $this->federatedShareProvider->getShareById($id);
478
-
479
-		if ($this->verifyShare($share, $token)) {
480
-			$this->federatedShareProvider->removeShareFromTable($share);
481
-			return new Http\DataResponse();
482
-		}
483
-
484
-		throw new OCSBadRequestException();
485
-	}
486
-
487
-	/**
488
-	 * get share
489
-	 *
490
-	 * @param int $id
491
-	 * @param string $token
492
-	 * @return array|bool
493
-	 */
494
-	protected function getShare($id, $token) {
495
-		$query = $this->connection->getQueryBuilder();
496
-		$query->select('*')->from($this->shareTable)
497
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
498
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
499
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
500
-
501
-		$result = $query->execute()->fetchAll();
502
-
503
-		if (!empty($result) && isset($result[0])) {
504
-			return $result[0];
505
-		}
506
-
507
-		return false;
508
-	}
509
-
510
-	/**
511
-	 * get file
512
-	 *
513
-	 * @param string $user
514
-	 * @param int $fileSource
515
-	 * @return array with internal path of the file and a absolute link to it
516
-	 */
517
-	private function getFile($user, $fileSource) {
518
-		\OC_Util::setupFS($user);
519
-
520
-		try {
521
-			$file = \OC\Files\Filesystem::getPath($fileSource);
522
-		} catch (NotFoundException $e) {
523
-			$file = null;
524
-		}
525
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
526
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
527
-
528
-		return array($file, $link);
529
-
530
-	}
531
-
532
-	/**
533
-	 * check if server-to-server sharing is enabled
534
-	 *
535
-	 * @param bool $incoming
536
-	 * @return bool
537
-	 */
538
-	private function isS2SEnabled($incoming = false) {
539
-
540
-		$result = \OCP\App::isEnabled('files_sharing');
541
-
542
-		if ($incoming) {
543
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
544
-		} else {
545
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
546
-		}
547
-
548
-		return $result;
549
-	}
550
-
551
-	/**
552
-	 * check if we got the right share
553
-	 *
554
-	 * @param Share\IShare $share
555
-	 * @param string $token
556
-	 * @return bool
557
-	 */
558
-	protected function verifyShare(Share\IShare $share, $token) {
559
-		if (
560
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
561
-			$share->getToken() === $token
562
-		) {
563
-			return true;
564
-		}
565
-
566
-		return false;
567
-	}
568
-
569
-	/**
570
-	 * @NoCSRFRequired
571
-	 * @PublicPage
572
-	 *
573
-	 * update share information to keep federated re-shares in sync
574
-	 *
575
-	 * @param int $id
576
-	 * @return Http\DataResponse
577
-	 * @throws OCSBadRequestException
578
-	 */
579
-	public function updatePermissions($id) {
580
-		$token = $this->request->getParam('token', null);
581
-		$permissions = $this->request->getParam('permissions', null);
582
-
583
-		try {
584
-			$share = $this->federatedShareProvider->getShareById($id);
585
-		} catch (Share\Exceptions\ShareNotFound $e) {
586
-			throw new OCSBadRequestException();
587
-		}
588
-
589
-		$validPermission = ctype_digit($permissions);
590
-		$validToken = $this->verifyShare($share, $token);
591
-		if ($validPermission && $validToken) {
592
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
593
-		} else {
594
-			throw new OCSBadRequestException();
595
-		}
596
-
597
-		return new Http\DataResponse();
598
-	}
599
-
600
-	/**
601
-	 * update permissions in database
602
-	 *
603
-	 * @param IShare $share
604
-	 * @param int $permissions
605
-	 */
606
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
607
-		$query = $this->connection->getQueryBuilder();
608
-		$query->update('share')
609
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
610
-			->set('permissions', $query->createNamedParameter($permissions))
611
-			->execute();
612
-	}
613
-
614
-	/**
615
-	 * @NoCSRFRequired
616
-	 * @PublicPage
617
-	 *
618
-	 * change the owner of a server-to-server share
619
-	 *
620
-	 * @param int $id
621
-	 * @return Http\DataResponse
622
-	 * @throws \InvalidArgumentException
623
-	 * @throws OCSException
624
-	 */
625
-	public function move($id) {
626
-
627
-		if (!$this->isS2SEnabled()) {
628
-			throw new OCSException('Server does not support federated cloud sharing', 503);
629
-		}
630
-
631
-		$token = $this->request->getParam('token');
632
-		$remote = $this->request->getParam('remote');
633
-		$newRemoteId = $this->request->getParam('remote_id', $id);
634
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
635
-
636
-		$qb = $this->connection->getQueryBuilder();
637
-		$query = $qb->update('share_external')
638
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
639
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
640
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
641
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
642
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
643
-		$affected = $query->execute();
644
-
645
-		if ($affected > 0) {
646
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
647
-		} else {
648
-			throw new OCSBadRequestException('Share not found or token invalid');
649
-		}
650
-	}
58
+    /** @var FederatedShareProvider */
59
+    private $federatedShareProvider;
60
+
61
+    /** @var IDBConnection */
62
+    private $connection;
63
+
64
+    /** @var Share\IManager */
65
+    private $shareManager;
66
+
67
+    /** @var Notifications */
68
+    private $notifications;
69
+
70
+    /** @var AddressHandler */
71
+    private $addressHandler;
72
+
73
+    /** @var  IUserManager */
74
+    private $userManager;
75
+
76
+    /** @var string */
77
+    private $shareTable = 'share';
78
+
79
+    /** @var ICloudIdManager */
80
+    private $cloudIdManager;
81
+
82
+    /** @var ILogger */
83
+    private $logger;
84
+
85
+    /** @var ICloudFederationFactory */
86
+    private $cloudFederationFactory;
87
+
88
+    /** @var ICloudFederationProviderManager */
89
+    private $cloudFederationProviderManager;
90
+
91
+    /**
92
+     * Server2Server constructor.
93
+     *
94
+     * @param string $appName
95
+     * @param IRequest $request
96
+     * @param FederatedShareProvider $federatedShareProvider
97
+     * @param IDBConnection $connection
98
+     * @param Share\IManager $shareManager
99
+     * @param Notifications $notifications
100
+     * @param AddressHandler $addressHandler
101
+     * @param IUserManager $userManager
102
+     * @param ICloudIdManager $cloudIdManager
103
+     * @param ILogger $logger
104
+     * @param ICloudFederationFactory $cloudFederationFactory
105
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
106
+     */
107
+    public function __construct($appName,
108
+                                IRequest $request,
109
+                                FederatedShareProvider $federatedShareProvider,
110
+                                IDBConnection $connection,
111
+                                Share\IManager $shareManager,
112
+                                Notifications $notifications,
113
+                                AddressHandler $addressHandler,
114
+                                IUserManager $userManager,
115
+                                ICloudIdManager $cloudIdManager,
116
+                                ILogger $logger,
117
+                                ICloudFederationFactory $cloudFederationFactory,
118
+                                ICloudFederationProviderManager $cloudFederationProviderManager
119
+    ) {
120
+        parent::__construct($appName, $request);
121
+
122
+        $this->federatedShareProvider = $federatedShareProvider;
123
+        $this->connection = $connection;
124
+        $this->shareManager = $shareManager;
125
+        $this->notifications = $notifications;
126
+        $this->addressHandler = $addressHandler;
127
+        $this->userManager = $userManager;
128
+        $this->cloudIdManager = $cloudIdManager;
129
+        $this->logger = $logger;
130
+        $this->cloudFederationFactory = $cloudFederationFactory;
131
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
132
+    }
133
+
134
+    /**
135
+     * @NoCSRFRequired
136
+     * @PublicPage
137
+     *
138
+     * create a new share
139
+     *
140
+     * @return Http\DataResponse
141
+     * @throws OCSException
142
+     */
143
+    public function createShare() {
144
+
145
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
146
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
147
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
148
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
149
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
150
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
151
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
152
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
153
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
154
+
155
+        if ($ownerFederatedId === null) {
156
+            $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
157
+        }
158
+        // if the owner of the share and the initiator are the same user
159
+        // we also complete the federated share ID for the initiator
160
+        if ($sharedByFederatedId === null && $owner === $sharedBy) {
161
+            $sharedByFederatedId = $ownerFederatedId;
162
+        }
163
+
164
+        $share = $this->cloudFederationFactory->getCloudFederationShare(
165
+            $shareWith,
166
+            $name,
167
+            '',
168
+            $remoteId,
169
+            $ownerFederatedId,
170
+            $owner,
171
+            $sharedByFederatedId,
172
+            $sharedBy,
173
+            ['name' => 'webdav', 'options' => ['access_token' => $token]],
174
+            'user',
175
+            'file'
176
+        );
177
+
178
+        try {
179
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
180
+            $provider->shareReceived($share);
181
+        } catch (ProviderDoesNotExistsException $e) {
182
+            throw new OCSException('Server does not support federated cloud sharing', 503);
183
+        } catch (ProviderCouldNotAddShareException $e) {
184
+            throw new OCSException($e->getMessage(), $e->getCode());
185
+        } catch (\Exception $e) {
186
+            throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
187
+        }
188
+
189
+        return new Http\DataResponse();
190
+    }
191
+
192
+    /**
193
+     * @NoCSRFRequired
194
+     * @PublicPage
195
+     *
196
+     * create re-share on behalf of another user
197
+     *
198
+     * @param int $id
199
+     * @return Http\DataResponse
200
+     * @throws OCSBadRequestException
201
+     * @throws OCSForbiddenException
202
+     * @throws OCSNotFoundException
203
+     */
204
+    public function reShare($id) {
205
+
206
+        $token = $this->request->getParam('token', null);
207
+        $shareWith = $this->request->getParam('shareWith', null);
208
+        $permission = (int)$this->request->getParam('permission', null);
209
+        $remoteId = (int)$this->request->getParam('remoteId', null);
210
+
211
+        if ($id === null ||
212
+            $token === null ||
213
+            $shareWith === null ||
214
+            $permission === null ||
215
+            $remoteId === null
216
+        ) {
217
+            throw new OCSBadRequestException();
218
+        }
219
+
220
+        try {
221
+            $share = $this->federatedShareProvider->getShareById($id);
222
+        } catch (Share\Exceptions\ShareNotFound $e) {
223
+            throw new OCSNotFoundException();
224
+        }
225
+
226
+        // don't allow to share a file back to the owner
227
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
228
+        $owner = $share->getShareOwner();
229
+        $currentServer = $this->addressHandler->generateRemoteURL();
230
+        if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
231
+            throw new OCSForbiddenException();
232
+        }
233
+
234
+        if ($this->verifyShare($share, $token)) {
235
+
236
+            // check if re-sharing is allowed
237
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
238
+                $share->setPermissions($share->getPermissions() & $permission);
239
+                // the recipient of the initial share is now the initiator for the re-share
240
+                $share->setSharedBy($share->getSharedWith());
241
+                $share->setSharedWith($shareWith);
242
+                try {
243
+                    $result = $this->federatedShareProvider->create($share);
244
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
245
+                    return new Http\DataResponse([
246
+                        'token' => $result->getToken(),
247
+                        'remoteId' => $result->getId()
248
+                    ]);
249
+                } catch (\Exception $e) {
250
+                    throw new OCSBadRequestException();
251
+                }
252
+            } else {
253
+                throw new OCSForbiddenException();
254
+            }
255
+        }
256
+        throw new OCSBadRequestException();
257
+    }
258
+
259
+    /**
260
+     * @NoCSRFRequired
261
+     * @PublicPage
262
+     *
263
+     * accept server-to-server share
264
+     *
265
+     * @param int $id
266
+     * @return Http\DataResponse
267
+     * @throws OCSException
268
+     */
269
+    public function acceptShare($id) {
270
+
271
+        if (!$this->isS2SEnabled()) {
272
+            throw new OCSException('Server does not support federated cloud sharing', 503);
273
+        }
274
+
275
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
276
+
277
+        try {
278
+            $share = $this->federatedShareProvider->getShareById($id);
279
+        } catch (Share\Exceptions\ShareNotFound $e) {
280
+            return new Http\DataResponse();
281
+        }
282
+
283
+        if ($this->verifyShare($share, $token)) {
284
+            $this->executeAcceptShare($share);
285
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
286
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
287
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
288
+                $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
289
+            }
290
+        }
291
+
292
+        return new Http\DataResponse();
293
+    }
294
+
295
+    protected function executeAcceptShare(Share\IShare $share) {
296
+        $fileId = (int) $share->getNode()->getId();
297
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
298
+
299
+        $event = \OC::$server->getActivityManager()->generateEvent();
300
+        $event->setApp('files_sharing')
301
+            ->setType('remote_share')
302
+            ->setAffectedUser($this->getCorrectUid($share))
303
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
304
+            ->setObject('files', $fileId, $file)
305
+            ->setLink($link);
306
+        \OC::$server->getActivityManager()->publish($event);
307
+    }
308
+
309
+    /**
310
+     * @NoCSRFRequired
311
+     * @PublicPage
312
+     *
313
+     * decline server-to-server share
314
+     *
315
+     * @param int $id
316
+     * @return Http\DataResponse
317
+     * @throws OCSException
318
+     */
319
+    public function declineShare($id) {
320
+
321
+        if (!$this->isS2SEnabled()) {
322
+            throw new OCSException('Server does not support federated cloud sharing', 503);
323
+        }
324
+
325
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
326
+
327
+        try {
328
+            $share = $this->federatedShareProvider->getShareById($id);
329
+        } catch (Share\Exceptions\ShareNotFound $e) {
330
+            return new Http\DataResponse();
331
+        }
332
+
333
+        if ($this->verifyShare($share, $token)) {
334
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
335
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
336
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
337
+                $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
338
+            }
339
+            $this->executeDeclineShare($share);
340
+        }
341
+
342
+        return new Http\DataResponse();
343
+    }
344
+
345
+    /**
346
+     * delete declined share and create a activity
347
+     *
348
+     * @param Share\IShare $share
349
+     */
350
+    protected function executeDeclineShare(Share\IShare $share) {
351
+        $this->federatedShareProvider->removeShareFromTable($share);
352
+        $fileId = (int) $share->getNode()->getId();
353
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
354
+
355
+        $event = \OC::$server->getActivityManager()->generateEvent();
356
+        $event->setApp('files_sharing')
357
+            ->setType('remote_share')
358
+            ->setAffectedUser($this->getCorrectUid($share))
359
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
360
+            ->setObject('files', $fileId, $file)
361
+            ->setLink($link);
362
+        \OC::$server->getActivityManager()->publish($event);
363
+
364
+    }
365
+
366
+    /**
367
+     * check if we are the initiator or the owner of a re-share and return the correct UID
368
+     *
369
+     * @param Share\IShare $share
370
+     * @return string
371
+     */
372
+    protected function getCorrectUid(Share\IShare $share) {
373
+        if ($this->userManager->userExists($share->getShareOwner())) {
374
+            return $share->getShareOwner();
375
+        }
376
+
377
+        return $share->getSharedBy();
378
+    }
379
+
380
+    /**
381
+     * @NoCSRFRequired
382
+     * @PublicPage
383
+     *
384
+     * remove server-to-server share if it was unshared by the owner
385
+     *
386
+     * @param int $id
387
+     * @return Http\DataResponse
388
+     * @throws OCSException
389
+     */
390
+    public function unshare($id) {
391
+
392
+        if (!$this->isS2SEnabled()) {
393
+            throw new OCSException('Server does not support federated cloud sharing', 503);
394
+        }
395
+
396
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
397
+
398
+        $qb = $this->connection->getQueryBuilder();
399
+        $qb->select('*')
400
+            ->from('share_external')
401
+            ->where(
402
+                $qb->expr()->andX(
403
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
404
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
405
+                )
406
+            );
407
+
408
+        $result = $qb->execute();
409
+        $share = $result->fetch();
410
+        $result->closeCursor();
411
+
412
+        if ($token && $id && !empty($share)) {
413
+
414
+            $remote = $this->cleanupRemote($share['remote']);
415
+
416
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
417
+            $mountpoint = $share['mountpoint'];
418
+            $user = $share['user'];
419
+
420
+            $qb = $this->connection->getQueryBuilder();
421
+            $qb->delete('share_external')
422
+                ->where(
423
+                    $qb->expr()->andX(
424
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
425
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
426
+                    )
427
+                );
428
+
429
+            $result = $qb->execute();
430
+            $result->closeCursor();
431
+
432
+            if ($share['accepted']) {
433
+                $path = trim($mountpoint, '/');
434
+            } else {
435
+                $path = trim($share['name'], '/');
436
+            }
437
+
438
+            $notificationManager = \OC::$server->getNotificationManager();
439
+            $notification = $notificationManager->createNotification();
440
+            $notification->setApp('files_sharing')
441
+                ->setUser($share['user'])
442
+                ->setObject('remote_share', (int)$share['id']);
443
+            $notificationManager->markProcessed($notification);
444
+
445
+            $event = \OC::$server->getActivityManager()->generateEvent();
446
+            $event->setApp('files_sharing')
447
+                ->setType('remote_share')
448
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
449
+                ->setAffectedUser($user)
450
+                ->setObject('remote_share', (int)$share['id'], $path);
451
+            \OC::$server->getActivityManager()->publish($event);
452
+        }
453
+
454
+        return new Http\DataResponse();
455
+    }
456
+
457
+    private function cleanupRemote($remote) {
458
+        $remote = substr($remote, strpos($remote, '://') + 3);
459
+
460
+        return rtrim($remote, '/');
461
+    }
462
+
463
+
464
+    /**
465
+     * @NoCSRFRequired
466
+     * @PublicPage
467
+     *
468
+     * federated share was revoked, either by the owner or the re-sharer
469
+     *
470
+     * @param int $id
471
+     * @return Http\DataResponse
472
+     * @throws OCSBadRequestException
473
+     */
474
+    public function revoke($id) {
475
+        $token = $this->request->getParam('token');
476
+
477
+        $share = $this->federatedShareProvider->getShareById($id);
478
+
479
+        if ($this->verifyShare($share, $token)) {
480
+            $this->federatedShareProvider->removeShareFromTable($share);
481
+            return new Http\DataResponse();
482
+        }
483
+
484
+        throw new OCSBadRequestException();
485
+    }
486
+
487
+    /**
488
+     * get share
489
+     *
490
+     * @param int $id
491
+     * @param string $token
492
+     * @return array|bool
493
+     */
494
+    protected function getShare($id, $token) {
495
+        $query = $this->connection->getQueryBuilder();
496
+        $query->select('*')->from($this->shareTable)
497
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
498
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
499
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
500
+
501
+        $result = $query->execute()->fetchAll();
502
+
503
+        if (!empty($result) && isset($result[0])) {
504
+            return $result[0];
505
+        }
506
+
507
+        return false;
508
+    }
509
+
510
+    /**
511
+     * get file
512
+     *
513
+     * @param string $user
514
+     * @param int $fileSource
515
+     * @return array with internal path of the file and a absolute link to it
516
+     */
517
+    private function getFile($user, $fileSource) {
518
+        \OC_Util::setupFS($user);
519
+
520
+        try {
521
+            $file = \OC\Files\Filesystem::getPath($fileSource);
522
+        } catch (NotFoundException $e) {
523
+            $file = null;
524
+        }
525
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
526
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
527
+
528
+        return array($file, $link);
529
+
530
+    }
531
+
532
+    /**
533
+     * check if server-to-server sharing is enabled
534
+     *
535
+     * @param bool $incoming
536
+     * @return bool
537
+     */
538
+    private function isS2SEnabled($incoming = false) {
539
+
540
+        $result = \OCP\App::isEnabled('files_sharing');
541
+
542
+        if ($incoming) {
543
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
544
+        } else {
545
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
546
+        }
547
+
548
+        return $result;
549
+    }
550
+
551
+    /**
552
+     * check if we got the right share
553
+     *
554
+     * @param Share\IShare $share
555
+     * @param string $token
556
+     * @return bool
557
+     */
558
+    protected function verifyShare(Share\IShare $share, $token) {
559
+        if (
560
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
561
+            $share->getToken() === $token
562
+        ) {
563
+            return true;
564
+        }
565
+
566
+        return false;
567
+    }
568
+
569
+    /**
570
+     * @NoCSRFRequired
571
+     * @PublicPage
572
+     *
573
+     * update share information to keep federated re-shares in sync
574
+     *
575
+     * @param int $id
576
+     * @return Http\DataResponse
577
+     * @throws OCSBadRequestException
578
+     */
579
+    public function updatePermissions($id) {
580
+        $token = $this->request->getParam('token', null);
581
+        $permissions = $this->request->getParam('permissions', null);
582
+
583
+        try {
584
+            $share = $this->federatedShareProvider->getShareById($id);
585
+        } catch (Share\Exceptions\ShareNotFound $e) {
586
+            throw new OCSBadRequestException();
587
+        }
588
+
589
+        $validPermission = ctype_digit($permissions);
590
+        $validToken = $this->verifyShare($share, $token);
591
+        if ($validPermission && $validToken) {
592
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
593
+        } else {
594
+            throw new OCSBadRequestException();
595
+        }
596
+
597
+        return new Http\DataResponse();
598
+    }
599
+
600
+    /**
601
+     * update permissions in database
602
+     *
603
+     * @param IShare $share
604
+     * @param int $permissions
605
+     */
606
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
607
+        $query = $this->connection->getQueryBuilder();
608
+        $query->update('share')
609
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
610
+            ->set('permissions', $query->createNamedParameter($permissions))
611
+            ->execute();
612
+    }
613
+
614
+    /**
615
+     * @NoCSRFRequired
616
+     * @PublicPage
617
+     *
618
+     * change the owner of a server-to-server share
619
+     *
620
+     * @param int $id
621
+     * @return Http\DataResponse
622
+     * @throws \InvalidArgumentException
623
+     * @throws OCSException
624
+     */
625
+    public function move($id) {
626
+
627
+        if (!$this->isS2SEnabled()) {
628
+            throw new OCSException('Server does not support federated cloud sharing', 503);
629
+        }
630
+
631
+        $token = $this->request->getParam('token');
632
+        $remote = $this->request->getParam('remote');
633
+        $newRemoteId = $this->request->getParam('remote_id', $id);
634
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
635
+
636
+        $qb = $this->connection->getQueryBuilder();
637
+        $query = $qb->update('share_external')
638
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
639
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
640
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
641
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
642
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
643
+        $affected = $query->execute();
644
+
645
+        if ($affected > 0) {
646
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
647
+        } else {
648
+            throw new OCSBadRequestException('Share not found or token invalid');
649
+        }
650
+    }
651 651
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
149 149
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
150 150
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
151
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
151
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
152 152
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
153 153
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
154 154
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 		} catch (ProviderCouldNotAddShareException $e) {
184 184
 			throw new OCSException($e->getMessage(), $e->getCode());
185 185
 		} catch (\Exception $e) {
186
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
186
+			throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
187 187
 		}
188 188
 
189 189
 		return new Http\DataResponse();
@@ -205,8 +205,8 @@  discard block
 block discarded – undo
205 205
 
206 206
 		$token = $this->request->getParam('token', null);
207 207
 		$shareWith = $this->request->getParam('shareWith', null);
208
-		$permission = (int)$this->request->getParam('permission', null);
209
-		$remoteId = (int)$this->request->getParam('remoteId', null);
208
+		$permission = (int) $this->request->getParam('permission', null);
209
+		$remoteId = (int) $this->request->getParam('remoteId', null);
210 210
 
211 211
 		if ($id === null ||
212 212
 			$token === null ||
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 				$share->setSharedWith($shareWith);
242 242
 				try {
243 243
 					$result = $this->federatedShareProvider->create($share);
244
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
244
+					$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $remoteId);
245 245
 					return new Http\DataResponse([
246 246
 						'token' => $result->getToken(),
247 247
 						'remoteId' => $result->getId()
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 			$notification = $notificationManager->createNotification();
440 440
 			$notification->setApp('files_sharing')
441 441
 				->setUser($share['user'])
442
-				->setObject('remote_share', (int)$share['id']);
442
+				->setObject('remote_share', (int) $share['id']);
443 443
 			$notificationManager->markProcessed($notification);
444 444
 
445 445
 			$event = \OC::$server->getActivityManager()->generateEvent();
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 				->setType('remote_share')
448 448
 				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
449 449
 				->setAffectedUser($user)
450
-				->setObject('remote_share', (int)$share['id'], $path);
450
+				->setObject('remote_share', (int) $share['id'], $path);
451 451
 			\OC::$server->getActivityManager()->publish($event);
452 452
 		}
453 453
 
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
 		$validPermission = ctype_digit($permissions);
590 590
 		$validToken = $this->verifyShare($share, $token);
591 591
 		if ($validPermission && $validToken) {
592
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
592
+			$this->updatePermissionsInDatabase($share, (int) $permissions);
593 593
 		} else {
594 594
 			throw new OCSBadRequestException();
595 595
 		}
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Config.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -32,15 +32,15 @@
 block discarded – undo
32 32
  */
33 33
 class Config {
34 34
 
35
-	public function __construct() {
36
-	}
35
+    public function __construct() {
36
+    }
37 37
 
38
-	public function incomingRequestsEnabled() {
39
-		return true;
40
-	}
38
+    public function incomingRequestsEnabled() {
39
+        return true;
40
+    }
41 41
 
42
-	public function outgoingRequestsEnabled() {
43
-		return true;
44
-	}
42
+    public function outgoingRequestsEnabled() {
43
+        return true;
44
+    }
45 45
 
46 46
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/AppInfo/Application.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -28,10 +28,10 @@
 block discarded – undo
28 28
 
29 29
 class Application extends App {
30 30
 
31
-	public function __construct() {
32
-		parent::__construct('cloud_federation_api');
31
+    public function __construct() {
32
+        parent::__construct('cloud_federation_api');
33 33
 
34
-		$container = $this->getContainer();
35
-		$container->registerCapability(Capabilities::class);
36
-	}
34
+        $container = $this->getContainer();
35
+        $container->registerCapability(Capabilities::class);
36
+    }
37 37
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Capabilities.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -28,29 +28,29 @@
 block discarded – undo
28 28
 
29 29
 class Capabilities implements ICapability {
30 30
 
31
-	/** @var IURLGenerator */
32
-	private $urlGenerator;
33
-
34
-	public function __construct(IURLGenerator $urlGenerator) {
35
-		$this->urlGenerator = $urlGenerator;
36
-	}
37
-
38
-	/**
39
-	 * Function an app uses to return the capabilities
40
-	 *
41
-	 * @return array Array containing the apps capabilities
42
-	 * @since 8.2.0
43
-	 */
44
-	public function getCapabilities() {
45
-		$url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
46
-		$capabilities = ['ocm' =>
47
-			[
48
-				'enabled' => true,
49
-				'api-version' => '2.0-draft',
50
-				'end-point' => substr($url, 0, strrpos($url, '/')),
51
-			]
52
-		];
53
-
54
-		return $capabilities;
55
-	}
31
+    /** @var IURLGenerator */
32
+    private $urlGenerator;
33
+
34
+    public function __construct(IURLGenerator $urlGenerator) {
35
+        $this->urlGenerator = $urlGenerator;
36
+    }
37
+
38
+    /**
39
+     * Function an app uses to return the capabilities
40
+     *
41
+     * @return array Array containing the apps capabilities
42
+     * @since 8.2.0
43
+     */
44
+    public function getCapabilities() {
45
+        $url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
46
+        $capabilities = ['ocm' =>
47
+            [
48
+                'enabled' => true,
49
+                'api-version' => '2.0-draft',
50
+                'end-point' => substr($url, 0, strrpos($url, '/')),
51
+            ]
52
+        ];
53
+
54
+        return $capabilities;
55
+    }
56 56
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 
138 138
 		if (!$this->userManager->userExists($shareWith)) {
139 139
 			return new JSONResponse(
140
-				['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
140
+				['message' => 'User "'.$shareWith.'" does not exists at '.$this->urlGenerator->getBaseUrl()],
141 141
 				Http::STATUS_BAD_REQUEST
142 142
 			);
143 143
 		}
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			);
169 169
 		} catch (\Exception $e) {
170 170
 			return new JSONResponse(
171
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
171
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
172 172
 				Http::STATUS_BAD_REQUEST
173 173
 			);
174 174
 		}
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 			);
223 223
 		} catch (\Exception $e) {
224 224
 			return new JSONResponse(
225
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
225
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
226 226
 				Http::STATUS_BAD_REQUEST
227 227
 			);
228 228
 		}
@@ -244,13 +244,13 @@  discard block
 block discarded – undo
244 244
 	private function mapUid($uid) {
245 245
 		\OC::$server->getURLGenerator()->linkToDocs('key');
246 246
 		// FIXME this should be a method in the user management instead
247
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
247
+		$this->logger->debug('shareWith before, '.$uid, ['app' => $this->appName]);
248 248
 		\OCP\Util::emitHook(
249 249
 			'\OCA\Files_Sharing\API\Server2Server',
250 250
 			'preLoginNameUsedAsUserName',
251 251
 			array('uid' => &$uid)
252 252
 		);
253
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
253
+		$this->logger->debug('shareWith after, '.$uid, ['app' => $this->appName]);
254 254
 
255 255
 		return $uid;
256 256
 	}
Please login to merge, or discard this patch.
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -49,223 +49,223 @@
 block discarded – undo
49 49
  */
50 50
 class RequestHandlerController extends Controller {
51 51
 
52
-	/** @var ILogger */
53
-	private $logger;
54
-
55
-	/** @var IUserManager */
56
-	private $userManager;
57
-
58
-	/** @var IURLGenerator */
59
-	private $urlGenerator;
60
-
61
-	/** @var ICloudFederationProviderManager */
62
-	private $cloudFederationProviderManager;
63
-
64
-	/** @var Config */
65
-	private $config;
66
-
67
-	/** @var ICloudFederationFactory */
68
-	private $factory;
69
-
70
-	/** @var ICloudIdManager */
71
-	private $cloudIdManager;
72
-
73
-	public function __construct($appName,
74
-								IRequest $request,
75
-								ILogger $logger,
76
-								IUserManager $userManager,
77
-								IURLGenerator $urlGenerator,
78
-								ICloudFederationProviderManager $cloudFederationProviderManager,
79
-								Config $config,
80
-								ICloudFederationFactory $factory,
81
-								ICloudIdManager $cloudIdManager
82
-	) {
83
-		parent::__construct($appName, $request);
84
-
85
-		$this->logger = $logger;
86
-		$this->userManager = $userManager;
87
-		$this->urlGenerator = $urlGenerator;
88
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
89
-		$this->config = $config;
90
-		$this->factory = $factory;
91
-		$this->cloudIdManager = $cloudIdManager;
92
-	}
93
-
94
-	/**
95
-	 * add share
96
-	 *
97
-	 * @NoCSRFRequired
98
-	 * @PublicPage
99
-	 * @BruteForceProtection(action=receiveFederatedShare)
100
-	 *
101
-	 * @param string $shareWith
102
-	 * @param string $name resource name (e.g. document.odt)
103
-	 * @param string $description share description (optional)
104
-	 * @param string $providerId resource UID on the provider side
105
-	 * @param string $owner provider specific UID of the user who owns the resource
106
-	 * @param string $ownerDisplayName display name of the user who shared the item
107
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
108
-	 * @param $sharedByDisplayName display name of the user who shared the resource
109
-	 * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
110
-	 * @param string $shareType ('group' or 'user' share)
111
-	 * @param $resourceType ('file', 'calendar',...)
112
-	 * @return Http\DataResponse|JSONResponse
113
-	 *
114
-	 * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"access_token":"8Lrd1FVEREthux7","permissions":31}}}' http://localhost/server/index.php/ocm/shares
115
-	 */
116
-	public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
117
-
118
-		if (!$this->config->incomingRequestsEnabled()) {
119
-			return new JSONResponse(
120
-				['message' => 'This server doesn\'t support outgoing federated shares'],
121
-			Http::STATUS_NOT_IMPLEMENTED
122
-			);
123
-		}
124
-
125
-		// check if all required parameters are set
126
-		if ($shareWith === null ||
127
-			$name === null ||
128
-			$providerId === null ||
129
-			$owner === null ||
130
-			$resourceType === null ||
131
-			$shareType === null ||
132
-			!is_array($protocol) ||
133
-			!isset($protocol['name']) ||
134
-			!isset ($protocol['options']) ||
135
-			!is_array($protocol['options'])
136
-		) {
137
-			return new JSONResponse(
138
-				['message' => 'Missing arguments'],
139
-				Http::STATUS_BAD_REQUEST
140
-			);
141
-		}
142
-
143
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
144
-		$shareWithLocalId = $cloudId->getUser();
145
-		$shareWith = $this->mapUid($shareWithLocalId);
146
-
147
-		if (!$this->userManager->userExists($shareWith)) {
148
-			return new JSONResponse(
149
-				['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
150
-				Http::STATUS_BAD_REQUEST
151
-			);
152
-		}
153
-
154
-		// if no explicit display name is given, we use the uid as display name
155
-		$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
156
-		$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
157
-
158
-		// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
159
-		if ($sharedBy === null) {
160
-			$sharedBy = $owner;
161
-			$sharedByDisplayName = $ownerDisplayName;
162
-		}
163
-
164
-		try {
165
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
166
-			$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType);
167
-			$id = $provider->shareReceived($share);
168
-		} catch (ProviderDoesNotExistsException $e) {
169
-			return new JSONResponse(
170
-				['message' => $e->getMessage()],
171
-				Http::STATUS_NOT_IMPLEMENTED
172
-			);
173
-		} catch (ProviderCouldNotAddShareException $e) {
174
-			return new JSONResponse(
175
-				['message' => $e->getMessage()],
176
-				$e->getCode()
177
-			);
178
-		} catch (\Exception $e) {
179
-			return new JSONResponse(
180
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
181
-				Http::STATUS_BAD_REQUEST
182
-			);
183
-		}
184
-
185
-		return new JSONResponse(
186
-			['id' => $id, 'createdAt' => time()],
187
-			Http::STATUS_CREATED);
188
-
189
-	}
190
-
191
-	/**
192
-	 * receive notification about existing share
193
-	 *
194
-	 * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
195
-	 * @param string $resourceType (calendar, file, contact,...)
196
-	 * @param array $message contain the actual notification, content is defined by cloud federation provider
197
-	 * @return JSONResponse
198
-	 */
199
-	public function receiveNotification($notificationType, $resourceType, $message) {
200
-		if (!$this->config->incomingRequestsEnabled()) {
201
-			return new JSONResponse(
202
-				['message' => 'This server doesn\'t support outgoing federated shares'],
203
-				Http::STATUS_NOT_IMPLEMENTED
204
-			);
205
-		}
206
-
207
-		// check if all required parameters are set
208
-		if ($notificationType === null ||
209
-			$resourceType === null ||
210
-			!is_array($message)
211
-		) {
212
-			return new JSONResponse(
213
-				['message' => 'Missing arguments'],
214
-				Http::STATUS_BAD_REQUEST
215
-			);
216
-		}
217
-
218
-		try {
219
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
220
-			$provider->notificationReceived($notificationType, $message);
221
-		} catch (ProviderDoesNotExistsException $e) {
222
-			return new JSONResponse(
223
-				['message' => $e->getMessage()],
224
-				Http::STATUS_BAD_REQUEST
225
-			);
226
-		} catch (ShareNotFoundException $e) {
227
-			return new JSONResponse(
228
-				['message' => $e->getMessage()],
229
-				Http::STATUS_BAD_REQUEST
230
-			);
231
-		} catch (ActionNotSupportedException $e) {
232
-			return new JSONResponse(
233
-				['message' => $e->getMessage()],
234
-				Http::STATUS_NOT_IMPLEMENTED
235
-			);
236
-		} catch (\Exception $e) {
237
-			return new JSONResponse(
238
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
239
-				Http::STATUS_BAD_REQUEST
240
-			);
241
-		}
242
-
243
-
244
-		return new JSONResponse(
245
-			['id' => $id, 'createdAt' => date()],
246
-			Http::STATUS_CREATED);
247
-
248
-
249
-	}
250
-
251
-	/**
252
-	 * map login name to internal LDAP UID if a LDAP backend is in use
253
-	 *
254
-	 * @param string $uid
255
-	 * @return string mixed
256
-	 */
257
-	private function mapUid($uid) {
258
-		\OC::$server->getURLGenerator()->linkToDocs('key');
259
-		// FIXME this should be a method in the user management instead
260
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
261
-		\OCP\Util::emitHook(
262
-			'\OCA\Files_Sharing\API\Server2Server',
263
-			'preLoginNameUsedAsUserName',
264
-			array('uid' => &$uid)
265
-		);
266
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
267
-
268
-		return $uid;
269
-	}
52
+    /** @var ILogger */
53
+    private $logger;
54
+
55
+    /** @var IUserManager */
56
+    private $userManager;
57
+
58
+    /** @var IURLGenerator */
59
+    private $urlGenerator;
60
+
61
+    /** @var ICloudFederationProviderManager */
62
+    private $cloudFederationProviderManager;
63
+
64
+    /** @var Config */
65
+    private $config;
66
+
67
+    /** @var ICloudFederationFactory */
68
+    private $factory;
69
+
70
+    /** @var ICloudIdManager */
71
+    private $cloudIdManager;
72
+
73
+    public function __construct($appName,
74
+                                IRequest $request,
75
+                                ILogger $logger,
76
+                                IUserManager $userManager,
77
+                                IURLGenerator $urlGenerator,
78
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
79
+                                Config $config,
80
+                                ICloudFederationFactory $factory,
81
+                                ICloudIdManager $cloudIdManager
82
+    ) {
83
+        parent::__construct($appName, $request);
84
+
85
+        $this->logger = $logger;
86
+        $this->userManager = $userManager;
87
+        $this->urlGenerator = $urlGenerator;
88
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
89
+        $this->config = $config;
90
+        $this->factory = $factory;
91
+        $this->cloudIdManager = $cloudIdManager;
92
+    }
93
+
94
+    /**
95
+     * add share
96
+     *
97
+     * @NoCSRFRequired
98
+     * @PublicPage
99
+     * @BruteForceProtection(action=receiveFederatedShare)
100
+     *
101
+     * @param string $shareWith
102
+     * @param string $name resource name (e.g. document.odt)
103
+     * @param string $description share description (optional)
104
+     * @param string $providerId resource UID on the provider side
105
+     * @param string $owner provider specific UID of the user who owns the resource
106
+     * @param string $ownerDisplayName display name of the user who shared the item
107
+     * @param string $sharedBy provider specific UID of the user who shared the resource
108
+     * @param $sharedByDisplayName display name of the user who shared the resource
109
+     * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
110
+     * @param string $shareType ('group' or 'user' share)
111
+     * @param $resourceType ('file', 'calendar',...)
112
+     * @return Http\DataResponse|JSONResponse
113
+     *
114
+     * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"access_token":"8Lrd1FVEREthux7","permissions":31}}}' http://localhost/server/index.php/ocm/shares
115
+     */
116
+    public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
117
+
118
+        if (!$this->config->incomingRequestsEnabled()) {
119
+            return new JSONResponse(
120
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
121
+            Http::STATUS_NOT_IMPLEMENTED
122
+            );
123
+        }
124
+
125
+        // check if all required parameters are set
126
+        if ($shareWith === null ||
127
+            $name === null ||
128
+            $providerId === null ||
129
+            $owner === null ||
130
+            $resourceType === null ||
131
+            $shareType === null ||
132
+            !is_array($protocol) ||
133
+            !isset($protocol['name']) ||
134
+            !isset ($protocol['options']) ||
135
+            !is_array($protocol['options'])
136
+        ) {
137
+            return new JSONResponse(
138
+                ['message' => 'Missing arguments'],
139
+                Http::STATUS_BAD_REQUEST
140
+            );
141
+        }
142
+
143
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
144
+        $shareWithLocalId = $cloudId->getUser();
145
+        $shareWith = $this->mapUid($shareWithLocalId);
146
+
147
+        if (!$this->userManager->userExists($shareWith)) {
148
+            return new JSONResponse(
149
+                ['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
150
+                Http::STATUS_BAD_REQUEST
151
+            );
152
+        }
153
+
154
+        // if no explicit display name is given, we use the uid as display name
155
+        $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
156
+        $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
157
+
158
+        // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
159
+        if ($sharedBy === null) {
160
+            $sharedBy = $owner;
161
+            $sharedByDisplayName = $ownerDisplayName;
162
+        }
163
+
164
+        try {
165
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
166
+            $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType);
167
+            $id = $provider->shareReceived($share);
168
+        } catch (ProviderDoesNotExistsException $e) {
169
+            return new JSONResponse(
170
+                ['message' => $e->getMessage()],
171
+                Http::STATUS_NOT_IMPLEMENTED
172
+            );
173
+        } catch (ProviderCouldNotAddShareException $e) {
174
+            return new JSONResponse(
175
+                ['message' => $e->getMessage()],
176
+                $e->getCode()
177
+            );
178
+        } catch (\Exception $e) {
179
+            return new JSONResponse(
180
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
181
+                Http::STATUS_BAD_REQUEST
182
+            );
183
+        }
184
+
185
+        return new JSONResponse(
186
+            ['id' => $id, 'createdAt' => time()],
187
+            Http::STATUS_CREATED);
188
+
189
+    }
190
+
191
+    /**
192
+     * receive notification about existing share
193
+     *
194
+     * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
195
+     * @param string $resourceType (calendar, file, contact,...)
196
+     * @param array $message contain the actual notification, content is defined by cloud federation provider
197
+     * @return JSONResponse
198
+     */
199
+    public function receiveNotification($notificationType, $resourceType, $message) {
200
+        if (!$this->config->incomingRequestsEnabled()) {
201
+            return new JSONResponse(
202
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
203
+                Http::STATUS_NOT_IMPLEMENTED
204
+            );
205
+        }
206
+
207
+        // check if all required parameters are set
208
+        if ($notificationType === null ||
209
+            $resourceType === null ||
210
+            !is_array($message)
211
+        ) {
212
+            return new JSONResponse(
213
+                ['message' => 'Missing arguments'],
214
+                Http::STATUS_BAD_REQUEST
215
+            );
216
+        }
217
+
218
+        try {
219
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
220
+            $provider->notificationReceived($notificationType, $message);
221
+        } catch (ProviderDoesNotExistsException $e) {
222
+            return new JSONResponse(
223
+                ['message' => $e->getMessage()],
224
+                Http::STATUS_BAD_REQUEST
225
+            );
226
+        } catch (ShareNotFoundException $e) {
227
+            return new JSONResponse(
228
+                ['message' => $e->getMessage()],
229
+                Http::STATUS_BAD_REQUEST
230
+            );
231
+        } catch (ActionNotSupportedException $e) {
232
+            return new JSONResponse(
233
+                ['message' => $e->getMessage()],
234
+                Http::STATUS_NOT_IMPLEMENTED
235
+            );
236
+        } catch (\Exception $e) {
237
+            return new JSONResponse(
238
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
239
+                Http::STATUS_BAD_REQUEST
240
+            );
241
+        }
242
+
243
+
244
+        return new JSONResponse(
245
+            ['id' => $id, 'createdAt' => date()],
246
+            Http::STATUS_CREATED);
247
+
248
+
249
+    }
250
+
251
+    /**
252
+     * map login name to internal LDAP UID if a LDAP backend is in use
253
+     *
254
+     * @param string $uid
255
+     * @return string mixed
256
+     */
257
+    private function mapUid($uid) {
258
+        \OC::$server->getURLGenerator()->linkToDocs('key');
259
+        // FIXME this should be a method in the user management instead
260
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
261
+        \OCP\Util::emitHook(
262
+            '\OCA\Files_Sharing\API\Server2Server',
263
+            'preLoginNameUsedAsUserName',
264
+            array('uid' => &$uid)
265
+        );
266
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
267
+
268
+        return $uid;
269
+    }
270 270
 
271 271
 }
Please login to merge, or discard this patch.