Completed
Pull Request — master (#4212)
by Individual IT
13:52
created
apps/testing/appinfo/routes.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -27,31 +27,31 @@
 block discarded – undo
27 27
 use OCP\API;
28 28
 
29 29
 $config = new Config(
30
-	\OC::$server->getConfig(),
31
-	\OC::$server->getRequest()
30
+    \OC::$server->getConfig(),
31
+    \OC::$server->getRequest()
32 32
 );
33 33
 
34 34
 API::register(
35
-	'post',
36
-	'/apps/testing/api/v1/app/{appid}/{configkey}',
37
-	[$config, 'setAppValue'],
38
-	'testing',
39
-	API::ADMIN_AUTH
35
+    'post',
36
+    '/apps/testing/api/v1/app/{appid}/{configkey}',
37
+    [$config, 'setAppValue'],
38
+    'testing',
39
+    API::ADMIN_AUTH
40 40
 );
41 41
 
42 42
 API::register(
43
-	'delete',
44
-	'/apps/testing/api/v1/app/{appid}/{configkey}',
45
-	[$config, 'deleteAppValue'],
46
-	'testing',
47
-	API::ADMIN_AUTH
43
+    'delete',
44
+    '/apps/testing/api/v1/app/{appid}/{configkey}',
45
+    [$config, 'deleteAppValue'],
46
+    'testing',
47
+    API::ADMIN_AUTH
48 48
 );
49 49
 
50 50
 $locking = new Provisioning(
51
-	\OC::$server->getLockingProvider(),
52
-	\OC::$server->getDatabaseConnection(),
53
-	\OC::$server->getConfig(),
54
-	\OC::$server->getRequest()
51
+    \OC::$server->getLockingProvider(),
52
+    \OC::$server->getDatabaseConnection(),
53
+    \OC::$server->getConfig(),
54
+    \OC::$server->getRequest()
55 55
 );
56 56
 API::register('get', '/apps/testing/api/v1/lockprovisioning', [$locking, 'isLockingEnabled'], 'files_lockprovisioning', API::ADMIN_AUTH);
57 57
 API::register('get', '/apps/testing/api/v1/lockprovisioning/{type}/{user}', [$locking, 'isLocked'], 'files_lockprovisioning', API::ADMIN_AUTH);
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 1 patch
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -32,279 +32,279 @@
 block discarded – undo
32 32
 use OCP\Http\Client\IClientService;
33 33
 
34 34
 class Notifications {
35
-	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
36
-
37
-	/** @var AddressHandler */
38
-	private $addressHandler;
39
-
40
-	/** @var IClientService */
41
-	private $httpClientService;
42
-
43
-	/** @var DiscoveryManager */
44
-	private $discoveryManager;
45
-
46
-	/** @var IJobList  */
47
-	private $jobList;
48
-
49
-	/**
50
-	 * @param AddressHandler $addressHandler
51
-	 * @param IClientService $httpClientService
52
-	 * @param DiscoveryManager $discoveryManager
53
-	 * @param IJobList $jobList
54
-	 */
55
-	public function __construct(
56
-		AddressHandler $addressHandler,
57
-		IClientService $httpClientService,
58
-		DiscoveryManager $discoveryManager,
59
-		IJobList $jobList
60
-	) {
61
-		$this->addressHandler = $addressHandler;
62
-		$this->httpClientService = $httpClientService;
63
-		$this->discoveryManager = $discoveryManager;
64
-		$this->jobList = $jobList;
65
-	}
66
-
67
-	/**
68
-	 * send server-to-server share to remote server
69
-	 *
70
-	 * @param string $token
71
-	 * @param string $shareWith
72
-	 * @param string $name
73
-	 * @param int $remote_id
74
-	 * @param string $owner
75
-	 * @param string $ownerFederatedId
76
-	 * @param string $sharedBy
77
-	 * @param string $sharedByFederatedId
78
-	 * @return bool
79
-	 * @throws \OC\HintException
80
-	 * @throws \OC\ServerNotAvailableException
81
-	 */
82
-	public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
83
-
84
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
85
-
86
-		if ($user && $remote) {
87
-			$local = $this->addressHandler->generateRemoteURL();
88
-
89
-			$fields = array(
90
-				'shareWith' => $user,
91
-				'token' => $token,
92
-				'name' => $name,
93
-				'remoteId' => $remote_id,
94
-				'owner' => $owner,
95
-				'ownerFederatedId' => $ownerFederatedId,
96
-				'sharedBy' => $sharedBy,
97
-				'sharedByFederatedId' => $sharedByFederatedId,
98
-				'remote' => $local,
99
-			);
100
-
101
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
102
-			$status = json_decode($result['result'], true);
103
-
104
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
105
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
106
-				return true;
107
-			}
108
-
109
-		}
110
-
111
-		return false;
112
-	}
113
-
114
-	/**
115
-	 * ask owner to re-share the file with the given user
116
-	 *
117
-	 * @param string $token
118
-	 * @param int $id remote Id
119
-	 * @param int $shareId internal share Id
120
-	 * @param string $remote remote address of the owner
121
-	 * @param string $shareWith
122
-	 * @param int $permission
123
-	 * @return bool
124
-	 * @throws \OC\HintException
125
-	 * @throws \OC\ServerNotAvailableException
126
-	 */
127
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission) {
128
-
129
-		$fields = array(
130
-			'shareWith' => $shareWith,
131
-			'token' => $token,
132
-			'permission' => $permission,
133
-			'remoteId' => $shareId
134
-		);
135
-
136
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
137
-		$status = json_decode($result['result'], true);
138
-
139
-		$httpRequestSuccessful = $result['success'];
140
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
141
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
142
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
143
-
144
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
145
-			return [
146
-				$status['ocs']['data']['token'],
147
-				(int)$status['ocs']['data']['remoteId']
148
-			];
149
-		}
150
-
151
-		return false;
152
-	}
153
-
154
-	/**
155
-	 * send server-to-server unshare to remote server
156
-	 *
157
-	 * @param string $remote url
158
-	 * @param int $id share id
159
-	 * @param string $token
160
-	 * @return bool
161
-	 */
162
-	public function sendRemoteUnShare($remote, $id, $token) {
163
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
164
-	}
165
-
166
-	/**
167
-	 * send server-to-server unshare to remote server
168
-	 *
169
-	 * @param string $remote url
170
-	 * @param int $id share id
171
-	 * @param string $token
172
-	 * @return bool
173
-	 */
174
-	public function sendRevokeShare($remote, $id, $token) {
175
-		$this->sendUpdateToRemote($remote, $id, $token, 'revoke');
176
-	}
177
-
178
-	/**
179
-	 * send notification to remote server if the permissions was changed
180
-	 *
181
-	 * @param string $remote
182
-	 * @param int $remoteId
183
-	 * @param string $token
184
-	 * @param int $permissions
185
-	 * @return bool
186
-	 */
187
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
188
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
189
-	}
190
-
191
-	/**
192
-	 * forward accept reShare to remote server
193
-	 *
194
-	 * @param string $remote
195
-	 * @param int $remoteId
196
-	 * @param string $token
197
-	 */
198
-	public function sendAcceptShare($remote, $remoteId, $token) {
199
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
200
-	}
201
-
202
-	/**
203
-	 * forward decline reShare to remote server
204
-	 *
205
-	 * @param string $remote
206
-	 * @param int $remoteId
207
-	 * @param string $token
208
-	 */
209
-	public function sendDeclineShare($remote, $remoteId, $token) {
210
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
211
-	}
212
-
213
-	/**
214
-	 * inform remote server whether server-to-server share was accepted/declined
215
-	 *
216
-	 * @param string $remote
217
-	 * @param string $token
218
-	 * @param int $remoteId Share id on the remote host
219
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
220
-	 * @param array $data
221
-	 * @param int $try
222
-	 * @return boolean
223
-	 */
224
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
225
-
226
-		$fields = array('token' => $token);
227
-		foreach ($data as $key => $value) {
228
-			$fields[$key] = $value;
229
-		}
230
-
231
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields);
232
-		$status = json_decode($result['result'], true);
233
-
234
-		if ($result['success'] &&
235
-			($status['ocs']['meta']['statuscode'] === 100 ||
236
-				$status['ocs']['meta']['statuscode'] === 200
237
-			)
238
-		) {
239
-			return true;
240
-		} elseif ($try === 0) {
241
-			// only add new job on first try
242
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
243
-				[
244
-					'remote' => $remote,
245
-					'remoteId' => $remoteId,
246
-					'token' => $token,
247
-					'action' => $action,
248
-					'data' => json_encode($data),
249
-					'try' => $try,
250
-					'lastRun' => $this->getTimestamp()
251
-				]
252
-			);
253
-		}
254
-
255
-		return false;
256
-	}
257
-
258
-
259
-	/**
260
-	 * return current timestamp
261
-	 *
262
-	 * @return int
263
-	 */
264
-	protected function getTimestamp() {
265
-		return time();
266
-	}
267
-
268
-	/**
269
-	 * try http post with the given protocol, if no protocol is given we pick
270
-	 * the secure one (https)
271
-	 *
272
-	 * @param string $remoteDomain
273
-	 * @param string $urlSuffix
274
-	 * @param array $fields post parameters
275
-	 * @return array
276
-	 * @throws \Exception
277
-	 */
278
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
279
-		$client = $this->httpClientService->newClient();
280
-
281
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
282
-			$remoteDomain = 'https://' . $remoteDomain;
283
-		}
284
-
285
-		$result = [
286
-			'success' => false,
287
-			'result' => '',
288
-		];
289
-
290
-		$endpoint = $this->discoveryManager->getShareEndpoint($remoteDomain);
291
-		try {
292
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
293
-				'body' => $fields,
294
-				'timeout' => 10,
295
-				'connect_timeout' => 10,
296
-			]);
297
-			$result['result'] = $response->getBody();
298
-			$result['success'] = true;
299
-		} catch (\Exception $e) {
300
-			// if flat re-sharing is not supported by the remote server
301
-			// we re-throw the exception and fall back to the old behaviour.
302
-			// (flat re-shares has been introduced in Nextcloud 9.1)
303
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
304
-				throw $e;
305
-			}
306
-		}
307
-
308
-		return $result;
309
-	}
35
+    const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
36
+
37
+    /** @var AddressHandler */
38
+    private $addressHandler;
39
+
40
+    /** @var IClientService */
41
+    private $httpClientService;
42
+
43
+    /** @var DiscoveryManager */
44
+    private $discoveryManager;
45
+
46
+    /** @var IJobList  */
47
+    private $jobList;
48
+
49
+    /**
50
+     * @param AddressHandler $addressHandler
51
+     * @param IClientService $httpClientService
52
+     * @param DiscoveryManager $discoveryManager
53
+     * @param IJobList $jobList
54
+     */
55
+    public function __construct(
56
+        AddressHandler $addressHandler,
57
+        IClientService $httpClientService,
58
+        DiscoveryManager $discoveryManager,
59
+        IJobList $jobList
60
+    ) {
61
+        $this->addressHandler = $addressHandler;
62
+        $this->httpClientService = $httpClientService;
63
+        $this->discoveryManager = $discoveryManager;
64
+        $this->jobList = $jobList;
65
+    }
66
+
67
+    /**
68
+     * send server-to-server share to remote server
69
+     *
70
+     * @param string $token
71
+     * @param string $shareWith
72
+     * @param string $name
73
+     * @param int $remote_id
74
+     * @param string $owner
75
+     * @param string $ownerFederatedId
76
+     * @param string $sharedBy
77
+     * @param string $sharedByFederatedId
78
+     * @return bool
79
+     * @throws \OC\HintException
80
+     * @throws \OC\ServerNotAvailableException
81
+     */
82
+    public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
83
+
84
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
85
+
86
+        if ($user && $remote) {
87
+            $local = $this->addressHandler->generateRemoteURL();
88
+
89
+            $fields = array(
90
+                'shareWith' => $user,
91
+                'token' => $token,
92
+                'name' => $name,
93
+                'remoteId' => $remote_id,
94
+                'owner' => $owner,
95
+                'ownerFederatedId' => $ownerFederatedId,
96
+                'sharedBy' => $sharedBy,
97
+                'sharedByFederatedId' => $sharedByFederatedId,
98
+                'remote' => $local,
99
+            );
100
+
101
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
102
+            $status = json_decode($result['result'], true);
103
+
104
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
105
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
106
+                return true;
107
+            }
108
+
109
+        }
110
+
111
+        return false;
112
+    }
113
+
114
+    /**
115
+     * ask owner to re-share the file with the given user
116
+     *
117
+     * @param string $token
118
+     * @param int $id remote Id
119
+     * @param int $shareId internal share Id
120
+     * @param string $remote remote address of the owner
121
+     * @param string $shareWith
122
+     * @param int $permission
123
+     * @return bool
124
+     * @throws \OC\HintException
125
+     * @throws \OC\ServerNotAvailableException
126
+     */
127
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission) {
128
+
129
+        $fields = array(
130
+            'shareWith' => $shareWith,
131
+            'token' => $token,
132
+            'permission' => $permission,
133
+            'remoteId' => $shareId
134
+        );
135
+
136
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
137
+        $status = json_decode($result['result'], true);
138
+
139
+        $httpRequestSuccessful = $result['success'];
140
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
141
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
142
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
143
+
144
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
145
+            return [
146
+                $status['ocs']['data']['token'],
147
+                (int)$status['ocs']['data']['remoteId']
148
+            ];
149
+        }
150
+
151
+        return false;
152
+    }
153
+
154
+    /**
155
+     * send server-to-server unshare to remote server
156
+     *
157
+     * @param string $remote url
158
+     * @param int $id share id
159
+     * @param string $token
160
+     * @return bool
161
+     */
162
+    public function sendRemoteUnShare($remote, $id, $token) {
163
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
164
+    }
165
+
166
+    /**
167
+     * send server-to-server unshare to remote server
168
+     *
169
+     * @param string $remote url
170
+     * @param int $id share id
171
+     * @param string $token
172
+     * @return bool
173
+     */
174
+    public function sendRevokeShare($remote, $id, $token) {
175
+        $this->sendUpdateToRemote($remote, $id, $token, 'revoke');
176
+    }
177
+
178
+    /**
179
+     * send notification to remote server if the permissions was changed
180
+     *
181
+     * @param string $remote
182
+     * @param int $remoteId
183
+     * @param string $token
184
+     * @param int $permissions
185
+     * @return bool
186
+     */
187
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
188
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
189
+    }
190
+
191
+    /**
192
+     * forward accept reShare to remote server
193
+     *
194
+     * @param string $remote
195
+     * @param int $remoteId
196
+     * @param string $token
197
+     */
198
+    public function sendAcceptShare($remote, $remoteId, $token) {
199
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
200
+    }
201
+
202
+    /**
203
+     * forward decline reShare to remote server
204
+     *
205
+     * @param string $remote
206
+     * @param int $remoteId
207
+     * @param string $token
208
+     */
209
+    public function sendDeclineShare($remote, $remoteId, $token) {
210
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
211
+    }
212
+
213
+    /**
214
+     * inform remote server whether server-to-server share was accepted/declined
215
+     *
216
+     * @param string $remote
217
+     * @param string $token
218
+     * @param int $remoteId Share id on the remote host
219
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
220
+     * @param array $data
221
+     * @param int $try
222
+     * @return boolean
223
+     */
224
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
225
+
226
+        $fields = array('token' => $token);
227
+        foreach ($data as $key => $value) {
228
+            $fields[$key] = $value;
229
+        }
230
+
231
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields);
232
+        $status = json_decode($result['result'], true);
233
+
234
+        if ($result['success'] &&
235
+            ($status['ocs']['meta']['statuscode'] === 100 ||
236
+                $status['ocs']['meta']['statuscode'] === 200
237
+            )
238
+        ) {
239
+            return true;
240
+        } elseif ($try === 0) {
241
+            // only add new job on first try
242
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
243
+                [
244
+                    'remote' => $remote,
245
+                    'remoteId' => $remoteId,
246
+                    'token' => $token,
247
+                    'action' => $action,
248
+                    'data' => json_encode($data),
249
+                    'try' => $try,
250
+                    'lastRun' => $this->getTimestamp()
251
+                ]
252
+            );
253
+        }
254
+
255
+        return false;
256
+    }
257
+
258
+
259
+    /**
260
+     * return current timestamp
261
+     *
262
+     * @return int
263
+     */
264
+    protected function getTimestamp() {
265
+        return time();
266
+    }
267
+
268
+    /**
269
+     * try http post with the given protocol, if no protocol is given we pick
270
+     * the secure one (https)
271
+     *
272
+     * @param string $remoteDomain
273
+     * @param string $urlSuffix
274
+     * @param array $fields post parameters
275
+     * @return array
276
+     * @throws \Exception
277
+     */
278
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
279
+        $client = $this->httpClientService->newClient();
280
+
281
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
282
+            $remoteDomain = 'https://' . $remoteDomain;
283
+        }
284
+
285
+        $result = [
286
+            'success' => false,
287
+            'result' => '',
288
+        ];
289
+
290
+        $endpoint = $this->discoveryManager->getShareEndpoint($remoteDomain);
291
+        try {
292
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
293
+                'body' => $fields,
294
+                'timeout' => 10,
295
+                'connect_timeout' => 10,
296
+            ]);
297
+            $result['result'] = $response->getBody();
298
+            $result['success'] = true;
299
+        } catch (\Exception $e) {
300
+            // if flat re-sharing is not supported by the remote server
301
+            // we re-throw the exception and fall back to the old behaviour.
302
+            // (flat re-shares has been introduced in Nextcloud 9.1)
303
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
304
+                throw $e;
305
+            }
306
+        }
307
+
308
+        return $result;
309
+    }
310 310
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifier.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -34,197 +34,197 @@
 block discarded – undo
