Completed
Pull Request — master (#3838)
by Vars
12:18
created
apps/federatedfilesharing/lib/DiscoveryManager.php 2 patches
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -39,105 +39,105 @@
 block discarded – undo
39 39
  * @package OCA\FederatedFileSharing
40 40
  */
41 41
 class DiscoveryManager {
42
-	/** @var ICache */
43
-	private $cache;
44
-	/** @var IClient */
45
-	private $client;
42
+    /** @var ICache */
43
+    private $cache;
44
+    /** @var IClient */
45
+    private $client;
46 46
 
47
-	/**
48
-	 * @param ICacheFactory $cacheFactory
49
-	 * @param IClientService $clientService
50
-	 */
51
-	public function __construct(ICacheFactory $cacheFactory,
52
-								IClientService $clientService) {
53
-		$this->cache = $cacheFactory->create('ocs-discovery');
54
-		$this->client = $clientService->newClient();
55
-	}
47
+    /**
48
+     * @param ICacheFactory $cacheFactory
49
+     * @param IClientService $clientService
50
+     */
51
+    public function __construct(ICacheFactory $cacheFactory,
52
+                                IClientService $clientService) {
53
+        $this->cache = $cacheFactory->create('ocs-discovery');
54
+        $this->client = $clientService->newClient();
55
+    }
56 56
 
57
-	/**
58
-	 * Returns whether the specified URL includes only safe characters, if not
59
-	 * returns false
60
-	 *
61
-	 * @param string $url
62
-	 * @return bool
63
-	 */
64
-	private function isSafeUrl($url) {
65
-		return (bool)preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
66
-	}
57
+    /**
58
+     * Returns whether the specified URL includes only safe characters, if not
59
+     * returns false
60
+     *
61
+     * @param string $url
62
+     * @return bool
63
+     */
64
+    private function isSafeUrl($url) {
65
+        return (bool)preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
66
+    }
67 67
 
68
-	/**
69
-	 * Discover the actual data and do some naive caching to ensure that the data
70
-	 * is not requested multiple times.
71
-	 *
72
-	 * If no valid discovery data is found the Nextcloud defaults are returned.
73
-	 *
74
-	 * @param string $remote
75
-	 * @return array
76
-	 */
77
-	private function discover($remote) {
78
-		// Check if something is in the cache
79
-		if($cacheData = $this->cache->get($remote)) {
80
-			return json_decode($cacheData, true);
81
-		}
68
+    /**
69
+     * Discover the actual data and do some naive caching to ensure that the data
70
+     * is not requested multiple times.
71
+     *
72
+     * If no valid discovery data is found the Nextcloud defaults are returned.
73
+     *
74
+     * @param string $remote
75
+     * @return array
76
+     */
77
+    private function discover($remote) {
78
+        // Check if something is in the cache
79
+        if($cacheData = $this->cache->get($remote)) {
80
+            return json_decode($cacheData, true);
81
+        }
82 82
 
83
-		// Default response body
84
-		$discoveredServices = [
85
-			'webdav' => '/public.php/webdav',
86
-			'share' => '/ocs/v1.php/cloud/shares',
87
-		];
83
+        // Default response body
84
+        $discoveredServices = [
85
+            'webdav' => '/public.php/webdav',
86
+            'share' => '/ocs/v1.php/cloud/shares',
87
+        ];
88 88
 
89
-		// Read the data from the response body
90
-		try {
91
-			$response = $this->client->get($remote . '/ocs-provider/', [
92
-				'timeout' => 10,
93
-				'connect_timeout' => 10,
94
-			]);
95
-			if($response->getStatusCode() === 200) {
96
-				$decodedService = json_decode($response->getBody(), true);
97
-				if(is_array($decodedService)) {
98
-					$endpoints = [
99
-						'webdav',
100
-						'share',
101
-					];
89
+        // Read the data from the response body
90
+        try {
91
+            $response = $this->client->get($remote . '/ocs-provider/', [
92
+                'timeout' => 10,
93
+                'connect_timeout' => 10,
94
+            ]);
95
+            if($response->getStatusCode() === 200) {
96
+                $decodedService = json_decode($response->getBody(), true);
97
+                if(is_array($decodedService)) {
98
+                    $endpoints = [
99
+                        'webdav',
100
+                        'share',
101
+                    ];
102 102
 
103
-					foreach($endpoints as $endpoint) {
104
-						if(isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
-							$endpointUrl = (string)$decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
-							if($this->isSafeUrl($endpointUrl)) {
107
-								$discoveredServices[$endpoint] = $endpointUrl;
108
-							}
109
-						}
110
-					}
111
-				}
112
-			}
113
-		} catch (ClientException $e) {
114
-			// Don't throw any exception since exceptions are handled before
115
-		} catch (ConnectException $e) {
116
-			// Don't throw any exception since exceptions are handled before
117
-		}
103
+                    foreach($endpoints as $endpoint) {
104
+                        if(isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
+                            $endpointUrl = (string)$decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
+                            if($this->isSafeUrl($endpointUrl)) {
107
+                                $discoveredServices[$endpoint] = $endpointUrl;
108
+                            }
109
+                        }
110
+                    }
111
+                }
112
+            }
113
+        } catch (ClientException $e) {
114
+            // Don't throw any exception since exceptions are handled before
115
+        } catch (ConnectException $e) {
116
+            // Don't throw any exception since exceptions are handled before
117
+        }
118 118
 
119
-		// Write into cache
120
-		$this->cache->set($remote, json_encode($discoveredServices));
121
-		return $discoveredServices;
122
-	}
119
+        // Write into cache
120
+        $this->cache->set($remote, json_encode($discoveredServices));
121
+        return $discoveredServices;
122
+    }
123 123
 
124
-	/**
125
-	 * Return the public WebDAV endpoint used by the specified remote
126
-	 *
127
-	 * @param string $host
128
-	 * @return string
129
-	 */
130
-	public function getWebDavEndpoint($host) {
131
-		return $this->discover($host)['webdav'];
132
-	}
124
+    /**
125
+     * Return the public WebDAV endpoint used by the specified remote
126
+     *
127
+     * @param string $host
128
+     * @return string
129
+     */
130
+    public function getWebDavEndpoint($host) {
131
+        return $this->discover($host)['webdav'];
132
+    }
133 133
 
134
-	/**
135
-	 * Return the sharing endpoint used by the specified remote
136
-	 *
137
-	 * @param string $host
138
-	 * @return string
139
-	 */
140
-	public function getShareEndpoint($host) {
141
-		return $this->discover($host)['share'];
142
-	}
134
+    /**
135
+     * Return the sharing endpoint used by the specified remote
136
+     *
137
+     * @param string $host
138
+     * @return string
139
+     */
140
+    public function getShareEndpoint($host) {
141
+        return $this->discover($host)['share'];
142
+    }
143 143
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 	 * @return bool
63 63
 	 */
64 64
 	private function isSafeUrl($url) {
65
-		return (bool)preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
65
+		return (bool) preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
66 66
 	}
67 67
 
68 68
 	/**
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 */
77 77
 	private function discover($remote) {
78 78
 		// Check if something is in the cache
79
-		if($cacheData = $this->cache->get($remote)) {
79
+		if ($cacheData = $this->cache->get($remote)) {
80 80
 			return json_decode($cacheData, true);
81 81
 		}
82 82
 
@@ -88,22 +88,22 @@  discard block
 block discarded – undo
88 88
 
89 89
 		// Read the data from the response body
90 90
 		try {
91
-			$response = $this->client->get($remote . '/ocs-provider/', [
91
+			$response = $this->client->get($remote.'/ocs-provider/', [
92 92
 				'timeout' => 10,
93 93
 				'connect_timeout' => 10,
94 94
 			]);
95
-			if($response->getStatusCode() === 200) {
95
+			if ($response->getStatusCode() === 200) {
96 96
 				$decodedService = json_decode($response->getBody(), true);
97
-				if(is_array($decodedService)) {
97
+				if (is_array($decodedService)) {
98 98
 					$endpoints = [
99 99
 						'webdav',
100 100
 						'share',
101 101
 					];
102 102
 
103
-					foreach($endpoints as $endpoint) {
104
-						if(isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
-							$endpointUrl = (string)$decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
-							if($this->isSafeUrl($endpointUrl)) {
103
+					foreach ($endpoints as $endpoint) {
104
+						if (isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
+							$endpointUrl = (string) $decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
+							if ($this->isSafeUrl($endpointUrl)) {
107 107
 								$discoveredServices[$endpoint] = $endpointUrl;
108 108
 							}
109 109
 						}
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php 2 patches
Indentation   +282 added lines, -282 removed lines patch added patch discarded remove patch
@@ -54,287 +54,287 @@
 block discarded – undo
54 54
  */
55 55
 class MountPublicLinkController extends Controller {
56 56
 
57
-	/** @var FederatedShareProvider */
58
-	private $federatedShareProvider;
59
-
60
-	/** @var AddressHandler */
61
-	private $addressHandler;
62
-
63
-	/** @var IManager  */
64
-	private $shareManager;
65
-
66
-	/** @var  ISession */
67
-	private $session;
68
-
69
-	/** @var IL10N */
70
-	private $l;
71
-
72
-	/** @var IUserSession */
73
-	private $userSession;
74
-
75
-	/** @var IClientService */
76
-	private $clientService;
77
-
78
-	/** @var ICloudIdManager  */
79
-	private $cloudIdManager;
80
-
81
-	/**
82
-	 * MountPublicLinkController constructor.
83
-	 *
84
-	 * @param string $appName
85
-	 * @param IRequest $request
86
-	 * @param FederatedShareProvider $federatedShareProvider
87
-	 * @param IManager $shareManager
88
-	 * @param AddressHandler $addressHandler
89
-	 * @param ISession $session
90
-	 * @param IL10N $l
91
-	 * @param IUserSession $userSession
92
-	 * @param IClientService $clientService
93
-	 * @param ICloudIdManager $cloudIdManager
94
-	 */
95
-	public function __construct($appName,
96
-								IRequest $request,
97
-								FederatedShareProvider $federatedShareProvider,
98
-								IManager $shareManager,
99
-								AddressHandler $addressHandler,
100
-								ISession $session,
101
-								IL10N $l,
102
-								IUserSession $userSession,
103
-								IClientService $clientService,
104
-								ICloudIdManager $cloudIdManager
105
-	) {
106
-		parent::__construct($appName, $request);
107
-
108
-		$this->federatedShareProvider = $federatedShareProvider;
109
-		$this->shareManager = $shareManager;
110
-		$this->addressHandler = $addressHandler;
111
-		$this->session = $session;
112
-		$this->l = $l;
113
-		$this->userSession = $userSession;
114
-		$this->clientService = $clientService;
115
-		$this->cloudIdManager = $cloudIdManager;
116
-	}
117
-
118
-	/**
119
-	 * send federated share to a user of a public link
120
-	 *
121
-	 * @NoCSRFRequired
122
-	 * @PublicPage
123
-	 * @BruteForceProtection publicLink2FederatedShare
124
-	 *
125
-	 * @param string $shareWith
126
-	 * @param string $token
127
-	 * @param string $password
128
-	 * @return JSONResponse
129
-	 */
130
-	public function createFederatedShare($shareWith, $token, $password = '') {
131
-
132
-		if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
-			return new JSONResponse(
134
-				['message' => 'This server doesn\'t support outgoing federated shares'],
135
-				Http::STATUS_BAD_REQUEST
136
-			);
137
-		}
138
-
139
-		try {
140
-			list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
-			$share = $this->shareManager->getShareByToken($token);
142
-		} catch (HintException $e) {
143
-			return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
-		}
145
-
146
-		// make sure that user is authenticated in case of a password protected link
147
-		$storedPassword = $share->getPassword();
148
-		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
-			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
151
-			return new JSONResponse(
152
-				['message' => 'No permission to access the share'],
153
-				Http::STATUS_BAD_REQUEST
154
-			);
155
-		}
156
-
157
-		$share->setSharedWith($shareWith);
158
-
159
-		try {
160
-			$this->federatedShareProvider->create($share);
161
-		} catch (\Exception $e) {
162
-			return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
163
-		}
164
-
165
-		return new JSONResponse(['remoteUrl' => $server]);
166
-	}
167
-
168
-	/**
169
-	 * ask other server to get a federated share
170
-	 *
171
-	 * @NoAdminRequired
172
-	 *
173
-	 * @param string $token
174
-	 * @param string $remote
175
-	 * @param string $password
176
-	 * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
177
-	 * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
178
-	 * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
179
-	 * @return JSONResponse
180
-	 */
181
-	public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
182
-		// check if server admin allows to mount public links from other servers
183
-		if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
184
-			return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
185
-		}
186
-
187
-		$cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
188
-
189
-		$httpClient = $this->clientService->newClient();
190
-
191
-		try {
192
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
193
-				[
194
-					'body' =>
195
-						[
196
-							'token' => $token,
197
-							'shareWith' => rtrim($cloudId->getId(), '/'),
198
-							'password' => $password
199
-						],
200
-					'connect_timeout' => 10,
201
-				]
202
-			);
203
-		} catch (\Exception $e) {
204
-			if (empty($password)) {
205
-				$message = $this->l->t("Couldn't establish a federated share.");
206
-			} else {
207
-				$message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
208
-			}
209
-			return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
210
-		}
211
-
212
-		$body = $response->getBody();
213
-		$result = json_decode($body, true);
214
-
215
-		if (is_array($result) && isset($result['remoteUrl'])) {
216
-			return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
217
-		}
218
-
219
-		// if we doesn't get the expected response we assume that we try to add
220
-		// a federated share from a Nextcloud <= 9 server
221
-		return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
222
-	}
223
-
224
-	/**
225
-	 * Allow Nextcloud to mount a public link directly
226
-	 *
227
-	 * This code was copied from the apps/files_sharing/ajax/external.php with
228
-	 * minimal changes, just to guarantee backward compatibility
229
-	 *
230
-	 * ToDo: Remove this method once Nextcloud 9 reaches end of life
231
-	 *
232
-	 * @param string $token
233
-	 * @param string $remote
234
-	 * @param string $password
235
-	 * @param string $name
236
-	 * @param string $owner
237
-	 * @param string $ownerDisplayName
238
-	 * @return JSONResponse
239
-	 */
240
-	private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
241
-
242
-		// Check for invalid name
243
-		if (!Util::isValidFileName($name)) {
244
-			return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
245
-		}
246
-		$currentUser = $this->userSession->getUser()->getUID();
247
-		$currentServer = $this->addressHandler->generateRemoteURL();
248
-		if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
249
-			return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
250
-		}
251
-		$discoveryManager = new DiscoveryManager(
252
-			\OC::$server->getMemCacheFactory(),
253
-			\OC::$server->getHTTPClientService()
254
-		);
255
-		$externalManager = new Manager(
256
-			\OC::$server->getDatabaseConnection(),
257
-			Filesystem::getMountManager(),
258
-			Filesystem::getLoader(),
259
-			\OC::$server->getHTTPClientService(),
260
-			\OC::$server->getNotificationManager(),
261
-			$discoveryManager,
262
-			\OC::$server->getUserSession()->getUser()->getUID()
263
-		);
264
-
265
-		// check for ssl cert
266
-
267
-		if (strpos($remote, 'https') === 0) {
268
-			try {
269
-				$client = $this->clientService->newClient();
270
-				$client->get($remote, [
271
-					'timeout' => 10,
272
-					'connect_timeout' => 10,
273
-				])->getBody();
274
-			} catch (\Exception $e) {
275
-				return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
276
-			}
277
-		}
278
-		$mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
279
-		/**
280
-		 * @var \OCA\Files_Sharing\External\Storage $storage
281
-		 */
282
-		$storage = $mount->getStorage();
283
-		try {
284
-			// check if storage exists
285
-			$storage->checkStorageAvailability();
286
-		} catch (StorageInvalidException $e) {
287
-			// note: checkStorageAvailability will already remove the invalid share
288
-			Util::writeLog(
289
-				'federatedfilesharing',
290
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
291
-				Util::DEBUG
292
-			);
293
-			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
294
-		} catch (\Exception $e) {
295
-			Util::writeLog(
296
-				'federatedfilesharing',
297
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
298
-				Util::DEBUG
299
-			);
300
-			$externalManager->removeShare($mount->getMountPoint());
301
-			return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
302
-		}
303
-		$result = $storage->file_exists('');
304
-		if ($result) {
305
-			try {
306
-				$storage->getScanner()->scanAll();
307
-				return new JSONResponse(
308
-					[
309
-						'message' => $this->l->t('Federated Share successfully added'),
310
-						'legacyMount' => '1'
311
-					]
312
-				);
313
-			} catch (StorageInvalidException $e) {
314
-				Util::writeLog(
315
-					'federatedfilesharing',
316
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
317
-					Util::DEBUG
318
-				);
319
-				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
320
-			} catch (\Exception $e) {
321
-				Util::writeLog(
322
-					'federatedfilesharing',
323
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
324
-					Util::DEBUG
325
-				);
326
-				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
327
-			}
328
-		} else {
329
-			$externalManager->removeShare($mount->getMountPoint());
330
-			Util::writeLog(
331
-				'federatedfilesharing',
332
-				'Couldn\'t add remote share',
333
-				Util::DEBUG
334
-			);
335
-			return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
336
-		}
337
-
338
-	}
57
+    /** @var FederatedShareProvider */
58
+    private $federatedShareProvider;
59
+
60
+    /** @var AddressHandler */
61
+    private $addressHandler;
62
+
63
+    /** @var IManager  */
64
+    private $shareManager;
65
+
66
+    /** @var  ISession */
67
+    private $session;
68
+
69
+    /** @var IL10N */
70
+    private $l;
71
+
72
+    /** @var IUserSession */
73
+    private $userSession;
74
+
75
+    /** @var IClientService */
76
+    private $clientService;
77
+
78
+    /** @var ICloudIdManager  */
79
+    private $cloudIdManager;
80
+
81
+    /**
82
+     * MountPublicLinkController constructor.
83
+     *
84
+     * @param string $appName
85
+     * @param IRequest $request
86
+     * @param FederatedShareProvider $federatedShareProvider
87
+     * @param IManager $shareManager
88
+     * @param AddressHandler $addressHandler
89
+     * @param ISession $session
90
+     * @param IL10N $l
91
+     * @param IUserSession $userSession
92
+     * @param IClientService $clientService
93
+     * @param ICloudIdManager $cloudIdManager
94
+     */
95
+    public function __construct($appName,
96
+                                IRequest $request,
97
+                                FederatedShareProvider $federatedShareProvider,
98
+                                IManager $shareManager,
99
+                                AddressHandler $addressHandler,
100
+                                ISession $session,
101
+                                IL10N $l,
102
+                                IUserSession $userSession,
103
+                                IClientService $clientService,
104
+                                ICloudIdManager $cloudIdManager
105
+    ) {
106
+        parent::__construct($appName, $request);
107
+
108
+        $this->federatedShareProvider = $federatedShareProvider;
109
+        $this->shareManager = $shareManager;
110
+        $this->addressHandler = $addressHandler;
111
+        $this->session = $session;
112
+        $this->l = $l;
113
+        $this->userSession = $userSession;
114
+        $this->clientService = $clientService;
115
+        $this->cloudIdManager = $cloudIdManager;
116
+    }
117
+
118
+    /**
119
+     * send federated share to a user of a public link
120
+     *
121
+     * @NoCSRFRequired
122
+     * @PublicPage
123
+     * @BruteForceProtection publicLink2FederatedShare
124
+     *
125
+     * @param string $shareWith
126
+     * @param string $token
127
+     * @param string $password
128
+     * @return JSONResponse
129
+     */
130
+    public function createFederatedShare($shareWith, $token, $password = '') {
131
+
132
+        if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
+            return new JSONResponse(
134
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
135
+                Http::STATUS_BAD_REQUEST
136
+            );
137
+        }
138
+
139
+        try {
140
+            list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
+            $share = $this->shareManager->getShareByToken($token);
142
+        } catch (HintException $e) {
143
+            return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
+        }
145
+
146
+        // make sure that user is authenticated in case of a password protected link
147
+        $storedPassword = $share->getPassword();
148
+        $authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
+            $this->shareManager->checkPassword($share, $password);
150
+        if (!empty($storedPassword) && !$authenticated ) {
151
+            return new JSONResponse(
152
+                ['message' => 'No permission to access the share'],
153
+                Http::STATUS_BAD_REQUEST
154
+            );
155
+        }
156
+
157
+        $share->setSharedWith($shareWith);
158
+
159
+        try {
160
+            $this->federatedShareProvider->create($share);
161
+        } catch (\Exception $e) {
162
+            return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
163
+        }
164
+
165
+        return new JSONResponse(['remoteUrl' => $server]);
166
+    }
167
+
168
+    /**
169
+     * ask other server to get a federated share
170
+     *
171
+     * @NoAdminRequired
172
+     *
173
+     * @param string $token
174
+     * @param string $remote
175
+     * @param string $password
176
+     * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
177
+     * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
178
+     * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
179
+     * @return JSONResponse
180
+     */
181
+    public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
182
+        // check if server admin allows to mount public links from other servers
183
+        if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
184
+            return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
185
+        }
186
+
187
+        $cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
188
+
189
+        $httpClient = $this->clientService->newClient();
190
+
191
+        try {
192
+            $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
193
+                [
194
+                    'body' =>
195
+                        [
196
+                            'token' => $token,
197
+                            'shareWith' => rtrim($cloudId->getId(), '/'),
198
+                            'password' => $password
199
+                        ],
200
+                    'connect_timeout' => 10,
201
+                ]
202
+            );
203
+        } catch (\Exception $e) {
204
+            if (empty($password)) {
205
+                $message = $this->l->t("Couldn't establish a federated share.");
206
+            } else {
207
+                $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
208
+            }
209
+            return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
210
+        }
211
+
212
+        $body = $response->getBody();
213
+        $result = json_decode($body, true);
214
+
215
+        if (is_array($result) && isset($result['remoteUrl'])) {
216
+            return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
217
+        }
218
+
219
+        // if we doesn't get the expected response we assume that we try to add
220
+        // a federated share from a Nextcloud <= 9 server
221
+        return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
222
+    }
223
+
224
+    /**
225
+     * Allow Nextcloud to mount a public link directly
226
+     *
227
+     * This code was copied from the apps/files_sharing/ajax/external.php with
228
+     * minimal changes, just to guarantee backward compatibility
229
+     *
230
+     * ToDo: Remove this method once Nextcloud 9 reaches end of life
231
+     *
232
+     * @param string $token
233
+     * @param string $remote
234
+     * @param string $password
235
+     * @param string $name
236
+     * @param string $owner
237
+     * @param string $ownerDisplayName
238
+     * @return JSONResponse
239
+     */
240
+    private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
241
+
242
+        // Check for invalid name
243
+        if (!Util::isValidFileName($name)) {
244
+            return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
245
+        }
246
+        $currentUser = $this->userSession->getUser()->getUID();
247
+        $currentServer = $this->addressHandler->generateRemoteURL();
248
+        if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
249
+            return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
250
+        }
251
+        $discoveryManager = new DiscoveryManager(
252
+            \OC::$server->getMemCacheFactory(),
253
+            \OC::$server->getHTTPClientService()
254
+        );
255
+        $externalManager = new Manager(
256
+            \OC::$server->getDatabaseConnection(),
257
+            Filesystem::getMountManager(),
258
+            Filesystem::getLoader(),
259
+            \OC::$server->getHTTPClientService(),
260
+            \OC::$server->getNotificationManager(),
261
+            $discoveryManager,
262
+            \OC::$server->getUserSession()->getUser()->getUID()
263
+        );
264
+
265
+        // check for ssl cert
266
+
267
+        if (strpos($remote, 'https') === 0) {
268
+            try {
269
+                $client = $this->clientService->newClient();
270
+                $client->get($remote, [
271
+                    'timeout' => 10,
272
+                    'connect_timeout' => 10,
273
+                ])->getBody();
274
+            } catch (\Exception $e) {
275
+                return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
276
+            }
277
+        }
278
+        $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
279
+        /**
280
+         * @var \OCA\Files_Sharing\External\Storage $storage
281
+         */
282
+        $storage = $mount->getStorage();
283
+        try {
284
+            // check if storage exists
285
+            $storage->checkStorageAvailability();
286
+        } catch (StorageInvalidException $e) {
287
+            // note: checkStorageAvailability will already remove the invalid share
288
+            Util::writeLog(
289
+                'federatedfilesharing',
290
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
291
+                Util::DEBUG
292
+            );
293
+            return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
294
+        } catch (\Exception $e) {
295
+            Util::writeLog(
296
+                'federatedfilesharing',
297
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
298
+                Util::DEBUG
299
+            );
300
+            $externalManager->removeShare($mount->getMountPoint());
301
+            return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
302
+        }
303
+        $result = $storage->file_exists('');
304
+        if ($result) {
305
+            try {
306
+                $storage->getScanner()->scanAll();
307
+                return new JSONResponse(
308
+                    [
309
+                        'message' => $this->l->t('Federated Share successfully added'),
310
+                        'legacyMount' => '1'
311
+                    ]
312
+                );
313
+            } catch (StorageInvalidException $e) {
314
+                Util::writeLog(
315
+                    'federatedfilesharing',
316
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
317
+                    Util::DEBUG
318
+                );
319
+                return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
320
+            } catch (\Exception $e) {
321
+                Util::writeLog(
322
+                    'federatedfilesharing',
323
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
324
+                    Util::DEBUG
325
+                );
326
+                return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
327
+            }
328
+        } else {
329
+            $externalManager->removeShare($mount->getMountPoint());
330
+            Util::writeLog(
331
+                'federatedfilesharing',
332
+                'Couldn\'t add remote share',
333
+                Util::DEBUG
334
+            );
335
+            return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
336
+        }
337
+
338
+    }
339 339
 
340 340
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 		$storedPassword = $share->getPassword();
148 148
 		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149 149
 			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
150
+		if (!empty($storedPassword) && !$authenticated) {
151 151
 			return new JSONResponse(
152 152
 				['message' => 'No permission to access the share'],
153 153
 				Http::STATUS_BAD_REQUEST
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		$httpClient = $this->clientService->newClient();
190 190
 
191 191
 		try {
192
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
192
+			$response = $httpClient->post($remote.'/index.php/apps/federatedfilesharing/createFederatedShare',
193 193
 				[
194 194
 					'body' =>
195 195
 						[
@@ -287,14 +287,14 @@  discard block
 block discarded – undo
287 287
 			// note: checkStorageAvailability will already remove the invalid share
288 288
 			Util::writeLog(
289 289
 				'federatedfilesharing',
290
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
290
+				'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
291 291
 				Util::DEBUG
292 292
 			);
293 293
 			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
294 294
 		} catch (\Exception $e) {
295 295
 			Util::writeLog(
296 296
 				'federatedfilesharing',
297
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
297
+				'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
298 298
 				Util::DEBUG
299 299
 			);
300 300
 			$externalManager->removeShare($mount->getMountPoint());
@@ -313,14 +313,14 @@  discard block
 block discarded – undo
313 313
 			} catch (StorageInvalidException $e) {
314 314
 				Util::writeLog(
315 315
 					'federatedfilesharing',
316
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
316
+					'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
317 317
 					Util::DEBUG
318 318
 				);
319 319
 				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
320 320
 			} catch (\Exception $e) {
321 321
 				Util::writeLog(
322 322
 					'federatedfilesharing',
323
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
323
+					'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
324 324
 					Util::DEBUG
325 325
 				);
326 326
 				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 2 patches
Indentation   +567 added lines, -567 removed lines patch added patch discarded remove patch
@@ -48,576 +48,576 @@
 block discarded – undo
48 48
 
49 49
 class RequestHandlerController extends OCSController {
50 50
 
51
-	/** @var FederatedShareProvider */
52
-	private $federatedShareProvider;
53
-
54
-	/** @var IDBConnection */
55
-	private $connection;
56
-
57
-	/** @var Share\IManager */
58
-	private $shareManager;
59
-
60
-	/** @var Notifications */
61
-	private $notifications;
62
-
63
-	/** @var AddressHandler */
64
-	private $addressHandler;
65
-
66
-	/** @var  IUserManager */
67
-	private $userManager;
68
-
69
-	/** @var string */
70
-	private $shareTable = 'share';
71
-
72
-	/** @var ICloudIdManager  */
73
-	private $cloudIdManager;
74
-
75
-	/**
76
-	 * Server2Server constructor.
77
-	 *
78
-	 * @param string $appName
79
-	 * @param IRequest $request
80
-	 * @param FederatedShareProvider $federatedShareProvider
81
-	 * @param IDBConnection $connection
82
-	 * @param Share\IManager $shareManager
83
-	 * @param Notifications $notifications
84
-	 * @param AddressHandler $addressHandler
85
-	 * @param IUserManager $userManager
86
-	 * @param ICloudIdManager $cloudIdManager
87
-	 */
88
-	public function __construct($appName,
89
-								IRequest $request,
90
-								FederatedShareProvider $federatedShareProvider,
91
-								IDBConnection $connection,
92
-								Share\IManager $shareManager,
93
-								Notifications $notifications,
94
-								AddressHandler $addressHandler,
95
-								IUserManager $userManager,
96
-								ICloudIdManager $cloudIdManager
97
-	) {
98
-		parent::__construct($appName, $request);
99
-
100
-		$this->federatedShareProvider = $federatedShareProvider;
101
-		$this->connection = $connection;
102
-		$this->shareManager = $shareManager;
103
-		$this->notifications = $notifications;
104
-		$this->addressHandler = $addressHandler;
105
-		$this->userManager = $userManager;
106
-		$this->cloudIdManager = $cloudIdManager;
107
-	}
108
-
109
-	/**
110
-	 * @NoCSRFRequired
111
-	 * @PublicPage
112
-	 *
113
-	 * create a new share
114
-	 *
115
-	 * @return Http\DataResponse
116
-	 * @throws OCSException
117
-	 */
118
-	public function createShare() {
119
-
120
-		if (!$this->isS2SEnabled(true)) {
121
-			throw new OCSException('Server does not support federated cloud sharing', 503);
122
-		}
123
-
124
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
125
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
126
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
127
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
128
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
129
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
130
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
131
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
132
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
133
-
134
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
135
-
136
-			if(!\OCP\Util::isValidFileName($name)) {
137
-				throw new OCSException('The mountpoint name contains invalid characters.', 400);
138
-			}
139
-
140
-			// FIXME this should be a method in the user management instead
141
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
142
-			\OCP\Util::emitHook(
143
-				'\OCA\Files_Sharing\API\Server2Server',
144
-				'preLoginNameUsedAsUserName',
145
-				array('uid' => &$shareWith)
146
-			);
147
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
148
-
149
-			if (!\OCP\User::userExists($shareWith)) {
150
-				throw new OCSException('User does not exists', 400);
151
-			}
152
-
153
-			\OC_Util::setupFS($shareWith);
154
-
155
-			$discoveryManager = new DiscoveryManager(
156
-				\OC::$server->getMemCacheFactory(),
157
-				\OC::$server->getHTTPClientService()
158
-			);
159
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
160
-					\OC::$server->getDatabaseConnection(),
161
-					\OC\Files\Filesystem::getMountManager(),
162
-					\OC\Files\Filesystem::getLoader(),
163
-					\OC::$server->getHTTPClientService(),
164
-					\OC::$server->getNotificationManager(),
165
-					$discoveryManager,
166
-					$shareWith
167
-				);
168
-
169
-			try {
170
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
171
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
172
-
173
-				if ($ownerFederatedId === null) {
174
-					$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
175
-				}
176
-				// if the owner of the share and the initiator are the same user
177
-				// we also complete the federated share ID for the initiator
178
-				if ($sharedByFederatedId === null && $owner === $sharedBy) {
179
-					$sharedByFederatedId = $ownerFederatedId;
180
-				}
181
-
182
-				$event = \OC::$server->getActivityManager()->generateEvent();
183
-				$event->setApp('files_sharing')
184
-					->setType('remote_share')
185
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
186
-					->setAffectedUser($shareWith)
187
-					->setObject('remote_share', (int) $shareId, $name);
188
-				\OC::$server->getActivityManager()->publish($event);
189
-
190
-				$urlGenerator = \OC::$server->getURLGenerator();
191
-
192
-				$notificationManager = \OC::$server->getNotificationManager();
193
-				$notification = $notificationManager->createNotification();
194
-				$notification->setApp('files_sharing')
195
-					->setUser($shareWith)
196
-					->setDateTime(new \DateTime())
197
-					->setObject('remote_share', $shareId)
198
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
199
-
200
-				$declineAction = $notification->createAction();
201
-				$declineAction->setLabel('decline')
202
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
203
-				$notification->addAction($declineAction);
204
-
205
-				$acceptAction = $notification->createAction();
206
-				$acceptAction->setLabel('accept')
207
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
208
-				$notification->addAction($acceptAction);
209
-
210
-				$notificationManager->notify($notification);
211
-
212
-				return new Http\DataResponse();
213
-			} catch (\Exception $e) {
214
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
215
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
216
-			}
217
-		}
218
-
219
-		throw new OCSException('server can not add remote share, missing parameter', 400);
220
-	}
221
-
222
-	/**
223
-	 * @NoCSRFRequired
224
-	 * @PublicPage
225
-	 *
226
-	 * create re-share on behalf of another user
227
-	 *
228
-	 * @param int $id
229
-	 * @return Http\DataResponse
230
-	 * @throws OCSBadRequestException
231
-	 * @throws OCSForbiddenException
232
-	 * @throws OCSNotFoundException
233
-	 */
234
-	public function reShare($id) {
235
-
236
-		$token = $this->request->getParam('token', null);
237
-		$shareWith = $this->request->getParam('shareWith', null);
238
-		$permission = (int)$this->request->getParam('permission', null);
239
-		$remoteId = (int)$this->request->getParam('remoteId', null);
240
-
241
-		if ($id === null ||
242
-			$token === null ||
243
-			$shareWith === null ||
244
-			$permission === null ||
245
-			$remoteId === null
246
-		) {
247
-			throw new OCSBadRequestException();
248
-		}
249
-
250
-		try {
251
-			$share = $this->federatedShareProvider->getShareById($id);
252
-		} catch (Share\Exceptions\ShareNotFound $e) {
253
-			throw new OCSNotFoundException();
254
-		}
255
-
256
-		// don't allow to share a file back to the owner
257
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
258
-		$owner = $share->getShareOwner();
259
-		$currentServer = $this->addressHandler->generateRemoteURL();
260
-		if ($this->addressHandler->compareAddresses($user, $remote,$owner , $currentServer)) {
261
-			throw new OCSForbiddenException();
262
-		}
263
-
264
-		if ($this->verifyShare($share, $token)) {
265
-
266
-			// check if re-sharing is allowed
267
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
268
-				$share->setPermissions($share->getPermissions() & $permission);
269
-				// the recipient of the initial share is now the initiator for the re-share
270
-				$share->setSharedBy($share->getSharedWith());
271
-				$share->setSharedWith($shareWith);
272
-				try {
273
-					$result = $this->federatedShareProvider->create($share);
274
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
275
-					return new Http\DataResponse([
276
-						'token' => $result->getToken(),
277
-						'remoteId' => $result->getId()
278
-					]);
279
-				} catch (\Exception $e) {
280
-					throw new OCSBadRequestException();
281
-				}
282
-			} else {
283
-				throw new OCSForbiddenException();
284
-			}
285
-		}
286
-		throw new OCSBadRequestException();
287
-	}
288
-
289
-	/**
290
-	 * @NoCSRFRequired
291
-	 * @PublicPage
292
-	 *
293
-	 * accept server-to-server share
294
-	 *
295
-	 * @param int $id
296
-	 * @return Http\DataResponse
297
-	 * @throws OCSException
298
-	 */
299
-	public function acceptShare($id) {
300
-
301
-		if (!$this->isS2SEnabled()) {
302
-			throw new OCSException('Server does not support federated cloud sharing', 503);
303
-		}
304
-
305
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
306
-
307
-		try {
308
-			$share = $this->federatedShareProvider->getShareById($id);
309
-		} catch (Share\Exceptions\ShareNotFound $e) {
310
-			return new Http\DataResponse();
311
-		}
312
-
313
-		if ($this->verifyShare($share, $token)) {
314
-			$this->executeAcceptShare($share);
315
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
316
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
317
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
318
-				$this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
319
-			}
320
-		}
321
-
322
-		return new Http\DataResponse();
323
-	}
324
-
325
-	protected function executeAcceptShare(Share\IShare $share) {
326
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
327
-
328
-		$event = \OC::$server->getActivityManager()->generateEvent();
329
-		$event->setApp('files_sharing')
330
-			->setType('remote_share')
331
-			->setAffectedUser($this->getCorrectUid($share))
332
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), $file])
333
-			->setObject('files', (int) $share->getNode()->getId(), $file)
334
-			->setLink($link);
335
-		\OC::$server->getActivityManager()->publish($event);
336
-	}
337
-
338
-	/**
339
-	 * @NoCSRFRequired
340
-	 * @PublicPage
341
-	 *
342
-	 * decline server-to-server share
343
-	 *
344
-	 * @param int $id
345
-	 * @return Http\DataResponse
346
-	 * @throws OCSException
347
-	 */
348
-	public function declineShare($id) {
349
-
350
-		if (!$this->isS2SEnabled()) {
351
-			throw new OCSException('Server does not support federated cloud sharing', 503);
352
-		}
353
-
354
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
355
-
356
-		try {
357
-			$share = $this->federatedShareProvider->getShareById($id);
358
-		} catch (Share\Exceptions\ShareNotFound $e) {
359
-			return new Http\DataResponse();
360
-		}
361
-
362
-		if($this->verifyShare($share, $token)) {
363
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
364
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
365
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
366
-				$this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
367
-			}
368
-			$this->executeDeclineShare($share);
369
-		}
370
-
371
-		return new Http\DataResponse();
372
-	}
373
-
374
-	/**
375
-	 * delete declined share and create a activity
376
-	 *
377
-	 * @param Share\IShare $share
378
-	 */
379
-	protected function executeDeclineShare(Share\IShare $share) {
380
-		$this->federatedShareProvider->removeShareFromTable($share);
381
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
382
-
383
-		$event = \OC::$server->getActivityManager()->generateEvent();
384
-		$event->setApp('files_sharing')
385
-			->setType('remote_share')
386
-			->setAffectedUser($this->getCorrectUid($share))
387
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), $file])
388
-			->setObject('files', (int) $share->getNode()->getId(), $file)
389
-			->setLink($link);
390
-		\OC::$server->getActivityManager()->publish($event);
391
-
392
-	}
393
-
394
-	/**
395
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
396
-	 *
397
-	 * @param Share\IShare $share
398
-	 * @return string
399
-	 */
400
-	protected function getCorrectUid(Share\IShare $share) {
401
-		if($this->userManager->userExists($share->getShareOwner())) {
402
-			return $share->getShareOwner();
403
-		}
404
-
405
-		return $share->getSharedBy();
406
-	}
407
-
408
-	/**
409
-	 * @NoCSRFRequired
410
-	 * @PublicPage
411
-	 *
412
-	 * remove server-to-server share if it was unshared by the owner
413
-	 *
414
-	 * @param int $id
415
-	 * @return Http\DataResponse
416
-	 * @throws OCSException
417
-	 */
418
-	public function unshare($id) {
419
-
420
-		if (!$this->isS2SEnabled()) {
421
-			throw new OCSException('Server does not support federated cloud sharing', 503);
422
-		}
423
-
424
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
425
-
426
-		$query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
427
-		$query->execute(array($id, $token));
428
-		$share = $query->fetchRow();
429
-
430
-		if ($token && $id && !empty($share)) {
431
-
432
-			$remote = $this->cleanupRemote($share['remote']);
433
-
434
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
435
-			$mountpoint = $share['mountpoint'];
436
-			$user = $share['user'];
437
-
438
-			$query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
439
-			$query->execute(array($id, $token));
440
-
441
-			if ($share['accepted']) {
442
-				$path = trim($mountpoint, '/');
443
-			} else {
444
-				$path = trim($share['name'], '/');
445
-			}
446
-
447
-			$notificationManager = \OC::$server->getNotificationManager();
448
-			$notification = $notificationManager->createNotification();
449
-			$notification->setApp('files_sharing')
450
-				->setUser($share['user'])
451
-				->setObject('remote_share', (int) $share['id']);
452
-			$notificationManager->markProcessed($notification);
453
-
454
-			$event = \OC::$server->getActivityManager()->generateEvent();
455
-			$event->setApp('files_sharing')
456
-				->setType('remote_share')
457
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner, $path])
458
-				->setAffectedUser($user)
459
-				->setObject('remote_share', (int) $share['id'], $path);
460
-			\OC::$server->getActivityManager()->publish($event);
461
-		}
462
-
463
-		return new Http\DataResponse();
464
-	}
465
-
466
-	private function cleanupRemote($remote) {
467
-		$remote = substr($remote, strpos($remote, '://') + 3);
468
-
469
-		return rtrim($remote, '/');
470
-	}
471
-
472
-
473
-	/**
474
-	 * @NoCSRFRequired
475
-	 * @PublicPage
476
-	 *
477
-	 * federated share was revoked, either by the owner or the re-sharer
478
-	 *
479
-	 * @param int $id
480
-	 * @return Http\DataResponse
481
-	 * @throws OCSBadRequestException
482
-	 */
483
-	public function revoke($id) {
484
-		$token = $this->request->getParam('token');
51
+    /** @var FederatedShareProvider */
52
+    private $federatedShareProvider;
53
+
54
+    /** @var IDBConnection */
55
+    private $connection;
56
+
57
+    /** @var Share\IManager */
58
+    private $shareManager;
59
+
60
+    /** @var Notifications */
61
+    private $notifications;
62
+
63
+    /** @var AddressHandler */
64
+    private $addressHandler;
65
+
66
+    /** @var  IUserManager */
67
+    private $userManager;
68
+
69
+    /** @var string */
70
+    private $shareTable = 'share';
71
+
72
+    /** @var ICloudIdManager  */
73
+    private $cloudIdManager;
74
+
75
+    /**
76
+     * Server2Server constructor.
77
+     *
78
+     * @param string $appName
79
+     * @param IRequest $request
80
+     * @param FederatedShareProvider $federatedShareProvider
81
+     * @param IDBConnection $connection
82
+     * @param Share\IManager $shareManager
83
+     * @param Notifications $notifications
84
+     * @param AddressHandler $addressHandler
85
+     * @param IUserManager $userManager
86
+     * @param ICloudIdManager $cloudIdManager
87
+     */
88
+    public function __construct($appName,
89
+                                IRequest $request,
90
+                                FederatedShareProvider $federatedShareProvider,
91
+                                IDBConnection $connection,
92
+                                Share\IManager $shareManager,
93
+                                Notifications $notifications,
94
+                                AddressHandler $addressHandler,
95
+                                IUserManager $userManager,
96
+                                ICloudIdManager $cloudIdManager
97
+    ) {
98
+        parent::__construct($appName, $request);
99
+
100
+        $this->federatedShareProvider = $federatedShareProvider;
101
+        $this->connection = $connection;
102
+        $this->shareManager = $shareManager;
103
+        $this->notifications = $notifications;
104
+        $this->addressHandler = $addressHandler;
105
+        $this->userManager = $userManager;
106
+        $this->cloudIdManager = $cloudIdManager;
107
+    }
108
+
109
+    /**
110
+     * @NoCSRFRequired
111
+     * @PublicPage
112
+     *
113
+     * create a new share
114
+     *
115
+     * @return Http\DataResponse
116
+     * @throws OCSException
117
+     */
118
+    public function createShare() {
119
+
120
+        if (!$this->isS2SEnabled(true)) {
121
+            throw new OCSException('Server does not support federated cloud sharing', 503);
122
+        }
123
+
124
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
125
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
126
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
127
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
128
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
129
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
130
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
131
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
132
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
133
+
134
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
135
+
136
+            if(!\OCP\Util::isValidFileName($name)) {
137
+                throw new OCSException('The mountpoint name contains invalid characters.', 400);
138
+            }
139
+
140
+            // FIXME this should be a method in the user management instead
141
+            \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
142
+            \OCP\Util::emitHook(
143
+                '\OCA\Files_Sharing\API\Server2Server',
144
+                'preLoginNameUsedAsUserName',
145
+                array('uid' => &$shareWith)
146
+            );
147
+            \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
148
+
149
+            if (!\OCP\User::userExists($shareWith)) {
150
+                throw new OCSException('User does not exists', 400);
151
+            }
152
+
153
+            \OC_Util::setupFS($shareWith);
154
+
155
+            $discoveryManager = new DiscoveryManager(
156
+                \OC::$server->getMemCacheFactory(),
157
+                \OC::$server->getHTTPClientService()
158
+            );
159
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
160
+                    \OC::$server->getDatabaseConnection(),
161
+                    \OC\Files\Filesystem::getMountManager(),
162
+                    \OC\Files\Filesystem::getLoader(),
163
+                    \OC::$server->getHTTPClientService(),
164
+                    \OC::$server->getNotificationManager(),
165
+                    $discoveryManager,
166
+                    $shareWith
167
+                );
168
+
169
+            try {
170
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
171
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
172
+
173
+                if ($ownerFederatedId === null) {
174
+                    $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
175
+                }
176
+                // if the owner of the share and the initiator are the same user
177
+                // we also complete the federated share ID for the initiator
178
+                if ($sharedByFederatedId === null && $owner === $sharedBy) {
179
+                    $sharedByFederatedId = $ownerFederatedId;
180
+                }
181
+
182
+                $event = \OC::$server->getActivityManager()->generateEvent();
183
+                $event->setApp('files_sharing')
184
+                    ->setType('remote_share')
185
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
186
+                    ->setAffectedUser($shareWith)
187
+                    ->setObject('remote_share', (int) $shareId, $name);
188
+                \OC::$server->getActivityManager()->publish($event);
189
+
190
+                $urlGenerator = \OC::$server->getURLGenerator();
191
+
192
+                $notificationManager = \OC::$server->getNotificationManager();
193
+                $notification = $notificationManager->createNotification();
194
+                $notification->setApp('files_sharing')
195
+                    ->setUser($shareWith)
196
+                    ->setDateTime(new \DateTime())
197
+                    ->setObject('remote_share', $shareId)
198
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
199
+
200
+                $declineAction = $notification->createAction();
201
+                $declineAction->setLabel('decline')
202
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
203
+                $notification->addAction($declineAction);
204
+
205
+                $acceptAction = $notification->createAction();
206
+                $acceptAction->setLabel('accept')
207
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
208
+                $notification->addAction($acceptAction);
209
+
210
+                $notificationManager->notify($notification);
211
+
212
+                return new Http\DataResponse();
213
+            } catch (\Exception $e) {
214
+                \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
215
+                throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
216
+            }
217
+        }
218
+
219
+        throw new OCSException('server can not add remote share, missing parameter', 400);
220
+    }
221
+
222
+    /**
223
+     * @NoCSRFRequired
224
+     * @PublicPage
225
+     *
226
+     * create re-share on behalf of another user
227
+     *
228
+     * @param int $id
229
+     * @return Http\DataResponse
230
+     * @throws OCSBadRequestException
231
+     * @throws OCSForbiddenException
232
+     * @throws OCSNotFoundException
233
+     */
234
+    public function reShare($id) {
235
+
236
+        $token = $this->request->getParam('token', null);
237
+        $shareWith = $this->request->getParam('shareWith', null);
238
+        $permission = (int)$this->request->getParam('permission', null);
239
+        $remoteId = (int)$this->request->getParam('remoteId', null);
240
+
241
+        if ($id === null ||
242
+            $token === null ||
243
+            $shareWith === null ||
244
+            $permission === null ||
245
+            $remoteId === null
246
+        ) {
247
+            throw new OCSBadRequestException();
248
+        }
249
+
250
+        try {
251
+            $share = $this->federatedShareProvider->getShareById($id);
252
+        } catch (Share\Exceptions\ShareNotFound $e) {
253
+            throw new OCSNotFoundException();
254
+        }
255
+
256
+        // don't allow to share a file back to the owner
257
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
258
+        $owner = $share->getShareOwner();
259
+        $currentServer = $this->addressHandler->generateRemoteURL();
260
+        if ($this->addressHandler->compareAddresses($user, $remote,$owner , $currentServer)) {
261
+            throw new OCSForbiddenException();
262
+        }
263
+
264
+        if ($this->verifyShare($share, $token)) {
265
+
266
+            // check if re-sharing is allowed
267
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
268
+                $share->setPermissions($share->getPermissions() & $permission);
269
+                // the recipient of the initial share is now the initiator for the re-share
270
+                $share->setSharedBy($share->getSharedWith());
271
+                $share->setSharedWith($shareWith);
272
+                try {
273
+                    $result = $this->federatedShareProvider->create($share);
274
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
275
+                    return new Http\DataResponse([
276
+                        'token' => $result->getToken(),
277
+                        'remoteId' => $result->getId()
278
+                    ]);
279
+                } catch (\Exception $e) {
280
+                    throw new OCSBadRequestException();
281
+                }
282
+            } else {
283
+                throw new OCSForbiddenException();
284
+            }
285
+        }
286
+        throw new OCSBadRequestException();
287
+    }
288
+
289
+    /**
290
+     * @NoCSRFRequired
291
+     * @PublicPage
292
+     *
293
+     * accept server-to-server share
294
+     *
295
+     * @param int $id
296
+     * @return Http\DataResponse
297
+     * @throws OCSException
298
+     */
299
+    public function acceptShare($id) {
300
+
301
+        if (!$this->isS2SEnabled()) {
302
+            throw new OCSException('Server does not support federated cloud sharing', 503);
303
+        }
304
+
305
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
306
+
307
+        try {
308
+            $share = $this->federatedShareProvider->getShareById($id);
309
+        } catch (Share\Exceptions\ShareNotFound $e) {
310
+            return new Http\DataResponse();
311
+        }
312
+
313
+        if ($this->verifyShare($share, $token)) {
314
+            $this->executeAcceptShare($share);
315
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
316
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
317
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
318
+                $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
319
+            }
320
+        }
321
+
322
+        return new Http\DataResponse();
323
+    }
324
+
325
+    protected function executeAcceptShare(Share\IShare $share) {
326
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
327
+
328
+        $event = \OC::$server->getActivityManager()->generateEvent();
329
+        $event->setApp('files_sharing')
330
+            ->setType('remote_share')
331
+            ->setAffectedUser($this->getCorrectUid($share))
332
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), $file])
333
+            ->setObject('files', (int) $share->getNode()->getId(), $file)
334
+            ->setLink($link);
335
+        \OC::$server->getActivityManager()->publish($event);
336
+    }
337
+
338
+    /**
339
+     * @NoCSRFRequired
340
+     * @PublicPage
341
+     *
342
+     * decline server-to-server share
343
+     *
344
+     * @param int $id
345
+     * @return Http\DataResponse
346
+     * @throws OCSException
347
+     */
348
+    public function declineShare($id) {
349
+
350
+        if (!$this->isS2SEnabled()) {
351
+            throw new OCSException('Server does not support federated cloud sharing', 503);
352
+        }
353
+
354
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
355
+
356
+        try {
357
+            $share = $this->federatedShareProvider->getShareById($id);
358
+        } catch (Share\Exceptions\ShareNotFound $e) {
359
+            return new Http\DataResponse();
360
+        }
361
+
362
+        if($this->verifyShare($share, $token)) {
363
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
364
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
365
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
366
+                $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
367
+            }
368
+            $this->executeDeclineShare($share);
369
+        }
370
+
371
+        return new Http\DataResponse();
372
+    }
373
+
374
+    /**
375
+     * delete declined share and create a activity
376
+     *
377
+     * @param Share\IShare $share
378
+     */
379
+    protected function executeDeclineShare(Share\IShare $share) {
380
+        $this->federatedShareProvider->removeShareFromTable($share);
381
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $share->getNode()->getId());
382
+
383
+        $event = \OC::$server->getActivityManager()->generateEvent();
384
+        $event->setApp('files_sharing')
385
+            ->setType('remote_share')
386
+            ->setAffectedUser($this->getCorrectUid($share))
387
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), $file])
388
+            ->setObject('files', (int) $share->getNode()->getId(), $file)
389
+            ->setLink($link);
390
+        \OC::$server->getActivityManager()->publish($event);
391
+
392
+    }
393
+
394
+    /**
395
+     * check if we are the initiator or the owner of a re-share and return the correct UID
396
+     *
397
+     * @param Share\IShare $share
398
+     * @return string
399
+     */
400
+    protected function getCorrectUid(Share\IShare $share) {
401
+        if($this->userManager->userExists($share->getShareOwner())) {
402
+            return $share->getShareOwner();
403
+        }
404
+
405
+        return $share->getSharedBy();
406
+    }
407
+
408
+    /**
409
+     * @NoCSRFRequired
410
+     * @PublicPage
411
+     *
412
+     * remove server-to-server share if it was unshared by the owner
413
+     *
414
+     * @param int $id
415
+     * @return Http\DataResponse
416
+     * @throws OCSException
417
+     */
418
+    public function unshare($id) {
419
+
420
+        if (!$this->isS2SEnabled()) {
421
+            throw new OCSException('Server does not support federated cloud sharing', 503);
422
+        }
423
+
424
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
425
+
426
+        $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
427
+        $query->execute(array($id, $token));
428
+        $share = $query->fetchRow();
429
+
430
+        if ($token && $id && !empty($share)) {
431
+
432
+            $remote = $this->cleanupRemote($share['remote']);
433
+
434
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
435
+            $mountpoint = $share['mountpoint'];
436
+            $user = $share['user'];
437
+
438
+            $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
439
+            $query->execute(array($id, $token));
440
+
441
+            if ($share['accepted']) {
442
+                $path = trim($mountpoint, '/');
443
+            } else {
444
+                $path = trim($share['name'], '/');
445
+            }
446
+
447
+            $notificationManager = \OC::$server->getNotificationManager();
448
+            $notification = $notificationManager->createNotification();
449
+            $notification->setApp('files_sharing')
450
+                ->setUser($share['user'])
451
+                ->setObject('remote_share', (int) $share['id']);
452
+            $notificationManager->markProcessed($notification);
453
+
454
+            $event = \OC::$server->getActivityManager()->generateEvent();
455
+            $event->setApp('files_sharing')
456
+                ->setType('remote_share')
457
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner, $path])
458
+                ->setAffectedUser($user)
459
+                ->setObject('remote_share', (int) $share['id'], $path);
460
+            \OC::$server->getActivityManager()->publish($event);
461
+        }
462
+
463
+        return new Http\DataResponse();
464
+    }
465
+
466
+    private function cleanupRemote($remote) {
467
+        $remote = substr($remote, strpos($remote, '://') + 3);
468
+
469
+        return rtrim($remote, '/');
470
+    }
471
+
472
+
473
+    /**
474
+     * @NoCSRFRequired
475
+     * @PublicPage
476
+     *
477
+     * federated share was revoked, either by the owner or the re-sharer
478
+     *
479
+     * @param int $id
480
+     * @return Http\DataResponse
481
+     * @throws OCSBadRequestException
482
+     */
483
+    public function revoke($id) {
484
+        $token = $this->request->getParam('token');
485 485
 		
486
-		$share = $this->federatedShareProvider->getShareById($id);
486
+        $share = $this->federatedShareProvider->getShareById($id);
487 487
 		
488
-		if ($this->verifyShare($share, $token)) {
489
-			$this->federatedShareProvider->removeShareFromTable($share);
490
-			return new Http\DataResponse();
491
-		}
488
+        if ($this->verifyShare($share, $token)) {
489
+            $this->federatedShareProvider->removeShareFromTable($share);
490
+            return new Http\DataResponse();
491
+        }
492 492
 
493
-		throw new OCSBadRequestException();
494
-	}
493
+        throw new OCSBadRequestException();
494
+    }
495 495
 	
