Completed
Pull Request — master (#9345)
by Björn
99:07 queued 63:01
created
apps/files_sharing/lib/External/Manager.php 3 patches
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -131,18 +131,18 @@  discard block
 block discarded – undo
131 131
 	 * @param int $remoteId
132 132
 	 * @return Mount|null
133 133
 	 */
134
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
134
+	public function addShare($remote, $token, $password, $name, $owner, $accepted = false, $user = null, $remoteId = -1) {
135 135
 
136 136
 		$user = $user ? $user : $this->uid;
137 137
 		$accepted = $accepted ? 1 : 0;
138
-		$name = Filesystem::normalizePath('/' . $name);
138
+		$name = Filesystem::normalizePath('/'.$name);
139 139
 
140 140
 		if (!$accepted) {
141 141
 			// To avoid conflicts with the mount point generation later,
142 142
 			// we only use a temporary mount point name here. The real
143 143
 			// mount point name will be generated when accepting the share,
144 144
 			// using the original share item name.
145
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
145
+			$tmpMountPointName = '{{TemporaryMountPointName#'.$name.'}}';
146 146
 			$mountPoint = $tmpMountPointName;
147 147
 			$hash = md5($tmpMountPointName);
148 148
 			$data = [
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 			$i = 1;
162 162
 			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163 163
 				// The external share already exists for the user
164
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
164
+				$data['mountpoint'] = $tmpMountPointName.'-'.$i;
165 165
 				$data['mountpoint_hash'] = md5($data['mountpoint']);
166 166
 				$i++;
167 167
 			}
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 		}
170 170
 
171 171
 		$mountPoint = Files::buildNotExistingFileName('/', $name);
172
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
172
+		$mountPoint = Filesystem::normalizePath('/'.$mountPoint);
173 173
 		$hash = md5($mountPoint);
174 174
 
175 175
 		$query = $this->connection->prepare('
@@ -290,14 +290,14 @@  discard block
 block discarded – undo
290 290
 
291 291
 		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
292 292
 
293
-		if($result === true) {
293
+		if ($result === true) {
294 294
 			return true;
295 295
 		}
296 296
 
297 297
 		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
298 298
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
299 299
 
300
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
300
+		$url = rtrim($remote, '/').$endpoint.'/'.$remoteId.'/'.$feedback.'?format='.\OCP\Share::RESPONSE_FORMAT;
301 301
 		$fields = array('token' => $token);
302 302
 
303 303
 		$client = $this->clientService->newClient();
@@ -354,13 +354,13 @@  discard block
 block discarded – undo
354 354
 	 * @return string
355 355
 	 */
356 356
 	protected function stripPath($path) {
357
-		$prefix = '/' . $this->uid . '/files';
357
+		$prefix = '/'.$this->uid.'/files';
358 358
 		return rtrim(substr($path, strlen($prefix)), '/');
359 359
 	}
360 360
 
361 361
 	public function getMount($data) {
362 362
 		$data['manager'] = $this;
363
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
363
+		$mountPoint = '/'.$this->uid.'/files'.$data['mountpoint'];
364 364
 		$data['mountpoint'] = $mountPoint;
365 365
 		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
366 366
 		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 			WHERE `mountpoint_hash` = ?
401 401
 			AND `user` = ?
402 402
 		');
403
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
403
+		$result = (bool) $query->execute(array($target, $targetHash, $sourceHash, $this->uid));
404 404
 
405 405
 		return $result;
406 406
 	}
@@ -435,9 +435,9 @@  discard block
 block discarded – undo
435 435
 			WHERE `mountpoint_hash` = ?
436 436
 			AND `user` = ?
437 437
 		');
438
-		$result = (bool)$query->execute(array($hash, $this->uid));
438
+		$result = (bool) $query->execute(array($hash, $this->uid));
439 439
 
440
-		if($result) {
440
+		if ($result) {
441 441
 			$this->removeReShares($id);
442 442
 		}
443 443
 
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
 
459 459
 
460 460
 		$query->delete('federated_reshares')
461
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
461
+			->where($query->expr()->in('share_id', $query->createFunction('('.$select.')')));
462 462
 		$query->execute();
463 463
 
464 464
 		$deleteReShares = $this->connection->getQueryBuilder();
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 
483 483
 		if ($result) {
484 484
 			$shares = $getShare->fetchAll();
485
-			foreach($shares as $share) {
485
+			foreach ($shares as $share) {
486 486
 				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
487 487
 			}
488 488
 		}
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
 			DELETE FROM `*PREFIX*share_external`
492 492
 			WHERE `user` = ?
493 493
 		');
494
-		return (bool)$query->execute(array($uid));
494
+		return (bool) $query->execute(array($uid));
495 495
 	}
496 496
 
497 497
 	/**
Please login to merge, or discard this patch.
Doc Comments   +4 added lines, -1 removed lines patch added patch discarded remove patch
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 	 *
325 325
 	 * @param string $remoteDomain
326 326
 	 * @param string $token
327
-	 * @param $remoteId id of the share
327
+	 * @param integer $remoteId id of the share
328 328
 	 * @param string $feedback
329 329
 	 * @return bool
330 330
 	 */
@@ -421,6 +421,9 @@  discard block
 block discarded – undo
421 421
 		return $result;
422 422
 	}
423 423
 
424
+	/**
425
+	 * @param string $mountPoint
426
+	 */
424 427
 	public function removeShare($mountPoint) {
425 428
 
426 429
 		$mountPointObj = $this->mountManager->find($mountPoint);
Please login to merge, or discard this patch.
Indentation   +468 added lines, -468 removed lines patch added patch discarded remove patch
@@ -44,512 +44,512 @@
 block discarded – undo
44 44
 use OCP\Share;
45 45
 
46 46
 class Manager {
47
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $uid;
53
-
54
-	/**
55
-	 * @var IDBConnection
56
-	 */
57
-	private $connection;
58
-
59
-	/**
60
-	 * @var \OC\Files\Mount\Manager
61
-	 */
62
-	private $mountManager;
63
-
64
-	/**
65
-	 * @var IStorageFactory
66
-	 */
67
-	private $storageLoader;
68
-
69
-	/**
70
-	 * @var IClientService
71
-	 */
72
-	private $clientService;
73
-
74
-	/**
75
-	 * @var IManager
76
-	 */
77
-	private $notificationManager;
78
-
79
-	/**
80
-	 * @var IDiscoveryService
81
-	 */
82
-	private $discoveryService;
83
-
84
-	/** @var ICloudFederationProviderManager */
85
-	private $cloudFederationProviderManager;
86
-
87
-	/** @var ICloudFederationFactory */
88
-	private $cloudFederationFactory;
89
-
90
-	/**
91
-	 * @param IDBConnection $connection
92
-	 * @param \OC\Files\Mount\Manager $mountManager
93
-	 * @param IStorageFactory $storageLoader
94
-	 * @param IClientService $clientService
95
-	 * @param IManager $notificationManager
96
-	 * @param IDiscoveryService $discoveryService
97
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
-	 * @param ICloudFederationFactory $cloudFederationFactory
99
-	 * @param string $uid
100
-	 */
101
-	public function __construct(IDBConnection $connection,
102
-								\OC\Files\Mount\Manager $mountManager,
103
-								IStorageFactory $storageLoader,
104
-								IClientService $clientService,
105
-								IManager $notificationManager,
106
-								IDiscoveryService $discoveryService,
107
-								ICloudFederationProviderManager $cloudFederationProviderManager,
108
-								ICloudFederationFactory $cloudFederationFactory,
109
-								$uid) {
110
-		$this->connection = $connection;
111
-		$this->mountManager = $mountManager;
112
-		$this->storageLoader = $storageLoader;
113
-		$this->clientService = $clientService;
114
-		$this->uid = $uid;
115
-		$this->notificationManager = $notificationManager;
116
-		$this->discoveryService = $discoveryService;
117
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
-		$this->cloudFederationFactory = $cloudFederationFactory;
119
-	}
120
-
121
-	/**
122
-	 * add new server-to-server share
123
-	 *
124
-	 * @param string $remote
125
-	 * @param string $token
126
-	 * @param string $password
127
-	 * @param string $name
128
-	 * @param string $owner
129
-	 * @param boolean $accepted
130
-	 * @param string $user
131
-	 * @param int $remoteId
132
-	 * @return Mount|null
133
-	 */
134
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
135
-
136
-		$user = $user ? $user : $this->uid;
137
-		$accepted = $accepted ? 1 : 0;
138
-		$name = Filesystem::normalizePath('/' . $name);
139
-
140
-		if (!$accepted) {
141
-			// To avoid conflicts with the mount point generation later,
142
-			// we only use a temporary mount point name here. The real
143
-			// mount point name will be generated when accepting the share,
144
-			// using the original share item name.
145
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
146
-			$mountPoint = $tmpMountPointName;
147
-			$hash = md5($tmpMountPointName);
148
-			$data = [
149
-				'remote'		=> $remote,
150
-				'share_token'	=> $token,
151
-				'password'		=> $password,
152
-				'name'			=> $name,
153
-				'owner'			=> $owner,
154
-				'user'			=> $user,
155
-				'mountpoint'	=> $mountPoint,
156
-				'mountpoint_hash'	=> $hash,
157
-				'accepted'		=> $accepted,
158
-				'remote_id'		=> $remoteId,
159
-			];
160
-
161
-			$i = 1;
162
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163
-				// The external share already exists for the user
164
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
165
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
166
-				$i++;
167
-			}
168
-			return null;
169
-		}
170
-
171
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
172
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
173
-		$hash = md5($mountPoint);
174
-
175
-		$query = $this->connection->prepare('
47
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $uid;
53
+
54
+    /**
55
+     * @var IDBConnection
56
+     */
57
+    private $connection;
58
+
59
+    /**
60
+     * @var \OC\Files\Mount\Manager
61
+     */
62
+    private $mountManager;
63
+
64
+    /**
65
+     * @var IStorageFactory
66
+     */
67
+    private $storageLoader;
68
+
69
+    /**
70
+     * @var IClientService
71
+     */
72
+    private $clientService;
73
+
74
+    /**
75
+     * @var IManager
76
+     */
77
+    private $notificationManager;
78
+
79
+    /**
80
+     * @var IDiscoveryService
81
+     */
82
+    private $discoveryService;
83
+
84
+    /** @var ICloudFederationProviderManager */
85
+    private $cloudFederationProviderManager;
86
+
87
+    /** @var ICloudFederationFactory */
88
+    private $cloudFederationFactory;
89
+
90
+    /**
91
+     * @param IDBConnection $connection
92
+     * @param \OC\Files\Mount\Manager $mountManager
93
+     * @param IStorageFactory $storageLoader
94
+     * @param IClientService $clientService
95
+     * @param IManager $notificationManager
96
+     * @param IDiscoveryService $discoveryService
97
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
+     * @param ICloudFederationFactory $cloudFederationFactory
99
+     * @param string $uid
100
+     */
101
+    public function __construct(IDBConnection $connection,
102
+                                \OC\Files\Mount\Manager $mountManager,
103
+                                IStorageFactory $storageLoader,
104
+                                IClientService $clientService,
105
+                                IManager $notificationManager,
106
+                                IDiscoveryService $discoveryService,
107
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
108
+                                ICloudFederationFactory $cloudFederationFactory,
109
+                                $uid) {
110
+        $this->connection = $connection;
111
+        $this->mountManager = $mountManager;
112
+        $this->storageLoader = $storageLoader;
113
+        $this->clientService = $clientService;
114
+        $this->uid = $uid;
115
+        $this->notificationManager = $notificationManager;
116
+        $this->discoveryService = $discoveryService;
117
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
+        $this->cloudFederationFactory = $cloudFederationFactory;
119
+    }
120
+
121
+    /**
122
+     * add new server-to-server share
123
+     *
124
+     * @param string $remote
125
+     * @param string $token
126
+     * @param string $password
127
+     * @param string $name
128
+     * @param string $owner
129
+     * @param boolean $accepted
130
+     * @param string $user
131
+     * @param int $remoteId
132
+     * @return Mount|null
133
+     */
134
+    public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
135
+
136
+        $user = $user ? $user : $this->uid;
137
+        $accepted = $accepted ? 1 : 0;
138
+        $name = Filesystem::normalizePath('/' . $name);
139
+
140
+        if (!$accepted) {
141
+            // To avoid conflicts with the mount point generation later,
142
+            // we only use a temporary mount point name here. The real
143
+            // mount point name will be generated when accepting the share,
144
+            // using the original share item name.
145
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
146
+            $mountPoint = $tmpMountPointName;
147
+            $hash = md5($tmpMountPointName);
148
+            $data = [
149
+                'remote'		=> $remote,
150
+                'share_token'	=> $token,
151
+                'password'		=> $password,
152
+                'name'			=> $name,
153
+                'owner'			=> $owner,
154
+                'user'			=> $user,
155
+                'mountpoint'	=> $mountPoint,
156
+                'mountpoint_hash'	=> $hash,
157
+                'accepted'		=> $accepted,
158
+                'remote_id'		=> $remoteId,
159
+            ];
160
+
161
+            $i = 1;
162
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163
+                // The external share already exists for the user
164
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
165
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
166
+                $i++;
167
+            }
168
+            return null;
169
+        }
170
+
171
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
172
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
173
+        $hash = md5($mountPoint);
174
+
175
+        $query = $this->connection->prepare('
176 176
 				INSERT INTO `*PREFIX*share_external`
177 177
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`)
178 178
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
179 179
 			');
180
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
181
-
182
-		$options = array(
183
-			'remote'	=> $remote,
184
-			'token'		=> $token,
185
-			'password'	=> $password,
186
-			'mountpoint'	=> $mountPoint,
187
-			'owner'		=> $owner
188
-		);
189
-		return $this->mountShare($options);
190
-	}
191
-
192
-	/**
193
-	 * get share
194
-	 *
195
-	 * @param int $id share id
196
-	 * @return mixed share of false
197
-	 */
198
-	public function getShare($id) {
199
-		$getShare = $this->connection->prepare('
180
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
181
+
182
+        $options = array(
183
+            'remote'	=> $remote,
184
+            'token'		=> $token,
185
+            'password'	=> $password,
186
+            'mountpoint'	=> $mountPoint,
187
+            'owner'		=> $owner
188
+        );
189
+        return $this->mountShare($options);
190
+    }
191
+
192
+    /**
193
+     * get share
194
+     *
195
+     * @param int $id share id
196
+     * @return mixed share of false
197
+     */
198
+    public function getShare($id) {
199
+        $getShare = $this->connection->prepare('
200 200
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
201 201
 			FROM  `*PREFIX*share_external`
202 202
 			WHERE `id` = ? AND `user` = ?');
203
-		$result = $getShare->execute(array($id, $this->uid));
204
-
205
-		return $result ? $getShare->fetch() : false;
206
-	}
207
-
208
-	/**
209
-	 * accept server-to-server share
210
-	 *
211
-	 * @param int $id
212
-	 * @return bool True if the share could be accepted, false otherwise
213
-	 */
214
-	public function acceptShare($id) {
215
-
216
-		$share = $this->getShare($id);
217
-		$result = false;
218
-
219
-		if ($share) {
220
-			\OC_Util::setupFS($this->uid);
221
-			$shareFolder = Helper::getShareFolder();
222
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
223
-			$mountPoint = Filesystem::normalizePath($mountPoint);
224
-			$hash = md5($mountPoint);
225
-
226
-			$acceptShare = $this->connection->prepare('
203
+        $result = $getShare->execute(array($id, $this->uid));
204
+
205
+        return $result ? $getShare->fetch() : false;
206
+    }
207
+
208
+    /**
209
+     * accept server-to-server share
210
+     *
211
+     * @param int $id
212
+     * @return bool True if the share could be accepted, false otherwise
213
+     */
214
+    public function acceptShare($id) {
215
+
216
+        $share = $this->getShare($id);
217
+        $result = false;
218
+
219
+        if ($share) {
220
+            \OC_Util::setupFS($this->uid);
221
+            $shareFolder = Helper::getShareFolder();
222
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
223
+            $mountPoint = Filesystem::normalizePath($mountPoint);
224
+            $hash = md5($mountPoint);
225
+
226
+            $acceptShare = $this->connection->prepare('
227 227
 				UPDATE `*PREFIX*share_external`
228 228
 				SET `accepted` = ?,
229 229
 					`mountpoint` = ?,
230 230
 					`mountpoint_hash` = ?
231 231
 				WHERE `id` = ? AND `user` = ?');
232
-			$updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
233
-			if ($updated === true) {
234
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
235
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
236
-				$result = true;
237
-			}
238
-		}
239
-
240
-		// Make sure the user has no notification for something that does not exist anymore.
241
-		$this->processNotification($id);
242
-
243
-		return $result;
244
-	}
245
-
246
-	/**
247
-	 * decline server-to-server share
248
-	 *
249
-	 * @param int $id
250
-	 * @return bool True if the share could be declined, false otherwise
251
-	 */
252
-	public function declineShare($id) {
253
-
254
-		$share = $this->getShare($id);
255
-
256
-		if ($share) {
257
-			$removeShare = $this->connection->prepare('
232
+            $updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
233
+            if ($updated === true) {
234
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
235
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
236
+                $result = true;
237
+            }
238
+        }
239
+
240
+        // Make sure the user has no notification for something that does not exist anymore.
241
+        $this->processNotification($id);
242
+
243
+        return $result;
244
+    }
245
+
246
+    /**
247
+     * decline server-to-server share
248
+     *
249
+     * @param int $id
250
+     * @return bool True if the share could be declined, false otherwise
251
+     */
252
+    public function declineShare($id) {
253
+
254
+        $share = $this->getShare($id);
255
+
256
+        if ($share) {
257
+            $removeShare = $this->connection->prepare('
258 258
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
259
-			$removeShare->execute(array($id, $this->uid));
260
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
261
-
262
-			$this->processNotification($id);
263
-			return true;
264
-		}
265
-
266
-		return false;
267
-	}
268
-
269
-	/**
270
-	 * @param int $remoteShare
271
-	 */
272
-	public function processNotification($remoteShare) {
273
-		$filter = $this->notificationManager->createNotification();
274
-		$filter->setApp('files_sharing')
275
-			->setUser($this->uid)
276
-			->setObject('remote_share', (int) $remoteShare);
277
-		$this->notificationManager->markProcessed($filter);
278
-	}
279
-
280
-	/**
281
-	 * inform remote server whether server-to-server share was accepted/declined
282
-	 *
283
-	 * @param string $remote
284
-	 * @param string $token
285
-	 * @param int $remoteId Share id on the remote host
286
-	 * @param string $feedback
287
-	 * @return boolean
288
-	 */
289
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
290
-
291
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
292
-
293
-		if($result === true) {
294
-			return true;
295
-		}
296
-
297
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
298
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
299
-
300
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
301
-		$fields = array('token' => $token);
302
-
303
-		$client = $this->clientService->newClient();
304
-
305
-		try {
306
-			$response = $client->post(
307
-				$url,
308
-				[
309
-					'body' => $fields,
310
-					'connect_timeout' => 10,
311
-				]
312
-			);
313
-		} catch (\Exception $e) {
314
-			return false;
315
-		}
316
-
317
-		$status = json_decode($response->getBody(), true);
318
-
319
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
320
-	}
321
-
322
-	/**
323
-	 * try send accept message to ocm end-point
324
-	 *
325
-	 * @param string $remoteDomain
326
-	 * @param string $token
327
-	 * @param $remoteId id of the share
328
-	 * @param string $feedback
329
-	 * @return bool
330
-	 */
331
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
332
-		switch ($feedback) {
333
-			case 'accept':
334
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
335
-				$notification->setMessage(
336
-					'SHARE_ACCEPTED',
337
-					'file',
338
-					$remoteId,
339
-					[
340
-						'sharedSecret' => $token,
341
-						'message' => 'Recipient accept the share'
342
-					]
343
-
344
-				);
345
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
346
-			case 'decline':
347
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
348
-				$notification->setMessage(
349
-					'SHARE_DECLINED',
350
-					'file',
351
-					$remoteId,
352
-					[
353
-						'sharedSecret' => $token,
354
-						'message' => 'Recipient declined the share'
355
-					]
356
-
357
-				);
358
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
359
-		}
360
-
361
-		return false;
362
-
363
-	}
364
-
365
-
366
-	/**
367
-	 * remove '/user/files' from the path and trailing slashes
368
-	 *
369
-	 * @param string $path
370
-	 * @return string
371
-	 */
372
-	protected function stripPath($path) {
373
-		$prefix = '/' . $this->uid . '/files';
374
-		return rtrim(substr($path, strlen($prefix)), '/');
375
-	}
376
-
377
-	public function getMount($data) {
378
-		$data['manager'] = $this;
379
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
380
-		$data['mountpoint'] = $mountPoint;
381
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
382
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
383
-	}
384
-
385
-	/**
386
-	 * @param array $data
387
-	 * @return Mount
388
-	 */
389
-	protected function mountShare($data) {
390
-		$mount = $this->getMount($data);
391
-		$this->mountManager->addMount($mount);
392
-		return $mount;
393
-	}
394
-
395
-	/**
396
-	 * @return \OC\Files\Mount\Manager
397
-	 */
398
-	public function getMountManager() {
399
-		return $this->mountManager;
400
-	}
401
-
402
-	/**
403
-	 * @param string $source
404
-	 * @param string $target
405
-	 * @return bool
406
-	 */
407
-	public function setMountPoint($source, $target) {
408
-		$source = $this->stripPath($source);
409
-		$target = $this->stripPath($target);
410
-		$sourceHash = md5($source);
411
-		$targetHash = md5($target);
412
-
413
-		$query = $this->connection->prepare('
259
+            $removeShare->execute(array($id, $this->uid));
260
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
261
+
262
+            $this->processNotification($id);
263
+            return true;
264
+        }
265
+
266
+        return false;
267
+    }
268
+
269
+    /**
270
+     * @param int $remoteShare
271
+     */
272
+    public function processNotification($remoteShare) {
273
+        $filter = $this->notificationManager->createNotification();
274
+        $filter->setApp('files_sharing')
275
+            ->setUser($this->uid)
276
+            ->setObject('remote_share', (int) $remoteShare);
277
+        $this->notificationManager->markProcessed($filter);
278
+    }
279
+
280
+    /**
281
+     * inform remote server whether server-to-server share was accepted/declined
282
+     *
283
+     * @param string $remote
284
+     * @param string $token
285
+     * @param int $remoteId Share id on the remote host
286
+     * @param string $feedback
287
+     * @return boolean
288
+     */
289
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
290
+
291
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
292
+
293
+        if($result === true) {
294
+            return true;
295
+        }
296
+
297
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
298
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
299
+
300
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
301
+        $fields = array('token' => $token);
302
+
303
+        $client = $this->clientService->newClient();
304
+
305
+        try {
306
+            $response = $client->post(
307
+                $url,
308
+                [
309
+                    'body' => $fields,
310
+                    'connect_timeout' => 10,
311
+                ]
312
+            );
313
+        } catch (\Exception $e) {
314
+            return false;
315
+        }
316
+
317
+        $status = json_decode($response->getBody(), true);
318
+
319
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
320
+    }
321
+
322
+    /**
323
+     * try send accept message to ocm end-point
324
+     *
325
+     * @param string $remoteDomain
326
+     * @param string $token
327
+     * @param $remoteId id of the share
328
+     * @param string $feedback
329
+     * @return bool
330
+     */
331
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
332
+        switch ($feedback) {
333
+            case 'accept':
334
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
335
+                $notification->setMessage(
336
+                    'SHARE_ACCEPTED',
337
+                    'file',
338
+                    $remoteId,
339
+                    [
340
+                        'sharedSecret' => $token,
341
+                        'message' => 'Recipient accept the share'
342
+                    ]
343
+
344
+                );
345
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
346
+            case 'decline':
347
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
348
+                $notification->setMessage(
349
+                    'SHARE_DECLINED',
350
+                    'file',
351
+                    $remoteId,
352
+                    [
353
+                        'sharedSecret' => $token,
354
+                        'message' => 'Recipient declined the share'
355
+                    ]
356
+
357
+                );
358
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
359
+        }
360
+
361
+        return false;
362
+
363
+    }
364
+
365
+
366
+    /**
367
+     * remove '/user/files' from the path and trailing slashes
368
+     *
369
+     * @param string $path
370
+     * @return string
371
+     */
372
+    protected function stripPath($path) {
373
+        $prefix = '/' . $this->uid . '/files';
374
+        return rtrim(substr($path, strlen($prefix)), '/');
375
+    }
376
+
377
+    public function getMount($data) {
378
+        $data['manager'] = $this;
379
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
380
+        $data['mountpoint'] = $mountPoint;
381
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
382
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
383
+    }
384
+
385
+    /**
386
+     * @param array $data
387
+     * @return Mount
388
+     */
389
+    protected function mountShare($data) {
390
+        $mount = $this->getMount($data);
391
+        $this->mountManager->addMount($mount);
392
+        return $mount;
393
+    }
394
+
395
+    /**
396
+     * @return \OC\Files\Mount\Manager
397
+     */
398
+    public function getMountManager() {
399
+        return $this->mountManager;
400
+    }
401
+
402
+    /**
403
+     * @param string $source
404
+     * @param string $target
405
+     * @return bool
406
+     */
407
+    public function setMountPoint($source, $target) {
408
+        $source = $this->stripPath($source);
409
+        $target = $this->stripPath($target);
410
+        $sourceHash = md5($source);
411
+        $targetHash = md5($target);
412
+
413
+        $query = $this->connection->prepare('
414 414
 			UPDATE `*PREFIX*share_external`
415 415
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
416 416
 			WHERE `mountpoint_hash` = ?
417 417
 			AND `user` = ?
418 418
 		');
419
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
419
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
420 420
 
421
-		return $result;
422
-	}
421
+        return $result;
422
+    }
423 423
 
424
-	public function removeShare($mountPoint) {
424
+    public function removeShare($mountPoint) {
425 425
 
426
-		$mountPointObj = $this->mountManager->find($mountPoint);
427
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
426
+        $mountPointObj = $this->mountManager->find($mountPoint);
427
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
428 428
 
429
-		$mountPoint = $this->stripPath($mountPoint);
430
-		$hash = md5($mountPoint);
429
+        $mountPoint = $this->stripPath($mountPoint);
430
+        $hash = md5($mountPoint);
431 431
 
432
-		$getShare = $this->connection->prepare('
432
+        $getShare = $this->connection->prepare('
433 433
 			SELECT `remote`, `share_token`, `remote_id`
434 434
 			FROM  `*PREFIX*share_external`
435 435
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
436
-		$result = $getShare->execute(array($hash, $this->uid));
437
-
438
-		if ($result) {
439
-			try {
440
-				$share = $getShare->fetch();
441
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
442
-			} catch (\Exception $e) {
443
-				// if we fail to notify the remote (probably cause the remote is down)
444
-				// we still want the share to be gone to prevent undeletable remotes
445
-			}
446
-		}
447
-		$getShare->closeCursor();
448
-
449
-		$query = $this->connection->prepare('
436
+        $result = $getShare->execute(array($hash, $this->uid));
437
+
438
+        if ($result) {
439
+            try {
440
+                $share = $getShare->fetch();
441
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
442
+            } catch (\Exception $e) {
443
+                // if we fail to notify the remote (probably cause the remote is down)
444
+                // we still want the share to be gone to prevent undeletable remotes
445
+            }
446
+        }
447
+        $getShare->closeCursor();
448
+
449
+        $query = $this->connection->prepare('
450 450
 			DELETE FROM `*PREFIX*share_external`
451 451
 			WHERE `mountpoint_hash` = ?
452 452
 			AND `user` = ?
453 453
 		');
454
-		$result = (bool)$query->execute(array($hash, $this->uid));
455
-
456
-		if($result) {
457
-			$this->removeReShares($id);
458
-		}
459
-
460
-		return $result;
461
-	}
462
-
463
-	/**
464
-	 * remove re-shares from share table and mapping in the federated_reshares table
465
-	 *
466
-	 * @param $mountPointId
467
-	 */
468
-	protected function removeReShares($mountPointId) {
469
-		$selectQuery = $this->connection->getQueryBuilder();
470
-		$query = $this->connection->getQueryBuilder();
471
-		$selectQuery->select('id')->from('share')
472
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
473
-		$select = $selectQuery->getSQL();
474
-
475
-
476
-		$query->delete('federated_reshares')
477
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
478
-		$query->execute();
479
-
480
-		$deleteReShares = $this->connection->getQueryBuilder();
481
-		$deleteReShares->delete('share')
482
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
483
-		$deleteReShares->execute();
484
-	}
485
-
486
-	/**
487
-	 * remove all shares for user $uid if the user was deleted
488
-	 *
489
-	 * @param string $uid
490
-	 * @return bool
491
-	 */
492
-	public function removeUserShares($uid) {
493
-		$getShare = $this->connection->prepare('
454
+        $result = (bool)$query->execute(array($hash, $this->uid));
455
+
456
+        if($result) {
457
+            $this->removeReShares($id);
458
+        }
459
+
460
+        return $result;
461
+    }
462
+
463
+    /**
464
+     * remove re-shares from share table and mapping in the federated_reshares table
465
+     *
466
+     * @param $mountPointId
467
+     */
468
+    protected function removeReShares($mountPointId) {
469
+        $selectQuery = $this->connection->getQueryBuilder();
470
+        $query = $this->connection->getQueryBuilder();
471
+        $selectQuery->select('id')->from('share')
472
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
473
+        $select = $selectQuery->getSQL();
474
+
475
+
476
+        $query->delete('federated_reshares')
477
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
478
+        $query->execute();
479
+
480
+        $deleteReShares = $this->connection->getQueryBuilder();
481
+        $deleteReShares->delete('share')
482
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
483
+        $deleteReShares->execute();
484
+    }
485
+
486
+    /**
487
+     * remove all shares for user $uid if the user was deleted
488
+     *
489
+     * @param string $uid
490
+     * @return bool
491
+     */
492
+    public function removeUserShares($uid) {
493
+        $getShare = $this->connection->prepare('
494 494
 			SELECT `remote`, `share_token`, `remote_id`
495 495
 			FROM  `*PREFIX*share_external`
496 496
 			WHERE `user` = ?');
497
-		$result = $getShare->execute(array($uid));
497
+        $result = $getShare->execute(array($uid));
498 498
 
499
-		if ($result) {
500
-			$shares = $getShare->fetchAll();
501
-			foreach($shares as $share) {
502
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
503
-			}
504
-		}
499
+        if ($result) {
500
+            $shares = $getShare->fetchAll();
501
+            foreach($shares as $share) {
502
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
503
+            }
504
+        }
505 505
 
506
-		$query = $this->connection->prepare('
506
+        $query = $this->connection->prepare('
507 507
 			DELETE FROM `*PREFIX*share_external`
508 508
 			WHERE `user` = ?
509 509
 		');
510
-		return (bool)$query->execute(array($uid));
511
-	}
512
-
513
-	/**
514
-	 * return a list of shares which are not yet accepted by the user
515
-	 *
516
-	 * @return array list of open server-to-server shares
517
-	 */
518
-	public function getOpenShares() {
519
-		return $this->getShares(false);
520
-	}
521
-
522
-	/**
523
-	 * return a list of shares which are accepted by the user
524
-	 *
525
-	 * @return array list of accepted server-to-server shares
526
-	 */
527
-	public function getAcceptedShares() {
528
-		return $this->getShares(true);
529
-	}
530
-
531
-	/**
532
-	 * return a list of shares for the user
533
-	 *
534
-	 * @param bool|null $accepted True for accepted only,
535
-	 *                            false for not accepted,
536
-	 *                            null for all shares of the user
537
-	 * @return array list of open server-to-server shares
538
-	 */
539
-	private function getShares($accepted) {
540
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
510
+        return (bool)$query->execute(array($uid));
511
+    }
512
+
513
+    /**
514
+     * return a list of shares which are not yet accepted by the user
515
+     *
516
+     * @return array list of open server-to-server shares
517
+     */
518
+    public function getOpenShares() {
519
+        return $this->getShares(false);
520
+    }
521
+
522
+    /**
523
+     * return a list of shares which are accepted by the user
524
+     *
525
+     * @return array list of accepted server-to-server shares
526
+     */
527
+    public function getAcceptedShares() {
528
+        return $this->getShares(true);
529
+    }
530
+
531
+    /**
532
+     * return a list of shares for the user
533
+     *
534
+     * @param bool|null $accepted True for accepted only,
535
+     *                            false for not accepted,
536
+     *                            null for all shares of the user
537
+     * @return array list of open server-to-server shares
538
+     */
539
+    private function getShares($accepted) {
540
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
541 541
 		          FROM `*PREFIX*share_external` 
542 542
 				  WHERE `user` = ?';
543
-		$parameters = [$this->uid];
544
-		if (!is_null($accepted)) {
545
-			$query .= ' AND `accepted` = ?';
546
-			$parameters[] = (int) $accepted;
547
-		}
548
-		$query .= ' ORDER BY `id` ASC';
549
-
550
-		$shares = $this->connection->prepare($query);
551
-		$result = $shares->execute($parameters);
552
-
553
-		return $result ? $shares->fetchAll() : [];
554
-	}
543
+        $parameters = [$this->uid];
544
+        if (!is_null($accepted)) {
545
+            $query .= ' AND `accepted` = ?';
546
+            $parameters[] = (int) $accepted;
547
+        }
548
+        $query .= ' ORDER BY `id` ASC';
549
+
550
+        $shares = $this->connection->prepare($query);
551
+        $result = $shares->execute($parameters);
552
+
553
+        return $result ? $shares->fetchAll() : [];
554
+    }
555 555
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/AppInfo/Application.php 1 patch
Indentation   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -45,136 +45,136 @@
 block discarded – undo
45 45
 use OCA\Files_Sharing\External\Manager;
46 46
 
47 47
 class Application extends App {
48
-	public function __construct(array $urlParams = array()) {
49
-		parent::__construct('files_sharing', $urlParams);
48
+    public function __construct(array $urlParams = array()) {
49
+        parent::__construct('files_sharing', $urlParams);
50 50
 
51
-		$container = $this->getContainer();
52
-		/** @var IServerContainer $server */
53
-		$server = $container->getServer();
51
+        $container = $this->getContainer();
52
+        /** @var IServerContainer $server */
53
+        $server = $container->getServer();
54 54
 
55
-		/**
56
-		 * Controllers
57
-		 */
58
-		$container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
59
-			$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
60
-			return new ShareController(
61
-				$c->query('AppName'),
62
-				$c->query('Request'),
63
-				$server->getConfig(),
64
-				$server->getURLGenerator(),
65
-				$server->getUserManager(),
66
-				$server->getLogger(),
67
-				$server->getActivityManager(),
68
-				$server->getShareManager(),
69
-				$server->getSession(),
70
-				$server->getPreviewManager(),
71
-				$server->getRootFolder(),
72
-				$federatedSharingApp->getFederatedShareProvider(),
73
-				$server->getEventDispatcher(),
74
-				$server->getL10N($c->query('AppName')),
75
-				$server->query(Defaults::class)
76
-			);
77
-		});
78
-		$container->registerService('ExternalSharesController', function (SimpleContainer $c) {
79
-			return new ExternalSharesController(
80
-				$c->query('AppName'),
81
-				$c->query('Request'),
82
-				$c->query('ExternalManager'),
83
-				$c->query('HttpClientService')
84
-			);
85
-		});
55
+        /**
56
+         * Controllers
57
+         */
58
+        $container->registerService('ShareController', function (SimpleContainer $c) use ($server) {
59
+            $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
60
+            return new ShareController(
61
+                $c->query('AppName'),
62
+                $c->query('Request'),
63
+                $server->getConfig(),
64
+                $server->getURLGenerator(),
65
+                $server->getUserManager(),
66
+                $server->getLogger(),
67
+                $server->getActivityManager(),
68
+                $server->getShareManager(),
69
+                $server->getSession(),
70
+                $server->getPreviewManager(),
71
+                $server->getRootFolder(),
72
+                $federatedSharingApp->getFederatedShareProvider(),
73
+                $server->getEventDispatcher(),
74
+                $server->getL10N($c->query('AppName')),
75
+                $server->query(Defaults::class)
76
+            );
77
+        });
78
+        $container->registerService('ExternalSharesController', function (SimpleContainer $c) {
79
+            return new ExternalSharesController(
80
+                $c->query('AppName'),
81
+                $c->query('Request'),
82
+                $c->query('ExternalManager'),
83
+                $c->query('HttpClientService')
84
+            );
85
+        });
86 86
 
87
-		/**
88
-		 * Core class wrappers
89
-		 */
90
-		$container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
91
-			return $server->getHTTPClientService();
92
-		});
93
-		$container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
94
-			return $server->getCloudIdManager();
95
-		});
96
-		$container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
97
-			$user = $server->getUserSession()->getUser();
98
-			$uid = $user ? $user->getUID() : null;
99
-			return new \OCA\Files_Sharing\External\Manager(
100
-				$server->getDatabaseConnection(),
101
-				\OC\Files\Filesystem::getMountManager(),
102
-				\OC\Files\Filesystem::getLoader(),
103
-				$server->getHTTPClientService(),
104
-				$server->getNotificationManager(),
105
-				$server->query(\OCP\OCS\IDiscoveryService::class),
106
-				$server->getCloudFederationProviderManager(),
107
-				$server->getCloudFederationFactory(),
108
-				$uid
109
-			);
110
-		});
111
-		$container->registerAlias(Manager::class, 'ExternalManager');
87
+        /**
88
+         * Core class wrappers
89
+         */
90
+        $container->registerService('HttpClientService', function (SimpleContainer $c) use ($server) {
91
+            return $server->getHTTPClientService();
92
+        });
93
+        $container->registerService(ICloudIdManager::class, function (SimpleContainer $c) use ($server) {
94
+            return $server->getCloudIdManager();
95
+        });
96
+        $container->registerService('ExternalManager', function (SimpleContainer $c) use ($server) {
97
+            $user = $server->getUserSession()->getUser();
98
+            $uid = $user ? $user->getUID() : null;
99
+            return new \OCA\Files_Sharing\External\Manager(
100
+                $server->getDatabaseConnection(),
101
+                \OC\Files\Filesystem::getMountManager(),
102
+                \OC\Files\Filesystem::getLoader(),
103
+                $server->getHTTPClientService(),
104
+                $server->getNotificationManager(),
105
+                $server->query(\OCP\OCS\IDiscoveryService::class),
106
+                $server->getCloudFederationProviderManager(),
107
+                $server->getCloudFederationFactory(),
108
+                $uid
109
+            );
110
+        });
111
+        $container->registerAlias(Manager::class, 'ExternalManager');
112 112
 
113
-		/**
114
-		 * Middleware
115
-		 */
116
-		$container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
117
-			return new SharingCheckMiddleware(
118
-				$c->query('AppName'),
119
-				$server->getConfig(),
120
-				$server->getAppManager(),
121
-				$c['ControllerMethodReflector'],
122
-				$server->getShareManager(),
123
-				$server->getRequest()
124
-			);
125
-		});
113
+        /**
114
+         * Middleware
115
+         */
116
+        $container->registerService('SharingCheckMiddleware', function (SimpleContainer $c) use ($server) {
117
+            return new SharingCheckMiddleware(
118
+                $c->query('AppName'),
119
+                $server->getConfig(),
120
+                $server->getAppManager(),
121
+                $c['ControllerMethodReflector'],
122
+                $server->getShareManager(),
123
+                $server->getRequest()
124
+            );
125
+        });
126 126
 
127
-		$container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
128
-			return new OCSShareAPIMiddleware(
129
-				$server->getShareManager(),
130
-				$server->getL10N($c->query('AppName'))
131
-			);
132
-		});
127
+        $container->registerService('OCSShareAPIMiddleware', function (SimpleContainer $c) use ($server) {
128
+            return new OCSShareAPIMiddleware(
129
+                $server->getShareManager(),
130
+                $server->getL10N($c->query('AppName'))
131
+            );
132
+        });
133 133
 
134
-		$container->registerService(ShareInfoMiddleware::class, function () use ($server) {
135
-			return new ShareInfoMiddleware(
136
-				$server->getShareManager()
137
-			);
138
-		});
134
+        $container->registerService(ShareInfoMiddleware::class, function () use ($server) {
135
+            return new ShareInfoMiddleware(
136
+                $server->getShareManager()
137
+            );
138
+        });
139 139
 
140
-		// Execute middlewares
141
-		$container->registerMiddleWare('SharingCheckMiddleware');
142
-		$container->registerMiddleWare('OCSShareAPIMiddleware');
143
-		$container->registerMiddleWare(ShareInfoMiddleware::class);
140
+        // Execute middlewares
141
+        $container->registerMiddleWare('SharingCheckMiddleware');
142
+        $container->registerMiddleWare('OCSShareAPIMiddleware');
143
+        $container->registerMiddleWare(ShareInfoMiddleware::class);
144 144
 
145
-		$container->registerService('MountProvider', function (IContainer $c) {
146
-			/** @var \OCP\IServerContainer $server */
147
-			$server = $c->query('ServerContainer');
148
-			return new MountProvider(
149
-				$server->getConfig(),
150
-				$server->getShareManager(),
151
-				$server->getLogger()
152
-			);
153
-		});
145
+        $container->registerService('MountProvider', function (IContainer $c) {
146
+            /** @var \OCP\IServerContainer $server */
147
+            $server = $c->query('ServerContainer');
148
+            return new MountProvider(
149
+                $server->getConfig(),
150
+                $server->getShareManager(),
151
+                $server->getLogger()
152
+            );
153
+        });
154 154
 
155
-		$container->registerService('ExternalMountProvider', function (IContainer $c) {
156
-			/** @var \OCP\IServerContainer $server */
157
-			$server = $c->query('ServerContainer');
158
-			return new \OCA\Files_Sharing\External\MountProvider(
159
-				$server->getDatabaseConnection(),
160
-				function() use ($c) {
161
-					return $c->query('ExternalManager');
162
-				},
163
-				$server->getCloudIdManager()
164
-			);
165
-		});
155
+        $container->registerService('ExternalMountProvider', function (IContainer $c) {
156
+            /** @var \OCP\IServerContainer $server */
157
+            $server = $c->query('ServerContainer');
158
+            return new \OCA\Files_Sharing\External\MountProvider(
159
+                $server->getDatabaseConnection(),
160
+                function() use ($c) {
161
+                    return $c->query('ExternalManager');
162
+                },
163
+                $server->getCloudIdManager()
164
+            );
165
+        });
166 166
 
167
-		/*
167
+        /*
168 168
 		 * Register capabilities
169 169
 		 */
170
-		$container->registerCapability(Capabilities::class);
171
-	}
170
+        $container->registerCapability(Capabilities::class);
171
+    }
172 172
 
173
-	public function registerMountProviders() {
174
-		/** @var \OCP\IServerContainer $server */
175
-		$server = $this->getContainer()->query('ServerContainer');
176
-		$mountProviderCollection = $server->getMountProviderCollection();
177
-		$mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
178
-		$mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
179
-	}
173
+    public function registerMountProviders() {
174
+        /** @var \OCP\IServerContainer $server */
175
+        $server = $this->getContainer()->query('ServerContainer');
176
+        $mountProviderCollection = $server->getMountProviderCollection();
177
+        $mountProviderCollection->registerProvider($this->getContainer()->query('MountProvider'));
178
+        $mountProviderCollection->registerProvider($this->getContainer()->query('ExternalMountProvider'));
179
+    }
180 180
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Hooks.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -32,33 +32,33 @@
 block discarded – undo
32 32
 
33 33
 class Hooks {
34 34
 
35
-	public static function deleteUser($params) {
36
-		$manager = new External\Manager(
37
-			\OC::$server->getDatabaseConnection(),
38
-			\OC\Files\Filesystem::getMountManager(),
39
-			\OC\Files\Filesystem::getLoader(),
40
-			\OC::$server->getHTTPClientService(),
41
-			\OC::$server->getNotificationManager(),
42
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
43
-			\OC::$server->getCloudFederationProviderManager(),
44
-			\OC::$server->getCloudFederationFactory(),
45
-			$params['uid']);
35
+    public static function deleteUser($params) {
36
+        $manager = new External\Manager(
37
+            \OC::$server->getDatabaseConnection(),
38
+            \OC\Files\Filesystem::getMountManager(),
39
+            \OC\Files\Filesystem::getLoader(),
40
+            \OC::$server->getHTTPClientService(),
41
+            \OC::$server->getNotificationManager(),
42
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
43
+            \OC::$server->getCloudFederationProviderManager(),
44
+            \OC::$server->getCloudFederationFactory(),
45
+            $params['uid']);
46 46
 
47
-		$manager->removeUserShares($params['uid']);
48
-	}
47
+        $manager->removeUserShares($params['uid']);
48
+    }
49 49
 
50
-	public static function unshareChildren($params) {
51
-		$path = Filesystem::getView()->getAbsolutePath($params['path']);
52
-		$view = new \OC\Files\View('/');
50
+    public static function unshareChildren($params) {
51
+        $path = Filesystem::getView()->getAbsolutePath($params['path']);
52
+        $view = new \OC\Files\View('/');
53 53
 
54
-		// find share mount points within $path and unmount them
55
-		$mountManager = \OC\Files\Filesystem::getMountManager();
56
-		$mountedShares = $mountManager->findIn($path);
57
-		foreach ($mountedShares as $mount) {
58
-			if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
59
-				$mountPoint = $mount->getMountPoint();
60
-				$view->unlink($mountPoint);
61
-			}
62
-		}
63
-	}
54
+        // find share mount points within $path and unmount them
55
+        $mountManager = \OC\Files\Filesystem::getMountManager();
56
+        $mountedShares = $mountManager->findIn($path);
57
+        foreach ($mountedShares as $mount) {
58
+            if ($mount->getStorage()->instanceOfStorage(ISharedStorage::class)) {
59
+                $mountPoint = $mount->getMountPoint();
60
+                $view->unlink($mountPoint);
61
+            }
62
+        }
63
+    }
64 64
 }
Please login to merge, or discard this patch.
lib/public/Federation/Exceptions/ActionNotSupportedException.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
 	 */
32 32
 	public function __construct($action) {
33 33
 		$l = \OC::$server->getL10N('federation');
34
-		$message = 'Action "' . $action . '" not supported or implemented.';
34
+		$message = 'Action "'.$action.'" not supported or implemented.';
35 35
 		$hint = $l->t('Action "%s" not supported or implemented.', [$action]);
36 36
 		parent::__construct($message, $hint);
37 37
 	}
Please login to merge, or discard this patch.
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -32,17 +32,17 @@
 block discarded – undo
32 32
  */
33 33
 class ActionNotSupportedException extends HintException {
34 34
 
35
-	/**
36
-	 * ActionNotSupportedException constructor.
37
-	 *
38
-	 * @since 14.0.0
39
-	 *
40
-	 */
41
-	public function __construct($action) {
42
-		$l = \OC::$server->getL10N('federation');
43
-		$message = 'Action "' . $action . '" not supported or implemented.';
44
-		$hint = $l->t('Action "%s" not supported or implemented.', [$action]);
45
-		parent::__construct($message, $hint);
46
-	}
35
+    /**
36
+     * ActionNotSupportedException constructor.
37
+     *
38
+     * @since 14.0.0
39
+     *
40
+     */
41
+    public function __construct($action) {
42
+        $l = \OC::$server->getL10N('federation');
43
+        $message = 'Action "' . $action . '" not supported or implemented.';
44
+        $hint = $l->t('Action "%s" not supported or implemented.', [$action]);
45
+        parent::__construct($message, $hint);
46
+    }
47 47
 
48 48
 }
Please login to merge, or discard this patch.
lib/private/Federation/CloudFederationFactory.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -27,37 +27,37 @@
 block discarded – undo
27 27
 
28 28
 class CloudFederationFactory implements ICloudFederationFactory {
29 29
 
30
-	/**
31
-	 * get a CloudFederationShare Object to prepare a share you want to send
32
-	 *
33
-	 * @param string $shareWith
34
-	 * @param string $name resource name (e.g. document.odt)
35
-	 * @param string $description share description (optional)
36
-	 * @param string $providerId resource UID on the provider side
37
-	 * @param string $owner provider specific UID of the user who owns the resource
38
-	 * @param string $ownerDisplayName display name of the user who shared the item
39
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
40
-	 * @param string $sharedByDisplayName display name of the user who shared the resource
41
-	 * @param string $sharedSecret used to authenticate requests across servers
42
-	 * @param string $shareType ('group' or 'user' share)
43
-	 * @param $resourceType ('file', 'calendar',...)
44
-	 * @return ICloudFederationShare
45
-	 *
46
-	 * @since 14.0.0
47
-	 */
48
-	public function getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $sharedSecret, $shareType, $resourceType) {
49
-		return new CloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $shareType, $resourceType, $sharedSecret);
50
-	}
30
+    /**
31
+     * get a CloudFederationShare Object to prepare a share you want to send
32
+     *
33
+     * @param string $shareWith
34
+     * @param string $name resource name (e.g. document.odt)
35
+     * @param string $description share description (optional)
36
+     * @param string $providerId resource UID on the provider side
37
+     * @param string $owner provider specific UID of the user who owns the resource
38
+     * @param string $ownerDisplayName display name of the user who shared the item
39
+     * @param string $sharedBy provider specific UID of the user who shared the resource
40
+     * @param string $sharedByDisplayName display name of the user who shared the resource
41
+     * @param string $sharedSecret used to authenticate requests across servers
42
+     * @param string $shareType ('group' or 'user' share)
43
+     * @param $resourceType ('file', 'calendar',...)
44
+     * @return ICloudFederationShare
45
+     *
46
+     * @since 14.0.0
47
+     */
48
+    public function getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $sharedSecret, $shareType, $resourceType) {
49
+        return new CloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $shareType, $resourceType, $sharedSecret);
50
+    }
51 51
 
52
-	/**
53
-	 * get a Cloud FederationNotification object to prepare a notification you
54
-	 * want to send
55
-	 *
56
-	 * @return ICloudFederationNotification
57
-	 *
58
-	 * @since 14.0.0
59
-	 */
60
-	public function getCloudFederationNotification() {
61
-		return new CloudFederationNotification();
62
-	}
52
+    /**
53
+     * get a Cloud FederationNotification object to prepare a notification you
54
+     * want to send
55
+     *
56
+     * @return ICloudFederationNotification
57
+     *
58
+     * @since 14.0.0
59
+     */
60
+    public function getCloudFederationNotification() {
61
+        return new CloudFederationNotification();
62
+    }
63 63
 }
Please login to merge, or discard this patch.
lib/public/Federation/Exceptions/BadRequestException.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@
 block discarded – undo
36 36
 		$l = \OC::$server->getL10N('federation');
37 37
 		$this->parameterList = $missingParameters;
38 38
 		$parameterList = implode(',', $missingParameters);
39
-		$message = 'Parameters missing in order to complete the request. Missing Parameters: ' . $parameterList;
39
+		$message = 'Parameters missing in order to complete the request. Missing Parameters: '.$parameterList;
40 40
 		$hint = $l->t('Parameters missing in order to complete the request. Missing Parameters: "%s"', [$parameterList]);
41 41
 		parent::__construct($message, $hint);
42 42
 	}
Please login to merge, or discard this patch.
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -32,46 +32,46 @@
 block discarded – undo
32 32
  */
33 33
 class BadRequestException extends HintException {
34 34
 
35
-	private $parameterList;
35
+    private $parameterList;
36 36
 
37
-	/**
38
-	 * BadRequestException constructor.
39
-	 *
40
-	 * @since 14.0.0
41
-	 *
42
-	 * @param array $missingParameters
43
-	 */
44
-	public function __construct(array $missingParameters) {
45
-		$l = \OC::$server->getL10N('federation');
46
-		$this->parameterList = $missingParameters;
47
-		$parameterList = implode(',', $missingParameters);
48
-		$message = 'Parameters missing in order to complete the request. Missing Parameters: ' . $parameterList;
49
-		$hint = $l->t('Parameters missing in order to complete the request. Missing Parameters: "%s"', [$parameterList]);
50
-		parent::__construct($message, $hint);
51
-	}
37
+    /**
38
+     * BadRequestException constructor.
39
+     *
40
+     * @since 14.0.0
41
+     *
42
+     * @param array $missingParameters
43
+     */
44
+    public function __construct(array $missingParameters) {
45
+        $l = \OC::$server->getL10N('federation');
46
+        $this->parameterList = $missingParameters;
47
+        $parameterList = implode(',', $missingParameters);
48
+        $message = 'Parameters missing in order to complete the request. Missing Parameters: ' . $parameterList;
49
+        $hint = $l->t('Parameters missing in order to complete the request. Missing Parameters: "%s"', [$parameterList]);
50
+        parent::__construct($message, $hint);
51
+    }
52 52
 
53
-	/**
54
-	 * get array with the return message as defined in the OCM API
55
-	 *
56
-	 * @since 14.0.0
57
-	 *
58
-	 * @return array
59
-	 */
60
-	public function getReturnMessage() {
61
-		$result = [
62
-			'message' => 'RESOURCE_NOT_FOUND',
63
-			'validationErrors' =>[
64
-			]
65
-		];
53
+    /**
54
+     * get array with the return message as defined in the OCM API
55
+     *
56
+     * @since 14.0.0
57
+     *
58
+     * @return array
59
+     */
60
+    public function getReturnMessage() {
61
+        $result = [
62
+            'message' => 'RESOURCE_NOT_FOUND',
63
+            'validationErrors' =>[
64
+            ]
65
+        ];
66 66
 
67
-		foreach ($this->parameterList as $missingParameter) {
68
-			$result['validationErrors'] = [
69
-				'name' => $missingParameter,
70
-				'message' => 'NOT_FOUND'
71
-			];
72
-		}
67
+        foreach ($this->parameterList as $missingParameter) {
68
+            $result['validationErrors'] = [
69
+                'name' => $missingParameter,
70
+                'message' => 'NOT_FOUND'
71
+            ];
72
+        }
73 73
 
74
-		return $result;
75
-	}
74
+        return $result;
75
+    }
76 76
 
77 77
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Capabilities.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -28,37 +28,37 @@
 block discarded – undo
28 28
 
29 29
 class Capabilities implements ICapability {
30 30
 
31
-	/** @var IURLGenerator */
32
-	private $urlGenerator;
31
+    /** @var IURLGenerator */
32
+    private $urlGenerator;
33 33
 
34
-	public function __construct(IURLGenerator $urlGenerator) {
35
-		$this->urlGenerator = $urlGenerator;
36
-	}
34
+    public function __construct(IURLGenerator $urlGenerator) {
35
+        $this->urlGenerator = $urlGenerator;
36
+    }
37 37
 
38
-	/**
39
-	 * Function an app uses to return the capabilities
40
-	 *
41
-	 * @return array Array containing the apps capabilities
42
-	 * @since 8.2.0
43
-	 */
44
-	public function getCapabilities() {
45
-		$url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
46
-		$capabilities = ['ocm' =>
47
-			[
48
-				'enabled' => true,
49
-				'apiVersion' => '1.0-proposal1',
50
-				'endPoint' => substr($url, 0, strrpos($url, '/')),
51
-				'shareTypes' => [
52
-					[
53
-						'name' => 'file',
54
-						'protocols' => [
55
-							'webdav' => '/public.php/webdav/',
56
-						]
57
-					],
58
-				]
59
-			]
60
-		];
38
+    /**
39
+     * Function an app uses to return the capabilities
40
+     *
41
+     * @return array Array containing the apps capabilities
42
+     * @since 8.2.0
43
+     */
44
+    public function getCapabilities() {
45
+        $url = $this->urlGenerator->linkToRouteAbsolute('cloud_federation_api.requesthandlercontroller.addShare');
46
+        $capabilities = ['ocm' =>
47
+            [
48
+                'enabled' => true,
49
+                'apiVersion' => '1.0-proposal1',
50
+                'endPoint' => substr($url, 0, strrpos($url, '/')),
51
+                'shareTypes' => [
52
+                    [
53
+                        'name' => 'file',
54
+                        'protocols' => [
55
+                            'webdav' => '/public.php/webdav/',
56
+                        ]
57
+                    ],
58
+                ]
59
+            ]
60
+        ];
61 61
 
62
-		return $capabilities;
63
-	}
62
+        return $capabilities;
63
+    }
64 64
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Controller/RequestHandlerController.php 3 patches
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -247,8 +247,7 @@
 block discarded – undo
247 247
 			return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
248 248
 		} catch (AuthenticationFailedException $e) {
249 249
 			return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
250
-		}
251
-		catch (\Exception $e) {
250
+		} catch (\Exception $e) {
252 251
 			return new JSONResponse(
253 252
 				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
254 253
 				Http::STATUS_BAD_REQUEST
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 
150 150
 		if (!$this->userManager->userExists($shareWith)) {
151 151
 			return new JSONResponse(
152
-				['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
152
+				['message' => 'User "'.$shareWith.'" does not exists at '.$this->urlGenerator->getBaseUrl()],
153 153
 				Http::STATUS_BAD_REQUEST
154 154
 			);
155 155
 		}
@@ -181,14 +181,14 @@  discard block
 block discarded – undo
181 181
 			);
182 182
 		} catch (\Exception $e) {
183 183
 			return new JSONResponse(
184
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
184
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
185 185
 				Http::STATUS_BAD_REQUEST
186 186
 			);
187 187
 		}
188 188
 
189 189
 		$user = $this->userManager->get($shareWithLocalId);
190 190
 		$recipientDisplayName = '';
191
-		if($user) {
191
+		if ($user) {
192 192
 			$recipientDisplayName = $user->getDisplayName();
193 193
 		}
194 194
 
@@ -256,12 +256,12 @@  discard block
 block discarded – undo
256 256
 		}
257 257
 		catch (\Exception $e) {
258 258
 			return new JSONResponse(
259
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
259
+				['message' => 'Internal error at '.$this->urlGenerator->getBaseUrl()],
260 260
 				Http::STATUS_BAD_REQUEST
261 261
 			);
262 262
 		}
263 263
 
264
-		return new JSONResponse($result,Http::STATUS_CREATED);
264
+		return new JSONResponse($result, Http::STATUS_CREATED);
265 265
 
266 266
 	}
267 267
 
@@ -274,13 +274,13 @@  discard block
 block discarded – undo
274 274
 	private function mapUid($uid) {
275 275
 		\OC::$server->getURLGenerator()->linkToDocs('key');
276 276
 		// FIXME this should be a method in the user management instead
277
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
277
+		$this->logger->debug('shareWith before, '.$uid, ['app' => $this->appName]);
278 278
 		\OCP\Util::emitHook(
279 279
 			'\OCA\Files_Sharing\API\Server2Server',
280 280
 			'preLoginNameUsedAsUserName',
281 281
 			array('uid' => &$uid)
282 282
 		);
283
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
283
+		$this->logger->debug('shareWith after, '.$uid, ['app' => $this->appName]);
284 284
 
285 285
 		return $uid;
286 286
 	}
Please login to merge, or discard this patch.
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -51,225 +51,225 @@
 block discarded – undo
51 51
  */
52 52
 class RequestHandlerController extends Controller {
53 53
 
54
-	/** @var ILogger */
55
-	private $logger;
54
+    /** @var ILogger */
55
+    private $logger;
56 56
 
57
-	/** @var IUserManager */
58
-	private $userManager;
57
+    /** @var IUserManager */
58
+    private $userManager;
59 59
 
60
-	/** @var IURLGenerator */
61
-	private $urlGenerator;
60
+    /** @var IURLGenerator */
61
+    private $urlGenerator;
62 62
 
63
-	/** @var ICloudFederationProviderManager */
64
-	private $cloudFederationProviderManager;
63
+    /** @var ICloudFederationProviderManager */
64
+    private $cloudFederationProviderManager;
65 65
 
66
-	/** @var Config */
67
-	private $config;
66
+    /** @var Config */
67
+    private $config;
68 68
 
69
-	/** @var ICloudFederationFactory */
70
-	private $factory;
69
+    /** @var ICloudFederationFactory */
70
+    private $factory;
71 71
 
72
-	/** @var ICloudIdManager */
73
-	private $cloudIdManager;
72
+    /** @var ICloudIdManager */
73
+    private $cloudIdManager;
74 74
 
75
-	public function __construct($appName,
76
-								IRequest $request,
77
-								ILogger $logger,
78
-								IUserManager $userManager,
79
-								IURLGenerator $urlGenerator,
80
-								ICloudFederationProviderManager $cloudFederationProviderManager,
81
-								Config $config,
82
-								ICloudFederationFactory $factory,
83
-								ICloudIdManager $cloudIdManager
84
-	) {
85
-		parent::__construct($appName, $request);
75
+    public function __construct($appName,
76
+                                IRequest $request,
77
+                                ILogger $logger,
78
+                                IUserManager $userManager,
79
+                                IURLGenerator $urlGenerator,
80
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
81
+                                Config $config,
82
+                                ICloudFederationFactory $factory,
83
+                                ICloudIdManager $cloudIdManager
84
+    ) {
85
+        parent::__construct($appName, $request);
86 86
 
87
-		$this->logger = $logger;
88
-		$this->userManager = $userManager;
89
-		$this->urlGenerator = $urlGenerator;
90
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
91
-		$this->config = $config;
92
-		$this->factory = $factory;
93
-		$this->cloudIdManager = $cloudIdManager;
94
-	}
87
+        $this->logger = $logger;
88
+        $this->userManager = $userManager;
89
+        $this->urlGenerator = $urlGenerator;
90
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
91
+        $this->config = $config;
92
+        $this->factory = $factory;
93
+        $this->cloudIdManager = $cloudIdManager;
94
+    }
95 95
 
96
-	/**
97
-	 * add share
98
-	 *
99
-	 * @NoCSRFRequired
100
-	 * @PublicPage
101
-	 * @BruteForceProtection(action=receiveFederatedShare)
102
-	 *
103
-	 * @param string $shareWith
104
-	 * @param string $name resource name (e.g. document.odt)
105
-	 * @param string $description share description (optional)
106
-	 * @param string $providerId resource UID on the provider side
107
-	 * @param string $owner provider specific UID of the user who owns the resource
108
-	 * @param string $ownerDisplayName display name of the user who shared the item
109
-	 * @param string $sharedBy provider specific UID of the user who shared the resource
110
-	 * @param string $sharedByDisplayName display name of the user who shared the resource
111
-	 * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
112
-	 * @param string $shareType ('group' or 'user' share)
113
-	 * @param $resourceType ('file', 'calendar',...)
114
-	 * @return Http\DataResponse|JSONResponse
115
-	 *
116
-	 * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
117
-	 */
118
-	public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
96
+    /**
97
+     * add share
98
+     *
99
+     * @NoCSRFRequired
100
+     * @PublicPage
101
+     * @BruteForceProtection(action=receiveFederatedShare)
102
+     *
103
+     * @param string $shareWith
104
+     * @param string $name resource name (e.g. document.odt)
105
+     * @param string $description share description (optional)
106
+     * @param string $providerId resource UID on the provider side
107
+     * @param string $owner provider specific UID of the user who owns the resource
108
+     * @param string $ownerDisplayName display name of the user who shared the item
109
+     * @param string $sharedBy provider specific UID of the user who shared the resource
110
+     * @param string $sharedByDisplayName display name of the user who shared the resource
111
+     * @param array $protocol (e,.g. ['name' => 'webdav', 'options' => ['username' => 'john', 'permissions' => 31]])
112
+     * @param string $shareType ('group' or 'user' share)
113
+     * @param $resourceType ('file', 'calendar',...)
114
+     * @return Http\DataResponse|JSONResponse
115
+     *
116
+     * Example: curl -H "Content-Type: application/json" -X POST -d '{"shareWith":"admin1@serve1","name":"welcome server2.txt","description":"desc","providerId":"2","owner":"admin2@http://localhost/server2","ownerDisplayName":"admin2 display","shareType":"user","resourceType":"file","protocol":{"name":"webdav","options":{"sharedSecret":"secret","permissions":"webdav-property"}}}' http://localhost/server/index.php/ocm/shares
117
+     */
118
+    public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
119 119
 
120
-		// check if all required parameters are set
121
-		if ($shareWith === null ||
122
-			$name === null ||
123
-			$providerId === null ||
124
-			$owner === null ||
125
-			$resourceType === null ||
126
-			$shareType === null ||
127
-			!is_array($protocol) ||
128
-			!isset($protocol['name']) ||
129
-			!isset ($protocol['options']) ||
130
-			!is_array($protocol['options']) ||
131
-			!isset($protocol['options']['sharedSecret'])
132
-		) {
133
-			return new JSONResponse(
134
-				['message' => 'Missing arguments'],
135
-				Http::STATUS_BAD_REQUEST
136
-			);
137
-		}
120
+        // check if all required parameters are set
121
+        if ($shareWith === null ||
122
+            $name === null ||
123
+            $providerId === null ||
124
+            $owner === null ||
125
+            $resourceType === null ||
126
+            $shareType === null ||
127
+            !is_array($protocol) ||
128
+            !isset($protocol['name']) ||
129
+            !isset ($protocol['options']) ||
130
+            !is_array($protocol['options']) ||
131
+            !isset($protocol['options']['sharedSecret'])
132
+        ) {
133
+            return new JSONResponse(
134
+                ['message' => 'Missing arguments'],
135
+                Http::STATUS_BAD_REQUEST
136
+            );
137
+        }
138 138
 
139
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
140
-		$shareWithLocalId = $cloudId->getUser();
141
-		$shareWith = $this->mapUid($shareWithLocalId);
139
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
140
+        $shareWithLocalId = $cloudId->getUser();
141
+        $shareWith = $this->mapUid($shareWithLocalId);
142 142
 
143
-		if (!$this->userManager->userExists($shareWith)) {
144
-			return new JSONResponse(
145
-				['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
146
-				Http::STATUS_BAD_REQUEST
147
-			);
148
-		}
143
+        if (!$this->userManager->userExists($shareWith)) {
144
+            return new JSONResponse(
145
+                ['message' => 'User "' . $shareWith . '" does not exists at ' . $this->urlGenerator->getBaseUrl()],
146
+                Http::STATUS_BAD_REQUEST
147
+            );
148
+        }
149 149
 
150
-		// if no explicit display name is given, we use the uid as display name
151
-		$ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
152
-		$sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
150
+        // if no explicit display name is given, we use the uid as display name
151
+        $ownerDisplayName = $ownerDisplayName === null ? $owner : $ownerDisplayName;
152
+        $sharedByDisplayName = $sharedByDisplayName === null ? $sharedBy : $sharedByDisplayName;
153 153
 
154
-		// sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
155
-		if ($sharedBy === null) {
156
-			$sharedBy = $owner;
157
-			$sharedByDisplayName = $ownerDisplayName;
158
-		}
154
+        // sharedBy* parameter is optional, if nothing is set we assume that it is the same user as the owner
155
+        if ($sharedBy === null) {
156
+            $sharedBy = $owner;
157
+            $sharedByDisplayName = $ownerDisplayName;
158
+        }
159 159
 
160
-		try {
161
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
162
-			$share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
163
-			$share->setProtocol($protocol);
164
-			$id = $provider->shareReceived($share);
165
-		} catch (ProviderDoesNotExistsException $e) {
166
-			return new JSONResponse(
167
-				['message' => $e->getMessage()],
168
-				Http::STATUS_NOT_IMPLEMENTED
169
-			);
170
-		} catch (ProviderCouldNotAddShareException $e) {
171
-			return new JSONResponse(
172
-				['message' => $e->getMessage()],
173
-				$e->getCode()
174
-			);
175
-		} catch (\Exception $e) {
176
-			return new JSONResponse(
177
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
178
-				Http::STATUS_BAD_REQUEST
179
-			);
180
-		}
160
+        try {
161
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
162
+            $share = $this->factory->getCloudFederationShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, '', $shareType, $resourceType);
163
+            $share->setProtocol($protocol);
164
+            $id = $provider->shareReceived($share);
165
+        } catch (ProviderDoesNotExistsException $e) {
166
+            return new JSONResponse(
167
+                ['message' => $e->getMessage()],
168
+                Http::STATUS_NOT_IMPLEMENTED
169
+            );
170
+        } catch (ProviderCouldNotAddShareException $e) {
171
+            return new JSONResponse(
172
+                ['message' => $e->getMessage()],
173
+                $e->getCode()
174
+            );
175
+        } catch (\Exception $e) {
176
+            return new JSONResponse(
177
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
178
+                Http::STATUS_BAD_REQUEST
179
+            );
180
+        }
181 181
 
182
-		$user = $this->userManager->get($shareWithLocalId);
183
-		$recipientDisplayName = '';
184
-		if($user) {
185
-			$recipientDisplayName = $user->getDisplayName();
186
-		}
182
+        $user = $this->userManager->get($shareWithLocalId);
183
+        $recipientDisplayName = '';
184
+        if($user) {
185
+            $recipientDisplayName = $user->getDisplayName();
186
+        }
187 187
 
188
-		return new JSONResponse(
189
-			['recipientDisplayName' => $recipientDisplayName],
190
-			Http::STATUS_CREATED);
188
+        return new JSONResponse(
189
+            ['recipientDisplayName' => $recipientDisplayName],
190
+            Http::STATUS_CREATED);
191 191
 
192
-	}
192
+    }
193 193
 
194
-	/**
195
-	 * receive notification about existing share
196
-	 *
197
-	 * @NoCSRFRequired
198
-	 * @PublicPage
199
-	 * @BruteForceProtection(action=receiveFederatedShareNotification)
200
-	 *
201
-	 * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
202
-	 * @param string $resourceType (calendar, file, contact,...)
203
-	 * @param string $providerId id of the share
204
-	 * @param array $notification the actual payload of the notification
205
-	 * @return JSONResponse
206
-	 */
207
-	public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
194
+    /**
195
+     * receive notification about existing share
196
+     *
197
+     * @NoCSRFRequired
198
+     * @PublicPage
199
+     * @BruteForceProtection(action=receiveFederatedShareNotification)
200
+     *
201
+     * @param string $notificationType (notification type, e.g. SHARE_ACCEPTED)
202
+     * @param string $resourceType (calendar, file, contact,...)
203
+     * @param string $providerId id of the share
204
+     * @param array $notification the actual payload of the notification
205
+     * @return JSONResponse
206
+     */
207
+    public function receiveNotification($notificationType, $resourceType, $providerId, array $notification) {
208 208
 
209
-		// check if all required parameters are set
210
-		if ($notificationType === null ||
211
-			$resourceType === null ||
212
-			$providerId === null ||
213
-			!is_array($notification)
214
-		) {
215
-			return new JSONResponse(
216
-				['message' => 'Missing arguments'],
217
-				Http::STATUS_BAD_REQUEST
218
-			);
219
-		}
209
+        // check if all required parameters are set
210
+        if ($notificationType === null ||
211
+            $resourceType === null ||
212
+            $providerId === null ||
213
+            !is_array($notification)
214
+        ) {
215
+            return new JSONResponse(
216
+                ['message' => 'Missing arguments'],
217
+                Http::STATUS_BAD_REQUEST
218
+            );
219
+        }
220 220
 
221
-		try {
222
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
223
-			$result = $provider->notificationReceived($notificationType, $providerId, $notification);
224
-		} catch (ProviderDoesNotExistsException $e) {
225
-			return new JSONResponse(
226
-				['message' => $e->getMessage()],
227
-				Http::STATUS_BAD_REQUEST
228
-			);
229
-		} catch (ShareNotFound $e) {
230
-			return new JSONResponse(
231
-				['message' => $e->getMessage()],
232
-				Http::STATUS_BAD_REQUEST
233
-			);
234
-		} catch (ActionNotSupportedException $e) {
235
-			return new JSONResponse(
236
-				['message' => $e->getMessage()],
237
-				Http::STATUS_NOT_IMPLEMENTED
238
-			);
239
-		} catch (BadRequestException $e) {
240
-			return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
241
-		} catch (AuthenticationFailedException $e) {
242
-			return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
243
-		}
244
-		catch (\Exception $e) {
245
-			return new JSONResponse(
246
-				['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
247
-				Http::STATUS_BAD_REQUEST
248
-			);
249
-		}
221
+        try {
222
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
223
+            $result = $provider->notificationReceived($notificationType, $providerId, $notification);
224
+        } catch (ProviderDoesNotExistsException $e) {
225
+            return new JSONResponse(
226
+                ['message' => $e->getMessage()],
227
+                Http::STATUS_BAD_REQUEST
228
+            );
229
+        } catch (ShareNotFound $e) {
230
+            return new JSONResponse(
231
+                ['message' => $e->getMessage()],
232
+                Http::STATUS_BAD_REQUEST
233
+            );
234
+        } catch (ActionNotSupportedException $e) {
235
+            return new JSONResponse(
236
+                ['message' => $e->getMessage()],
237
+                Http::STATUS_NOT_IMPLEMENTED
238
+            );
239
+        } catch (BadRequestException $e) {
240
+            return new JSONResponse($e->getReturnMessage(), Http::STATUS_BAD_REQUEST);
241
+        } catch (AuthenticationFailedException $e) {
242
+            return new JSONResponse(["message" => "RESOURCE_NOT_FOUND"], Http::STATUS_FORBIDDEN);
243
+        }
244
+        catch (\Exception $e) {
245
+            return new JSONResponse(
246
+                ['message' => 'Internal error at ' . $this->urlGenerator->getBaseUrl()],
247
+                Http::STATUS_BAD_REQUEST
248
+            );
249
+        }
250 250
 
251
-		return new JSONResponse($result,Http::STATUS_CREATED);
251
+        return new JSONResponse($result,Http::STATUS_CREATED);
252 252
 
253
-	}
253
+    }
254 254
 
255
-	/**
256
-	 * map login name to internal LDAP UID if a LDAP backend is in use
257
-	 *
258
-	 * @param string $uid
259
-	 * @return string mixed
260
-	 */
261
-	private function mapUid($uid) {
262
-		\OC::$server->getURLGenerator()->linkToDocs('key');
263
-		// FIXME this should be a method in the user management instead
264
-		$this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
265
-		\OCP\Util::emitHook(
266
-			'\OCA\Files_Sharing\API\Server2Server',
267
-			'preLoginNameUsedAsUserName',
268
-			array('uid' => &$uid)
269
-		);
270
-		$this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
255
+    /**
256
+     * map login name to internal LDAP UID if a LDAP backend is in use
257
+     *
258
+     * @param string $uid
259
+     * @return string mixed
260
+     */
261
+    private function mapUid($uid) {
262
+        \OC::$server->getURLGenerator()->linkToDocs('key');
263
+        // FIXME this should be a method in the user management instead
264
+        $this->logger->debug('shareWith before, ' . $uid, ['app' => $this->appName]);
265
+        \OCP\Util::emitHook(
266
+            '\OCA\Files_Sharing\API\Server2Server',
267
+            'preLoginNameUsedAsUserName',
268
+            array('uid' => &$uid)
269
+        );
270
+        $this->logger->debug('shareWith after, ' . $uid, ['app' => $this->appName]);
271 271
 
272
-		return $uid;
273
-	}
272
+        return $uid;
273
+    }
274 274
 
275 275
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 			$ocsStatus = isset($status['ocs']);
118 118
 			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119 119
 
120
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
120
+			if ($result['success'] && (!$ocsStatus || $ocsSuccess)) {
121 121
 				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122 122
 				return true;
123 123
 			}
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 			return [$ocmResult['token'], $ocmResult['providerId']];
161 161
 		}
162 162
 
163
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
163
+		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/'.$id.'/reshare', $fields);
164 164
 		$status = json_decode($result['result'], true);
165 165
 
166 166
 		$httpRequestSuccessful = $result['success'];
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172 172
 			return [
173 173
 				$status['ocs']['data']['token'],
174
-				(int)$status['ocs']['data']['remoteId']
174
+				(int) $status['ocs']['data']['remoteId']
175 175
 			];
176 176
 		}
177 177
 
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			$fields[$key] = $value;
259 259
 		}
260 260
 
261
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
261
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$remoteId.'/'.$action, $fields, $action);
262 262
 		$status = json_decode($result['result'], true);
263 263
 
264 264
 		if ($result['success'] &&
@@ -306,10 +306,10 @@  discard block
 block discarded – undo
306 306
 	 * @return array
307 307
 	 * @throws \Exception
308 308
 	 */
309
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
309
+	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action = "share") {
310 310
 
311 311
 		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
-			$remoteDomain = 'https://' . $remoteDomain;
312
+			$remoteDomain = 'https://'.$remoteDomain;
313 313
 		}
314 314
 
315 315
 		$result = [
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
349 349
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
350 350
 		try {
351
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
351
+			$response = $client->post($remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT, [
352 352
 				'body' => $fields,
353 353
 				'timeout' => 10,
354 354
 				'connect_timeout' => 10,
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 		switch ($action) {
406 406
 			case 'share':
407 407
 				$share = $this->cloudFederationFactory->getCloudFederationShare(
408
-					$fields['shareWith'] . '@' . $remoteDomain,
408
+					$fields['shareWith'].'@'.$remoteDomain,
409 409
 					$fields['name'],
410 410
 					'',
411 411
 					$fields['remoteId'],
Please login to merge, or discard this patch.
Indentation   +406 added lines, -406 removed lines patch added patch discarded remove patch
@@ -33,410 +33,410 @@
 block discarded – undo
33 33
 use OCP\OCS\IDiscoveryService;
34 34
 
35 35
 class Notifications {
36
-	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
-
38
-	/** @var AddressHandler */
39
-	private $addressHandler;
40
-
41
-	/** @var IClientService */
42
-	private $httpClientService;
43
-
44
-	/** @var IDiscoveryService */
45
-	private $discoveryService;
46
-
47
-	/** @var IJobList  */
48
-	private $jobList;
49
-
50
-	/** @var ICloudFederationProviderManager */
51
-	private $federationProviderManager;
52
-
53
-	/** @var ICloudFederationFactory */
54
-	private $cloudFederationFactory;
55
-
56
-	/**
57
-	 * @param AddressHandler $addressHandler
58
-	 * @param IClientService $httpClientService
59
-	 * @param IDiscoveryService $discoveryService
60
-	 * @param IJobList $jobList
61
-	 * @param ICloudFederationProviderManager $federationProviderManager
62
-	 * @param ICloudFederationFactory $cloudFederationFactory
63
-	 */
64
-	public function __construct(
65
-		AddressHandler $addressHandler,
66
-		IClientService $httpClientService,
67
-		IDiscoveryService $discoveryService,
68
-		IJobList $jobList,
69
-		ICloudFederationProviderManager $federationProviderManager,
70
-		ICloudFederationFactory $cloudFederationFactory
71
-	) {
72
-		$this->addressHandler = $addressHandler;
73
-		$this->httpClientService = $httpClientService;
74
-		$this->discoveryService = $discoveryService;
75
-		$this->jobList = $jobList;
76
-		$this->federationProviderManager = $federationProviderManager;
77
-		$this->cloudFederationFactory = $cloudFederationFactory;
78
-	}
79
-
80
-	/**
81
-	 * send server-to-server share to remote server
82
-	 *
83
-	 * @param string $token
84
-	 * @param string $shareWith
85
-	 * @param string $name
86
-	 * @param int $remote_id
87
-	 * @param string $owner
88
-	 * @param string $ownerFederatedId
89
-	 * @param string $sharedBy
90
-	 * @param string $sharedByFederatedId
91
-	 * @return bool
92
-	 * @throws \OC\HintException
93
-	 * @throws \OC\ServerNotAvailableException
94
-	 */
95
-	public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
96
-
97
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
98
-
99
-		if ($user && $remote) {
100
-			$local = $this->addressHandler->generateRemoteURL();
101
-
102
-			$fields = array(
103
-				'shareWith' => $user,
104
-				'token' => $token,
105
-				'name' => $name,
106
-				'remoteId' => $remote_id,
107
-				'owner' => $owner,
108
-				'ownerFederatedId' => $ownerFederatedId,
109
-				'sharedBy' => $sharedBy,
110
-				'sharedByFederatedId' => $sharedByFederatedId,
111
-				'remote' => $local,
112
-			);
113
-
114
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
115
-			$status = json_decode($result['result'], true);
116
-
117
-			$ocsStatus = isset($status['ocs']);
118
-			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119
-
120
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
121
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122
-				return true;
123
-			}
124
-
125
-		}
126
-
127
-		return false;
128
-	}
129
-
130
-	/**
131
-	 * ask owner to re-share the file with the given user
132
-	 *
133
-	 * @param string $token
134
-	 * @param int $id remote Id
135
-	 * @param int $shareId internal share Id
136
-	 * @param string $remote remote address of the owner
137
-	 * @param string $shareWith
138
-	 * @param int $permission
139
-	 * @param string $filename
140
-	 * @return bool
141
-	 * @throws \OC\HintException
142
-	 * @throws \OC\ServerNotAvailableException
143
-	 */
144
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
145
-
146
-		$fields = array(
147
-			'shareWith' => $shareWith,
148
-			'token' => $token,
149
-			'permission' => $permission,
150
-			'remoteId' => $shareId,
151
-		);
152
-
153
-		$ocmFields = $fields;
154
-		$ocmFields['remoteId'] = $id;
155
-		$ocmFields['localId'] = $shareId;
156
-		$ocmFields['name'] = $filename;
157
-
158
-		$ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
159
-		if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
160
-			return [$ocmResult['token'], $ocmResult['providerId']];
161
-		}
162
-
163
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
164
-		$status = json_decode($result['result'], true);
165
-
166
-		$httpRequestSuccessful = $result['success'];
167
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
168
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
169
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
170
-
171
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172
-			return [
173
-				$status['ocs']['data']['token'],
174
-				(int)$status['ocs']['data']['remoteId']
175
-			];
176
-		}
177
-
178
-		return false;
179
-	}
180
-
181
-	/**
182
-	 * send server-to-server unshare to remote server
183
-	 *
184
-	 * @param string $remote url
185
-	 * @param int $id share id
186
-	 * @param string $token
187
-	 * @return bool
188
-	 */
189
-	public function sendRemoteUnShare($remote, $id, $token) {
190
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
191
-	}
192
-
193
-	/**
194
-	 * send server-to-server unshare to remote server
195
-	 *
196
-	 * @param string $remote url
197
-	 * @param int $id share id
198
-	 * @param string $token
199
-	 * @return bool
200
-	 */
201
-	public function sendRevokeShare($remote, $id, $token) {
202
-		$this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
203
-	}
204
-
205
-	/**
206
-	 * send notification to remote server if the permissions was changed
207
-	 *
208
-	 * @param string $remote
209
-	 * @param int $remoteId
210
-	 * @param string $token
211
-	 * @param int $permissions
212
-	 * @return bool
213
-	 */
214
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
215
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
216
-	}
217
-
218
-	/**
219
-	 * forward accept reShare to remote server
220
-	 *
221
-	 * @param string $remote
222
-	 * @param int $remoteId
223
-	 * @param string $token
224
-	 */
225
-	public function sendAcceptShare($remote, $remoteId, $token) {
226
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
227
-	}
228
-
229
-	/**
230
-	 * forward decline reShare to remote server
231
-	 *
232
-	 * @param string $remote
233
-	 * @param int $remoteId
234
-	 * @param string $token
235
-	 */
236
-	public function sendDeclineShare($remote, $remoteId, $token) {
237
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
238
-	}
239
-
240
-	/**
241
-	 * inform remote server whether server-to-server share was accepted/declined
242
-	 *
243
-	 * @param string $remote
244
-	 * @param string $token
245
-	 * @param int $remoteId Share id on the remote host
246
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
247
-	 * @param array $data
248
-	 * @param int $try
249
-	 * @return boolean
250
-	 */
251
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
252
-
253
-		$fields = [
254
-			'token' => $token,
255
-			'remoteId' => $remoteId
256
-			];
257
-		foreach ($data as $key => $value) {
258
-			$fields[$key] = $value;
259
-		}
260
-
261
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
262
-		$status = json_decode($result['result'], true);
263
-
264
-		if ($result['success'] &&
265
-			($status['ocs']['meta']['statuscode'] === 100 ||
266
-				$status['ocs']['meta']['statuscode'] === 200
267
-			)
268
-		) {
269
-			return true;
270
-		} elseif ($try === 0) {
271
-			// only add new job on first try
272
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
273
-				[
274
-					'remote' => $remote,
275
-					'remoteId' => $remoteId,
276
-					'token' => $token,
277
-					'action' => $action,
278
-					'data' => json_encode($data),
279
-					'try' => $try,
280
-					'lastRun' => $this->getTimestamp()
281
-				]
282
-			);
283
-		}
284
-
285
-		return false;
286
-	}
287
-
288
-
289
-	/**
290
-	 * return current timestamp
291
-	 *
292
-	 * @return int
293
-	 */
294
-	protected function getTimestamp() {
295
-		return time();
296
-	}
297
-
298
-	/**
299
-	 * try http post with the given protocol, if no protocol is given we pick
300
-	 * the secure one (https)
301
-	 *
302
-	 * @param string $remoteDomain
303
-	 * @param string $urlSuffix
304
-	 * @param array $fields post parameters
305
-	 * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
306
-	 * @return array
307
-	 * @throws \Exception
308
-	 */
309
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
310
-
311
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
-			$remoteDomain = 'https://' . $remoteDomain;
313
-		}
314
-
315
-		$result = [
316
-			'success' => false,
317
-			'result' => '',
318
-		];
319
-
320
-		// if possible we use the new OCM API
321
-		$ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
322
-		if (is_array($ocmResult)) {
323
-			$result['success'] = true;
324
-			$result['result'] = json_encode([
325
-				'ocs' => ['meta' => ['statuscode' => 200]]]);
326
-			return $result;
327
-		}
328
-
329
-		return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
330
-	}
331
-
332
-	/**
333
-	 * try old federated sharing API if the OCM api doesn't work
334
-	 *
335
-	 * @param $remoteDomain
336
-	 * @param $urlSuffix
337
-	 * @param array $fields
338
-	 * @return mixed
339
-	 * @throws \Exception
340
-	 */
341
-	protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
342
-
343
-		$result = [
344
-			'success' => false,
345
-			'result' => '',
346
-		];
347
-
348
-		// Fall back to old API
349
-		$client = $this->httpClientService->newClient();
350
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
351
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
352
-		try {
353
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
354
-				'body' => $fields,
355
-				'timeout' => 10,
356
-				'connect_timeout' => 10,
357
-			]);
358
-			$result['result'] = $response->getBody();
359
-			$result['success'] = true;
360
-		} catch (\Exception $e) {
361
-			// if flat re-sharing is not supported by the remote server
362
-			// we re-throw the exception and fall back to the old behaviour.
363
-			// (flat re-shares has been introduced in Nextcloud 9.1)
364
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
365
-				throw $e;
366
-			}
367
-		}
368
-
369
-		return $result;
370
-
371
-	}
372
-
373
-	/**
374
-	 * send action regarding federated sharing to the remote server using the OCM API
375
-	 *
376
-	 * @param $remoteDomain
377
-	 * @param $fields
378
-	 * @param $action
379
-	 *
380
-	 * @return bool
381
-	 */
382
-	protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
383
-		switch ($action) {
384
-			case 'share':
385
-				$share = $this->cloudFederationFactory->getCloudFederationShare(
386
-					$fields['shareWith'] . '@' . $remoteDomain,
387
-					$fields['name'],
388
-					'',
389
-					$fields['remoteId'],
390
-					$fields['ownerFederatedId'],
391
-					$fields['owner'],
392
-					$fields['sharedByFederatedId'],
393
-					$fields['sharedBy'],
394
-					$fields['token'],
395
-					'user',
396
-					'file'
397
-				);
398
-				return $this->federationProviderManager->sendShare($share);
399
-			case 'reshare':
400
-				// ask owner to reshare a file
401
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
402
-				$notification->setMessage('REQUEST_RESHARE',
403
-					'file',
404
-					$fields['remoteId'],
405
-					[
406
-						'sharedSecret' => $fields['token'],
407
-						'shareWith' => $fields['shareWith'],
408
-						'senderId' => $fields['localId'],
409
-						'message' => 'Ask owner to reshare the file'
410
-					]
411
-				);
412
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
413
-			case 'unshare':
414
-				//owner unshares the file from the recipient again
415
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
416
-				$notification->setMessage('SHARE_UNSHARED',
417
-					'file',
418
-					$fields['remoteId'],
419
-					[
420
-						'sharedSecret' => $fields['token'],
421
-						'messgage' => 'file is no longer shared with you'
422
-					]
423
-				);
424
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
425
-			case 'reshare_undo':
426
-				// if a reshare was unshared we send the information to the initiator/owner
427
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
428
-				$notification->setMessage('RESHARE_UNDO',
429
-					'file',
430
-					$fields['remoteId'],
431
-					[
432
-						'sharedSecret' => $fields['token'],
433
-						'message' => 'reshare was revoked'
434
-					]
435
-				);
436
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
437
-		}
438
-
439
-		return false;
440
-
441
-	}
36
+    const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
+
38
+    /** @var AddressHandler */
39
+    private $addressHandler;
40
+
41
+    /** @var IClientService */
42
+    private $httpClientService;
43
+
44
+    /** @var IDiscoveryService */
45
+    private $discoveryService;
46
+
47
+    /** @var IJobList  */
48
+    private $jobList;
49
+
50
+    /** @var ICloudFederationProviderManager */
51
+    private $federationProviderManager;
52
+
53
+    /** @var ICloudFederationFactory */
54
+    private $cloudFederationFactory;
55
+
56
+    /**
57
+     * @param AddressHandler $addressHandler
58
+     * @param IClientService $httpClientService
59
+     * @param IDiscoveryService $discoveryService
60
+     * @param IJobList $jobList
61
+     * @param ICloudFederationProviderManager $federationProviderManager
62
+     * @param ICloudFederationFactory $cloudFederationFactory
63
+     */
64
+    public function __construct(
65
+        AddressHandler $addressHandler,
66
+        IClientService $httpClientService,
67
+        IDiscoveryService $discoveryService,
68
+        IJobList $jobList,
69
+        ICloudFederationProviderManager $federationProviderManager,
70
+        ICloudFederationFactory $cloudFederationFactory
71
+    ) {
72
+        $this->addressHandler = $addressHandler;
73
+        $this->httpClientService = $httpClientService;
74
+        $this->discoveryService = $discoveryService;
75
+        $this->jobList = $jobList;
76
+        $this->federationProviderManager = $federationProviderManager;
77
+        $this->cloudFederationFactory = $cloudFederationFactory;
78
+    }
79
+
80
+    /**
81
+     * send server-to-server share to remote server
82
+     *
83
+     * @param string $token
84
+     * @param string $shareWith
85
+     * @param string $name
86
+     * @param int $remote_id
87
+     * @param string $owner
88
+     * @param string $ownerFederatedId
89
+     * @param string $sharedBy
90
+     * @param string $sharedByFederatedId
91
+     * @return bool
92
+     * @throws \OC\HintException
93
+     * @throws \OC\ServerNotAvailableException
94
+     */
95
+    public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
96
+
97
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
98
+
99
+        if ($user && $remote) {
100
+            $local = $this->addressHandler->generateRemoteURL();
101
+
102
+            $fields = array(
103
+                'shareWith' => $user,
104
+                'token' => $token,
105
+                'name' => $name,
106
+                'remoteId' => $remote_id,
107
+                'owner' => $owner,
108
+                'ownerFederatedId' => $ownerFederatedId,
109
+                'sharedBy' => $sharedBy,
110
+                'sharedByFederatedId' => $sharedByFederatedId,
111
+                'remote' => $local,
112
+            );
113
+
114
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
115
+            $status = json_decode($result['result'], true);
116
+
117
+            $ocsStatus = isset($status['ocs']);
118
+            $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
119
+
120
+            if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
121
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
122
+                return true;
123
+            }
124
+
125
+        }
126
+
127
+        return false;
128
+    }
129
+
130
+    /**
131
+     * ask owner to re-share the file with the given user
132
+     *
133
+     * @param string $token
134
+     * @param int $id remote Id
135
+     * @param int $shareId internal share Id
136
+     * @param string $remote remote address of the owner
137
+     * @param string $shareWith
138
+     * @param int $permission
139
+     * @param string $filename
140
+     * @return bool
141
+     * @throws \OC\HintException
142
+     * @throws \OC\ServerNotAvailableException
143
+     */
144
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
145
+
146
+        $fields = array(
147
+            'shareWith' => $shareWith,
148
+            'token' => $token,
149
+            'permission' => $permission,
150
+            'remoteId' => $shareId,
151
+        );
152
+
153
+        $ocmFields = $fields;
154
+        $ocmFields['remoteId'] = $id;
155
+        $ocmFields['localId'] = $shareId;
156
+        $ocmFields['name'] = $filename;
157
+
158
+        $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
159
+        if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
160
+            return [$ocmResult['token'], $ocmResult['providerId']];
161
+        }
162
+
163
+        $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
164
+        $status = json_decode($result['result'], true);
165
+
166
+        $httpRequestSuccessful = $result['success'];
167
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
168
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
169
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
170
+
171
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
172
+            return [
173
+                $status['ocs']['data']['token'],
174
+                (int)$status['ocs']['data']['remoteId']
175
+            ];
176
+        }
177
+
178
+        return false;
179
+    }
180
+
181
+    /**
182
+     * send server-to-server unshare to remote server
183
+     *
184
+     * @param string $remote url
185
+     * @param int $id share id
186
+     * @param string $token
187
+     * @return bool
188
+     */
189
+    public function sendRemoteUnShare($remote, $id, $token) {
190
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
191
+    }
192
+
193
+    /**
194
+     * send server-to-server unshare to remote server
195
+     *
196
+     * @param string $remote url
197
+     * @param int $id share id
198
+     * @param string $token
199
+     * @return bool
200
+     */
201
+    public function sendRevokeShare($remote, $id, $token) {
202
+        $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
203
+    }
204
+
205
+    /**
206
+     * send notification to remote server if the permissions was changed
207
+     *
208
+     * @param string $remote
209
+     * @param int $remoteId
210
+     * @param string $token
211
+     * @param int $permissions
212
+     * @return bool
213
+     */
214
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
215
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
216
+    }
217
+
218
+    /**
219
+     * forward accept reShare to remote server
220
+     *
221
+     * @param string $remote
222
+     * @param int $remoteId
223
+     * @param string $token
224
+     */
225
+    public function sendAcceptShare($remote, $remoteId, $token) {
226
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
227
+    }
228
+
229
+    /**
230
+     * forward decline reShare to remote server
231
+     *
232
+     * @param string $remote
233
+     * @param int $remoteId
234
+     * @param string $token
235
+     */
236
+    public function sendDeclineShare($remote, $remoteId, $token) {
237
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
238
+    }
239
+
240
+    /**
241
+     * inform remote server whether server-to-server share was accepted/declined
242
+     *
243
+     * @param string $remote
244
+     * @param string $token
245
+     * @param int $remoteId Share id on the remote host
246
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
247
+     * @param array $data
248
+     * @param int $try
249
+     * @return boolean
250
+     */
251
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
252
+
253
+        $fields = [
254
+            'token' => $token,
255
+            'remoteId' => $remoteId
256
+            ];
257
+        foreach ($data as $key => $value) {
258
+            $fields[$key] = $value;
259
+        }
260
+
261
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
262
+        $status = json_decode($result['result'], true);
263
+
264
+        if ($result['success'] &&
265
+            ($status['ocs']['meta']['statuscode'] === 100 ||
266
+                $status['ocs']['meta']['statuscode'] === 200
267
+            )
268
+        ) {
269
+            return true;
270
+        } elseif ($try === 0) {
271
+            // only add new job on first try
272
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
273
+                [
274
+                    'remote' => $remote,
275
+                    'remoteId' => $remoteId,
276
+                    'token' => $token,
277
+                    'action' => $action,
278
+                    'data' => json_encode($data),
279
+                    'try' => $try,
280
+                    'lastRun' => $this->getTimestamp()
281
+                ]
282
+            );
283
+        }
284
+
285
+        return false;
286
+    }
287
+
288
+
289
+    /**
290
+     * return current timestamp
291
+     *
292
+     * @return int
293
+     */
294
+    protected function getTimestamp() {
295
+        return time();
296
+    }
297
+
298
+    /**
299
+     * try http post with the given protocol, if no protocol is given we pick
300
+     * the secure one (https)
301
+     *
302
+     * @param string $remoteDomain
303
+     * @param string $urlSuffix
304
+     * @param array $fields post parameters
305
+     * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
306
+     * @return array
307
+     * @throws \Exception
308
+     */
309
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
310
+
311
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
312
+            $remoteDomain = 'https://' . $remoteDomain;
313
+        }
314
+
315
+        $result = [
316
+            'success' => false,
317
+            'result' => '',
318
+        ];
319
+
320
+        // if possible we use the new OCM API
321
+        $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
322
+        if (is_array($ocmResult)) {
323
+            $result['success'] = true;
324
+            $result['result'] = json_encode([
325
+                'ocs' => ['meta' => ['statuscode' => 200]]]);
326
+            return $result;
327
+        }
328
+
329
+        return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
330
+    }
331
+
332
+    /**
333
+     * try old federated sharing API if the OCM api doesn't work
334
+     *
335
+     * @param $remoteDomain
336
+     * @param $urlSuffix
337
+     * @param array $fields
338
+     * @return mixed
339
+     * @throws \Exception
340
+     */
341
+    protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
342
+
343
+        $result = [
344
+            'success' => false,
345
+            'result' => '',
346
+        ];
347
+
348
+        // Fall back to old API
349
+        $client = $this->httpClientService->newClient();
350
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
351
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
352
+        try {
353
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
354
+                'body' => $fields,
355
+                'timeout' => 10,
356
+                'connect_timeout' => 10,
357
+            ]);
358
+            $result['result'] = $response->getBody();
359
+            $result['success'] = true;
360
+        } catch (\Exception $e) {
361
+            // if flat re-sharing is not supported by the remote server
362
+            // we re-throw the exception and fall back to the old behaviour.
363
+            // (flat re-shares has been introduced in Nextcloud 9.1)
364
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
365
+                throw $e;
366
+            }
367
+        }
368
+
369
+        return $result;
370
+
371
+    }
372
+
373
+    /**
374
+     * send action regarding federated sharing to the remote server using the OCM API
375
+     *
376
+     * @param $remoteDomain
377
+     * @param $fields
378
+     * @param $action
379
+     *
380
+     * @return bool
381
+     */
382
+    protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
383
+        switch ($action) {
384
+            case 'share':
385
+                $share = $this->cloudFederationFactory->getCloudFederationShare(
386
+                    $fields['shareWith'] . '@' . $remoteDomain,
387
+                    $fields['name'],
388
+                    '',
389
+                    $fields['remoteId'],
390
+                    $fields['ownerFederatedId'],
391
+                    $fields['owner'],
392
+                    $fields['sharedByFederatedId'],
393
+                    $fields['sharedBy'],
394
+                    $fields['token'],
395
+                    'user',
396
+                    'file'
397
+                );
398
+                return $this->federationProviderManager->sendShare($share);
399
+            case 'reshare':
400
+                // ask owner to reshare a file
401
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
402
+                $notification->setMessage('REQUEST_RESHARE',
403
+                    'file',
404
+                    $fields['remoteId'],
405
+                    [
406
+                        'sharedSecret' => $fields['token'],
407
+                        'shareWith' => $fields['shareWith'],
408
+                        'senderId' => $fields['localId'],
409
+                        'message' => 'Ask owner to reshare the file'
410
+                    ]
411
+                );
412
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
413
+            case 'unshare':
414
+                //owner unshares the file from the recipient again
415
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
416
+                $notification->setMessage('SHARE_UNSHARED',
417
+                    'file',
418
+                    $fields['remoteId'],
419
+                    [
420
+                        'sharedSecret' => $fields['token'],
421
+                        'messgage' => 'file is no longer shared with you'
422
+                    ]
423
+                );
424
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
425
+            case 'reshare_undo':
426
+                // if a reshare was unshared we send the information to the initiator/owner
427
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
428
+                $notification->setMessage('RESHARE_UNDO',
429
+                    'file',
430
+                    $fields['remoteId'],
431
+                    [
432
+                        'sharedSecret' => $fields['token'],
433
+                        'message' => 'reshare was revoked'
434
+                    ]
435
+                );
436
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
437
+        }
438
+
439
+        return false;
440
+
441
+    }
442 442
 }
Please login to merge, or discard this patch.