Completed
Pull Request — master (#9345)
by Björn
22:56
created
ocm-provider/index.php 1 patch
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.
apps/federatedfilesharing/lib/ocm/CloudFederationProviderFiles.php 1 patch
Indentation   +229 added lines, -229 removed lines patch added patch discarded remove patch
@@ -38,235 +38,235 @@
 block discarded – undo
38 38
 
39 39
 class CloudFederationProviderFiles implements ICloudFederationProvider {
40 40
 
41
-	/** @var IAppManager */
42
-	private $appManager;
43
-
44
-	/** @var FederatedShareProvider */
45
-	private $federatedShareProvider;
46
-
47
-	/** @var AddressHandler */
48
-	private $addressHandler;
49
-
50
-	/** @var ILogger */
51
-	private $logger;
52
-
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-
56
-	/** @var ICloudIdManager */
57
-	private $cloudIdManager;
58
-
59
-	/** @var IActivityManager */
60
-	private $activityManager;
61
-
62
-	/** @var INotificationManager */
63
-	private $notificationManager;
64
-
65
-	/** @var IURLGenerator */
66
-	private $urlGenerator;
67
-
68
-	/**
69
-	 * CloudFederationProvider constructor.
70
-	 *
71
-	 * @param IAppManager $appManager
72
-	 * @param FederatedShareProvider $federatedShareProvider
73
-	 * @param AddressHandler $addressHandler
74
-	 * @param ILogger $logger
75
-	 * @param IUserManager $userManager
76
-	 * @param ICloudIdManager $cloudIdManager
77
-	 * @param IActivityManager $activityManager
78
-	 * @param INotificationManager $notificationManager
79
-	 * @param IURLGenerator $urlGenerator
80
-	 */
81
-	public function __construct(IAppManager $appManager,
82
-								FederatedShareProvider $federatedShareProvider,
83
-								AddressHandler $addressHandler,
84
-								ILogger $logger,
85
-								IUserManager $userManager,
86
-								ICloudIdManager $cloudIdManager,
87
-								IActivityManager $activityManager,
88
-								INotificationManager $notificationManager,
89
-								IURLGenerator $urlGenerator
90
-	) {
91
-		$this->appManager = $appManager;
92
-		$this->federatedShareProvider = $federatedShareProvider;
93
-		$this->addressHandler = $addressHandler;
94
-		$this->logger = $logger;
95
-		$this->userManager = $userManager;
96
-		$this->cloudIdManager = $cloudIdManager;
97
-		$this->activityManager = $activityManager;
98
-		$this->notificationManager = $notificationManager;
99
-		$this->urlGenerator = $urlGenerator;
100
-	}
101
-
102
-
103
-
104
-	/**
105
-	 * @return string
106
-	 */
107
-	public function getShareType() {
108
-		return 'file';
109
-	}
110
-
111
-	/**
112
-	 * send new share to another server
113
-	 *
114
-	 * @since 14.0.0
115
-	 */
116
-	public function sendShare() {
117
-		// TODO: Implement sendShare() method.
118
-	}
119
-
120
-	/**
121
-	 * share received from another server
122
-	 *
123
-	 * @param ICloudFederationShare $share
124
-	 * @return string provider specific unique ID of the share
125
-	 *
126
-	 * @throws ProviderCouldNotAddShareException
127
-	 * @throws \OCP\AppFramework\QueryException
128
-	 * @throws \OC\HintException
129
-	 * @since 14.0.0
130
-	 */
131
-	public function shareReceived(ICloudFederationShare $share) {
132
-
133
-		if (!$this->isS2SEnabled(true)) {
134
-			throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
135
-		}
136
-
137
-		$protocol = $share->getProtocol();
138
-		if ($protocol['name'] !== 'webdav') {
139
-			throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
140
-		}
141
-
142
-		list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
143
-
144
-		$remote = $remote;
145
-		$token = isset($protocol['options']['access_token']) ? $protocol['options']['access_token'] : null;
146
-		$name = $share->getResourceName();
147
-		$owner = $share->getOwnerDisplayName();
148
-		$sharedBy = $share->getSharedByDisplayName();
149
-		$shareWith = $share->getShareWith();
150
-		$remoteId = $share->getProviderId();
151
-		$sharedByFederatedId = $share->getSharedBy();
152
-		$ownerFederatedId = $share->getOwner();
153
-
154
-		// if no explicit information about the person who created the share was send
155
-		// we assume that the share comes from the owner
156
-		if ($sharedByFederatedId === null) {
157
-			$sharedBy = $owner;
158
-			$sharedByFederatedId = $ownerFederatedId;
159
-		}
160
-
161
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
162
-
163
-			if (!\OCP\Util::isValidFileName($name)) {
164
-				throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
165
-			}
166
-
167
-			// FIXME this should be a method in the user management instead
168
-			$this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
169
-			\OCP\Util::emitHook(
170
-				'\OCA\Files_Sharing\API\Server2Server',
171
-				'preLoginNameUsedAsUserName',
172
-				array('uid' => &$shareWith)
173
-			);
174
-			$this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
175
-
176
-			if (!$this->userManager->userExists($shareWith)) {
177
-				throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
178
-			}
179
-
180
-			\OC_Util::setupFS($shareWith);
181
-
182
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
183
-				\OC::$server->getDatabaseConnection(),
184
-				\OC\Files\Filesystem::getMountManager(),
185
-				\OC\Files\Filesystem::getLoader(),
186
-				\OC::$server->getHTTPClientService(),
187
-				\OC::$server->getNotificationManager(),
188
-				\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
189
-				$shareWith
190
-			);
191
-
192
-			try {
193
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
194
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
195
-
196
-				$event = $this->activityManager->generateEvent();
197
-				$event->setApp('files_sharing')
198
-					->setType('remote_share')
199
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
200
-					->setAffectedUser($shareWith)
201
-					->setObject('remote_share', (int)$shareId, $name);
202
-				\OC::$server->getActivityManager()->publish($event);
203
-
204
-				$notification = $this->notificationManager->createNotification();
205
-				$notification->setApp('files_sharing')
206
-					->setUser($shareWith)
207
-					->setDateTime(new \DateTime())
208
-					->setObject('remote_share', $shareId)
209
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
210
-
211
-				$declineAction = $notification->createAction();
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');
214
-				$notification->addAction($declineAction);
215
-
216
-				$acceptAction = $notification->createAction();
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');
219
-				$notification->addAction($acceptAction);
220
-
221
-				$this->notificationManager->notify($notification);
222
-
223
-				return $shareId;
224
-			} catch (\Exception $e) {
225
-				$this->logger->logException($e, [
226
-					'message' => 'Server can not add remote share.',
227
-					'level' => \OCP\Util::ERROR,
228
-					'app' => 'files_sharing'
229
-				]);
230
-				throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
231
-			}
232
-		}
233
-
234
-		throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
235
-
236
-	}
237
-
238
-	/**
239
-	 * notification received from another server
240
-	 *
241
-	 * @param string $id unique ID of a already existing share
242
-	 * @param array $notification provider specific notification
243
-	 *
244
-	 * @throws \OCP\Federation\Exceptions\ShareNotFoundException
245
-	 *
246
-	 * @since 14.0.0
247
-	 */
248
-	public function notificationReceived($id, $notification) {
249
-		// TODO: Implement notificationReceived() method.
250
-	}
251
-
252
-	/**
253
-	 * check if server-to-server sharing is enabled
254
-	 *
255
-	 * @param bool $incoming
256
-	 * @return bool
257
-	 */
258
-	private function isS2SEnabled($incoming = false) {
259
-
260
-		$result = $this->appManager->isEnabledForUser('files_sharing');
261
-
262
-		if ($incoming) {
263
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
264
-		} else {
265
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
266
-		}
267
-
268
-		return $result;
269
-	}
41
+    /** @var IAppManager */
42
+    private $appManager;
43
+
44
+    /** @var FederatedShareProvider */
45
+    private $federatedShareProvider;
46
+
47
+    /** @var AddressHandler */
48
+    private $addressHandler;
49
+
50
+    /** @var ILogger */
51
+    private $logger;
52
+
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+
56
+    /** @var ICloudIdManager */
57
+    private $cloudIdManager;
58
+
59
+    /** @var IActivityManager */
60
+    private $activityManager;
61
+
62
+    /** @var INotificationManager */
63
+    private $notificationManager;
64
+
65
+    /** @var IURLGenerator */
66
+    private $urlGenerator;
67
+
68
+    /**
69
+     * CloudFederationProvider constructor.
70
+     *
71
+     * @param IAppManager $appManager
72
+     * @param FederatedShareProvider $federatedShareProvider
73
+     * @param AddressHandler $addressHandler
74
+     * @param ILogger $logger
75
+     * @param IUserManager $userManager
76
+     * @param ICloudIdManager $cloudIdManager
77
+     * @param IActivityManager $activityManager
78
+     * @param INotificationManager $notificationManager
79
+     * @param IURLGenerator $urlGenerator
80
+     */
81
+    public function __construct(IAppManager $appManager,
82
+                                FederatedShareProvider $federatedShareProvider,
83
+                                AddressHandler $addressHandler,
84
+                                ILogger $logger,
85
+                                IUserManager $userManager,
86
+                                ICloudIdManager $cloudIdManager,
87
+                                IActivityManager $activityManager,
88
+                                INotificationManager $notificationManager,
89
+                                IURLGenerator $urlGenerator
90
+    ) {
91
+        $this->appManager = $appManager;
92
+        $this->federatedShareProvider = $federatedShareProvider;
93
+        $this->addressHandler = $addressHandler;
94
+        $this->logger = $logger;
95
+        $this->userManager = $userManager;
96
+        $this->cloudIdManager = $cloudIdManager;
97
+        $this->activityManager = $activityManager;
98
+        $this->notificationManager = $notificationManager;
99
+        $this->urlGenerator = $urlGenerator;
100
+    }
101
+
102
+
103
+
104
+    /**
105
+     * @return string
106
+     */
107
+    public function getShareType() {
108
+        return 'file';
109
+    }
110
+
111
+    /**
112
+     * send new share to another server
113
+     *
114
+     * @since 14.0.0
115
+     */
116
+    public function sendShare() {
117
+        // TODO: Implement sendShare() method.
118
+    }
119
+
120
+    /**
121
+     * share received from another server
122
+     *
123
+     * @param ICloudFederationShare $share
124
+     * @return string provider specific unique ID of the share
125
+     *
126
+     * @throws ProviderCouldNotAddShareException
127
+     * @throws \OCP\AppFramework\QueryException
128
+     * @throws \OC\HintException
129
+     * @since 14.0.0
130
+     */
131
+    public function shareReceived(ICloudFederationShare $share) {
132
+
133
+        if (!$this->isS2SEnabled(true)) {
134
+            throw new ProviderCouldNotAddShareException('Server does not support federated cloud sharing', '', Http::STATUS_SERVICE_UNAVAILABLE);
135
+        }
136
+
137
+        $protocol = $share->getProtocol();
138
+        if ($protocol['name'] !== 'webdav') {
139
+            throw new ProviderCouldNotAddShareException('Unsupported protocol for data exchange.', '', Http::STATUS_NOT_IMPLEMENTED);
140
+        }
141
+
142
+        list($ownerUid, $remote) = $this->addressHandler->splitUserRemote($share->getOwner());
143
+
144
+        $remote = $remote;
145
+        $token = isset($protocol['options']['access_token']) ? $protocol['options']['access_token'] : null;
146
+        $name = $share->getResourceName();
147
+        $owner = $share->getOwnerDisplayName();
148
+        $sharedBy = $share->getSharedByDisplayName();
149
+        $shareWith = $share->getShareWith();
150
+        $remoteId = $share->getProviderId();
151
+        $sharedByFederatedId = $share->getSharedBy();
152
+        $ownerFederatedId = $share->getOwner();
153
+
154
+        // if no explicit information about the person who created the share was send
155
+        // we assume that the share comes from the owner
156
+        if ($sharedByFederatedId === null) {
157
+            $sharedBy = $owner;
158
+            $sharedByFederatedId = $ownerFederatedId;
159
+        }
160
+
161
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
162
+
163
+            if (!\OCP\Util::isValidFileName($name)) {
164
+                throw new ProviderCouldNotAddShareException('The mountpoint name contains invalid characters.', '', Http::STATUS_BAD_REQUEST);
165
+            }
166
+
167
+            // FIXME this should be a method in the user management instead
168
+            $this->logger->debug('shareWith before, ' . $shareWith, ['app' => 'files_sharing']);
169
+            \OCP\Util::emitHook(
170
+                '\OCA\Files_Sharing\API\Server2Server',
171
+                'preLoginNameUsedAsUserName',
172
+                array('uid' => &$shareWith)
173
+            );
174
+            $this->logger->debug('shareWith after, ' . $shareWith, ['app' => 'files_sharing']);
175
+
176
+            if (!$this->userManager->userExists($shareWith)) {
177
+                throw new ProviderCouldNotAddShareException('User does not exists', '',Http::STATUS_BAD_REQUEST);
178
+            }
179
+
180
+            \OC_Util::setupFS($shareWith);
181
+
182
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
183
+                \OC::$server->getDatabaseConnection(),
184
+                \OC\Files\Filesystem::getMountManager(),
185
+                \OC\Files\Filesystem::getLoader(),
186
+                \OC::$server->getHTTPClientService(),
187
+                \OC::$server->getNotificationManager(),
188
+                \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
189
+                $shareWith
190
+            );
191
+
192
+            try {
193
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
194
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
195
+
196
+                $event = $this->activityManager->generateEvent();
197
+                $event->setApp('files_sharing')
198
+                    ->setType('remote_share')
199
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
200
+                    ->setAffectedUser($shareWith)
201
+                    ->setObject('remote_share', (int)$shareId, $name);
202
+                \OC::$server->getActivityManager()->publish($event);
203
+
204
+                $notification = $this->notificationManager->createNotification();
205
+                $notification->setApp('files_sharing')
206
+                    ->setUser($shareWith)
207
+                    ->setDateTime(new \DateTime())
208
+                    ->setObject('remote_share', $shareId)
209
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
210
+
211
+                $declineAction = $notification->createAction();
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');
214
+                $notification->addAction($declineAction);
215
+
216
+                $acceptAction = $notification->createAction();
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');
219
+                $notification->addAction($acceptAction);
220
+
221
+                $this->notificationManager->notify($notification);
222
+
223
+                return $shareId;
224
+            } catch (\Exception $e) {
225
+                $this->logger->logException($e, [
226
+                    'message' => 'Server can not add remote share.',
227
+                    'level' => \OCP\Util::ERROR,
228
+                    'app' => 'files_sharing'
229
+                ]);
230
+                throw new ProviderCouldNotAddShareException('internal server error, was not able to add share from ' . $remote, '', HTTP::STATUS_INTERNAL_SERVER_ERROR);
231
+            }
232
+        }
233
+
234
+        throw new ProviderCouldNotAddShareException('server can not add remote share, missing parameter', '', HTTP::STATUS_BAD_REQUEST);
235
+
236
+    }
237
+
238
+    /**
239
+     * notification received from another server
240
+     *
241
+     * @param string $id unique ID of a already existing share
242
+     * @param array $notification provider specific notification
243
+     *
244
+     * @throws \OCP\Federation\Exceptions\ShareNotFoundException
245
+     *
246
+     * @since 14.0.0
247
+     */
248
+    public function notificationReceived($id, $notification) {
249
+        // TODO: Implement notificationReceived() method.
250
+    }
251
+
252
+    /**
253
+     * check if server-to-server sharing is enabled
254
+     *
255
+     * @param bool $incoming
256
+     * @return bool
257
+     */
258
+    private function isS2SEnabled($incoming = false) {
259
+
260
+        $result = $this->appManager->isEnabledForUser('files_sharing');
261
+
262
+        if ($incoming) {
263
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
264
+        } else {
265
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
266
+        }
267
+
268
+        return $result;
269
+    }
270 270
 
