Completed
Pull Request — master (#5823)
by Björn
17:16
created
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +399 added lines, -399 removed lines patch added patch discarded remove patch
@@ -39,445 +39,445 @@
 block discarded – undo
39 39
 use OCP\OCS\IDiscoveryService;
40 40
 
41 41
 class Manager {
42
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
43
-
44
-	/**
45
-	 * @var string
46
-	 */
47
-	private $uid;
48
-
49
-	/**
50
-	 * @var IDBConnection
51
-	 */
52
-	private $connection;
53
-
54
-	/**
55
-	 * @var \OC\Files\Mount\Manager
56
-	 */
57
-	private $mountManager;
58
-
59
-	/**
60
-	 * @var IStorageFactory
61
-	 */
62
-	private $storageLoader;
63
-
64
-	/**
65
-	 * @var IClientService
66
-	 */
67
-	private $clientService;
68
-
69
-	/**
70
-	 * @var IManager
71
-	 */
72
-	private $notificationManager;
73
-
74
-	/**
75
-	 * @var IDiscoveryService
76
-	 */
77
-	private $discoveryService;
78
-
79
-	/**
80
-	 * @param IDBConnection $connection
81
-	 * @param \OC\Files\Mount\Manager $mountManager
82
-	 * @param IStorageFactory $storageLoader
83
-	 * @param IClientService $clientService
84
-	 * @param IManager $notificationManager
85
-	 * @param IDiscoveryService $discoveryService
86
-	 * @param string $uid
87
-	 */
88
-	public function __construct(IDBConnection $connection,
89
-								\OC\Files\Mount\Manager $mountManager,
90
-								IStorageFactory $storageLoader,
91
-								IClientService $clientService,
92
-								IManager $notificationManager,
93
-								IDiscoveryService $discoveryService,
94
-								$uid) {
95
-		$this->connection = $connection;
96
-		$this->mountManager = $mountManager;
97
-		$this->storageLoader = $storageLoader;
98
-		$this->clientService = $clientService;
99
-		$this->uid = $uid;
100
-		$this->notificationManager = $notificationManager;
101
-		$this->discoveryService = $discoveryService;
102
-	}
103
-
104
-	/**
105
-	 * add new server-to-server share
106
-	 *
107
-	 * @param string $remote
108
-	 * @param string $token
109
-	 * @param string $password
110
-	 * @param string $name
111
-	 * @param string $owner
112
-	 * @param boolean $accepted
113
-	 * @param string $user
114
-	 * @param int $remoteId
115
-	 * @return Mount|null
116
-	 */
117
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
118
-
119
-		$user = $user ? $user : $this->uid;
120
-		$accepted = $accepted ? 1 : 0;
121
-		$name = Filesystem::normalizePath('/' . $name);
122
-
123
-		if (!$accepted) {
124
-			// To avoid conflicts with the mount point generation later,
125
-			// we only use a temporary mount point name here. The real
126
-			// mount point name will be generated when accepting the share,
127
-			// using the original share item name.
128
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
129
-			$mountPoint = $tmpMountPointName;
130
-			$hash = md5($tmpMountPointName);
131
-			$data = [
132
-				'remote'		=> $remote,
133
-				'share_token'	=> $token,
134
-				'password'		=> $password,
135
-				'name'			=> $name,
136
-				'owner'			=> $owner,
137
-				'user'			=> $user,
138
-				'mountpoint'	=> $mountPoint,
139
-				'mountpoint_hash'	=> $hash,
140
-				'accepted'		=> $accepted,
141
-				'remote_id'		=> $remoteId,
142
-			];
143
-
144
-			$i = 1;
145
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
146
-				// The external share already exists for the user
147
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
148
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
149
-				$i++;
150
-			}
151
-			return null;
152
-		}
153
-
154
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
155
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
156
-		$hash = md5($mountPoint);
157
-
158
-		$query = $this->connection->prepare('
42
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
43
+
44
+    /**
45
+     * @var string
46
+     */
47
+    private $uid;
48
+
49
+    /**
50
+     * @var IDBConnection
51
+     */
52
+    private $connection;
53
+
54
+    /**
55
+     * @var \OC\Files\Mount\Manager
56
+     */
57
+    private $mountManager;
58
+
59
+    /**
60
+     * @var IStorageFactory
61
+     */
62
+    private $storageLoader;
63
+
64
+    /**
65
+     * @var IClientService
66
+     */
67
+    private $clientService;
68
+
69
+    /**
70
+     * @var IManager
71
+     */
72
+    private $notificationManager;
73
+
74
+    /**
75
+     * @var IDiscoveryService
76
+     */
77
+    private $discoveryService;
78
+
79
+    /**
80
+     * @param IDBConnection $connection
81
+     * @param \OC\Files\Mount\Manager $mountManager
82
+     * @param IStorageFactory $storageLoader
83
+     * @param IClientService $clientService
84
+     * @param IManager $notificationManager
85
+     * @param IDiscoveryService $discoveryService
86
+     * @param string $uid
87
+     */
88
+    public function __construct(IDBConnection $connection,
89
+                                \OC\Files\Mount\Manager $mountManager,
90
+                                IStorageFactory $storageLoader,
91
+                                IClientService $clientService,
92
+                                IManager $notificationManager,
93
+                                IDiscoveryService $discoveryService,
94
+                                $uid) {
95
+        $this->connection = $connection;
96
+        $this->mountManager = $mountManager;
97
+        $this->storageLoader = $storageLoader;
98
+        $this->clientService = $clientService;
99
+        $this->uid = $uid;
100
+        $this->notificationManager = $notificationManager;
101
+        $this->discoveryService = $discoveryService;
102
+    }
103
+
104
+    /**
105
+     * add new server-to-server share
106
+     *
107
+     * @param string $remote
108
+     * @param string $token
109
+     * @param string $password
110
+     * @param string $name
111
+     * @param string $owner
112
+     * @param boolean $accepted
113
+     * @param string $user
114
+     * @param int $remoteId
115
+     * @return Mount|null
116
+     */
117
+    public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
118
+
119
+        $user = $user ? $user : $this->uid;
120
+        $accepted = $accepted ? 1 : 0;
121
+        $name = Filesystem::normalizePath('/' . $name);
122
+
123
+        if (!$accepted) {
124
+            // To avoid conflicts with the mount point generation later,
125
+            // we only use a temporary mount point name here. The real
126
+            // mount point name will be generated when accepting the share,
127
+            // using the original share item name.
128
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
129
+            $mountPoint = $tmpMountPointName;
130
+            $hash = md5($tmpMountPointName);
131
+            $data = [
132
+                'remote'		=> $remote,
133
+                'share_token'	=> $token,
134
+                'password'		=> $password,
135
+                'name'			=> $name,
136
+                'owner'			=> $owner,
137
+                'user'			=> $user,
138
+                'mountpoint'	=> $mountPoint,
139
+                'mountpoint_hash'	=> $hash,
140
+                'accepted'		=> $accepted,
141
+                'remote_id'		=> $remoteId,
142
+            ];
143
+
144
+            $i = 1;
145
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
146
+                // The external share already exists for the user
147
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
148
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
149
+                $i++;
150
+            }
151
+            return null;
152
+        }
153
+
154
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
155
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
156
+        $hash = md5($mountPoint);
157
+
158
+        $query = $this->connection->prepare('
159 159
 				INSERT INTO `*PREFIX*share_external`
160 160
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`)
161 161
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
162 162
 			');
163
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
164
-
165
-		$options = array(
166
-			'remote'	=> $remote,
167
-			'token'		=> $token,
168
-			'password'	=> $password,
169
-			'mountpoint'	=> $mountPoint,
170
-			'owner'		=> $owner
171
-		);
172
-		return $this->mountShare($options);
173
-	}
174
-
175
-	/**
176
-	 * get share
177
-	 *
178
-	 * @param int $id share id
179
-	 * @return mixed share of false
180
-	 */
181
-	public function getShare($id) {
182
-		$getShare = $this->connection->prepare('
163
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
164
+
165
+        $options = array(
166
+            'remote'	=> $remote,
167
+            'token'		=> $token,
168
+            'password'	=> $password,
169
+            'mountpoint'	=> $mountPoint,
170
+            'owner'		=> $owner
171
+        );
172
+        return $this->mountShare($options);
173
+    }
174
+
175
+    /**
176
+     * get share
177
+     *
178
+     * @param int $id share id
179
+     * @return mixed share of false
180
+     */
181
+    public function getShare($id) {
182
+        $getShare = $this->connection->prepare('
183 183
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
184 184
 			FROM  `*PREFIX*share_external`
185 185
 			WHERE `id` = ? AND `user` = ?');
186
-		$result = $getShare->execute(array($id, $this->uid));
187
-
188
-		return $result ? $getShare->fetch() : false;
189
-	}
190
-
191
-	/**
192
-	 * accept server-to-server share
193
-	 *
194
-	 * @param int $id
195
-	 * @return bool True if the share could be accepted, false otherwise
196
-	 */
197
-	public function acceptShare($id) {
198
-
199
-		$share = $this->getShare($id);
200
-		$result = false;
201
-
202
-		if ($share) {
203
-			\OC_Util::setupFS($this->uid);
204
-			$shareFolder = Helper::getShareFolder();
205
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
206
-			$mountPoint = Filesystem::normalizePath($mountPoint);
207
-			$hash = md5($mountPoint);
208
-
209
-			$acceptShare = $this->connection->prepare('
186
+        $result = $getShare->execute(array($id, $this->uid));
187
+
188
+        return $result ? $getShare->fetch() : false;
189
+    }
190
+
191
+    /**
192
+     * accept server-to-server share
193
+     *
194
+     * @param int $id
195
+     * @return bool True if the share could be accepted, false otherwise
196
+     */
197
+    public function acceptShare($id) {
198
+
199
+        $share = $this->getShare($id);
200
+        $result = false;
201
+
202
+        if ($share) {
203
+            \OC_Util::setupFS($this->uid);
204
+            $shareFolder = Helper::getShareFolder();
205
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
206
+            $mountPoint = Filesystem::normalizePath($mountPoint);
207
+            $hash = md5($mountPoint);
208
+
209
+            $acceptShare = $this->connection->prepare('
210 210
 				UPDATE `*PREFIX*share_external`
211 211
 				SET `accepted` = ?,
212 212
 					`mountpoint` = ?,
213 213
 					`mountpoint_hash` = ?
214 214
 				WHERE `id` = ? AND `user` = ?');
215
-			$updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
216
-			if ($updated === true) {
217
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
218
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]);
219
-				$result = true;
220
-			}
221
-		}
222
-
223
-		// Make sure the user has no notification for something that does not exist anymore.
224
-		$this->processNotification($id);
225
-
226
-		return $result;
227
-	}
228
-
229
-	/**
230
-	 * decline server-to-server share
231
-	 *
232
-	 * @param int $id
233
-	 * @return bool True if the share could be declined, false otherwise
234
-	 */
235
-	public function declineShare($id) {
236
-
237
-		$share = $this->getShare($id);
238
-
239
-		if ($share) {
240
-			$removeShare = $this->connection->prepare('
215
+            $updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
216
+            if ($updated === true) {
217
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
218
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $share['remote']]);
219
+                $result = true;
220
+            }
221
+        }
222
+
223
+        // Make sure the user has no notification for something that does not exist anymore.
224
+        $this->processNotification($id);
225
+
226
+        return $result;
227
+    }
228
+
229
+    /**
230
+     * decline server-to-server share
231
+     *
232
+     * @param int $id
233
+     * @return bool True if the share could be declined, false otherwise
234
+     */
235
+    public function declineShare($id) {
236
+
237
+        $share = $this->getShare($id);
238
+
239
+        if ($share) {
240
+            $removeShare = $this->connection->prepare('
241 241
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
242
-			$removeShare->execute(array($id, $this->uid));
243
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
244
-
245
-			$this->processNotification($id);
246
-			return true;
247
-		}
248
-
249
-		return false;
250
-	}
251
-
252
-	/**
253
-	 * @param int $remoteShare
254
-	 */
255
-	public function processNotification($remoteShare) {
256
-		$filter = $this->notificationManager->createNotification();
257
-		$filter->setApp('files_sharing')
258
-			->setUser($this->uid)
259
-			->setObject('remote_share', (int) $remoteShare);
260
-		$this->notificationManager->markProcessed($filter);
261
-	}
262
-
263
-	/**
264
-	 * inform remote server whether server-to-server share was accepted/declined
265
-	 *
266
-	 * @param string $remote
267
-	 * @param string $token
268
-	 * @param int $remoteId Share id on the remote host
269
-	 * @param string $feedback
270
-	 * @return boolean
271
-	 */
272
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
273
-
274
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
275
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
276
-
277
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
278
-		$fields = array('token' => $token);
279
-
280
-		$client = $this->clientService->newClient();
281
-
282
-		try {
283
-			$response = $client->post(
284
-				$url,
285
-				[
286
-					'body' => $fields,
287
-					'connect_timeout' => 10,
288
-				]
289
-			);
290
-		} catch (\Exception $e) {
291
-			return false;
292
-		}
293
-
294
-		$status = json_decode($response->getBody(), true);
295
-
296
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
297
-	}
298
-
299
-	/**
300
-	 * remove '/user/files' from the path and trailing slashes
301
-	 *
302
-	 * @param string $path
303
-	 * @return string
304
-	 */
305
-	protected function stripPath($path) {
306
-		$prefix = '/' . $this->uid . '/files';
307
-		return rtrim(substr($path, strlen($prefix)), '/');
308
-	}
309
-
310
-	public function getMount($data) {
311
-		$data['manager'] = $this;
312
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
313
-		$data['mountpoint'] = $mountPoint;
314
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
315
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
316
-	}
317
-
318
-	/**
319
-	 * @param array $data
320
-	 * @return Mount
321
-	 */
322
-	protected function mountShare($data) {
323
-		$mount = $this->getMount($data);
324
-		$this->mountManager->addMount($mount);
325
-		return $mount;
326
-	}
327
-
328
-	/**
329
-	 * @return \OC\Files\Mount\Manager
330
-	 */
331
-	public function getMountManager() {
332
-		return $this->mountManager;
333
-	}
334
-
335
-	/**
336
-	 * @param string $source
337
-	 * @param string $target
338
-	 * @return bool
339
-	 */
340
-	public function setMountPoint($source, $target) {
341
-		$source = $this->stripPath($source);
342
-		$target = $this->stripPath($target);
343
-		$sourceHash = md5($source);
344
-		$targetHash = md5($target);
345
-
346
-		$query = $this->connection->prepare('
242
+            $removeShare->execute(array($id, $this->uid));
243
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
244
+
245
+            $this->processNotification($id);
246
+            return true;
247
+        }
248
+
249
+        return false;
250
+    }
251
+
252
+    /**
253
+     * @param int $remoteShare
254
+     */
255
+    public function processNotification($remoteShare) {
256
+        $filter = $this->notificationManager->createNotification();
257
+        $filter->setApp('files_sharing')
258
+            ->setUser($this->uid)
259
+            ->setObject('remote_share', (int) $remoteShare);
260
+        $this->notificationManager->markProcessed($filter);
261
+    }
262
+
263
+    /**
264
+     * inform remote server whether server-to-server share was accepted/declined
265
+     *
266
+     * @param string $remote
267
+     * @param string $token
268
+     * @param int $remoteId Share id on the remote host
269
+     * @param string $feedback
270
+     * @return boolean
271
+     */
272
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
273
+
274
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
275
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
276
+
277
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
278
+        $fields = array('token' => $token);
279
+
280
+        $client = $this->clientService->newClient();
281
+
282
+        try {
283
+            $response = $client->post(
284
+                $url,
285
+                [
286
+                    'body' => $fields,
287
+                    'connect_timeout' => 10,
288
+                ]
289
+            );
290
+        } catch (\Exception $e) {
291
+            return false;
292
+        }
293
+
294
+        $status = json_decode($response->getBody(), true);
295
+
296
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
297
+    }
298
+
299
+    /**
300
+     * remove '/user/files' from the path and trailing slashes
301
+     *
302
+     * @param string $path
303
+     * @return string
304
+     */
305
+    protected function stripPath($path) {
306
+        $prefix = '/' . $this->uid . '/files';
307
+        return rtrim(substr($path, strlen($prefix)), '/');
308
+    }
309
+
310
+    public function getMount($data) {
311
+        $data['manager'] = $this;
312
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
313
+        $data['mountpoint'] = $mountPoint;
314
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
315
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
316
+    }
317
+
318
+    /**
319
+     * @param array $data
320
+     * @return Mount
321
+     */
322
+    protected function mountShare($data) {
323
+        $mount = $this->getMount($data);
324
+        $this->mountManager->addMount($mount);
325
+        return $mount;
326
+    }
327
+
328
+    /**
329
+     * @return \OC\Files\Mount\Manager
330
+     */
331
+    public function getMountManager() {
332
+        return $this->mountManager;
333
+    }
334
+
335
+    /**
336
+     * @param string $source
337
+     * @param string $target
338
+     * @return bool
339
+     */
340
+    public function setMountPoint($source, $target) {
341
+        $source = $this->stripPath($source);
342
+        $target = $this->stripPath($target);
343
+        $sourceHash = md5($source);
344
+        $targetHash = md5($target);
345
+
346
+        $query = $this->connection->prepare('
347 347
 			UPDATE `*PREFIX*share_external`
348 348
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
349 349
 			WHERE `mountpoint_hash` = ?
350 350
 			AND `user` = ?
351 351
 		');
352
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
352
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
353 353
 
354
-		return $result;
355
-	}
354
+        return $result;
355
+    }
356 356
 
357
-	public function removeShare($mountPoint) {
357
+    public function removeShare($mountPoint) {
358 358
 
359
-		$mountPointObj = $this->mountManager->find($mountPoint);
360
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
359
+        $mountPointObj = $this->mountManager->find($mountPoint);
360
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
361 361
 
362
-		$mountPoint = $this->stripPath($mountPoint);
363
-		$hash = md5($mountPoint);
362
+        $mountPoint = $this->stripPath($mountPoint);
363
+        $hash = md5($mountPoint);
364 364
 
365
-		$getShare = $this->connection->prepare('
365
+        $getShare = $this->connection->prepare('
366 366
 			SELECT `remote`, `share_token`, `remote_id`
367 367
 			FROM  `*PREFIX*share_external`
368 368
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
369
-		$result = $getShare->execute(array($hash, $this->uid));
369
+        $result = $getShare->execute(array($hash, $this->uid));
370 370
 
371
-		if ($result) {
372
-			$share = $getShare->fetch();
373
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
374
-		}
375
-		$getShare->closeCursor();
371
+        if ($result) {
372
+            $share = $getShare->fetch();
373
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
374
+        }
375
+        $getShare->closeCursor();
376 376
 
377
-		$query = $this->connection->prepare('
377
+        $query = $this->connection->prepare('
378 378
 			DELETE FROM `*PREFIX*share_external`
379 379
 			WHERE `mountpoint_hash` = ?
380 380
 			AND `user` = ?
381 381
 		');
382
-		$result = (bool)$query->execute(array($hash, $this->uid));
383
-
384
-		if($result) {
385
-			$this->removeReShares($id);
386
-		}
387
-
388
-		return $result;
389
-	}
390
-
391
-	/**
392
-	 * remove re-shares from share table and mapping in the federated_reshares table
393
-	 *
394
-	 * @param $mountPointId
395
-	 */
396
-	protected function removeReShares($mountPointId) {
397
-		$selectQuery = $this->connection->getQueryBuilder();
398
-		$query = $this->connection->getQueryBuilder();
399
-		$selectQuery->select('id')->from('share')
400
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
401
-		$select = $selectQuery->getSQL();
402
-
403
-
404
-		$query->delete('federated_reshares')
405
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
406
-		$query->execute();
407
-
408
-		$deleteReShares = $this->connection->getQueryBuilder();
409
-		$deleteReShares->delete('share')
410
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
411
-		$deleteReShares->execute();
412
-	}
413
-
414
-	/**
415
-	 * remove all shares for user $uid if the user was deleted
416
-	 *
417
-	 * @param string $uid
418
-	 * @return bool
419
-	 */
420
-	public function removeUserShares($uid) {
421
-		$getShare = $this->connection->prepare('
382
+        $result = (bool)$query->execute(array($hash, $this->uid));
383
+
384
+        if($result) {
385
+            $this->removeReShares($id);
386
+        }
387
+
388
+        return $result;
389
+    }
390
+
391
+    /**
392
+     * remove re-shares from share table and mapping in the federated_reshares table
393
+     *
394
+     * @param $mountPointId
395
+     */
396
+    protected function removeReShares($mountPointId) {
397
+        $selectQuery = $this->connection->getQueryBuilder();
398
+        $query = $this->connection->getQueryBuilder();
399
+        $selectQuery->select('id')->from('share')
400
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
401
+        $select = $selectQuery->getSQL();
402
+
403
+
404
+        $query->delete('federated_reshares')
405
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
406
+        $query->execute();
407
+
408
+        $deleteReShares = $this->connection->getQueryBuilder();
409
+        $deleteReShares->delete('share')
410
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
411
+        $deleteReShares->execute();
412
+    }
413
+
414
+    /**
415
+     * remove all shares for user $uid if the user was deleted
416
+     *
417
+     * @param string $uid
418
+     * @return bool
419
+     */
420
+    public function removeUserShares($uid) {
421
+        $getShare = $this->connection->prepare('
422 422
 			SELECT `remote`, `share_token`, `remote_id`
423 423
 			FROM  `*PREFIX*share_external`
424 424
 			WHERE `user` = ?');
425
-		$result = $getShare->execute(array($uid));
425
+        $result = $getShare->execute(array($uid));
426 426
 
427
-		if ($result) {
428
-			$shares = $getShare->fetchAll();
429
-			foreach($shares as $share) {
430
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
431
-			}
432
-		}
427
+        if ($result) {
428
+            $shares = $getShare->fetchAll();
429
+            foreach($shares as $share) {
430
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
431
+            }
432
+        }
433 433
 
434
-		$query = $this->connection->prepare('
434
+        $query = $this->connection->prepare('
435 435
 			DELETE FROM `*PREFIX*share_external`
436 436
 			WHERE `user` = ?
437 437
 		');
438
-		return (bool)$query->execute(array($uid));
439
-	}
440
-
441
-	/**
442
-	 * return a list of shares which are not yet accepted by the user
443
-	 *
444
-	 * @return array list of open server-to-server shares
445
-	 */
446
-	public function getOpenShares() {
447
-		return $this->getShares(false);
448
-	}
449
-
450
-	/**
451
-	 * return a list of shares which are accepted by the user
452
-	 *
453
-	 * @return array list of accepted server-to-server shares
454
-	 */
455
-	public function getAcceptedShares() {
456
-		return $this->getShares(true);
457
-	}
458
-
459
-	/**
460
-	 * return a list of shares for the user
461
-	 *
462
-	 * @param bool|null $accepted True for accepted only,
463
-	 *                            false for not accepted,
464
-	 *                            null for all shares of the user
465
-	 * @return array list of open server-to-server shares
466
-	 */
467
-	private function getShares($accepted) {
468
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
438
+        return (bool)$query->execute(array($uid));
439
+    }
440
+
441
+    /**
442
+     * return a list of shares which are not yet accepted by the user
443
+     *
444
+     * @return array list of open server-to-server shares
445
+     */
446
+    public function getOpenShares() {
447
+        return $this->getShares(false);
448
+    }
449
+
450
+    /**
451
+     * return a list of shares which are accepted by the user
452
+     *
453
+     * @return array list of accepted server-to-server shares
454
+     */
455
+    public function getAcceptedShares() {
456
+        return $this->getShares(true);
457
+    }
458
+
459
+    /**
460
+     * return a list of shares for the user
461
+     *
462
+     * @param bool|null $accepted True for accepted only,
463
+     *                            false for not accepted,
464
+     *                            null for all shares of the user
465
+     * @return array list of open server-to-server shares
466
+     */
467
+    private function getShares($accepted) {
468
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
469 469
 		          FROM `*PREFIX*share_external` 
470 470
 				  WHERE `user` = ?';
471
-		$parameters = [$this->uid];
472
-		if (!is_null($accepted)) {
473
-			$query .= ' AND `accepted` = ?';
474
-			$parameters[] = (int) $accepted;
475
-		}
476
-		$query .= ' ORDER BY `id` ASC';
477
-
478
-		$shares = $this->connection->prepare($query);
479
-		$result = $shares->execute($parameters);
480
-
481
-		return $result ? $shares->fetchAll() : [];
482
-	}
471
+        $parameters = [$this->uid];
472
+        if (!is_null($accepted)) {
473
+            $query .= ' AND `accepted` = ?';
474
+            $parameters[] = (int) $accepted;
475
+        }
476
+        $query .= ' ORDER BY `id` ASC';
477
+
478
+        $shares = $this->connection->prepare($query);
479
+        $result = $shares->execute($parameters);
480
+
481
+        return $result ? $shares->fetchAll() : [];
482
+    }
483 483
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/RemoteController.php 2 patches
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -34,156 +34,156 @@
 block discarded – undo
34 34
 
35 35
 class RemoteController extends OCSController {
36 36
 
37
-	/** @var Manager */
38
-	private $externalManager;
39
-
40
-	/** @var ILogger */
41
-	private $logger;
42
-
43
-	/**
44
-	 * @NoAdminRequired
45
-	 *
46
-	 * Remote constructor.
47
-	 *
48
-	 * @param string $appName
49
-	 * @param IRequest $request
50
-	 * @param Manager $externalManager
51
-	 */
52
-	public function __construct($appName,
53
-								IRequest $request,
54
-								Manager $externalManager,
55
-								ILogger $logger) {
56
-		parent::__construct($appName, $request);
57
-
58
-		$this->externalManager = $externalManager;
59
-		$this->logger = $logger;
60
-	}
61
-
62
-	/**
63
-	 * @NoAdminRequired
64
-	 *
65
-	 * Get list of pending remote shares
66
-	 *
67
-	 * @return DataResponse
68
-	 */
69
-	public function getOpenShares() {
70
-		return new DataResponse($this->externalManager->getOpenShares());
71
-	}
72
-
73
-	/**
74
-	 * @NoAdminRequired
75
-	 *
76
-	 * Accept a remote share
77
-	 *
78
-	 * @param int $id
79
-	 * @return DataResponse
80
-	 * @throws OCSNotFoundException
81
-	 */
82
-	public function acceptShare($id) {
83
-		if ($this->externalManager->acceptShare($id)) {
84
-			return new DataResponse();
85
-		}
86
-
87
-		$this->logger->error('Could not accept federated share with id: ' . $id,
88
-			['app' => 'files_sharing']);
89
-
90
-		throw new OCSNotFoundException('wrong share ID, share doesn\'t exist.');
91
-	}
92
-
93
-	/**
94
-	 * @NoAdminRequired
95
-	 *
96
-	 * Decline a remote share
97
-	 *
98
-	 * @param int $id
99
-	 * @return DataResponse
100
-	 * @throws OCSNotFoundException
101
-	 */
102
-	public function declineShare($id) {
103
-		if ($this->externalManager->declineShare($id)) {
104
-			return new DataResponse();
105
-		}
106
-
107
-		// Make sure the user has no notification for something that does not exist anymore.
108
-		$this->externalManager->processNotification($id);
109
-
110
-		throw new OCSNotFoundException('wrong share ID, share doesn\'t exist.');
111
-	}
112
-
113
-	/**
114
-	 * @param array $share Share with info from the share_external table
115
-	 * @return array enriched share info with data from the filecache
116
-	 */
117
-	private static function extendShareInfo($share) {
118
-		$view = new \OC\Files\View('/' . \OC_User::getUser() . '/files/');
119
-		$info = $view->getFileInfo($share['mountpoint']);
120
-
121
-		$share['mimetype'] = $info->getMimetype();
122
-		$share['mtime'] = $info->getMTime();
123
-		$share['permissions'] = $info->getPermissions();
124
-		$share['type'] = $info->getType();
125
-		$share['file_id'] = $info->getId();
126
-
127
-		return $share;
128
-	}
129
-
130
-	/**
131
-	 * @NoAdminRequired
132
-	 *
133
-	 * List accepted remote shares
134
-	 *
135
-	 * @return DataResponse
136
-	 */
137
-	public function getShares() {
138
-		$shares = $this->externalManager->getAcceptedShares();
139
-		$shares = array_map('self::extendShareInfo', $shares);
140
-
141
-		return new DataResponse($shares);
142
-	}
143
-
144
-	/**
145
-	 * @NoAdminRequired
146
-	 *
147
-	 * Get info of a remote share
148
-	 *
149
-	 * @param int $id
150
-	 * @return DataResponse
151
-	 * @throws OCSNotFoundException
152
-	 */
153
-	public function getShare($id) {
154
-		$shareInfo = $this->externalManager->getShare($id);
155
-
156
-		if ($shareInfo === false) {
157
-			throw new OCSNotFoundException('share does not exist');
158
-		} else {
159
-			$shareInfo = self::extendShareInfo($shareInfo);
160
-			return new DataResponse($shareInfo);
161
-		}
162
-	}
163
-
164
-	/**
165
-	 * @NoAdminRequired
166
-	 *
167
-	 * Unshare a remote share
168
-	 *
169
-	 * @param int $id
170
-	 * @return DataResponse
171
-	 * @throws OCSNotFoundException
172
-	 * @throws OCSForbiddenException
173
-	 */
174
-	public function unshare($id) {
175
-		$shareInfo = $this->externalManager->getShare($id);
176
-
177
-		if ($shareInfo === false) {
178
-			throw new OCSNotFoundException('Share does not exist');
179
-		}
180
-
181
-		$mountPoint = '/' . \OC_User::getUser() . '/files' . $shareInfo['mountpoint'];
182
-
183
-		if ($this->externalManager->removeShare($mountPoint) === true) {
184
-			return new DataResponse();
185
-		} else {
186
-			throw new OCSForbiddenException('Could not unshare');
187
-		}
188
-	}
37
+    /** @var Manager */
38
+    private $externalManager;
39
+
40
+    /** @var ILogger */
41
+    private $logger;
42
+
43
+    /**
44
+     * @NoAdminRequired
45
+     *
46
+     * Remote constructor.
47
+     *
48
+     * @param string $appName
49
+     * @param IRequest $request
50
+     * @param Manager $externalManager
51
+     */
52
+    public function __construct($appName,
53
+                                IRequest $request,
54
+                                Manager $externalManager,
55
+                                ILogger $logger) {
56
+        parent::__construct($appName, $request);
57
+
58
+        $this->externalManager = $externalManager;
59
+        $this->logger = $logger;
60
+    }
61
+
62
+    /**
63
+     * @NoAdminRequired
64
+     *
65
+     * Get list of pending remote shares
66
+     *
67
+     * @return DataResponse
68
+     */
69
+    public function getOpenShares() {
70
+        return new DataResponse($this->externalManager->getOpenShares());
71
+    }
72
+
73
+    /**
74
+     * @NoAdminRequired
75
+     *
76
+     * Accept a remote share
77
+     *
78
+     * @param int $id
79
+     * @return DataResponse
80
+     * @throws OCSNotFoundException
81
+     */
82
+    public function acceptShare($id) {
83
+        if ($this->externalManager->acceptShare($id)) {
84
+            return new DataResponse();
85
+        }
86
+
87
+        $this->logger->error('Could not accept federated share with id: ' . $id,
88
+            ['app' => 'files_sharing']);
89
+
90
+        throw new OCSNotFoundException('wrong share ID, share doesn\'t exist.');
91
+    }
92
+
93
+    /**
94
+     * @NoAdminRequired
95
+     *
96
+     * Decline a remote share
97
+     *
98
+     * @param int $id
99
+     * @return DataResponse
100
+     * @throws OCSNotFoundException
101
+     */
102
+    public function declineShare($id) {
103
+        if ($this->externalManager->declineShare($id)) {
104
+            return new DataResponse();
105
+        }
106
+
107
+        // Make sure the user has no notification for something that does not exist anymore.
108
+        $this->externalManager->processNotification($id);
109
+
110
+        throw new OCSNotFoundException('wrong share ID, share doesn\'t exist.');
111
+    }
112
+
113
+    /**
114
+     * @param array $share Share with info from the share_external table
115
+     * @return array enriched share info with data from the filecache
116
+     */
117
+    private static function extendShareInfo($share) {
118
+        $view = new \OC\Files\View('/' . \OC_User::getUser() . '/files/');
119
+        $info = $view->getFileInfo($share['mountpoint']);
120
+
121
+        $share['mimetype'] = $info->getMimetype();
122
+        $share['mtime'] = $info->getMTime();
123
+        $share['permissions'] = $info->getPermissions();
124
+        $share['type'] = $info->getType();
125
+        $share['file_id'] = $info->getId();
126
+
127
+        return $share;
128
+    }
129
+
130
+    /**
131
+     * @NoAdminRequired
132
+     *
133
+     * List accepted remote shares
134
+     *
135
+     * @return DataResponse
136
+     */
137
+    public function getShares() {
138
+        $shares = $this->externalManager->getAcceptedShares();
139
+        $shares = array_map('self::extendShareInfo', $shares);
140
+
141
+        return new DataResponse($shares);
142
+    }
143
+
144
+    /**
145
+     * @NoAdminRequired
146
+     *
147
+     * Get info of a remote share
148
+     *
149
+     * @param int $id
150
+     * @return DataResponse
151
+     * @throws OCSNotFoundException
152
+     */
153
+    public function getShare($id) {
154
+        $shareInfo = $this->externalManager->getShare($id);
155
+
156
+        if ($shareInfo === false) {
157
+            throw new OCSNotFoundException('share does not exist');
158
+        } else {
159
+            $shareInfo = self::extendShareInfo($shareInfo);
160
+            return new DataResponse($shareInfo);
161
+        }
162
+    }
163
+
164
+    /**
165
+     * @NoAdminRequired
166
+     *
167
+     * Unshare a remote share
168
+     *
169
+     * @param int $id
170
+     * @return DataResponse
171
+     * @throws OCSNotFoundException
172
+     * @throws OCSForbiddenException
173
+     */
174
+    public function unshare($id) {
175
+        $shareInfo = $this->externalManager->getShare($id);
176
+
177
+        if ($shareInfo === false) {
178
+            throw new OCSNotFoundException('Share does not exist');
179
+        }
180
+
181
+        $mountPoint = '/' . \OC_User::getUser() . '/files' . $shareInfo['mountpoint'];
182
+
183
+        if ($this->externalManager->removeShare($mountPoint) === true) {
184
+            return new DataResponse();
185
+        } else {
186
+            throw new OCSForbiddenException('Could not unshare');
187
+        }
188
+    }
189 189
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 			return new DataResponse();
85 85
 		}
86 86
 
87
-		$this->logger->error('Could not accept federated share with id: ' . $id,
87
+		$this->logger->error('Could not accept federated share with id: '.$id,
88 88
 			['app' => 'files_sharing']);
89 89
 
90 90
 		throw new OCSNotFoundException('wrong share ID, share doesn\'t exist.');
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 	 * @return array enriched share info with data from the filecache
116 116
 	 */
117 117
 	private static function extendShareInfo($share) {
118
-		$view = new \OC\Files\View('/' . \OC_User::getUser() . '/files/');
118
+		$view = new \OC\Files\View('/'.\OC_User::getUser().'/files/');
119 119
 		$info = $view->getFileInfo($share['mountpoint']);
120 120
 
121 121
 		$share['mimetype'] = $info->getMimetype();
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 			throw new OCSNotFoundException('Share does not exist');
179 179
 		}
180 180
 
181
-		$mountPoint = '/' . \OC_User::getUser() . '/files' . $shareInfo['mountpoint'];
181
+		$mountPoint = '/'.\OC_User::getUser().'/files'.$shareInfo['mountpoint'];
182 182
 
183 183
 		if ($this->externalManager->removeShare($mountPoint) === true) {
184 184
 			return new DataResponse();
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 2 patches
Indentation   +607 added lines, -607 removed lines patch added patch discarded remove patch
@@ -47,611 +47,611 @@
 block discarded – undo
47 47
 
48 48
 class RequestHandlerController extends OCSController {
49 49
 
50
-	/** @var FederatedShareProvider */
51
-	private $federatedShareProvider;
52
-
53
-	/** @var IDBConnection */
54
-	private $connection;
55
-
56
-	/** @var Share\IManager */
57
-	private $shareManager;
58
-
59
-	/** @var Notifications */
60
-	private $notifications;
61
-
62
-	/** @var AddressHandler */
63
-	private $addressHandler;
64
-
65
-	/** @var  IUserManager */
66
-	private $userManager;
67
-
68
-	/** @var string */
69
-	private $shareTable = 'share';
70
-
71
-	/** @var ICloudIdManager */
72
-	private $cloudIdManager;
73
-
74
-	/**
75
-	 * Server2Server constructor.
76
-	 *
77
-	 * @param string $appName
78
-	 * @param IRequest $request
79
-	 * @param FederatedShareProvider $federatedShareProvider
80
-	 * @param IDBConnection $connection
81
-	 * @param Share\IManager $shareManager
82
-	 * @param Notifications $notifications
83
-	 * @param AddressHandler $addressHandler
84
-	 * @param IUserManager $userManager
85
-	 * @param ICloudIdManager $cloudIdManager
86
-	 */
87
-	public function __construct($appName,
88
-								IRequest $request,
89
-								FederatedShareProvider $federatedShareProvider,
90
-								IDBConnection $connection,
91
-								Share\IManager $shareManager,
92
-								Notifications $notifications,
93
-								AddressHandler $addressHandler,
94
-								IUserManager $userManager,
95
-								ICloudIdManager $cloudIdManager
96
-	) {
97
-		parent::__construct($appName, $request);
98
-
99
-		$this->federatedShareProvider = $federatedShareProvider;
100
-		$this->connection = $connection;
101
-		$this->shareManager = $shareManager;
102
-		$this->notifications = $notifications;
103
-		$this->addressHandler = $addressHandler;
104
-		$this->userManager = $userManager;
105
-		$this->cloudIdManager = $cloudIdManager;
106
-	}
107
-
108
-	/**
109
-	 * @NoCSRFRequired
110
-	 * @PublicPage
111
-	 *
112
-	 * create a new share
113
-	 *
114
-	 * @return Http\DataResponse
115
-	 * @throws OCSException
116
-	 */
117
-	public function createShare() {
118
-
119
-		if (!$this->isS2SEnabled(true)) {
120
-			throw new OCSException('Server does not support federated cloud sharing', 503);
121
-		}
122
-
123
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
124
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
125
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
126
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
127
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
128
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
129
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
130
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
131
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
132
-
133
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
134
-
135
-			if (!\OCP\Util::isValidFileName($name)) {
136
-				throw new OCSException('The mountpoint name contains invalid characters.', 400);
137
-			}
138
-
139
-			// FIXME this should be a method in the user management instead
140
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
141
-			\OCP\Util::emitHook(
142
-				'\OCA\Files_Sharing\API\Server2Server',
143
-				'preLoginNameUsedAsUserName',
144
-				array('uid' => &$shareWith)
145
-			);
146
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
147
-
148
-			if (!\OCP\User::userExists($shareWith)) {
149
-				throw new OCSException('User does not exists', 400);
150
-			}
151
-
152
-			\OC_Util::setupFS($shareWith);
153
-
154
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
155
-					\OC::$server->getDatabaseConnection(),
156
-					\OC\Files\Filesystem::getMountManager(),
157
-					\OC\Files\Filesystem::getLoader(),
158
-					\OC::$server->getHTTPClientService(),
159
-					\OC::$server->getNotificationManager(),
160
-					\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
161
-					$shareWith
162
-				);
163
-
164
-			try {
165
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
166
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
167
-
168
-				if ($ownerFederatedId === null) {
169
-					$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
170
-				}
171
-				// if the owner of the share and the initiator are the same user
172
-				// we also complete the federated share ID for the initiator
173
-				if ($sharedByFederatedId === null && $owner === $sharedBy) {
174
-					$sharedByFederatedId = $ownerFederatedId;
175
-				}
176
-
177
-				$event = \OC::$server->getActivityManager()->generateEvent();
178
-				$event->setApp('files_sharing')
179
-					->setType('remote_share')
180
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
181
-					->setAffectedUser($shareWith)
182
-					->setObject('remote_share', (int)$shareId, $name);
183
-				\OC::$server->getActivityManager()->publish($event);
184
-
185
-				$urlGenerator = \OC::$server->getURLGenerator();
186
-
187
-				$notificationManager = \OC::$server->getNotificationManager();
188
-				$notification = $notificationManager->createNotification();
189
-				$notification->setApp('files_sharing')
190
-					->setUser($shareWith)
191
-					->setDateTime(new \DateTime())
192
-					->setObject('remote_share', $shareId)
193
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
194
-
195
-				$declineAction = $notification->createAction();
196
-				$declineAction->setLabel('decline')
197
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
198
-				$notification->addAction($declineAction);
199
-
200
-				$acceptAction = $notification->createAction();
201
-				$acceptAction->setLabel('accept')
202
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
203
-				$notification->addAction($acceptAction);
204
-
205
-				$notificationManager->notify($notification);
206
-
207
-				return new Http\DataResponse();
208
-			} catch (\Exception $e) {
209
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
210
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
211
-			}
212
-		}
213
-
214
-		throw new OCSException('server can not add remote share, missing parameter', 400);
215
-	}
216
-
217
-	/**
218
-	 * @NoCSRFRequired
219
-	 * @PublicPage
220
-	 *
221
-	 * create re-share on behalf of another user
222
-	 *
223
-	 * @param int $id
224
-	 * @return Http\DataResponse
225
-	 * @throws OCSBadRequestException
226
-	 * @throws OCSForbiddenException
227
-	 * @throws OCSNotFoundException
228
-	 */
229
-	public function reShare($id) {
230
-
231
-		$token = $this->request->getParam('token', null);
232
-		$shareWith = $this->request->getParam('shareWith', null);
233
-		$permission = (int)$this->request->getParam('permission', null);
234
-		$remoteId = (int)$this->request->getParam('remoteId', null);
235
-
236
-		if ($id === null ||
237
-			$token === null ||
238
-			$shareWith === null ||
239
-			$permission === null ||
240
-			$remoteId === null
241
-		) {
242
-			throw new OCSBadRequestException();
243
-		}
244
-
245
-		try {
246
-			$share = $this->federatedShareProvider->getShareById($id);
247
-		} catch (Share\Exceptions\ShareNotFound $e) {
248
-			throw new OCSNotFoundException();
249
-		}
250
-
251
-		// don't allow to share a file back to the owner
252
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
253
-		$owner = $share->getShareOwner();
254
-		$currentServer = $this->addressHandler->generateRemoteURL();
255
-		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
256
-			throw new OCSForbiddenException();
257
-		}
258
-
259
-		if ($this->verifyShare($share, $token)) {
260
-
261
-			// check if re-sharing is allowed
262
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
263
-				$share->setPermissions($share->getPermissions() & $permission);
264
-				// the recipient of the initial share is now the initiator for the re-share
265
-				$share->setSharedBy($share->getSharedWith());
266
-				$share->setSharedWith($shareWith);
267
-				try {
268
-					$result = $this->federatedShareProvider->create($share);
269
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
270
-					return new Http\DataResponse([
271
-						'token' => $result->getToken(),
272
-						'remoteId' => $result->getId()
273
-					]);
274
-				} catch (\Exception $e) {
275
-					throw new OCSBadRequestException();
276
-				}
277
-			} else {
278
-				throw new OCSForbiddenException();
279
-			}
280
-		}
281
-		throw new OCSBadRequestException();
282
-	}
283
-
284
-	/**
285
-	 * @NoCSRFRequired
286
-	 * @PublicPage
287
-	 *
288
-	 * accept server-to-server share
289
-	 *
290
-	 * @param int $id
291
-	 * @return Http\DataResponse
292
-	 * @throws OCSException
293
-	 */
294
-	public function acceptShare($id) {
295
-
296
-		if (!$this->isS2SEnabled()) {
297
-			throw new OCSException('Server does not support federated cloud sharing', 503);
298
-		}
299
-
300
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
301
-
302
-		try {
303
-			$share = $this->federatedShareProvider->getShareById($id);
304
-		} catch (Share\Exceptions\ShareNotFound $e) {
305
-			return new Http\DataResponse();
306
-		}
307
-
308
-		if ($this->verifyShare($share, $token)) {
309
-			$this->executeAcceptShare($share);
310
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
311
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
312
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
313
-				$this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
314
-			}
315
-		}
316
-
317
-		return new Http\DataResponse();
318
-	}
319
-
320
-	protected function executeAcceptShare(Share\IShare $share) {
321
-		$fileId = (int) $share->getNode()->getId();
322
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
323
-
324
-		$event = \OC::$server->getActivityManager()->generateEvent();
325
-		$event->setApp('files_sharing')
326
-			->setType('remote_share')
327
-			->setAffectedUser($this->getCorrectUid($share))
328
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
329
-			->setObject('files', $fileId, $file)
330
-			->setLink($link);
331
-		\OC::$server->getActivityManager()->publish($event);
332
-	}
333
-
334
-	/**
335
-	 * @NoCSRFRequired
336
-	 * @PublicPage
337
-	 *
338
-	 * decline server-to-server share
339
-	 *
340
-	 * @param int $id
341
-	 * @return Http\DataResponse
342
-	 * @throws OCSException
343
-	 */
344
-	public function declineShare($id) {
345
-
346
-		if (!$this->isS2SEnabled()) {
347
-			throw new OCSException('Server does not support federated cloud sharing', 503);
348
-		}
349
-
350
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
351
-
352
-		try {
353
-			$share = $this->federatedShareProvider->getShareById($id);
354
-		} catch (Share\Exceptions\ShareNotFound $e) {
355
-			return new Http\DataResponse();
356
-		}
357
-
358
-		if ($this->verifyShare($share, $token)) {
359
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
360
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
361
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
362
-				$this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
363
-			}
364
-			$this->executeDeclineShare($share);
365
-		}
366
-
367
-		return new Http\DataResponse();
368
-	}
369
-
370
-	/**
371
-	 * delete declined share and create a activity
372
-	 *
373
-	 * @param Share\IShare $share
374
-	 */
375
-	protected function executeDeclineShare(Share\IShare $share) {
376
-		$this->federatedShareProvider->removeShareFromTable($share);
377
-		$fileId = (int) $share->getNode()->getId();
378
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
379
-
380
-		$event = \OC::$server->getActivityManager()->generateEvent();
381
-		$event->setApp('files_sharing')
382
-			->setType('remote_share')
383
-			->setAffectedUser($this->getCorrectUid($share))
384
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
385
-			->setObject('files', $fileId, $file)
386
-			->setLink($link);
387
-		\OC::$server->getActivityManager()->publish($event);
388
-
389
-	}
390
-
391
-	/**
392
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
393
-	 *
394
-	 * @param Share\IShare $share
395
-	 * @return string
396
-	 */
397
-	protected function getCorrectUid(Share\IShare $share) {
398
-		if ($this->userManager->userExists($share->getShareOwner())) {
399
-			return $share->getShareOwner();
400
-		}
401
-
402
-		return $share->getSharedBy();
403
-	}
404
-
405
-	/**
406
-	 * @NoCSRFRequired
407
-	 * @PublicPage
408
-	 *
409
-	 * remove server-to-server share if it was unshared by the owner
410
-	 *
411
-	 * @param int $id
412
-	 * @return Http\DataResponse
413
-	 * @throws OCSException
414
-	 */
415
-	public function unshare($id) {
416
-
417
-		if (!$this->isS2SEnabled()) {
418
-			throw new OCSException('Server does not support federated cloud sharing', 503);
419
-		}
420
-
421
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
422
-
423
-		$query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
424
-		$query->execute(array($id, $token));
425
-		$share = $query->fetchRow();
426
-
427
-		if ($token && $id && !empty($share)) {
428
-
429
-			$remote = $this->cleanupRemote($share['remote']);
430
-
431
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
432
-			$mountpoint = $share['mountpoint'];
433
-			$user = $share['user'];
434
-
435
-			$query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
436
-			$query->execute(array($id, $token));
437
-
438
-			if ($share['accepted']) {
439
-				$path = trim($mountpoint, '/');
440
-			} else {
441
-				$path = trim($share['name'], '/');
442
-			}
443
-
444
-			$notificationManager = \OC::$server->getNotificationManager();
445
-			$notification = $notificationManager->createNotification();
446
-			$notification->setApp('files_sharing')
447
-				->setUser($share['user'])
448
-				->setObject('remote_share', (int)$share['id']);
449
-			$notificationManager->markProcessed($notification);
450
-
451
-			$event = \OC::$server->getActivityManager()->generateEvent();
452
-			$event->setApp('files_sharing')
453
-				->setType('remote_share')
454
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
455
-				->setAffectedUser($user)
456
-				->setObject('remote_share', (int)$share['id'], $path);
457
-			\OC::$server->getActivityManager()->publish($event);
458
-		}
459
-
460
-		return new Http\DataResponse();
461
-	}
462
-
463
-	private function cleanupRemote($remote) {
464
-		$remote = substr($remote, strpos($remote, '://') + 3);
465
-
466
-		return rtrim($remote, '/');
467
-	}
468
-
469
-
470
-	/**
471
-	 * @NoCSRFRequired
472
-	 * @PublicPage
473
-	 *
474
-	 * federated share was revoked, either by the owner or the re-sharer
475
-	 *
476
-	 * @param int $id
477
-	 * @return Http\DataResponse
478
-	 * @throws OCSBadRequestException
479
-	 */
480
-	public function revoke($id) {
481
-		$token = $this->request->getParam('token');
482
-
483
-		$share = $this->federatedShareProvider->getShareById($id);
484
-
485
-		if ($this->verifyShare($share, $token)) {
486
-			$this->federatedShareProvider->removeShareFromTable($share);
487
-			return new Http\DataResponse();
488
-		}
489
-
490
-		throw new OCSBadRequestException();
491
-	}
492
-
493
-	/**
494
-	 * get share
495
-	 *
496
-	 * @param int $id
497
-	 * @param string $token
498
-	 * @return array|bool
499
-	 */
500
-	protected function getShare($id, $token) {
501
-		$query = $this->connection->getQueryBuilder();
502
-		$query->select('*')->from($this->shareTable)
503
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
504
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
505
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
506
-
507
-		$result = $query->execute()->fetchAll();
508
-
509
-		if (!empty($result) && isset($result[0])) {
510
-			return $result[0];
511
-		}
512
-
513
-		return false;
514
-	}
515
-
516
-	/**
517
-	 * get file
518
-	 *
519
-	 * @param string $user
520
-	 * @param int $fileSource
521
-	 * @return array with internal path of the file and a absolute link to it
522
-	 */
523
-	private function getFile($user, $fileSource) {
524
-		\OC_Util::setupFS($user);
525
-
526
-		try {
527
-			$file = \OC\Files\Filesystem::getPath($fileSource);
528
-		} catch (NotFoundException $e) {
529
-			$file = null;
530
-		}
531
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
532
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
533
-
534
-		return array($file, $link);
535
-
536
-	}
537
-
538
-	/**
539
-	 * check if server-to-server sharing is enabled
540
-	 *
541
-	 * @param bool $incoming
542
-	 * @return bool
543
-	 */
544
-	private function isS2SEnabled($incoming = false) {
545
-
546
-		$result = \OCP\App::isEnabled('files_sharing');
547
-
548
-		if ($incoming) {
549
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
550
-		} else {
551
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
552
-		}
553
-
554
-		return $result;
555
-	}
556
-
557
-	/**
558
-	 * check if we got the right share
559
-	 *
560
-	 * @param Share\IShare $share
561
-	 * @param string $token
562
-	 * @return bool
563
-	 */
564
-	protected function verifyShare(Share\IShare $share, $token) {
565
-		if (
566
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
567
-			$share->getToken() === $token
568
-		) {
569
-			return true;
570
-		}
571
-
572
-		return false;
573
-	}
574
-
575
-	/**
576
-	 * @NoCSRFRequired
577
-	 * @PublicPage
578
-	 *
579
-	 * update share information to keep federated re-shares in sync
580
-	 *
581
-	 * @param int $id
582
-	 * @return Http\DataResponse
583
-	 * @throws OCSBadRequestException
584
-	 */
585
-	public function updatePermissions($id) {
586
-		$token = $this->request->getParam('token', null);
587
-		$permissions = $this->request->getParam('permissions', null);
588
-
589
-		try {
590
-			$share = $this->federatedShareProvider->getShareById($id);
591
-		} catch (Share\Exceptions\ShareNotFound $e) {
592
-			throw new OCSBadRequestException();
593
-		}
594
-
595
-		$validPermission = ctype_digit($permissions);
596
-		$validToken = $this->verifyShare($share, $token);
597
-		if ($validPermission && $validToken) {
598
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
599
-		} else {
600
-			throw new OCSBadRequestException();
601
-		}
602
-
603
-		return new Http\DataResponse();
604
-	}
605
-
606
-	/**
607
-	 * update permissions in database
608
-	 *
609
-	 * @param IShare $share
610
-	 * @param int $permissions
611
-	 */
612
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
613
-		$query = $this->connection->getQueryBuilder();
614
-		$query->update('share')
615
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
616
-			->set('permissions', $query->createNamedParameter($permissions))
617
-			->execute();
618
-	}
619
-
620
-	/**
621
-	 * @NoCSRFRequired
622
-	 * @PublicPage
623
-	 *
624
-	 * change the owner of a server-to-server share
625
-	 *
626
-	 * @param int $id
627
-	 * @return Http\DataResponse
628
-	 * @throws \InvalidArgumentException
629
-	 * @throws OCSException
630
-	 */
631
-	public function move($id) {
632
-
633
-		if (!$this->isS2SEnabled()) {
634
-			throw new OCSException('Server does not support federated cloud sharing', 503);
635
-		}
636
-
637
-		$token = $this->request->getParam('token');
638
-		$remote = $this->request->getParam('remote');
639
-		$newRemoteId = $this->request->getParam('remote_id', $id);
640
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
641
-
642
-		$qb = $this->connection->getQueryBuilder();
643
-		$query = $qb->update('share_external')
644
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
645
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
646
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
647
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
648
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
649
-		$affected = $query->execute();
650
-
651
-		if ($affected > 0) {
652
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
653
-		} else {
654
-			throw new OCSBadRequestException('Share not found or token invalid');
655
-		}
656
-	}
50
+    /** @var FederatedShareProvider */
51
+    private $federatedShareProvider;
52
+
53
+    /** @var IDBConnection */
54
+    private $connection;
55
+
56
+    /** @var Share\IManager */
57
+    private $shareManager;
58
+
59
+    /** @var Notifications */
60
+    private $notifications;
61
+
62
+    /** @var AddressHandler */
63
+    private $addressHandler;
64
+
65
+    /** @var  IUserManager */
66
+    private $userManager;
67
+
68
+    /** @var string */
69
+    private $shareTable = 'share';
70
+
71
+    /** @var ICloudIdManager */
72
+    private $cloudIdManager;
73
+
74
+    /**
75
+     * Server2Server constructor.
76
+     *
77
+     * @param string $appName
78
+     * @param IRequest $request
79
+     * @param FederatedShareProvider $federatedShareProvider
80
+     * @param IDBConnection $connection
81
+     * @param Share\IManager $shareManager
82
+     * @param Notifications $notifications
83
+     * @param AddressHandler $addressHandler
84
+     * @param IUserManager $userManager
85
+     * @param ICloudIdManager $cloudIdManager
86
+     */
87
+    public function __construct($appName,
88
+                                IRequest $request,
89
+                                FederatedShareProvider $federatedShareProvider,
90
+                                IDBConnection $connection,
91
+                                Share\IManager $shareManager,
92
+                                Notifications $notifications,
93
+                                AddressHandler $addressHandler,
94
+                                IUserManager $userManager,
95
+                                ICloudIdManager $cloudIdManager
96
+    ) {
97
+        parent::__construct($appName, $request);
98
+
99
+        $this->federatedShareProvider = $federatedShareProvider;
100
+        $this->connection = $connection;
101
+        $this->shareManager = $shareManager;
102
+        $this->notifications = $notifications;
103
+        $this->addressHandler = $addressHandler;
104
+        $this->userManager = $userManager;
105
+        $this->cloudIdManager = $cloudIdManager;
106
+    }
107
+
108
+    /**
109
+     * @NoCSRFRequired
110
+     * @PublicPage
111
+     *
112
+     * create a new share
113
+     *
114
+     * @return Http\DataResponse
115
+     * @throws OCSException
116
+     */
117
+    public function createShare() {
118
+
119
+        if (!$this->isS2SEnabled(true)) {
120
+            throw new OCSException('Server does not support federated cloud sharing', 503);
121
+        }
122
+
123
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
124
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
125
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
126
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
127
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
128
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
129
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
130
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
131
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
132
+
133
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
134
+
135
+            if (!\OCP\Util::isValidFileName($name)) {
136
+                throw new OCSException('The mountpoint name contains invalid characters.', 400);
137
+            }
138
+
139
+            // FIXME this should be a method in the user management instead
140
+            \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
141
+            \OCP\Util::emitHook(
142
+                '\OCA\Files_Sharing\API\Server2Server',
143
+                'preLoginNameUsedAsUserName',
144
+                array('uid' => &$shareWith)
145
+            );
146
+            \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
147
+
148
+            if (!\OCP\User::userExists($shareWith)) {
149
+                throw new OCSException('User does not exists', 400);
150
+            }
151
+
152
+            \OC_Util::setupFS($shareWith);
153
+
154
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
155
+                    \OC::$server->getDatabaseConnection(),
156
+                    \OC\Files\Filesystem::getMountManager(),
157
+                    \OC\Files\Filesystem::getLoader(),
158
+                    \OC::$server->getHTTPClientService(),
159
+                    \OC::$server->getNotificationManager(),
160
+                    \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
161
+                    $shareWith
162
+                );
163
+
164
+            try {
165
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
166
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
167
+
168
+                if ($ownerFederatedId === null) {
169
+                    $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
170
+                }
171
+                // if the owner of the share and the initiator are the same user
172
+                // we also complete the federated share ID for the initiator
173
+                if ($sharedByFederatedId === null && $owner === $sharedBy) {
174
+                    $sharedByFederatedId = $ownerFederatedId;
175
+                }
176
+
177
+                $event = \OC::$server->getActivityManager()->generateEvent();
178
+                $event->setApp('files_sharing')
179
+                    ->setType('remote_share')
180
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
181
+                    ->setAffectedUser($shareWith)
182
+                    ->setObject('remote_share', (int)$shareId, $name);
183
+                \OC::$server->getActivityManager()->publish($event);
184
+
185
+                $urlGenerator = \OC::$server->getURLGenerator();
186
+
187
+                $notificationManager = \OC::$server->getNotificationManager();
188
+                $notification = $notificationManager->createNotification();
189
+                $notification->setApp('files_sharing')
190
+                    ->setUser($shareWith)
191
+                    ->setDateTime(new \DateTime())
192
+                    ->setObject('remote_share', $shareId)
193
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
194
+
195
+                $declineAction = $notification->createAction();
196
+                $declineAction->setLabel('decline')
197
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
198
+                $notification->addAction($declineAction);
199
+
200
+                $acceptAction = $notification->createAction();
201
+                $acceptAction->setLabel('accept')
202
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
203
+                $notification->addAction($acceptAction);
204
+
205
+                $notificationManager->notify($notification);
206
+
207
+                return new Http\DataResponse();
208
+            } catch (\Exception $e) {
209
+                \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
210
+                throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
211
+            }
212
+        }
213
+
214
+        throw new OCSException('server can not add remote share, missing parameter', 400);
215
+    }
216
+
217
+    /**
218
+     * @NoCSRFRequired
219
+     * @PublicPage
220
+     *
221
+     * create re-share on behalf of another user
222
+     *
223
+     * @param int $id
224
+     * @return Http\DataResponse
225
+     * @throws OCSBadRequestException
226
+     * @throws OCSForbiddenException
227
+     * @throws OCSNotFoundException
228
+     */
229
+    public function reShare($id) {
230
+
231
+        $token = $this->request->getParam('token', null);
232
+        $shareWith = $this->request->getParam('shareWith', null);
233
+        $permission = (int)$this->request->getParam('permission', null);
234
+        $remoteId = (int)$this->request->getParam('remoteId', null);
235
+
236
+        if ($id === null ||
237
+            $token === null ||
238
+            $shareWith === null ||
239
+            $permission === null ||
240
+            $remoteId === null
241
+        ) {
242
+            throw new OCSBadRequestException();
243
+        }
244
+
245
+        try {
246
+            $share = $this->federatedShareProvider->getShareById($id);
247
+        } catch (Share\Exceptions\ShareNotFound $e) {
248
+            throw new OCSNotFoundException();
249
+        }
250
+
251
+        // don't allow to share a file back to the owner
252
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
253
+        $owner = $share->getShareOwner();
254
+        $currentServer = $this->addressHandler->generateRemoteURL();
255
+        if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
256
+            throw new OCSForbiddenException();
257
+        }
258
+
259
+        if ($this->verifyShare($share, $token)) {
260
+
261
+            // check if re-sharing is allowed
262
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
263
+                $share->setPermissions($share->getPermissions() & $permission);
264
+                // the recipient of the initial share is now the initiator for the re-share
265
+                $share->setSharedBy($share->getSharedWith());
266
+                $share->setSharedWith($shareWith);
267
+                try {
268
+                    $result = $this->federatedShareProvider->create($share);
269
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
270
+                    return new Http\DataResponse([
271
+                        'token' => $result->getToken(),
272
+                        'remoteId' => $result->getId()
273
+                    ]);
274
+                } catch (\Exception $e) {
275
+                    throw new OCSBadRequestException();
276
+                }
277
+            } else {
278
+                throw new OCSForbiddenException();
279
+            }
280
+        }
281
+        throw new OCSBadRequestException();
282
+    }
283
+
284
+    /**
285
+     * @NoCSRFRequired
286
+     * @PublicPage
287
+     *
288
+     * accept server-to-server share
289
+     *
290
+     * @param int $id
291
+     * @return Http\DataResponse
292
+     * @throws OCSException
293
+     */
294
+    public function acceptShare($id) {
295
+
296
+        if (!$this->isS2SEnabled()) {
297
+            throw new OCSException('Server does not support federated cloud sharing', 503);
298
+        }
299
+
300
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
301
+
302
+        try {
303
+            $share = $this->federatedShareProvider->getShareById($id);
304
+        } catch (Share\Exceptions\ShareNotFound $e) {
305
+            return new Http\DataResponse();
306
+        }
307
+
308
+        if ($this->verifyShare($share, $token)) {
309
+            $this->executeAcceptShare($share);
310
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
311
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
312
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
313
+                $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
314
+            }
315
+        }
316
+
317
+        return new Http\DataResponse();
318
+    }
319
+
320
+    protected function executeAcceptShare(Share\IShare $share) {
321
+        $fileId = (int) $share->getNode()->getId();
322
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
323
+
324
+        $event = \OC::$server->getActivityManager()->generateEvent();
325
+        $event->setApp('files_sharing')
326
+            ->setType('remote_share')
327
+            ->setAffectedUser($this->getCorrectUid($share))
328
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
329
+            ->setObject('files', $fileId, $file)
330
+            ->setLink($link);
331
+        \OC::$server->getActivityManager()->publish($event);
332
+    }
333
+
334
+    /**
335
+     * @NoCSRFRequired
336
+     * @PublicPage
337
+     *
338
+     * decline server-to-server share
339
+     *
340
+     * @param int $id
341
+     * @return Http\DataResponse
342
+     * @throws OCSException
343
+     */
344
+    public function declineShare($id) {
345
+
346
+        if (!$this->isS2SEnabled()) {
347
+            throw new OCSException('Server does not support federated cloud sharing', 503);
348
+        }
349
+
350
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
351
+
352
+        try {
353
+            $share = $this->federatedShareProvider->getShareById($id);
354
+        } catch (Share\Exceptions\ShareNotFound $e) {
355
+            return new Http\DataResponse();
356
+        }
357
+
358
+        if ($this->verifyShare($share, $token)) {
359
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
360
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
361
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
362
+                $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
363
+            }
364
+            $this->executeDeclineShare($share);
365
+        }
366
+
367
+        return new Http\DataResponse();
368
+    }
369
+
370
+    /**
371
+     * delete declined share and create a activity
372
+     *
373
+     * @param Share\IShare $share
374
+     */
375
+    protected function executeDeclineShare(Share\IShare $share) {
376
+        $this->federatedShareProvider->removeShareFromTable($share);
377
+        $fileId = (int) $share->getNode()->getId();
378
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
379
+
380
+        $event = \OC::$server->getActivityManager()->generateEvent();
381
+        $event->setApp('files_sharing')
382
+            ->setType('remote_share')
383
+            ->setAffectedUser($this->getCorrectUid($share))
384
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
385
+            ->setObject('files', $fileId, $file)
386
+            ->setLink($link);
387
+        \OC::$server->getActivityManager()->publish($event);
388
+
389
+    }
390
+
391
+    /**
392
+     * check if we are the initiator or the owner of a re-share and return the correct UID
393
+     *
394
+     * @param Share\IShare $share
395
+     * @return string
396
+     */
397
+    protected function getCorrectUid(Share\IShare $share) {
398
+        if ($this->userManager->userExists($share->getShareOwner())) {
399
+            return $share->getShareOwner();
400
+        }
401
+
402
+        return $share->getSharedBy();
403
+    }
404
+
405
+    /**
406
+     * @NoCSRFRequired
407
+     * @PublicPage
408
+     *
409
+     * remove server-to-server share if it was unshared by the owner
410
+     *
411
+     * @param int $id
412
+     * @return Http\DataResponse
413
+     * @throws OCSException
414
+     */
415
+    public function unshare($id) {
416
+
417
+        if (!$this->isS2SEnabled()) {
418
+            throw new OCSException('Server does not support federated cloud sharing', 503);
419
+        }
420
+
421
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
422
+
423
+        $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
424
+        $query->execute(array($id, $token));
425
+        $share = $query->fetchRow();
426
+
427
+        if ($token && $id && !empty($share)) {
428
+
429
+            $remote = $this->cleanupRemote($share['remote']);
430
+
431
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
432
+            $mountpoint = $share['mountpoint'];
433
+            $user = $share['user'];
434
+
435
+            $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
436
+            $query->execute(array($id, $token));
437
+
438
+            if ($share['accepted']) {
439
+                $path = trim($mountpoint, '/');
440
+            } else {
441
+                $path = trim($share['name'], '/');
442
+            }
443
+
444
+            $notificationManager = \OC::$server->getNotificationManager();
445
+            $notification = $notificationManager->createNotification();
446
+            $notification->setApp('files_sharing')
447
+                ->setUser($share['user'])
448
+                ->setObject('remote_share', (int)$share['id']);
449
+            $notificationManager->markProcessed($notification);
450
+
451
+            $event = \OC::$server->getActivityManager()->generateEvent();
452
+            $event->setApp('files_sharing')
453
+                ->setType('remote_share')
454
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
455
+                ->setAffectedUser($user)
456
+                ->setObject('remote_share', (int)$share['id'], $path);
457
+            \OC::$server->getActivityManager()->publish($event);
458
+        }
459
+
460
+        return new Http\DataResponse();
461
+    }
462
+
463
+    private function cleanupRemote($remote) {
464
+        $remote = substr($remote, strpos($remote, '://') + 3);
465
+
466
+        return rtrim($remote, '/');
467
+    }
468
+
469
+
470
+    /**
471
+     * @NoCSRFRequired
472
+     * @PublicPage
473
+     *
474
+     * federated share was revoked, either by the owner or the re-sharer
475
+     *
476
+     * @param int $id
477
+     * @return Http\DataResponse
478
+     * @throws OCSBadRequestException
479
+     */
480
+    public function revoke($id) {
481
+        $token = $this->request->getParam('token');
482
+
483
+        $share = $this->federatedShareProvider->getShareById($id);
484
+
485
+        if ($this->verifyShare($share, $token)) {
486
+            $this->federatedShareProvider->removeShareFromTable($share);
487
+            return new Http\DataResponse();
488
+        }
489
+
490
+        throw new OCSBadRequestException();
491
+    }
492
+
493
+    /**
494
+     * get share
495
+     *
496
+     * @param int $id
497
+     * @param string $token
498
+     * @return array|bool
499
+     */
500
+    protected function getShare($id, $token) {
501
+        $query = $this->connection->getQueryBuilder();
502
+        $query->select('*')->from($this->shareTable)
503
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
504
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
505
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
506
+
507
+        $result = $query->execute()->fetchAll();
508
+
509
+        if (!empty($result) && isset($result[0])) {
510
+            return $result[0];
511
+        }
512
+
513
+        return false;
514
+    }
515
+
516
+    /**
517
+     * get file
518
+     *
519
+     * @param string $user
520
+     * @param int $fileSource
521
+     * @return array with internal path of the file and a absolute link to it
522
+     */
523
+    private function getFile($user, $fileSource) {
524
+        \OC_Util::setupFS($user);
525
+
526
+        try {
527
+            $file = \OC\Files\Filesystem::getPath($fileSource);
528
+        } catch (NotFoundException $e) {
529
+            $file = null;
530
+        }
531
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
532
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
533
+
534
+        return array($file, $link);
535
+
536
+    }
537
+
538
+    /**
539
+     * check if server-to-server sharing is enabled
540
+     *
541
+     * @param bool $incoming
542
+     * @return bool
543
+     */
544
+    private function isS2SEnabled($incoming = false) {
545
+
546
+        $result = \OCP\App::isEnabled('files_sharing');
547
+
548
+        if ($incoming) {
549
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
550
+        } else {
551
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
552
+        }
553
+
554
+        return $result;
555
+    }
556
+
557
+    /**
558
+     * check if we got the right share
559
+     *
560
+     * @param Share\IShare $share
561
+     * @param string $token
562
+     * @return bool
563
+     */
564
+    protected function verifyShare(Share\IShare $share, $token) {
565
+        if (
566
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
567
+            $share->getToken() === $token
568
+        ) {
569
+            return true;
570
+        }
571
+
572
+        return false;
573
+    }
574
+
575
+    /**
576
+     * @NoCSRFRequired
577
+     * @PublicPage
578
+     *
579
+     * update share information to keep federated re-shares in sync
580
+     *
581
+     * @param int $id
582
+     * @return Http\DataResponse
583
+     * @throws OCSBadRequestException
584
+     */
585
+    public function updatePermissions($id) {
586
+        $token = $this->request->getParam('token', null);
587
+        $permissions = $this->request->getParam('permissions', null);
588
+
589
+        try {
590
+            $share = $this->federatedShareProvider->getShareById($id);
591
+        } catch (Share\Exceptions\ShareNotFound $e) {
592
+            throw new OCSBadRequestException();
593
+        }
594
+
595
+        $validPermission = ctype_digit($permissions);
596
+        $validToken = $this->verifyShare($share, $token);
597
+        if ($validPermission && $validToken) {
598
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
599
+        } else {
600
+            throw new OCSBadRequestException();
601
+        }
602
+
603
+        return new Http\DataResponse();
604
+    }
605
+
606
+    /**
607
+     * update permissions in database
608
+     *
609
+     * @param IShare $share
610
+     * @param int $permissions
611
+     */
612
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
613
+        $query = $this->connection->getQueryBuilder();
614
+        $query->update('share')
615
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
616
+            ->set('permissions', $query->createNamedParameter($permissions))
617
+            ->execute();
618
+    }
619
+
620
+    /**
621
+     * @NoCSRFRequired
622
+     * @PublicPage
623
+     *
624
+     * change the owner of a server-to-server share
625
+     *
626
+     * @param int $id
627
+     * @return Http\DataResponse
628
+     * @throws \InvalidArgumentException
629
+     * @throws OCSException
630
+     */
631
+    public function move($id) {
632
+
633
+        if (!$this->isS2SEnabled()) {
634
+            throw new OCSException('Server does not support federated cloud sharing', 503);
635
+        }
636
+
637
+        $token = $this->request->getParam('token');
638
+        $remote = $this->request->getParam('remote');
639
+        $newRemoteId = $this->request->getParam('remote_id', $id);
640
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
641
+
642
+        $qb = $this->connection->getQueryBuilder();
643
+        $query = $qb->update('share_external')
644
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
645
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
646
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
647
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
648
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
649
+        $affected = $query->execute();
650
+
651
+        if ($affected > 0) {
652
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
653
+        } else {
654
+            throw new OCSBadRequestException('Share not found or token invalid');
655
+        }
656
+    }
657 657
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
127 127
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
128 128
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
129
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
129
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
130 130
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
131 131
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
132 132
 
@@ -137,13 +137,13 @@  discard block
 block discarded – undo
137 137
 			}
138 138
 
139 139
 			// FIXME this should be a method in the user management instead
140
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
140
+			\OCP\Util::writeLog('files_sharing', 'shareWith before, '.$shareWith, \OCP\Util::DEBUG);
141 141
 			\OCP\Util::emitHook(
142 142
 				'\OCA\Files_Sharing\API\Server2Server',
143 143
 				'preLoginNameUsedAsUserName',
144 144
 				array('uid' => &$shareWith)
145 145
 			);
146
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
146
+			\OCP\Util::writeLog('files_sharing', 'shareWith after, '.$shareWith, \OCP\Util::DEBUG);
147 147
 
148 148
 			if (!\OCP\User::userExists($shareWith)) {
149 149
 				throw new OCSException('User does not exists', 400);
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 					->setType('remote_share')
180 180
 					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
181 181
 					->setAffectedUser($shareWith)
182
-					->setObject('remote_share', (int)$shareId, $name);
182
+					->setObject('remote_share', (int) $shareId, $name);
183 183
 				\OC::$server->getActivityManager()->publish($event);
184 184
 
185 185
 				$urlGenerator = \OC::$server->getURLGenerator();
@@ -194,20 +194,20 @@  discard block
 block discarded – undo
194 194
 
195 195
 				$declineAction = $notification->createAction();
196 196
 				$declineAction->setLabel('decline')
197
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
197
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
198 198
 				$notification->addAction($declineAction);
199 199
 
200 200
 				$acceptAction = $notification->createAction();
201 201
 				$acceptAction->setLabel('accept')
202
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
202
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
203 203
 				$notification->addAction($acceptAction);
204 204
 
205 205
 				$notificationManager->notify($notification);
206 206
 
207 207
 				return new Http\DataResponse();
208 208
 			} catch (\Exception $e) {
209
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
210
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
209
+				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, '.$e->getMessage(), \OCP\Util::ERROR);
210
+				throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
211 211
 			}
212 212
 		}
213 213
 
@@ -230,8 +230,8 @@  discard block
 block discarded – undo
230 230
 
231 231
 		$token = $this->request->getParam('token', null);
232 232
 		$shareWith = $this->request->getParam('shareWith', null);
233
-		$permission = (int)$this->request->getParam('permission', null);
234
-		$remoteId = (int)$this->request->getParam('remoteId', null);
233
+		$permission = (int) $this->request->getParam('permission', null);
234
+		$remoteId = (int) $this->request->getParam('remoteId', null);
235 235
 
236 236
 		if ($id === null ||
237 237
 			$token === null ||
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 				$share->setSharedWith($shareWith);
267 267
 				try {
268 268
 					$result = $this->federatedShareProvider->create($share);
269
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
269
+					$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $remoteId);
270 270
 					return new Http\DataResponse([
271 271
 						'token' => $result->getToken(),
272 272
 						'remoteId' => $result->getId()
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 			$notification = $notificationManager->createNotification();
446 446
 			$notification->setApp('files_sharing')
447 447
 				->setUser($share['user'])
448
-				->setObject('remote_share', (int)$share['id']);
448
+				->setObject('remote_share', (int) $share['id']);
449 449
 			$notificationManager->markProcessed($notification);
450 450
 
451 451
 			$event = \OC::$server->getActivityManager()->generateEvent();
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 				->setType('remote_share')
454 454
 				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
455 455
 				->setAffectedUser($user)
456
-				->setObject('remote_share', (int)$share['id'], $path);
456
+				->setObject('remote_share', (int) $share['id'], $path);
457 457
 			\OC::$server->getActivityManager()->publish($event);
458 458
 		}
459 459
 
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 		$validPermission = ctype_digit($permissions);
596 596
 		$validToken = $this->verifyShare($share, $token);
597 597
 		if ($validPermission && $validToken) {
598
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
598
+			$this->updatePermissionsInDatabase($share, (int) $permissions);
599 599
 		} else {
600 600
 			throw new OCSBadRequestException();
601 601
 		}
Please login to merge, or discard this patch.