496
-	/**
497
-	 * get share
498
-	 *
499
-	 * @param int $id
500
-	 * @param string $token
501
-	 * @return array|bool
502
-	 */
503
-	protected function getShare($id, $token) {
504
-		$query = $this->connection->getQueryBuilder();
505
-		$query->select('*')->from($this->shareTable)
506
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
507
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
508
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
509
-
510
-		$result = $query->execute()->fetchAll();
511
-
512
-		if (!empty($result) && isset($result[0])) {
513
-			return $result[0];
514
-		}
515
-
516
-		return false;
517
-	}
518
-
519
-	/**
520
-	 * get file
521
-	 *
522
-	 * @param string $user
523
-	 * @param int $fileSource
524
-	 * @return array with internal path of the file and a absolute link to it
525
-	 */
526
-	private function getFile($user, $fileSource) {
527
-		\OC_Util::setupFS($user);
528
-
529
-		try {
530
-			$file = \OC\Files\Filesystem::getPath($fileSource);
531
-		} catch (NotFoundException $e) {
532
-			$file = null;
533
-		}
534
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
535
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
536
-
537
-		return array($file, $link);
538
-
539
-	}
540
-
541
-	/**
542
-	 * check if server-to-server sharing is enabled
543
-	 *
544
-	 * @param bool $incoming
545
-	 * @return bool
546
-	 */
547
-	private function isS2SEnabled($incoming = false) {
548
-
549
-		$result = \OCP\App::isEnabled('files_sharing');
550
-
551
-		if ($incoming) {
552
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
553
-		} else {
554
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
555
-		}
556
-
557
-		return $result;
558
-	}
559
-
560
-	/**
561
-	 * check if we got the right share
562
-	 *
563
-	 * @param Share\IShare $share
564
-	 * @param string $token
565
-	 * @return bool
566
-	 */
567
-	protected function verifyShare(Share\IShare $share, $token) {
568
-		if (
569
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
570
-			$share->getToken() === $token
571
-		) {
572
-			return true;
573
-		}
574
-
575
-		return false;
576
-	}
577
-
578
-	/**
579
-	 * @NoCSRFRequired
580
-	 * @PublicPage
581
-	 *
582
-	 * update share information to keep federated re-shares in sync
583
-	 *
584
-	 * @param int $id
585
-	 * @return Http\DataResponse
586
-	 * @throws OCSBadRequestException
587
-	 */
588
-	public function updatePermissions($id) {
589
-		$token = $this->request->getParam('token', null);
590
-		$permissions = $this->request->getParam('permissions', null);
591
-
592
-		try {
593
-			$share = $this->federatedShareProvider->getShareById($id);
594
-		} catch (Share\Exceptions\ShareNotFound $e) {
595
-			throw new OCSBadRequestException();
596
-		}
597
-
598
-		$validPermission = ctype_digit($permissions);
599
-		$validToken = $this->verifyShare($share, $token);
600
-		if ($validPermission && $validToken) {
601
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
602
-		} else {
603
-			throw new OCSBadRequestException();
604
-		}
605
-
606
-		return new Http\DataResponse();
607
-	}
608
-
609
-	/**
610
-	 * update permissions in database
611
-	 *
612
-	 * @param IShare $share
613
-	 * @param int $permissions
614
-	 */
615
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
616
-		$query = $this->connection->getQueryBuilder();
617
-		$query->update('share')
618
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
619
-			->set('permissions', $query->createNamedParameter($permissions))
620
-			->execute();
621
-	}
496
+    /**
497
+     * get share
498
+     *
499
+     * @param int $id
500
+     * @param string $token
501
+     * @return array|bool
502
+     */
503
+    protected function getShare($id, $token) {
504
+        $query = $this->connection->getQueryBuilder();
505
+        $query->select('*')->from($this->shareTable)
506
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
507
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
508
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
509
+
510
+        $result = $query->execute()->fetchAll();
511
+
512
+        if (!empty($result) && isset($result[0])) {
513
+            return $result[0];
514
+        }
515
+
516
+        return false;
517
+    }
518
+
519
+    /**
520
+     * get file
521
+     *
522
+     * @param string $user
523
+     * @param int $fileSource
524
+     * @return array with internal path of the file and a absolute link to it
525
+     */
526
+    private function getFile($user, $fileSource) {
527
+        \OC_Util::setupFS($user);
528
+
529
+        try {
530
+            $file = \OC\Files\Filesystem::getPath($fileSource);
531
+        } catch (NotFoundException $e) {
532
+            $file = null;
533
+        }
534
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
535
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
536
+
537
+        return array($file, $link);
538
+
539
+    }
540
+
541
+    /**
542
+     * check if server-to-server sharing is enabled
543
+     *
544
+     * @param bool $incoming
545
+     * @return bool
546
+     */
547
+    private function isS2SEnabled($incoming = false) {
548
+
549
+        $result = \OCP\App::isEnabled('files_sharing');
550
+
551
+        if ($incoming) {
552
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
553
+        } else {
554
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
555
+        }
556
+
557
+        return $result;
558
+    }
559
+
560
+    /**
561
+     * check if we got the right share
562
+     *
563
+     * @param Share\IShare $share
564
+     * @param string $token
565
+     * @return bool
566
+     */
567
+    protected function verifyShare(Share\IShare $share, $token) {
568
+        if (
569
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
570
+            $share->getToken() === $token
571
+        ) {
572
+            return true;
573
+        }
574
+
575
+        return false;
576
+    }
577
+
578
+    /**
579
+     * @NoCSRFRequired
580
+     * @PublicPage
581
+     *
582
+     * update share information to keep federated re-shares in sync
583
+     *
584
+     * @param int $id
585
+     * @return Http\DataResponse
586
+     * @throws OCSBadRequestException
587
+     */
588
+    public function updatePermissions($id) {
589
+        $token = $this->request->getParam('token', null);
590
+        $permissions = $this->request->getParam('permissions', null);
591
+
592
+        try {
593
+            $share = $this->federatedShareProvider->getShareById($id);
594
+        } catch (Share\Exceptions\ShareNotFound $e) {
595
+            throw new OCSBadRequestException();
596
+        }
597
+
598
+        $validPermission = ctype_digit($permissions);
599
+        $validToken = $this->verifyShare($share, $token);
600
+        if ($validPermission && $validToken) {
601
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
602
+        } else {
603
+            throw new OCSBadRequestException();
604
+        }
605
+
606
+        return new Http\DataResponse();
607
+    }
608
+
609
+    /**
610
+     * update permissions in database
611
+     *
612
+     * @param IShare $share
613
+     * @param int $permissions
614
+     */
615
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
616
+        $query = $this->connection->getQueryBuilder();
617
+        $query->update('share')
618
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
619
+            ->set('permissions', $query->createNamedParameter($permissions))
620
+            ->execute();
621
+    }
622 622
 