271 271
 
272 272
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -39,107 +39,107 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/** @var FederatedShareProvider */
43
-	protected $federatedShareProvider;
42
+    /** @var FederatedShareProvider */
43
+    protected $federatedShareProvider;
44 44
 
45
-	public function __construct() {
46
-		parent::__construct('federatedfilesharing');
45
+    public function __construct() {
46
+        parent::__construct('federatedfilesharing');
47 47
 
48
-		$container = $this->getContainer();
49
-		$server = $container->getServer();
48
+        $container = $this->getContainer();
49
+        $server = $container->getServer();
50 50
 
51
-		$cloudFederationManager = $server->getCloudFederationProviderManager();
52
-		$cloudFederationManager->addCloudFederationProvider('file',
53
-			'Federated Files Sharing',
54
-			function() use ($container) {
55
-				$server = $container->getServer();
56
-				return new CloudFederationProviderFiles(
57
-					$server->getAppManager(),
58
-					$server->query(FederatedShareProvider::class),
59
-					$server->query(AddressHandler::class),
60
-					$server->getLogger(),
61
-					$server->getUserManager(),
62
-					$server->getCloudIdManager(),
63
-					$server->getActivityManager(),
64
-					$server->getNotificationManager(),
65
-					$server->getURLGenerator()
66
-				);
67
-			});
51
+        $cloudFederationManager = $server->getCloudFederationProviderManager();
52
+        $cloudFederationManager->addCloudFederationProvider('file',
53
+            'Federated Files Sharing',
54
+            function() use ($container) {
55
+                $server = $container->getServer();
56
+                return new CloudFederationProviderFiles(
57
+                    $server->getAppManager(),
58
+                    $server->query(FederatedShareProvider::class),
59
+                    $server->query(AddressHandler::class),
60
+                    $server->getLogger(),
61
+                    $server->getUserManager(),
62
+                    $server->getCloudIdManager(),
63
+                    $server->getActivityManager(),
64
+                    $server->getNotificationManager(),
65
+                    $server->getURLGenerator()
66
+                );
67
+            });
68 68
 
69
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
70
-			$addressHandler = new AddressHandler(
71
-				$server->getURLGenerator(),
72
-				$server->getL10N('federatedfilesharing'),
73
-				$server->getCloudIdManager()
74
-			);
75
-			$notification = new Notifications(
76
-				$addressHandler,
77
-				$server->getHTTPClientService(),
78
-				$server->query(\OCP\OCS\IDiscoveryService::class),
79
-				\OC::$server->getJobList()
80
-			);
81
-			return new RequestHandlerController(
82
-				$c->query('AppName'),
83
-				$server->getRequest(),
84
-				$this->getFederatedShareProvider(),
85
-				$server->getDatabaseConnection(),
86
-				$server->getShareManager(),
87
-				$notification,
88
-				$addressHandler,
89
-				$server->getUserManager(),
90
-				$server->getCloudIdManager(),
91
-				$server->getLogger(),
92
-				$server->getCloudFederationFactory(),
93
-				$server->getCloudFederationProviderManager()
94
-			);
95
-		});
96
-	}
69
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
70
+            $addressHandler = new AddressHandler(
71
+                $server->getURLGenerator(),
72
+                $server->getL10N('federatedfilesharing'),
73
+                $server->getCloudIdManager()
74
+            );
75
+            $notification = new Notifications(
76
+                $addressHandler,
77
+                $server->getHTTPClientService(),
78
+                $server->query(\OCP\OCS\IDiscoveryService::class),
79
+                \OC::$server->getJobList()
80
+            );
81
+            return new RequestHandlerController(
82
+                $c->query('AppName'),
83
+                $server->getRequest(),
84
+                $this->getFederatedShareProvider(),
85
+                $server->getDatabaseConnection(),
86
+                $server->getShareManager(),
87
+                $notification,
88
+                $addressHandler,
89
+                $server->getUserManager(),
90
+                $server->getCloudIdManager(),
91
+                $server->getLogger(),
92
+                $server->getCloudFederationFactory(),
93
+                $server->getCloudFederationProviderManager()
94
+            );
95
+        });
96
+    }
97 97
 