34 34
 use OCP\Notification\INotifier;
35 35
 
36 36
 class Notifier implements INotifier {
37
-	/** @var IFactory */
38
-	protected $factory;
39
-	/** @var IManager */
40
-	protected $contactsManager;
41
-	/** @var IURLGenerator */
42
-	protected $url;
43
-	/** @var array */
44
-	protected $federatedContacts;
45
-	/** @var ICloudIdManager */
46
-	protected $cloudIdManager;
47
-
48
-	/**
49
-	 * @param IFactory $factory
50
-	 * @param IManager $contactsManager
51
-	 * @param IURLGenerator $url
52
-	 * @param ICloudIdManager $cloudIdManager
53
-	 */
54
-	public function __construct(IFactory $factory, IManager $contactsManager, IURLGenerator $url, ICloudIdManager $cloudIdManager) {
55
-		$this->factory = $factory;
56
-		$this->contactsManager = $contactsManager;
57
-		$this->url = $url;
58
-		$this->cloudIdManager = $cloudIdManager;
59
-	}
60
-
61
-	/**
62
-	 * @param INotification $notification
63
-	 * @param string $languageCode The code of the language that should be used to prepare the notification
64
-	 * @return INotification
65
-	 * @throws \InvalidArgumentException
66
-	 */
67
-	public function prepare(INotification $notification, $languageCode) {
68
-		if ($notification->getApp() !== 'files_sharing') {
69
-			// Not my app => throw
70
-			throw new \InvalidArgumentException();
71
-		}
72
-
73
-		// Read the language from the notification
74
-		$l = $this->factory->get('files_sharing', $languageCode);
75
-
76
-		switch ($notification->getSubject()) {
77
-			// Deal with known subjects
78
-			case 'remote_share':
79
-				$notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
80
-
81
-				$params = $notification->getSubjectParameters();
82
-				if ($params[0] !== $params[1] && $params[1] !== null) {
83
-					$notification->setParsedSubject(
84
-						$l->t('You received "%3$s" as a remote share from %1$s (on behalf of %2$s)', $params)
85
-					);
86
-					$notification->setRichSubject(
87
-						$l->t('You received {share} as a remote share from {user} (on behalf of {behalf})'),
88
-						[
89
-							'share' => [
90
-								'type' => 'pending-federated-share',
91
-								'id' => $notification->getObjectId(),
92
-								'name' => $params[2],
93
-							],
94
-							'user' => $this->createRemoteUser($params[0]),
95
-							'behalf' => $this->createRemoteUser($params[1]),
96
-						]
97
-					);
98
-				} else {
99
-					$notification->setParsedSubject(
100
-						$l->t('You received "%3$s" as a remote share from %1$s', $params)
101
-					);
102
-					$notification->setRichSubject(
103
-						$l->t('You received {share} as a remote share from {user}'),
104
-						[
105
-							'share' => [
106
-								'type' => 'pending-federated-share',
107
-								'id' => $notification->getObjectId(),
108
-								'name' => $params[2],
109
-							],
110
-							'user' => $this->createRemoteUser($params[0]),
111
-						]
112
-					);
113
-				}
114
-
115
-				// Deal with the actions for a known subject
116
-				foreach ($notification->getActions() as $action) {
117
-					switch ($action->getLabel()) {
118
-						case 'accept':
119
-							$action->setParsedLabel(
120
-								(string) $l->t('Accept')
121
-							)
122
-							->setPrimary(true);
123
-							break;
124
-
125
-						case 'decline':
126
-							$action->setParsedLabel(
127
-								(string) $l->t('Decline')
128
-							);
129
-							break;
130
-					}
131
-
132
-					$notification->addParsedAction($action);
133
-				}
134
-				return $notification;
135
-
136
-			default:
137
-				// Unknown subject => Unknown notification => throw
138
-				throw new \InvalidArgumentException();
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * @param string $cloudId
144
-	 * @return array
145
-	 */
146
-	protected function createRemoteUser($cloudId) {
147
-		$displayName = $cloudId;
148
-		try {
149
-			$resolvedId = $this->cloudIdManager->resolveCloudId($cloudId);
150
-			$displayName = $this->getDisplayName($resolvedId);
151
-			$user = $resolvedId->getUser();
152
-			$server = $resolvedId->getRemote();
153
-		} catch (HintException $e) {
154
-			$user = $cloudId;
155
-			$server = '';
156
-		}
157
-
158
-		return [
159
-			'type' => 'user',
160
-			'id' => $user,
161
-			'name' => $displayName,
162
-			'server' => $server,
163
-		];
164
-	}
165
-
166
-	/**
167
-	 * Try to find the user in the contacts
168
-	 *
169
-	 * @param ICloudId $cloudId
170
-	 * @return string
171
-	 */
172
-	protected function getDisplayName(ICloudId $cloudId) {
173
-		$server = $cloudId->getRemote();
174
-		$user = $cloudId->getUser();
175
-		if (strpos($server, 'http://') === 0) {
176
-			$server = substr($server, strlen('http://'));
177
-		} else if (strpos($server, 'https://') === 0) {
178
-			$server = substr($server, strlen('https://'));
179
-		}
180
-
181
-		try {
182
-			return $this->getDisplayNameFromContact($cloudId->getId());
183
-		} catch (\OutOfBoundsException $e) {
184
-		}
185
-
186
-		try {
187
-			$this->getDisplayNameFromContact($user . '@http://' . $server);
188
-		} catch (\OutOfBoundsException $e) {
189
-		}
190
-
191
-		try {
192
-			$this->getDisplayNameFromContact($user . '@https://' . $server);
193
-		} catch (\OutOfBoundsException $e) {
194
-		}
195
-
196
-		return $cloudId->getId();
197
-	}
198
-
199
-	/**
200
-	 * Try to find the user in the contacts
201
-	 *
202
-	 * @param string $federatedCloudId
203
-	 * @return string
204
-	 * @throws \OutOfBoundsException when there is no contact for the id
205
-	 */
206
-	protected function getDisplayNameFromContact($federatedCloudId) {
207
-		if (isset($this->federatedContacts[$federatedCloudId])) {
208
-			if ($this->federatedContacts[$federatedCloudId] !== '') {
209
-				return $this->federatedContacts[$federatedCloudId];
210
-			} else {
211
-				throw new \OutOfBoundsException('No contact found for federated cloud id');
212
-			}
213
-		}
214
-
215
-		$addressBookEntries = $this->contactsManager->search($federatedCloudId, ['CLOUD']);
216
-		foreach ($addressBookEntries as $entry) {
217
-			if (isset($entry['CLOUD'])) {
218
-				foreach ($entry['CLOUD'] as $cloudID) {
219
-					if ($cloudID === $federatedCloudId) {
220
-						$this->federatedContacts[$federatedCloudId] = $entry['FN'];
221
-						return $entry['FN'];
222
-					}
223
-				}
224
-			}
225
-		}
226
-
227
-		$this->federatedContacts[$federatedCloudId] = '';
228
-		throw new \OutOfBoundsException('No contact found for federated cloud id');
229
-	}
37
+    /** @var IFactory */
38
+    protected $factory;
39
+    /** @var IManager */
40
+    protected $contactsManager;
41
+    /** @var IURLGenerator */
42
+    protected $url;
43
+    /** @var array */
44
+    protected $federatedContacts;
45
+    /** @var ICloudIdManager */
46
+    protected $cloudIdManager;
47
+
48
+    /**
49
+     * @param IFactory $factory
50
+     * @param IManager $contactsManager
51
+     * @param IURLGenerator $url
52
+     * @param ICloudIdManager $cloudIdManager
53
+     */
54
+    public function __construct(IFactory $factory, IManager $contactsManager, IURLGenerator $url, ICloudIdManager $cloudIdManager) {
55
+        $this->factory = $factory;
56
+        $this->contactsManager = $contactsManager;
57
+        $this->url = $url;
58
+        $this->cloudIdManager = $cloudIdManager;
59
+    }
60
+
61
+    /**
62
+     * @param INotification $notification
63
+     * @param string $languageCode The code of the language that should be used to prepare the notification
64
+     * @return INotification
65
+     * @throws \InvalidArgumentException
66
+     */
67
+    public function prepare(INotification $notification, $languageCode) {
68
+        if ($notification->getApp() !== 'files_sharing') {
69
+            // Not my app => throw
70
+            throw new \InvalidArgumentException();
71
+        }
72
+
73
+        // Read the language from the notification
74
+        $l = $this->factory->get('files_sharing', $languageCode);
75
+
76
+        switch ($notification->getSubject()) {
77
+            // Deal with known subjects
78
+            case 'remote_share':
79
+                $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('core', 'actions/share.svg')));
80
+
81
+                $params = $notification->getSubjectParameters();
82
+                if ($params[0] !== $params[1] && $params[1] !== null) {
83
+                    $notification->setParsedSubject(
84
+                        $l->t('You received "%3$s" as a remote share from %1$s (on behalf of %2$s)', $params)
85
+                    );
86
+                    $notification->setRichSubject(
87
+                        $l->t('You received {share} as a remote share from {user} (on behalf of {behalf})'),
88
+                        [
89
+                            'share' => [
90
+                                'type' => 'pending-federated-share',
91
+                                'id' => $notification->getObjectId(),
92
+                                'name' => $params[2],
93
+                            ],
94
+                            'user' => $this->createRemoteUser($params[0]),
95
+                            'behalf' => $this->createRemoteUser($params[1]),
96
+                        ]
97
+                    );
98
+                } else {
99
+                    $notification->setParsedSubject(
100
+                        $l->t('You received "%3$s" as a remote share from %1$s', $params)
101
+                    );
102
+                    $notification->setRichSubject(
103
+                        $l->t('You received {share} as a remote share from {user}'),
104
+                        [
105
+                            'share' => [
106
+                                'type' => 'pending-federated-share',
107
+                                'id' => $notification->getObjectId(),
108
+                                'name' => $params[2],
109
+                            ],
110
+                            'user' => $this->createRemoteUser($params[0]),
111
+                        ]
112
+                    );
113
+                }
114
+
115
+                // Deal with the actions for a known subject
116
+                foreach ($notification->getActions() as $action) {
117
+                    switch ($action->getLabel()) {
118
+                        case 'accept':
119
+                            $action->setParsedLabel(
120
+                                (string) $l->t('Accept')
121
+                            )
122
+                            ->setPrimary(true);
123
+                            break;
124
+
125
+                        case 'decline':
126
+                            $action->setParsedLabel(
127
+                                (string) $l->t('Decline')
128
+                            );
129
+                            break;
130
+                    }
131
+
132
+                    $notification->addParsedAction($action);
133
+                }
134
+                return $notification;
135
+
136
+            default:
137
+                // Unknown subject => Unknown notification => throw
138
+                throw new \InvalidArgumentException();
139
+        }
140
+    }
141
+
142
+    /**
143
+     * @param string $cloudId
144
+     * @return array
145
+     */
146
+    protected function createRemoteUser($cloudId) {
147
+        $displayName = $cloudId;
148
+        try {
149
+            $resolvedId = $this->cloudIdManager->resolveCloudId($cloudId);
150
+            $displayName = $this->getDisplayName($resolvedId);
151
+            $user = $resolvedId->getUser();
152
+            $server = $resolvedId->getRemote();
153
+        } catch (HintException $e) {
154
+            $user = $cloudId;
155
+            $server = '';
156
+        }
157
+
158
+        return [
159
+            'type' => 'user',
160
+            'id' => $user,
161
+            'name' => $displayName,
162
+            'server' => $server,
163
+        ];
164
+    }
165
+
166
+    /**
167
+     * Try to find the user in the contacts
168
+     *
169
+     * @param ICloudId $cloudId
170
+     * @return string
171
+     */
172
+    protected function getDisplayName(ICloudId $cloudId) {
173
+        $server = $cloudId->getRemote();
174
+        $user = $cloudId->getUser();
175
+        if (strpos($server, 'http://') === 0) {
176
+            $server = substr($server, strlen('http://'));
177
+        } else if (strpos($server, 'https://') === 0) {
178
+            $server = substr($server, strlen('https://'));
179
+        }
180
+
181
+        try {
182
+            return $this->getDisplayNameFromContact($cloudId->getId());
183
+        } catch (\OutOfBoundsException $e) {
184
+        }
185
+
186
+        try {
187
+            $this->getDisplayNameFromContact($user . '@http://' . $server);
188
+        } catch (\OutOfBoundsException $e) {
189
+        }
190
+
191
+        try {
192
+            $this->getDisplayNameFromContact($user . '@https://' . $server);
193
+        } catch (\OutOfBoundsException $e) {
194
+        }
195
+
196
+        return $cloudId->getId();
197
+    }
198
+
199
+    /**
200
+     * Try to find the user in the contacts
201
+     *
202
+     * @param string $federatedCloudId
203
+     * @return string
204
+     * @throws \OutOfBoundsException when there is no contact for the id
205
+     */
206
+    protected function getDisplayNameFromContact($federatedCloudId) {
207
+        if (isset($this->federatedContacts[$federatedCloudId])) {
208
+            if ($this->federatedContacts[$federatedCloudId] !== '') {
209
+                return $this->federatedContacts[$federatedCloudId];
210
+            } else {
211
+                throw new \OutOfBoundsException('No contact found for federated cloud id');
212
+            }
213
+        }
214
+
215
+        $addressBookEntries = $this->contactsManager->search($federatedCloudId, ['CLOUD']);
216
+        foreach ($addressBookEntries as $entry) {
217
+            if (isset($entry['CLOUD'])) {
218
+                foreach ($entry['CLOUD'] as $cloudID) {
219
+                    if ($cloudID === $federatedCloudId) {
220
+                        $this->federatedContacts[$federatedCloudId] = $entry['FN'];
221
+                        return $entry['FN'];
222
+                    }
223
+                }
224
+            }
225
+        }
226
+
227
+        $this->federatedContacts[$federatedCloudId] = '';
228
+        throw new \OutOfBoundsException('No contact found for federated cloud id');
229
+    }
230 230
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 patch
Indentation   +904 added lines, -904 removed lines patch added patch discarded remove patch
@@ -49,918 +49,918 @@
 block discarded – undo
49 49
  */
50 50
 class FederatedShareProvider implements IShareProvider {
51 51
 
52
-	const SHARE_TYPE_REMOTE = 6;
53
-
54
-	/** @var IDBConnection */
55
-	private $dbConnection;
56
-
57
-	/** @var AddressHandler */
58
-	private $addressHandler;
59
-
60
-	/** @var Notifications */
61
-	private $notifications;
62
-
63
-	/** @var TokenHandler */
64
-	private $tokenHandler;
65
-
66
-	/** @var IL10N */
67
-	private $l;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var IRootFolder */
73
-	private $rootFolder;
74
-
75
-	/** @var IConfig */
76
-	private $config;
77
-
78
-	/** @var string */
79
-	private $externalShareTable = 'share_external';
80
-
81
-	/** @var IUserManager */
82
-	private $userManager;
83
-
84
-	/** @var ICloudIdManager */
85
-	private $cloudIdManager;
86
-
87
-	/**
88
-	 * DefaultShareProvider constructor.
89
-	 *
90
-	 * @param IDBConnection $connection
91
-	 * @param AddressHandler $addressHandler
92
-	 * @param Notifications $notifications
93
-	 * @param TokenHandler $tokenHandler
94
-	 * @param IL10N $l10n
95
-	 * @param ILogger $logger
96
-	 * @param IRootFolder $rootFolder
97
-	 * @param IConfig $config
98
-	 * @param IUserManager $userManager
99
-	 * @param ICloudIdManager $cloudIdManager
100
-	 */
101
-	public function __construct(
102
-			IDBConnection $connection,
103
-			AddressHandler $addressHandler,
104
-			Notifications $notifications,
105
-			TokenHandler $tokenHandler,
106
-			IL10N $l10n,
107
-			ILogger $logger,
108
-			IRootFolder $rootFolder,
109
-			IConfig $config,
110
-			IUserManager $userManager,
111
-			ICloudIdManager $cloudIdManager
112
-	) {
113
-		$this->dbConnection = $connection;
114
-		$this->addressHandler = $addressHandler;
115
-		$this->notifications = $notifications;
116
-		$this->tokenHandler = $tokenHandler;
117
-		$this->l = $l10n;
118
-		$this->logger = $logger;
119
-		$this->rootFolder = $rootFolder;
120
-		$this->config = $config;
121
-		$this->userManager = $userManager;
122
-		$this->cloudIdManager = $cloudIdManager;
123
-	}
124
-
125
-	/**
126
-	 * Return the identifier of this provider.
127
-	 *
128
-	 * @return string Containing only [a-zA-Z0-9]
129
-	 */
130
-	public function identifier() {
131
-		return 'ocFederatedSharing';
132
-	}
133
-
134
-	/**
135
-	 * Share a path
136
-	 *
137
-	 * @param IShare $share
138
-	 * @return IShare The share object
139
-	 * @throws ShareNotFound
140
-	 * @throws \Exception
141
-	 */
142
-	public function create(IShare $share) {
143
-
144
-		$shareWith = $share->getSharedWith();
145
-		$itemSource = $share->getNodeId();
146
-		$itemType = $share->getNodeType();
147
-		$permissions = $share->getPermissions();
148
-		$sharedBy = $share->getSharedBy();
149
-
150
-		/*
52
+    const SHARE_TYPE_REMOTE = 6;
53
+
54
+    /** @var IDBConnection */
55
+    private $dbConnection;
56
+
57
+    /** @var AddressHandler */
58
+    private $addressHandler;
59
+
60
+    /** @var Notifications */
61
+    private $notifications;
62
+
63
+    /** @var TokenHandler */
64
+    private $tokenHandler;
65
+
66
+    /** @var IL10N */
67
+    private $l;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var IRootFolder */
73
+    private $rootFolder;
74
+
75
+    /** @var IConfig */
76
+    private $config;
77
+
78
+    /** @var string */
79
+    private $externalShareTable = 'share_external';
80
+
81
+    /** @var IUserManager */
82
+    private $userManager;
83
+
84
+    /** @var ICloudIdManager */
85
+    private $cloudIdManager;
86
+
87
+    /**
88
+     * DefaultShareProvider constructor.
89
+     *
90
+     * @param IDBConnection $connection
91
+     * @param AddressHandler $addressHandler
92
+     * @param Notifications $notifications
93
+     * @param TokenHandler $tokenHandler
94
+     * @param IL10N $l10n
95
+     * @param ILogger $logger
96
+     * @param IRootFolder $rootFolder
97
+     * @param IConfig $config
98
+     * @param IUserManager $userManager
99
+     * @param ICloudIdManager $cloudIdManager
100
+     */
101
+    public function __construct(
102
+            IDBConnection $connection,
103
+            AddressHandler $addressHandler,
104
+            Notifications $notifications,
105
+            TokenHandler $tokenHandler,
106
+            IL10N $l10n,
107
+            ILogger $logger,
108
+            IRootFolder $rootFolder,
109
+            IConfig $config,
110
+            IUserManager $userManager,
111
+            ICloudIdManager $cloudIdManager
112
+    ) {
113
+        $this->dbConnection = $connection;
114
+        $this->addressHandler = $addressHandler;
115
+        $this->notifications = $notifications;
116
+        $this->tokenHandler = $tokenHandler;
117
+        $this->l = $l10n;
118
+        $this->logger = $logger;
119
+        $this->rootFolder = $rootFolder;
120
+        $this->config = $config;
121
+        $this->userManager = $userManager;
122
+        $this->cloudIdManager = $cloudIdManager;
123
+    }
124
+
125
+    /**
126
+     * Return the identifier of this provider.
127
+     *
128
+     * @return string Containing only [a-zA-Z0-9]
129
+     */
130
+    public function identifier() {
131
+        return 'ocFederatedSharing';
132
+    }
133
+
134
+    /**
135
+     * Share a path
136
+     *
137
+     * @param IShare $share
138
+     * @return IShare The share object
139
+     * @throws ShareNotFound
140
+     * @throws \Exception
141
+     */
142
+    public function create(IShare $share) {
143
+
144
+        $shareWith = $share->getSharedWith();
145
+        $itemSource = $share->getNodeId();
146
+        $itemType = $share->getNodeType();
147
+        $permissions = $share->getPermissions();
148
+        $sharedBy = $share->getSharedBy();
149
+
150
+        /*
151 151
 		 * Check if file is not already shared with the remote user
152 152
 		 */
153
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
154
-		if (!empty($alreadyShared)) {
155
-			$message = 'Sharing %s failed, because this item is already shared with %s';
156
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
157
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
158
-			throw new \Exception($message_t);
159
-		}
160
-
161
-
162
-		// don't allow federated shares if source and target server are the same
163
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
164
-		$currentServer = $this->addressHandler->generateRemoteURL();
165
-		$currentUser = $sharedBy;
166
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
167
-			$message = 'Not allowed to create a federated share with the same user.';
168
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
169
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
170
-			throw new \Exception($message_t);
171
-		}
172
-
173
-
174
-		$share->setSharedWith($cloudId->getId());
175
-
176
-		try {
177
-			$remoteShare = $this->getShareFromExternalShareTable($share);
178
-		} catch (ShareNotFound $e) {
179
-			$remoteShare = null;
180
-		}
181
-
182
-		if ($remoteShare) {
183
-			try {
184
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
185
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
186
-				$share->setId($shareId);
187
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
188
-				// remote share was create successfully if we get a valid token as return
189
-				$send = is_string($token) && $token !== '';
190
-			} catch (\Exception $e) {
191
-				// fall back to old re-share behavior if the remote server
192
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
193
-				$this->removeShareFromTable($share);
194
-				$shareId = $this->createFederatedShare($share);
195
-			}
196
-			if ($send) {
197
-				$this->updateSuccessfulReshare($shareId, $token);
198
-				$this->storeRemoteId($shareId, $remoteId);
199
-			} else {
200
-				$this->removeShareFromTable($share);
201
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
202
-				throw new \Exception($message_t);
203
-			}
204
-
205
-		} else {
206
-			$shareId = $this->createFederatedShare($share);
207
-		}
208
-
209
-		$data = $this->getRawShare($shareId);
210
-		return $this->createShareObject($data);
211
-	}
212
-
213
-	/**
214
-	 * create federated share and inform the recipient
215
-	 *
216
-	 * @param IShare $share
217
-	 * @return int
218
-	 * @throws ShareNotFound
219
-	 * @throws \Exception
220
-	 */
221
-	protected function createFederatedShare(IShare $share) {
222
-		$token = $this->tokenHandler->generateToken();
223
-		$shareId = $this->addShareToDB(
224
-			$share->getNodeId(),
225
-			$share->getNodeType(),
226
-			$share->getSharedWith(),
227
-			$share->getSharedBy(),
228
-			$share->getShareOwner(),
229
-			$share->getPermissions(),
230
-			$token
231
-		);
232
-
233
-		$failure = false;
234
-
235
-		try {
236
-			$sharedByFederatedId = $share->getSharedBy();
237
-			if ($this->userManager->userExists($sharedByFederatedId)) {
238
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
239
-				$sharedByFederatedId = $cloudId->getId();
240
-			}
241
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
242
-			$send = $this->notifications->sendRemoteShare(
243
-				$token,
244
-				$share->getSharedWith(),
245
-				$share->getNode()->getName(),
246
-				$shareId,
247
-				$share->getShareOwner(),
248
-				$ownerCloudId->getId(),
249
-				$share->getSharedBy(),
250
-				$sharedByFederatedId
251
-			);
252
-
253
-			if ($send === false) {
254
-				$failure = true;
255
-			}
256
-		} catch (\Exception $e) {
257
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
258
-			$failure = true;
259
-		}
260
-
261
-		if($failure) {
262
-			$this->removeShareFromTableById($shareId);
263
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
264
-				[$share->getNode()->getName(), $share->getSharedWith()]);
265
-			throw new \Exception($message_t);
266
-		}
267
-
268
-		return $shareId;
269
-
270
-	}
271
-
272
-	/**
273
-	 * @param string $shareWith
274
-	 * @param IShare $share
275
-	 * @param string $shareId internal share Id
276
-	 * @return array
277
-	 * @throws \Exception
278
-	 */
279
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
280
-
281
-		$remoteShare = $this->getShareFromExternalShareTable($share);
282
-		$token = $remoteShare['share_token'];
283
-		$remoteId = $remoteShare['remote_id'];
284
-		$remote = $remoteShare['remote'];
285
-
286
-		list($token, $remoteId) = $this->notifications->requestReShare(
287
-			$token,
288
-			$remoteId,
289
-			$shareId,
290
-			$remote,
291
-			$shareWith,
292
-			$share->getPermissions()
293
-		);
294
-
295
-		return [$token, $remoteId];
296
-	}
297
-
298
-	/**
299
-	 * get federated share from the share_external table but exclude mounted link shares
300
-	 *
301
-	 * @param IShare $share
302
-	 * @return array
303
-	 * @throws ShareNotFound
304
-	 */
305
-	protected function getShareFromExternalShareTable(IShare $share) {
306
-		$query = $this->dbConnection->getQueryBuilder();
307
-		$query->select('*')->from($this->externalShareTable)
308
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
309
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
310
-		$result = $query->execute()->fetchAll();
311
-
312
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
313
-			return $result[0];
314
-		}
315
-
316
-		throw new ShareNotFound('share not found in share_external table');
317
-	}
318
-
319
-	/**
320
-	 * add share to the database and return the ID
321
-	 *
322
-	 * @param int $itemSource
323
-	 * @param string $itemType
324
-	 * @param string $shareWith
325
-	 * @param string $sharedBy
326
-	 * @param string $uidOwner
327
-	 * @param int $permissions
328
-	 * @param string $token
329
-	 * @return int
330
-	 */
331
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
332
-		$qb = $this->dbConnection->getQueryBuilder();
333
-		$qb->insert('share')
334
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
335
-			->setValue('item_type', $qb->createNamedParameter($itemType))
336
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
337
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
338
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
339
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
340
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
341
-			->setValue('permissions', $qb->createNamedParameter($permissions))
342
-			->setValue('token', $qb->createNamedParameter($token))
343
-			->setValue('stime', $qb->createNamedParameter(time()));
344
-
345
-		/*
153
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
154
+        if (!empty($alreadyShared)) {
155
+            $message = 'Sharing %s failed, because this item is already shared with %s';
156
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
157
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
158
+            throw new \Exception($message_t);
159
+        }
160
+
161
+
162
+        // don't allow federated shares if source and target server are the same
163
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
164
+        $currentServer = $this->addressHandler->generateRemoteURL();
165
+        $currentUser = $sharedBy;
166
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
167
+            $message = 'Not allowed to create a federated share with the same user.';
168
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
169
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
170
+            throw new \Exception($message_t);
171
+        }
172
+
173
+
174
+        $share->setSharedWith($cloudId->getId());
175
+
176
+        try {
177
+            $remoteShare = $this->getShareFromExternalShareTable($share);
178
+        } catch (ShareNotFound $e) {
179
+            $remoteShare = null;
180
+        }
181
+
182
+        if ($remoteShare) {
183
+            try {
184
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
185
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
186
+                $share->setId($shareId);
187
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
188
+                // remote share was create successfully if we get a valid token as return
189
+                $send = is_string($token) && $token !== '';
190
+            } catch (\Exception $e) {
191
+                // fall back to old re-share behavior if the remote server
192
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
193
+                $this->removeShareFromTable($share);
194
+                $shareId = $this->createFederatedShare($share);
195
+            }
196
+            if ($send) {
197
+                $this->updateSuccessfulReshare($shareId, $token);
198
+                $this->storeRemoteId($shareId, $remoteId);
199
+            } else {
200
+                $this->removeShareFromTable($share);
201
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
202
+                throw new \Exception($message_t);
203
+            }
204
+
205
+        } else {
206
+            $shareId = $this->createFederatedShare($share);
207
+        }
208
+
209
+        $data = $this->getRawShare($shareId);
210
+        return $this->createShareObject($data);
211
+    }
212
+
213
+    /**
214
+     * create federated share and inform the recipient
215
+     *
216
+     * @param IShare $share
217
+     * @return int
218
+     * @throws ShareNotFound
219
+     * @throws \Exception
220
+     */
221
+    protected function createFederatedShare(IShare $share) {
222
+        $token = $this->tokenHandler->generateToken();
223
+        $shareId = $this->addShareToDB(
224
+            $share->getNodeId(),
225
+            $share->getNodeType(),
226
+            $share->getSharedWith(),
227
+            $share->getSharedBy(),
228
+            $share->getShareOwner(),
229
+            $share->getPermissions(),
230
+            $token
231
+        );
232
+
233
+        $failure = false;
234
+
235
+        try {
236
+            $sharedByFederatedId = $share->getSharedBy();
237
+            if ($this->userManager->userExists($sharedByFederatedId)) {
238
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
239
+                $sharedByFederatedId = $cloudId->getId();
240
+            }
241
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
242
+            $send = $this->notifications->sendRemoteShare(
243
+                $token,
244
+                $share->getSharedWith(),
245
+                $share->getNode()->getName(),
246
+                $shareId,
247
+                $share->getShareOwner(),
248
+                $ownerCloudId->getId(),
249
+                $share->getSharedBy(),
250
+                $sharedByFederatedId
251
+            );
252
+
253
+            if ($send === false) {
254
+                $failure = true;
255
+            }
256
+        } catch (\Exception $e) {
257
+            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
258
+            $failure = true;
259
+        }
260
+
261
+        if($failure) {
262
+            $this->removeShareFromTableById($shareId);
263
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
264
+                [$share->getNode()->getName(), $share->getSharedWith()]);
265
+            throw new \Exception($message_t);
266
+        }
267
+
268
+        return $shareId;
269
+
270
+    }
271
+
272
+    /**
273
+     * @param string $shareWith
274
+     * @param IShare $share
275
+     * @param string $shareId internal share Id
276
+     * @return array
277
+     * @throws \Exception
278
+     */
279
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
280
+
281
+        $remoteShare = $this->getShareFromExternalShareTable($share);
282
+        $token = $remoteShare['share_token'];
283
+        $remoteId = $remoteShare['remote_id'];
284
+        $remote = $remoteShare['remote'];
285
+
286
+        list($token, $remoteId) = $this->notifications->requestReShare(
287
+            $token,
288
+            $remoteId,
289
+            $shareId,
290
+            $remote,
291
+            $shareWith,
292
+            $share->getPermissions()
293
+        );
294
+
295
+        return [$token, $remoteId];
296
+    }
297
+
298
+    /**
299
+     * get federated share from the share_external table but exclude mounted link shares
300
+     *
301
+     * @param IShare $share
302
+     * @return array
303
+     * @throws ShareNotFound
304
+     */
305
+    protected function getShareFromExternalShareTable(IShare $share) {
306
+        $query = $this->dbConnection->getQueryBuilder();
307
+        $query->select('*')->from($this->externalShareTable)
308
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
309
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
310
+        $result = $query->execute()->fetchAll();
311
+
312
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
313
+            return $result[0];
314
+        }
315
+
316
+        throw new ShareNotFound('share not found in share_external table');
317
+    }
318
+
319
+    /**
320
+     * add share to the database and return the ID
321
+     *
322
+     * @param int $itemSource
323
+     * @param string $itemType
324
+     * @param string $shareWith
325
+     * @param string $sharedBy
326
+     * @param string $uidOwner
327
+     * @param int $permissions
328
+     * @param string $token
329
+     * @return int
330
+     */
331
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
332
+        $qb = $this->dbConnection->getQueryBuilder();
333
+        $qb->insert('share')
334
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
335
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
336
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
337
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
338
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
339
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
340
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
341
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
342
+            ->setValue('token', $qb->createNamedParameter($token))
343
+            ->setValue('stime', $qb->createNamedParameter(time()));
344
+
345
+        /*
346 346
 		 * Added to fix https://github.com/owncloud/core/issues/22215
347 347
 		 * Can be removed once we get rid of ajax/share.php
348 348
 		 */