623 623
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -127,24 +127,24 @@  discard block
 block discarded – undo
127 127
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
128 128
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
129 129
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
130
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
130
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
131 131
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
132 132
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
133 133
 
134 134
 		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
135 135
 
136
-			if(!\OCP\Util::isValidFileName($name)) {
136
+			if (!\OCP\Util::isValidFileName($name)) {
137 137
 				throw new OCSException('The mountpoint name contains invalid characters.', 400);
138 138
 			}
139 139
 
140 140
 			// FIXME this should be a method in the user management instead
141
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
141
+			\OCP\Util::writeLog('files_sharing', 'shareWith before, '.$shareWith, \OCP\Util::DEBUG);
142 142
 			\OCP\Util::emitHook(
143 143
 				'\OCA\Files_Sharing\API\Server2Server',
144 144
 				'preLoginNameUsedAsUserName',
145 145
 				array('uid' => &$shareWith)
146 146
 			);
147
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
147
+			\OCP\Util::writeLog('files_sharing', 'shareWith after, '.$shareWith, \OCP\Util::DEBUG);
148 148
 
149 149
 			if (!\OCP\User::userExists($shareWith)) {
150 150
 				throw new OCSException('User does not exists', 400);
@@ -199,20 +199,20 @@  discard block
 block discarded – undo
199 199
 
200 200
 				$declineAction = $notification->createAction();
201 201
 				$declineAction->setLabel('decline')
202
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
202
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
203 203
 				$notification->addAction($declineAction);
204 204
 
205 205
 				$acceptAction = $notification->createAction();
206 206
 				$acceptAction->setLabel('accept')
207
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
207
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v1.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
208 208
 				$notification->addAction($acceptAction);
209 209
 
210 210
 				$notificationManager->notify($notification);
211 211
 
212 212
 				return new Http\DataResponse();
213 213
 			} catch (\Exception $e) {
214
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
215
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
214
+				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, '.$e->getMessage(), \OCP\Util::ERROR);
215
+				throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
216 216
 			}
217 217
 		}
