Completed
Pull Request — master (#32303)
by Victor
12:09
created

Notifications::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 5
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Björn Schießle <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 * @author Lukas Reschke <[email protected]>
6
 * @author Thomas Müller <[email protected]>
7
 * @author Vincent Petry <[email protected]>
8
 *
9
 * @copyright Copyright (c) 2018, ownCloud GmbH
10
 * @license AGPL-3.0
11
 *
12
 * This code is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License, version 3,
14
 * as published by the Free Software Foundation.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License, version 3,
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
23
 *
24
 */
25
26
namespace OCA\FederatedFileSharing;
27
28
use OCA\FederatedFileSharing\Ocm\NotificationManager;
29
use OCP\AppFramework\Http;
30
use OCP\BackgroundJob\IJobList;
31
use OCP\Http\Client\IClientService;
32
use OCP\IConfig;
33
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 1
46
	/** @var IJobList  */
47
	private $jobList;
48
49 1
	/** @var IConfig */
50 1
	private $config;
51 1
52
	/**
53
	 * @param AddressHandler $addressHandler
54
	 * @param IClientService $httpClientService
55
	 * @param DiscoveryManager $discoveryManager
56
	 * @param IJobList $jobList
57
	 * @param IConfig $config
58
	 */
59
	public function __construct(
60
		AddressHandler $addressHandler,
61
		IClientService $httpClientService,
62
		DiscoveryManager $discoveryManager,
63
		IJobList $jobList,
64
		IConfig $config
65
	) {
66
		$this->addressHandler = $addressHandler;
67
		$this->httpClientService = $httpClientService;
68
		$this->discoveryManager = $discoveryManager;
69
		$this->jobList = $jobList;
70
		$this->config = $config;
71
	}
72
73
	/**
74
	 * send server-to-server share to remote server
75
	 *
76
	 * @param Address $shareWithAddress
77
	 * @param Address $ownerAddress
78
	 * @param Address $sharedByAddress
79
	 * @param string $token
80
	 * @param string $shareWith
0 ignored issues
show
Documentation introduced by
There is no parameter named $shareWith. Did you maybe mean $shareWithAddress?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
81
	 * @param string $name
82
	 * @param int $remote_id
83
	 *
84
	 * @return bool
85
	 *
86
	 * @throws \OC\HintException
87
	 * @throws \OC\ServerNotAvailableException
88
	 */
89
	public function sendRemoteShare(Address $shareWithAddress,
90
		Address $ownerAddress,
91
		Address $sharedByAddress,
92
		$token,
93
		$name,
94
		$remote_id
95
	) {
96
		$remoteShareSuccess = false;
97
		if ($shareWithAddress->getUserId() && $shareWithAddress->getCloudId()) {
98
			$remoteShareSuccess = $this->sendOcmRemoteShare(
99
				$shareWithAddress, $ownerAddress, $sharedByAddress, $token, $name, $remote_id
100
			);
101
			if (!$remoteShareSuccess) {
102
				$remoteShareSuccess = $this->sendPreOcmRemoteShare(
103
					$shareWithAddress, $ownerAddress, $sharedByAddress, $token, $name, $remote_id
104
				);
105
			}
106
		}
107
		if ($remoteShareSuccess) {
108
			\OC_Hook::emit(
109
				'OCP\Share',
110
				'federated_share_added',
111
				['server' => $shareWithAddress->getHostName()]
112
			);
113
		}
114
		return $remoteShareSuccess;
115
	}
116
117
	/**
118
	 * ask owner to re-share the file with the given user
119
	 *
120
	 * @param string $token
121
	 * @param int $id remote Id
122
	 * @param int $shareId internal share Id
123
	 * @param string $remote remote address of the owner
124
	 * @param string $shareWith
125
	 * @param int $permission
126
	 * @return bool
127
	 * @throws \Exception
128
	 */
129
	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission) {
130
		$ocmNotificationManager = new NotificationManager();
131
		$data = [
132
			'shareWith' => $shareWith,
133
			'senderId' => $id
134
		];
135
		$ocmNotification = $ocmNotificationManager->convertToOcmFileNotification($shareId, $token, 'reshare', $data);
136
		$ocmFields = $ocmNotification->toArray();
137
138
		$url = \rtrim(
139
			$this->addressHandler->removeProtocolFromUrl($remote),
140
			'/'
141
		);
142
		$result = $this->tryHttpPostToShareEndpoint($url, '/notifications', $ocmFields, true);
143
		if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) {
144
			$response = \json_decode($result['result'], true);
145
			if (\is_array($response) && isset($response['token'], $response['providerId'])) {
146
				return [
147
					$response['token'],
148
					(int) $response['providerId']
149
				];
150
			}
151
			return true;
152
		}