98
-	/**
99
-	 * get instance of federated share provider
100
-	 *
101
-	 * @return FederatedShareProvider
102
-	 */
103
-	public function getFederatedShareProvider() {
104
-		if ($this->federatedShareProvider === null) {
105
-			$this->initFederatedShareProvider();
106
-		}
107
-		return $this->federatedShareProvider;
108
-	}
98
+    /**
99
+     * get instance of federated share provider
100
+     *
101
+     * @return FederatedShareProvider
102
+     */
103
+    public function getFederatedShareProvider() {
104
+        if ($this->federatedShareProvider === null) {
105
+            $this->initFederatedShareProvider();
106
+        }
107
+        return $this->federatedShareProvider;
108
+    }
109 109
 
110
-	/**
111
-	 * initialize federated share provider
112
-	 */
113
-	protected function initFederatedShareProvider() {
114
-		$c = $this->getContainer();
115
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
116
-			\OC::$server->getURLGenerator(),
117
-			\OC::$server->getL10N('federatedfilesharing'),
118
-			\OC::$server->getCloudIdManager()
119
-		);
120
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
121
-			$addressHandler,
122
-			\OC::$server->getHTTPClientService(),
123
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
124
-			\OC::$server->getJobList()
125
-		);
126
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
127
-			\OC::$server->getSecureRandom()
128
-		);
110
+    /**
111
+     * initialize federated share provider
112
+     */
113
+    protected function initFederatedShareProvider() {
114
+        $c = $this->getContainer();
115
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
116
+            \OC::$server->getURLGenerator(),
117
+            \OC::$server->getL10N('federatedfilesharing'),
118
+            \OC::$server->getCloudIdManager()
119
+        );
120
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
121
+            $addressHandler,
122
+            \OC::$server->getHTTPClientService(),
123
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
124
+            \OC::$server->getJobList()
125
+        );
126
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
127
+            \OC::$server->getSecureRandom()
128
+        );
129 129
 