218 218
 
@@ -235,8 +235,8 @@  discard block
 block discarded – undo
235 235
 
236 236
 		$token = $this->request->getParam('token', null);
237 237
 		$shareWith = $this->request->getParam('shareWith', null);
238
-		$permission = (int)$this->request->getParam('permission', null);
239
-		$remoteId = (int)$this->request->getParam('remoteId', null);
238
+		$permission = (int) $this->request->getParam('permission', null);
239
+		$remoteId = (int) $this->request->getParam('remoteId', null);
240 240
 
241 241
 		if ($id === null ||
242 242
 			$token === null ||
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
258 258
 		$owner = $share->getShareOwner();
259 259
 		$currentServer = $this->addressHandler->generateRemoteURL();
260
-		if ($this->addressHandler->compareAddresses($user, $remote,$owner , $currentServer)) {
260
+		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
261 261
 			throw new OCSForbiddenException();
262 262
 		}
263 263
 
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 				$share->setSharedWith($shareWith);
272 272
 				try {
273 273
 					$result = $this->federatedShareProvider->create($share);
274
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
274
+					$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $remoteId);
275 275
 					return new Http\DataResponse([
276 276
 						'token' => $result->getToken(),
277 277
 						'remoteId' => $result->getId()
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
 			return new Http\DataResponse();
360 360
 		}
361 361
 
362
-		if($this->verifyShare($share, $token)) {
362
+		if ($this->verifyShare($share, $token)) {
363 363
 			if ($share->getShareOwner() !== $share->getSharedBy()) {
364 364
 				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
365 365
 				$remoteId = $this->federatedShareProvider->getRemoteId($share);
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 	 * @return string
399 399
 	 */
400 400
 	protected function getCorrectUid(Share\IShare $share) {
401
-		if($this->userManager->userExists($share->getShareOwner())) {
401
+		if ($this->userManager->userExists($share->getShareOwner())) {
402 402
 			return $share->getShareOwner();
403 403
 		}
404 404
 
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 		$validPermission = ctype_digit($permissions);
599 599
 		$validToken = $this->verifyShare($share, $token);
600 600
 		if ($validPermission && $validToken) {
601
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
601
+			$this->updatePermissionsInDatabase($share, (int) $permissions);
602 602
 		} else {
603 603
 			throw new OCSBadRequestException();
604 604
 		}
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -33,98 +33,98 @@
 block discarded – undo
33 33
 
34 34
 class Application extends App {
35 35
 
36
-	/** @var FederatedShareProvider */
37
-	protected $federatedShareProvider;
36
+    /** @var FederatedShareProvider */
37
+    protected $federatedShareProvider;
38 38
 
39
-	public function __construct() {
40
-		parent::__construct('federatedfilesharing');
39
+    public function __construct() {
40
+        parent::__construct('federatedfilesharing');
41 41
 
42
-		$container = $this->getContainer();
43
-		$server = $container->getServer();
42
+        $container = $this->getContainer();
43
+        $server = $container->getServer();
44 44
 
45
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
46
-			$addressHandler = new AddressHandler(
47
-				$server->getURLGenerator(),
48
-				$server->getL10N('federatedfilesharing'),
49
-				$server->getCloudIdManager()
50
-			);
51
-			$notification = new Notifications(
52
-				$addressHandler,
53
-				$server->getHTTPClientService(),
54
-				new \OCA\FederatedFileSharing\DiscoveryManager(
55
-					$server->getMemCacheFactory(),
56
-					$server->getHTTPClientService()
57
-				),
58
-				\OC::$server->getJobList()
59
-			);
60
-			return new RequestHandlerController(
61
-				$c->query('AppName'),
62
-				$server->getRequest(),
63
-				$this->getFederatedShareProvider(),
64
-				$server->getDatabaseConnection(),
65
-				$server->getShareManager(),
66
-				$notification,
67
-				$addressHandler,
68
-				$server->getUserManager(),
69
-				$server->getCloudIdManager()
70
-			);
71
-		});
72
-	}
45
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
46
+            $addressHandler = new AddressHandler(
47
+                $server->getURLGenerator(),
48
+                $server->getL10N('federatedfilesharing'),
49
+                $server->getCloudIdManager()
50
+            );
51
+            $notification = new Notifications(
52
+                $addressHandler,
53
+                $server->getHTTPClientService(),
54
+                new \OCA\FederatedFileSharing\DiscoveryManager(
55
+                    $server->getMemCacheFactory(),
56
+                    $server->getHTTPClientService()
57
+                ),
58
+                \OC::$server->getJobList()
59
+            );
60
+            return new RequestHandlerController(
61
+                $c->query('AppName'),
62
+                $server->getRequest(),
63
+                $this->getFederatedShareProvider(),
64
+                $server->getDatabaseConnection(),
65
+                $server->getShareManager(),
66
+                $notification,
67
+                $addressHandler,
68
+                $server->getUserManager(),
69
+                $server->getCloudIdManager()
70
+            );
71
+        });
72
+    }
73 73
 
74
-	/**
75
-	 * register personal and admin settings page
76
-	 */
77
-	public function registerSettings() {
78
-		\OCP\App::registerPersonal('federatedfilesharing', 'settings-personal');
79
-	}
74
+    /**
75
+     * register personal and admin settings page
76
+     */
77
+    public function registerSettings() {
78
+        \OCP\App::registerPersonal('federatedfilesharing', 'settings-personal');
79
+    }
80 80
 
81
-	/**
82
-	 * get instance of federated share provider
83
-	 *
84
-	 * @return FederatedShareProvider
85
-	 */
86
-	public function getFederatedShareProvider() {
87
-		if ($this->federatedShareProvider === null) {
88
-			$this->initFederatedShareProvider();
89
-		}
90
-		return $this->federatedShareProvider;
91
-	}
81
+    /**
82
+     * get instance of federated share provider
83
+     *
84
+     * @return FederatedShareProvider
85
+     */
86
+    public function getFederatedShareProvider() {
87
+        if ($this->federatedShareProvider === null) {
88
+            $this->initFederatedShareProvider();
89
+        }
90
+        return $this->federatedShareProvider;
91
+    }
92 92
 
93
-	/**
94
-	 * initialize federated share provider
95
-	 */
96
-	protected function initFederatedShareProvider() {
97
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
98
-			\OC::$server->getURLGenerator(),
99
-			\OC::$server->getL10N('federatedfilesharing'),
100
-			\OC::$server->getCloudIdManager()
101
-		);
102
-		$discoveryManager = new \OCA\FederatedFileSharing\DiscoveryManager(
103
-			\OC::$server->getMemCacheFactory(),
104
-			\OC::$server->getHTTPClientService()
105
-		);
106
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
107
-			$addressHandler,
108
-			\OC::$server->getHTTPClientService(),
109
-			$discoveryManager,
110
-			\OC::$server->getJobList()
111
-		);
112
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
113
-			\OC::$server->getSecureRandom()
114
-		);
93
+    /**
94
+     * initialize federated share provider
95
+     */
96
+    protected function initFederatedShareProvider() {
97
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
98
+            \OC::$server->getURLGenerator(),
99
+            \OC::$server->getL10N('federatedfilesharing'),
100
+            \OC::$server->getCloudIdManager()
101
+        );
102
+        $discoveryManager = new \OCA\FederatedFileSharing\DiscoveryManager(
103
+            \OC::$server->getMemCacheFactory(),
104
+            \OC::$server->getHTTPClientService()
105
+        );
106
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
107
+            $addressHandler,
108
+            \OC::$server->getHTTPClientService(),
109
+            $discoveryManager,
110
+            \OC::$server->getJobList()
111
+        );
112
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
113
+            \OC::$server->getSecureRandom()
114
+        );
115 115
 
