Completed
Pull Request — master (#9345)
by Björn
256:46 queued 240:36
created
apps/federatedfilesharing/lib/FederatedShareProvider.php 1 patch
Indentation   +975 added lines, -975 removed lines patch added patch discarded remove patch
@@ -54,989 +54,989 @@
 block discarded – undo
54 54
  */
55 55
 class FederatedShareProvider implements IShareProvider {
56 56
 
57
-	const SHARE_TYPE_REMOTE = 6;
58
-
59
-	/** @var IDBConnection */
60
-	private $dbConnection;
61
-
62
-	/** @var AddressHandler */
63
-	private $addressHandler;
64
-
65
-	/** @var Notifications */
66
-	private $notifications;
67
-
68
-	/** @var TokenHandler */
69
-	private $tokenHandler;
70
-
71
-	/** @var IL10N */
72
-	private $l;
73
-
74
-	/** @var ILogger */
75
-	private $logger;
76
-
77
-	/** @var IRootFolder */
78
-	private $rootFolder;
79
-
80
-	/** @var IConfig */
81
-	private $config;
82
-
83
-	/** @var string */
84
-	private $externalShareTable = 'share_external';
85
-
86
-	/** @var IUserManager */
87
-	private $userManager;
88
-
89
-	/** @var ICloudIdManager */
90
-	private $cloudIdManager;
91
-
92
-	/** @var \OCP\GlobalScale\IConfig */
93
-	private $gsConfig;
94
-
95
-	/**
96
-	 * DefaultShareProvider constructor.
97
-	 *
98
-	 * @param IDBConnection $connection
99
-	 * @param AddressHandler $addressHandler
100
-	 * @param Notifications $notifications
101
-	 * @param TokenHandler $tokenHandler
102
-	 * @param IL10N $l10n
103
-	 * @param ILogger $logger
104
-	 * @param IRootFolder $rootFolder
105
-	 * @param IConfig $config
106
-	 * @param IUserManager $userManager
107
-	 * @param ICloudIdManager $cloudIdManager
108
-	 * @param \OCP\GlobalScale\IConfig $globalScaleConfig
109
-	 */
110
-	public function __construct(
111
-			IDBConnection $connection,
112
-			AddressHandler $addressHandler,
113
-			Notifications $notifications,
114
-			TokenHandler $tokenHandler,
115
-			IL10N $l10n,
116
-			ILogger $logger,
117
-			IRootFolder $rootFolder,
118
-			IConfig $config,
119
-			IUserManager $userManager,
120
-			ICloudIdManager $cloudIdManager,
121
-			\OCP\GlobalScale\IConfig $globalScaleConfig
122
-	) {
123
-		$this->dbConnection = $connection;
124
-		$this->addressHandler = $addressHandler;
125
-		$this->notifications = $notifications;
126
-		$this->tokenHandler = $tokenHandler;
127
-		$this->l = $l10n;
128
-		$this->logger = $logger;
129
-		$this->rootFolder = $rootFolder;
130
-		$this->config = $config;
131
-		$this->userManager = $userManager;
132
-		$this->cloudIdManager = $cloudIdManager;
133
-		$this->gsConfig = $globalScaleConfig;
134
-	}
135
-
136
-	/**
137
-	 * Return the identifier of this provider.
138
-	 *
139
-	 * @return string Containing only [a-zA-Z0-9]
140
-	 */
141
-	public function identifier() {
142
-		return 'ocFederatedSharing';
143
-	}
144
-
145
-	/**
146
-	 * Share a path
147
-	 *
148
-	 * @param IShare $share
149
-	 * @return IShare The share object
150
-	 * @throws ShareNotFound
151
-	 * @throws \Exception
152
-	 */
153
-	public function create(IShare $share) {
154
-
155
-		$shareWith = $share->getSharedWith();
156
-		$itemSource = $share->getNodeId();
157
-		$itemType = $share->getNodeType();
158
-		$permissions = $share->getPermissions();
159
-		$sharedBy = $share->getSharedBy();
160
-
161
-		/*
57
+    const SHARE_TYPE_REMOTE = 6;
58
+
59
+    /** @var IDBConnection */
60
+    private $dbConnection;
61
+
62
+    /** @var AddressHandler */
63
+    private $addressHandler;
64
+
65
+    /** @var Notifications */
66
+    private $notifications;
67
+
68
+    /** @var TokenHandler */
69
+    private $tokenHandler;
70
+
71
+    /** @var IL10N */
72
+    private $l;
73
+
74
+    /** @var ILogger */
75
+    private $logger;
76
+
77
+    /** @var IRootFolder */
78
+    private $rootFolder;
79
+
80
+    /** @var IConfig */
81
+    private $config;
82
+
83
+    /** @var string */
84
+    private $externalShareTable = 'share_external';
85
+
86
+    /** @var IUserManager */
87
+    private $userManager;
88
+
89
+    /** @var ICloudIdManager */
90
+    private $cloudIdManager;
91
+
92
+    /** @var \OCP\GlobalScale\IConfig */
93
+    private $gsConfig;
94
+
95
+    /**
96
+     * DefaultShareProvider constructor.
97
+     *
98
+     * @param IDBConnection $connection
99
+     * @param AddressHandler $addressHandler
100
+     * @param Notifications $notifications
101
+     * @param TokenHandler $tokenHandler
102
+     * @param IL10N $l10n
103
+     * @param ILogger $logger
104
+     * @param IRootFolder $rootFolder
105
+     * @param IConfig $config
106
+     * @param IUserManager $userManager
107
+     * @param ICloudIdManager $cloudIdManager
108
+     * @param \OCP\GlobalScale\IConfig $globalScaleConfig
109
+     */
110
+    public function __construct(
111
+            IDBConnection $connection,
112
+            AddressHandler $addressHandler,
113
+            Notifications $notifications,
114
+            TokenHandler $tokenHandler,
115
+            IL10N $l10n,
116
+            ILogger $logger,
117
+            IRootFolder $rootFolder,
118
+            IConfig $config,
119
+            IUserManager $userManager,
120
+            ICloudIdManager $cloudIdManager,
121
+            \OCP\GlobalScale\IConfig $globalScaleConfig
122
+    ) {
123
+        $this->dbConnection = $connection;
124
+        $this->addressHandler = $addressHandler;
125
+        $this->notifications = $notifications;
126
+        $this->tokenHandler = $tokenHandler;
127
+        $this->l = $l10n;
128
+        $this->logger = $logger;
129
+        $this->rootFolder = $rootFolder;
130
+        $this->config = $config;
131
+        $this->userManager = $userManager;
132
+        $this->cloudIdManager = $cloudIdManager;
133
+        $this->gsConfig = $globalScaleConfig;
134
+    }
135
+
136
+    /**
137
+     * Return the identifier of this provider.
138
+     *
139
+     * @return string Containing only [a-zA-Z0-9]
140
+     */
141
+    public function identifier() {
142
+        return 'ocFederatedSharing';
143
+    }
144
+
145
+    /**
146
+     * Share a path
147
+     *
148
+     * @param IShare $share
149
+     * @return IShare The share object
150
+     * @throws ShareNotFound
151
+     * @throws \Exception
152
+     */
153
+    public function create(IShare $share) {
154
+
155
+        $shareWith = $share->getSharedWith();
156
+        $itemSource = $share->getNodeId();
157
+        $itemType = $share->getNodeType();
158
+        $permissions = $share->getPermissions();
159
+        $sharedBy = $share->getSharedBy();
160
+
161
+        /*
162 162
 		 * Check if file is not already shared with the remote user
163 163
 		 */
164
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
165
-		if (!empty($alreadyShared)) {
166
-			$message = 'Sharing %s failed, because this item is already shared with %s';
167
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
168
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
169
-			throw new \Exception($message_t);
170
-		}
171
-
172
-
173
-		// don't allow federated shares if source and target server are the same
174
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
175
-		$currentServer = $this->addressHandler->generateRemoteURL();
176
-		$currentUser = $sharedBy;
177
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
178
-			$message = 'Not allowed to create a federated share with the same user.';
179
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
180
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
181
-			throw new \Exception($message_t);
182
-		}
183
-
184
-
185
-		$share->setSharedWith($cloudId->getId());
186
-
187
-		try {
188
-			$remoteShare = $this->getShareFromExternalShareTable($share);
189
-		} catch (ShareNotFound $e) {
190
-			$remoteShare = null;
191
-		}
192
-
193
-		if ($remoteShare) {
194
-			try {
195
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
196
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
197
-				$share->setId($shareId);
198
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
199
-				// remote share was create successfully if we get a valid token as return
200
-				$send = is_string($token) && $token !== '';
201
-			} catch (\Exception $e) {
202
-				// fall back to old re-share behavior if the remote server
203
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
204
-				$this->removeShareFromTable($share);
205
-				$shareId = $this->createFederatedShare($share);
206
-			}
207
-			if ($send) {
208
-				$this->updateSuccessfulReshare($shareId, $token);
209
-				$this->storeRemoteId($shareId, $remoteId);
210
-			} else {
211
-				$this->removeShareFromTable($share);
212
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
213
-				throw new \Exception($message_t);
214
-			}
215
-
216
-		} else {
217
-			$shareId = $this->createFederatedShare($share);
218
-		}
219
-
220
-		$data = $this->getRawShare($shareId);
221
-		return $this->createShareObject($data);
222
-	}
223
-
224
-	/**
225
-	 * create federated share and inform the recipient
226
-	 *
227
-	 * @param IShare $share
228
-	 * @return int
229
-	 * @throws ShareNotFound
230
-	 * @throws \Exception
231
-	 */
232
-	protected function createFederatedShare(IShare $share) {
233
-		$token = $this->tokenHandler->generateToken();
234
-		$shareId = $this->addShareToDB(
235
-			$share->getNodeId(),
236
-			$share->getNodeType(),
237
-			$share->getSharedWith(),
238
-			$share->getSharedBy(),
239
-			$share->getShareOwner(),
240
-			$share->getPermissions(),
241
-			$token
242
-		);
243
-
244
-		$failure = false;
245
-
246
-		try {
247
-			$sharedByFederatedId = $share->getSharedBy();
248
-			if ($this->userManager->userExists($sharedByFederatedId)) {
249
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
250
-				$sharedByFederatedId = $cloudId->getId();
251
-			}
252
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
253
-			$send = $this->notifications->sendRemoteShare(
254
-				$token,
255
-				$share->getSharedWith(),
256
-				$share->getNode()->getName(),
257
-				$shareId,
258
-				$share->getShareOwner(),
259
-				$ownerCloudId->getId(),
260
-				$share->getSharedBy(),
261
-				$sharedByFederatedId
262
-			);
263
-
264
-			if ($send === false) {
265
-				$failure = true;
266
-			}
267
-		} catch (\Exception $e) {
268
-			$this->logger->logException($e, [
269
-				'message' => 'Failed to notify remote server of federated share, removing share.',
270
-				'level' => ILogger::ERROR,
271
-				'app' => 'federatedfilesharing',
272
-			]);
273
-			$failure = true;
274
-		}
275
-
276
-		if($failure) {
277
-			$this->removeShareFromTableById($shareId);
278
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
279
-				[$share->getNode()->getName(), $share->getSharedWith()]);
280
-			throw new \Exception($message_t);
281
-		}
282
-
283
-		return $shareId;
284
-
285
-	}
286
-
287
-	/**
288
-	 * @param string $shareWith
289
-	 * @param IShare $share
290
-	 * @param string $shareId internal share Id
291
-	 * @return array
292
-	 * @throws \Exception
293
-	 */
294
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
295
-
296
-		$remoteShare = $this->getShareFromExternalShareTable($share);
297
-		$token = $remoteShare['share_token'];
298
-		$remoteId = $remoteShare['remote_id'];
299
-		$remote = $remoteShare['remote'];
300
-
301
-		list($token, $remoteId) = $this->notifications->requestReShare(
302
-			$token,
303
-			$remoteId,
304
-			$shareId,
305
-			$remote,
306
-			$shareWith,
307
-			$share->getPermissions()
308
-		);
309
-
310
-		return [$token, $remoteId];
311
-	}
312
-
313
-	/**
314
-	 * get federated share from the share_external table but exclude mounted link shares
315
-	 *
316
-	 * @param IShare $share
317
-	 * @return array
318
-	 * @throws ShareNotFound
319
-	 */
320
-	protected function getShareFromExternalShareTable(IShare $share) {
321
-		$query = $this->dbConnection->getQueryBuilder();
322
-		$query->select('*')->from($this->externalShareTable)
323
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
324
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
325
-		$result = $query->execute()->fetchAll();
326
-
327
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
328
-			return $result[0];
329
-		}
330
-
331
-		throw new ShareNotFound('share not found in share_external table');
332
-	}
333
-
334
-	/**
335
-	 * add share to the database and return the ID
336
-	 *
337
-	 * @param int $itemSource
338
-	 * @param string $itemType
339
-	 * @param string $shareWith
340
-	 * @param string $sharedBy
341
-	 * @param string $uidOwner
342
-	 * @param int $permissions
343
-	 * @param string $token
344
-	 * @return int
345
-	 */
346
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
347
-		$qb = $this->dbConnection->getQueryBuilder();
348
-		$qb->insert('share')
349
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
350
-			->setValue('item_type', $qb->createNamedParameter($itemType))
351
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
352
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
353
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
354
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
355
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
356
-			->setValue('permissions', $qb->createNamedParameter($permissions))
357
-			->setValue('token', $qb->createNamedParameter($token))
358
-			->setValue('stime', $qb->createNamedParameter(time()));
359
-
360
-		/*
164
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
165
+        if (!empty($alreadyShared)) {
166
+            $message = 'Sharing %s failed, because this item is already shared with %s';
167
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
168
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
169
+            throw new \Exception($message_t);
170
+        }
171
+
172
+
173
+        // don't allow federated shares if source and target server are the same
174
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
175
+        $currentServer = $this->addressHandler->generateRemoteURL();
176
+        $currentUser = $sharedBy;
177
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
178
+            $message = 'Not allowed to create a federated share with the same user.';
179
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
180
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
181
+            throw new \Exception($message_t);
182
+        }
183
+
184
+
185
+        $share->setSharedWith($cloudId->getId());
186
+
187
+        try {
188
+            $remoteShare = $this->getShareFromExternalShareTable($share);
189
+        } catch (ShareNotFound $e) {
190
+            $remoteShare = null;
191
+        }
192
+
193
+        if ($remoteShare) {
194
+            try {
195
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
196
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
197
+                $share->setId($shareId);
198
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
199
+                // remote share was create successfully if we get a valid token as return
200
+                $send = is_string($token) && $token !== '';
201
+            } catch (\Exception $e) {
202
+                // fall back to old re-share behavior if the remote server
203
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
204
+                $this->removeShareFromTable($share);
205
+                $shareId = $this->createFederatedShare($share);
206
+            }
207
+            if ($send) {
208
+                $this->updateSuccessfulReshare($shareId, $token);
209
+                $this->storeRemoteId($shareId, $remoteId);
210
+            } else {
211
+                $this->removeShareFromTable($share);
212
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
213
+                throw new \Exception($message_t);
214
+            }
215
+
216
+        } else {
217
+            $shareId = $this->createFederatedShare($share);
218
+        }
219
+
220
+        $data = $this->getRawShare($shareId);
221
+        return $this->createShareObject($data);
222
+    }
223
+
224
+    /**
225
+     * create federated share and inform the recipient
226
+     *
227
+     * @param IShare $share
228
+     * @return int
229
+     * @throws ShareNotFound
230
+     * @throws \Exception
231
+     */
232
+    protected function createFederatedShare(IShare $share) {
233
+        $token = $this->tokenHandler->generateToken();
234
+        $shareId = $this->addShareToDB(
235
+            $share->getNodeId(),
236
+            $share->getNodeType(),
237
+            $share->getSharedWith(),
238
+            $share->getSharedBy(),
239
+            $share->getShareOwner(),
240
+            $share->getPermissions(),
241
+            $token
242
+        );
243
+
244
+        $failure = false;
245
+
246
+        try {
247
+            $sharedByFederatedId = $share->getSharedBy();
248
+            if ($this->userManager->userExists($sharedByFederatedId)) {
249
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
250
+                $sharedByFederatedId = $cloudId->getId();
251
+            }
252
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
253
+            $send = $this->notifications->sendRemoteShare(
254
+                $token,
255
+                $share->getSharedWith(),
256
+                $share->getNode()->getName(),
257
+                $shareId,
258
+                $share->getShareOwner(),
259
+                $ownerCloudId->getId(),
260
+                $share->getSharedBy(),
261
+                $sharedByFederatedId
262
+            );
263
+
264
+            if ($send === false) {
265
+                $failure = true;
266
+            }
267
+        } catch (\Exception $e) {
268
+            $this->logger->logException($e, [
269
+                'message' => 'Failed to notify remote server of federated share, removing share.',
270
+                'level' => ILogger::ERROR,
271
+                'app' => 'federatedfilesharing',
272
+            ]);
273
+            $failure = true;
274
+        }
275
+
276
+        if($failure) {
277
+            $this->removeShareFromTableById($shareId);
278
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
279
+                [$share->getNode()->getName(), $share->getSharedWith()]);
280
+            throw new \Exception($message_t);
281
+        }
282
+
283
+        return $shareId;
284
+
285
+    }
286
+
287
+    /**
288
+     * @param string $shareWith
289
+     * @param IShare $share
290
+     * @param string $shareId internal share Id
291
+     * @return array
292
+     * @throws \Exception
293
+     */
294
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
295
+
296
+        $remoteShare = $this->getShareFromExternalShareTable($share);
297
+        $token = $remoteShare['share_token'];
298
+        $remoteId = $remoteShare['remote_id'];
299
+        $remote = $remoteShare['remote'];
300
+
301
+        list($token, $remoteId) = $this->notifications->requestReShare(
302
+            $token,
303
+            $remoteId,
304
+            $shareId,
305
+            $remote,
306
+            $shareWith,
307
+            $share->getPermissions()
308
+        );
309
+
310
+        return [$token, $remoteId];
311
+    }
312
+
313
+    /**
314
+     * get federated share from the share_external table but exclude mounted link shares
315
+     *
316
+     * @param IShare $share
317
+     * @return array
318
+     * @throws ShareNotFound
319
+     */
320
+    protected function getShareFromExternalShareTable(IShare $share) {
321
+        $query = $this->dbConnection->getQueryBuilder();
322
+        $query->select('*')->from($this->externalShareTable)
323
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
324
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
325
+        $result = $query->execute()->fetchAll();
326
+
327
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
328
+            return $result[0];
329
+        }
330
+
331
+        throw new ShareNotFound('share not found in share_external table');
332
+    }
333
+
334
+    /**
335
+     * add share to the database and return the ID
336
+     *
337
+     * @param int $itemSource
338
+     * @param string $itemType
339
+     * @param string $shareWith
340
+     * @param string $sharedBy
341
+     * @param string $uidOwner
342
+     * @param int $permissions
343
+     * @param string $token
344
+     * @return int
345
+     */
346
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
347
+        $qb = $this->dbConnection->getQueryBuilder();
348
+        $qb->insert('share')
349
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
350
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
351
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
352
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
353
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
354
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
355
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
356
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
357
+            ->setValue('token', $qb->createNamedParameter($token))
358
+            ->setValue('stime', $qb->createNamedParameter(time()));
359
+
360
+        /*
361 361
 		 * Added to fix https://github.com/owncloud/core/issues/22215
362 362
 		 * Can be removed once we get rid of ajax/share.php
363 363
 		 */