130
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
131
-			\OC::$server->getDatabaseConnection(),
132
-			$addressHandler,
133
-			$notifications,
134
-			$tokenHandler,
135
-			\OC::$server->getL10N('federatedfilesharing'),
136
-			\OC::$server->getLogger(),
137
-			\OC::$server->getLazyRootFolder(),
138
-			\OC::$server->getConfig(),
139
-			\OC::$server->getUserManager(),
140
-			\OC::$server->getCloudIdManager(),
141
-			$c->query(IConfig::class)
142
-		);
143
-	}
130
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
131
+            \OC::$server->getDatabaseConnection(),
132
+            $addressHandler,
133
+            $notifications,
134
+            $tokenHandler,
135
+            \OC::$server->getL10N('federatedfilesharing'),
136
+            \OC::$server->getLogger(),
137
+            \OC::$server->getLazyRootFolder(),
138
+            \OC::$server->getConfig(),
139
+            \OC::$server->getUserManager(),
140
+            \OC::$server->getCloudIdManager(),
141
+            $c->query(IConfig::class)
142
+        );
143
+    }
144 144
 
145 145
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 1 patch
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.
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 1 patch
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -47,212 +47,212 @@
 block discarded – undo
47 47
  */
48 48
 class RequestHandlerController extends Controller {
49 49
 
50
-	/** @var ILogger */
51
-	private $logger;
52
-
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-
56
-	/** @var IURLGenerator */
57
-	private $urlGenerator;
58
-
59
-	/** @var ICloudFederationProviderManager */
60
-	private $cloudFederationProviderManager;
61
-
62
-	/** @var Config */
63
-	private $config;
64
-
65
-	/** @var ICloudFederationFactory */
66
-	private $factory;
67
-
68
-	public function __construct($appName,
69
-								IRequest $request,
70
-								ILogger $logger,
71
-								IUserManager $userManager,
72
-								IURLGenerator $urlGenerator,
73
-								ICloudFederationProviderManager $cloudFederationProviderManager,
74
-								Config $config,
75
-								ICloudFederationFactory $factory
76
-	) {
77
-		parent::__construct($appName, $request);
78
-
79
-		$this->logger = $logger;
80
-		$this->userManager = $userManager;
81
-		$this->urlGenerator = $urlGenerator;
82
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
83
-		$this->config = $config;
84
-		$this->factory = $factory;
85
-	}
86
-
87
-	/**
88
-	 * add share
89
-	 *
90
-	 * @NoCSRFRequired
91
-	 * @PublicPage
92
-	 * @BruteForceProtection(action=receiveFederatedShare)
93
-	 *
94
-	 * @param string $shareWith
95
-	 * @param string $name resource name (e.g. document.odt)
96
-	 * @param string $description share description (optional)
97
-	 * @param string $providerId resource UID on the provider side
98
-	 * @param string $owner provider specific UID of the user who owns the resource
99
-	 * @param string $ownerDisplayName display name of the user who shared the item
100
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
101
-	 * @param $sharedByDisplayName display name of the user who shared the resource
102
-	 * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
103
-	 * @param string $shareType ('group' or 'user' share)
104
-	 * @param $resourceType ('file', 'calendar',...)
105
-	 * @return Http\DataResponse|JSONResponse
106
-	 *
107
-	 * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1","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
108
-	 */
109
-	public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
110
-
111
-		if (!$this->config->incomingRequestsEnabled()) {
112
-			return new JSONResponse(
113
-				['message' => 'This server doesn\'t support outgoing federated shares'],
114
-			Http::STATUS_NOT_IMPLEMENTED
115
-			);
116
-		}
117
-
118
-		// check if all required parameters are set
119
-		if ($shareWith === null ||
120
-			$name === null ||
121
-			$providerId === null ||
122
-			$owner === null ||
123
-			$resourceType === null ||
124
-			$shareType === null ||
125
-			!is_array($protocol) ||
126
-			!isset($protocol['name']) ||
127
-			!isset ($protocol['options']) ||
128
-			!is_array($protocol['options'])
129
-		) {
130
-			return new JSONResponse(
131
-				['message' => 'Missing arguments'],
132
-				Http::STATUS_BAD_REQUEST
133
-			);
134
-		}
135
-
136
-		$shareWith = $this->mapUid($shareWith);
137
-
138
-		if (!$this->userManager->userExists($shareWith)) {
139
-			return new JSONResponse(
140
-				['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
141
-				Http::STATUS_BAD_REQUEST
142
-			);
143
-		}
144
-
145
-		// if no explicit display name is given, we use the uid as display name
146
-		$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
147
-		$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
148
-
149
-		// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
150
-		if ($sharedBy === null) {
151
-			$sharedBy = $owner;
152
-			$sharedByDisplayName = $ownerDisplayName;
153
-		}
154
-
155
-		try {
156
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
157
-			$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType);
158
-			$id = $provider->shareReceived($share);
159
-		} catch (ProviderDoesNotExistsException $e) {
160
-			return new JSONResponse(
161
-				['message' => $e->getMessage()],
162
-				Http::STATUS_NOT_IMPLEMENTED
163
-			);
164
-		} catch (ProviderCouldNotAddShareException $e) {
165
-			return new JSONResponse(
166
-				['message' => $e->getMessage()],
167
-				$e->getCode()
168
-			);
169
-		} catch (\Exception $e) {
170
-			return new JSONResponse(
171
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
172
-				Http::STATUS_BAD_REQUEST
173
-			);
174
-		}
175
-
176
-		return new JSONResponse(
177
-			['id' => $id, 'createdAt' => time()],
178
-			Http::STATUS_CREATED);
179
-
180
-	}
181
-
182
-	/**
183
-	 * receive notification about existing share
184
-	 *
185
-	 * @param string $version API version
186
-	 * @param string $name resource name (e.g "file", "calendar",...)
187
-	 * @param string $id unique id of the corresponding item on the receiving site
188
-	 * @param array $notification contain the actual notification, content is defined by cloud federation provider
189
-	 * @return JSONResponse
190
-	 */
191
-	public function receiveNotification($version, $name, $id, $notification) {
192
-		if (!$this->config->incomingRequestsEnabled()) {
193
-			return new JSONResponse(
194
-				['message' => 'This server doesn\'t support outgoing federated shares'],
195
-				Http::STATUS_NOT_IMPLEMENTED
196
-			);
197
-		}
198
-
199
-		// check if all required parameters are set
200
-		if ($name === null ||
201
-			$id === null ||
202
-			!is_array($notification)
203
-		) {
204
-			return new JSONResponse(
205
-				['message' => 'Missing arguments'],
206
-				Http::STATUS_BAD_REQUEST
207
-			);
208
-		}
209
-
210
-		try {
211
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($name);
212
-			$provider->notificationReceived($id, $notification);
213
-		} catch (ProviderDoesNotExistsException $e) {
214
-			return new JSONResponse(
215
-				['message' => $e->getMessage()],
216
-				Http::STATUS_BAD_REQUEST
217
-			);
218
-		} catch (ShareNotFoundException $e) {
219
-			return new JSONResponse(
220
-				['message' => $e->getMessage()],
221
-				Http::STATUS_BAD_REQUEST
222
-			);
223
-		} catch (\Exception $e) {
224
-			return new JSONResponse(
225
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
226
-				Http::STATUS_BAD_REQUEST
227
-			);
228
-		}
229
-
230
-
231
-		return new JSONResponse(
232
-			['id' => $id, 'createdAt' => date()],
233
-			Http::STATUS_CREATED);
234
-
235
-
236
-	}
237
-
238
-	/**
239
-	 * map login name to internal LDAP UID if a LDAP backend is in use
240
-	 *
241
-	 * @param string $uid
242
-	 * @return string mixed
243
-	 */
244
-	private function mapUid($uid) {
245
-		\OC::$server->getURLGenerator()->linkToDocs('key');
246
-		// FIXME this should be a method in the user management instead
247
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
248
-		\OCP\Util::emitHook(
249
-			'\OCA\Files_Sharing\API\Server2Server',
250
-			'preLoginNameUsedAsUserName',
251
-			array('uid' => &$uid)
252
-		);
253
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
254
-
255
-		return $uid;
256
-	}
50
+    /** @var ILogger */
51
+    private $logger;
52
+
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+
56
+    /** @var IURLGenerator */
57
+    private $urlGenerator;
58
+
59
+    /** @var ICloudFederationProviderManager */
60
+    private $cloudFederationProviderManager;
61
+
62
+    /** @var Config */
63
+    private $config;
64
+
65
+    /** @var ICloudFederationFactory */
66
+    private $factory;
67
+
68
+    public function __construct($appName,
69
+                                IRequest $request,
70
+                                ILogger $logger,
71
+                                IUserManager $userManager,
72
+                                IURLGenerator $urlGenerator,
73
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
74
+                                Config $config,
75
+                                ICloudFederationFactory $factory
76
+    ) {
77
+        parent::__construct($appName, $request);
78
+
79
+        $this->logger = $logger;
80
+        $this->userManager = $userManager;
81
+        $this->urlGenerator = $urlGenerator;
82
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
83
+        $this->config = $config;
84
+        $this->factory = $factory;
85
+    }
86
+
87
+    /**
88
+     * add share
89
+     *
90
+     * @NoCSRFRequired
91
+     * @PublicPage
92
+     * @BruteForceProtection(action=receiveFederatedShare)
93
+     *
94
+     * @param string $shareWith
95
+     * @param string $name resource name (e.g. document.odt)
96
+     * @param string $description share description (optional)
97
+     * @param string $providerId resource UID on the provider side
98
+     * @param string $owner provider specific UID of the user who owns the resource
99
+     * @param string $ownerDisplayName display name of the user who shared the item
100
+     * @param string $sharedBy provider specific UID of the user who shared the resource
101
+     * @param $sharedByDisplayName display name of the user who shared the resource
102
+     * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
103
+     * @param string $shareType ('group' or 'user' share)
104
+     * @param $resourceType ('file', 'calendar',...)
105
+     * @return Http\DataResponse|JSONResponse
106
+     *
107
+     * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1","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
108
+     */
109
+    public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
110
+
111
+        if (!$this->config->incomingRequestsEnabled()) {
112
+            return new JSONResponse(
113
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
114
+            Http::STATUS_NOT_IMPLEMENTED
115
+            );
116
+        }
117
+
118
+        // check if all required parameters are set
119
+        if ($shareWith === null ||
120
+            $name === null ||
121
+            $providerId === null ||
122
+            $owner === null ||
123
+            $resourceType === null ||
124
+            $shareType === null ||
125
+            !is_array($protocol) ||
126
+            !isset($protocol['name']) ||
127
+            !isset ($protocol['options']) ||
128
+            !is_array($protocol['options'])
129
+        ) {
130
+            return new JSONResponse(
131
+                ['message' => 'Missing arguments'],
132
+                Http::STATUS_BAD_REQUEST
133
+            );
134
+        }
135
+
136
+        $shareWith = $this->mapUid($shareWith);
137
+
138
+        if (!$this->userManager->userExists($shareWith)) {
139
+            return new JSONResponse(
140
+                ['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
141
+                Http::STATUS_BAD_REQUEST
142
+            );
143
+        }
144
+
145
+        // if no explicit display name is given, we use the uid as display name
146
+        $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
147
+        $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
148
+
149
+        // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
150
+        if ($sharedBy === null) {
151
+            $sharedBy = $owner;
152
+            $sharedByDisplayName = $ownerDisplayName;
153
+        }
154
+
155
+        try {
156
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
157
+            $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType);
158
+            $id = $provider->shareReceived($share);
159
+        } catch (ProviderDoesNotExistsException $e) {
160
+            return new JSONResponse(
161
+                ['message' => $e->getMessage()],
162
+                Http::STATUS_NOT_IMPLEMENTED
163
+            );
164
+        } catch (ProviderCouldNotAddShareException $e) {
165
+            return new JSONResponse(
166
+                ['message' => $e->getMessage()],
167
+                $e->getCode()
168
+            );
169
+        } catch (\Exception $e) {
170
+            return new JSONResponse(
171
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
172
+                Http::STATUS_BAD_REQUEST
173
+            );
174
+        }
175
+
176
+        return new JSONResponse(
177
+            ['id' => $id, 'createdAt' => time()],
178
+            Http::STATUS_CREATED);
179
+
180
+    }
181
+
182
+    /**
183
+     * receive notification about existing share
184
+     *
185
+     * @param string $version API version
186
+     * @param string $name resource name (e.g "file", "calendar",...)
187
+     * @param string $id unique id of the corresponding item on the receiving site
188
+     * @param array $notification contain the actual notification, content is defined by cloud federation provider
189
+     * @return JSONResponse
190
+     */
191
+    public function receiveNotification($version, $name, $id, $notification) {
192
+        if (!$this->config->incomingRequestsEnabled()) {
193
+            return new JSONResponse(
194
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
195
+                Http::STATUS_NOT_IMPLEMENTED
196
+            );
197
+        }
198
+
199
+        // check if all required parameters are set
200
+        if ($name === null ||
201
+            $id === null ||
202
+            !is_array($notification)
203
+        ) {
204
+            return new JSONResponse(
205
+                ['message' => 'Missing arguments'],
206
+                Http::STATUS_BAD_REQUEST
207
+            );
208
+        }
209
+
210
+        try {
211
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($name);
212
+            $provider->notificationReceived($id, $notification);
213
+        } catch (ProviderDoesNotExistsException $e) {
214
+            return new JSONResponse(
215
+                ['message' => $e->getMessage()],
216
+                Http::STATUS_BAD_REQUEST
217
+            );
218
+        } catch (ShareNotFoundException $e) {
219
+            return new JSONResponse(
220
+                ['message' => $e->getMessage()],
221
+                Http::STATUS_BAD_REQUEST
222
+            );
223
+        } catch (\Exception $e) {
224
+            return new JSONResponse(
225
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
226
+                Http::STATUS_BAD_REQUEST
227
+            );
228
+        }
229
+
230
+
231
+        return new JSONResponse(
232
+            ['id' => $id, 'createdAt' => date()],
233
+            Http::STATUS_CREATED);
234
+
235
+
236
+    }
237
+
238
+    /**
239
+     * map login name to internal LDAP UID if a LDAP backend is in use
240
+     *
241
+     * @param string $uid
242
+     * @return string mixed
243
+     */
244
+    private function mapUid($uid) {
245
+        \OC::$server->getURLGenerator()->linkToDocs('key');
246
+        // FIXME this should be a method in the user management instead
247
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
248
+        \OCP\Util::emitHook(
249
+            '\OCA\Files_Sharing\API\Server2Server',
250
+            'preLoginNameUsedAsUserName',
251
+            array('uid' => &$uid)
252
+        );
253
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
254
+
255
+        return $uid;
256
+    }
257 257
 