116
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
117
-			\OC::$server->getDatabaseConnection(),
118
-			$addressHandler,
119
-			$notifications,
120
-			$tokenHandler,
121
-			\OC::$server->getL10N('federatedfilesharing'),
122
-			\OC::$server->getLogger(),
123
-			\OC::$server->getLazyRootFolder(),
124
-			\OC::$server->getConfig(),
125
-			\OC::$server->getUserManager(),
126
-			\OC::$server->getCloudIdManager()
127
-		);
128
-	}
116
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
117
+            \OC::$server->getDatabaseConnection(),
118
+            $addressHandler,
119
+            $notifications,
120
+            $tokenHandler,
121
+            \OC::$server->getL10N('federatedfilesharing'),
122
+            \OC::$server->getLogger(),
123
+            \OC::$server->getLazyRootFolder(),
124
+            \OC::$server->getConfig(),
125
+            \OC::$server->getUserManager(),
126
+            \OC::$server->getCloudIdManager()
127
+        );
128
+    }
129 129
 
130 130
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php 2 patches
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -42,107 +42,107 @@
 block discarded – undo
42 42
  */
43 43
 class RetryJob extends Job {
44 44
 
45
-	/** @var  bool */
46
-	private $retainJob = true;
47
-
48
-	/** @var Notifications */
49
-	private $notifications;
50
-
51
-	/** @var int max number of attempts to send the request */
52
-	private $maxTry = 20;
53
-
54
-	/** @var int how much time should be between two tries (10 minutes) */
55
-	private $interval = 600;
56
-
57
-	/**
58
-	 * UnShare constructor.
59
-	 *
60
-	 * @param Notifications $notifications
61
-	 */
62
-	public function __construct(Notifications $notifications = null) {
63
-		if ($notifications) {
64
-			$this->notifications = $notifications;
65
-		} else {
66
-			$addressHandler = new AddressHandler(
67
-				\OC::$server->getURLGenerator(),
68
-				\OC::$server->getL10N('federatedfilesharing'),
69
-				\OC::$server->getCloudIdManager()
70
-			);
71
-			$discoveryManager = new DiscoveryManager(
72
-				\OC::$server->getMemCacheFactory(),
73
-				\OC::$server->getHTTPClientService()
74
-			);
75
-			$this->notifications = new Notifications(
76
-				$addressHandler,
77
-				\OC::$server->getHTTPClientService(),
78
-				$discoveryManager,
79
-				\OC::$server->getJobList()
80
-			);
81
-		}
82
-
83
-	}
84
-
85
-	/**
86
-	 * run the job, then remove it from the jobList
87
-	 *
88
-	 * @param JobList $jobList
89
-	 * @param ILogger $logger
90
-	 */
91
-	public function execute($jobList, ILogger $logger = null) {
92
-
93
-		if ($this->shouldRun($this->argument)) {
94
-			parent::execute($jobList, $logger);
95
-			$jobList->remove($this, $this->argument);
96
-			if ($this->retainJob) {
97
-				$this->reAddJob($jobList, $this->argument);
98
-			}
99
-		}
100
-	}
101
-
102
-	protected function run($argument) {
103
-		$remote = $argument['remote'];
104
-		$remoteId = $argument['remoteId'];
105
-		$token = $argument['token'];
106
-		$action = $argument['action'];
107
-		$data = json_decode($argument['data'], true);
108
-		$try = (int)$argument['try'] + 1;
109
-
110
-		$result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
45
+    /** @var  bool */
46
+    private $retainJob = true;
47
+
48
+    /** @var Notifications */
49
+    private $notifications;
50
+
51
+    /** @var int max number of attempts to send the request */
52
+    private $maxTry = 20;
53
+
54
+    /** @var int how much time should be between two tries (10 minutes) */
55
+    private $interval = 600;
56
+
57
+    /**
58
+     * UnShare constructor.
59
+     *
60
+     * @param Notifications $notifications
61
+     */
62
+    public function __construct(Notifications $notifications = null) {
63
+        if ($notifications) {
64
+            $this->notifications = $notifications;
65
+        } else {
66
+            $addressHandler = new AddressHandler(
67
+                \OC::$server->getURLGenerator(),
68
+                \OC::$server->getL10N('federatedfilesharing'),
69
+                \OC::$server->getCloudIdManager()
70
+            );
71
+            $discoveryManager = new DiscoveryManager(
72
+                \OC::$server->getMemCacheFactory(),
73
+                \OC::$server->getHTTPClientService()
74
+            );
75
+            $this->notifications = new Notifications(
76
+                $addressHandler,
77
+                \OC::$server->getHTTPClientService(),
78
+                $discoveryManager,
79
+                \OC::$server->getJobList()
80
+            );
81
+        }
82
+
83
+    }
84
+
85
+    /**
86
+     * run the job, then remove it from the jobList
87
+     *
88
+     * @param JobList $jobList
89
+     * @param ILogger $logger
90
+     */
91
+    public function execute($jobList, ILogger $logger = null) {
92
+
93
+        if ($this->shouldRun($this->argument)) {
94
+            parent::execute($jobList, $logger);
95
+            $jobList->remove($this, $this->argument);
96
+            if ($this->retainJob) {
97
+                $this->reAddJob($jobList, $this->argument);
98
+            }
99
+        }
100
+    }
101
+
102
+    protected function run($argument) {
103
+        $remote = $argument['remote'];
104
+        $remoteId = $argument['remoteId'];
105
+        $token = $argument['token'];
106
+        $action = $argument['action'];
107
+        $data = json_decode($argument['data'], true);
108
+        $try = (int)$argument['try'] + 1;
109
+
110
+        $result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
111 111
 		
112
-		if ($result === true || $try > $this->maxTry) {
113
-			$this->retainJob = false;
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * re-add background job with new arguments
119
-	 *
120
-	 * @param IJobList $jobList
121
-	 * @param array $argument
122
-	 */
123
-	protected function reAddJob(IJobList $jobList, array $argument) {
124
-		$jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
125
-			[
126
-				'remote' => $argument['remote'],
127
-				'remoteId' => $argument['remoteId'],
128
-				'token' => $argument['token'],
129
-				'data' => $argument['data'],
130
-				'action' => $argument['action'],
131
-				'try' => (int)$argument['try'] + 1,
132
-				'lastRun' => time()
133
-			]
134
-		);
135
-	}
136
-
137
-	/**
138
-	 * test if it is time for the next run
139
-	 *
140
-	 * @param array $argument
141
-	 * @return bool
142
-	 */
143
-	protected function shouldRun(array $argument) {
144
-		$lastRun = (int)$argument['lastRun'];
145
-		return ((time() - $lastRun) > $this->interval);
146
-	}
112
+        if ($result === true || $try > $this->maxTry) {
113
+            $this->retainJob = false;
114
+        }
115
+    }
116
+
117
+    /**
118
+     * re-add background job with new arguments
119
+     *
120
+     * @param IJobList $jobList
121
+     * @param array $argument
122
+     */
123
+    protected function reAddJob(IJobList $jobList, array $argument) {
124
+        $jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
125
+            [
126
+                'remote' => $argument['remote'],
127
+                'remoteId' => $argument['remoteId'],
128
+                'token' => $argument['token'],
129
+                'data' => $argument['data'],
130
+                'action' => $argument['action'],
131
+                'try' => (int)$argument['try'] + 1,
132
+                'lastRun' => time()
133
+            ]
134
+        );
135
+    }
136
+
137
+    /**
138
+     * test if it is time for the next run
139
+     *
140
+     * @param array $argument
141
+     * @return bool
142
+     */
143
+    protected function shouldRun(array $argument) {
144
+        $lastRun = (int)$argument['lastRun'];
145
+        return ((time() - $lastRun) > $this->interval);
146
+    }
147 147
 
148 148
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 		$token = $argument['token'];
106 106
 		$action = $argument['action'];
107 107
 		$data = json_decode($argument['data'], true);
108
-		$try = (int)$argument['try'] + 1;
108
+		$try = (int) $argument['try'] + 1;
109 109
 
110 110
 		$result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
111 111
 		
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 				'token' => $argument['token'],
129 129
 				'data' => $argument['data'],
130 130
 				'action' => $argument['action'],
131
-				'try' => (int)$argument['try'] + 1,
131
+				'try' => (int) $argument['try'] + 1,
132 132
 				'lastRun' => time()
133 133
 			]