364
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
365
-
366
-		$qb->execute();
367
-		$id = $qb->getLastInsertId();
368
-
369
-		return (int)$id;
370
-	}
371
-
372
-	/**
373
-	 * Update a share
374
-	 *
375
-	 * @param IShare $share
376
-	 * @return IShare The share object
377
-	 */
378
-	public function update(IShare $share) {
379
-		/*
364
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
365
+
366
+        $qb->execute();
367
+        $id = $qb->getLastInsertId();
368
+
369
+        return (int)$id;
370
+    }
371
+
372
+    /**
373
+     * Update a share
374
+     *
375
+     * @param IShare $share
376
+     * @return IShare The share object
377
+     */
378
+    public function update(IShare $share) {
379
+        /*
380 380
 		 * We allow updating the permissions of federated shares
381 381
 		 */
382
-		$qb = $this->dbConnection->getQueryBuilder();
383
-			$qb->update('share')
384
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
385
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
386
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
387
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
388
-				->execute();
389
-
390
-		// send the updated permission to the owner/initiator, if they are not the same
391
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
392
-			$this->sendPermissionUpdate($share);
393
-		}
394
-
395
-		return $share;
396
-	}
397
-
398
-	/**
399
-	 * send the updated permission to the owner/initiator, if they are not the same
400
-	 *
401
-	 * @param IShare $share
402
-	 * @throws ShareNotFound
403
-	 * @throws \OC\HintException
404
-	 */
405
-	protected function sendPermissionUpdate(IShare $share) {
406
-		$remoteId = $this->getRemoteId($share);
407
-		// if the local user is the owner we send the permission change to the initiator
408
-		if ($this->userManager->userExists($share->getShareOwner())) {
409
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
410
-		} else { // ... if not we send the permission change to the owner
411
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
412
-		}
413
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
414
-	}
415
-
416
-
417
-	/**
418
-	 * update successful reShare with the correct token
419
-	 *
420
-	 * @param int $shareId
421
-	 * @param string $token
422
-	 */
423
-	protected function updateSuccessfulReShare($shareId, $token) {
424
-		$query = $this->dbConnection->getQueryBuilder();
425
-		$query->update('share')
426
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
427
-			->set('token', $query->createNamedParameter($token))
428
-			->execute();
429
-	}
430
-
431
-	/**
432
-	 * store remote ID in federated reShare table
433
-	 *
434
-	 * @param $shareId
435
-	 * @param $remoteId
436
-	 */
437
-	public function storeRemoteId($shareId, $remoteId) {
438
-		$query = $this->dbConnection->getQueryBuilder();
439
-		$query->insert('federated_reshares')
440
-			->values(
441
-				[
442
-					'share_id' =>  $query->createNamedParameter($shareId),
443
-					'remote_id' => $query->createNamedParameter($remoteId),
444
-				]
445
-			);
446
-		$query->execute();
447
-	}
448
-
449
-	/**
450
-	 * get share ID on remote server for federated re-shares
451
-	 *
452
-	 * @param IShare $share
453
-	 * @return int
454
-	 * @throws ShareNotFound
455
-	 */
456
-	public function getRemoteId(IShare $share) {
457
-		$query = $this->dbConnection->getQueryBuilder();
458
-		$query->select('remote_id')->from('federated_reshares')
459
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
460
-		$data = $query->execute()->fetch();
461
-
462
-		if (!is_array($data) || !isset($data['remote_id'])) {
463
-			throw new ShareNotFound();
464
-		}
465
-
466
-		return (int)$data['remote_id'];
467
-	}
468
-
469
-	/**
470
-	 * @inheritdoc
471
-	 */
472
-	public function move(IShare $share, $recipient) {
473
-		/*
382
+        $qb = $this->dbConnection->getQueryBuilder();
383
+            $qb->update('share')
384
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
385
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
386
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
387
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
388
+                ->execute();
389
+
390
+        // send the updated permission to the owner/initiator, if they are not the same
391
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
392
+            $this->sendPermissionUpdate($share);
393
+        }
394
+
395
+        return $share;
396
+    }
397
+
398
+    /**
399
+     * send the updated permission to the owner/initiator, if they are not the same
400
+     *
401
+     * @param IShare $share
402
+     * @throws ShareNotFound
403
+     * @throws \OC\HintException
404
+     */
405
+    protected function sendPermissionUpdate(IShare $share) {
406
+        $remoteId = $this->getRemoteId($share);
407
+        // if the local user is the owner we send the permission change to the initiator
408
+        if ($this->userManager->userExists($share->getShareOwner())) {
409
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
410
+        } else { // ... if not we send the permission change to the owner
411
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
412
+        }
413
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
414
+    }
415
+
416
+
417
+    /**
418
+     * update successful reShare with the correct token
419
+     *
420
+     * @param int $shareId
421
+     * @param string $token
422
+     */
423
+    protected function updateSuccessfulReShare($shareId, $token) {
424
+        $query = $this->dbConnection->getQueryBuilder();
425
+        $query->update('share')
426
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
427
+            ->set('token', $query->createNamedParameter($token))
428
+            ->execute();
429
+    }
430
+
431
+    /**
432
+     * store remote ID in federated reShare table
433
+     *
434
+     * @param $shareId
435
+     * @param $remoteId
436
+     */
437
+    public function storeRemoteId($shareId, $remoteId) {
438
+        $query = $this->dbConnection->getQueryBuilder();
439
+        $query->insert('federated_reshares')
440
+            ->values(
441
+                [
442
+                    'share_id' =>  $query->createNamedParameter($shareId),
443
+                    'remote_id' => $query->createNamedParameter($remoteId),
444
+                ]
445
+            );
446
+        $query->execute();
447
+    }
448
+
449
+    /**
450
+     * get share ID on remote server for federated re-shares
451
+     *
452
+     * @param IShare $share
453
+     * @return int
454
+     * @throws ShareNotFound
455
+     */
456
+    public function getRemoteId(IShare $share) {
457
+        $query = $this->dbConnection->getQueryBuilder();
458
+        $query->select('remote_id')->from('federated_reshares')
459
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
460
+        $data = $query->execute()->fetch();
461
+
462
+        if (!is_array($data) || !isset($data['remote_id'])) {
463
+            throw new ShareNotFound();
464
+        }
465
+
466
+        return (int)$data['remote_id'];
467
+    }
468
+
469
+    /**
470
+     * @inheritdoc
471
+     */
472
+    public function move(IShare $share, $recipient) {
473
+        /*
474 474
 		 * This function does nothing yet as it is just for outgoing
475 475
 		 * federated shares.
476 476
 		 */
477
-		return $share;
478
-	}
479
-
480
-	/**
481
-	 * Get all children of this share
482
-	 *
483
-	 * @param IShare $parent
484
-	 * @return IShare[]
485
-	 */
486
-	public function getChildren(IShare $parent) {
487
-		$children = [];
488
-
489
-		$qb = $this->dbConnection->getQueryBuilder();
490
-		$qb->select('*')
491
-			->from('share')
492
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
493
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
494
-			->orderBy('id');
495
-
496
-		$cursor = $qb->execute();
497
-		while($data = $cursor->fetch()) {
498
-			$children[] = $this->createShareObject($data);
499
-		}
500
-		$cursor->closeCursor();
501
-
502
-		return $children;
503
-	}
504
-
505
-	/**
506
-	 * Delete a share (owner unShares the file)
507
-	 *
508
-	 * @param IShare $share
509
-	 */
510
-	public function delete(IShare $share) {
511
-
512
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
513
-
514
-		$isOwner = false;
515
-
516
-		$this->removeShareFromTable($share);
517
-
518
-		// if the local user is the owner we can send the unShare request directly...
519
-		if ($this->userManager->userExists($share->getShareOwner())) {
520
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
521
-			$this->revokeShare($share, true);
522
-			$isOwner = true;
523
-		} else { // ... if not we need to correct ID for the unShare request
524
-			$remoteId = $this->getRemoteId($share);
525
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
526
-			$this->revokeShare($share, false);
527
-		}
528
-
529
-		// send revoke notification to the other user, if initiator and owner are not the same user
530
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
531
-			$remoteId = $this->getRemoteId($share);
532
-			if ($isOwner) {
533
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
534
-			} else {
535
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
536
-			}
537
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
538
-		}
539
-	}
540
-
541
-	/**
542
-	 * in case of a re-share we need to send the other use (initiator or owner)
543
-	 * a message that the file was unshared
544
-	 *
545
-	 * @param IShare $share
546
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
547
-	 * @throws ShareNotFound
548
-	 * @throws \OC\HintException
549
-	 */
550
-	protected function revokeShare($share, $isOwner) {
551
-		// also send a unShare request to the initiator, if this is a different user than the owner
552
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
553
-			if ($isOwner) {
554
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
555
-			} else {
556
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
557
-			}
558
-			$remoteId = $this->getRemoteId($share);
559
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
560
-		}
561
-	}
562
-
563
-	/**
564
-	 * remove share from table
565
-	 *
566
-	 * @param IShare $share
567
-	 */
568
-	public function removeShareFromTable(IShare $share) {
569
-		$this->removeShareFromTableById($share->getId());
570
-	}
571
-
572
-	/**
573
-	 * remove share from table
574
-	 *
575
-	 * @param string $shareId
576
-	 */
577
-	private function removeShareFromTableById($shareId) {
578
-		$qb = $this->dbConnection->getQueryBuilder();
579
-		$qb->delete('share')
580
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
581
-		$qb->execute();
582
-
583
-		$qb->delete('federated_reshares')
584
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
585
-		$qb->execute();
586
-	}
587
-
588
-	/**
589
-	 * @inheritdoc
590
-	 */
591
-	public function deleteFromSelf(IShare $share, $recipient) {
592
-		// nothing to do here. Technically deleteFromSelf in the context of federated
593
-		// shares is a umount of a external storage. This is handled here
594
-		// apps/files_sharing/lib/external/manager.php
595
-		// TODO move this code over to this app
596
-	}
597
-
598
-
599
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
600
-		$qb = $this->dbConnection->getQueryBuilder();
601
-		$qb->select('*')
602
-			->from('share', 's')
603
-			->andWhere($qb->expr()->orX(
604
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
605
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
606
-			))
607
-			->andWhere(
608
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
609
-			);
610
-
611
-		/**
612
-		 * Reshares for this user are shares where they are the owner.
613
-		 */
614
-		if ($reshares === false) {
615
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
616
-		} else {
617
-			$qb->andWhere(
618
-				$qb->expr()->orX(
619
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
620
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
621
-				)
622
-			);
623
-		}
624
-
625
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
626
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
627
-
628
-		$qb->orderBy('id');
629
-
630
-		$cursor = $qb->execute();
631
-		$shares = [];
632
-		while ($data = $cursor->fetch()) {
633
-			$shares[$data['fileid']][] = $this->createShareObject($data);
634
-		}
635
-		$cursor->closeCursor();
636
-
637
-		return $shares;
638
-	}
639
-
640
-	/**
641
-	 * @inheritdoc
642
-	 */
643
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
644
-		$qb = $this->dbConnection->getQueryBuilder();
645
-		$qb->select('*')
646
-			->from('share');
647
-
648
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
649
-
650
-		/**
651
-		 * Reshares for this user are shares where they are the owner.
652
-		 */
653
-		if ($reshares === false) {
654
-			//Special case for old shares created via the web UI
655
-			$or1 = $qb->expr()->andX(
656
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
657
-				$qb->expr()->isNull('uid_initiator')
658
-			);
659
-
660
-			$qb->andWhere(
661
-				$qb->expr()->orX(
662
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
663
-					$or1
664
-				)
665
-			);
666
-		} else {
667
-			$qb->andWhere(
668
-				$qb->expr()->orX(
669
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
670
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
671
-				)
672
-			);
673
-		}
674
-
675
-		if ($node !== null) {
676
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
677
-		}
678
-
679
-		if ($limit !== -1) {
680
-			$qb->setMaxResults($limit);
681
-		}
682
-
683
-		$qb->setFirstResult($offset);
684
-		$qb->orderBy('id');
685
-
686
-		$cursor = $qb->execute();
687
-		$shares = [];
688
-		while($data = $cursor->fetch()) {
689
-			$shares[] = $this->createShareObject($data);
690
-		}
691
-		$cursor->closeCursor();
692
-
693
-		return $shares;
694
-	}
695
-
696
-	/**
697
-	 * @inheritdoc
698
-	 */
699
-	public function getShareById($id, $recipientId = null) {
700
-		$qb = $this->dbConnection->getQueryBuilder();
701
-
702
-		$qb->select('*')
703
-			->from('share')
704
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
705
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
706
-
707
-		$cursor = $qb->execute();
708
-		$data = $cursor->fetch();
709
-		$cursor->closeCursor();
710
-
711
-		if ($data === false) {
712
-			throw new ShareNotFoundException('Can not find share with ID: ' . $id);
713
-		}
714
-
715
-		try {
716
-			$share = $this->createShareObject($data);
717
-		} catch (InvalidShare $e) {
718
-			throw new ShareNotFoundException();
719
-		}
720
-
721
-		return $share;
722
-	}
723
-
724
-	/**
725
-	 * Get shares for a given path
726
-	 *
727
-	 * @param \OCP\Files\Node $path
728
-	 * @return IShare[]
729
-	 */
730
-	public function getSharesByPath(Node $path) {
731
-		$qb = $this->dbConnection->getQueryBuilder();
732
-
733
-		$cursor = $qb->select('*')
734
-			->from('share')
735
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
736
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
737
-			->execute();
738
-
739
-		$shares = [];
740
-		while($data = $cursor->fetch()) {
741
-			$shares[] = $this->createShareObject($data);
742
-		}
743
-		$cursor->closeCursor();
744
-
745
-		return $shares;
746
-	}
747
-
748
-	/**
749
-	 * @inheritdoc
750
-	 */
751
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
752
-		/** @var IShare[] $shares */
753
-		$shares = [];
754
-
755
-		//Get shares directly with this user
756
-		$qb = $this->dbConnection->getQueryBuilder();
757
-		$qb->select('*')
758
-			->from('share');
759
-
760
-		// Order by id
761
-		$qb->orderBy('id');
762
-
763
-		// Set limit and offset
764
-		if ($limit !== -1) {
765
-			$qb->setMaxResults($limit);
766
-		}
767
-		$qb->setFirstResult($offset);
768
-
769
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
770
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
771
-
772
-		// Filter by node if provided
773
-		if ($node !== null) {
774
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
775
-		}
776
-
777
-		$cursor = $qb->execute();
778
-
779
-		while($data = $cursor->fetch()) {
780
-			$shares[] = $this->createShareObject($data);
781
-		}
782
-		$cursor->closeCursor();
783
-
784
-
785
-		return $shares;
786
-	}
787
-
788
-	/**
789
-	 * Get a share by token
790
-	 *
791
-	 * @param string $token
792
-	 * @return IShare
793
-	 * @throws ShareNotFound
794
-	 */
795
-	public function getShareByToken($token) {
796
-		$qb = $this->dbConnection->getQueryBuilder();
797
-
798
-		$cursor = $qb->select('*')
799
-			->from('share')
800
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
801
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
802
-			->execute();
803
-
804
-		$data = $cursor->fetch();
805
-
806
-		if ($data === false) {
807
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
808
-		}
809
-
810
-		try {
811
-			$share = $this->createShareObject($data);
812
-		} catch (InvalidShare $e) {
813
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
814
-		}
815
-
816
-		return $share;
817
-	}
818
-
819
-	/**
820
-	 * get database row of a give share
821
-	 *
822
-	 * @param $id
823
-	 * @return array
824
-	 * @throws ShareNotFound
825
-	 */
826
-	private function getRawShare($id) {
827
-
828
-		// Now fetch the inserted share and create a complete share object
829
-		$qb = $this->dbConnection->getQueryBuilder();
830
-		$qb->select('*')
831
-			->from('share')
832
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
833
-
834
-		$cursor = $qb->execute();
835
-		$data = $cursor->fetch();
836
-		$cursor->closeCursor();
837
-
838
-		if ($data === false) {
839
-			throw new ShareNotFound;
840
-		}
841
-
842
-		return $data;
843
-	}
844
-
845
-	/**
846
-	 * Create a share object from an database row
847
-	 *
848
-	 * @param array $data
849
-	 * @return IShare
850
-	 * @throws InvalidShare
851
-	 * @throws ShareNotFound
852
-	 */
853
-	private function createShareObject($data) {
854
-
855
-		$share = new Share($this->rootFolder, $this->userManager);
856
-		$share->setId((int)$data['id'])
857
-			->setShareType((int)$data['share_type'])
858
-			->setPermissions((int)$data['permissions'])
859
-			->setTarget($data['file_target'])
860
-			->setMailSend((bool)$data['mail_send'])
861
-			->setToken($data['token']);
862
-
863
-		$shareTime = new \DateTime();
864
-		$shareTime->setTimestamp((int)$data['stime']);
865
-		$share->setShareTime($shareTime);
866
-		$share->setSharedWith($data['share_with']);
867
-
868
-		if ($data['uid_initiator'] !== null) {
869
-			$share->setShareOwner($data['uid_owner']);
870
-			$share->setSharedBy($data['uid_initiator']);
871
-		} else {
872
-			//OLD SHARE
873
-			$share->setSharedBy($data['uid_owner']);
874
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
875
-
876
-			$owner = $path->getOwner();
877
-			$share->setShareOwner($owner->getUID());
878
-		}
879
-
880
-		$share->setNodeId((int)$data['file_source']);
881
-		$share->setNodeType($data['item_type']);
882
-
883
-		$share->setProviderId($this->identifier());
884
-
885
-		return $share;
886
-	}
887
-
888
-	/**
889
-	 * Get the node with file $id for $user
890
-	 *
891
-	 * @param string $userId
892
-	 * @param int $id
893
-	 * @return \OCP\Files\File|\OCP\Files\Folder
894
-	 * @throws InvalidShare
895
-	 */
896
-	private function getNode($userId, $id) {
897
-		try {
898
-			$userFolder = $this->rootFolder->getUserFolder($userId);
899
-		} catch (NotFoundException $e) {
900
-			throw new InvalidShare();
901
-		}
902
-
903
-		$nodes = $userFolder->getById($id);
904
-
905
-		if (empty($nodes)) {
906
-			throw new InvalidShare();
907
-		}
908
-
909
-		return $nodes[0];
910
-	}
911
-
912
-	/**
913
-	 * A user is deleted from the system
914
-	 * So clean up the relevant shares.
915
-	 *
916
-	 * @param string $uid
917
-	 * @param int $shareType
918
-	 */
919
-	public function userDeleted($uid, $shareType) {
920
-		//TODO: probabaly a good idea to send unshare info to remote servers
921
-
922
-		$qb = $this->dbConnection->getQueryBuilder();
923
-
924
-		$qb->delete('share')
925
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
926
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
927
-			->execute();
928
-	}
929
-
930
-	/**
931
-	 * This provider does not handle groups
932
-	 *
933
-	 * @param string $gid
934
-	 */
935
-	public function groupDeleted($gid) {
936
-		// We don't handle groups here
937
-	}
938
-
939
-	/**
940
-	 * This provider does not handle groups
941
-	 *
942
-	 * @param string $uid
943
-	 * @param string $gid
944
-	 */
945
-	public function userDeletedFromGroup($uid, $gid) {
946
-		// We don't handle groups here
947
-	}
948
-
949
-	/**
950
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
951
-	 *
952
-	 * @return bool
953
-	 */
954
-	public function isOutgoingServer2serverShareEnabled() {
955
-		if ($this->gsConfig->onlyInternalFederation()) {
956
-			return false;
957
-		}
958
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
959
-		return ($result === 'yes');
960
-	}
961
-
962
-	/**
963
-	 * check if users are allowed to mount public links from other Nextclouds
964
-	 *
965
-	 * @return bool
966
-	 */
967
-	public function isIncomingServer2serverShareEnabled() {
968
-		if ($this->gsConfig->onlyInternalFederation()) {
969
-			return false;
970
-		}
971
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
972
-		return ($result === 'yes');
973
-	}
974
-
975
-	/**
976
-	 * Check if querying sharees on the lookup server is enabled
977
-	 *
978
-	 * @return bool
979
-	 */
980
-	public function isLookupServerQueriesEnabled() {
981
-		// in a global scale setup we should always query the lookup server
982
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
983
-			return true;
984
-		}
985
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
986
-		return ($result === 'yes');
987
-	}
988
-
989
-
990
-	/**
991
-	 * Check if it is allowed to publish user specific data to the lookup server
992
-	 *
993
-	 * @return bool
994
-	 */
995
-	public function isLookupServerUploadEnabled() {
996
-		// in a global scale setup the admin is responsible to keep the lookup server up-to-date
997
-		if ($this->gsConfig->isGlobalScaleEnabled()) {
998
-			return false;
999
-		}
1000
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
1001
-		return ($result === 'yes');
1002
-	}
1003
-
1004
-	/**
1005
-	 * @inheritdoc
1006
-	 */
1007
-	public function getAccessList($nodes, $currentAccess) {
1008
-		$ids = [];
1009
-		foreach ($nodes as $node) {
1010
-			$ids[] = $node->getId();
1011
-		}
1012
-
1013
-		$qb = $this->dbConnection->getQueryBuilder();
1014
-		$qb->select('share_with', 'token', 'file_source')
1015
-			->from('share')
1016
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1017
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1018
-			->andWhere($qb->expr()->orX(
1019
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1020
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1021
-			));
1022
-		$cursor = $qb->execute();
1023
-
1024
-		if ($currentAccess === false) {
1025
-			$remote = $cursor->fetch() !== false;
1026
-			$cursor->closeCursor();
1027
-
1028
-			return ['remote' => $remote];
1029
-		}
1030
-
1031
-		$remote = [];
1032
-		while ($row = $cursor->fetch()) {
1033
-			$remote[$row['share_with']] = [
1034
-				'node_id' => $row['file_source'],
1035
-				'token' => $row['token'],
1036
-			];
1037
-		}
1038
-		$cursor->closeCursor();
1039
-
1040
-		return ['remote' => $remote];
1041
-	}
477
+        return $share;
478
+    }
479
+
480
+    /**
481
+     * Get all children of this share
482
+     *
483
+     * @param IShare $parent
484
+     * @return IShare[]
485
+     */
486
+    public function getChildren(IShare $parent) {
487
+        $children = [];
488
+
489
+        $qb = $this->dbConnection->getQueryBuilder();
490
+        $qb->select('*')
491
+            ->from('share')
492
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
493
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
494
+            ->orderBy('id');
495
+
496
+        $cursor = $qb->execute();
497
+        while($data = $cursor->fetch()) {
498
+            $children[] = $this->createShareObject($data);
499
+        }
500
+        $cursor->closeCursor();
501
+
502
+        return $children;
503
+    }
504
+
505
+    /**
506
+     * Delete a share (owner unShares the file)
507
+     *
508
+     * @param IShare $share
509
+     */
510
+    public function delete(IShare $share) {
511
+
512
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
513
+
514
+        $isOwner = false;
515
+
516
+        $this->removeShareFromTable($share);
517
+
518
+        // if the local user is the owner we can send the unShare request directly...
519
+        if ($this->userManager->userExists($share->getShareOwner())) {
520
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
521
+            $this->revokeShare($share, true);
522
+            $isOwner = true;
523
+        } else { // ... if not we need to correct ID for the unShare request
524
+            $remoteId = $this->getRemoteId($share);
525
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
526
+            $this->revokeShare($share, false);
527
+        }
528
+
529
+        // send revoke notification to the other user, if initiator and owner are not the same user
530
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
531
+            $remoteId = $this->getRemoteId($share);
532
+            if ($isOwner) {
533
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
534
+            } else {
535
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
536
+            }
537
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
538
+        }
539
+    }
540
+
541
+    /**
542
+     * in case of a re-share we need to send the other use (initiator or owner)
543
+     * a message that the file was unshared
544
+     *
545
+     * @param IShare $share
546
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
547
+     * @throws ShareNotFound
548
+     * @throws \OC\HintException
549
+     */
550
+    protected function revokeShare($share, $isOwner) {
551
+        // also send a unShare request to the initiator, if this is a different user than the owner
552
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
553
+            if ($isOwner) {
554
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
555
+            } else {
556
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
557
+            }
558
+            $remoteId = $this->getRemoteId($share);
559
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
560
+        }
561
+    }
562
+
563
+    /**
564
+     * remove share from table
565
+     *
566
+     * @param IShare $share
567
+     */
568
+    public function removeShareFromTable(IShare $share) {
569
+        $this->removeShareFromTableById($share->getId());
570
+    }
571
+
572
+    /**
573
+     * remove share from table
574
+     *
575
+     * @param string $shareId
576
+     */
577
+    private function removeShareFromTableById($shareId) {
578
+        $qb = $this->dbConnection->getQueryBuilder();
579
+        $qb->delete('share')
580
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
581
+        $qb->execute();
582
+
583
+        $qb->delete('federated_reshares')
584
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
585
+        $qb->execute();
586
+    }
587
+
588
+    /**
589
+     * @inheritdoc
590
+     */
591
+    public function deleteFromSelf(IShare $share, $recipient) {
592
+        // nothing to do here. Technically deleteFromSelf in the context of federated
593
+        // shares is a umount of a external storage. This is handled here
594
+        // apps/files_sharing/lib/external/manager.php
595
+        // TODO move this code over to this app
596
+    }
597
+
598
+
599
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
600
+        $qb = $this->dbConnection->getQueryBuilder();
601
+        $qb->select('*')
602
+            ->from('share', 's')
603
+            ->andWhere($qb->expr()->orX(
604
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
605
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
606
+            ))
607
+            ->andWhere(
608
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
609
+            );
610
+
611
+        /**
612
+         * Reshares for this user are shares where they are the owner.
613
+         */
614
+        if ($reshares === false) {
615
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
616
+        } else {
617
+            $qb->andWhere(
618
+                $qb->expr()->orX(
619
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
620
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
621
+                )
622
+            );
623
+        }
624
+
625
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
626
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
627
+
628
+        $qb->orderBy('id');
629
+
630
+        $cursor = $qb->execute();
631
+        $shares = [];
632
+        while ($data = $cursor->fetch()) {
633
+            $shares[$data['fileid']][] = $this->createShareObject($data);
634
+        }
635
+        $cursor->closeCursor();
636
+
637
+        return $shares;
638
+    }
639
+
640
+    /**
641
+     * @inheritdoc
642
+     */
643
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
644
+        $qb = $this->dbConnection->getQueryBuilder();
645
+        $qb->select('*')
646
+            ->from('share');
647
+
648
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
649
+
650
+        /**
651
+         * Reshares for this user are shares where they are the owner.
652
+         */
653
+        if ($reshares === false) {
654
+            //Special case for old shares created via the web UI
655
+            $or1 = $qb->expr()->andX(
656
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
657
+                $qb->expr()->isNull('uid_initiator')
658
+            );
659
+
660
+            $qb->andWhere(
661
+                $qb->expr()->orX(
662
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
663
+                    $or1
664
+                )
665
+            );
666
+        } else {
667
+            $qb->andWhere(
668
+                $qb->expr()->orX(
669
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
670
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
671
+                )
672
+            );
673
+        }
674
+
675
+        if ($node !== null) {
676
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
677
+        }
678
+
679
+        if ($limit !== -1) {
680
+            $qb->setMaxResults($limit);
681
+        }
682
+
683
+        $qb->setFirstResult($offset);
684
+        $qb->orderBy('id');
685
+
686
+        $cursor = $qb->execute();
687
+        $shares = [];
688
+        while($data = $cursor->fetch()) {
689
+            $shares[] = $this->createShareObject($data);
690
+        }
691
+        $cursor->closeCursor();
692
+
693
+        return $shares;
694
+    }
695
+
696
+    /**
697
+     * @inheritdoc
698
+     */
699
+    public function getShareById($id, $recipientId = null) {
700
+        $qb = $this->dbConnection->getQueryBuilder();
701
+
702
+        $qb->select('*')
703
+            ->from('share')
704
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
705
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
706
+
707
+        $cursor = $qb->execute();
708
+        $data = $cursor->fetch();
709
+        $cursor->closeCursor();
710
+
711
+        if ($data === false) {
712
+            throw new ShareNotFoundException('Can not find share with ID: ' . $id);
713
+        }
714
+
715
+        try {
716
+            $share = $this->createShareObject($data);
717
+        } catch (InvalidShare $e) {
718
+            throw new ShareNotFoundException();
719
+        }
720
+
721
+        return $share;
722
+    }
723
+
724
+    /**
725
+     * Get shares for a given path
726
+     *
727
+     * @param \OCP\Files\Node $path
728
+     * @return IShare[]
729
+     */
730
+    public function getSharesByPath(Node $path) {
731
+        $qb = $this->dbConnection->getQueryBuilder();
732
+
733
+        $cursor = $qb->select('*')
734
+            ->from('share')
735
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
736
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
737
+            ->execute();
738
+
739
+        $shares = [];
740
+        while($data = $cursor->fetch()) {
741
+            $shares[] = $this->createShareObject($data);
742
+        }
743
+        $cursor->closeCursor();
744
+
745
+        return $shares;
746
+    }
747
+
748
+    /**
749
+     * @inheritdoc
750
+     */
751
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
752
+        /** @var IShare[] $shares */
753
+        $shares = [];
754
+
755
+        //Get shares directly with this user
756
+        $qb = $this->dbConnection->getQueryBuilder();
757
+        $qb->select('*')
758
+            ->from('share');
759
+
760
+        // Order by id
761
+        $qb->orderBy('id');
762
+
763
+        // Set limit and offset
764
+        if ($limit !== -1) {
765
+            $qb->setMaxResults($limit);
766
+        }
767
+        $qb->setFirstResult($offset);
768
+
769
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
770
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
771
+
772
+        // Filter by node if provided
773
+        if ($node !== null) {
774
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
775
+        }
776
+
777
+        $cursor = $qb->execute();
778
+
779
+        while($data = $cursor->fetch()) {
780
+            $shares[] = $this->createShareObject($data);
781
+        }
782
+        $cursor->closeCursor();
783
+
784
+
785
+        return $shares;
786
+    }
787
+
788
+    /**
789
+     * Get a share by token
790
+     *
791
+     * @param string $token
792
+     * @return IShare
793
+     * @throws ShareNotFound
794
+     */
795
+    public function getShareByToken($token) {
796
+        $qb = $this->dbConnection->getQueryBuilder();
797
+
798
+        $cursor = $qb->select('*')
799
+            ->from('share')
800
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
801
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
802
+            ->execute();
803
+
804
+        $data = $cursor->fetch();
805
+
806
+        if ($data === false) {
807
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
808
+        }
809
+
810
+        try {
811
+            $share = $this->createShareObject($data);
812
+        } catch (InvalidShare $e) {
813
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
814
+        }
815
+
816
+        return $share;
817
+    }
818
+
819
+    /**
820
+     * get database row of a give share
821
+     *
822
+     * @param $id
823
+     * @return array
824
+     * @throws ShareNotFound
825
+     */
826
+    private function getRawShare($id) {
827
+
828
+        // Now fetch the inserted share and create a complete share object
829
+        $qb = $this->dbConnection->getQueryBuilder();
830
+        $qb->select('*')
831
+            ->from('share')
832
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
833
+
834
+        $cursor = $qb->execute();
835
+        $data = $cursor->fetch();
836
+        $cursor->closeCursor();
837
+
838
+        if ($data === false) {
839
+            throw new ShareNotFound;
840
+        }
841
+
842
+        return $data;
843
+    }
844
+
845
+    /**
846
+     * Create a share object from an database row
847
+     *
848
+     * @param array $data
849
+     * @return IShare
850
+     * @throws InvalidShare
851
+     * @throws ShareNotFound
852
+     */
853
+    private function createShareObject($data) {
854
+
855
+        $share = new Share($this->rootFolder, $this->userManager);
856
+        $share->setId((int)$data['id'])
857
+            ->setShareType((int)$data['share_type'])
858
+            ->setPermissions((int)$data['permissions'])
859
+            ->setTarget($data['file_target'])
860
+            ->setMailSend((bool)$data['mail_send'])
861
+            ->setToken($data['token']);
862
+
863
+        $shareTime = new \DateTime();
864
+        $shareTime->setTimestamp((int)$data['stime']);
865
+        $share->setShareTime($shareTime);
866
+        $share->setSharedWith($data['share_with']);
867
+
868
+        if ($data['uid_initiator'] !== null) {
869
+            $share->setShareOwner($data['uid_owner']);
870
+            $share->setSharedBy($data['uid_initiator']);
871
+        } else {
872
+            //OLD SHARE
873
+            $share->setSharedBy($data['uid_owner']);
874
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
875
+
876
+            $owner = $path->getOwner();
877
+            $share->setShareOwner($owner->getUID());
878
+        }
879
+
880
+        $share->setNodeId((int)$data['file_source']);
881
+        $share->setNodeType($data['item_type']);
882
+
883
+        $share->setProviderId($this->identifier());
884
+
885
+        return $share;
886
+    }
887
+
888
+    /**
889
+     * Get the node with file $id for $user
890
+     *
891
+     * @param string $userId
892
+     * @param int $id
893
+     * @return \OCP\Files\File|\OCP\Files\Folder
894
+     * @throws InvalidShare
895
+     */
896
+    private function getNode($userId, $id) {
897
+        try {
898
+            $userFolder = $this->rootFolder->getUserFolder($userId);
899
+        } catch (NotFoundException $e) {
900
+            throw new InvalidShare();
901
+        }
902
+
903
+        $nodes = $userFolder->getById($id);
904
+
905
+        if (empty($nodes)) {
906
+            throw new InvalidShare();
907
+        }
908
+
909
+        return $nodes[0];
910
+    }
911
+
912
+    /**
913
+     * A user is deleted from the system
914
+     * So clean up the relevant shares.
915
+     *
916
+     * @param string $uid
917
+     * @param int $shareType
918
+     */
919
+    public function userDeleted($uid, $shareType) {
920
+        //TODO: probabaly a good idea to send unshare info to remote servers
921
+
922
+        $qb = $this->dbConnection->getQueryBuilder();
923
+
924
+        $qb->delete('share')
925
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
926
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
927
+            ->execute();
928
+    }
929
+
930
+    /**
931
+     * This provider does not handle groups
932
+     *
933
+     * @param string $gid
934
+     */
935
+    public function groupDeleted($gid) {
936
+        // We don't handle groups here
937
+    }
938
+
939
+    /**
940
+     * This provider does not handle groups
941
+     *
942
+     * @param string $uid
943
+     * @param string $gid
944
+     */
945
+    public function userDeletedFromGroup($uid, $gid) {
946
+        // We don't handle groups here
947
+    }
948
+
949
+    /**
950
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
951
+     *
952
+     * @return bool
953
+     */
954
+    public function isOutgoingServer2serverShareEnabled() {
955
+        if ($this->gsConfig->onlyInternalFederation()) {
956
+            return false;
957
+        }
958
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
959
+        return ($result === 'yes');
960
+    }
961
+
962
+    /**
963
+     * check if users are allowed to mount public links from other Nextclouds
964
+     *
965
+     * @return bool
966
+     */
967
+    public function isIncomingServer2serverShareEnabled() {
968
+        if ($this->gsConfig->onlyInternalFederation()) {
969
+            return false;
970
+        }
971
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
972
+        return ($result === 'yes');
973
+    }
974
+
975
+    /**
976
+     * Check if querying sharees on the lookup server is enabled
977
+     *
978
+     * @return bool
979
+     */
980
+    public function isLookupServerQueriesEnabled() {
981
+        // in a global scale setup we should always query the lookup server
982
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
983
+            return true;
984
+        }
985
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
986
+        return ($result === 'yes');
987
+    }
988
+
989
+
990
+    /**
991
+     * Check if it is allowed to publish user specific data to the lookup server
992
+     *
993
+     * @return bool
994
+     */
995
+    public function isLookupServerUploadEnabled() {
996
+        // in a global scale setup the admin is responsible to keep the lookup server up-to-date
997
+        if ($this->gsConfig->isGlobalScaleEnabled()) {
998
+            return false;
999
+        }
1000
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
1001
+        return ($result === 'yes');
1002
+    }
1003
+
1004
+    /**
1005
+     * @inheritdoc
1006
+     */
1007
+    public function getAccessList($nodes, $currentAccess) {
1008
+        $ids = [];
1009
+        foreach ($nodes as $node) {
1010
+            $ids[] = $node->getId();
1011
+        }
1012
+
1013
+        $qb = $this->dbConnection->getQueryBuilder();
1014
+        $qb->select('share_with', 'token', 'file_source')
1015
+            ->from('share')
1016
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
1017
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1018
+            ->andWhere($qb->expr()->orX(
1019
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1020
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1021
+            ));
1022
+        $cursor = $qb->execute();
1023
+
1024
+        if ($currentAccess === false) {
1025
+            $remote = $cursor->fetch() !== false;
1026
+            $cursor->closeCursor();
1027
+
1028
+            return ['remote' => $remote];
1029
+        }
1030
+
1031
+        $remote = [];
1032
+        while ($row = $cursor->fetch()) {
1033
+            $remote[$row['share_with']] = [
1034
+                'node_id' => $row['file_source'],
1035
+                'token' => $row['token'],
1036
+            ];
1037
+        }
1038
+        $cursor->closeCursor();
1039
+
1040
+        return ['remote' => $remote];
1041
+    }
1042 1042
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -39,113 +39,113 @@
 block discarded – undo
