Completed
Push — master ( c65848...a5c801 )
by Blizzz
112:32 queued 99:32
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/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/federation/templates/settings-admin.php 3 patches
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -28,10 +28,10 @@
 block discarded – undo
28 28
 				<?php if((int)$trustedServer['status'] === TrustedServers::STATUS_OK) { ?>
29 29
 					<span class="status success"></span>
30 30
 				<?php
31
-				} elseif(
32
-					(int)$trustedServer['status'] === TrustedServers::STATUS_PENDING ||
33
-					(int)$trustedServer['status'] === TrustedServers::STATUS_ACCESS_REVOKED
34
-				) { ?>
31
+                } elseif(
32
+                    (int)$trustedServer['status'] === TrustedServers::STATUS_PENDING ||
33
+                    (int)$trustedServer['status'] === TrustedServers::STATUS_ACCESS_REVOKED
34
+                ) { ?>
35 35
 					<span class="status indeterminate"></span>
36 36
 				<?php } else {?>
37 37
 					<span class="status error"></span>
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 	<em><?php p($l->t('Federation allows you to connect with other trusted servers to exchange the user directory. For example this will be used to auto-complete external users for federated sharing.')); ?></em>
12 12
 
13 13
 	<p>
14
-		<input id="autoAddServers" type="checkbox" class="checkbox" <?php if($_['autoAddServers']) p('checked'); ?> />
14
+		<input id="autoAddServers" type="checkbox" class="checkbox" <?php if ($_['autoAddServers']) p('checked'); ?> />
15 15
 		<label for="autoAddServers"><?php p($l->t('Add server automatically once a federated share was created successfully')); ?></label>
16 16
 	</p>
17 17
 
@@ -23,14 +23,14 @@  discard block
 block discarded – undo
23 23
 		<span class="msg"></span>
24 24
 	</p>
25 25
 	<ul id="listOfTrustedServers">
26
-		<?php foreach($_['trustedServers'] as $trustedServer) { ?>
26
+		<?php foreach ($_['trustedServers'] as $trustedServer) { ?>
27 27
 			<li id="<?php p($trustedServer['id']); ?>">
28
-				<?php if((int)$trustedServer['status'] === TrustedServers::STATUS_OK) { ?>
28
+				<?php if ((int) $trustedServer['status'] === TrustedServers::STATUS_OK) { ?>
29 29
 					<span class="status success"></span>
30 30
 				<?php
31
-				} elseif(
32
-					(int)$trustedServer['status'] === TrustedServers::STATUS_PENDING ||
33
-					(int)$trustedServer['status'] === TrustedServers::STATUS_ACCESS_REVOKED
31
+				} elseif (
32
+					(int) $trustedServer['status'] === TrustedServers::STATUS_PENDING ||
33
+					(int) $trustedServer['status'] === TrustedServers::STATUS_ACCESS_REVOKED
34 34
 				) { ?>
35 35
 					<span class="status indeterminate"></span>
36 36
 				<?php } else {?>
Please login to merge, or discard this patch.
Braces   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -11,7 +11,10 @@
 block discarded – undo
11 11
 	<em><?php p($l->t('Federation allows you to connect with other trusted servers to exchange the user directory. For example this will be used to auto-complete external users for federated sharing.')); ?></em>
12 12
 
13 13
 	<p>
14
-		<input id="autoAddServers" type="checkbox" class="checkbox" <?php if($_['autoAddServers']) p('checked'); ?> />
14
+		<input id="autoAddServers" type="checkbox" class="checkbox" <?php if($_['autoAddServers']) {
15
+    p('checked');
16
+}
17
+?> />
15 18
 		<label for="autoAddServers"><?php p($l->t('Add server automatically once a federated share was created successfully')); ?></label>
16 19
 	</p>
17 20
 
Please login to merge, or discard this patch.
apps/federation/lib/DAV/FedAuth.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -29,40 +29,40 @@
 block discarded – undo
29 29
 
30 30
 class FedAuth extends AbstractBasic {
31 31
 
32
-	/** @var DbHandler */
33
-	private $db;
32
+    /** @var DbHandler */
33
+    private $db;
34 34
 
35
-	/**
36
-	 * FedAuth constructor.
37
-	 *
38
-	 * @param DbHandler $db
39
-	 */
40
-	public function __construct(DbHandler $db) {
41
-		$this->db = $db;
42
-		$this->principalPrefix = 'principals/system/';
35
+    /**
36
+     * FedAuth constructor.
37
+     *
38
+     * @param DbHandler $db
39
+     */
40
+    public function __construct(DbHandler $db) {
41
+        $this->db = $db;
42
+        $this->principalPrefix = 'principals/system/';
43 43
 
44
-		// setup realm
45
-		$defaults = new \OCP\Defaults();
46
-		$this->realm = $defaults->getName();
47
-	}
44
+        // setup realm
45
+        $defaults = new \OCP\Defaults();
46
+        $this->realm = $defaults->getName();
47
+    }
48 48
 
49
-	/**
50
-	 * Validates a username and password
51
-	 *
52
-	 * This method should return true or false depending on if login
53
-	 * succeeded.
54
-	 *
55
-	 * @param string $username
56
-	 * @param string $password
57
-	 * @return bool
58
-	 */
59
-	protected function validateUserPass($username, $password) {
60
-		return $this->db->auth($username, $password);
61
-	}
49
+    /**
50
+     * Validates a username and password
51
+     *
52
+     * This method should return true or false depending on if login
53
+     * succeeded.
54
+     *
55
+     * @param string $username
56
+     * @param string $password
57
+     * @return bool
58
+     */
59
+    protected function validateUserPass($username, $password) {
60
+        return $this->db->auth($username, $password);
61
+    }
62 62
 
63
-	/**
64
-	 * @inheritdoc
65
-	 */
66
-	function challenge(RequestInterface $request, ResponseInterface $response) {
67
-	}
63
+    /**
64
+     * @inheritdoc
65
+     */
66
+    function challenge(RequestInterface $request, ResponseInterface $response) {
67
+    }
68 68
 }
Please login to merge, or discard this patch.