Completed
Pull Request — master (#4106)
by Blizzz
11:34
created
apps/testing/lib/Application.php 2 patches
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -25,18 +25,18 @@
 block discarded – undo
25 25
 use OCA\Testing\AlternativeHomeUserBackend;
26 26
 
27 27
 class Application extends App {
28
-	public function __construct (array $urlParams = array()) {
29
-		$appName = 'testing';
30
-		parent::__construct($appName, $urlParams);
28
+    public function __construct (array $urlParams = array()) {
29
+        $appName = 'testing';
30
+        parent::__construct($appName, $urlParams);
31 31
 
32
-		$c = $this->getContainer();
33
-		$config = $c->getServer()->getConfig();
34
-		if ($config->getAppValue($appName, 'enable_alt_user_backend', 'no') === 'yes') {
35
-			$userManager = $c->getServer()->getUserManager();
32
+        $c = $this->getContainer();
33
+        $config = $c->getServer()->getConfig();
34
+        if ($config->getAppValue($appName, 'enable_alt_user_backend', 'no') === 'yes') {
35
+            $userManager = $c->getServer()->getUserManager();
36 36
 
37
-			// replace all user backends with this one
38
-			$userManager->clearBackends();
39
-			$userManager->registerBackend($c->query(AlternativeHomeUserBackend::class));
40
-		}
41
-	}
37
+            // replace all user backends with this one
38
+            $userManager->clearBackends();
39
+            $userManager->registerBackend($c->query(AlternativeHomeUserBackend::class));
40
+        }
41
+    }
42 42
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@
 block discarded – undo
25 25
 use OCA\Testing\AlternativeHomeUserBackend;
26 26
 
27 27
 class Application extends App {
28
-	public function __construct (array $urlParams = array()) {
28
+	public function __construct(array $urlParams = array()) {
29 29
 		$appName = 'testing';
30 30
 		parent::__construct($appName, $urlParams);
31 31
 
Please login to merge, or discard this patch.
apps/testing/lib/AlternativeHomeUserBackend.php 2 patches
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -34,23 +34,23 @@
 block discarded – undo
34 34
  *	]
35 35
  */
36 36
 class AlternativeHomeUserBackend extends \OC\User\Database {
37
-	public function __construct() {
38
-		parent::__construct();
39
-	}
40
-	/**
41
-	 * get the user's home directory
42
-	 * @param string $uid the username
43
-	 * @return string|false
44
-	 */
45
-	public function getHome($uid) {
46
-		if ($this->userExists($uid)) {
47
-			// workaround to avoid killing the admin
48
-			if ($uid !== 'admin') {
49
-				$uid = md5($uid);
50
-			}
51
-			return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
52
-		}
37
+    public function __construct() {
38
+        parent::__construct();
39
+    }
40
+    /**
41
+     * get the user's home directory
42
+     * @param string $uid the username
43
+     * @return string|false
44
+     */
45
+    public function getHome($uid) {
46
+        if ($this->userExists($uid)) {
47
+            // workaround to avoid killing the admin
48
+            if ($uid !== 'admin') {
49
+                $uid = md5($uid);
50
+            }
51
+            return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
52
+        }
53 53
 
54
-		return false;
55
-	}
54
+        return false;
55
+    }
56 56
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@
 block discarded – undo
48 48
 			if ($uid !== 'admin') {
49 49
 				$uid = md5($uid);
50 50
 			}
51
-			return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
51
+			return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/'.$uid;
52 52
 		}
53 53
 
54 54
 		return false;
Please login to merge, or discard this patch.
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/templates/settings-admin.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -5,16 +5,16 @@  discard block
 block discarded – undo
5 5
 ?>
6 6
 
7 7
 <div id="fileSharingSettings" class="followupsection">
8
-	<h3><?php p($l->t('Federated Cloud Sharing'));?></h3>
8
+	<h3><?php p($l->t('Federated Cloud Sharing')); ?></h3>
9 9
 	<a target="_blank" rel="noreferrer" class="icon-info svg"
10
-		title="<?php p($l->t('Open documentation'));?>"
10
+		title="<?php p($l->t('Open documentation')); ?>"
11 11
 		href="<?php p(link_to_docs('admin-sharing-federated')); ?>"></a>
12 12
 
13 13
 	<p>
14 14
 		<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled" class="checkbox"
15 15
 			   value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
16 16
 		<label for="outgoingServer2serverShareEnabled">
17
-			<?php p($l->t('Allow users on this server to send shares to other servers'));?>
17
+			<?php p($l->t('Allow users on this server to send shares to other servers')); ?>
18 18
 		</label>
19 19
 	</p>
20 20
 
@@ -22,14 +22,14 @@  discard block
 block discarded – undo
22 22
 		<input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled" class="checkbox"
23 23
 			   value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
24 24
 		<label for="incomingServer2serverShareEnabled">
25
-			<?php p($l->t('Allow users on this server to receive shares from other servers'));?>
25
+			<?php p($l->t('Allow users on this server to receive shares from other servers')); ?>
26 26
 		</label><br/>
27 27
 	</p>
28 28
 	<p>
29 29
 		<input type="checkbox" name="lookupServerEnabled" id="lookupServerEnabled" class="checkbox"
30 30
 			   value="1" <?php if ($_['lookupServerEnabled']) print_unescaped('checked="checked"'); ?> />
31 31
 		<label for="lookupServerEnabled">
32
-			<?php p($l->t('Search global and public address book for users'));?>
32
+			<?php p($l->t('Search global and public address book for users')); ?>
33 33
 		</label><br/>
34 34
 	</p>
35 35
 </div>
Please login to merge, or discard this patch.
Braces   +12 added lines, -3 removed lines patch added patch discarded remove patch
@@ -12,7 +12,10 @@  discard block
 block discarded – undo
12 12
 
13 13
 	<p>
14 14
 		<input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled" class="checkbox"
15
-			   value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
15
+			   value="1" <?php if ($_['outgoingServer2serverShareEnabled']) {
16
+    print_unescaped('checked="checked"');
17
+}
18
+?> />
16 19
 		<label for="outgoingServer2serverShareEnabled">
17 20
 			<?php p($l->t('Allow users on this server to send shares to other servers'));?>
18 21
 		</label>
@@ -20,14 +23,20 @@  discard block
 block discarded – undo
20 23
 
21 24
 	<p>
22 25
 		<input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled" class="checkbox"
23
-			   value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> />
26
+			   value="1" <?php if ($_['incomingServer2serverShareEnabled']) {
27
+    print_unescaped('checked="checked"');
28
+}
29
+?> />
24 30
 		<label for="incomingServer2serverShareEnabled">
25 31
 			<?php p($l->t('Allow users on this server to receive shares from other servers'));?>
26 32
 		</label><br/>
27 33
 	</p>
28 34
 	<p>
29 35
 		<input type="checkbox" name="lookupServerEnabled" id="lookupServerEnabled" class="checkbox"
30
-			   value="1" <?php if ($_['lookupServerEnabled']) print_unescaped('checked="checked"'); ?> />
36
+			   value="1" <?php if ($_['lookupServerEnabled']) {
37
+    print_unescaped('checked="checked"');
38
+}
39
+?> />
31 40
 		<label for="lookupServerEnabled">
32 41
 			<?php p($l->t('Search global and public address book for users'));?>
33 42
 		</label><br/>
Please login to merge, or discard this patch.
apps/federatedfilesharing/settings-personal.php 2 patches
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 $isIE8 = false;
36 36
 preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
37 37
 if (count($matches) > 0 && $matches[1] <= 9) {
38
-	$isIE8 = true;
38
+    $isIE8 = true;
39 39
 }
40 40
 
41 41
 $cloudID = \OC::$server->getUserSession()->getUser()->getCloudId();
@@ -45,15 +45,15 @@  discard block
 block discarded – undo
45 45
 $color = $theme->getMailHeaderColor();
46 46
 $textColor = "#ffffff";
47 47
 if(\OC::$server->getAppManager()->isEnabledForUser("theming")) {
48
-	$logoPath = $theme->getLogo();
49
-	try {
50
-		$util = \OC::$server->query("\OCA\Theming\Util");
51
-		if($util->invertTextColor($color)) {
52
-			$textColor = "#000000";
53
-		}
54
-	} catch (OCP\AppFramework\QueryException $e) {
48
+    $logoPath = $theme->getLogo();
49
+    try {
50
+        $util = \OC::$server->query("\OCA\Theming\Util");
51
+        if($util->invertTextColor($color)) {
52
+            $textColor = "#000000";
53
+        }
54
+    } catch (OCP\AppFramework\QueryException $e) {
55 55
 		
56
-	}
56
+    }
57 57
 }
58 58
 
59 59
 
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -39,16 +39,16 @@
 block discarded – undo
39 39
 }
40 40
 
41 41
 $cloudID = \OC::$server->getUserSession()->getUser()->getCloudId();
42
-$url = 'https://nextcloud.com/federation#' . $cloudID;
42
+$url = 'https://nextcloud.com/federation#'.$cloudID;
43 43
 $logoPath = \OC::$server->getURLGenerator()->imagePath('core', 'logo-icon.svg');
44 44
 $theme = \OC::$server->getThemingDefaults();
45 45
 $color = $theme->getMailHeaderColor();
46 46
 $textColor = "#ffffff";
47
-if(\OC::$server->getAppManager()->isEnabledForUser("theming")) {
47
+if (\OC::$server->getAppManager()->isEnabledForUser("theming")) {
48 48
 	$logoPath = $theme->getLogo();
49 49
 	try {
50 50
 		$util = \OC::$server->query("\OCA\Theming\Util");
51
-		if($util->invertTextColor($color)) {
51
+		if ($util->invertTextColor($color)) {
52 52
 			$textColor = "#000000";
53 53
 		}
54 54
 	} catch (OCP\AppFramework\QueryException $e) {
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 2 patches
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.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 			'remoteId' => $shareId
134 134
 		);
135 135
 
136
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
136
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$id.'/reshare', $fields);
137 137
 		$status = json_decode($result['result'], true);
138 138
 
139 139
 		$httpRequestSuccessful = $result['success'];
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
145 145
 			return [
146 146
 				$status['ocs']['data']['token'],
147
-				(int)$status['ocs']['data']['remoteId']
147
+				(int) $status['ocs']['data']['remoteId']
148 148
 			];
149 149
 		}
150 150
 
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 			$fields[$key] = $value;
229 229
 		}
230 230
 
231
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields);
231
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$remoteId.'/'.$action, $fields);
232 232
 		$status = json_decode($result['result'], true);
233 233
 
234 234
 		if ($result['success'] &&
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		$client = $this->httpClientService->newClient();
280 280
 
281 281
 		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
282
-			$remoteDomain = 'https://' . $remoteDomain;
282
+			$remoteDomain = 'https://'.$remoteDomain;
283 283
 		}
284 284
 
285 285
 		$result = [
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 
290 290
 		$endpoint = $this->discoveryManager->getShareEndpoint($remoteDomain);
291 291
 		try {
292
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
292
+			$response = $client->post($remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT, [
293 293
 				'body' => $fields,
294 294
 				'timeout' => 10,
295 295
 				'connect_timeout' => 10,
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifier.php 2 patches
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.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -184,12 +184,12 @@
 block discarded – undo
184 184
 		}
185 185
 
186 186
 		try {
187
-			$this->getDisplayNameFromContact($user . '@http://' . $server);
187
+			$this->getDisplayNameFromContact($user.'@http://'.$server);
188 188
 		} catch (\OutOfBoundsException $e) {
189 189
 		}
190 190
 
191 191
 		try {
192
-			$this->getDisplayNameFromContact($user . '@https://' . $server);
192
+			$this->getDisplayNameFromContact($user.'@https://'.$server);
193 193
 		} catch (\OutOfBoundsException $e) {
194 194
 		}
195 195
 
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/DiscoveryManager.php 2 patches
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -39,105 +39,105 @@
 block discarded – undo
39 39
  * @package OCA\FederatedFileSharing
40 40
  */
41 41
 class DiscoveryManager {
42
-	/** @var ICache */
43
-	private $cache;
44
-	/** @var IClient */
45
-	private $client;
42
+    /** @var ICache */
43
+    private $cache;
44
+    /** @var IClient */
45
+    private $client;
46 46
 
47
-	/**
48
-	 * @param ICacheFactory $cacheFactory
49
-	 * @param IClientService $clientService
50
-	 */
51
-	public function __construct(ICacheFactory $cacheFactory,
52
-								IClientService $clientService) {
53
-		$this->cache = $cacheFactory->create('ocs-discovery');
54
-		$this->client = $clientService->newClient();
55
-	}
47
+    /**
48
+     * @param ICacheFactory $cacheFactory
49
+     * @param IClientService $clientService
50
+     */
51
+    public function __construct(ICacheFactory $cacheFactory,
52
+                                IClientService $clientService) {
53
+        $this->cache = $cacheFactory->create('ocs-discovery');
54
+        $this->client = $clientService->newClient();
55
+    }
56 56
 
57
-	/**
58
-	 * Returns whether the specified URL includes only safe characters, if not
59
-	 * returns false
60
-	 *
61
-	 * @param string $url
62
-	 * @return bool
63
-	 */
64
-	private function isSafeUrl($url) {
65
-		return (bool)preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
66
-	}
57
+    /**
58
+     * Returns whether the specified URL includes only safe characters, if not
59
+     * returns false
60
+     *
61
+     * @param string $url
62
+     * @return bool
63
+     */
64
+    private function isSafeUrl($url) {
65
+        return (bool)preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
66
+    }
67 67
 
68
-	/**
69
-	 * Discover the actual data and do some naive caching to ensure that the data
70
-	 * is not requested multiple times.
71
-	 *
72
-	 * If no valid discovery data is found the Nextcloud defaults are returned.
73
-	 *
74
-	 * @param string $remote
75
-	 * @return array
76
-	 */
77
-	private function discover($remote) {
78
-		// Check if something is in the cache
79
-		if($cacheData = $this->cache->get($remote)) {
80
-			return json_decode($cacheData, true);
81
-		}
68
+    /**
69
+     * Discover the actual data and do some naive caching to ensure that the data
70
+     * is not requested multiple times.
71
+     *
72
+     * If no valid discovery data is found the Nextcloud defaults are returned.
73
+     *
74
+     * @param string $remote
75
+     * @return array
76
+     */
77
+    private function discover($remote) {
78
+        // Check if something is in the cache
79
+        if($cacheData = $this->cache->get($remote)) {
80
+            return json_decode($cacheData, true);
81
+        }
82 82
 
83
-		// Default response body
84
-		$discoveredServices = [
85
-			'webdav' => '/public.php/webdav',
86
-			'share' => '/ocs/v1.php/cloud/shares',
87
-		];
83
+        // Default response body
84
+        $discoveredServices = [
85
+            'webdav' => '/public.php/webdav',
86
+            'share' => '/ocs/v1.php/cloud/shares',
87
+        ];
88 88
 
89
-		// Read the data from the response body
90
-		try {
91
-			$response = $this->client->get($remote . '/ocs-provider/', [
92
-				'timeout' => 10,
93
-				'connect_timeout' => 10,
94
-			]);
95
-			if($response->getStatusCode() === 200) {
96
-				$decodedService = json_decode($response->getBody(), true);
97
-				if(is_array($decodedService)) {
98
-					$endpoints = [
99
-						'webdav',
100
-						'share',
101
-					];
89
+        // Read the data from the response body
90
+        try {
91
+            $response = $this->client->get($remote . '/ocs-provider/', [
92
+                'timeout' => 10,
93
+                'connect_timeout' => 10,
94
+            ]);
95
+            if($response->getStatusCode() === 200) {
96
+                $decodedService = json_decode($response->getBody(), true);
97
+                if(is_array($decodedService)) {
98
+                    $endpoints = [
99
+                        'webdav',
100
+                        'share',
101
+                    ];
102 102
 
103
-					foreach($endpoints as $endpoint) {
104
-						if(isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
-							$endpointUrl = (string)$decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
-							if($this->isSafeUrl($endpointUrl)) {
107
-								$discoveredServices[$endpoint] = $endpointUrl;
108
-							}
109
-						}
110
-					}
111
-				}
112
-			}
113
-		} catch (ClientException $e) {
114
-			// Don't throw any exception since exceptions are handled before
115
-		} catch (ConnectException $e) {
116
-			// Don't throw any exception since exceptions are handled before
117
-		}
103
+                    foreach($endpoints as $endpoint) {
104
+                        if(isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
+                            $endpointUrl = (string)$decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
+                            if($this->isSafeUrl($endpointUrl)) {
107
+                                $discoveredServices[$endpoint] = $endpointUrl;
108
+                            }
109
+                        }
110
+                    }
111
+                }
112
+            }
113
+        } catch (ClientException $e) {
114
+            // Don't throw any exception since exceptions are handled before
115
+        } catch (ConnectException $e) {
116
+            // Don't throw any exception since exceptions are handled before
117
+        }
118 118
 
119
-		// Write into cache
120
-		$this->cache->set($remote, json_encode($discoveredServices));
121
-		return $discoveredServices;
122
-	}
119
+        // Write into cache
120
+        $this->cache->set($remote, json_encode($discoveredServices));
121
+        return $discoveredServices;
122
+    }
123 123
 
124
-	/**
125
-	 * Return the public WebDAV endpoint used by the specified remote
126
-	 *
127
-	 * @param string $host
128
-	 * @return string
129
-	 */
130
-	public function getWebDavEndpoint($host) {
131
-		return $this->discover($host)['webdav'];
132
-	}
124
+    /**
125
+     * Return the public WebDAV endpoint used by the specified remote
126
+     *
127
+     * @param string $host
128
+     * @return string
129
+     */
130
+    public function getWebDavEndpoint($host) {
131
+        return $this->discover($host)['webdav'];
132
+    }
133 133
 
134
-	/**
135
-	 * Return the sharing endpoint used by the specified remote
136
-	 *
137
-	 * @param string $host
138
-	 * @return string
139
-	 */
140
-	public function getShareEndpoint($host) {
141
-		return $this->discover($host)['share'];
142
-	}
134
+    /**
135
+     * Return the sharing endpoint used by the specified remote
136
+     *
137
+     * @param string $host
138
+     * @return string
139
+     */
140
+    public function getShareEndpoint($host) {
141
+        return $this->discover($host)['share'];
142
+    }
143 143
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 	 * @return bool
63 63
 	 */
64 64
 	private function isSafeUrl($url) {
65
-		return (bool)preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
65
+		return (bool) preg_match('/^[\/\.A-Za-z0-9]+$/', $url);
66 66
 	}
67 67
 
68 68
 	/**
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 */
77 77
 	private function discover($remote) {
78 78
 		// Check if something is in the cache
79
-		if($cacheData = $this->cache->get($remote)) {
79
+		if ($cacheData = $this->cache->get($remote)) {
80 80
 			return json_decode($cacheData, true);
81 81
 		}
82 82
 
@@ -88,22 +88,22 @@  discard block
 block discarded – undo
88 88
 
89 89
 		// Read the data from the response body
90 90
 		try {
91
-			$response = $this->client->get($remote . '/ocs-provider/', [
91
+			$response = $this->client->get($remote.'/ocs-provider/', [
92 92
 				'timeout' => 10,
93 93
 				'connect_timeout' => 10,
94 94
 			]);
95
-			if($response->getStatusCode() === 200) {
95
+			if ($response->getStatusCode() === 200) {
96 96
 				$decodedService = json_decode($response->getBody(), true);
97
-				if(is_array($decodedService)) {
97
+				if (is_array($decodedService)) {
98 98
 					$endpoints = [
99 99
 						'webdav',
100 100
 						'share',
101 101
 					];
102 102
 
103
-					foreach($endpoints as $endpoint) {
104
-						if(isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
-							$endpointUrl = (string)$decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
-							if($this->isSafeUrl($endpointUrl)) {
103
+					foreach ($endpoints as $endpoint) {
104
+						if (isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) {
105
+							$endpointUrl = (string) $decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint];
106
+							if ($this->isSafeUrl($endpointUrl)) {
107 107
 								$discoveredServices[$endpoint] = $endpointUrl;
108 108
 							}
109 109
 						}
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/MountPublicLinkController.php 2 patches
Indentation   +282 added lines, -282 removed lines patch added patch discarded remove patch
@@ -54,287 +54,287 @@
 block discarded – undo
54 54
  */
55 55
 class MountPublicLinkController extends Controller {
56 56
 
57
-	/** @var FederatedShareProvider */
58
-	private $federatedShareProvider;
59
-
60
-	/** @var AddressHandler */
61
-	private $addressHandler;
62
-
63
-	/** @var IManager  */
64
-	private $shareManager;
65
-
66
-	/** @var  ISession */
67
-	private $session;
68
-
69
-	/** @var IL10N */
70
-	private $l;
71
-
72
-	/** @var IUserSession */
73
-	private $userSession;
74
-
75
-	/** @var IClientService */
76
-	private $clientService;
77
-
78
-	/** @var ICloudIdManager  */
79
-	private $cloudIdManager;
80
-
81
-	/**
82
-	 * MountPublicLinkController constructor.
83
-	 *
84
-	 * @param string $appName
85
-	 * @param IRequest $request
86
-	 * @param FederatedShareProvider $federatedShareProvider
87
-	 * @param IManager $shareManager
88
-	 * @param AddressHandler $addressHandler
89
-	 * @param ISession $session
90
-	 * @param IL10N $l
91
-	 * @param IUserSession $userSession
92
-	 * @param IClientService $clientService
93
-	 * @param ICloudIdManager $cloudIdManager
94
-	 */
95
-	public function __construct($appName,
96
-								IRequest $request,
97
-								FederatedShareProvider $federatedShareProvider,
98
-								IManager $shareManager,
99
-								AddressHandler $addressHandler,
100
-								ISession $session,
101
-								IL10N $l,
102
-								IUserSession $userSession,
103
-								IClientService $clientService,
104
-								ICloudIdManager $cloudIdManager
105
-	) {
106
-		parent::__construct($appName, $request);
107
-
108
-		$this->federatedShareProvider = $federatedShareProvider;
109
-		$this->shareManager = $shareManager;
110
-		$this->addressHandler = $addressHandler;
111
-		$this->session = $session;
112
-		$this->l = $l;
113
-		$this->userSession = $userSession;
114
-		$this->clientService = $clientService;
115
-		$this->cloudIdManager = $cloudIdManager;
116
-	}
117
-
118
-	/**
119
-	 * send federated share to a user of a public link
120
-	 *
121
-	 * @NoCSRFRequired
122
-	 * @PublicPage
123
-	 * @BruteForceProtection publicLink2FederatedShare
124
-	 *
125
-	 * @param string $shareWith
126
-	 * @param string $token
127
-	 * @param string $password
128
-	 * @return JSONResponse
129
-	 */
130
-	public function createFederatedShare($shareWith, $token, $password = '') {
131
-
132
-		if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
-			return new JSONResponse(
134
-				['message' => 'This server doesn\'t support outgoing federated shares'],
135
-				Http::STATUS_BAD_REQUEST
136
-			);
137
-		}
138
-
139
-		try {
140
-			list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
-			$share = $this->shareManager->getShareByToken($token);
142
-		} catch (HintException $e) {
143
-			return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
-		}
145
-
146
-		// make sure that user is authenticated in case of a password protected link
147
-		$storedPassword = $share->getPassword();
148
-		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
-			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
151
-			return new JSONResponse(
152
-				['message' => 'No permission to access the share'],
153
-				Http::STATUS_BAD_REQUEST
154
-			);
155
-		}
156
-
157
-		$share->setSharedWith($shareWith);
158
-
159
-		try {
160
-			$this->federatedShareProvider->create($share);
161
-		} catch (\Exception $e) {
162
-			return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
163
-		}
164
-
165
-		return new JSONResponse(['remoteUrl' => $server]);
166
-	}
167
-
168
-	/**
169
-	 * ask other server to get a federated share
170
-	 *
171
-	 * @NoAdminRequired
172
-	 *
173
-	 * @param string $token
174
-	 * @param string $remote
175
-	 * @param string $password
176
-	 * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
177
-	 * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
178
-	 * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
179
-	 * @return JSONResponse
180
-	 */
181
-	public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
182
-		// check if server admin allows to mount public links from other servers
183
-		if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
184
-			return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
185
-		}
186
-
187
-		$cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
188
-
189
-		$httpClient = $this->clientService->newClient();
190
-
191
-		try {
192
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
193
-				[
194
-					'body' =>
195
-						[
196
-							'token' => $token,
197
-							'shareWith' => rtrim($cloudId->getId(), '/'),
198
-							'password' => $password
199
-						],
200
-					'connect_timeout' => 10,
201
-				]
202
-			);
203
-		} catch (\Exception $e) {
204
-			if (empty($password)) {
205
-				$message = $this->l->t("Couldn't establish a federated share.");
206
-			} else {
207
-				$message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
208
-			}
209
-			return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
210
-		}
211
-
212
-		$body = $response->getBody();
213
-		$result = json_decode($body, true);
214
-
215
-		if (is_array($result) && isset($result['remoteUrl'])) {
216
-			return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
217
-		}
218
-
219
-		// if we doesn't get the expected response we assume that we try to add
220
-		// a federated share from a Nextcloud <= 9 server
221
-		return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
222
-	}
223
-
224
-	/**
225
-	 * Allow Nextcloud to mount a public link directly
226
-	 *
227
-	 * This code was copied from the apps/files_sharing/ajax/external.php with
228
-	 * minimal changes, just to guarantee backward compatibility
229
-	 *
230
-	 * ToDo: Remove this method once Nextcloud 9 reaches end of life
231
-	 *
232
-	 * @param string $token
233
-	 * @param string $remote
234
-	 * @param string $password
235
-	 * @param string $name
236
-	 * @param string $owner
237
-	 * @param string $ownerDisplayName
238
-	 * @return JSONResponse
239
-	 */
240
-	private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
241
-
242
-		// Check for invalid name
243
-		if (!Util::isValidFileName($name)) {
244
-			return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
245
-		}
246
-		$currentUser = $this->userSession->getUser()->getUID();
247
-		$currentServer = $this->addressHandler->generateRemoteURL();
248
-		if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
249
-			return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
250
-		}
251
-		$discoveryManager = new DiscoveryManager(
252
-			\OC::$server->getMemCacheFactory(),
253
-			\OC::$server->getHTTPClientService()
254
-		);
255
-		$externalManager = new Manager(
256
-			\OC::$server->getDatabaseConnection(),
257
-			Filesystem::getMountManager(),
258
-			Filesystem::getLoader(),
259
-			\OC::$server->getHTTPClientService(),
260
-			\OC::$server->getNotificationManager(),
261
-			$discoveryManager,
262
-			\OC::$server->getUserSession()->getUser()->getUID()
263
-		);
264
-
265
-		// check for ssl cert
266
-
267
-		if (strpos($remote, 'https') === 0) {
268
-			try {
269
-				$client = $this->clientService->newClient();
270
-				$client->get($remote, [
271
-					'timeout' => 10,
272
-					'connect_timeout' => 10,
273
-				])->getBody();
274
-			} catch (\Exception $e) {
275
-				return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
276
-			}
277
-		}
278
-		$mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
279
-		/**
280
-		 * @var \OCA\Files_Sharing\External\Storage $storage
281
-		 */
282
-		$storage = $mount->getStorage();
283
-		try {
284
-			// check if storage exists
285
-			$storage->checkStorageAvailability();
286
-		} catch (StorageInvalidException $e) {
287
-			// note: checkStorageAvailability will already remove the invalid share
288
-			Util::writeLog(
289
-				'federatedfilesharing',
290
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
291
-				Util::DEBUG
292
-			);
293
-			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
294
-		} catch (\Exception $e) {
295
-			Util::writeLog(
296
-				'federatedfilesharing',
297
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
298
-				Util::DEBUG
299
-			);
300
-			$externalManager->removeShare($mount->getMountPoint());
301
-			return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
302
-		}
303
-		$result = $storage->file_exists('');
304
-		if ($result) {
305
-			try {
306
-				$storage->getScanner()->scanAll();
307
-				return new JSONResponse(
308
-					[
309
-						'message' => $this->l->t('Federated Share successfully added'),
310
-						'legacyMount' => '1'
311
-					]
312
-				);
313
-			} catch (StorageInvalidException $e) {
314
-				Util::writeLog(
315
-					'federatedfilesharing',
316
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
317
-					Util::DEBUG
318
-				);
319
-				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
320
-			} catch (\Exception $e) {
321
-				Util::writeLog(
322
-					'federatedfilesharing',
323
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
324
-					Util::DEBUG
325
-				);
326
-				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
327
-			}
328
-		} else {
329
-			$externalManager->removeShare($mount->getMountPoint());
330
-			Util::writeLog(
331
-				'federatedfilesharing',
332
-				'Couldn\'t add remote share',
333
-				Util::DEBUG
334
-			);
335
-			return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
336
-		}
337
-
338
-	}
57
+    /** @var FederatedShareProvider */
58
+    private $federatedShareProvider;
59
+
60
+    /** @var AddressHandler */
61
+    private $addressHandler;
62
+
63
+    /** @var IManager  */
64
+    private $shareManager;
65
+
66
+    /** @var  ISession */
67
+    private $session;
68
+
69
+    /** @var IL10N */
70
+    private $l;
71
+
72
+    /** @var IUserSession */
73
+    private $userSession;
74
+
75
+    /** @var IClientService */
76
+    private $clientService;
77
+
78
+    /** @var ICloudIdManager  */
79
+    private $cloudIdManager;
80
+
81
+    /**
82
+     * MountPublicLinkController constructor.
83
+     *
84
+     * @param string $appName
85
+     * @param IRequest $request
86
+     * @param FederatedShareProvider $federatedShareProvider
87
+     * @param IManager $shareManager
88
+     * @param AddressHandler $addressHandler
89
+     * @param ISession $session
90
+     * @param IL10N $l
91
+     * @param IUserSession $userSession
92
+     * @param IClientService $clientService
93
+     * @param ICloudIdManager $cloudIdManager
94
+     */
95
+    public function __construct($appName,
96
+                                IRequest $request,
97
+                                FederatedShareProvider $federatedShareProvider,
98
+                                IManager $shareManager,
99
+                                AddressHandler $addressHandler,
100
+                                ISession $session,
101
+                                IL10N $l,
102
+                                IUserSession $userSession,
103
+                                IClientService $clientService,
104
+                                ICloudIdManager $cloudIdManager
105
+    ) {
106
+        parent::__construct($appName, $request);
107
+
108
+        $this->federatedShareProvider = $federatedShareProvider;
109
+        $this->shareManager = $shareManager;
110
+        $this->addressHandler = $addressHandler;
111
+        $this->session = $session;
112
+        $this->l = $l;
113
+        $this->userSession = $userSession;
114
+        $this->clientService = $clientService;
115
+        $this->cloudIdManager = $cloudIdManager;
116
+    }
117
+
118
+    /**
119
+     * send federated share to a user of a public link
120
+     *
121
+     * @NoCSRFRequired
122
+     * @PublicPage
123
+     * @BruteForceProtection publicLink2FederatedShare
124
+     *
125
+     * @param string $shareWith
126
+     * @param string $token
127
+     * @param string $password
128
+     * @return JSONResponse
129
+     */
130
+    public function createFederatedShare($shareWith, $token, $password = '') {
131
+
132
+        if (!$this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
133
+            return new JSONResponse(
134
+                ['message' => 'This server doesn\'t support outgoing federated shares'],
135
+                Http::STATUS_BAD_REQUEST
136
+            );
137
+        }
138
+
139
+        try {
140
+            list(, $server) = $this->addressHandler->splitUserRemote($shareWith);
141
+            $share = $this->shareManager->getShareByToken($token);
142
+        } catch (HintException $e) {
143
+            return new JSONResponse(['message' => $e->getHint()], Http::STATUS_BAD_REQUEST);
144
+        }
145
+
146
+        // make sure that user is authenticated in case of a password protected link
147
+        $storedPassword = $share->getPassword();
148
+        $authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149
+            $this->shareManager->checkPassword($share, $password);
150
+        if (!empty($storedPassword) && !$authenticated ) {
151
+            return new JSONResponse(
152
+                ['message' => 'No permission to access the share'],
153
+                Http::STATUS_BAD_REQUEST
154
+            );
155
+        }
156
+
157
+        $share->setSharedWith($shareWith);
158
+
159
+        try {
160
+            $this->federatedShareProvider->create($share);
161
+        } catch (\Exception $e) {
162
+            return new JSONResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
163
+        }
164
+
165
+        return new JSONResponse(['remoteUrl' => $server]);
166
+    }
167
+
168
+    /**
169
+     * ask other server to get a federated share
170
+     *
171
+     * @NoAdminRequired
172
+     *
173
+     * @param string $token
174
+     * @param string $remote
175
+     * @param string $password
176
+     * @param string $owner (only for legacy reasons, can be removed with legacyMountPublicLink())
177
+     * @param string $ownerDisplayName (only for legacy reasons, can be removed with legacyMountPublicLink())
178
+     * @param string $name (only for legacy reasons, can be removed with legacyMountPublicLink())
179
+     * @return JSONResponse
180
+     */
181
+    public function askForFederatedShare($token, $remote, $password = '', $owner = '', $ownerDisplayName = '', $name = '') {
182
+        // check if server admin allows to mount public links from other servers
183
+        if ($this->federatedShareProvider->isIncomingServer2serverShareEnabled() === false) {
184
+            return new JSONResponse(['message' => $this->l->t('Server to server sharing is not enabled on this server')], Http::STATUS_BAD_REQUEST);
185
+        }
186
+
187
+        $cloudId = $this->cloudIdManager->getCloudId($this->userSession->getUser()->getUID(), $this->addressHandler->generateRemoteURL());
188
+
189
+        $httpClient = $this->clientService->newClient();
190
+
191
+        try {
192
+            $response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
193
+                [
194
+                    'body' =>
195
+                        [
196
+                            'token' => $token,
197
+                            'shareWith' => rtrim($cloudId->getId(), '/'),
198
+                            'password' => $password
199
+                        ],
200
+                    'connect_timeout' => 10,
201
+                ]
202
+            );
203
+        } catch (\Exception $e) {
204
+            if (empty($password)) {
205
+                $message = $this->l->t("Couldn't establish a federated share.");
206
+            } else {
207
+                $message = $this->l->t("Couldn't establish a federated share, maybe the password was wrong.");
208
+            }
209
+            return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST);
210
+        }
211
+
212
+        $body = $response->getBody();
213
+        $result = json_decode($body, true);
214
+
215
+        if (is_array($result) && isset($result['remoteUrl'])) {
216
+            return new JSONResponse(['message' => $this->l->t('Federated Share request was successful, you will receive a invitation. Check your notifications.')]);
217
+        }
218
+
219
+        // if we doesn't get the expected response we assume that we try to add
220
+        // a federated share from a Nextcloud <= 9 server
221
+        return $this->legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName);
222
+    }
223
+
224
+    /**
225
+     * Allow Nextcloud to mount a public link directly
226
+     *
227
+     * This code was copied from the apps/files_sharing/ajax/external.php with
228
+     * minimal changes, just to guarantee backward compatibility
229
+     *
230
+     * ToDo: Remove this method once Nextcloud 9 reaches end of life
231
+     *
232
+     * @param string $token
233
+     * @param string $remote
234
+     * @param string $password
235
+     * @param string $name
236
+     * @param string $owner
237
+     * @param string $ownerDisplayName
238
+     * @return JSONResponse
239
+     */
240
+    private function legacyMountPublicLink($token, $remote, $password, $name, $owner, $ownerDisplayName) {
241
+
242
+        // Check for invalid name
243
+        if (!Util::isValidFileName($name)) {
244
+            return new JSONResponse(['message' => $this->l->t('The mountpoint name contains invalid characters.')], Http::STATUS_BAD_REQUEST);
245
+        }
246
+        $currentUser = $this->userSession->getUser()->getUID();
247
+        $currentServer = $this->addressHandler->generateRemoteURL();
248
+        if (Helper::isSameUserOnSameServer($owner, $remote, $currentUser, $currentServer)) {
249
+            return new JSONResponse(['message' => $this->l->t('Not allowed to create a federated share with the owner.')], Http::STATUS_BAD_REQUEST);
250
+        }
251
+        $discoveryManager = new DiscoveryManager(
252
+            \OC::$server->getMemCacheFactory(),
253
+            \OC::$server->getHTTPClientService()
254
+        );
255
+        $externalManager = new Manager(
256
+            \OC::$server->getDatabaseConnection(),
257
+            Filesystem::getMountManager(),
258
+            Filesystem::getLoader(),
259
+            \OC::$server->getHTTPClientService(),
260
+            \OC::$server->getNotificationManager(),
261
+            $discoveryManager,
262
+            \OC::$server->getUserSession()->getUser()->getUID()
263
+        );
264
+
265
+        // check for ssl cert
266
+
267
+        if (strpos($remote, 'https') === 0) {
268
+            try {
269
+                $client = $this->clientService->newClient();
270
+                $client->get($remote, [
271
+                    'timeout' => 10,
272
+                    'connect_timeout' => 10,
273
+                ])->getBody();
274
+            } catch (\Exception $e) {
275
+                return new JSONResponse(['message' => $this->l->t('Invalid or untrusted SSL certificate')], Http::STATUS_BAD_REQUEST);
276
+            }
277
+        }
278
+        $mount = $externalManager->addShare($remote, $token, $password, $name, $ownerDisplayName, true);
279
+        /**
280
+         * @var \OCA\Files_Sharing\External\Storage $storage
281
+         */
282
+        $storage = $mount->getStorage();
283
+        try {
284
+            // check if storage exists
285
+            $storage->checkStorageAvailability();
286
+        } catch (StorageInvalidException $e) {
287
+            // note: checkStorageAvailability will already remove the invalid share
288
+            Util::writeLog(
289
+                'federatedfilesharing',
290
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
291
+                Util::DEBUG
292
+            );
293
+            return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
294
+        } catch (\Exception $e) {
295
+            Util::writeLog(
296
+                'federatedfilesharing',
297
+                'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
298
+                Util::DEBUG
299
+            );
300
+            $externalManager->removeShare($mount->getMountPoint());
301
+            return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
302
+        }
303
+        $result = $storage->file_exists('');
304
+        if ($result) {
305
+            try {
306
+                $storage->getScanner()->scanAll();
307
+                return new JSONResponse(
308
+                    [
309
+                        'message' => $this->l->t('Federated Share successfully added'),
310
+                        'legacyMount' => '1'
311
+                    ]
312
+                );
313
+            } catch (StorageInvalidException $e) {
314
+                Util::writeLog(
315
+                    'federatedfilesharing',
316
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
317
+                    Util::DEBUG
318
+                );
319
+                return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
320
+            } catch (\Exception $e) {
321
+                Util::writeLog(
322
+                    'federatedfilesharing',
323
+                    'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
324
+                    Util::DEBUG
325
+                );
326
+                return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
327
+            }
328
+        } else {
329
+            $externalManager->removeShare($mount->getMountPoint());
330
+            Util::writeLog(
331
+                'federatedfilesharing',
332
+                'Couldn\'t add remote share',
333
+                Util::DEBUG
334
+            );
335
+            return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
336
+        }
337
+
338
+    }
339 339
 
340 340
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 		$storedPassword = $share->getPassword();
148 148
 		$authenticated = $this->session->get('public_link_authenticated') === $share->getId() ||
149 149
 			$this->shareManager->checkPassword($share, $password);
150
-		if (!empty($storedPassword) && !$authenticated ) {
150
+		if (!empty($storedPassword) && !$authenticated) {
151 151
 			return new JSONResponse(
152 152
 				['message' => 'No permission to access the share'],
153 153
 				Http::STATUS_BAD_REQUEST
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		$httpClient = $this->clientService->newClient();
190 190
 
191 191
 		try {
192
-			$response = $httpClient->post($remote . '/index.php/apps/federatedfilesharing/createFederatedShare',
192
+			$response = $httpClient->post($remote.'/index.php/apps/federatedfilesharing/createFederatedShare',
193 193
 				[
194 194
 					'body' =>
195 195
 						[
@@ -287,14 +287,14 @@  discard block
 block discarded – undo
287 287
 			// note: checkStorageAvailability will already remove the invalid share
288 288
 			Util::writeLog(
289 289
 				'federatedfilesharing',
290
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
290
+				'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
291 291
 				Util::DEBUG
292 292
 			);
293 293
 			return new JSONResponse(['message' => $this->l->t('Could not authenticate to remote share, password might be wrong')], Http::STATUS_BAD_REQUEST);
294 294
 		} catch (\Exception $e) {
295 295
 			Util::writeLog(
296 296
 				'federatedfilesharing',
297
-				'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
297
+				'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
298 298
 				Util::DEBUG
299 299
 			);
300 300
 			$externalManager->removeShare($mount->getMountPoint());
@@ -313,14 +313,14 @@  discard block
 block discarded – undo
313 313
 			} catch (StorageInvalidException $e) {
314 314
 				Util::writeLog(
315 315
 					'federatedfilesharing',
316
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
316
+					'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
317 317
 					Util::DEBUG
318 318
 				);
319 319
 				return new JSONResponse(['message' => $this->l->t('Storage not valid')], Http::STATUS_BAD_REQUEST);
320 320
 			} catch (\Exception $e) {
321 321
 				Util::writeLog(
322 322
 					'federatedfilesharing',
323
-					'Invalid remote storage: ' . get_class($e) . ': ' . $e->getMessage(),
323
+					'Invalid remote storage: '.get_class($e).': '.$e->getMessage(),
324 324
 					Util::DEBUG
325 325
 				);
326 326
 				return new JSONResponse(['message' => $this->l->t('Couldn\'t add remote share')], Http::STATUS_BAD_REQUEST);
Please login to merge, or discard this patch.