39 39
 
40 40
 class Application extends App {
41 41
 
42
-	/** @var FederatedShareProvider */
43
-	protected $federatedShareProvider;
42
+    /** @var FederatedShareProvider */
43
+    protected $federatedShareProvider;
44 44
 
45
-	public function __construct() {
46
-		parent::__construct('federatedfilesharing');
45
+    public function __construct() {
46
+        parent::__construct('federatedfilesharing');
47 47
 
48
-		$container = $this->getContainer();
49
-		$server = $container->getServer();
48
+        $container = $this->getContainer();
49
+        $server = $container->getServer();
50 50
 
51
-		$cloudFederationManager = $server->getCloudFederationProviderManager();
52
-		$cloudFederationManager->addCloudFederationProvider('file',
53
-			'Federated Files Sharing',
54
-			function() use ($container) {
55
-				$server = $container->getServer();
56
-				return new CloudFederationProviderFiles(
57
-					$server->getAppManager(),
58
-					$server->query(FederatedShareProvider::class),
59
-					$server->query(AddressHandler::class),
60
-					$server->getLogger(),
61
-					$server->getUserManager(),
62
-					$server->getCloudIdManager(),
63
-					$server->getActivityManager(),
64
-					$server->getNotificationManager(),
65
-					$server->getURLGenerator(),
66
-					$server->getCloudFederationFactory(),
67
-					$server->getCloudFederationProviderManager()
68
-				);
69
-			});
51
+        $cloudFederationManager = $server->getCloudFederationProviderManager();
52
+        $cloudFederationManager->addCloudFederationProvider('file',
53
+            'Federated Files Sharing',
54
+            function() use ($container) {
55
+                $server = $container->getServer();
56
+                return new CloudFederationProviderFiles(
57
+                    $server->getAppManager(),
58
+                    $server->query(FederatedShareProvider::class),
59
+                    $server->query(AddressHandler::class),
60
+                    $server->getLogger(),
61
+                    $server->getUserManager(),
62
+                    $server->getCloudIdManager(),
63
+                    $server->getActivityManager(),
64
+                    $server->getNotificationManager(),
65
+                    $server->getURLGenerator(),
66
+                    $server->getCloudFederationFactory(),
67
+                    $server->getCloudFederationProviderManager()
68
+                );
69
+            });
70 70
 
71
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
72
-			$addressHandler = new AddressHandler(
73
-				$server->getURLGenerator(),
74
-				$server->getL10N('federatedfilesharing'),
75
-				$server->getCloudIdManager()
76
-			);
77
-			$notification = new Notifications(
78
-				$addressHandler,
79
-				$server->getHTTPClientService(),
80
-				$server->query(\OCP\OCS\IDiscoveryService::class),
81
-				\OC::$server->getJobList(),
82
-				\OC::$server->getCloudFederationProviderManager(),
83
-				\OC::$server->getCloudFederationFactory()
84
-			);
85
-			return new RequestHandlerController(
86
-				$c->query('AppName'),
87
-				$server->getRequest(),
88
-				$this->getFederatedShareProvider(),
89
-				$server->getDatabaseConnection(),
90
-				$server->getShareManager(),
91
-				$notification,
92
-				$addressHandler,
93
-				$server->getUserManager(),
94
-				$server->getCloudIdManager(),
95
-				$server->getLogger(),
96
-				$server->getCloudFederationFactory(),
97
-				$server->getCloudFederationProviderManager()
98
-			);
99
-		});
100
-	}
71
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
72
+            $addressHandler = new AddressHandler(
73
+                $server->getURLGenerator(),
74
+                $server->getL10N('federatedfilesharing'),
75
+                $server->getCloudIdManager()
76
+            );
77
+            $notification = new Notifications(
78
+                $addressHandler,
79
+                $server->getHTTPClientService(),
80
+                $server->query(\OCP\OCS\IDiscoveryService::class),
81
+                \OC::$server->getJobList(),
82
+                \OC::$server->getCloudFederationProviderManager(),
83
+                \OC::$server->getCloudFederationFactory()
84
+            );
85
+            return new RequestHandlerController(
86
+                $c->query('AppName'),
87
+                $server->getRequest(),
88
+                $this->getFederatedShareProvider(),
89
+                $server->getDatabaseConnection(),
90
+                $server->getShareManager(),
91
+                $notification,
92
+                $addressHandler,
93
+                $server->getUserManager(),
94
+                $server->getCloudIdManager(),
95
+                $server->getLogger(),
96
+                $server->getCloudFederationFactory(),
97
+                $server->getCloudFederationProviderManager()
98
+            );
99
+        });
100
+    }
101 101
 