153
154
		$fields = [
155
			'shareWith' => $shareWith,
156
			'token' => $token,
157
			'permission' => $permission,
158
			'remoteId' => $shareId
159
		];
160
161
		$url = $this->addressHandler->removeProtocolFromUrl($remote);
162
		$result = $this->tryHttpPostToShareEndpoint(\rtrim($url, '/'), '/' . $id . '/reshare', $fields);
163
		$status = \json_decode($result['result'], true);
164
165
		$httpRequestSuccessful = $result['success'];
166
		$validToken = isset($status['ocs']['data']['token']) && \is_string($status['ocs']['data']['token']);
167
		$validRemoteId = isset($status['ocs']['data']['remoteId']);
168
169
		if ($httpRequestSuccessful && $this->isOcsStatusOk($status) && $validToken && $validRemoteId) {
170
			return [
171
				$status['ocs']['data']['token'],
172
				(int)$status['ocs']['data']['remoteId']
173
			];
174
		}
175
176
		return false;
177
	}
178
179
	/**
180
	 * send server-to-server unshare to remote server
181
	 *
182
	 * @param string $remote url
183
	 * @param int $id share id
184
	 * @param string $token
185
	 * @return bool
186
	 */
187
	public function sendRemoteUnShare($remote, $id, $token) {
188
		return $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
189
	}
190
191
	/**
192
	 * send server-to-server unshare to remote server
193
	 *
194
	 * @param string $remote url
195
	 * @param int $id share id
196
	 * @param string $token
197
	 * @return bool
198
	 */
199
	public function sendRevokeShare($remote, $id, $token) {
200
		return $this->sendUpdateToRemote($remote, $id, $token, 'revoke');
201
	}
202
203
	/**
204
	 * send notification to remote server if the permissions was changed
205
	 *
206
	 * @param string $remote
207
	 * @param int $remoteId
208
	 * @param string $token
209
	 * @param int $permissions
210
	 * @return bool
211
	 */
212
	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
213
		return $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
214
	}
215
216
	/**
217
	 * forward accept reShare to remote server
218
	 *
219
	 * @param string $remote
220
	 * @param int $remoteId
221
	 * @param string $token
222
	 */
223
	public function sendAcceptShare($remote, $remoteId, $token) {
224
		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
225
	}
226
227
	/**
228
	 * forward decline reShare to remote server
229
	 *
230
	 * @param string $remote
231
	 * @param int $remoteId
232
	 * @param string $token
233
	 */
234
	public function sendDeclineShare($remote, $remoteId, $token) {
235
		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
236
	}
237
238
	/**
239
	 * inform remote server whether server-to-server share was accepted/declined
240
	 *
241
	 * @param string $remote
242
	 * @param int $remoteId Share id on the remote host
243
	 * @param string $token
244
	 * @param string $action possible actions:
245
	 * 	                     accept, decline, unshare, revoke, permissions
246
	 * @param array $data
247
	 * @param int $try
248
	 *
249
	 * @return boolean
250
	 *
251
	 * @throws \Exception
252
	 */
253
	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
254
		$ocmNotificationManager = new NotificationManager();
255
		$ocmNotification = $ocmNotificationManager->convertToOcmFileNotification($remoteId, $token, $action, $data);
256
		$ocmFields = $ocmNotification->toArray();
257
		$url = \rtrim(
258
			$this->addressHandler->removeProtocolFromUrl($remote),
259
			'/'
260
		);
261
		$result = $this->tryHttpPostToShareEndpoint($url, '/notifications', $ocmFields, true);
262
		if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) {
263
			return true;
264
		}
265
266
		$fields = ['token' => $token];
267
		foreach ($data as $key => $value) {
268
			$fields[$key] = $value;
269
		}
270
271
		$url = \rtrim(
272
			$this->addressHandler->removeProtocolFromUrl($remote),
273
			'/'
274
		);
275
		$result = $this->tryHttpPostToShareEndpoint($url, '/' . $remoteId . '/' . $action, $fields);
276
		$status = \json_decode($result['result'], true);
277
278
		if ($result['success'] && $this->isOcsStatusOk($status)) {
279
			return true;
280
		} elseif ($try === 0) {
281
			// only add new job on first try
282
			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
283
				[
284
					'remote' => $remote,
285
					'remoteId' => $remoteId,
286
					'token' => $token,
287
					'action' => $action,
288
					'data' => \json_encode($data),
289
					'try' => $try,
290
					'lastRun' => $this->getTimestamp()
291
				]
292
			);
293
		}
294
295
		return false;
296
	}
297
298
	/**
299
	 * return current timestamp
300
	 *
301
	 * @return int
302
	 */