258 258
 }
Please login to merge, or discard this patch.
lib/public/Federation/ICloudFederationProvider.php 1 patch
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -36,44 +36,44 @@
 block discarded – undo
36 36
 
37 37
 interface ICloudFederationProvider {
38 38
 
39
-	/**
40
-	 * get the name of the share type, handled by this provider
41
-	 *
42
-	 * @return string
43
-	 *
44
-	 * @since 14.0.0
45
-	 */
46
-	public function getShareType();
39
+    /**
40
+     * get the name of the share type, handled by this provider
41
+     *
42
+     * @return string
43
+     *
44
+     * @since 14.0.0
45
+     */
46
+    public function getShareType();
47 47
 
48
-	/**
49
-	 * send new share to another server
50
-	 *
51
-	 * @since 14.0.0
52
-	 */
53
-	public function sendShare();
48
+    /**
49
+     * send new share to another server
50
+     *
51
+     * @since 14.0.0
52
+     */
53
+    public function sendShare();
54 54
 
55
-	/**
56
-	 * share received from another server
57
-	 *
58
-	 * @param ICloudFederationShare $share
59
-	 * @return string provider specific unique ID of the share
60
-	 *
61
-	 * @throws ProviderCouldNotAddShareException
62
-	 *
63
-	 * @since 14.0.0
64
-	 */
65
-	public function shareReceived(ICloudFederationShare $share);
55
+    /**
56
+     * share received from another server
57
+     *
58
+     * @param ICloudFederationShare $share
59
+     * @return string provider specific unique ID of the share
60
+     *
61
+     * @throws ProviderCouldNotAddShareException
62
+     *
63
+     * @since 14.0.0
64
+     */
65
+    public function shareReceived(ICloudFederationShare $share);
66 66
 
67
-	/**
68
-	 * notification received from another server
69
-	 *
70
-	 * @param string $id unique ID of a already existing share
71
-	 * @param array $notification provider specific notification
72
-	 *
73
-	 * @throws ShareNotFoundException
74
-	 *
75
-	 * @since 14.0.0
76
-	 */
77
-	public function notificationReceived($id, $notification);
67
+    /**
68
+     * notification received from another server
69
+     *
70
+     * @param string $id unique ID of a already existing share
71
+     * @param array $notification provider specific notification
72
+     *
73
+     * @throws ShareNotFoundException
74
+     *
75
+     * @since 14.0.0
76
+     */
77
+    public function notificationReceived($id, $notification);
78 78
 
79 79
 }
Please login to merge, or discard this patch.