102
-	/**
103
-	 * get instance of federated share provider
104
-	 *
105
-	 * @return FederatedShareProvider
106
-	 */
107
-	public function getFederatedShareProvider() {
108
-		if ($this->federatedShareProvider === null) {
109
-			$this->initFederatedShareProvider();
110
-		}
111
-		return $this->federatedShareProvider;
112
-	}
102
+    /**
103
+     * get instance of federated share provider
104
+     *
105
+     * @return FederatedShareProvider
106
+     */
107
+    public function getFederatedShareProvider() {
108
+        if ($this->federatedShareProvider === null) {
109
+            $this->initFederatedShareProvider();
110
+        }
111
+        return $this->federatedShareProvider;
112
+    }
113 113
 
114
-	/**
115
-	 * initialize federated share provider
116
-	 */
117
-	protected function initFederatedShareProvider() {
118
-		$c = $this->getContainer();
119
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
120
-			\OC::$server->getURLGenerator(),
121
-			\OC::$server->getL10N('federatedfilesharing'),
122
-			\OC::$server->getCloudIdManager()
123
-		);
124
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
125
-			$addressHandler,
126
-			\OC::$server->getHTTPClientService(),
127
-			\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
128
-			\OC::$server->getJobList(),
129
-			\OC::$server->getCloudFederationProviderManager(),
130
-			\OC::$server->getCloudFederationFactory()
131
-		);
132
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
133
-			\OC::$server->getSecureRandom()
134
-		);
114
+    /**
115
+     * initialize federated share provider
116
+     */
117
+    protected function initFederatedShareProvider() {
118
+        $c = $this->getContainer();
119
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
120
+            \OC::$server->getURLGenerator(),
121
+            \OC::$server->getL10N('federatedfilesharing'),
122
+            \OC::$server->getCloudIdManager()
123
+        );
124
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
125
+            $addressHandler,
126
+            \OC::$server->getHTTPClientService(),
127
+            \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
128
+            \OC::$server->getJobList(),
129
+            \OC::$server->getCloudFederationProviderManager(),
130
+            \OC::$server->getCloudFederationFactory()
131
+        );
132
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
133
+            \OC::$server->getSecureRandom()
134
+        );
135 135
 