349
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
350
-
351
-		$qb->execute();
352
-		$id = $qb->getLastInsertId();
353
-
354
-		return (int)$id;
355
-	}
356
-
357
-	/**
358
-	 * Update a share
359
-	 *
360
-	 * @param IShare $share
361
-	 * @return IShare The share object
362
-	 */
363
-	public function update(IShare $share) {
364
-		/*
349
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
350
+
351
+        $qb->execute();
352
+        $id = $qb->getLastInsertId();
353
+
354
+        return (int)$id;
355
+    }
356
+
357
+    /**
358
+     * Update a share
359
+     *
360
+     * @param IShare $share
361
+     * @return IShare The share object
362
+     */
363
+    public function update(IShare $share) {
364
+        /*
365 365
 		 * We allow updating the permissions of federated shares
366 366
 		 */
367
-		$qb = $this->dbConnection->getQueryBuilder();
368
-			$qb->update('share')
369
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
370
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
371
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
372
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
373
-				->execute();
374
-
375
-		// send the updated permission to the owner/initiator, if they are not the same
376
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
377
-			$this->sendPermissionUpdate($share);
378
-		}
379
-
380
-		return $share;
381
-	}
382
-
383
-	/**
384
-	 * send the updated permission to the owner/initiator, if they are not the same
385
-	 *
386
-	 * @param IShare $share
387
-	 * @throws ShareNotFound
388
-	 * @throws \OC\HintException
389
-	 */
390
-	protected function sendPermissionUpdate(IShare $share) {
391
-		$remoteId = $this->getRemoteId($share);
392
-		// if the local user is the owner we send the permission change to the initiator
393
-		if ($this->userManager->userExists($share->getShareOwner())) {
394
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
395
-		} else { // ... if not we send the permission change to the owner
396
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
397
-		}
398
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
399
-	}
400
-
401
-
402
-	/**
403
-	 * update successful reShare with the correct token
404
-	 *
405
-	 * @param int $shareId
406
-	 * @param string $token
407
-	 */
408
-	protected function updateSuccessfulReShare($shareId, $token) {
409
-		$query = $this->dbConnection->getQueryBuilder();
410
-		$query->update('share')
411
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
412
-			->set('token', $query->createNamedParameter($token))
413
-			->execute();
414
-	}
415
-
416
-	/**
417
-	 * store remote ID in federated reShare table
418
-	 *
419
-	 * @param $shareId
420
-	 * @param $remoteId
421
-	 */
422
-	public function storeRemoteId($shareId, $remoteId) {
423
-		$query = $this->dbConnection->getQueryBuilder();
424
-		$query->insert('federated_reshares')
425
-			->values(
426
-				[
427
-					'share_id' =>  $query->createNamedParameter($shareId),
428
-					'remote_id' => $query->createNamedParameter($remoteId),
429
-				]
430
-			);
431
-		$query->execute();
432
-	}
433
-
434
-	/**
435
-	 * get share ID on remote server for federated re-shares
436
-	 *
437
-	 * @param IShare $share
438
-	 * @return int
439
-	 * @throws ShareNotFound
440
-	 */
441
-	public function getRemoteId(IShare $share) {
442
-		$query = $this->dbConnection->getQueryBuilder();
443
-		$query->select('remote_id')->from('federated_reshares')
444
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
445
-		$data = $query->execute()->fetch();
446
-
447
-		if (!is_array($data) || !isset($data['remote_id'])) {
448
-			throw new ShareNotFound();
449
-		}
450
-
451
-		return (int)$data['remote_id'];
452
-	}
453
-
454
-	/**
455
-	 * @inheritdoc
456
-	 */
457
-	public function move(IShare $share, $recipient) {
458
-		/*
367
+        $qb = $this->dbConnection->getQueryBuilder();
368
+            $qb->update('share')
369
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
370
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
371
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
372
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
373
+                ->execute();
374
+
375
+        // send the updated permission to the owner/initiator, if they are not the same
376
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
377
+            $this->sendPermissionUpdate($share);
378
+        }
379
+
380
+        return $share;
381
+    }
382
+
383
+    /**
384
+     * send the updated permission to the owner/initiator, if they are not the same
385
+     *
386
+     * @param IShare $share
387
+     * @throws ShareNotFound
388
+     * @throws \OC\HintException
389
+     */
390
+    protected function sendPermissionUpdate(IShare $share) {
391
+        $remoteId = $this->getRemoteId($share);
392
+        // if the local user is the owner we send the permission change to the initiator
393
+        if ($this->userManager->userExists($share->getShareOwner())) {
394
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
395
+        } else { // ... if not we send the permission change to the owner
396
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
397
+        }
398
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
399
+    }
400
+
401
+
402
+    /**
403
+     * update successful reShare with the correct token
404
+     *
405
+     * @param int $shareId
406
+     * @param string $token
407
+     */
408
+    protected function updateSuccessfulReShare($shareId, $token) {
409
+        $query = $this->dbConnection->getQueryBuilder();
410
+        $query->update('share')
411
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
412
+            ->set('token', $query->createNamedParameter($token))
413
+            ->execute();
414
+    }
415
+
416
+    /**
417
+     * store remote ID in federated reShare table
418
+     *
419
+     * @param $shareId
420
+     * @param $remoteId
421
+     */
422
+    public function storeRemoteId($shareId, $remoteId) {
423
+        $query = $this->dbConnection->getQueryBuilder();
424
+        $query->insert('federated_reshares')
425
+            ->values(
426
+                [
427
+                    'share_id' =>  $query->createNamedParameter($shareId),
428
+                    'remote_id' => $query->createNamedParameter($remoteId),
429
+                ]
430
+            );
431
+        $query->execute();
432
+    }
433
+
434
+    /**
435
+     * get share ID on remote server for federated re-shares
436
+     *
437
+     * @param IShare $share
438
+     * @return int
439
+     * @throws ShareNotFound
440
+     */
441
+    public function getRemoteId(IShare $share) {
442
+        $query = $this->dbConnection->getQueryBuilder();
443
+        $query->select('remote_id')->from('federated_reshares')
444
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
445
+        $data = $query->execute()->fetch();
446
+
447
+        if (!is_array($data) || !isset($data['remote_id'])) {
448
+            throw new ShareNotFound();
449
+        }
450
+
451
+        return (int)$data['remote_id'];
452
+    }
453
+
454
+    /**
455
+     * @inheritdoc
456
+     */
457
+    public function move(IShare $share, $recipient) {
458
+        /*
459 459
 		 * This function does nothing yet as it is just for outgoing
460 460
 		 * federated shares.
461 461
 		 */
462
-		return $share;
463
-	}
464
-
465
-	/**
466
-	 * Get all children of this share
467
-	 *
468
-	 * @param IShare $parent
469
-	 * @return IShare[]
470
-	 */
471
-	public function getChildren(IShare $parent) {
472
-		$children = [];
473
-
474
-		$qb = $this->dbConnection->getQueryBuilder();
475
-		$qb->select('*')
476
-			->from('share')
477
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
478
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
479
-			->orderBy('id');
480
-
481
-		$cursor = $qb->execute();
482
-		while($data = $cursor->fetch()) {
483
-			$children[] = $this->createShareObject($data);
484
-		}
485
-		$cursor->closeCursor();
486
-
487
-		return $children;
488
-	}
489
-
490
-	/**
491
-	 * Delete a share (owner unShares the file)
492
-	 *
493
-	 * @param IShare $share
494
-	 */
495
-	public function delete(IShare $share) {
496
-
497
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
498
-
499
-		$isOwner = false;
500
-
501
-		$this->removeShareFromTable($share);
502
-
503
-		// if the local user is the owner we can send the unShare request directly...
504
-		if ($this->userManager->userExists($share->getShareOwner())) {
505
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
506
-			$this->revokeShare($share, true);
507
-			$isOwner = true;
508
-		} else { // ... if not we need to correct ID for the unShare request
509
-			$remoteId = $this->getRemoteId($share);
510
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
511
-			$this->revokeShare($share, false);
512
-		}
513
-
514
-		// send revoke notification to the other user, if initiator and owner are not the same user
515
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
516
-			$remoteId = $this->getRemoteId($share);
517
-			if ($isOwner) {
518
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
519
-			} else {
520
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
521
-			}
522
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * in case of a re-share we need to send the other use (initiator or owner)
528
-	 * a message that the file was unshared
529
-	 *
530
-	 * @param IShare $share
531
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
532
-	 * @throws ShareNotFound
533
-	 * @throws \OC\HintException
534
-	 */
535
-	protected function revokeShare($share, $isOwner) {
536
-		// also send a unShare request to the initiator, if this is a different user than the owner
537
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
538
-			if ($isOwner) {
539
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
540
-			} else {
541
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
542
-			}
543
-			$remoteId = $this->getRemoteId($share);
544
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
545
-		}
546
-	}
547
-
548
-	/**
549
-	 * remove share from table
550
-	 *
551
-	 * @param IShare $share
552
-	 */
553
-	public function removeShareFromTable(IShare $share) {
554
-		$this->removeShareFromTableById($share->getId());
555
-	}
556
-
557
-	/**
558
-	 * remove share from table
559
-	 *
560
-	 * @param string $shareId
561
-	 */
562
-	private function removeShareFromTableById($shareId) {
563
-		$qb = $this->dbConnection->getQueryBuilder();
564
-		$qb->delete('share')
565
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
566
-		$qb->execute();
567
-
568
-		$qb->delete('federated_reshares')
569
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
570
-		$qb->execute();
571
-	}
572
-
573
-	/**
574
-	 * @inheritdoc
575
-	 */
576
-	public function deleteFromSelf(IShare $share, $recipient) {
577
-		// nothing to do here. Technically deleteFromSelf in the context of federated
578
-		// shares is a umount of a external storage. This is handled here
579
-		// apps/files_sharing/lib/external/manager.php
580
-		// TODO move this code over to this app
581
-		return;
582
-	}
583
-
584
-
585
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
586
-		$qb = $this->dbConnection->getQueryBuilder();
587
-		$qb->select('*')
588
-			->from('share', 's')
589
-			->andWhere($qb->expr()->orX(
590
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
591
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
592
-			))
593
-			->andWhere(
594
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
595
-			);
596
-
597
-		/**
598
-		 * Reshares for this user are shares where they are the owner.
599
-		 */
600
-		if ($reshares === false) {
601
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
602
-		} else {
603
-			$qb->andWhere(
604
-				$qb->expr()->orX(
605
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
606
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
607
-				)
608
-			);
609
-		}
610
-
611
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
612
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
613
-
614
-		$qb->orderBy('id');
615
-
616
-		$cursor = $qb->execute();
617
-		$shares = [];
618
-		while ($data = $cursor->fetch()) {
619
-			$shares[$data['fileid']][] = $this->createShareObject($data);
620
-		}
621
-		$cursor->closeCursor();
622
-
623
-		return $shares;
624
-	}
625
-
626
-	/**
627
-	 * @inheritdoc
628
-	 */
629
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
630
-		$qb = $this->dbConnection->getQueryBuilder();
631
-		$qb->select('*')
632
-			->from('share');
633
-
634
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
635
-
636
-		/**
637
-		 * Reshares for this user are shares where they are the owner.
638
-		 */
639
-		if ($reshares === false) {
640
-			//Special case for old shares created via the web UI
641
-			$or1 = $qb->expr()->andX(
642
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
643
-				$qb->expr()->isNull('uid_initiator')
644
-			);
645
-
646
-			$qb->andWhere(
647
-				$qb->expr()->orX(
648
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
649
-					$or1
650
-				)
651
-			);
652
-		} else {
653
-			$qb->andWhere(
654
-				$qb->expr()->orX(
655
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
656
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
657
-				)
658
-			);
659
-		}
660
-
661
-		if ($node !== null) {
662
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
663
-		}
664
-
665
-		if ($limit !== -1) {
666
-			$qb->setMaxResults($limit);
667
-		}
668
-
669
-		$qb->setFirstResult($offset);
670
-		$qb->orderBy('id');
671
-
672
-		$cursor = $qb->execute();
673
-		$shares = [];
674
-		while($data = $cursor->fetch()) {
675
-			$shares[] = $this->createShareObject($data);
676
-		}
677
-		$cursor->closeCursor();
678
-
679
-		return $shares;
680
-	}
681
-
682
-	/**
683
-	 * @inheritdoc
684
-	 */
685
-	public function getShareById($id, $recipientId = null) {
686
-		$qb = $this->dbConnection->getQueryBuilder();
687
-
688
-		$qb->select('*')
689
-			->from('share')
690
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
691
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
692
-
693
-		$cursor = $qb->execute();
694
-		$data = $cursor->fetch();
695
-		$cursor->closeCursor();
696
-
697
-		if ($data === false) {
698
-			throw new ShareNotFound();
699
-		}
700
-
701
-		try {
702
-			$share = $this->createShareObject($data);
703
-		} catch (InvalidShare $e) {
704
-			throw new ShareNotFound();
705
-		}
706
-
707
-		return $share;
708
-	}
709
-
710
-	/**
711
-	 * Get shares for a given path
712
-	 *
713
-	 * @param \OCP\Files\Node $path
714
-	 * @return IShare[]
715
-	 */
716
-	public function getSharesByPath(Node $path) {
717
-		$qb = $this->dbConnection->getQueryBuilder();
718
-
719
-		$cursor = $qb->select('*')
720
-			->from('share')
721
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
722
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
723
-			->execute();
724
-
725
-		$shares = [];
726
-		while($data = $cursor->fetch()) {
727
-			$shares[] = $this->createShareObject($data);
728
-		}
729
-		$cursor->closeCursor();
730
-
731
-		return $shares;
732
-	}
733
-
734
-	/**
735
-	 * @inheritdoc
736
-	 */
737
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
738
-		/** @var IShare[] $shares */
739
-		$shares = [];
740
-
741
-		//Get shares directly with this user
742
-		$qb = $this->dbConnection->getQueryBuilder();
743
-		$qb->select('*')
744
-			->from('share');
745
-
746
-		// Order by id
747
-		$qb->orderBy('id');
748
-
749
-		// Set limit and offset
750
-		if ($limit !== -1) {
751
-			$qb->setMaxResults($limit);
752
-		}
753
-		$qb->setFirstResult($offset);
754
-
755
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
756
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
757
-
758
-		// Filter by node if provided
759
-		if ($node !== null) {
760
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
761
-		}
762
-
763
-		$cursor = $qb->execute();
764
-
765
-		while($data = $cursor->fetch()) {
766
-			$shares[] = $this->createShareObject($data);
767
-		}
768
-		$cursor->closeCursor();
769
-
770
-
771
-		return $shares;
772
-	}
773
-
774
-	/**
775
-	 * Get a share by token
776
-	 *
777
-	 * @param string $token
778
-	 * @return IShare
779
-	 * @throws ShareNotFound
780
-	 */
781
-	public function getShareByToken($token) {
782
-		$qb = $this->dbConnection->getQueryBuilder();
783
-
784
-		$cursor = $qb->select('*')
785
-			->from('share')
786
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
787
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
788
-			->execute();
789
-
790
-		$data = $cursor->fetch();
791
-
792
-		if ($data === false) {
793
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
794
-		}
795
-
796
-		try {
797
-			$share = $this->createShareObject($data);
798
-		} catch (InvalidShare $e) {
799
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
800
-		}
801
-
802
-		return $share;
803
-	}
804
-
805
-	/**
806
-	 * get database row of a give share
807
-	 *
808
-	 * @param $id
809
-	 * @return array
810
-	 * @throws ShareNotFound
811
-	 */
812
-	private function getRawShare($id) {
813
-
814
-		// Now fetch the inserted share and create a complete share object
815
-		$qb = $this->dbConnection->getQueryBuilder();
816
-		$qb->select('*')
817
-			->from('share')
818
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
819
-
820
-		$cursor = $qb->execute();
821
-		$data = $cursor->fetch();
822
-		$cursor->closeCursor();
823
-
824
-		if ($data === false) {
825
-			throw new ShareNotFound;
826
-		}
827
-
828
-		return $data;
829
-	}
830
-
831
-	/**
832
-	 * Create a share object from an database row
833
-	 *
834
-	 * @param array $data
835
-	 * @return IShare
836
-	 * @throws InvalidShare
837
-	 * @throws ShareNotFound
838
-	 */
839
-	private function createShareObject($data) {
840
-
841
-		$share = new Share($this->rootFolder, $this->userManager);
842
-		$share->setId((int)$data['id'])
843
-			->setShareType((int)$data['share_type'])
844
-			->setPermissions((int)$data['permissions'])
845
-			->setTarget($data['file_target'])
846
-			->setMailSend((bool)$data['mail_send'])
847
-			->setToken($data['token']);
848
-
849
-		$shareTime = new \DateTime();
850
-		$shareTime->setTimestamp((int)$data['stime']);
851
-		$share->setShareTime($shareTime);
852
-		$share->setSharedWith($data['share_with']);
853
-
854
-		if ($data['uid_initiator'] !== null) {
855
-			$share->setShareOwner($data['uid_owner']);
856
-			$share->setSharedBy($data['uid_initiator']);
857
-		} else {
858
-			//OLD SHARE
859
-			$share->setSharedBy($data['uid_owner']);
860
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
861
-
862
-			$owner = $path->getOwner();
863
-			$share->setShareOwner($owner->getUID());
864
-		}
865
-
866
-		$share->setNodeId((int)$data['file_source']);
867
-		$share->setNodeType($data['item_type']);
868
-
869
-		$share->setProviderId($this->identifier());
870
-
871
-		return $share;
872
-	}
873
-
874
-	/**
875
-	 * Get the node with file $id for $user
876
-	 *
877
-	 * @param string $userId
878
-	 * @param int $id
879
-	 * @return \OCP\Files\File|\OCP\Files\Folder
880
-	 * @throws InvalidShare
881
-	 */
882
-	private function getNode($userId, $id) {
883
-		try {
884
-			$userFolder = $this->rootFolder->getUserFolder($userId);
885
-		} catch (NotFoundException $e) {
886
-			throw new InvalidShare();
887
-		}
888
-
889
-		$nodes = $userFolder->getById($id);
890
-
891
-		if (empty($nodes)) {
892
-			throw new InvalidShare();
893
-		}
894
-
895
-		return $nodes[0];
896
-	}
897
-
898
-	/**
899
-	 * A user is deleted from the system
900
-	 * So clean up the relevant shares.
901
-	 *
902
-	 * @param string $uid
903
-	 * @param int $shareType
904
-	 */
905
-	public function userDeleted($uid, $shareType) {
906
-		//TODO: probabaly a good idea to send unshare info to remote servers
907
-
908
-		$qb = $this->dbConnection->getQueryBuilder();
909
-
910
-		$qb->delete('share')
911
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
912
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
913
-			->execute();
914
-	}
915
-
916
-	/**
917
-	 * This provider does not handle groups
918
-	 *
919
-	 * @param string $gid
920
-	 */
921
-	public function groupDeleted($gid) {
922
-		// We don't handle groups here
923
-		return;
924
-	}
925
-
926
-	/**
927
-	 * This provider does not handle groups
928
-	 *
929
-	 * @param string $uid
930
-	 * @param string $gid
931
-	 */
932
-	public function userDeletedFromGroup($uid, $gid) {
933
-		// We don't handle groups here
934
-		return;
935
-	}
936
-
937
-	/**
938
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
939
-	 *
940
-	 * @return bool
941
-	 */
942
-	public function isOutgoingServer2serverShareEnabled() {
943
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
944
-		return ($result === 'yes') ? true : false;
945
-	}
946
-
947
-	/**
948
-	 * check if users are allowed to mount public links from other ownClouds
949
-	 *
950
-	 * @return bool
951
-	 */
952
-	public function isIncomingServer2serverShareEnabled() {
953
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
954
-		return ($result === 'yes') ? true : false;
955
-	}
956
-
957
-	/**
958
-	 * Check if querying sharees on the lookup server is enabled
959
-	 *
960
-	 * @return bool
961
-	 */
962
-	public function isLookupServerQueriesEnabled() {
963
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
964
-		return ($result === 'yes') ? true : false;
965
-	}
462
+        return $share;
463
+    }
464
+
465
+    /**
466
+     * Get all children of this share
467
+     *
468
+     * @param IShare $parent
469
+     * @return IShare[]
470
+     */
471
+    public function getChildren(IShare $parent) {
472
+        $children = [];
473
+
474
+        $qb = $this->dbConnection->getQueryBuilder();
475
+        $qb->select('*')
476
+            ->from('share')
477
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
478
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
479
+            ->orderBy('id');
480
+
481
+        $cursor = $qb->execute();
482
+        while($data = $cursor->fetch()) {
483
+            $children[] = $this->createShareObject($data);
484
+        }
485
+        $cursor->closeCursor();
486
+
487
+        return $children;
488
+    }
489
+
490
+    /**
491
+     * Delete a share (owner unShares the file)
492
+     *
493
+     * @param IShare $share
494
+     */
495
+    public function delete(IShare $share) {
496
+
497
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
498
+
499
+        $isOwner = false;
500
+
501
+        $this->removeShareFromTable($share);
502
+
503
+        // if the local user is the owner we can send the unShare request directly...
504
+        if ($this->userManager->userExists($share->getShareOwner())) {
505
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
506
+            $this->revokeShare($share, true);
507
+            $isOwner = true;
508
+        } else { // ... if not we need to correct ID for the unShare request
509
+            $remoteId = $this->getRemoteId($share);
510
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
511
+            $this->revokeShare($share, false);
512
+        }
513
+
514
+        // send revoke notification to the other user, if initiator and owner are not the same user
515
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
516
+            $remoteId = $this->getRemoteId($share);
517
+            if ($isOwner) {
518
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
519
+            } else {
520
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
521
+            }
522
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
523
+        }
524
+    }
525
+
526
+    /**
527
+     * in case of a re-share we need to send the other use (initiator or owner)
528
+     * a message that the file was unshared
529
+     *
530
+     * @param IShare $share
531
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
532
+     * @throws ShareNotFound
533
+     * @throws \OC\HintException
534
+     */
535
+    protected function revokeShare($share, $isOwner) {
536
+        // also send a unShare request to the initiator, if this is a different user than the owner
537
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
538
+            if ($isOwner) {
539
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
540
+            } else {
541
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
542
+            }
543
+            $remoteId = $this->getRemoteId($share);
544
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
545
+        }
546
+    }
547
+
548
+    /**
549
+     * remove share from table
550
+     *
551
+     * @param IShare $share
552
+     */
553
+    public function removeShareFromTable(IShare $share) {
554
+        $this->removeShareFromTableById($share->getId());
555
+    }
556
+
557
+    /**
558
+     * remove share from table
559
+     *
560
+     * @param string $shareId
561
+     */
562
+    private function removeShareFromTableById($shareId) {
563
+        $qb = $this->dbConnection->getQueryBuilder();
564
+        $qb->delete('share')
565
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
566
+        $qb->execute();
567
+
568
+        $qb->delete('federated_reshares')
569
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
570
+        $qb->execute();
571
+    }
572
+
573
+    /**
574
+     * @inheritdoc
575
+     */
576
+    public function deleteFromSelf(IShare $share, $recipient) {
577
+        // nothing to do here. Technically deleteFromSelf in the context of federated
578
+        // shares is a umount of a external storage. This is handled here
579
+        // apps/files_sharing/lib/external/manager.php
580
+        // TODO move this code over to this app
581
+        return;
582
+    }
583
+
584
+
585
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
586
+        $qb = $this->dbConnection->getQueryBuilder();
587
+        $qb->select('*')
588
+            ->from('share', 's')
589
+            ->andWhere($qb->expr()->orX(
590
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
591
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
592
+            ))
593
+            ->andWhere(
594
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
595
+            );
596
+
597
+        /**
598
+         * Reshares for this user are shares where they are the owner.
599
+         */
600
+        if ($reshares === false) {
601
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
602
+        } else {
603
+            $qb->andWhere(
604
+                $qb->expr()->orX(
605
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
606
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
607
+                )
608
+            );
609
+        }
610
+
611
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
612
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
613
+
614
+        $qb->orderBy('id');
615
+
616
+        $cursor = $qb->execute();
617
+        $shares = [];
618
+        while ($data = $cursor->fetch()) {
619
+            $shares[$data['fileid']][] = $this->createShareObject($data);
620
+        }
621
+        $cursor->closeCursor();
622
+
623
+        return $shares;
624
+    }
625
+
626
+    /**
627
+     * @inheritdoc
628
+     */
629
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
630
+        $qb = $this->dbConnection->getQueryBuilder();
631
+        $qb->select('*')
632
+            ->from('share');
633
+
634
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
635
+
636
+        /**
637
+         * Reshares for this user are shares where they are the owner.
638
+         */
639
+        if ($reshares === false) {
640
+            //Special case for old shares created via the web UI
641
+            $or1 = $qb->expr()->andX(
642
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
643
+                $qb->expr()->isNull('uid_initiator')
644
+            );
645
+
646
+            $qb->andWhere(
647
+                $qb->expr()->orX(
648
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
649
+                    $or1
650
+                )
651
+            );
652
+        } else {
653
+            $qb->andWhere(
654
+                $qb->expr()->orX(
655
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
656
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
657
+                )
658
+            );
659
+        }
660
+
661
+        if ($node !== null) {
662
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
663
+        }
664
+
665
+        if ($limit !== -1) {
666
+            $qb->setMaxResults($limit);
667
+        }
668
+
669
+        $qb->setFirstResult($offset);
670
+        $qb->orderBy('id');
671
+
672
+        $cursor = $qb->execute();
673
+        $shares = [];
674
+        while($data = $cursor->fetch()) {
675
+            $shares[] = $this->createShareObject($data);
676
+        }
677
+        $cursor->closeCursor();
678
+
679
+        return $shares;
680
+    }
681
+
682
+    /**
683
+     * @inheritdoc
684
+     */
685
+    public function getShareById($id, $recipientId = null) {
686
+        $qb = $this->dbConnection->getQueryBuilder();
687
+
688
+        $qb->select('*')
689
+            ->from('share')
690
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
691
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
692
+
693
+        $cursor = $qb->execute();
694
+        $data = $cursor->fetch();
695
+        $cursor->closeCursor();
696
+
697
+        if ($data === false) {
698
+            throw new ShareNotFound();
699
+        }
700
+
701
+        try {
702
+            $share = $this->createShareObject($data);
703
+        } catch (InvalidShare $e) {
704
+            throw new ShareNotFound();
705
+        }
706
+
707
+        return $share;
708
+    }
709
+
710
+    /**
711
+     * Get shares for a given path
712
+     *
713
+     * @param \OCP\Files\Node $path
714
+     * @return IShare[]
715
+     */
716
+    public function getSharesByPath(Node $path) {
717
+        $qb = $this->dbConnection->getQueryBuilder();
718
+
719
+        $cursor = $qb->select('*')
720
+            ->from('share')
721
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
722
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
723
+            ->execute();
724
+
725
+        $shares = [];
726
+        while($data = $cursor->fetch()) {
727
+            $shares[] = $this->createShareObject($data);
728
+        }
729
+        $cursor->closeCursor();
730
+
731
+        return $shares;
732
+    }
733
+
734
+    /**
735
+     * @inheritdoc
736
+     */
737
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
738
+        /** @var IShare[] $shares */
739
+        $shares = [];
740
+
741
+        //Get shares directly with this user
742
+        $qb = $this->dbConnection->getQueryBuilder();
743
+        $qb->select('*')
744
+            ->from('share');
745
+
746
+        // Order by id
747
+        $qb->orderBy('id');
748
+
749
+        // Set limit and offset
750
+        if ($limit !== -1) {
751
+            $qb->setMaxResults($limit);
752
+        }
753
+        $qb->setFirstResult($offset);
754
+
755
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
756
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
757
+
758
+        // Filter by node if provided
759
+        if ($node !== null) {
760
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
761
+        }
762
+
763
+        $cursor = $qb->execute();
764
+
765
+        while($data = $cursor->fetch()) {
766
+            $shares[] = $this->createShareObject($data);
767
+        }
768
+        $cursor->closeCursor();
769
+
770
+
771
+        return $shares;
772
+    }
773
+
774
+    /**
775
+     * Get a share by token
776
+     *
777
+     * @param string $token
778
+     * @return IShare
779
+     * @throws ShareNotFound
780
+     */
781
+    public function getShareByToken($token) {
782
+        $qb = $this->dbConnection->getQueryBuilder();
783
+
784
+        $cursor = $qb->select('*')
785
+            ->from('share')
786
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
787
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
788
+            ->execute();
789
+
790
+        $data = $cursor->fetch();
791
+
792
+        if ($data === false) {
793
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
794
+        }
795
+
796
+        try {
797
+            $share = $this->createShareObject($data);
798
+        } catch (InvalidShare $e) {
799
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
800
+        }
801
+
802
+        return $share;
803
+    }
804
+
805
+    /**
806
+     * get database row of a give share
807
+     *
808
+     * @param $id
809
+     * @return array
810
+     * @throws ShareNotFound
811
+     */
812
+    private function getRawShare($id) {
813
+
814
+        // Now fetch the inserted share and create a complete share object
815
+        $qb = $this->dbConnection->getQueryBuilder();
816
+        $qb->select('*')
817
+            ->from('share')
818
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
819
+
820
+        $cursor = $qb->execute();
821
+        $data = $cursor->fetch();
822
+        $cursor->closeCursor();
823
+
824
+        if ($data === false) {
825
+            throw new ShareNotFound;
826
+        }
827
+
828
+        return $data;
829
+    }
830
+
831
+    /**
832
+     * Create a share object from an database row
833
+     *
834
+     * @param array $data
835
+     * @return IShare
836
+     * @throws InvalidShare
837
+     * @throws ShareNotFound
838
+     */
839
+    private function createShareObject($data) {
840
+
841
+        $share = new Share($this->rootFolder, $this->userManager);
842
+        $share->setId((int)$data['id'])
843
+            ->setShareType((int)$data['share_type'])
844
+            ->setPermissions((int)$data['permissions'])
845
+            ->setTarget($data['file_target'])
846
+            ->setMailSend((bool)$data['mail_send'])
847
+            ->setToken($data['token']);
848
+
849
+        $shareTime = new \DateTime();
850
+        $shareTime->setTimestamp((int)$data['stime']);
851
+        $share->setShareTime($shareTime);
852
+        $share->setSharedWith($data['share_with']);
853
+
854
+        if ($data['uid_initiator'] !== null) {
855
+            $share->setShareOwner($data['uid_owner']);
856
+            $share->setSharedBy($data['uid_initiator']);
857
+        } else {
858
+            //OLD SHARE
859
+            $share->setSharedBy($data['uid_owner']);
860
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
861
+
862
+            $owner = $path->getOwner();
863
+            $share->setShareOwner($owner->getUID());
864
+        }
865
+
866
+        $share->setNodeId((int)$data['file_source']);
867
+        $share->setNodeType($data['item_type']);
868
+
869
+        $share->setProviderId($this->identifier());
870
+
871
+        return $share;
872
+    }
873
+
874
+    /**
875
+     * Get the node with file $id for $user
876
+     *
877
+     * @param string $userId
878
+     * @param int $id
879
+     * @return \OCP\Files\File|\OCP\Files\Folder
880
+     * @throws InvalidShare
881
+     */
882
+    private function getNode($userId, $id) {
883
+        try {
884
+            $userFolder = $this->rootFolder->getUserFolder($userId);
885
+        } catch (NotFoundException $e) {
886
+            throw new InvalidShare();
887
+        }
888
+
889
+        $nodes = $userFolder->getById($id);
890
+
891
+        if (empty($nodes)) {
892
+            throw new InvalidShare();
893
+        }
894
+
895
+        return $nodes[0];
896
+    }
897
+
898
+    /**
899
+     * A user is deleted from the system
900
+     * So clean up the relevant shares.
901
+     *
902
+     * @param string $uid
903
+     * @param int $shareType
904
+     */
905
+    public function userDeleted($uid, $shareType) {
906
+        //TODO: probabaly a good idea to send unshare info to remote servers
907
+
908
+        $qb = $this->dbConnection->getQueryBuilder();
909
+
910
+        $qb->delete('share')
911
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
912
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
913
+            ->execute();
914
+    }
915
+
916
+    /**
917
+     * This provider does not handle groups
918
+     *
919
+     * @param string $gid
920
+     */
921
+    public function groupDeleted($gid) {
922
+        // We don't handle groups here
923
+        return;
924
+    }
925
+
926
+    /**
927
+     * This provider does not handle groups
928
+     *
929
+     * @param string $uid
930
+     * @param string $gid
931
+     */
932
+    public function userDeletedFromGroup($uid, $gid) {
933
+        // We don't handle groups here
934
+        return;
935
+    }
936
+
937
+    /**
938
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
939
+     *
940
+     * @return bool
941
+     */
942
+    public function isOutgoingServer2serverShareEnabled() {
943
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
944
+        return ($result === 'yes') ? true : false;
945
+    }
946
+
947
+    /**
948
+     * check if users are allowed to mount public links from other ownClouds
949
+     *
950
+     * @return bool
951
+     */
952
+    public function isIncomingServer2serverShareEnabled() {
953
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
954
+        return ($result === 'yes') ? true : false;
955
+    }
956
+
957
+    /**
958
+     * Check if querying sharees on the lookup server is enabled
959
+     *
960
+     * @return bool
961
+     */
962
+    public function isLookupServerQueriesEnabled() {
963
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
964
+        return ($result === 'yes') ? true : false;
965
+    }
966 966
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/DiscoveryManager.php 1 patch
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.
apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php 1 patch
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.
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 1 patch
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.
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.