303
	protected function getTimestamp() {
304
		return \time();
305
	}
306
307
	/**
308
	 * try http post first with https and then with http as a fallback
309
	 *
310
	 * @param string $remoteDomain
311
	 * @param string $urlSuffix
312
	 * @param array $fields post parameters
313
	 * @param bool $useOcm send request to OCM endpoint instead of OCS
314
	 *
315
	 * @return array
316
	 *
317
	 * @throws \Exception
318
	 */
319
	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $useOcm = false) {
320
		$client = $this->httpClientService->newClient();
321
		$protocol = 'https://';
322
		$result = [
323
			'success' => false,
324
			'result' => '',
325
		];
326
		$try = 0;
327
328
		while ($result['success'] === false && $try < 2) {
329
			if ($useOcm) {
330
				$endpoint = $this->discoveryManager->getOcmShareEndpoint($protocol . $remoteDomain);
331
				$endpoint .= $urlSuffix;
332
			} else {
333
				$relativePath = $this->discoveryManager->getShareEndpoint($protocol . $remoteDomain);
334
				$endpoint = $protocol . $remoteDomain . $relativePath . $urlSuffix . '?format=' . self::RESPONSE_FORMAT;
335
			}
336
337
			try {
338
				$response = $client->post($endpoint, [
339
					'body' => $fields,
340
					'timeout' => 10,
341
					'connect_timeout' => 10,
342
				]);
343
				$result['result'] = $response->getBody();
344
				$result['statusCode'] = $response->getStatusCode();
345
				$result['success'] = true;
346
				break;
347
			} catch (\Exception $e) {
348
				// if flat re-sharing is not supported by the remote server
349
				// we re-throw the exception and fall back to the old behaviour.
350
				// (flat re-shares has been introduced in ownCloud 9.1)
351
				if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
352
					throw $e;
353
				}
354
				$allowHttpFallback = $this->config->getSystemValue('sharing.federation.allowHttpFallback', false) === true;
355
				if (!$allowHttpFallback) {
356
					break;
357
				}
358
				$try++;
359
				$protocol = 'http://';
360
			}
361
		}
362
363
		return $result;
364
	}
365
366
	protected function sendOcmRemoteShare(Address $shareWithAddress, Address $ownerAddress, Address $sharedByAddress, $token, $name, $remote_id) {
367
		$fields = [
368
			'shareWith' => $shareWithAddress->getCloudId(),
369
			'name' => $name,
370
			'providerId' => $remote_id,
371
			'owner' => $ownerAddress->getCloudId(),
372
			'ownerDisplayName' => $ownerAddress->getDisplayName(),
373
			'sender' => $sharedByAddress->getCloudId(),
374
			'senderDisplayName' => $sharedByAddress->getDisplayName(),
375
			'shareType' => 'user',
376
			'resourceType' => 'file',
377
			'protocol' => [
378
				'name' => 'webdav',
379
				'options' => [
380
					'sharedSecret' => $token
381
				]
382
			]
383
		];
384
385
		$url = $shareWithAddress->getCleanHostName();
386
		$result = $this->tryHttpPostToShareEndpoint($url, '/shares', $fields, true);
387
388
		if (isset($result['statusCode']) && $result['statusCode'] === Http::STATUS_CREATED) {
389
			return true;
390
		}
391
		return false;
392
	}
393
394
	protected function sendPreOcmRemoteShare(Address $shareWithAddress, Address $ownerAddress, Address $sharedByAddress, $token, $name, $remote_id) {
395
		$fields = [
396
			'shareWith' => $shareWithAddress->getUserId(),
397
			'token' => $token,
398
			'name' => $name,
399
			'remoteId' => $remote_id,
400
			'owner' => $ownerAddress->getUserId(),
401
			'ownerFederatedId' => $ownerAddress->getCloudId(),
402
			'sharedBy' => $sharedByAddress->getUserId(),
403
			'sharedByFederatedId' => $sharedByAddress->getUserId(),
404
			'remote' => $this->addressHandler->generateRemoteURL(),
405
		];
406
		$url = $shareWithAddress->getCleanHostName();
407
		$result = $this->tryHttpPostToShareEndpoint($url, '', $fields);
408
		$status = \json_decode($result['result'], true);
409
410
		if ($result['success'] && $this->isOcsStatusOk($status)) {
411
			return true;
412
		}
413
		return false;
414
	}
415
416
	/**
417
	 * Validate ocs response - 100 or 200 means success
418
	 *
419
	 * @param array $status
420
	 *
421
	 * @return bool
422
	 */
423
	private function isOcsStatusOk($status) {
424
		return \in_array($status['ocs']['meta']['statuscode'], [100, 200]);
425
	}
426
}
427