136
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
137
-			\OC::$server->getDatabaseConnection(),
138
-			$addressHandler,
139
-			$notifications,
140
-			$tokenHandler,
141
-			\OC::$server->getL10N('federatedfilesharing'),
142
-			\OC::$server->getLogger(),
143
-			\OC::$server->getLazyRootFolder(),
144
-			\OC::$server->getConfig(),
145
-			\OC::$server->getUserManager(),
146
-			\OC::$server->getCloudIdManager(),
147
-			$c->query(IConfig::class)
148
-		);
149
-	}
136
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
137
+            \OC::$server->getDatabaseConnection(),
138
+            $addressHandler,
139
+            $notifications,
140
+            $tokenHandler,
141
+            \OC::$server->getL10N('federatedfilesharing'),
142
+            \OC::$server->getLogger(),
143
+            \OC::$server->getLazyRootFolder(),
144
+            \OC::$server->getConfig(),
145
+            \OC::$server->getUserManager(),
146
+            \OC::$server->getCloudIdManager(),
147
+            $c->query(IConfig::class)
148
+        );
149
+    }
150 150
 
151 151
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 1 patch
Indentation   +522 added lines, -522 removed lines patch added patch discarded remove patch
@@ -56,526 +56,526 @@
 block discarded – undo
56 56
 