134 134
 		);
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	 * @return bool
142 142
 	 */
143 143
 	protected function shouldRun(array $argument) {
144
-		$lastRun = (int)$argument['lastRun'];
144
+		$lastRun = (int) $argument['lastRun'];
145 145
 		return ((time() - $lastRun) > $this->interval);
146 146
 	}
147 147
 
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Settings/Admin.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -29,42 +29,42 @@
 block discarded – undo
29 29
 
30 30
 class Admin implements ISettings {
31 31
 
32
-	/** @var FederatedShareProvider */
33
-	private $fedShareProvider;
32
+    /** @var FederatedShareProvider */
33
+    private $fedShareProvider;
34 34
 
35
-	public function __construct(FederatedShareProvider $fedShareProvider) {
36
-		$this->fedShareProvider = $fedShareProvider;
37
-	}
35
+    public function __construct(FederatedShareProvider $fedShareProvider) {
36
+        $this->fedShareProvider = $fedShareProvider;
37
+    }
38 38
 
39
-	/**
40
-	 * @return TemplateResponse
41
-	 */
42
-	public function getForm() {
43
-		$parameters = [
44
-			'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(),
45
-			'incomingServer2serverShareEnabled' => $this->fedShareProvider->isIncomingServer2serverShareEnabled(),
46
-			'lookupServerEnabled' => $this->fedShareProvider->isLookupServerQueriesEnabled(),
47
-		];
39
+    /**
40
+     * @return TemplateResponse
41
+     */
42
+    public function getForm() {
43
+        $parameters = [
44
+            'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(),
45
+            'incomingServer2serverShareEnabled' => $this->fedShareProvider->isIncomingServer2serverShareEnabled(),
46
+            'lookupServerEnabled' => $this->fedShareProvider->isLookupServerQueriesEnabled(),
47
+        ];
48 48
 
49
-		return new TemplateResponse('federatedfilesharing', 'settings-admin', $parameters, '');
50
-	}
49
+        return new TemplateResponse('federatedfilesharing', 'settings-admin', $parameters, '');
50
+    }
51 51
 
52
-	/**
53
-	 * @return string the section ID, e.g. 'sharing'
54
-	 */
55
-	public function getSection() {
56
-		return 'sharing';
57
-	}
52
+    /**
53
+     * @return string the section ID, e.g. 'sharing'
54
+     */
55
+    public function getSection() {
56
+        return 'sharing';
57
+    }
58 58
 
59
-	/**
60
-	 * @return int whether the form should be rather on the top or bottom of
61
-	 * the admin section. The forms are arranged in ascending order of the
62
-	 * priority values. It is required to return a value between 0 and 100.
63
-	 *
64
-	 * E.g.: 70
65
-	 */
66
-	public function getPriority() {
67
-		return 20;
68
-	}
59
+    /**
60
+     * @return int whether the form should be rather on the top or bottom of
61
+     * the admin section. The forms are arranged in ascending order of the
62
+     * priority values. It is required to return a value between 0 and 100.
63
+     *
64
+     * E.g.: 70
65
+     */
66
+    public function getPriority() {
67
+        return 20;
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/TokenHandler.php 2 patches
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -33,30 +33,30 @@
 block discarded – undo
33 33
  */
34 34
 class TokenHandler {
35 35
 
36
-	const TOKEN_LENGTH = 15;
37
-
38
-	/** @var ISecureRandom */
39
-	private $secureRandom;
40
-
41
-	/**
42
-	 * TokenHandler constructor.
43
-	 *
44
-	 * @param ISecureRandom $secureRandom
45
-	 */
46
-	public function __construct(ISecureRandom $secureRandom) {
47
-		$this->secureRandom = $secureRandom;
48
-	}
49
-
50
-	/**
51
-	 * generate to token used to authenticate federated shares
52
-	 *
53
-	 * @return string
54
-	 */
55
-	public function generateToken() {
56
-		$token = $this->secureRandom->generate(
57
-			self::TOKEN_LENGTH,
58
-			ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
59
-		return $token;
60
-	}
36
+    const TOKEN_LENGTH = 15;
37
+
38
+    /** @var ISecureRandom */
39
+    private $secureRandom;
40
+
41
+    /**
42
+     * TokenHandler constructor.
43
+     *
44
+     * @param ISecureRandom $secureRandom
45
+     */
46
+    public function __construct(ISecureRandom $secureRandom) {
47
+        $this->secureRandom = $secureRandom;
48
+    }
49
+
50
+    /**
51
+     * generate to token used to authenticate federated shares
52
+     *
53
+     * @return string
54
+     */
55
+    public function generateToken() {
56
+        $token = $this->secureRandom->generate(
57
+            self::TOKEN_LENGTH,
58
+            ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
59
+        return $token;
60
+    }
61 61
 
62 62
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@
 block discarded – undo
55 55
 	public function generateToken() {
56 56
 		$token = $this->secureRandom->generate(
57 57
 			self::TOKEN_LENGTH,
58
-			ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
58
+			ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
59 59
 		return $token;
60 60
 	}
61 61
 
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AddressHandler.php 1 patch
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -33,122 +33,122 @@
 block discarded – undo
33 33
  */
34 34
 class AddressHandler {
35 35
 
36
-	/** @var IL10N */
37
-	private $l;
38
-
39
-	/** @var IURLGenerator */
40
-	private $urlGenerator;
41
-
42
-	/** @var ICloudIdManager */
43
-	private $cloudIdManager;
44
-
45
-	/**
46
-	 * AddressHandler constructor.
47
-	 *
48
-	 * @param IURLGenerator $urlGenerator
49
-	 * @param IL10N $il10n
50
-	 * @param ICloudIdManager $cloudIdManager
51
-	 */
52
-	public function __construct(
53
-		IURLGenerator $urlGenerator,
54
-		IL10N $il10n,
55
-		ICloudIdManager $cloudIdManager
56
-	) {
57
-		$this->l = $il10n;
58
-		$this->urlGenerator = $urlGenerator;
59
-		$this->cloudIdManager = $cloudIdManager;
60
-	}
61
-
62
-	/**
63
-	 * split user and remote from federated cloud id
64
-	 *
65
-	 * @param string $address federated share address
66
-	 * @return array [user, remoteURL]
67
-	 * @throws HintException
68
-	 */
69
-	public function splitUserRemote($address) {
70
-		try {
71
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
72
-			return [$cloudId->getUser(), $cloudId->getRemote()];
73
-		} catch (\InvalidArgumentException $e) {
74
-			$hint = $this->l->t('Invalid Federated Cloud ID');
75
-			throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
76
-		}
77
-	}
78
-
79
-	/**
80
-	 * generate remote URL part of federated ID
81
-	 *
82
-	 * @return string url of the current server
83
-	 */
84
-	public function generateRemoteURL() {
85
-		$url = $this->urlGenerator->getAbsoluteURL('/');
86
-		return $url;
87
-	}
88
-
89
-	/**
90
-	 * check if two federated cloud IDs refer to the same user
91
-	 *
92
-	 * @param string $user1
93
-	 * @param string $server1
94
-	 * @param string $user2
95
-	 * @param string $server2
96
-	 * @return bool true if both users and servers are the same
97
-	 */
98
-	public function compareAddresses($user1, $server1, $user2, $server2) {
99
-		$normalizedServer1 = strtolower($this->removeProtocolFromUrl($server1));
100
-		$normalizedServer2 = strtolower($this->removeProtocolFromUrl($server2));
101
-
102
-		if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
103
-			// FIXME this should be a method in the user management instead
104
-			\OCP\Util::emitHook(
105
-				'\OCA\Files_Sharing\API\Server2Server',
106
-				'preLoginNameUsedAsUserName',
107
-				array('uid' => &$user1)
108
-			);
109
-			\OCP\Util::emitHook(
110
-				'\OCA\Files_Sharing\API\Server2Server',
111
-				'preLoginNameUsedAsUserName',
112
-				array('uid' => &$user2)
113
-			);
114
-
115
-			if ($user1 === $user2) {
116
-				return true;
117
-			}
118
-		}
119
-
120
-		return false;
121
-	}
122
-
123
-	/**
124
-	 * remove protocol from URL
125
-	 *
126
-	 * @param string $url
127
-	 * @return string
128
-	 */
129
-	public function removeProtocolFromUrl($url) {
130
-		if (strpos($url, 'https://') === 0) {
131
-			return substr($url, strlen('https://'));
132
-		} else if (strpos($url, 'http://') === 0) {
133
-			return substr($url, strlen('http://'));
134
-		}
135
-
136
-		return $url;
137
-	}
138
-
139
-	/**
140
-	 * check if the url contain the protocol (http or https)
141
-	 *
142
-	 * @param string $url
143
-	 * @return bool
144
-	 */
145
-	public function urlContainProtocol($url) {
146
-		if (strpos($url, 'https://') === 0 ||
147
-			strpos($url, 'http://') === 0) {
148
-
149
-			return true;
150
-		}
151
-
152
-		return false;
153
-	}
36
+    /** @var IL10N */
37
+    private $l;
38
+
39
+    /** @var IURLGenerator */
40
+    private $urlGenerator;
41
+
42
+    /** @var ICloudIdManager */
43
+    private $cloudIdManager;
44
+
45
+    /**
46
+     * AddressHandler constructor.
47
+     *
48
+     * @param IURLGenerator $urlGenerator
49
+     * @param IL10N $il10n
50
+     * @param ICloudIdManager $cloudIdManager
51
+     */
52
+    public function __construct(
53
+        IURLGenerator $urlGenerator,
54
+        IL10N $il10n,
55
+        ICloudIdManager $cloudIdManager
56
+    ) {
57
+        $this->l = $il10n;
58
+        $this->urlGenerator = $urlGenerator;
59
+        $this->cloudIdManager = $cloudIdManager;
60
+    }
61
+
62
+    /**
63
+     * split user and remote from federated cloud id
64
+     *
65
+     * @param string $address federated share address
66
+     * @return array [user, remoteURL]
67
+     * @throws HintException
68
+     */
69
+    public function splitUserRemote($address) {
70
+        try {
71
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
72
+            return [$cloudId->getUser(), $cloudId->getRemote()];
73
+        } catch (\InvalidArgumentException $e) {
74
+            $hint = $this->l->t('Invalid Federated Cloud ID');
75
+            throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
76
+        }
77
+    }
78
+
79
+    /**
80
+     * generate remote URL part of federated ID
81
+     *
82
+     * @return string url of the current server
83
+     */
84
+    public function generateRemoteURL() {
85
+        $url = $this->urlGenerator->getAbsoluteURL('/');
86
+        return $url;
87
+    }
88
+
89
+    /**
90
+     * check if two federated cloud IDs refer to the same user
91
+     *
92
+     * @param string $user1
93
+     * @param string $server1
94
+     * @param string $user2
95
+     * @param string $server2
96
+     * @return bool true if both users and servers are the same
97
+     */
98
+    public function compareAddresses($user1, $server1, $user2, $server2) {
99
+        $normalizedServer1 = strtolower($this->removeProtocolFromUrl($server1));
100
+        $normalizedServer2 = strtolower($this->removeProtocolFromUrl($server2));
101
+
102
+        if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
103
+            // FIXME this should be a method in the user management instead
104
+            \OCP\Util::emitHook(
105
+                '\OCA\Files_Sharing\API\Server2Server',
106
+                'preLoginNameUsedAsUserName',
107
+                array('uid' => &$user1)
108
+            );
109
+            \OCP\Util::emitHook(
110
+                '\OCA\Files_Sharing\API\Server2Server',
111
+                'preLoginNameUsedAsUserName',
112
+                array('uid' => &$user2)
113
+            );
114
+
115
+            if ($user1 === $user2) {
116
+                return true;
117
+            }
118
+        }
119
+
120
+        return false;
121
+    }
122
+
123
+    /**
124
+     * remove protocol from URL
125
+     *
126
+     * @param string $url
127
+     * @return string
128
+     */
129
+    public function removeProtocolFromUrl($url) {
130
+        if (strpos($url, 'https://') === 0) {
131
+            return substr($url, strlen('https://'));
132
+        } else if (strpos($url, 'http://') === 0) {
133
+            return substr($url, strlen('http://'));
134
+        }
135
+
136
+        return $url;
137
+    }
138
+
139
+    /**
140
+     * check if the url contain the protocol (http or https)
141
+     *
142
+     * @param string $url
143
+     * @return bool
144
+     */
145
+    public function urlContainProtocol($url) {
146
+        if (strpos($url, 'https://') === 0 ||
147
+            strpos($url, 'http://') === 0) {
148
+
149
+            return true;
150
+        }
151
+
152
+        return false;
153
+    }
154 154
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/appinfo/routes.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -23,17 +23,17 @@
 block discarded – undo
23 23
  */
24 24
 
25 25
 return [
26
-	'routes' => [
27
-		['name' => 'MountPublicLink#createFederatedShare', 'url' => '/createFederatedShare', 'verb' => 'POST'],
28
-		['name' => 'MountPublicLink#askForFederatedShare', 'url' => '/askForFederatedShare', 'verb' => 'POST'],
29
-	],
30
-	'ocs' => [
31
-		['root' => '/cloud', 'name' => 'RequestHandler#createShare', 'url' => '/shares', 'verb' => 'POST'],
32
-		['root' => '/cloud', 'name' => 'RequestHandler#reShare', 'url' => '/shares/{id}/reshare', 'verb' => 'POST'],
33
-		['root' => '/cloud', 'name' => 'RequestHandler#updatePermissions', 'url' => '/shares/{id}/permissions', 'verb' => 'POST'],
34
-		['root' => '/cloud', 'name' => 'RequestHandler#acceptShare', 'url' => '/shares/{id}/accept', 'verb' => 'POST'],
35
-		['root' => '/cloud', 'name' => 'RequestHandler#declineShare', 'url' => '/shares/{id}/decline', 'verb' => 'POST'],
36
-		['root' => '/cloud', 'name' => 'RequestHandler#unshare', 'url' => '/shares/{id}/unshare', 'verb' => 'POST'],
37
-		['root' => '/cloud', 'name' => 'RequestHandler#revoke', 'url' => '/shares/{id}/revoke', 'verb' => 'POST'],
38
-	],
26
+    'routes' => [
27
+        ['name' => 'MountPublicLink#createFederatedShare', 'url' => '/createFederatedShare', 'verb' => 'POST'],
28
+        ['name' => 'MountPublicLink#askForFederatedShare', 'url' => '/askForFederatedShare', 'verb' => 'POST'],
29
+    ],
30
+    'ocs' => [
31
+        ['root' => '/cloud', 'name' => 'RequestHandler#createShare', 'url' => '/shares', 'verb' => 'POST'],
32
+        ['root' => '/cloud', 'name' => 'RequestHandler#reShare', 'url' => '/shares/{id}/reshare', 'verb' => 'POST'],
33
+        ['root' => '/cloud', 'name' => 'RequestHandler#updatePermissions', 'url' => '/shares/{id}/permissions', 'verb' => 'POST'],
34
+        ['root' => '/cloud', 'name' => 'RequestHandler#acceptShare', 'url' => '/shares/{id}/accept', 'verb' => 'POST'],
35
+        ['root' => '/cloud', 'name' => 'RequestHandler#declineShare', 'url' => '/shares/{id}/decline', 'verb' => 'POST'],
36
+        ['root' => '/cloud', 'name' => 'RequestHandler#unshare', 'url' => '/shares/{id}/unshare', 'verb' => 'POST'],
37
+        ['root' => '/cloud', 'name' => 'RequestHandler#revoke', 'url' => '/shares/{id}/revoke', 'verb' => 'POST'],
38
+    ],
39 39
 ];
Please login to merge, or discard this patch.