57 57
 class RequestHandlerController extends OCSController {
58 58
 
59
-	/** @var FederatedShareProvider */
60
-	private $federatedShareProvider;
61
-
62
-	/** @var IDBConnection */
63
-	private $connection;
64
-
65
-	/** @var Share\IManager */
66
-	private $shareManager;
67
-
68
-	/** @var Notifications */
69
-	private $notifications;
70
-
71
-	/** @var AddressHandler */
72
-	private $addressHandler;
73
-
74
-	/** @var  IUserManager */
75
-	private $userManager;
76
-
77
-	/** @var string */
78
-	private $shareTable = 'share';
79
-
80
-	/** @var ICloudIdManager */
81
-	private $cloudIdManager;
82
-
83
-	/** @var ILogger */
84
-	private $logger;
85
-
86
-	/** @var ICloudFederationFactory */
87
-	private $cloudFederationFactory;
88
-
89
-	/** @var ICloudFederationProviderManager */
90
-	private $cloudFederationProviderManager;
91
-
92
-	/**
93
-	 * Server2Server constructor.
94
-	 *
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param FederatedShareProvider $federatedShareProvider
98
-	 * @param IDBConnection $connection
99
-	 * @param Share\IManager $shareManager
100
-	 * @param Notifications $notifications
101
-	 * @param AddressHandler $addressHandler
102
-	 * @param IUserManager $userManager
103
-	 * @param ICloudIdManager $cloudIdManager
104
-	 * @param ILogger $logger
105
-	 * @param ICloudFederationFactory $cloudFederationFactory
106
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
107
-	 */
108
-	public function __construct($appName,
109
-								IRequest $request,
110
-								FederatedShareProvider $federatedShareProvider,
111
-								IDBConnection $connection,
112
-								Share\IManager $shareManager,
113
-								Notifications $notifications,
114
-								AddressHandler $addressHandler,
115
-								IUserManager $userManager,
116
-								ICloudIdManager $cloudIdManager,
117
-								ILogger $logger,
118
-								ICloudFederationFactory $cloudFederationFactory,
119
-								ICloudFederationProviderManager $cloudFederationProviderManager
120
-	) {
121
-		parent::__construct($appName, $request);
122
-
123
-		$this->federatedShareProvider = $federatedShareProvider;
124
-		$this->connection = $connection;
125
-		$this->shareManager = $shareManager;
126
-		$this->notifications = $notifications;
127
-		$this->addressHandler = $addressHandler;
128
-		$this->userManager = $userManager;
129
-		$this->cloudIdManager = $cloudIdManager;
130
-		$this->logger = $logger;
131
-		$this->cloudFederationFactory = $cloudFederationFactory;
132
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
133
-	}
134
-
135
-	/**
136
-	 * @NoCSRFRequired
137
-	 * @PublicPage
138
-	 *
139
-	 * create a new share
140
-	 *
141
-	 * @return Http\DataResponse
142
-	 * @throws OCSException
143
-	 */
144
-	public function createShare() {
145
-
146
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
147
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
148
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
149
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
150
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
151
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
152
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
153
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
154
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
155
-
156
-		if ($ownerFederatedId === null) {
157
-			$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
158
-		}
159
-		// if the owner of the share and the initiator are the same user
160
-		// we also complete the federated share ID for the initiator
161
-		if ($sharedByFederatedId === null && $owner === $sharedBy) {
162
-			$sharedByFederatedId = $ownerFederatedId;
163
-		}
164
-
165
-		$share = $this->cloudFederationFactory->getCloudFederationShare(
166
-			$shareWith,
167
-			$name,
168
-			'',
169
-			$remoteId,
170
-			$ownerFederatedId,
171
-			$owner,
172
-			$sharedByFederatedId,
173
-			$sharedBy,
174
-			$token,
175
-			'user',
176
-			'file'
177
-		);
178
-
179
-		try {
180
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
181
-			$provider->shareReceived($share);
182
-		} catch (ProviderDoesNotExistsException $e) {
183
-			throw new OCSException('Server does not support federated cloud sharing', 503);
184
-		} catch (ProviderCouldNotAddShareException $e) {
185
-			throw new OCSException($e->getMessage(), $e->getCode());
186
-		} catch (\Exception $e) {
187
-			throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
188
-		}
189
-
190
-		return new Http\DataResponse();
191
-	}
192
-
193
-	/**
194
-	 * @NoCSRFRequired
195
-	 * @PublicPage
196
-	 *
197
-	 * create re-share on behalf of another user
198
-	 *
199
-	 * @param int $id
200
-	 * @return Http\DataResponse
201
-	 * @throws OCSBadRequestException
202
-	 * @throws OCSForbiddenException
203
-	 * @throws OCSNotFoundException
204
-	 */
205
-	public function reShare($id) {
206
-
207
-		$token = $this->request->getParam('token', null);
208
-		$shareWith = $this->request->getParam('shareWith', null);
209
-		$permission = (int)$this->request->getParam('permission', null);
210
-		$remoteId = (int)$this->request->getParam('remoteId', null);
211
-
212
-		if ($id === null ||
213
-			$token === null ||
214
-			$shareWith === null ||
215
-			$permission === null ||
216
-			$remoteId === null
217
-		) {
218
-			throw new OCSBadRequestException();
219
-		}
220
-
221
-		try {
222
-			$share = $this->federatedShareProvider->getShareById($id);
223
-		} catch (Share\Exceptions\ShareNotFound $e) {
224
-			throw new OCSNotFoundException();
225
-		}
226
-
227
-		// don't allow to share a file back to the owner
228
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
229
-		$owner = $share->getShareOwner();
230
-		$currentServer = $this->addressHandler->generateRemoteURL();
231
-		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
232
-			throw new OCSForbiddenException();
233
-		}
234
-
235
-		if ($this->verifyShare($share, $token)) {
236
-
237
-			// check if re-sharing is allowed
238
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
239
-				$share->setPermissions($share->getPermissions() & $permission);
240
-				// the recipient of the initial share is now the initiator for the re-share
241
-				$share->setSharedBy($share->getSharedWith());
242
-				$share->setSharedWith($shareWith);
243
-				try {
244
-					$result = $this->federatedShareProvider->create($share);
245
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
246
-					return new Http\DataResponse([
247
-						'token' => $result->getToken(),
248
-						'remoteId' => $result->getId()
249
-					]);
250
-				} catch (\Exception $e) {
251
-					throw new OCSBadRequestException();
252
-				}
253
-			} else {
254
-				throw new OCSForbiddenException();
255
-			}
256
-		}
257
-		throw new OCSBadRequestException();
258
-	}
259
-
260
-	/**
261
-	 * @NoCSRFRequired
262
-	 * @PublicPage
263
-	 *
264
-	 * accept server-to-server share
265
-	 *
266
-	 * @param int $id
267
-	 * @return Http\DataResponse
268
-	 * @throws OCSException
269
-	 * @throws Share\Exceptions\ShareNotFound
270
-	 * @throws \OC\HintException
271
-	 */
272
-	public function acceptShare($id) {
273
-
274
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
275
-
276
-		$notification = [
277
-			'sharedSecret' => $token,
278
-			'message' => 'Recipient accept the share'
279
-		];
280
-
281
-		try {
282
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
283
-			$provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
284
-		} catch (ProviderDoesNotExistsException $e) {
285
-			throw new OCSException('Server does not support federated cloud sharing', 503);
286
-		} catch (ShareNotFoundException $e) {
287
-			$this->logger->debug('Share not found: ' . $e->getMessage());
288
-		} catch (\Exception $e) {
289
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
290
-		}
291
-
292
-		return new Http\DataResponse();
293
-	}
294
-
295
-	/**
296
-	 * @NoCSRFRequired
297
-	 * @PublicPage
298
-	 *
299
-	 * decline server-to-server share
300
-	 *
301
-	 * @param int $id
302
-	 * @return Http\DataResponse
303
-	 * @throws OCSException
304
-	 */
305
-	public function declineShare($id) {
306
-
307
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
308
-
309
-		$notification = [
310
-			'sharedSecret' => $token,
311
-			'message' => 'Recipient declined the share'
312
-		];
313
-
314
-		try {
315
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
316
-			$provider->notificationReceived('SHARE_DECLINED', $id, $notification);
317
-		} catch (ProviderDoesNotExistsException $e) {
318
-			throw new OCSException('Server does not support federated cloud sharing', 503);
319
-		} catch (ShareNotFoundException $e) {
320
-			$this->logger->debug('Share not found: ' . $e->getMessage());
321
-		} catch (\Exception $e) {
322
-			$this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
323
-		}
324
-
325
-		return new Http\DataResponse();
326
-	}
327
-
328
-	/**
329
-	 * @NoCSRFRequired
330
-	 * @PublicPage
331
-	 *
332
-	 * remove server-to-server share if it was unshared by the owner
333
-	 *
334
-	 * @param int $id
335
-	 * @return Http\DataResponse
336
-	 * @throws OCSException
337
-	 */
338
-	public function unshare($id) {
339
-
340
-		if (!$this->isS2SEnabled()) {
341
-			throw new OCSException('Server does not support federated cloud sharing', 503);
342
-		}
343
-
344
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
345
-
346
-		$qb = $this->connection->getQueryBuilder();
347
-		$qb->select('*')
348
-			->from('share_external')
349
-			->where(
350
-				$qb->expr()->andX(
351
-					$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
352
-					$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
353
-				)
354
-			);
355
-
356
-		$result = $qb->execute();
357
-		$share = $result->fetch();
358
-		$result->closeCursor();
359
-
360
-		if ($token && $id && !empty($share)) {
361
-
362
-			$remote = $this->cleanupRemote($share['remote']);
363
-
364
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
365
-			$mountpoint = $share['mountpoint'];
366
-			$user = $share['user'];
367
-
368
-			$qb = $this->connection->getQueryBuilder();
369
-			$qb->delete('share_external')
370
-				->where(
371
-					$qb->expr()->andX(
372
-						$qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
373
-						$qb->expr()->eq('share_token', $qb->createNamedParameter($token))
374
-					)
375
-				);
376
-
377
-			$result = $qb->execute();
378
-			$result->closeCursor();
379
-
380
-			if ($share['accepted']) {
381
-				$path = trim($mountpoint, '/');
382
-			} else {
383
-				$path = trim($share['name'], '/');
384
-			}
385
-
386
-			$notificationManager = \OC::$server->getNotificationManager();
387
-			$notification = $notificationManager->createNotification();
388
-			$notification->setApp('files_sharing')
389
-				->setUser($share['user'])
390
-				->setObject('remote_share', (int)$share['id']);
391
-			$notificationManager->markProcessed($notification);
392
-
393
-			$event = \OC::$server->getActivityManager()->generateEvent();
394
-			$event->setApp('files_sharing')
395
-				->setType('remote_share')
396
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
397
-				->setAffectedUser($user)
398
-				->setObject('remote_share', (int)$share['id'], $path);
399
-			\OC::$server->getActivityManager()->publish($event);
400
-		}
401
-
402
-		return new Http\DataResponse();
403
-	}
404
-
405
-	private function cleanupRemote($remote) {
406
-		$remote = substr($remote, strpos($remote, '://') + 3);
407
-
408
-		return rtrim($remote, '/');
409
-	}
410
-
411
-
412
-	/**
413
-	 * @NoCSRFRequired
414
-	 * @PublicPage
415
-	 *
416
-	 * federated share was revoked, either by the owner or the re-sharer
417
-	 *
418
-	 * @param int $id
419
-	 * @return Http\DataResponse
420
-	 * @throws OCSBadRequestException
421
-	 */
422
-	public function revoke($id) {
423
-		$token = $this->request->getParam('token');
424
-
425
-		$share = $this->federatedShareProvider->getShareById($id);
426
-
427
-		if ($this->verifyShare($share, $token)) {
428
-			$this->federatedShareProvider->removeShareFromTable($share);
429
-			return new Http\DataResponse();
430
-		}
431
-
432
-		throw new OCSBadRequestException();
433
-	}
434
-
435
-	/**
436
-	 * get share
437
-	 *
438
-	 * @param int $id
439
-	 * @param string $token
440
-	 * @return array|bool
441
-	 */
442
-	protected function getShare($id, $token) {
443
-		$query = $this->connection->getQueryBuilder();
444
-		$query->select('*')->from($this->shareTable)
445
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
446
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
447
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
448
-
449
-		$result = $query->execute()->fetchAll();
450
-
451
-		if (!empty($result) && isset($result[0])) {
452
-			return $result[0];
453
-		}
454
-
455
-		return false;
456
-	}
457
-
458
-	/**
459
-	 * get file
460
-	 *
461
-	 * @param string $user
462
-	 * @param int $fileSource
463
-	 * @return array with internal path of the file and a absolute link to it
464
-	 */
465
-	private function getFile($user, $fileSource) {
466
-		\OC_Util::setupFS($user);
467
-
468
-		try {
469
-			$file = \OC\Files\Filesystem::getPath($fileSource);
470
-		} catch (NotFoundException $e) {
471
-			$file = null;
472
-		}
473
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
474
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
475
-
476
-		return array($file, $link);
477
-
478
-	}
479
-
480
-	/**
481
-	 * check if server-to-server sharing is enabled
482
-	 *
483
-	 * @param bool $incoming
484
-	 * @return bool
485
-	 */
486
-	private function isS2SEnabled($incoming = false) {
487
-
488
-		$result = \OCP\App::isEnabled('files_sharing');
489
-
490
-		if ($incoming) {
491
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
492
-		} else {
493
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
494
-		}
495
-
496
-		return $result;
497
-	}
498
-
499
-	/**
500
-	 * @NoCSRFRequired
501
-	 * @PublicPage
502
-	 *
503
-	 * update share information to keep federated re-shares in sync
504
-	 *
505
-	 * @param int $id
506
-	 * @return Http\DataResponse
507
-	 * @throws OCSBadRequestException
508
-	 */
509
-	public function updatePermissions($id) {
510
-		$token = $this->request->getParam('token', null);
511
-		$permissions = $this->request->getParam('permissions', null);
512
-
513
-		try {
514
-			$share = $this->federatedShareProvider->getShareById($id);
515
-		} catch (Share\Exceptions\ShareNotFound $e) {
516
-			throw new OCSBadRequestException();
517
-		}
518
-
519
-		$validPermission = ctype_digit($permissions);
520
-		$validToken = $this->verifyShare($share, $token);
521
-		if ($validPermission && $validToken) {
522
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
523
-		} else {
524
-			throw new OCSBadRequestException();
525
-		}
526
-
527
-		return new Http\DataResponse();
528
-	}
529
-
530
-	/**
531
-	 * update permissions in database
532
-	 *
533
-	 * @param IShare $share
534
-	 * @param int $permissions
535
-	 */
536
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
537
-		$query = $this->connection->getQueryBuilder();
538
-		$query->update('share')
539
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
540
-			->set('permissions', $query->createNamedParameter($permissions))
541
-			->execute();
542
-	}
543
-
544
-	/**
545
-	 * @NoCSRFRequired
546
-	 * @PublicPage
547
-	 *
548
-	 * change the owner of a server-to-server share
549
-	 *
550
-	 * @param int $id
551
-	 * @return Http\DataResponse
552
-	 * @throws \InvalidArgumentException
553
-	 * @throws OCSException
554
-	 */
555
-	public function move($id) {
556
-
557
-		if (!$this->isS2SEnabled()) {
558
-			throw new OCSException('Server does not support federated cloud sharing', 503);
559
-		}
560
-
561
-		$token = $this->request->getParam('token');
562
-		$remote = $this->request->getParam('remote');
563
-		$newRemoteId = $this->request->getParam('remote_id', $id);
564
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
565
-
566
-		$qb = $this->connection->getQueryBuilder();
567
-		$query = $qb->update('share_external')
568
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
569
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
570
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
571
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
572
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
573
-		$affected = $query->execute();
574
-
575
-		if ($affected > 0) {
576
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
577
-		} else {
578
-			throw new OCSBadRequestException('Share not found or token invalid');
579
-		}
580
-	}
59
+    /** @var FederatedShareProvider */
60
+    private $federatedShareProvider;
61
+
62
+    /** @var IDBConnection */
63
+    private $connection;
64
+
65
+    /** @var Share\IManager */
66
+    private $shareManager;
67
+
68
+    /** @var Notifications */
69
+    private $notifications;
70
+
71
+    /** @var AddressHandler */
72
+    private $addressHandler;
73
+
74
+    /** @var  IUserManager */
75
+    private $userManager;
76
+
77
+    /** @var string */
78
+    private $shareTable = 'share';
79
+
80
+    /** @var ICloudIdManager */
81
+    private $cloudIdManager;
82
+
83
+    /** @var ILogger */
84
+    private $logger;
85
+
86
+    /** @var ICloudFederationFactory */
87
+    private $cloudFederationFactory;
88
+
89
+    /** @var ICloudFederationProviderManager */
90
+    private $cloudFederationProviderManager;
91
+
92
+    /**
93
+     * Server2Server constructor.
94
+     *
95
+     * @param string $appName
96
+     * @param IRequest $request
97
+     * @param FederatedShareProvider $federatedShareProvider
98
+     * @param IDBConnection $connection
99
+     * @param Share\IManager $shareManager
100
+     * @param Notifications $notifications
101
+     * @param AddressHandler $addressHandler
102
+     * @param IUserManager $userManager
103
+     * @param ICloudIdManager $cloudIdManager
104
+     * @param ILogger $logger
105
+     * @param ICloudFederationFactory $cloudFederationFactory
106
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
107
+     */
108
+    public function __construct($appName,
109
+                                IRequest $request,
110
+                                FederatedShareProvider $federatedShareProvider,
111
+                                IDBConnection $connection,
112
+                                Share\IManager $shareManager,
113
+                                Notifications $notifications,
114
+                                AddressHandler $addressHandler,
115
+                                IUserManager $userManager,
116
+                                ICloudIdManager $cloudIdManager,
117
+                                ILogger $logger,
118
+                                ICloudFederationFactory $cloudFederationFactory,
119
+                                ICloudFederationProviderManager $cloudFederationProviderManager
120
+    ) {
121
+        parent::__construct($appName, $request);
122
+
123
+        $this->federatedShareProvider = $federatedShareProvider;
124
+        $this->connection = $connection;
125
+        $this->shareManager = $shareManager;
126
+        $this->notifications = $notifications;
127
+        $this->addressHandler = $addressHandler;
128
+        $this->userManager = $userManager;
129
+        $this->cloudIdManager = $cloudIdManager;
130
+        $this->logger = $logger;
131
+        $this->cloudFederationFactory = $cloudFederationFactory;
132
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
133
+    }
134
+
135
+    /**
136
+     * @NoCSRFRequired
137
+     * @PublicPage
138
+     *
139
+     * create a new share
140
+     *
141
+     * @return Http\DataResponse
142
+     * @throws OCSException
143
+     */
144
+    public function createShare() {
145
+
146
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
147
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
148
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
149
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
150
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
151
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
152
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
153
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
154
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
155
+
156
+        if ($ownerFederatedId === null) {
157
+            $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
158
+        }
159
+        // if the owner of the share and the initiator are the same user
160
+        // we also complete the federated share ID for the initiator
161
+        if ($sharedByFederatedId === null && $owner === $sharedBy) {
162
+            $sharedByFederatedId = $ownerFederatedId;
163
+        }
164
+
165
+        $share = $this->cloudFederationFactory->getCloudFederationShare(
166
+            $shareWith,
167
+            $name,
168
+            '',
169
+            $remoteId,
170
+            $ownerFederatedId,
171
+            $owner,
172
+            $sharedByFederatedId,
173
+            $sharedBy,
174
+            $token,
175
+            'user',
176
+            'file'
177
+        );
178
+
179
+        try {
180
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
181
+            $provider->shareReceived($share);
182
+        } catch (ProviderDoesNotExistsException $e) {
183
+            throw new OCSException('Server does not support federated cloud sharing', 503);
184
+        } catch (ProviderCouldNotAddShareException $e) {
185
+            throw new OCSException($e->getMessage(), $e->getCode());
186
+        } catch (\Exception $e) {
187
+            throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
188
+        }
189
+
190
+        return new Http\DataResponse();
191
+    }
192
+
193
+    /**
194
+     * @NoCSRFRequired
195
+     * @PublicPage
196
+     *
197
+     * create re-share on behalf of another user
198
+     *
199
+     * @param int $id
200
+     * @return Http\DataResponse
201
+     * @throws OCSBadRequestException
202
+     * @throws OCSForbiddenException
203
+     * @throws OCSNotFoundException
204
+     */
205
+    public function reShare($id) {
206
+
207
+        $token = $this->request->getParam('token', null);
208
+        $shareWith = $this->request->getParam('shareWith', null);
209
+        $permission = (int)$this->request->getParam('permission', null);
210
+        $remoteId = (int)$this->request->getParam('remoteId', null);
211
+
212
+        if ($id === null ||
213
+            $token === null ||
214
+            $shareWith === null ||
215
+            $permission === null ||
216
+            $remoteId === null
217
+        ) {
218
+            throw new OCSBadRequestException();
219
+        }
220
+
221
+        try {
222
+            $share = $this->federatedShareProvider->getShareById($id);
223
+        } catch (Share\Exceptions\ShareNotFound $e) {
224
+            throw new OCSNotFoundException();
225
+        }
226
+
227
+        // don't allow to share a file back to the owner
228
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
229
+        $owner = $share->getShareOwner();
230
+        $currentServer = $this->addressHandler->generateRemoteURL();
231
+        if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
232
+            throw new OCSForbiddenException();
233
+        }
234
+
235
+        if ($this->verifyShare($share, $token)) {
236
+
237
+            // check if re-sharing is allowed
238
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
239
+                $share->setPermissions($share->getPermissions() & $permission);
240
+                // the recipient of the initial share is now the initiator for the re-share
241
+                $share->setSharedBy($share->getSharedWith());
242
+                $share->setSharedWith($shareWith);
243
+                try {
244
+                    $result = $this->federatedShareProvider->create($share);
245
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
246
+                    return new Http\DataResponse([
247
+                        'token' => $result->getToken(),
248
+                        'remoteId' => $result->getId()
249
+                    ]);
250
+                } catch (\Exception $e) {
251
+                    throw new OCSBadRequestException();
252
+                }
253
+            } else {
254
+                throw new OCSForbiddenException();
255
+            }
256
+        }
257
+        throw new OCSBadRequestException();
258
+    }
259
+
260
+    /**
261
+     * @NoCSRFRequired
262
+     * @PublicPage
263
+     *
264
+     * accept server-to-server share
265
+     *
266
+     * @param int $id
267
+     * @return Http\DataResponse
268
+     * @throws OCSException
269
+     * @throws Share\Exceptions\ShareNotFound
270
+     * @throws \OC\HintException
271
+     */
272
+    public function acceptShare($id) {
273
+
274
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
275
+
276
+        $notification = [
277
+            'sharedSecret' => $token,
278
+            'message' => 'Recipient accept the share'
279
+        ];
280
+
281
+        try {
282
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
283
+            $provider->notificationReceived('SHARE_ACCEPTED', $id, $notification);
284
+        } catch (ProviderDoesNotExistsException $e) {
285
+            throw new OCSException('Server does not support federated cloud sharing', 503);
286
+        } catch (ShareNotFoundException $e) {
287
+            $this->logger->debug('Share not found: ' . $e->getMessage());
288
+        } catch (\Exception $e) {
289
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
290
+        }
291
+
292
+        return new Http\DataResponse();
293
+    }
294
+
295
+    /**
296
+     * @NoCSRFRequired
297
+     * @PublicPage
298
+     *
299
+     * decline server-to-server share
300
+     *
301
+     * @param int $id
302
+     * @return Http\DataResponse
303
+     * @throws OCSException
304
+     */
305
+    public function declineShare($id) {
306
+
307
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
308
+
309
+        $notification = [
310
+            'sharedSecret' => $token,
311
+            'message' => 'Recipient declined the share'
312
+        ];
313
+
314
+        try {
315
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider('file');
316
+            $provider->notificationReceived('SHARE_DECLINED', $id, $notification);
317
+        } catch (ProviderDoesNotExistsException $e) {
318
+            throw new OCSException('Server does not support federated cloud sharing', 503);
319
+        } catch (ShareNotFoundException $e) {
320
+            $this->logger->debug('Share not found: ' . $e->getMessage());
321
+        } catch (\Exception $e) {
322
+            $this->logger->debug('internal server error, can not process notification: ' . $e->getMessage());
323
+        }
324
+
325
+        return new Http\DataResponse();
326
+    }
327
+
328
+    /**
329
+     * @NoCSRFRequired
330
+     * @PublicPage
331
+     *
332
+     * remove server-to-server share if it was unshared by the owner
333
+     *
334
+     * @param int $id
335
+     * @return Http\DataResponse
336
+     * @throws OCSException
337
+     */
338
+    public function unshare($id) {
339
+
340
+        if (!$this->isS2SEnabled()) {
341
+            throw new OCSException('Server does not support federated cloud sharing', 503);
342
+        }
343
+
344
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
345
+
346
+        $qb = $this->connection->getQueryBuilder();
347
+        $qb->select('*')
348
+            ->from('share_external')
349
+            ->where(
350
+                $qb->expr()->andX(
351
+                    $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
352
+                    $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
353
+                )
354
+            );
355
+
356
+        $result = $qb->execute();
357
+        $share = $result->fetch();
358
+        $result->closeCursor();
359
+
360
+        if ($token && $id && !empty($share)) {
361
+
362
+            $remote = $this->cleanupRemote($share['remote']);
363
+
364
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
365
+            $mountpoint = $share['mountpoint'];
366
+            $user = $share['user'];
367
+
368
+            $qb = $this->connection->getQueryBuilder();
369
+            $qb->delete('share_external')
370
+                ->where(
371
+                    $qb->expr()->andX(
372
+                        $qb->expr()->eq('remote_id', $qb->createNamedParameter($id)),
373
+                        $qb->expr()->eq('share_token', $qb->createNamedParameter($token))
374
+                    )
375
+                );
376
+
377
+            $result = $qb->execute();
378
+            $result->closeCursor();
379
+
380
+            if ($share['accepted']) {
381
+                $path = trim($mountpoint, '/');
382
+            } else {
383
+                $path = trim($share['name'], '/');
384
+            }
385
+
386
+            $notificationManager = \OC::$server->getNotificationManager();
387
+            $notification = $notificationManager->createNotification();
388
+            $notification->setApp('files_sharing')
389
+                ->setUser($share['user'])
390
+                ->setObject('remote_share', (int)$share['id']);
391
+            $notificationManager->markProcessed($notification);
392
+
393
+            $event = \OC::$server->getActivityManager()->generateEvent();
394
+            $event->setApp('files_sharing')
395
+                ->setType('remote_share')
396
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
397
+                ->setAffectedUser($user)
398
+                ->setObject('remote_share', (int)$share['id'], $path);
399
+            \OC::$server->getActivityManager()->publish($event);
400
+        }
401
+
402
+        return new Http\DataResponse();
403
+    }
404
+
405
+    private function cleanupRemote($remote) {
406
+        $remote = substr($remote, strpos($remote, '://') + 3);
407
+
408
+        return rtrim($remote, '/');
409
+    }
410
+
411
+
412
+    /**
413
+     * @NoCSRFRequired
414
+     * @PublicPage
415
+     *
416
+     * federated share was revoked, either by the owner or the re-sharer
417
+     *
418
+     * @param int $id
419
+     * @return Http\DataResponse
420
+     * @throws OCSBadRequestException
421
+     */
422
+    public function revoke($id) {
423
+        $token = $this->request->getParam('token');
424
+
425
+        $share = $this->federatedShareProvider->getShareById($id);
426
+
427
+        if ($this->verifyShare($share, $token)) {
428
+            $this->federatedShareProvider->removeShareFromTable($share);
429
+            return new Http\DataResponse();
430
+        }
431
+
432
+        throw new OCSBadRequestException();
433
+    }
434
+
435
+    /**
436
+     * get share
437
+     *
438
+     * @param int $id
439
+     * @param string $token
440
+     * @return array|bool
441
+     */
442
+    protected function getShare($id, $token) {
443
+        $query = $this->connection->getQueryBuilder();
444
+        $query->select('*')->from($this->shareTable)
445
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
446
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
447
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
448
+
449
+        $result = $query->execute()->fetchAll();
450
+
451
+        if (!empty($result) && isset($result[0])) {
452
+            return $result[0];
453
+        }
454
+
455
+        return false;
456
+    }
457
+
458
+    /**
459
+     * get file
460
+     *
461
+     * @param string $user
462
+     * @param int $fileSource
463
+     * @return array with internal path of the file and a absolute link to it
464
+     */
465
+    private function getFile($user, $fileSource) {
466
+        \OC_Util::setupFS($user);
467
+
468
+        try {
469
+            $file = \OC\Files\Filesystem::getPath($fileSource);
470
+        } catch (NotFoundException $e) {
471
+            $file = null;
472
+        }
473
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
474
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
475
+
476
+        return array($file, $link);
477
+
478
+    }
479
+
480
+    /**
481
+     * check if server-to-server sharing is enabled
482
+     *
483
+     * @param bool $incoming
484
+     * @return bool
485
+     */
486
+    private function isS2SEnabled($incoming = false) {
487
+
488
+        $result = \OCP\App::isEnabled('files_sharing');
489
+
490
+        if ($incoming) {
491
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
492
+        } else {
493
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
494
+        }
495
+
496
+        return $result;
497
+    }
498
+
499
+    /**
500
+     * @NoCSRFRequired
501
+     * @PublicPage
502
+     *
503
+     * update share information to keep federated re-shares in sync
504
+     *
505
+     * @param int $id
506
+     * @return Http\DataResponse
507
+     * @throws OCSBadRequestException
508
+     */
509
+    public function updatePermissions($id) {
510
+        $token = $this->request->getParam('token', null);
511
+        $permissions = $this->request->getParam('permissions', null);
512
+
513
+        try {
514
+            $share = $this->federatedShareProvider->getShareById($id);
515
+        } catch (Share\Exceptions\ShareNotFound $e) {
516
+            throw new OCSBadRequestException();
517
+        }
518
+
519
+        $validPermission = ctype_digit($permissions);
520
+        $validToken = $this->verifyShare($share, $token);
521
+        if ($validPermission && $validToken) {
522
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
523
+        } else {
524
+            throw new OCSBadRequestException();
525
+        }
526
+
527
+        return new Http\DataResponse();
528
+    }
529
+
530
+    /**
531
+     * update permissions in database
532
+     *
533
+     * @param IShare $share
534
+     * @param int $permissions
535
+     */
536
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
537
+        $query = $this->connection->getQueryBuilder();
538
+        $query->update('share')
539
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
540
+            ->set('permissions', $query->createNamedParameter($permissions))
541
+            ->execute();
542
+    }
543
+
544
+    /**
545
+     * @NoCSRFRequired
546
+     * @PublicPage
547
+     *
548
+     * change the owner of a server-to-server share
549
+     *
550
+     * @param int $id
551
+     * @return Http\DataResponse
552
+     * @throws \InvalidArgumentException
553
+     * @throws OCSException
554
+     */
555
+    public function move($id) {
556
+
557
+        if (!$this->isS2SEnabled()) {
558
+            throw new OCSException('Server does not support federated cloud sharing', 503);
559
+        }
560
+
561
+        $token = $this->request->getParam('token');
562
+        $remote = $this->request->getParam('remote');
563
+        $newRemoteId = $this->request->getParam('remote_id', $id);
564
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
565
+
566
+        $qb = $this->connection->getQueryBuilder();
567
+        $query = $qb->update('share_external')
568
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
569
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
570
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
571
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
572
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
573
+        $affected = $query->execute();
574
+
575
+        if ($affected > 0) {
576
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
577
+        } else {
578
+            throw new OCSBadRequestException('Share not found or token invalid');
579
+        }
580
+    }
581 581
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +468 added lines, -468 removed lines patch added patch discarded remove patch
@@ -44,512 +44,512 @@
 block discarded – undo
44 44
 use OCP\Share;
45 45
 
46 46
 class Manager {
47
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $uid;
53
-
54
-	/**
55
-	 * @var IDBConnection
56
-	 */
57
-	private $connection;
58
-
59
-	/**
60
-	 * @var \OC\Files\Mount\Manager
61
-	 */
62
-	private $mountManager;
63
-
64
-	/**
65
-	 * @var IStorageFactory
66
-	 */
67
-	private $storageLoader;
68
-
69
-	/**
70
-	 * @var IClientService
71
-	 */
72
-	private $clientService;
73
-
74
-	/**
75
-	 * @var IManager
76
-	 */
77
-	private $notificationManager;
78
-
79
-	/**
80
-	 * @var IDiscoveryService
81
-	 */
82
-	private $discoveryService;
83
-
84
-	/** @var ICloudFederationProviderManager */
85
-	private $cloudFederationProviderManager;
86
-
87
-	/** @var ICloudFederationFactory */
88
-	private $cloudFederationFactory;
89
-
90
-	/**
91
-	 * @param IDBConnection $connection
92
-	 * @param \OC\Files\Mount\Manager $mountManager
93
-	 * @param IStorageFactory $storageLoader
94
-	 * @param IClientService $clientService
95
-	 * @param IManager $notificationManager
96
-	 * @param IDiscoveryService $discoveryService
97
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
-	 * @param ICloudFederationFactory $cloudFederationFactory
99
-	 * @param string $uid
100
-	 */
101
-	public function __construct(IDBConnection $connection,
102
-								\OC\Files\Mount\Manager $mountManager,
103
-								IStorageFactory $storageLoader,
104
-								IClientService $clientService,
105
-								IManager $notificationManager,
106
-								IDiscoveryService $discoveryService,
107
-								ICloudFederationProviderManager $cloudFederationProviderManager,
108
-								ICloudFederationFactory $cloudFederationFactory,
109
-								$uid) {
110
-		$this->connection = $connection;
111
-		$this->mountManager = $mountManager;
112
-		$this->storageLoader = $storageLoader;
113
-		$this->clientService = $clientService;
114
-		$this->uid = $uid;
115
-		$this->notificationManager = $notificationManager;
116
-		$this->discoveryService = $discoveryService;
117
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
-		$this->cloudFederationFactory = $cloudFederationFactory;
119
-	}
120
-
121
-	/**
122
-	 * add new server-to-server share
123
-	 *
124
-	 * @param string $remote
125
-	 * @param string $token
126
-	 * @param string $password
127
-	 * @param string $name
128
-	 * @param string $owner
129
-	 * @param boolean $accepted
130
-	 * @param string $user
131
-	 * @param int $remoteId
132
-	 * @return Mount|null
133
-	 */
134
-	public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
135
-
136
-		$user = $user ? $user : $this->uid;
137
-		$accepted = $accepted ? 1 : 0;
138
-		$name = Filesystem::normalizePath('/' . $name);
139
-
140
-		if (!$accepted) {
141
-			// To avoid conflicts with the mount point generation later,
142
-			// we only use a temporary mount point name here. The real
143
-			// mount point name will be generated when accepting the share,
144
-			// using the original share item name.
145
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
146
-			$mountPoint = $tmpMountPointName;
147
-			$hash = md5($tmpMountPointName);
148
-			$data = [
149
-				'remote'		=> $remote,
150
-				'share_token'	=> $token,
151
-				'password'		=> $password,
152
-				'name'			=> $name,
153
-				'owner'			=> $owner,
154
-				'user'			=> $user,
155
-				'mountpoint'	=> $mountPoint,
156
-				'mountpoint_hash'	=> $hash,
157
-				'accepted'		=> $accepted,
158
-				'remote_id'		=> $remoteId,
159
-			];
160
-
161
-			$i = 1;
162
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163
-				// The external share already exists for the user
164
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
165
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
166
-				$i++;
167
-			}
168
-			return null;
169
-		}
170
-
171
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
172
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
173
-		$hash = md5($mountPoint);
174
-
175
-		$query = $this->connection->prepare('
47
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $uid;
53
+
54
+    /**
55
+     * @var IDBConnection
56
+     */
57
+    private $connection;
58
+
59
+    /**
60
+     * @var \OC\Files\Mount\Manager
61
+     */
62
+    private $mountManager;
63
+
64
+    /**
65
+     * @var IStorageFactory
66
+     */
67
+    private $storageLoader;
68
+
69
+    /**
70
+     * @var IClientService
71
+     */
72
+    private $clientService;
73
+
74
+    /**
75
+     * @var IManager
76
+     */
77
+    private $notificationManager;
78
+
79
+    /**
80
+     * @var IDiscoveryService
81
+     */
82
+    private $discoveryService;
83
+
84
+    /** @var ICloudFederationProviderManager */
85
+    private $cloudFederationProviderManager;
86
+
87
+    /** @var ICloudFederationFactory */
88
+    private $cloudFederationFactory;
89
+
90
+    /**
91
+     * @param IDBConnection $connection
92
+     * @param \OC\Files\Mount\Manager $mountManager
93
+     * @param IStorageFactory $storageLoader
94
+     * @param IClientService $clientService
95
+     * @param IManager $notificationManager
96
+     * @param IDiscoveryService $discoveryService
97
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
+     * @param ICloudFederationFactory $cloudFederationFactory
99
+     * @param string $uid
100
+     */
101
+    public function __construct(IDBConnection $connection,
102
+                                \OC\Files\Mount\Manager $mountManager,
103
+                                IStorageFactory $storageLoader,
104
+                                IClientService $clientService,
105
+                                IManager $notificationManager,
106
+                                IDiscoveryService $discoveryService,
107
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
108
+                                ICloudFederationFactory $cloudFederationFactory,
109
+                                $uid) {
110
+        $this->connection = $connection;
111
+        $this->mountManager = $mountManager;
112
+        $this->storageLoader = $storageLoader;
113
+        $this->clientService = $clientService;
114
+        $this->uid = $uid;
115
+        $this->notificationManager = $notificationManager;
116
+        $this->discoveryService = $discoveryService;
117
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
+        $this->cloudFederationFactory = $cloudFederationFactory;
119
+    }
120
+
121
+    /**
122
+     * add new server-to-server share
123
+     *
124
+     * @param string $remote
125
+     * @param string $token
126
+     * @param string $password
127
+     * @param string $name
128
+     * @param string $owner
129
+     * @param boolean $accepted
130
+     * @param string $user
131
+     * @param int $remoteId
132
+     * @return Mount|null
133
+     */
134
+    public function addShare($remote, $token, $password, $name, $owner, $accepted=false, $user = null, $remoteId = -1) {
135
+
136
+        $user = $user ? $user : $this->uid;
137
+        $accepted = $accepted ? 1 : 0;
138
+        $name = Filesystem::normalizePath('/' . $name);
139
+
140
+        if (!$accepted) {
141
+            // To avoid conflicts with the mount point generation later,
142
+            // we only use a temporary mount point name here. The real
143
+            // mount point name will be generated when accepting the share,
144
+            // using the original share item name.
145
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
146
+            $mountPoint = $tmpMountPointName;
147
+            $hash = md5($tmpMountPointName);
148
+            $data = [
149
+                'remote'		=> $remote,
150
+                'share_token'	=> $token,
151
+                'password'		=> $password,
152
+                'name'			=> $name,
153
+                'owner'			=> $owner,
154
+                'user'			=> $user,
155
+                'mountpoint'	=> $mountPoint,
156
+                'mountpoint_hash'	=> $hash,
157
+                'accepted'		=> $accepted,
158
+                'remote_id'		=> $remoteId,
159
+            ];
160
+
161
+            $i = 1;
162
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
163
+                // The external share already exists for the user
164
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
165
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
166
+                $i++;
167
+            }
168
+            return null;
169
+        }
170
+
171
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
172
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
173
+        $hash = md5($mountPoint);
174
+
175
+        $query = $this->connection->prepare('
176 176
 				INSERT INTO `*PREFIX*share_external`
177 177
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`)
178 178
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
179 179
 			');
180
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
181
-
182
-		$options = array(
183
-			'remote'	=> $remote,
184
-			'token'		=> $token,
185
-			'password'	=> $password,
186
-			'mountpoint'	=> $mountPoint,
187
-			'owner'		=> $owner
188
-		);
189
-		return $this->mountShare($options);
190
-	}
191
-
192
-	/**
193
-	 * get share
194
-	 *
195
-	 * @param int $id share id
196
-	 * @return mixed share of false
197
-	 */
198
-	public function getShare($id) {
199
-		$getShare = $this->connection->prepare('
180
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId));
181
+
182
+        $options = array(
183
+            'remote'	=> $remote,
184
+            'token'		=> $token,
185
+            'password'	=> $password,
186
+            'mountpoint'	=> $mountPoint,
187
+            'owner'		=> $owner
188
+        );
189
+        return $this->mountShare($options);
190
+    }
191
+
192
+    /**
193
+     * get share
194
+     *
195
+     * @param int $id share id
196
+     * @return mixed share of false
197
+     */
198
+    public function getShare($id) {
199
+        $getShare = $this->connection->prepare('
200 200
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
201 201
 			FROM  `*PREFIX*share_external`
202 202
 			WHERE `id` = ? AND `user` = ?');
203
-		$result = $getShare->execute(array($id, $this->uid));
204
-
205
-		return $result ? $getShare->fetch() : false;
206
-	}
207
-
208
-	/**
209
-	 * accept server-to-server share
210
-	 *
211
-	 * @param int $id
212
-	 * @return bool True if the share could be accepted, false otherwise
213
-	 */
214
-	public function acceptShare($id) {
215
-
216
-		$share = $this->getShare($id);
217
-		$result = false;
218
-
219
-		if ($share) {
220
-			\OC_Util::setupFS($this->uid);
221
-			$shareFolder = Helper::getShareFolder();
222
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
223
-			$mountPoint = Filesystem::normalizePath($mountPoint);
224
-			$hash = md5($mountPoint);
225
-
226
-			$acceptShare = $this->connection->prepare('
203
+        $result = $getShare->execute(array($id, $this->uid));
204
+
205
+        return $result ? $getShare->fetch() : false;
206
+    }
207
+
208
+    /**
209
+     * accept server-to-server share
210
+     *
211
+     * @param int $id
212
+     * @return bool True if the share could be accepted, false otherwise
213
+     */
214
+    public function acceptShare($id) {
215
+
216
+        $share = $this->getShare($id);
217
+        $result = false;
218
+
219
+        if ($share) {
220
+            \OC_Util::setupFS($this->uid);
221
+            $shareFolder = Helper::getShareFolder();
222
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
223
+            $mountPoint = Filesystem::normalizePath($mountPoint);
224
+            $hash = md5($mountPoint);
225
+
226
+            $acceptShare = $this->connection->prepare('
227 227
 				UPDATE `*PREFIX*share_external`
228 228
 				SET `accepted` = ?,
229 229
 					`mountpoint` = ?,
230 230
 					`mountpoint_hash` = ?
231 231
 				WHERE `id` = ? AND `user` = ?');
232
-			$updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
233
-			if ($updated === true) {
234
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
235
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
236
-				$result = true;
237
-			}
238
-		}
239
-
240
-		// Make sure the user has no notification for something that does not exist anymore.
241
-		$this->processNotification($id);
242
-
243
-		return $result;
244
-	}
245
-
246
-	/**
247
-	 * decline server-to-server share
248
-	 *
249
-	 * @param int $id
250
-	 * @return bool True if the share could be declined, false otherwise
251
-	 */
252
-	public function declineShare($id) {
253
-
254
-		$share = $this->getShare($id);
255
-
256
-		if ($share) {
257
-			$removeShare = $this->connection->prepare('
232
+            $updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
233
+            if ($updated === true) {
234
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
235
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
236
+                $result = true;
237
+            }
238
+        }
239
+
240
+        // Make sure the user has no notification for something that does not exist anymore.
241
+        $this->processNotification($id);
242
+
243
+        return $result;
244
+    }
245
+
246
+    /**
247
+     * decline server-to-server share
248
+     *
249
+     * @param int $id
250
+     * @return bool True if the share could be declined, false otherwise
251
+     */
252
+    public function declineShare($id) {
253
+
254
+        $share = $this->getShare($id);
255
+
256
+        if ($share) {
257
+            $removeShare = $this->connection->prepare('
258 258
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
259
-			$removeShare->execute(array($id, $this->uid));
260
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
261
-
262
-			$this->processNotification($id);
263
-			return true;
264
-		}
265
-
266
-		return false;
267
-	}
268
-
269
-	/**
270
-	 * @param int $remoteShare
271
-	 */
272
-	public function processNotification($remoteShare) {
273
-		$filter = $this->notificationManager->createNotification();
274
-		$filter->setApp('files_sharing')
275
-			->setUser($this->uid)
276
-			->setObject('remote_share', (int) $remoteShare);
277
-		$this->notificationManager->markProcessed($filter);
278
-	}
279
-
280
-	/**
281
-	 * inform remote server whether server-to-server share was accepted/declined
282
-	 *
283
-	 * @param string $remote
284
-	 * @param string $token
285
-	 * @param int $remoteId Share id on the remote host
286
-	 * @param string $feedback
287
-	 * @return boolean
288
-	 */
289
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
290
-
291
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
292
-
293
-		if($result === true) {
294
-			return true;
295
-		}
296
-
297
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
298
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
299
-
300
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
301
-		$fields = array('token' => $token);
302
-
303
-		$client = $this->clientService->newClient();
304
-
305
-		try {
306
-			$response = $client->post(
307
-				$url,
308
-				[
309
-					'body' => $fields,
310
-					'connect_timeout' => 10,
311
-				]
312
-			);
313
-		} catch (\Exception $e) {
314
-			return false;
315
-		}
316
-
317
-		$status = json_decode($response->getBody(), true);
318
-
319
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
320
-	}
321
-
322
-	/**
323
-	 * try send accept message to ocm end-point
324
-	 *
325
-	 * @param string $remoteDomain
326
-	 * @param string $token
327
-	 * @param $remoteId id of the share
328
-	 * @param string $feedback
329
-	 * @return bool
330
-	 */
331
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
332
-		switch ($feedback) {
333
-			case 'accept':
334
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
335
-				$notification->setMessage(
336
-					'SHARE_ACCEPTED',
337
-					'file',
338
-					$remoteId,
339
-					[
340
-						'sharedSecret' => $token,
341
-						'message' => 'Recipient accept the share'
342
-					]
343
-
344
-				);
345
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
346
-			case 'decline':
347
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
348
-				$notification->setMessage(
349
-					'SHARE_DECLINED',
350
-					'file',
351
-					$remoteId,
352
-					[
353
-						'sharedSecret' => $token,
354
-						'message' => 'Recipient declined the share'
355
-					]
356
-
357
-				);
358
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
359
-		}
360
-
361
-		return false;
362
-
363
-	}
364
-
365
-
366
-	/**
367
-	 * remove '/user/files' from the path and trailing slashes
368
-	 *
369
-	 * @param string $path
370
-	 * @return string
371
-	 */
372
-	protected function stripPath($path) {
373
-		$prefix = '/' . $this->uid . '/files';
374
-		return rtrim(substr($path, strlen($prefix)), '/');
375
-	}
376
-
377
-	public function getMount($data) {
378
-		$data['manager'] = $this;
379
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
380
-		$data['mountpoint'] = $mountPoint;
381
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
382
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
383
-	}
384
-
385
-	/**
386
-	 * @param array $data
387
-	 * @return Mount
388
-	 */
389
-	protected function mountShare($data) {
390
-		$mount = $this->getMount($data);
391
-		$this->mountManager->addMount($mount);
392
-		return $mount;
393
-	}
394
-
395
-	/**
396
-	 * @return \OC\Files\Mount\Manager
397
-	 */
398
-	public function getMountManager() {
399
-		return $this->mountManager;
400
-	}
401
-
402
-	/**
403
-	 * @param string $source
404
-	 * @param string $target
405
-	 * @return bool
406
-	 */
407
-	public function setMountPoint($source, $target) {
408
-		$source = $this->stripPath($source);
409
-		$target = $this->stripPath($target);
410
-		$sourceHash = md5($source);
411
-		$targetHash = md5($target);
412
-
413
-		$query = $this->connection->prepare('
259
+            $removeShare->execute(array($id, $this->uid));
260
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
261
+
262
+            $this->processNotification($id);
263
+            return true;
264
+        }
265
+
266
+        return false;
267
+    }
268
+
269
+    /**
270
+     * @param int $remoteShare
271
+     */
272
+    public function processNotification($remoteShare) {
273
+        $filter = $this->notificationManager->createNotification();
274
+        $filter->setApp('files_sharing')
275
+            ->setUser($this->uid)
276
+            ->setObject('remote_share', (int) $remoteShare);
277
+        $this->notificationManager->markProcessed($filter);
278
+    }
279
+
280
+    /**
281
+     * inform remote server whether server-to-server share was accepted/declined
282
+     *
283
+     * @param string $remote
284
+     * @param string $token
285
+     * @param int $remoteId Share id on the remote host
286
+     * @param string $feedback
287
+     * @return boolean
288
+     */
289
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
290
+
291
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
292
+
293
+        if($result === true) {
294
+            return true;
295
+        }
296
+
297
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
298
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
299
+
300
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
301
+        $fields = array('token' => $token);
302
+
303
+        $client = $this->clientService->newClient();
304
+
305
+        try {
306
+            $response = $client->post(
307
+                $url,
308
+                [
309
+                    'body' => $fields,
310
+                    'connect_timeout' => 10,
311
+                ]
312
+            );
313
+        } catch (\Exception $e) {
314
+            return false;
315
+        }
316
+
317
+        $status = json_decode($response->getBody(), true);
318
+
319
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
320
+    }
321
+
322
+    /**
323
+     * try send accept message to ocm end-point
324
+     *
325
+     * @param string $remoteDomain
326
+     * @param string $token
327
+     * @param $remoteId id of the share
328
+     * @param string $feedback
329
+     * @return bool
330
+     */
331
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
332
+        switch ($feedback) {
333
+            case 'accept':
334
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
335
+                $notification->setMessage(
336
+                    'SHARE_ACCEPTED',
337
+                    'file',
338
+                    $remoteId,
339
+                    [
340
+                        'sharedSecret' => $token,
341
+                        'message' => 'Recipient accept the share'
342
+                    ]
343
+
344
+                );
345
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
346
+            case 'decline':
347
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
348
+                $notification->setMessage(
349
+                    'SHARE_DECLINED',
350
+                    'file',
351
+                    $remoteId,
352
+                    [
353
+                        'sharedSecret' => $token,
354
+                        'message' => 'Recipient declined the share'
355
+                    ]
356
+
357
+                );
358
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
359
+        }
360
+
361
+        return false;
362
+
363
+    }
364
+
365
+
366
+    /**
367
+     * remove '/user/files' from the path and trailing slashes
368
+     *
369
+     * @param string $path
370
+     * @return string
371
+     */
372
+    protected function stripPath($path) {
373
+        $prefix = '/' . $this->uid . '/files';
374
+        return rtrim(substr($path, strlen($prefix)), '/');
375
+    }
376
+
377
+    public function getMount($data) {
378
+        $data['manager'] = $this;
379
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
380
+        $data['mountpoint'] = $mountPoint;
381
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
382
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
383
+    }
384
+
385
+    /**
386
+     * @param array $data
387
+     * @return Mount
388
+     */
389
+    protected function mountShare($data) {
390
+        $mount = $this->getMount($data);
391
+        $this->mountManager->addMount($mount);
392
+        return $mount;
393
+    }
394
+
395
+    /**
396
+     * @return \OC\Files\Mount\Manager
397
+     */
398
+    public function getMountManager() {
399
+        return $this->mountManager;
400
+    }
401
+
402
+    /**
403
+     * @param string $source
404
+     * @param string $target
405
+     * @return bool
406
+     */
407
+    public function setMountPoint($source, $target) {
408
+        $source = $this->stripPath($source);
409
+        $target = $this->stripPath($target);
410
+        $sourceHash = md5($source);
411
+        $targetHash = md5($target);
412
+
413
+        $query = $this->connection->prepare('
414 414
 			UPDATE `*PREFIX*share_external`
415 415
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
416 416
 			WHERE `mountpoint_hash` = ?
417 417
 			AND `user` = ?
418 418
 		');
419
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
419
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
420 420
 
421
-		return $result;
422
-	}
421
+        return $result;
422
+    }
423 423
 
424
-	public function removeShare($mountPoint) {
424
+    public function removeShare($mountPoint) {
425 425
 
426
-		$mountPointObj = $this->mountManager->find($mountPoint);
427
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
426
+        $mountPointObj = $this->mountManager->find($mountPoint);
427
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
428 428
 
429
-		$mountPoint = $this->stripPath($mountPoint);
430
-		$hash = md5($mountPoint);
429
+        $mountPoint = $this->stripPath($mountPoint);
430
+        $hash = md5($mountPoint);
431 431
 
432
-		$getShare = $this->connection->prepare('
432
+        $getShare = $this->connection->prepare('
433 433
 			SELECT `remote`, `share_token`, `remote_id`
434 434
 			FROM  `*PREFIX*share_external`
435 435
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
436
-		$result = $getShare->execute(array($hash, $this->uid));
437
-
438
-		if ($result) {
439
-			try {
440
-				$share = $getShare->fetch();
441
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
442
-			} catch (\Exception $e) {
443
-				// if we fail to notify the remote (probably cause the remote is down)
444
-				// we still want the share to be gone to prevent undeletable remotes
445
-			}
446
-		}
447
-		$getShare->closeCursor();
448
-
449
-		$query = $this->connection->prepare('
436
+        $result = $getShare->execute(array($hash, $this->uid));
437
+
438
+        if ($result) {
439
+            try {
440
+                $share = $getShare->fetch();
441
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
442
+            } catch (\Exception $e) {
443
+                // if we fail to notify the remote (probably cause the remote is down)
444
+                // we still want the share to be gone to prevent undeletable remotes
445
+            }
446
+        }
447
+        $getShare->closeCursor();
448
+
449
+        $query = $this->connection->prepare('
450 450
 			DELETE FROM `*PREFIX*share_external`
451 451
 			WHERE `mountpoint_hash` = ?
452 452
 			AND `user` = ?
453 453
 		');
454
-		$result = (bool)$query->execute(array($hash, $this->uid));
455
-
456
-		if($result) {
457
-			$this->removeReShares($id);
458
-		}
459
-
460
-		return $result;
461
-	}
462
-
463
-	/**
464
-	 * remove re-shares from share table and mapping in the federated_reshares table
465
-	 *
466
-	 * @param $mountPointId
467
-	 */
468
-	protected function removeReShares($mountPointId) {
469
-		$selectQuery = $this->connection->getQueryBuilder();
470
-		$query = $this->connection->getQueryBuilder();
471
-		$selectQuery->select('id')->from('share')
472
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
473
-		$select = $selectQuery->getSQL();
474
-
475
-
476
-		$query->delete('federated_reshares')
477
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
478
-		$query->execute();
479
-
480
-		$deleteReShares = $this->connection->getQueryBuilder();
481
-		$deleteReShares->delete('share')
482
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
483
-		$deleteReShares->execute();
484
-	}
485
-
486
-	/**
487
-	 * remove all shares for user $uid if the user was deleted
488
-	 *
489
-	 * @param string $uid
490
-	 * @return bool
491
-	 */
492
-	public function removeUserShares($uid) {
493
-		$getShare = $this->connection->prepare('
454
+        $result = (bool)$query->execute(array($hash, $this->uid));
455
+
456
+        if($result) {
457
+            $this->removeReShares($id);
458
+        }
459
+
460
+        return $result;
461
+    }
462
+
463
+    /**
464
+     * remove re-shares from share table and mapping in the federated_reshares table
465
+     *
466
+     * @param $mountPointId
467
+     */
468
+    protected function removeReShares($mountPointId) {
469
+        $selectQuery = $this->connection->getQueryBuilder();
470
+        $query = $this->connection->getQueryBuilder();
471
+        $selectQuery->select('id')->from('share')
472
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
473
+        $select = $selectQuery->getSQL();
474
+
475
+
476
+        $query->delete('federated_reshares')
477
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
478
+        $query->execute();
479
+
480
+        $deleteReShares = $this->connection->getQueryBuilder();
481
+        $deleteReShares->delete('share')
482
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
483
+        $deleteReShares->execute();
484
+    }
485
+
486
+    /**
487
+     * remove all shares for user $uid if the user was deleted
488
+     *
489
+     * @param string $uid
490
+     * @return bool
491
+     */
492
+    public function removeUserShares($uid) {
493
+        $getShare = $this->connection->prepare('
494 494
 			SELECT `remote`, `share_token`, `remote_id`
495 495
 			FROM  `*PREFIX*share_external`
496 496
 			WHERE `user` = ?');
497
-		$result = $getShare->execute(array($uid));
497
+        $result = $getShare->execute(array($uid));
498 498
 
499
-		if ($result) {
500
-			$shares = $getShare->fetchAll();
501
-			foreach($shares as $share) {
502
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
503
-			}
504
-		}
499
+        if ($result) {
500
+            $shares = $getShare->fetchAll();
501
+            foreach($shares as $share) {
502
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
503
+            }
504
+        }
505 505
 
506
-		$query = $this->connection->prepare('
506
+        $query = $this->connection->prepare('
507 507
 			DELETE FROM `*PREFIX*share_external`
508 508
 			WHERE `user` = ?
509 509
 		');
510
-		return (bool)$query->execute(array($uid));
511
-	}
512
-
513
-	/**
514
-	 * return a list of shares which are not yet accepted by the user
515
-	 *
516
-	 * @return array list of open server-to-server shares
517
-	 */
518
-	public function getOpenShares() {
519
-		return $this->getShares(false);
520
-	}
521
-
522
-	/**
523
-	 * return a list of shares which are accepted by the user
524
-	 *
525
-	 * @return array list of accepted server-to-server shares
526
-	 */
527
-	public function getAcceptedShares() {
528
-		return $this->getShares(true);
529
-	}
530
-
531
-	/**
532
-	 * return a list of shares for the user
533
-	 *
534
-	 * @param bool|null $accepted True for accepted only,
535
-	 *                            false for not accepted,
536
-	 *                            null for all shares of the user
537
-	 * @return array list of open server-to-server shares
538
-	 */
539
-	private function getShares($accepted) {
540
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
510
+        return (bool)$query->execute(array($uid));
511
+    }
512
+
513
+    /**
514
+     * return a list of shares which are not yet accepted by the user
515
+     *
516
+     * @return array list of open server-to-server shares
517
+     */
518
+    public function getOpenShares() {
519
+        return $this->getShares(false);
520
+    }
521
+
522
+    /**
523
+     * return a list of shares which are accepted by the user
524
+     *
525
+     * @return array list of accepted server-to-server shares
526
+     */
527
+    public function getAcceptedShares() {
528
+        return $this->getShares(true);
529
+    }
530
+
531
+    /**
532
+     * return a list of shares for the user
533
+     *
534
+     * @param bool|null $accepted True for accepted only,
535
+     *                            false for not accepted,
536
+     *                            null for all shares of the user
537
+     * @return array list of open server-to-server shares
538
+     */
539
+    private function getShares($accepted) {
540
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
541 541
 		          FROM `*PREFIX*share_external` 
542 542
 				  WHERE `user` = ?';
543
-		$parameters = [$this->uid];
544
-		if (!is_null($accepted)) {
545
-			$query .= ' AND `accepted` = ?';
546
-			$parameters[] = (int) $accepted;
547
-		}
548
-		$query .= ' ORDER BY `id` ASC';
549
-
550
-		$shares = $this->connection->prepare($query);
551
-		$result = $shares->execute($parameters);
552
-
553
-		return $result ? $shares->fetchAll() : [];
554
-	}
543
+        $parameters = [$this->uid];
544
+        if (!is_null($accepted)) {
545
+            $query .= ' AND `accepted` = ?';
546
+            $parameters[] = (int) $accepted;
547
+        }
548
+        $query .= ' ORDER BY `id` ASC';
549
+
550
+        $shares = $this->connection->prepare($query);
551
+        $result = $shares->execute($parameters);
552
+
553
+        return $result ? $shares->fetchAll() : [];
554
+    }
555 555
 }
Please login to merge, or discard this patch.