Completed
Pull Request — master (#4136)
by Björn
17:20
created
apps/sharebymail/lib/ShareByMailProvider.php 3 patches
Doc Comments   +13 added lines, -4 removed lines patch added patch discarded remove patch
@@ -191,10 +191,10 @@  discard block
 block discarded – undo
191 191
 	 * publish activity if a file/folder was shared by mail
192 192
 	 *
193 193
 	 * @param $subject
194
-	 * @param $parameters
195
-	 * @param $affectedUser
194
+	 * @param string[] $parameters
195
+	 * @param string $affectedUser
196 196
 	 * @param $fileId
197
-	 * @param $filePath
197
+	 * @param string $filePath
198 198
 	 */
199 199
 	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
200 200
 		$event = $this->activityManager->generateEvent();
@@ -246,6 +246,12 @@  discard block
 block discarded – undo
246 246
 
247 247
 	}
248 248
 
249
+	/**
250
+	 * @param string $link
251
+	 * @param string $owner
252
+	 * @param string $initiator
253
+	 * @param string $shareWith
254
+	 */
249 255
 	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
250 256
 		$ownerUser = $this->userManager->get($owner);
251 257
 		$initiatorUser = $this->userManager->get($initiator);
@@ -275,6 +281,7 @@  discard block
 block discarded – undo
275 281
 	 * @param $link
276 282
 	 * @param $owner
277 283
 	 * @param $initiator
284
+	 * @param string $template
278 285
 	 * @return string plain text mail
279 286
 	 * @throws HintException
280 287
 	 */
@@ -302,6 +309,7 @@  discard block
 block discarded – undo
302 309
 	 * @param string $filename
303 310
 	 * @param string $initiator
304 311
 	 * @param string $shareWith
312
+	 * @param string $password
305 313
 	 */
306 314
 	protected function sendPassword($filename, $initiator, $shareWith, $password) {
307 315
 		$initiatorUser = $this->userManager->get($initiator);
@@ -325,6 +333,7 @@  discard block
 block discarded – undo
325 333
 	 * @param string $filename
326 334
 	 * @param string $initiator
327 335
 	 * @param string $password
336
+	 * @param string $template
328 337
 	 * @return string plain text mail
329 338
 	 * @throws HintException
330 339
 	 */
@@ -775,7 +784,7 @@  discard block
 block discarded – undo
775 784
 	/**
776 785
 	 * get database row of a give share
777 786
 	 *
778
-	 * @param $id
787
+	 * @param integer $id
779 788
 	 * @return array
780 789
 	 * @throws ShareNotFound
781 790
 	 */
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -232,11 +232,11 @@  discard block
 block discarded – undo
232 232
 				$share->getShareOwner(),
233 233
 				$share->getSharedBy(), $share->getSharedWith());
234 234
 		} catch (HintException $hintException) {
235
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
235
+			$this->logger->error('Failed to send share by mail: '.$hintException->getMessage());
236 236
 			$this->removeShareFromTable($shareId);
237 237
 			throw $hintException;
238 238
 		} catch (\Exception $e) {
239
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
239
+			$this->logger->error('Failed to send share by mail: '.$e->getMessage());
240 240
 			$this->removeShareFromTable($shareId);
241 241
 			throw new HintException('Failed to send share by mail',
242 242
 				$this->l->t('Failed to send share by E-mail'));
@@ -252,9 +252,9 @@  discard block
 block discarded – undo
252 252
 		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
253 253
 		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
254 254
 		if ($owner === $initiator) {
255
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
255
+			$subject = (string) $this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
256 256
 		} else {
257
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
257
+			$subject = (string) $this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
258 258
 		}
259 259
 
260 260
 		$message = $this->mailer->createMessage();
@@ -281,11 +281,11 @@  discard block
 block discarded – undo
281 281
 	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
282 282
 
283 283
 		$mailBodyTemplate = new Template('sharebymail', $template, '');
284
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
285
-		$mailBodyTemplate->assign ('link', $link);
286
-		$mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
287
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
288
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
284
+		$mailBodyTemplate->assign('filename', \OCP\Util::sanitizeHTML($filename));
285
+		$mailBodyTemplate->assign('link', $link);
286
+		$mailBodyTemplate->assign('owner', \OCP\Util::sanitizeHTML($owner));
287
+		$mailBodyTemplate->assign('initiator', \OCP\Util::sanitizeHTML($initiator));
288
+		$mailBodyTemplate->assign('onBehalfOf', $initiator !== $owner);
289 289
 		$mailBody = $mailBodyTemplate->fetchPage();
290 290
 
291 291
 		if (is_string($mailBody)) {
@@ -306,11 +306,11 @@  discard block
 block discarded – undo
306 306
 	protected function sendPassword($filename, $initiator, $shareWith, $password) {
307 307
 		$initiatorUser = $this->userManager->get($initiator);
308 308
 		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
309
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', array($filename, $initiatorDisplayName));
309
+		$subject = (string) $this->l->t('Password to access »%s« shared to you by %s', array($filename, $initiatorDisplayName));
310 310
 
311 311
 		$message = $this->mailer->createMessage();
312 312
 		$htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
313
-		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
313
+		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename, $initiatorDisplayName, $password);
314 314
 		$message->setTo([$shareWith]);
315 315
 		$message->setSubject($subject);
316 316
 		$message->setBody($textBody, 'text/plain');
@@ -331,9 +331,9 @@  discard block
 block discarded – undo
331 331
 	protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
332 332
 
333 333
 		$mailBodyTemplate = new Template('sharebymail', $template, '');
334
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
335
-		$mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
336
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
334
+		$mailBodyTemplate->assign('filename', \OCP\Util::sanitizeHTML($filename));
335
+		$mailBodyTemplate->assign('password', \OCP\Util::sanitizeHTML($password));
336
+		$mailBodyTemplate->assign('initiator', \OCP\Util::sanitizeHTML($initiator));
337 337
 		$mailBody = $mailBodyTemplate->fetchPage();
338 338
 
339 339
 		if (is_string($mailBody)) {
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 	 */
353 353
 	protected function generateToken() {
354 354
 		$token = $this->secureRandom->generate(
355
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
355
+			15, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
356 356
 		return $token;
357 357
 	}
358 358
 
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 			->orderBy('id');
374 374
 
375 375
 		$cursor = $qb->execute();
376
-		while($data = $cursor->fetch()) {
376
+		while ($data = $cursor->fetch()) {
377 377
 			$children[] = $this->createShareObject($data);
378 378
 		}
379 379
 		$cursor->closeCursor();
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
 		$qb->execute();
417 417
 		$id = $qb->getLastInsertId();
418 418
 
419
-		return (int)$id;
419
+		return (int) $id;
420 420
 	}
421 421
 
422 422
 	/**
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 			$passwordHash = $this->hasher->hash($share->getPassword());
434 434
 		}
435 435
 
436
-		if($passwordHash !== null && $originalShare->getPassword() !== $passwordHash) {
436
+		if ($passwordHash !== null && $originalShare->getPassword() !== $passwordHash) {
437 437
 			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $share->getPassword());
438 438
 		}
439 439
 		/*
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
 
527 527
 		$cursor = $qb->execute();
528 528
 		$shares = [];
529
-		while($data = $cursor->fetch()) {
529
+		while ($data = $cursor->fetch()) {
530 530
 			$shares[] = $this->createShareObject($data);
531 531
 		}
532 532
 		$cursor->closeCursor();
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
 			->execute();
579 579
 
580 580
 		$shares = [];
581
-		while($data = $cursor->fetch()) {
581
+		while ($data = $cursor->fetch()) {
582 582
 			$shares[] = $this->createShareObject($data);
583 583
 		}
584 584
 		$cursor->closeCursor();
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 
618 618
 		$cursor = $qb->execute();
619 619
 
620
-		while($data = $cursor->fetch()) {
620
+		while ($data = $cursor->fetch()) {
621 621
 			$shares[] = $this->createShareObject($data);
622 622
 		}
623 623
 		$cursor->closeCursor();
@@ -680,15 +680,15 @@  discard block
 block discarded – undo
680 680
 	protected function createShareObject($data) {
681 681
 
682 682
 		$share = new Share($this->rootFolder, $this->userManager);
683
-		$share->setId((int)$data['id'])
684
-			->setShareType((int)$data['share_type'])
685
-			->setPermissions((int)$data['permissions'])
683
+		$share->setId((int) $data['id'])
684
+			->setShareType((int) $data['share_type'])
685
+			->setPermissions((int) $data['permissions'])
686 686
 			->setTarget($data['file_target'])
687
-			->setMailSend((bool)$data['mail_send'])
687
+			->setMailSend((bool) $data['mail_send'])
688 688
 			->setToken($data['token']);
689 689
 
690 690
 		$shareTime = new \DateTime();
691
-		$shareTime->setTimestamp((int)$data['stime']);
691
+		$shareTime->setTimestamp((int) $data['stime']);
692 692
 		$share->setShareTime($shareTime);
693 693
 		$share->setSharedWith($data['share_with']);
694 694
 		$share->setPassword($data['password']);
@@ -699,13 +699,13 @@  discard block
 block discarded – undo
699 699
 		} else {
700 700
 			//OLD SHARE
701 701
 			$share->setSharedBy($data['uid_owner']);
702
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
702
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
703 703
 
704 704
 			$owner = $path->getOwner();
705 705
 			$share->setShareOwner($owner->getUID());
706 706
 		}
707 707
 
708
-		$share->setNodeId((int)$data['file_source']);
708
+		$share->setNodeId((int) $data['file_source']);
709 709
 		$share->setNodeType($data['item_type']);
710 710
 
711 711
 		$share->setProviderId($this->identifier());
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 			);
825 825
 		}
826 826
 
827
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
827
+		$qb->innerJoin('s', 'filecache', 'f', 's.file_source = f.fileid');
828 828
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
829 829
 
830 830
 		$qb->orderBy('id');
Please login to merge, or discard this patch.
Indentation   +783 added lines, -783 removed lines patch added patch discarded remove patch
@@ -49,795 +49,795 @@
 block discarded – undo
49 49
  */
50 50
 class ShareByMailProvider implements IShareProvider {
51 51
 
52
-	/** @var  IDBConnection */
53
-	private $dbConnection;
54
-
55
-	/** @var ILogger */
56
-	private $logger;
57
-
58
-	/** @var ISecureRandom */
59
-	private $secureRandom;
60
-
61
-	/** @var IUserManager */
62
-	private $userManager;
63
-
64
-	/** @var IRootFolder */
65
-	private $rootFolder;
66
-
67
-	/** @var IL10N */
68
-	private $l;
69
-
70
-	/** @var IMailer */
71
-	private $mailer;
72
-
73
-	/** @var IURLGenerator */
74
-	private $urlGenerator;
75
-
76
-	/** @var IManager  */
77
-	private $activityManager;
78
-
79
-	/** @var IHasher */
80
-	private $hasher;
81
-
82
-	/**
83
-	 * Return the identifier of this provider.
84
-	 *
85
-	 * @return string Containing only [a-zA-Z0-9]
86
-	 */
87
-	public function identifier() {
88
-		return 'ocMailShare';
89
-	}
90
-
91
-	/**
92
-	 * DefaultShareProvider constructor.
93
-	 *
94
-	 * @param IDBConnection $connection
95
-	 * @param ISecureRandom $secureRandom
96
-	 * @param IUserManager $userManager
97
-	 * @param IRootFolder $rootFolder
98
-	 * @param IL10N $l
99
-	 * @param ILogger $logger
100
-	 * @param IMailer $mailer
101
-	 * @param IURLGenerator $urlGenerator
102
-	 * @param IManager $activityManager
103
-	 * @param IHasher $hasher
104
-	 */
105
-	public function __construct(
106
-		IDBConnection $connection,
107
-		ISecureRandom $secureRandom,
108
-		IUserManager $userManager,
109
-		IRootFolder $rootFolder,
110
-		IL10N $l,
111
-		ILogger $logger,
112
-		IMailer $mailer,
113
-		IURLGenerator $urlGenerator,
114
-		IManager $activityManager,
115
-		IHasher $hasher
116
-	) {
117
-		$this->dbConnection = $connection;
118
-		$this->secureRandom = $secureRandom;
119
-		$this->userManager = $userManager;
120
-		$this->rootFolder = $rootFolder;
121
-		$this->l = $l;
122
-		$this->logger = $logger;
123
-		$this->mailer = $mailer;
124
-		$this->urlGenerator = $urlGenerator;
125
-		$this->activityManager = $activityManager;
126
-		$this->hasher = $hasher;
127
-	}
128
-
129
-	/**
130
-	 * Share a path
131
-	 *
132
-	 * @param IShare $share
133
-	 * @return IShare The share object
134
-	 * @throws ShareNotFound
135
-	 * @throws \Exception
136
-	 */
137
-	public function create(IShare $share) {
138
-
139
-		$shareWith = $share->getSharedWith();
140
-		/*
52
+    /** @var  IDBConnection */
53
+    private $dbConnection;
54
+
55
+    /** @var ILogger */
56
+    private $logger;
57
+
58
+    /** @var ISecureRandom */
59
+    private $secureRandom;
60
+
61
+    /** @var IUserManager */
62
+    private $userManager;
63
+
64
+    /** @var IRootFolder */
65
+    private $rootFolder;
66
+
67
+    /** @var IL10N */
68
+    private $l;
69
+
70
+    /** @var IMailer */
71
+    private $mailer;
72
+
73
+    /** @var IURLGenerator */
74
+    private $urlGenerator;
75
+
76
+    /** @var IManager  */
77
+    private $activityManager;
78
+
79
+    /** @var IHasher */
80
+    private $hasher;
81
+
82
+    /**
83
+     * Return the identifier of this provider.
84
+     *
85
+     * @return string Containing only [a-zA-Z0-9]
86
+     */
87
+    public function identifier() {
88
+        return 'ocMailShare';
89
+    }
90
+
91
+    /**
92
+     * DefaultShareProvider constructor.
93
+     *
94
+     * @param IDBConnection $connection
95
+     * @param ISecureRandom $secureRandom
96
+     * @param IUserManager $userManager
97
+     * @param IRootFolder $rootFolder
98
+     * @param IL10N $l
99
+     * @param ILogger $logger
100
+     * @param IMailer $mailer
101
+     * @param IURLGenerator $urlGenerator
102
+     * @param IManager $activityManager
103
+     * @param IHasher $hasher
104
+     */
105
+    public function __construct(
106
+        IDBConnection $connection,
107
+        ISecureRandom $secureRandom,
108
+        IUserManager $userManager,
109
+        IRootFolder $rootFolder,
110
+        IL10N $l,
111
+        ILogger $logger,
112
+        IMailer $mailer,
113
+        IURLGenerator $urlGenerator,
114
+        IManager $activityManager,
115
+        IHasher $hasher
116
+    ) {
117
+        $this->dbConnection = $connection;
118
+        $this->secureRandom = $secureRandom;
119
+        $this->userManager = $userManager;
120
+        $this->rootFolder = $rootFolder;
121
+        $this->l = $l;
122
+        $this->logger = $logger;
123
+        $this->mailer = $mailer;
124
+        $this->urlGenerator = $urlGenerator;
125
+        $this->activityManager = $activityManager;
126
+        $this->hasher = $hasher;
127
+    }
128
+
129
+    /**
130
+     * Share a path
131
+     *
132
+     * @param IShare $share
133
+     * @return IShare The share object
134
+     * @throws ShareNotFound
135
+     * @throws \Exception
136
+     */
137
+    public function create(IShare $share) {
138
+
139
+        $shareWith = $share->getSharedWith();
140
+        /*
141 141
 		 * Check if file is not already shared with the remote user
142 142
 		 */
143
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
144
-		if (!empty($alreadyShared)) {
145
-			$message = 'Sharing %s failed, this item is already shared with %s';
146
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
147
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
148
-			throw new \Exception($message_t);
149
-		}
150
-
151
-		$shareId = $this->createMailShare($share);
152
-		$this->createActivity($share);
153
-		$data = $this->getRawShare($shareId);
154
-		return $this->createShareObject($data);
155
-
156
-	}
157
-
158
-	/**
159
-	 * create activity if a file/folder was shared by mail
160
-	 *
161
-	 * @param IShare $share
162
-	 */
163
-	protected function createActivity(IShare $share) {
164
-
165
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
166
-
167
-		$this->publishActivity(
168
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
169
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
170
-			$share->getSharedBy(),
171
-			$share->getNode()->getId(),
172
-			$userFolder->getRelativePath($share->getNode()->getPath())
173
-		);
174
-
175
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
176
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
177
-			$fileId = $share->getNode()->getId();
178
-			$nodes = $ownerFolder->getById($fileId);
179
-			$ownerPath = $nodes[0]->getPath();
180
-			$this->publishActivity(
181
-				Activity::SUBJECT_SHARED_EMAIL_BY,
182
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
183
-				$share->getShareOwner(),
184
-				$fileId,
185
-				$ownerFolder->getRelativePath($ownerPath)
186
-			);
187
-		}
188
-
189
-	}
190
-
191
-	/**
192
-	 * publish activity if a file/folder was shared by mail
193
-	 *
194
-	 * @param $subject
195
-	 * @param $parameters
196
-	 * @param $affectedUser
197
-	 * @param $fileId
198
-	 * @param $filePath
199
-	 */
200
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
201
-		$event = $this->activityManager->generateEvent();
202
-		$event->setApp('sharebymail')
203
-			->setType('shared')
204
-			->setSubject($subject, $parameters)
205
-			->setAffectedUser($affectedUser)
206
-			->setObject('files', $fileId, $filePath);
207
-		$this->activityManager->publish($event);
208
-
209
-	}
210
-
211
-	/**
212
-	 * @param IShare $share
213
-	 * @return int
214
-	 * @throws \Exception
215
-	 */
216
-	protected function createMailShare(IShare $share) {
217
-		$share->setToken($this->generateToken());
218
-		$shareId = $this->addShareToDB(
219
-			$share->getNodeId(),
220
-			$share->getNodeType(),
221
-			$share->getSharedWith(),
222
-			$share->getSharedBy(),
223
-			$share->getShareOwner(),
224
-			$share->getPermissions(),
225
-			$share->getToken()
226
-		);
227
-
228
-		try {
229
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
230
-				['token' => $share->getToken()]);
231
-			$this->sendMailNotification($share->getNode()->getName(),
232
-				$link,
233
-				$share->getShareOwner(),
234
-				$share->getSharedBy(), $share->getSharedWith());
235
-		} catch (HintException $hintException) {
236
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
237
-			$this->removeShareFromTable($shareId);
238
-			throw $hintException;
239
-		} catch (\Exception $e) {
240
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
241
-			$this->removeShareFromTable($shareId);
242
-			throw new HintException('Failed to send share by mail',
243
-				$this->l->t('Failed to send share by E-mail'));
244
-		}
245
-
246
-		return $shareId;
247
-
248
-	}
249
-
250
-	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
251
-		$ownerUser = $this->userManager->get($owner);
252
-		$initiatorUser = $this->userManager->get($initiator);
253
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
254
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
255
-		if ($owner === $initiator) {
256
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
257
-		} else {
258
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
259
-		}
260
-
261
-		$message = $this->mailer->createMessage();
262
-		$htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
263
-		$textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
264
-		$message->setTo([$shareWith]);
265
-		$message->setSubject($subject);
266
-		$message->setBody($textBody, 'text/plain');
267
-		$message->setHtmlBody($htmlBody);
268
-		$this->mailer->send($message);
269
-
270
-	}
271
-
272
-	/**
273
-	 * create mail body
274
-	 *
275
-	 * @param $filename
276
-	 * @param $link
277
-	 * @param $owner
278
-	 * @param $initiator
279
-	 * @return string plain text mail
280
-	 * @throws HintException
281
-	 */
282
-	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
283
-
284
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
285
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
286
-		$mailBodyTemplate->assign ('link', $link);
287
-		$mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
288
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
289
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
290
-		$mailBody = $mailBodyTemplate->fetchPage();
291
-
292
-		if (is_string($mailBody)) {
293
-			return $mailBody;
294
-		}
295
-
296
-		throw new HintException('Failed to create the E-mail',
297
-			$this->l->t('Failed to create the E-mail'));
298
-	}
299
-
300
-	/**
301
-	 * send password to recipient of a mail share
302
-	 *
303
-	 * @param string $filename
304
-	 * @param string $initiator
305
-	 * @param string $shareWith
306
-	 */
307
-	protected function sendPassword($filename, $initiator, $shareWith, $password) {
308
-		$initiatorUser = $this->userManager->get($initiator);
309
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
310
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', array($filename, $initiatorDisplayName));
311
-
312
-		$message = $this->mailer->createMessage();
313
-		$htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
314
-		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
315
-		$message->setTo([$shareWith]);
316
-		$message->setSubject($subject);
317
-		$message->setBody($textBody, 'text/plain');
318
-		$message->setHtmlBody($htmlBody);
319
-		$this->mailer->send($message);
320
-
321
-	}
322
-
323
-	/**
324
-	 * create mail body to send password to recipient
325
-	 *
326
-	 * @param string $filename
327
-	 * @param string $initiator
328
-	 * @param string $password
329
-	 * @return string plain text mail
330
-	 * @throws HintException
331
-	 */
332
-	protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
333
-
334
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
335
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
336
-		$mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
337
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
338
-		$mailBody = $mailBodyTemplate->fetchPage();
339
-
340
-		if (is_string($mailBody)) {
341
-			return $mailBody;
342
-		}
343
-
344
-		throw new HintException('Failed to create the E-mail',
345
-			$this->l->t('Failed to create the E-mail'));
346
-	}
347
-
348
-
349
-	/**
350
-	 * generate share token
351
-	 *
352
-	 * @return string
353
-	 */
354
-	protected function generateToken() {
355
-		$token = $this->secureRandom->generate(
356
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
357
-		return $token;
358
-	}
359
-
360
-	/**
361
-	 * Get all children of this share
362
-	 *
363
-	 * @param IShare $parent
364
-	 * @return IShare[]
365
-	 */
366
-	public function getChildren(IShare $parent) {
367
-		$children = [];
368
-
369
-		$qb = $this->dbConnection->getQueryBuilder();
370
-		$qb->select('*')
371
-			->from('share')
372
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
373
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
374
-			->orderBy('id');
375
-
376
-		$cursor = $qb->execute();
377
-		while($data = $cursor->fetch()) {
378
-			$children[] = $this->createShareObject($data);
379
-		}
380
-		$cursor->closeCursor();
381
-
382
-		return $children;
383
-	}
384
-
385
-	/**
386
-	 * add share to the database and return the ID
387
-	 *
388
-	 * @param int $itemSource
389
-	 * @param string $itemType
390
-	 * @param string $shareWith
391
-	 * @param string $sharedBy
392
-	 * @param string $uidOwner
393
-	 * @param int $permissions
394
-	 * @param string $token
395
-	 * @return int
396
-	 */
397
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
398
-		$qb = $this->dbConnection->getQueryBuilder();
399
-		$qb->insert('share')
400
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
401
-			->setValue('item_type', $qb->createNamedParameter($itemType))
402
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
403
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
404
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
405
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
406
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
407
-			->setValue('permissions', $qb->createNamedParameter($permissions))
408
-			->setValue('token', $qb->createNamedParameter($token))
409
-			->setValue('stime', $qb->createNamedParameter(time()));
410
-
411
-		/*
143
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
144
+        if (!empty($alreadyShared)) {
145
+            $message = 'Sharing %s failed, this item is already shared with %s';
146
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
147
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
148
+            throw new \Exception($message_t);
149
+        }
150
+
151
+        $shareId = $this->createMailShare($share);
152
+        $this->createActivity($share);
153
+        $data = $this->getRawShare($shareId);
154
+        return $this->createShareObject($data);
155
+
156
+    }
157
+
158
+    /**
159
+     * create activity if a file/folder was shared by mail
160
+     *
161
+     * @param IShare $share
162
+     */
163
+    protected function createActivity(IShare $share) {
164
+
165
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
166
+
167
+        $this->publishActivity(
168
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
169
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
170
+            $share->getSharedBy(),
171
+            $share->getNode()->getId(),
172
+            $userFolder->getRelativePath($share->getNode()->getPath())
173
+        );
174
+
175
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
176
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
177
+            $fileId = $share->getNode()->getId();
178
+            $nodes = $ownerFolder->getById($fileId);
179
+            $ownerPath = $nodes[0]->getPath();
180
+            $this->publishActivity(
181
+                Activity::SUBJECT_SHARED_EMAIL_BY,
182
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
183
+                $share->getShareOwner(),
184
+                $fileId,
185
+                $ownerFolder->getRelativePath($ownerPath)
186
+            );
187
+        }
188
+
189
+    }
190
+
191
+    /**
192
+     * publish activity if a file/folder was shared by mail
193
+     *
194
+     * @param $subject
195
+     * @param $parameters
196
+     * @param $affectedUser
197
+     * @param $fileId
198
+     * @param $filePath
199
+     */
200
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
201
+        $event = $this->activityManager->generateEvent();
202
+        $event->setApp('sharebymail')
203
+            ->setType('shared')
204
+            ->setSubject($subject, $parameters)
205
+            ->setAffectedUser($affectedUser)
206
+            ->setObject('files', $fileId, $filePath);
207
+        $this->activityManager->publish($event);
208
+
209
+    }
210
+
211
+    /**
212
+     * @param IShare $share
213
+     * @return int
214
+     * @throws \Exception
215
+     */
216
+    protected function createMailShare(IShare $share) {
217
+        $share->setToken($this->generateToken());
218
+        $shareId = $this->addShareToDB(
219
+            $share->getNodeId(),
220
+            $share->getNodeType(),
221
+            $share->getSharedWith(),
222
+            $share->getSharedBy(),
223
+            $share->getShareOwner(),
224
+            $share->getPermissions(),
225
+            $share->getToken()
226
+        );
227
+
228
+        try {
229
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
230
+                ['token' => $share->getToken()]);
231
+            $this->sendMailNotification($share->getNode()->getName(),
232
+                $link,
233
+                $share->getShareOwner(),
234
+                $share->getSharedBy(), $share->getSharedWith());
235
+        } catch (HintException $hintException) {
236
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
237
+            $this->removeShareFromTable($shareId);
238
+            throw $hintException;
239
+        } catch (\Exception $e) {
240
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
241
+            $this->removeShareFromTable($shareId);
242
+            throw new HintException('Failed to send share by mail',
243
+                $this->l->t('Failed to send share by E-mail'));
244
+        }
245
+
246
+        return $shareId;
247
+
248
+    }
249
+
250
+    protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
251
+        $ownerUser = $this->userManager->get($owner);
252
+        $initiatorUser = $this->userManager->get($initiator);
253
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
254
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
255
+        if ($owner === $initiator) {
256
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
257
+        } else {
258
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
259
+        }
260
+
261
+        $message = $this->mailer->createMessage();
262
+        $htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
263
+        $textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
264
+        $message->setTo([$shareWith]);
265
+        $message->setSubject($subject);
266
+        $message->setBody($textBody, 'text/plain');
267
+        $message->setHtmlBody($htmlBody);
268
+        $this->mailer->send($message);
269
+
270
+    }
271
+
272
+    /**
273
+     * create mail body
274
+     *
275
+     * @param $filename
276
+     * @param $link
277
+     * @param $owner
278
+     * @param $initiator
279
+     * @return string plain text mail
280
+     * @throws HintException
281
+     */
282
+    protected function createMailBody($template, $filename, $link, $owner, $initiator) {
283
+
284
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
285
+        $mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
286
+        $mailBodyTemplate->assign ('link', $link);
287
+        $mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
288
+        $mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
289
+        $mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
290
+        $mailBody = $mailBodyTemplate->fetchPage();
291
+
292
+        if (is_string($mailBody)) {
293
+            return $mailBody;
294
+        }
295
+
296
+        throw new HintException('Failed to create the E-mail',
297
+            $this->l->t('Failed to create the E-mail'));
298
+    }
299
+
300
+    /**
301
+     * send password to recipient of a mail share
302
+     *
303
+     * @param string $filename
304
+     * @param string $initiator
305
+     * @param string $shareWith
306
+     */
307
+    protected function sendPassword($filename, $initiator, $shareWith, $password) {
308
+        $initiatorUser = $this->userManager->get($initiator);
309
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
310
+        $subject = (string)$this->l->t('Password to access »%s« shared to you by %s', array($filename, $initiatorDisplayName));
311
+
312
+        $message = $this->mailer->createMessage();
313
+        $htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
314
+        $textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
315
+        $message->setTo([$shareWith]);
316
+        $message->setSubject($subject);
317
+        $message->setBody($textBody, 'text/plain');
318
+        $message->setHtmlBody($htmlBody);
319
+        $this->mailer->send($message);
320
+
321
+    }
322
+
323
+    /**
324
+     * create mail body to send password to recipient
325
+     *
326
+     * @param string $filename
327
+     * @param string $initiator
328
+     * @param string $password
329
+     * @return string plain text mail
330
+     * @throws HintException
331
+     */
332
+    protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
333
+
334
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
335
+        $mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
336
+        $mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
337
+        $mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
338
+        $mailBody = $mailBodyTemplate->fetchPage();
339
+
340
+        if (is_string($mailBody)) {
341
+            return $mailBody;
342
+        }
343
+
344
+        throw new HintException('Failed to create the E-mail',
345
+            $this->l->t('Failed to create the E-mail'));
346
+    }
347
+
348
+
349
+    /**
350
+     * generate share token
351
+     *
352
+     * @return string
353
+     */
354
+    protected function generateToken() {
355
+        $token = $this->secureRandom->generate(
356
+            15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
357
+        return $token;
358
+    }
359
+
360
+    /**
361
+     * Get all children of this share
362
+     *
363
+     * @param IShare $parent
364
+     * @return IShare[]
365
+     */
366
+    public function getChildren(IShare $parent) {
367
+        $children = [];
368
+
369
+        $qb = $this->dbConnection->getQueryBuilder();
370
+        $qb->select('*')
371
+            ->from('share')
372
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
373
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
374
+            ->orderBy('id');
375
+
376
+        $cursor = $qb->execute();
377
+        while($data = $cursor->fetch()) {
378
+            $children[] = $this->createShareObject($data);
379
+        }
380
+        $cursor->closeCursor();
381
+
382
+        return $children;
383
+    }
384
+
385
+    /**
386
+     * add share to the database and return the ID
387
+     *
388
+     * @param int $itemSource
389
+     * @param string $itemType
390
+     * @param string $shareWith
391
+     * @param string $sharedBy
392
+     * @param string $uidOwner
393
+     * @param int $permissions
394
+     * @param string $token
395
+     * @return int
396
+     */
397
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
398
+        $qb = $this->dbConnection->getQueryBuilder();
399
+        $qb->insert('share')
400
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
401
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
402
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
403
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
404
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
405
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
406
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
407
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
408
+            ->setValue('token', $qb->createNamedParameter($token))
409
+            ->setValue('stime', $qb->createNamedParameter(time()));
410
+
411
+        /*
412 412
 		 * Added to fix https://github.com/owncloud/core/issues/22215
413 413
 		 * Can be removed once we get rid of ajax/share.php
414 414
 		 */
415
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
416
-
417
-		$qb->execute();
418
-		$id = $qb->getLastInsertId();
419
-
420
-		return (int)$id;
421
-	}
422
-
423
-	/**
424
-	 * Update a share
425
-	 *
426
-	 * @param IShare $share
427
-	 * @return IShare The share object
428
-	 */
429
-	public function update(IShare $share) {
430
-
431
-		$originalShare = $this->getShareById($share->getId());
432
-		$passwordHash = null;
433
-		if ($share->getPassword() !== null) {
434
-			$passwordHash = $this->hasher->hash($share->getPassword());
435
-		}
436
-
437
-		if($passwordHash !== null && $originalShare->getPassword() !== $passwordHash) {
438
-			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $share->getPassword());
439
-		}
440
-		/*
415
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
416
+
417
+        $qb->execute();
418
+        $id = $qb->getLastInsertId();
419
+
420
+        return (int)$id;
421
+    }
422
+
423
+    /**
424
+     * Update a share
425
+     *
426
+     * @param IShare $share
427
+     * @return IShare The share object
428
+     */
429
+    public function update(IShare $share) {
430
+
431
+        $originalShare = $this->getShareById($share->getId());
432
+        $passwordHash = null;
433
+        if ($share->getPassword() !== null) {
434
+            $passwordHash = $this->hasher->hash($share->getPassword());
435
+        }
436
+
437
+        if($passwordHash !== null && $originalShare->getPassword() !== $passwordHash) {
438
+            $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $share->getPassword());
439
+        }
440
+        /*
441 441
 		 * We allow updating the permissions and password of mail shares
442 442
 		 */
443
-		$qb = $this->dbConnection->getQueryBuilder();
444
-		$qb->update('share')
445
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
446
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
447
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
448
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
449
-			->set('password', $qb->createNamedParameter($passwordHash))
450
-			->execute();
451
-
452
-		return $share;
453
-	}
454
-
455
-	/**
456
-	 * @inheritdoc
457
-	 */
458
-	public function move(IShare $share, $recipient) {
459
-		/**
460
-		 * nothing to do here, mail shares are only outgoing shares
461
-		 */
462
-		return $share;
463
-	}
464
-
465
-	/**
466
-	 * Delete a share (owner unShares the file)
467
-	 *
468
-	 * @param IShare $share
469
-	 */
470
-	public function delete(IShare $share) {
471
-		$this->removeShareFromTable($share->getId());
472
-	}
473
-
474
-	/**
475
-	 * @inheritdoc
476
-	 */
477
-	public function deleteFromSelf(IShare $share, $recipient) {
478
-		// nothing to do here, mail shares are only outgoing shares
479
-		return;
480
-	}
481
-
482
-	/**
483
-	 * @inheritdoc
484
-	 */
485
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
486
-		$qb = $this->dbConnection->getQueryBuilder();
487
-		$qb->select('*')
488
-			->from('share');
489
-
490
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
491
-
492
-		/**
493
-		 * Reshares for this user are shares where they are the owner.
494
-		 */
495
-		if ($reshares === false) {
496
-			//Special case for old shares created via the web UI
497
-			$or1 = $qb->expr()->andX(
498
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
-				$qb->expr()->isNull('uid_initiator')
500
-			);
501
-
502
-			$qb->andWhere(
503
-				$qb->expr()->orX(
504
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
505
-					$or1
506
-				)
507
-			);
508
-		} else {
509
-			$qb->andWhere(
510
-				$qb->expr()->orX(
511
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
512
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
513
-				)
514
-			);
515
-		}
516
-
517
-		if ($node !== null) {
518
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
519
-		}
520
-
521
-		if ($limit !== -1) {
522
-			$qb->setMaxResults($limit);
523
-		}
524
-
525
-		$qb->setFirstResult($offset);
526
-		$qb->orderBy('id');
527
-
528
-		$cursor = $qb->execute();
529
-		$shares = [];
530
-		while($data = $cursor->fetch()) {
531
-			$shares[] = $this->createShareObject($data);
532
-		}
533
-		$cursor->closeCursor();
534
-
535
-		return $shares;
536
-	}
537
-
538
-	/**
539
-	 * @inheritdoc
540
-	 */
541
-	public function getShareById($id, $recipientId = null) {
542
-		$qb = $this->dbConnection->getQueryBuilder();
543
-
544
-		$qb->select('*')
545
-			->from('share')
546
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
547
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
548
-
549
-		$cursor = $qb->execute();
550
-		$data = $cursor->fetch();
551
-		$cursor->closeCursor();
552
-
553
-		if ($data === false) {
554
-			throw new ShareNotFound();
555
-		}
556
-
557
-		try {
558
-			$share = $this->createShareObject($data);
559
-		} catch (InvalidShare $e) {
560
-			throw new ShareNotFound();
561
-		}
562
-
563
-		return $share;
564
-	}
565
-
566
-	/**
567
-	 * Get shares for a given path
568
-	 *
569
-	 * @param \OCP\Files\Node $path
570
-	 * @return IShare[]
571
-	 */
572
-	public function getSharesByPath(Node $path) {
573
-		$qb = $this->dbConnection->getQueryBuilder();
574
-
575
-		$cursor = $qb->select('*')
576
-			->from('share')
577
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
578
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
579
-			->execute();
580
-
581
-		$shares = [];
582
-		while($data = $cursor->fetch()) {
583
-			$shares[] = $this->createShareObject($data);
584
-		}
585
-		$cursor->closeCursor();
586
-
587
-		return $shares;
588
-	}
589
-
590
-	/**
591
-	 * @inheritdoc
592
-	 */
593
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
594
-		/** @var IShare[] $shares */
595
-		$shares = [];
596
-
597
-		//Get shares directly with this user
598
-		$qb = $this->dbConnection->getQueryBuilder();
599
-		$qb->select('*')
600
-			->from('share');
601
-
602
-		// Order by id
603
-		$qb->orderBy('id');
604
-
605
-		// Set limit and offset
606
-		if ($limit !== -1) {
607
-			$qb->setMaxResults($limit);
608
-		}
609
-		$qb->setFirstResult($offset);
610
-
611
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
612
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
613
-
614
-		// Filter by node if provided
615
-		if ($node !== null) {
616
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
617
-		}
618
-
619
-		$cursor = $qb->execute();
620
-
621
-		while($data = $cursor->fetch()) {
622
-			$shares[] = $this->createShareObject($data);
623
-		}
624
-		$cursor->closeCursor();
625
-
626
-
627
-		return $shares;
628
-	}
629
-
630
-	/**
631
-	 * Get a share by token
632
-	 *
633
-	 * @param string $token
634
-	 * @return IShare
635
-	 * @throws ShareNotFound
636
-	 */
637
-	public function getShareByToken($token) {
638
-		$qb = $this->dbConnection->getQueryBuilder();
639
-
640
-		$cursor = $qb->select('*')
641
-			->from('share')
642
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
643
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
644
-			->execute();
645
-
646
-		$data = $cursor->fetch();
647
-
648
-		if ($data === false) {
649
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
650
-		}
651
-
652
-		try {
653
-			$share = $this->createShareObject($data);
654
-		} catch (InvalidShare $e) {
655
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
656
-		}
657
-
658
-		return $share;
659
-	}
660
-
661
-	/**
662
-	 * remove share from table
663
-	 *
664
-	 * @param string $shareId
665
-	 */
666
-	protected function removeShareFromTable($shareId) {
667
-		$qb = $this->dbConnection->getQueryBuilder();
668
-		$qb->delete('share')
669
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
670
-		$qb->execute();
671
-	}
672
-
673
-	/**
674
-	 * Create a share object from an database row
675
-	 *
676
-	 * @param array $data
677
-	 * @return IShare
678
-	 * @throws InvalidShare
679
-	 * @throws ShareNotFound
680
-	 */
681
-	protected function createShareObject($data) {
682
-
683
-		$share = new Share($this->rootFolder, $this->userManager);
684
-		$share->setId((int)$data['id'])
685
-			->setShareType((int)$data['share_type'])
686
-			->setPermissions((int)$data['permissions'])
687
-			->setTarget($data['file_target'])
688
-			->setMailSend((bool)$data['mail_send'])
689
-			->setToken($data['token']);
690
-
691
-		$shareTime = new \DateTime();
692
-		$shareTime->setTimestamp((int)$data['stime']);
693
-		$share->setShareTime($shareTime);
694
-		$share->setSharedWith($data['share_with']);
695
-		$share->setPassword($data['password']);
696
-
697
-		if ($data['uid_initiator'] !== null) {
698
-			$share->setShareOwner($data['uid_owner']);
699
-			$share->setSharedBy($data['uid_initiator']);
700
-		} else {
701
-			//OLD SHARE
702
-			$share->setSharedBy($data['uid_owner']);
703
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
704
-
705
-			$owner = $path->getOwner();
706
-			$share->setShareOwner($owner->getUID());
707
-		}
708
-
709
-		$share->setNodeId((int)$data['file_source']);
710
-		$share->setNodeType($data['item_type']);
711
-
712
-		$share->setProviderId($this->identifier());
713
-
714
-		return $share;
715
-	}
716
-
717
-	/**
718
-	 * Get the node with file $id for $user
719
-	 *
720
-	 * @param string $userId
721
-	 * @param int $id
722
-	 * @return \OCP\Files\File|\OCP\Files\Folder
723
-	 * @throws InvalidShare
724
-	 */
725
-	private function getNode($userId, $id) {
726
-		try {
727
-			$userFolder = $this->rootFolder->getUserFolder($userId);
728
-		} catch (NotFoundException $e) {
729
-			throw new InvalidShare();
730
-		}
731
-
732
-		$nodes = $userFolder->getById($id);
733
-
734
-		if (empty($nodes)) {
735
-			throw new InvalidShare();
736
-		}
737
-
738
-		return $nodes[0];
739
-	}
740
-
741
-	/**
742
-	 * A user is deleted from the system
743
-	 * So clean up the relevant shares.
744
-	 *
745
-	 * @param string $uid
746
-	 * @param int $shareType
747
-	 */
748
-	public function userDeleted($uid, $shareType) {
749
-		$qb = $this->dbConnection->getQueryBuilder();
750
-
751
-		$qb->delete('share')
752
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
753
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
754
-			->execute();
755
-	}
756
-
757
-	/**
758
-	 * This provider does not support group shares
759
-	 *
760
-	 * @param string $gid
761
-	 */
762
-	public function groupDeleted($gid) {
763
-		return;
764
-	}
765
-
766
-	/**
767
-	 * This provider does not support group shares
768
-	 *
769
-	 * @param string $uid
770
-	 * @param string $gid
771
-	 */
772
-	public function userDeletedFromGroup($uid, $gid) {
773
-		return;
774
-	}
775
-
776
-	/**
777
-	 * get database row of a give share
778
-	 *
779
-	 * @param $id
780
-	 * @return array
781
-	 * @throws ShareNotFound
782
-	 */
783
-	protected function getRawShare($id) {
784
-
785
-		// Now fetch the inserted share and create a complete share object
786
-		$qb = $this->dbConnection->getQueryBuilder();
787
-		$qb->select('*')
788
-			->from('share')
789
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
790
-
791
-		$cursor = $qb->execute();
792
-		$data = $cursor->fetch();
793
-		$cursor->closeCursor();
794
-
795
-		if ($data === false) {
796
-			throw new ShareNotFound;
797
-		}
798
-
799
-		return $data;
800
-	}
801
-
802
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
803
-		$qb = $this->dbConnection->getQueryBuilder();
804
-		$qb->select('*')
805
-			->from('share', 's')
806
-			->andWhere($qb->expr()->orX(
807
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
808
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
809
-			))
810
-			->andWhere(
811
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
812
-			);
813
-
814
-		/**
815
-		 * Reshares for this user are shares where they are the owner.
816
-		 */
817
-		if ($reshares === false) {
818
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
819
-		} else {
820
-			$qb->andWhere(
821
-				$qb->expr()->orX(
822
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
823
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
824
-				)
825
-			);
826
-		}
827
-
828
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
829
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
830
-
831
-		$qb->orderBy('id');
832
-
833
-		$cursor = $qb->execute();
834
-		$shares = [];
835
-		while ($data = $cursor->fetch()) {
836
-			$shares[$data['fileid']][] = $this->createShareObject($data);
837
-		}
838
-		$cursor->closeCursor();
839
-
840
-		return $shares;
841
-	}
443
+        $qb = $this->dbConnection->getQueryBuilder();
444
+        $qb->update('share')
445
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
446
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
447
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
448
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
449
+            ->set('password', $qb->createNamedParameter($passwordHash))
450
+            ->execute();
451
+
452
+        return $share;
453
+    }
454
+
455
+    /**
456
+     * @inheritdoc
457
+     */
458
+    public function move(IShare $share, $recipient) {
459
+        /**
460
+         * nothing to do here, mail shares are only outgoing shares
461
+         */
462
+        return $share;
463
+    }
464
+
465
+    /**
466
+     * Delete a share (owner unShares the file)
467
+     *
468
+     * @param IShare $share
469
+     */
470
+    public function delete(IShare $share) {
471
+        $this->removeShareFromTable($share->getId());
472
+    }
473
+
474
+    /**
475
+     * @inheritdoc
476
+     */
477
+    public function deleteFromSelf(IShare $share, $recipient) {
478
+        // nothing to do here, mail shares are only outgoing shares
479
+        return;
480
+    }
481
+
482
+    /**
483
+     * @inheritdoc
484
+     */
485
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
486
+        $qb = $this->dbConnection->getQueryBuilder();
487
+        $qb->select('*')
488
+            ->from('share');
489
+
490
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
491
+
492
+        /**
493
+         * Reshares for this user are shares where they are the owner.
494
+         */
495
+        if ($reshares === false) {
496
+            //Special case for old shares created via the web UI
497
+            $or1 = $qb->expr()->andX(
498
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
+                $qb->expr()->isNull('uid_initiator')
500
+            );
501
+
502
+            $qb->andWhere(
503
+                $qb->expr()->orX(
504
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
505
+                    $or1
506
+                )
507
+            );
508
+        } else {
509
+            $qb->andWhere(
510
+                $qb->expr()->orX(
511
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
512
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
513
+                )
514
+            );
515
+        }
516
+
517
+        if ($node !== null) {
518
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
519
+        }
520
+
521
+        if ($limit !== -1) {
522
+            $qb->setMaxResults($limit);
523
+        }
524
+
525
+        $qb->setFirstResult($offset);
526
+        $qb->orderBy('id');
527
+
528
+        $cursor = $qb->execute();
529
+        $shares = [];
530
+        while($data = $cursor->fetch()) {
531
+            $shares[] = $this->createShareObject($data);
532
+        }
533
+        $cursor->closeCursor();
534
+
535
+        return $shares;
536
+    }
537
+
538
+    /**
539
+     * @inheritdoc
540
+     */
541
+    public function getShareById($id, $recipientId = null) {
542
+        $qb = $this->dbConnection->getQueryBuilder();
543
+
544
+        $qb->select('*')
545
+            ->from('share')
546
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
547
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
548
+
549
+        $cursor = $qb->execute();
550
+        $data = $cursor->fetch();
551
+        $cursor->closeCursor();
552
+
553
+        if ($data === false) {
554
+            throw new ShareNotFound();
555
+        }
556
+
557
+        try {
558
+            $share = $this->createShareObject($data);
559
+        } catch (InvalidShare $e) {
560
+            throw new ShareNotFound();
561
+        }
562
+
563
+        return $share;
564
+    }
565
+
566
+    /**
567
+     * Get shares for a given path
568
+     *
569
+     * @param \OCP\Files\Node $path
570
+     * @return IShare[]
571
+     */
572
+    public function getSharesByPath(Node $path) {
573
+        $qb = $this->dbConnection->getQueryBuilder();
574
+
575
+        $cursor = $qb->select('*')
576
+            ->from('share')
577
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
578
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
579
+            ->execute();
580
+
581
+        $shares = [];
582
+        while($data = $cursor->fetch()) {
583
+            $shares[] = $this->createShareObject($data);
584
+        }
585
+        $cursor->closeCursor();
586
+
587
+        return $shares;
588
+    }
589
+
590
+    /**
591
+     * @inheritdoc
592
+     */
593
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
594
+        /** @var IShare[] $shares */
595
+        $shares = [];
596
+
597
+        //Get shares directly with this user
598
+        $qb = $this->dbConnection->getQueryBuilder();
599
+        $qb->select('*')
600
+            ->from('share');
601
+
602
+        // Order by id
603
+        $qb->orderBy('id');
604
+
605
+        // Set limit and offset
606
+        if ($limit !== -1) {
607
+            $qb->setMaxResults($limit);
608
+        }
609
+        $qb->setFirstResult($offset);
610
+
611
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
612
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
613
+
614
+        // Filter by node if provided
615
+        if ($node !== null) {
616
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
617
+        }
618
+
619
+        $cursor = $qb->execute();
620
+
621
+        while($data = $cursor->fetch()) {
622
+            $shares[] = $this->createShareObject($data);
623
+        }
624
+        $cursor->closeCursor();
625
+
626
+
627
+        return $shares;
628
+    }
629
+
630
+    /**
631
+     * Get a share by token
632
+     *
633
+     * @param string $token
634
+     * @return IShare
635
+     * @throws ShareNotFound
636
+     */
637
+    public function getShareByToken($token) {
638
+        $qb = $this->dbConnection->getQueryBuilder();
639
+
640
+        $cursor = $qb->select('*')
641
+            ->from('share')
642
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
643
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
644
+            ->execute();
645
+
646
+        $data = $cursor->fetch();
647
+
648
+        if ($data === false) {
649
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
650
+        }
651
+
652
+        try {
653
+            $share = $this->createShareObject($data);
654
+        } catch (InvalidShare $e) {
655
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
656
+        }
657
+
658
+        return $share;
659
+    }
660
+
661
+    /**
662
+     * remove share from table
663
+     *
664
+     * @param string $shareId
665
+     */
666
+    protected function removeShareFromTable($shareId) {
667
+        $qb = $this->dbConnection->getQueryBuilder();
668
+        $qb->delete('share')
669
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
670
+        $qb->execute();
671
+    }
672
+
673
+    /**
674
+     * Create a share object from an database row
675
+     *
676
+     * @param array $data
677
+     * @return IShare
678
+     * @throws InvalidShare
679
+     * @throws ShareNotFound
680
+     */
681
+    protected function createShareObject($data) {
682
+
683
+        $share = new Share($this->rootFolder, $this->userManager);
684
+        $share->setId((int)$data['id'])
685
+            ->setShareType((int)$data['share_type'])
686
+            ->setPermissions((int)$data['permissions'])
687
+            ->setTarget($data['file_target'])
688
+            ->setMailSend((bool)$data['mail_send'])
689
+            ->setToken($data['token']);
690
+
691
+        $shareTime = new \DateTime();
692
+        $shareTime->setTimestamp((int)$data['stime']);
693
+        $share->setShareTime($shareTime);
694
+        $share->setSharedWith($data['share_with']);
695
+        $share->setPassword($data['password']);
696
+
697
+        if ($data['uid_initiator'] !== null) {
698
+            $share->setShareOwner($data['uid_owner']);
699
+            $share->setSharedBy($data['uid_initiator']);
700
+        } else {
701
+            //OLD SHARE
702
+            $share->setSharedBy($data['uid_owner']);
703
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
704
+
705
+            $owner = $path->getOwner();
706
+            $share->setShareOwner($owner->getUID());
707
+        }
708
+
709
+        $share->setNodeId((int)$data['file_source']);
710
+        $share->setNodeType($data['item_type']);
711
+
712
+        $share->setProviderId($this->identifier());
713
+
714
+        return $share;
715
+    }
716
+
717
+    /**
718
+     * Get the node with file $id for $user
719
+     *
720
+     * @param string $userId
721
+     * @param int $id
722
+     * @return \OCP\Files\File|\OCP\Files\Folder
723
+     * @throws InvalidShare
724
+     */
725
+    private function getNode($userId, $id) {
726
+        try {
727
+            $userFolder = $this->rootFolder->getUserFolder($userId);
728
+        } catch (NotFoundException $e) {
729
+            throw new InvalidShare();
730
+        }
731
+
732
+        $nodes = $userFolder->getById($id);
733
+
734
+        if (empty($nodes)) {
735
+            throw new InvalidShare();
736
+        }
737
+
738
+        return $nodes[0];
739
+    }
740
+
741
+    /**
742
+     * A user is deleted from the system
743
+     * So clean up the relevant shares.
744
+     *
745
+     * @param string $uid
746
+     * @param int $shareType
747
+     */
748
+    public function userDeleted($uid, $shareType) {
749
+        $qb = $this->dbConnection->getQueryBuilder();
750
+
751
+        $qb->delete('share')
752
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
753
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
754
+            ->execute();
755
+    }
756
+
757
+    /**
758
+     * This provider does not support group shares
759
+     *
760
+     * @param string $gid
761
+     */
762
+    public function groupDeleted($gid) {
763
+        return;
764
+    }
765
+
766
+    /**
767
+     * This provider does not support group shares
768
+     *
769
+     * @param string $uid
770
+     * @param string $gid
771
+     */
772
+    public function userDeletedFromGroup($uid, $gid) {
773
+        return;
774
+    }
775
+
776
+    /**
777
+     * get database row of a give share
778
+     *
779
+     * @param $id
780
+     * @return array
781
+     * @throws ShareNotFound
782
+     */
783
+    protected function getRawShare($id) {
784
+
785
+        // Now fetch the inserted share and create a complete share object
786
+        $qb = $this->dbConnection->getQueryBuilder();
787
+        $qb->select('*')
788
+            ->from('share')
789
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
790
+
791
+        $cursor = $qb->execute();
792
+        $data = $cursor->fetch();
793
+        $cursor->closeCursor();
794
+
795
+        if ($data === false) {
796
+            throw new ShareNotFound;
797
+        }
798
+
799
+        return $data;
800
+    }
801
+
802
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
803
+        $qb = $this->dbConnection->getQueryBuilder();
804
+        $qb->select('*')
805
+            ->from('share', 's')
806
+            ->andWhere($qb->expr()->orX(
807
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
808
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
809
+            ))
810
+            ->andWhere(
811
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
812
+            );
813
+
814
+        /**
815
+         * Reshares for this user are shares where they are the owner.
816
+         */
817
+        if ($reshares === false) {
818
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
819
+        } else {
820
+            $qb->andWhere(
821
+                $qb->expr()->orX(
822
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
823
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
824
+                )
825
+            );
826
+        }
827
+
828
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
829
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
830
+
831
+        $qb->orderBy('id');
832
+
833
+        $cursor = $qb->execute();
834
+        $shares = [];
835
+        while ($data = $cursor->fetch()) {
836
+            $shares[$data['fileid']][] = $this->createShareObject($data);
837
+        }
838
+        $cursor->closeCursor();
839
+
840
+        return $shares;
841
+    }
842 842
 
843 843
 }
Please login to merge, or discard this patch.
apps/files_sharing/appinfo/update.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -26,16 +26,16 @@
 block discarded – undo
26 26
 
27 27
 // Migration OC8.2 -> OC9
28 28
 if (version_compare($installedVersion, '0.9.1', '<')) {
29
-	$m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
30
-	$m->removeReShares();
31
-	$m->updateInitiatorInfo();
29
+    $m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
30
+    $m->removeReShares();
31
+    $m->updateInitiatorInfo();
32 32
 }
33 33
 
34 34
 if (version_compare($installedVersion, '1.1.1', '<')) {
35
-	$m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
35
+    $m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
36 36
 }
37 37
 
38 38
 if (version_compare($installedVersion, '1.4.0', '<')) {
39
-	$m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
40
-	$m->addPasswordColumn();
39
+    $m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
40
+    $m->addPasswordColumn();
41 41
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareAPIController.php 2 patches
Indentation   +867 added lines, -867 removed lines patch added patch discarded remove patch
@@ -51,880 +51,880 @@
 block discarded – undo
51 51
  */
52 52
 class ShareAPIController extends OCSController {
53 53
 
54
-	/** @var IManager */
55
-	private $shareManager;
56
-	/** @var IGroupManager */
57
-	private $groupManager;
58
-	/** @var IUserManager */
59
-	private $userManager;
60
-	/** @var IRequest */
61
-	protected $request;
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-	/** @var string */
67
-	private $currentUser;
68
-	/** @var IL10N */
69
-	private $l;
70
-	/** @var \OCP\Files\Node */
71
-	private $lockedNode;
72
-
73
-	/**
74
-	 * Share20OCS constructor.
75
-	 *
76
-	 * @param string $appName
77
-	 * @param IRequest $request
78
-	 * @param IManager $shareManager
79
-	 * @param IGroupManager $groupManager
80
-	 * @param IUserManager $userManager
81
-	 * @param IRootFolder $rootFolder
82
-	 * @param IURLGenerator $urlGenerator
83
-	 * @param string $userId
84
-	 * @param IL10N $l10n
85
-	 */
86
-	public function __construct(
87
-		$appName,
88
-		IRequest $request,
89
-		IManager $shareManager,
90
-		IGroupManager $groupManager,
91
-		IUserManager $userManager,
92
-		IRootFolder $rootFolder,
93
-		IURLGenerator $urlGenerator,
94
-		$userId,
95
-		IL10N $l10n
96
-	) {
97
-		parent::__construct($appName, $request);
98
-
99
-		$this->shareManager = $shareManager;
100
-		$this->userManager = $userManager;
101
-		$this->groupManager = $groupManager;
102
-		$this->request = $request;
103
-		$this->rootFolder = $rootFolder;
104
-		$this->urlGenerator = $urlGenerator;
105
-		$this->currentUser = $userId;
106
-		$this->l = $l10n;
107
-	}
108
-
109
-	/**
110
-	 * Convert an IShare to an array for OCS output
111
-	 *
112
-	 * @param \OCP\Share\IShare $share
113
-	 * @param Node|null $recipientNode
114
-	 * @return array
115
-	 * @throws NotFoundException In case the node can't be resolved.
116
-	 */
117
-	protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
118
-		$sharedBy = $this->userManager->get($share->getSharedBy());
119
-		$shareOwner = $this->userManager->get($share->getShareOwner());
120
-
121
-		$result = [
122
-			'id' => $share->getId(),
123
-			'share_type' => $share->getShareType(),
124
-			'uid_owner' => $share->getSharedBy(),
125
-			'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
126
-			'permissions' => $share->getPermissions(),
127
-			'stime' => $share->getShareTime()->getTimestamp(),
128
-			'parent' => null,
129
-			'expiration' => null,
130
-			'token' => null,
131
-			'uid_file_owner' => $share->getShareOwner(),
132
-			'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
133
-		];
134
-
135
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
136
-		if ($recipientNode) {
137
-			$node = $recipientNode;
138
-		} else {
139
-			$nodes = $userFolder->getById($share->getNodeId());
140
-
141
-			if (empty($nodes)) {
142
-				// fallback to guessing the path
143
-				$node = $userFolder->get($share->getTarget());
144
-				if ($node === null) {
145
-					throw new NotFoundException();
146
-				}
147
-			} else {
148
-				$node = $nodes[0];
149
-			}
150
-		}
151
-
152
-		$result['path'] = $userFolder->getRelativePath($node->getPath());
153
-		if ($node instanceOf \OCP\Files\Folder) {
154
-			$result['item_type'] = 'folder';
155
-		} else {
156
-			$result['item_type'] = 'file';
157
-		}
158
-		$result['mimetype'] = $node->getMimetype();
159
-		$result['storage_id'] = $node->getStorage()->getId();
160
-		$result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
161
-		$result['item_source'] = $node->getId();
162
-		$result['file_source'] = $node->getId();
163
-		$result['file_parent'] = $node->getParent()->getId();
164
-		$result['file_target'] = $share->getTarget();
165
-
166
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
167
-			$sharedWith = $this->userManager->get($share->getSharedWith());
168
-			$result['share_with'] = $share->getSharedWith();
169
-			$result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
170
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
171
-			$group = $this->groupManager->get($share->getSharedWith());
172
-			$result['share_with'] = $share->getSharedWith();
173
-			$result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
174
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
175
-
176
-			$result['share_with'] = $share->getPassword();
177
-			$result['share_with_displayname'] = $share->getPassword();
178
-
179
-			$result['token'] = $share->getToken();
180
-			$result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
181
-
182
-			$expiration = $share->getExpirationDate();
183
-			if ($expiration !== null) {
184
-				$result['expiration'] = $expiration->format('Y-m-d 00:00:00');
185
-			}
186
-
187
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
-			$result['share_with'] = $share->getSharedWith();
189
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
190
-			$result['token'] = $share->getToken();
191
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
-			$result['share_with'] = $share->getSharedWith();
193
-			$result['password'] = $share->getPassword();
194
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
195
-			$result['token'] = $share->getToken();
196
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
-			$result['share_with_displayname'] = $share->getSharedWith();
198
-			$result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
199
-		}
200
-
201
-
202
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
203
-
204
-		return $result;
205
-	}
206
-
207
-	/**
208
-	 * Check if one of the users address books knows the exact property, if
209
-	 * yes we return the full name.
210
-	 *
211
-	 * @param string $query
212
-	 * @param string $property
213
-	 * @return string
214
-	 */
215
-	private function getDisplayNameFromAddressBook($query, $property) {
216
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
217
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
218
-		foreach ($result as $r) {
219
-			foreach($r[$property] as $value) {
220
-				if ($value === $query) {
221
-					return $r['FN'];
222
-				}
223
-			}
224
-		}
225
-
226
-		return $query;
227
-	}
228
-
229
-	/**
230
-	 * Get a specific share by id
231
-	 *
232
-	 * @NoAdminRequired
233
-	 *
234
-	 * @param string $id
235
-	 * @return DataResponse
236
-	 * @throws OCSNotFoundException
237
-	 */
238
-	public function getShare($id) {
239
-		try {
240
-			$share = $this->getShareById($id);
241
-		} catch (ShareNotFound $e) {
242
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
243
-		}
244
-
245
-		if ($this->canAccessShare($share)) {
246
-			try {
247
-				$share = $this->formatShare($share);
248
-				return new DataResponse([$share]);
249
-			} catch (NotFoundException $e) {
250
-				//Fall trough
251
-			}
252
-		}
253
-
254
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
255
-	}
256
-
257
-	/**
258
-	 * Delete a share
259
-	 *
260
-	 * @NoAdminRequired
261
-	 *
262
-	 * @param string $id
263
-	 * @return DataResponse
264
-	 * @throws OCSNotFoundException
265
-	 */
266
-	public function deleteShare($id) {
267
-		try {
268
-			$share = $this->getShareById($id);
269
-		} catch (ShareNotFound $e) {
270
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
271
-		}
272
-
273
-		try {
274
-			$this->lock($share->getNode());
275
-		} catch (LockedException $e) {
276
-			throw new OCSNotFoundException($this->l->t('could not delete share'));
277
-		}
278
-
279
-		if (!$this->canAccessShare($share)) {
280
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
281
-		}
282
-
283
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
284
-			$share->getShareOwner() !== $this->currentUser &&
285
-			$share->getSharedBy() !== $this->currentUser) {
286
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
287
-		} else {
288
-			$this->shareManager->deleteShare($share);
289
-		}
290
-
291
-		return new DataResponse();
292
-	}
293
-
294
-	/**
295
-	 * @NoAdminRequired
296
-	 *
297
-	 * @param string $path
298
-	 * @param int $permissions
299
-	 * @param int $shareType
300
-	 * @param string $shareWith
301
-	 * @param string $publicUpload
302
-	 * @param string $password
303
-	 * @param string $expireDate
304
-	 *
305
-	 * @return DataResponse
306
-	 * @throws OCSNotFoundException
307
-	 * @throws OCSForbiddenException
308
-	 * @throws OCSBadRequestException
309
-	 * @throws OCSException
310
-	 */
311
-	public function createShare(
312
-		$path = null,
313
-		$permissions = \OCP\Constants::PERMISSION_ALL,
314
-		$shareType = -1,
315
-		$shareWith = null,
316
-		$publicUpload = 'false',
317
-		$password = '',
318
-		$expireDate = ''
319
-	) {
320
-		$share = $this->shareManager->newShare();
321
-
322
-		// Verify path
323
-		if ($path === null) {
324
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
325
-		}
326
-
327
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
328
-		try {
329
-			$path = $userFolder->get($path);
330
-		} catch (NotFoundException $e) {
331
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
332
-		}
333
-
334
-		$share->setNode($path);
335
-
336
-		try {
337
-			$this->lock($share->getNode());
338
-		} catch (LockedException $e) {
339
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
340
-		}
341
-
342
-		if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
343
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
344
-		}
345
-
346
-		// Shares always require read permissions
347
-		$permissions |= \OCP\Constants::PERMISSION_READ;
348
-
349
-		if ($path instanceof \OCP\Files\File) {
350
-			// Single file shares should never have delete or create permissions
351
-			$permissions &= ~\OCP\Constants::PERMISSION_DELETE;
352
-			$permissions &= ~\OCP\Constants::PERMISSION_CREATE;
353
-		}
354
-
355
-		/*
54
+    /** @var IManager */
55
+    private $shareManager;
56
+    /** @var IGroupManager */
57
+    private $groupManager;
58
+    /** @var IUserManager */
59
+    private $userManager;
60
+    /** @var IRequest */
61
+    protected $request;
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+    /** @var string */
67
+    private $currentUser;
68
+    /** @var IL10N */
69
+    private $l;
70
+    /** @var \OCP\Files\Node */
71
+    private $lockedNode;
72
+
73
+    /**
74
+     * Share20OCS constructor.
75
+     *
76
+     * @param string $appName
77
+     * @param IRequest $request
78
+     * @param IManager $shareManager
79
+     * @param IGroupManager $groupManager
80
+     * @param IUserManager $userManager
81
+     * @param IRootFolder $rootFolder
82
+     * @param IURLGenerator $urlGenerator
83
+     * @param string $userId
84
+     * @param IL10N $l10n
85
+     */
86
+    public function __construct(
87
+        $appName,
88
+        IRequest $request,
89
+        IManager $shareManager,
90
+        IGroupManager $groupManager,
91
+        IUserManager $userManager,
92
+        IRootFolder $rootFolder,
93
+        IURLGenerator $urlGenerator,
94
+        $userId,
95
+        IL10N $l10n
96
+    ) {
97
+        parent::__construct($appName, $request);
98
+
99
+        $this->shareManager = $shareManager;
100
+        $this->userManager = $userManager;
101
+        $this->groupManager = $groupManager;
102
+        $this->request = $request;
103
+        $this->rootFolder = $rootFolder;
104
+        $this->urlGenerator = $urlGenerator;
105
+        $this->currentUser = $userId;
106
+        $this->l = $l10n;
107
+    }
108
+
109
+    /**
110
+     * Convert an IShare to an array for OCS output
111
+     *
112
+     * @param \OCP\Share\IShare $share
113
+     * @param Node|null $recipientNode
114
+     * @return array
115
+     * @throws NotFoundException In case the node can't be resolved.
116
+     */
117
+    protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
118
+        $sharedBy = $this->userManager->get($share->getSharedBy());
119
+        $shareOwner = $this->userManager->get($share->getShareOwner());
120
+
121
+        $result = [
122
+            'id' => $share->getId(),
123
+            'share_type' => $share->getShareType(),
124
+            'uid_owner' => $share->getSharedBy(),
125
+            'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
126
+            'permissions' => $share->getPermissions(),
127
+            'stime' => $share->getShareTime()->getTimestamp(),
128
+            'parent' => null,
129
+            'expiration' => null,
130
+            'token' => null,
131
+            'uid_file_owner' => $share->getShareOwner(),
132
+            'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
133
+        ];
134
+
135
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
136
+        if ($recipientNode) {
137
+            $node = $recipientNode;
138
+        } else {
139
+            $nodes = $userFolder->getById($share->getNodeId());
140
+
141
+            if (empty($nodes)) {
142
+                // fallback to guessing the path
143
+                $node = $userFolder->get($share->getTarget());
144
+                if ($node === null) {
145
+                    throw new NotFoundException();
146
+                }
147
+            } else {
148
+                $node = $nodes[0];
149
+            }
150
+        }
151
+
152
+        $result['path'] = $userFolder->getRelativePath($node->getPath());
153
+        if ($node instanceOf \OCP\Files\Folder) {
154
+            $result['item_type'] = 'folder';
155
+        } else {
156
+            $result['item_type'] = 'file';
157
+        }
158
+        $result['mimetype'] = $node->getMimetype();
159
+        $result['storage_id'] = $node->getStorage()->getId();
160
+        $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
161
+        $result['item_source'] = $node->getId();
162
+        $result['file_source'] = $node->getId();
163
+        $result['file_parent'] = $node->getParent()->getId();
164
+        $result['file_target'] = $share->getTarget();
165
+
166
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
167
+            $sharedWith = $this->userManager->get($share->getSharedWith());
168
+            $result['share_with'] = $share->getSharedWith();
169
+            $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
170
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
171
+            $group = $this->groupManager->get($share->getSharedWith());
172
+            $result['share_with'] = $share->getSharedWith();
173
+            $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
174
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
175
+
176
+            $result['share_with'] = $share->getPassword();
177
+            $result['share_with_displayname'] = $share->getPassword();
178
+
179
+            $result['token'] = $share->getToken();
180
+            $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
181
+
182
+            $expiration = $share->getExpirationDate();
183
+            if ($expiration !== null) {
184
+                $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
185
+            }
186
+
187
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
+            $result['share_with'] = $share->getSharedWith();
189
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
190
+            $result['token'] = $share->getToken();
191
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
+            $result['share_with'] = $share->getSharedWith();
193
+            $result['password'] = $share->getPassword();
194
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
195
+            $result['token'] = $share->getToken();
196
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
+            $result['share_with_displayname'] = $share->getSharedWith();
198
+            $result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
199
+        }
200
+
201
+
202
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
203
+
204
+        return $result;
205
+    }
206
+
207
+    /**
208
+     * Check if one of the users address books knows the exact property, if
209
+     * yes we return the full name.
210
+     *
211
+     * @param string $query
212
+     * @param string $property
213
+     * @return string
214
+     */
215
+    private function getDisplayNameFromAddressBook($query, $property) {
216
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
217
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
218
+        foreach ($result as $r) {
219
+            foreach($r[$property] as $value) {
220
+                if ($value === $query) {
221
+                    return $r['FN'];
222
+                }
223
+            }
224
+        }
225
+
226
+        return $query;
227
+    }
228
+
229
+    /**
230
+     * Get a specific share by id
231
+     *
232
+     * @NoAdminRequired
233
+     *
234
+     * @param string $id
235
+     * @return DataResponse
236
+     * @throws OCSNotFoundException
237
+     */
238
+    public function getShare($id) {
239
+        try {
240
+            $share = $this->getShareById($id);
241
+        } catch (ShareNotFound $e) {
242
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
243
+        }
244
+
245
+        if ($this->canAccessShare($share)) {
246
+            try {
247
+                $share = $this->formatShare($share);
248
+                return new DataResponse([$share]);
249
+            } catch (NotFoundException $e) {
250
+                //Fall trough
251
+            }
252
+        }
253
+
254
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
255
+    }
256
+
257
+    /**
258
+     * Delete a share
259
+     *
260
+     * @NoAdminRequired
261
+     *
262
+     * @param string $id
263
+     * @return DataResponse
264
+     * @throws OCSNotFoundException
265
+     */
266
+    public function deleteShare($id) {
267
+        try {
268
+            $share = $this->getShareById($id);
269
+        } catch (ShareNotFound $e) {
270
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
271
+        }
272
+
273
+        try {
274
+            $this->lock($share->getNode());
275
+        } catch (LockedException $e) {
276
+            throw new OCSNotFoundException($this->l->t('could not delete share'));
277
+        }
278
+
279
+        if (!$this->canAccessShare($share)) {
280
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
281
+        }
282
+
283
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
284
+            $share->getShareOwner() !== $this->currentUser &&
285
+            $share->getSharedBy() !== $this->currentUser) {
286
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
287
+        } else {
288
+            $this->shareManager->deleteShare($share);
289
+        }
290
+
291
+        return new DataResponse();
292
+    }
293
+
294
+    /**
295
+     * @NoAdminRequired
296
+     *
297
+     * @param string $path
298
+     * @param int $permissions
299
+     * @param int $shareType
300
+     * @param string $shareWith
301
+     * @param string $publicUpload
302
+     * @param string $password
303
+     * @param string $expireDate
304
+     *
305
+     * @return DataResponse
306
+     * @throws OCSNotFoundException
307
+     * @throws OCSForbiddenException
308
+     * @throws OCSBadRequestException
309
+     * @throws OCSException
310
+     */
311
+    public function createShare(
312
+        $path = null,
313
+        $permissions = \OCP\Constants::PERMISSION_ALL,
314
+        $shareType = -1,
315
+        $shareWith = null,
316
+        $publicUpload = 'false',
317
+        $password = '',
318
+        $expireDate = ''
319
+    ) {
320
+        $share = $this->shareManager->newShare();
321
+
322
+        // Verify path
323
+        if ($path === null) {
324
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
325
+        }
326
+
327
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
328
+        try {
329
+            $path = $userFolder->get($path);
330
+        } catch (NotFoundException $e) {
331
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
332
+        }
333
+
334
+        $share->setNode($path);
335
+
336
+        try {
337
+            $this->lock($share->getNode());
338
+        } catch (LockedException $e) {
339
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
340
+        }
341
+
342
+        if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
343
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
344
+        }
345
+
346
+        // Shares always require read permissions
347
+        $permissions |= \OCP\Constants::PERMISSION_READ;
348
+
349
+        if ($path instanceof \OCP\Files\File) {
350
+            // Single file shares should never have delete or create permissions
351
+            $permissions &= ~\OCP\Constants::PERMISSION_DELETE;
352
+            $permissions &= ~\OCP\Constants::PERMISSION_CREATE;
353
+        }
354
+
355
+        /*
356 356
 		 * Hack for https://github.com/owncloud/core/issues/22587
357 357
 		 * We check the permissions via webdav. But the permissions of the mount point
358 358
 		 * do not equal the share permissions. Here we fix that for federated mounts.
359 359
 		 */
360
-		if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
361
-			$permissions &= ~($permissions & ~$path->getPermissions());
362
-		}
363
-
364
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
365
-			// Valid user is required to share
366
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
367
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
368
-			}
369
-			$share->setSharedWith($shareWith);
370
-			$share->setPermissions($permissions);
371
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
372
-			if (!$this->shareManager->allowGroupSharing()) {
373
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
374
-			}
375
-
376
-			// Valid group is required to share
377
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
378
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
379
-			}
380
-			$share->setSharedWith($shareWith);
381
-			$share->setPermissions($permissions);
382
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
383
-			//Can we even share links?
384
-			if (!$this->shareManager->shareApiAllowLinks()) {
385
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
386
-			}
387
-
388
-			/*
360
+        if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
361
+            $permissions &= ~($permissions & ~$path->getPermissions());
362
+        }
363
+
364
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
365
+            // Valid user is required to share
366
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
367
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
368
+            }
369
+            $share->setSharedWith($shareWith);
370
+            $share->setPermissions($permissions);
371
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
372
+            if (!$this->shareManager->allowGroupSharing()) {
373
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
374
+            }
375
+
376
+            // Valid group is required to share
377
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
378
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
379
+            }
380
+            $share->setSharedWith($shareWith);
381
+            $share->setPermissions($permissions);
382
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
383
+            //Can we even share links?
384
+            if (!$this->shareManager->shareApiAllowLinks()) {
385
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
386
+            }
387
+
388
+            /*
389 389
 			 * For now we only allow 1 link share.
390 390
 			 * Return the existing link share if this is a duplicate
391 391
 			 */
392
-			$existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
393
-			if (!empty($existingShares)) {
394
-				return new DataResponse($this->formatShare($existingShares[0]));
395
-			}
396
-
397
-			if ($publicUpload === 'true') {
398
-				// Check if public upload is allowed
399
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
400
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
401
-				}
402
-
403
-				// Public upload can only be set for folders
404
-				if ($path instanceof \OCP\Files\File) {
405
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
406
-				}
407
-
408
-				$share->setPermissions(
409
-					\OCP\Constants::PERMISSION_READ |
410
-					\OCP\Constants::PERMISSION_CREATE |
411
-					\OCP\Constants::PERMISSION_UPDATE |
412
-					\OCP\Constants::PERMISSION_DELETE
413
-				);
414
-			} else {
415
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
416
-			}
417
-
418
-			// Set password
419
-			if ($password !== '') {
420
-				$share->setPassword($password);
421
-			}
422
-
423
-			//Expire date
424
-			if ($expireDate !== '') {
425
-				try {
426
-					$expireDate = $this->parseDate($expireDate);
427
-					$share->setExpirationDate($expireDate);
428
-				} catch (\Exception $e) {
429
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
430
-				}
431
-			}
432
-
433
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
434
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
435
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
436
-			}
437
-
438
-			$share->setSharedWith($shareWith);
439
-			$share->setPermissions($permissions);
440
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
441
-			if ($share->getNodeType() === 'file') {
442
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
443
-			} else {
444
-				$share->setPermissions(
445
-					\OCP\Constants::PERMISSION_READ |
446
-					\OCP\Constants::PERMISSION_CREATE |
447
-					\OCP\Constants::PERMISSION_UPDATE |
448
-					\OCP\Constants::PERMISSION_DELETE);
449
-			}
450
-			$share->setSharedWith($shareWith);
451
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
452
-			if (!\OCP\App::isEnabled('circles')) {
453
-				throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
454
-			}
455
-
456
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($shareWith);
457
-
458
-			// Valid circle is required to share
459
-			if ($circle === null) {
460
-				throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
461
-			}
462
-			$share->setSharedWith($shareWith);
463
-			$share->setPermissions($permissions);
464
-		} else {
465
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
466
-		}
467
-
468
-		$share->setShareType($shareType);
469
-		$share->setSharedBy($this->currentUser);
470
-
471
-		try {
472
-			$share = $this->shareManager->createShare($share);
473
-		} catch (GenericShareException $e) {
474
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
475
-			throw new OCSException($e->getHint(), $code);
476
-		} catch (\Exception $e) {
477
-			throw new OCSForbiddenException($e->getMessage());
478
-		}
479
-
480
-		$output = $this->formatShare($share);
481
-
482
-		return new DataResponse($output);
483
-	}
484
-
485
-	/**
486
-	 * @param \OCP\Files\File|\OCP\Files\Folder $node
487
-	 * @return DataResponse
488
-	 */
489
-	private function getSharedWithMe($node = null) {
490
-
491
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
492
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
493
-		$circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
494
-
495
-		$shares = array_merge($userShares, $groupShares, $circleShares);
496
-
497
-		$shares = array_filter($shares, function (IShare $share) {
498
-			return $share->getShareOwner() !== $this->currentUser;
499
-		});
500
-
501
-		$formatted = [];
502
-		foreach ($shares as $share) {
503
-			if ($this->canAccessShare($share)) {
504
-				try {
505
-					$formatted[] = $this->formatShare($share);
506
-				} catch (NotFoundException $e) {
507
-					// Ignore this share
508
-				}
509
-			}
510
-		}
511
-
512
-		return new DataResponse($formatted);
513
-	}
514
-
515
-	/**
516
-	 * @param \OCP\Files\Folder $folder
517
-	 * @return DataResponse
518
-	 * @throws OCSBadRequestException
519
-	 */
520
-	private function getSharesInDir($folder) {
521
-		if (!($folder instanceof \OCP\Files\Folder)) {
522
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
523
-		}
524
-
525
-		$nodes = $folder->getDirectoryListing();
526
-		/** @var \OCP\Share\IShare[] $shares */
527
-		$shares = [];
528
-		foreach ($nodes as $node) {
529
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
530
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
531
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
532
-			if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
533
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
534
-			}
535
-			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
536
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
537
-			}
538
-		}
539
-
540
-		$formatted = [];
541
-		foreach ($shares as $share) {
542
-			try {
543
-				$formatted[] = $this->formatShare($share);
544
-			} catch (NotFoundException $e) {
545
-				//Ignore this share
546
-			}
547
-		}
548
-
549
-		return new DataResponse($formatted);
550
-	}
551
-
552
-	/**
553
-	 * The getShares function.
554
-	 *
555
-	 * @NoAdminRequired
556
-	 *
557
-	 * @param string $shared_with_me
558
-	 * @param string $reshares
559
-	 * @param string $subfiles
560
-	 * @param string $path
561
-	 *
562
-	 * - Get shares by the current user
563
-	 * - Get shares by the current user and reshares (?reshares=true)
564
-	 * - Get shares with the current user (?shared_with_me=true)
565
-	 * - Get shares for a specific path (?path=...)
566
-	 * - Get all shares in a folder (?subfiles=true&path=..)
567
-	 *
568
-	 * @return DataResponse
569
-	 * @throws OCSNotFoundException
570
-	 */
571
-	public function getShares(
572
-		$shared_with_me = 'false',
573
-		$reshares = 'false',
574
-		$subfiles = 'false',
575
-		$path = null
576
-	) {
577
-
578
-		if ($path !== null) {
579
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
580
-			try {
581
-				$path = $userFolder->get($path);
582
-				$this->lock($path);
583
-			} catch (\OCP\Files\NotFoundException $e) {
584
-				throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
585
-			} catch (LockedException $e) {
586
-				throw new OCSNotFoundException($this->l->t('Could not lock path'));
587
-			}
588
-		}
589
-
590
-		if ($shared_with_me === 'true') {
591
-			$result = $this->getSharedWithMe($path);
592
-			return $result;
593
-		}
594
-
595
-		if ($subfiles === 'true') {
596
-			$result = $this->getSharesInDir($path);
597
-			return $result;
598
-		}
599
-
600
-		if ($reshares === 'true') {
601
-			$reshares = true;
602
-		} else {
603
-			$reshares = false;
604
-		}
605
-
606
-		// Get all shares
607
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
608
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
609
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
610
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
611
-			$mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
612
-		} else {
613
-			$mailShares = [];
614
-		}
615
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
616
-			$circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
617
-		} else {
618
-			$circleShares = [];
619
-		}
620
-
621
-		$shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
622
-
623
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
624
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
625
-			$shares = array_merge($shares, $federatedShares);
626
-		}
627
-
628
-		$formatted = [];
629
-		foreach ($shares as $share) {
630
-			try {
631
-				$formatted[] = $this->formatShare($share, $path);
632
-			} catch (NotFoundException $e) {
633
-				//Ignore share
634
-			}
635
-		}
636
-
637
-		return new DataResponse($formatted);
638
-	}
639
-
640
-	/**
641
-	 * @NoAdminRequired
642
-	 *
643
-	 * @param int $id
644
-	 * @param int $permissions
645
-	 * @param string $password
646
-	 * @param string $publicUpload
647
-	 * @param string $expireDate
648
-	 * @return DataResponse
649
-	 * @throws OCSNotFoundException
650
-	 * @throws OCSBadRequestException
651
-	 * @throws OCSForbiddenException
652
-	 */
653
-	public function updateShare(
654
-		$id,
655
-		$permissions = null,
656
-		$password = null,
657
-		$publicUpload = null,
658
-		$expireDate = null
659
-	) {
660
-		try {
661
-			$share = $this->getShareById($id);
662
-		} catch (ShareNotFound $e) {
663
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
664
-		}
665
-
666
-		$this->lock($share->getNode());
667
-
668
-		if (!$this->canAccessShare($share, false)) {
669
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
670
-		}
671
-
672
-		/*
392
+            $existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
393
+            if (!empty($existingShares)) {
394
+                return new DataResponse($this->formatShare($existingShares[0]));
395
+            }
396
+
397
+            if ($publicUpload === 'true') {
398
+                // Check if public upload is allowed
399
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
400
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
401
+                }
402
+
403
+                // Public upload can only be set for folders
404
+                if ($path instanceof \OCP\Files\File) {
405
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
406
+                }
407
+
408
+                $share->setPermissions(
409
+                    \OCP\Constants::PERMISSION_READ |
410
+                    \OCP\Constants::PERMISSION_CREATE |
411
+                    \OCP\Constants::PERMISSION_UPDATE |
412
+                    \OCP\Constants::PERMISSION_DELETE
413
+                );
414
+            } else {
415
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
416
+            }
417
+
418
+            // Set password
419
+            if ($password !== '') {
420
+                $share->setPassword($password);
421
+            }
422
+
423
+            //Expire date
424
+            if ($expireDate !== '') {
425
+                try {
426
+                    $expireDate = $this->parseDate($expireDate);
427
+                    $share->setExpirationDate($expireDate);
428
+                } catch (\Exception $e) {
429
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
430
+                }
431
+            }
432
+
433
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
434
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
435
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
436
+            }
437
+
438
+            $share->setSharedWith($shareWith);
439
+            $share->setPermissions($permissions);
440
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
441
+            if ($share->getNodeType() === 'file') {
442
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
443
+            } else {
444
+                $share->setPermissions(
445
+                    \OCP\Constants::PERMISSION_READ |
446
+                    \OCP\Constants::PERMISSION_CREATE |
447
+                    \OCP\Constants::PERMISSION_UPDATE |
448
+                    \OCP\Constants::PERMISSION_DELETE);
449
+            }
450
+            $share->setSharedWith($shareWith);
451
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
452
+            if (!\OCP\App::isEnabled('circles')) {
453
+                throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
454
+            }
455
+
456
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($shareWith);
457
+
458
+            // Valid circle is required to share
459
+            if ($circle === null) {
460
+                throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
461
+            }
462
+            $share->setSharedWith($shareWith);
463
+            $share->setPermissions($permissions);
464
+        } else {
465
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
466
+        }
467
+
468
+        $share->setShareType($shareType);
469
+        $share->setSharedBy($this->currentUser);
470
+
471
+        try {
472
+            $share = $this->shareManager->createShare($share);
473
+        } catch (GenericShareException $e) {
474
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
475
+            throw new OCSException($e->getHint(), $code);
476
+        } catch (\Exception $e) {
477
+            throw new OCSForbiddenException($e->getMessage());
478
+        }
479
+
480
+        $output = $this->formatShare($share);
481
+
482
+        return new DataResponse($output);
483
+    }
484
+
485
+    /**
486
+     * @param \OCP\Files\File|\OCP\Files\Folder $node
487
+     * @return DataResponse
488
+     */
489
+    private function getSharedWithMe($node = null) {
490
+
491
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
492
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
493
+        $circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
494
+
495
+        $shares = array_merge($userShares, $groupShares, $circleShares);
496
+
497
+        $shares = array_filter($shares, function (IShare $share) {
498
+            return $share->getShareOwner() !== $this->currentUser;
499
+        });
500
+
501
+        $formatted = [];
502
+        foreach ($shares as $share) {
503
+            if ($this->canAccessShare($share)) {
504
+                try {
505
+                    $formatted[] = $this->formatShare($share);
506
+                } catch (NotFoundException $e) {
507
+                    // Ignore this share
508
+                }
509
+            }
510
+        }
511
+
512
+        return new DataResponse($formatted);
513
+    }
514
+
515
+    /**
516
+     * @param \OCP\Files\Folder $folder
517
+     * @return DataResponse
518
+     * @throws OCSBadRequestException
519
+     */
520
+    private function getSharesInDir($folder) {
521
+        if (!($folder instanceof \OCP\Files\Folder)) {
522
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
523
+        }
524
+
525
+        $nodes = $folder->getDirectoryListing();
526
+        /** @var \OCP\Share\IShare[] $shares */
527
+        $shares = [];
528
+        foreach ($nodes as $node) {
529
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
530
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
531
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
532
+            if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
533
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
534
+            }
535
+            if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
536
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
537
+            }
538
+        }
539
+
540
+        $formatted = [];
541
+        foreach ($shares as $share) {
542
+            try {
543
+                $formatted[] = $this->formatShare($share);
544
+            } catch (NotFoundException $e) {
545
+                //Ignore this share
546
+            }
547
+        }
548
+
549
+        return new DataResponse($formatted);
550
+    }
551
+
552
+    /**
553
+     * The getShares function.
554
+     *
555
+     * @NoAdminRequired
556
+     *
557
+     * @param string $shared_with_me
558
+     * @param string $reshares
559
+     * @param string $subfiles
560
+     * @param string $path
561
+     *
562
+     * - Get shares by the current user
563
+     * - Get shares by the current user and reshares (?reshares=true)
564
+     * - Get shares with the current user (?shared_with_me=true)
565
+     * - Get shares for a specific path (?path=...)
566
+     * - Get all shares in a folder (?subfiles=true&path=..)
567
+     *
568
+     * @return DataResponse
569
+     * @throws OCSNotFoundException
570
+     */
571
+    public function getShares(
572
+        $shared_with_me = 'false',
573
+        $reshares = 'false',
574
+        $subfiles = 'false',
575
+        $path = null
576
+    ) {
577
+
578
+        if ($path !== null) {
579
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
580
+            try {
581
+                $path = $userFolder->get($path);
582
+                $this->lock($path);
583
+            } catch (\OCP\Files\NotFoundException $e) {
584
+                throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
585
+            } catch (LockedException $e) {
586
+                throw new OCSNotFoundException($this->l->t('Could not lock path'));
587
+            }
588
+        }
589
+
590
+        if ($shared_with_me === 'true') {
591
+            $result = $this->getSharedWithMe($path);
592
+            return $result;
593
+        }
594
+
595
+        if ($subfiles === 'true') {
596
+            $result = $this->getSharesInDir($path);
597
+            return $result;
598
+        }
599
+
600
+        if ($reshares === 'true') {
601
+            $reshares = true;
602
+        } else {
603
+            $reshares = false;
604
+        }
605
+
606
+        // Get all shares
607
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
608
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
609
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
610
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
611
+            $mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
612
+        } else {
613
+            $mailShares = [];
614
+        }
615
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
616
+            $circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
617
+        } else {
618
+            $circleShares = [];
619
+        }
620
+
621
+        $shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
622
+
623
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
624
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
625
+            $shares = array_merge($shares, $federatedShares);
626
+        }
627
+
628
+        $formatted = [];
629
+        foreach ($shares as $share) {
630
+            try {
631
+                $formatted[] = $this->formatShare($share, $path);
632
+            } catch (NotFoundException $e) {
633
+                //Ignore share
634
+            }
635
+        }
636
+
637
+        return new DataResponse($formatted);
638
+    }
639
+
640
+    /**
641
+     * @NoAdminRequired
642
+     *
643
+     * @param int $id
644
+     * @param int $permissions
645
+     * @param string $password
646
+     * @param string $publicUpload
647
+     * @param string $expireDate
648
+     * @return DataResponse
649
+     * @throws OCSNotFoundException
650
+     * @throws OCSBadRequestException
651
+     * @throws OCSForbiddenException
652
+     */
653
+    public function updateShare(
654
+        $id,
655
+        $permissions = null,
656
+        $password = null,
657
+        $publicUpload = null,
658
+        $expireDate = null
659
+    ) {
660
+        try {
661
+            $share = $this->getShareById($id);
662
+        } catch (ShareNotFound $e) {
663
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
664
+        }
665
+
666
+        $this->lock($share->getNode());
667
+
668
+        if (!$this->canAccessShare($share, false)) {
669
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
670
+        }
671
+
672
+        /*
673 673
 		 * expirationdate, password and publicUpload only make sense for link shares
674 674
 		 */
675
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
676
-			if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
677
-				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
678
-			}
679
-
680
-			$newPermissions = null;
681
-			if ($publicUpload === 'true') {
682
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
683
-			} else if ($publicUpload === 'false') {
684
-				$newPermissions = \OCP\Constants::PERMISSION_READ;
685
-			}
686
-
687
-			if ($permissions !== null) {
688
-				$newPermissions = (int)$permissions;
689
-			}
690
-
691
-			if ($newPermissions !== null &&
692
-				!in_array($newPermissions, [
693
-					\OCP\Constants::PERMISSION_READ,
694
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
695
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
696
-					\OCP\Constants::PERMISSION_CREATE, // hidden file list
697
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
698
-				])
699
-			) {
700
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
701
-			}
702
-
703
-			if (
704
-				// legacy
705
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
706
-				// correct
707
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
708
-			) {
709
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
710
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
711
-				}
712
-
713
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
714
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
715
-				}
716
-
717
-				// normalize to correct public upload permissions
718
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
719
-			}
720
-
721
-			if ($newPermissions !== null) {
722
-				$share->setPermissions($newPermissions);
723
-				$permissions = $newPermissions;
724
-			}
725
-
726
-			if ($expireDate === '') {
727
-				$share->setExpirationDate(null);
728
-			} else if ($expireDate !== null) {
729
-				try {
730
-					$expireDate = $this->parseDate($expireDate);
731
-				} catch (\Exception $e) {
732
-					throw new OCSBadRequestException($e->getMessage());
733
-				}
734
-				$share->setExpirationDate($expireDate);
735
-			}
736
-
737
-			if ($password === '') {
738
-				$share->setPassword(null);
739
-			} else if ($password !== null) {
740
-				$share->setPassword($password);
741
-			}
742
-
743
-		} else {
744
-			// For other shares only permissions is valid.
745
-			if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL && $permissions === null) {
746
-				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
747
-			} elseif ($permissions !== null) {
748
-				$permissions = (int)$permissions;
749
-				$share->setPermissions($permissions);
750
-			}
751
-
752
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
753
-				if ($expireDate === '') {
754
-					$share->setExpirationDate(null);
755
-				} else if ($expireDate !== null) {
756
-					try {
757
-						$expireDate = $this->parseDate($expireDate);
758
-					} catch (\Exception $e) {
759
-						throw new OCSBadRequestException($e->getMessage());
760
-					}
761
-					$share->setExpirationDate($expireDate);
762
-				}
763
-
764
-				if ($password === '') {
765
-					$share->setPassword(null);
766
-				} else if ($password !== null) {
767
-					$share->setPassword($password);
768
-				}
769
-			}
770
-		}
771
-
772
-		if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
773
-			/* Check if this is an incomming share */
774
-			$incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
775
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
776
-
777
-			/** @var \OCP\Share\IShare[] $incomingShares */
778
-			if (!empty($incomingShares)) {
779
-				$maxPermissions = 0;
780
-				foreach ($incomingShares as $incomingShare) {
781
-					$maxPermissions |= $incomingShare->getPermissions();
782
-				}
783
-
784
-				if ($share->getPermissions() & ~$maxPermissions) {
785
-					throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
786
-				}
787
-			}
788
-		}
789
-
790
-
791
-		try {
792
-			$share = $this->shareManager->updateShare($share);
793
-		} catch (\Exception $e) {
794
-			throw new OCSBadRequestException($e->getMessage());
795
-		}
796
-
797
-		return new DataResponse($this->formatShare($share));
798
-	}
799
-
800
-	/**
801
-	 * @param \OCP\Share\IShare $share
802
-	 * @return bool
803
-	 */
804
-	protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
805
-		// A file with permissions 0 can't be accessed by us. So Don't show it
806
-		if ($share->getPermissions() === 0) {
807
-			return false;
808
-		}
809
-
810
-		// Owner of the file and the sharer of the file can always get share
811
-		if ($share->getShareOwner() === $this->currentUser ||
812
-			$share->getSharedBy() === $this->currentUser
813
-		) {
814
-			return true;
815
-		}
816
-
817
-		// If the share is shared with you (or a group you are a member of)
818
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
819
-			$share->getSharedWith() === $this->currentUser
820
-		) {
821
-			return true;
822
-		}
823
-
824
-		if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
825
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
826
-			$user = $this->userManager->get($this->currentUser);
827
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
828
-				return true;
829
-			}
830
-		}
831
-
832
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
833
-			// TODO: have a sanity check like above?
834
-			return true;
835
-		}
836
-
837
-		return false;
838
-	}
839
-
840
-	/**
841
-	 * Make sure that the passed date is valid ISO 8601
842
-	 * So YYYY-MM-DD
843
-	 * If not throw an exception
844
-	 *
845
-	 * @param string $expireDate
846
-	 *
847
-	 * @throws \Exception
848
-	 * @return \DateTime
849
-	 */
850
-	private function parseDate($expireDate) {
851
-		try {
852
-			$date = new \DateTime($expireDate);
853
-		} catch (\Exception $e) {
854
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
855
-		}
856
-
857
-		if ($date === false) {
858
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
859
-		}
860
-
861
-		$date->setTime(0, 0, 0);
862
-
863
-		return $date;
864
-	}
865
-
866
-	/**
867
-	 * Since we have multiple providers but the OCS Share API v1 does
868
-	 * not support this we need to check all backends.
869
-	 *
870
-	 * @param string $id
871
-	 * @return \OCP\Share\IShare
872
-	 * @throws ShareNotFound
873
-	 */
874
-	private function getShareById($id) {
875
-		$share = null;
876
-
877
-		// First check if it is an internal share.
878
-		try {
879
-			$share = $this->shareManager->getShareById('ocinternal:' . $id);
880
-			return $share;
881
-		} catch (ShareNotFound $e) {
882
-			// Do nothing, just try the other share type
883
-		}
884
-
885
-
886
-		try {
887
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
888
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id);
889
-				return $share;
890
-			}
891
-		} catch (ShareNotFound $e) {
892
-			// Do nothing, just try the other share type
893
-		}
894
-
895
-		try {
896
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
897
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id);
898
-				return $share;
899
-			}
900
-		} catch (ShareNotFound $e) {
901
-			// Do nothing, just try the other share type
902
-		}
903
-
904
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
905
-			throw new ShareNotFound();
906
-		}
907
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
908
-
909
-		return $share;
910
-	}
911
-
912
-	/**
913
-	 * Lock a Node
914
-	 *
915
-	 * @param \OCP\Files\Node $node
916
-	 */
917
-	private function lock(\OCP\Files\Node $node) {
918
-		$node->lock(ILockingProvider::LOCK_SHARED);
919
-		$this->lockedNode = $node;
920
-	}
921
-
922
-	/**
923
-	 * Cleanup the remaining locks
924
-	 */
925
-	public function cleanup() {
926
-		if ($this->lockedNode !== null) {
927
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
928
-		}
929
-	}
675
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
676
+            if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
677
+                throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
678
+            }
679
+
680
+            $newPermissions = null;
681
+            if ($publicUpload === 'true') {
682
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
683
+            } else if ($publicUpload === 'false') {
684
+                $newPermissions = \OCP\Constants::PERMISSION_READ;
685
+            }
686
+
687
+            if ($permissions !== null) {
688
+                $newPermissions = (int)$permissions;
689
+            }
690
+
691
+            if ($newPermissions !== null &&
692
+                !in_array($newPermissions, [
693
+                    \OCP\Constants::PERMISSION_READ,
694
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
695
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
696
+                    \OCP\Constants::PERMISSION_CREATE, // hidden file list
697
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
698
+                ])
699
+            ) {
700
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
701
+            }
702
+
703
+            if (
704
+                // legacy
705
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
706
+                // correct
707
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
708
+            ) {
709
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
710
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
711
+                }
712
+
713
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
714
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
715
+                }
716
+
717
+                // normalize to correct public upload permissions
718
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
719
+            }
720
+
721
+            if ($newPermissions !== null) {
722
+                $share->setPermissions($newPermissions);
723
+                $permissions = $newPermissions;
724
+            }
725
+
726
+            if ($expireDate === '') {
727
+                $share->setExpirationDate(null);
728
+            } else if ($expireDate !== null) {
729
+                try {
730
+                    $expireDate = $this->parseDate($expireDate);
731
+                } catch (\Exception $e) {
732
+                    throw new OCSBadRequestException($e->getMessage());
733
+                }
734
+                $share->setExpirationDate($expireDate);
735
+            }
736
+
737
+            if ($password === '') {
738
+                $share->setPassword(null);
739
+            } else if ($password !== null) {
740
+                $share->setPassword($password);
741
+            }
742
+
743
+        } else {
744
+            // For other shares only permissions is valid.
745
+            if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL && $permissions === null) {
746
+                throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
747
+            } elseif ($permissions !== null) {
748
+                $permissions = (int)$permissions;
749
+                $share->setPermissions($permissions);
750
+            }
751
+
752
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
753
+                if ($expireDate === '') {
754
+                    $share->setExpirationDate(null);
755
+                } else if ($expireDate !== null) {
756
+                    try {
757
+                        $expireDate = $this->parseDate($expireDate);
758
+                    } catch (\Exception $e) {
759
+                        throw new OCSBadRequestException($e->getMessage());
760
+                    }
761
+                    $share->setExpirationDate($expireDate);
762
+                }
763
+
764
+                if ($password === '') {
765
+                    $share->setPassword(null);
766
+                } else if ($password !== null) {
767
+                    $share->setPassword($password);
768
+                }
769
+            }
770
+        }
771
+
772
+        if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
773
+            /* Check if this is an incomming share */
774
+            $incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
775
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
776
+
777
+            /** @var \OCP\Share\IShare[] $incomingShares */
778
+            if (!empty($incomingShares)) {
779
+                $maxPermissions = 0;
780
+                foreach ($incomingShares as $incomingShare) {
781
+                    $maxPermissions |= $incomingShare->getPermissions();
782
+                }
783
+
784
+                if ($share->getPermissions() & ~$maxPermissions) {
785
+                    throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
786
+                }
787
+            }
788
+        }
789
+
790
+
791
+        try {
792
+            $share = $this->shareManager->updateShare($share);
793
+        } catch (\Exception $e) {
794
+            throw new OCSBadRequestException($e->getMessage());
795
+        }
796
+
797
+        return new DataResponse($this->formatShare($share));
798
+    }
799
+
800
+    /**
801
+     * @param \OCP\Share\IShare $share
802
+     * @return bool
803
+     */
804
+    protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
805
+        // A file with permissions 0 can't be accessed by us. So Don't show it
806
+        if ($share->getPermissions() === 0) {
807
+            return false;
808
+        }
809
+
810
+        // Owner of the file and the sharer of the file can always get share
811
+        if ($share->getShareOwner() === $this->currentUser ||
812
+            $share->getSharedBy() === $this->currentUser
813
+        ) {
814
+            return true;
815
+        }
816
+
817
+        // If the share is shared with you (or a group you are a member of)
818
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
819
+            $share->getSharedWith() === $this->currentUser
820
+        ) {
821
+            return true;
822
+        }
823
+
824
+        if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
825
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
826
+            $user = $this->userManager->get($this->currentUser);
827
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
828
+                return true;
829
+            }
830
+        }
831
+
832
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
833
+            // TODO: have a sanity check like above?
834
+            return true;
835
+        }
836
+
837
+        return false;
838
+    }
839
+
840
+    /**
841
+     * Make sure that the passed date is valid ISO 8601
842
+     * So YYYY-MM-DD
843
+     * If not throw an exception
844
+     *
845
+     * @param string $expireDate
846
+     *
847
+     * @throws \Exception
848
+     * @return \DateTime
849
+     */
850
+    private function parseDate($expireDate) {
851
+        try {
852
+            $date = new \DateTime($expireDate);
853
+        } catch (\Exception $e) {
854
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
855
+        }
856
+
857
+        if ($date === false) {
858
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
859
+        }
860
+
861
+        $date->setTime(0, 0, 0);
862
+
863
+        return $date;
864
+    }
865
+
866
+    /**
867
+     * Since we have multiple providers but the OCS Share API v1 does
868
+     * not support this we need to check all backends.
869
+     *
870
+     * @param string $id
871
+     * @return \OCP\Share\IShare
872
+     * @throws ShareNotFound
873
+     */
874
+    private function getShareById($id) {
875
+        $share = null;
876
+
877
+        // First check if it is an internal share.
878
+        try {
879
+            $share = $this->shareManager->getShareById('ocinternal:' . $id);
880
+            return $share;
881
+        } catch (ShareNotFound $e) {
882
+            // Do nothing, just try the other share type
883
+        }
884
+
885
+
886
+        try {
887
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
888
+                $share = $this->shareManager->getShareById('ocCircleShare:' . $id);
889
+                return $share;
890
+            }
891
+        } catch (ShareNotFound $e) {
892
+            // Do nothing, just try the other share type
893
+        }
894
+
895
+        try {
896
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
897
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id);
898
+                return $share;
899
+            }
900
+        } catch (ShareNotFound $e) {
901
+            // Do nothing, just try the other share type
902
+        }
903
+
904
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
905
+            throw new ShareNotFound();
906
+        }
907
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
908
+
909
+        return $share;
910
+    }
911
+
912
+    /**
913
+     * Lock a Node
914
+     *
915
+     * @param \OCP\Files\Node $node
916
+     */
917
+    private function lock(\OCP\Files\Node $node) {
918
+        $node->lock(ILockingProvider::LOCK_SHARED);
919
+        $this->lockedNode = $node;
920
+    }
921
+
922
+    /**
923
+     * Cleanup the remaining locks
924
+     */
925
+    public function cleanup() {
926
+        if ($this->lockedNode !== null) {
927
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
928
+        }
929
+    }
930 930
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
217 217
 		$result = \OC::$server->getContactsManager()->search($query, [$property]);
218 218
 		foreach ($result as $r) {
219
-			foreach($r[$property] as $value) {
219
+			foreach ($r[$property] as $value) {
220 220
 				if ($value === $query) {
221 221
 					return $r['FN'];
222 222
 				}
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 
495 495
 		$shares = array_merge($userShares, $groupShares, $circleShares);
496 496
 
497
-		$shares = array_filter($shares, function (IShare $share) {
497
+		$shares = array_filter($shares, function(IShare $share) {
498 498
 			return $share->getShareOwner() !== $this->currentUser;
499 499
 		});
500 500
 
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
530 530
 			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
531 531
 			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
532
-			if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
532
+			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
533 533
 				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
534 534
 			}
535 535
 			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
 			}
686 686
 
687 687
 			if ($permissions !== null) {
688
-				$newPermissions = (int)$permissions;
688
+				$newPermissions = (int) $permissions;
689 689
 			}
690 690
 
691 691
 			if ($newPermissions !== null &&
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
 			if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL && $permissions === null) {
746 746
 				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
747 747
 			} elseif ($permissions !== null) {
748
-				$permissions = (int)$permissions;
748
+				$permissions = (int) $permissions;
749 749
 				$share->setPermissions($permissions);
750 750
 			}
751 751
 
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 
877 877
 		// First check if it is an internal share.
878 878
 		try {
879
-			$share = $this->shareManager->getShareById('ocinternal:' . $id);
879
+			$share = $this->shareManager->getShareById('ocinternal:'.$id);
880 880
 			return $share;
881 881
 		} catch (ShareNotFound $e) {
882 882
 			// Do nothing, just try the other share type
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
 
886 886
 		try {
887 887
 			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
888
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id);
888
+				$share = $this->shareManager->getShareById('ocCircleShare:'.$id);
889 889
 				return $share;
890 890
 			}
891 891
 		} catch (ShareNotFound $e) {
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 
895 895
 		try {
896 896
 			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
897
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id);
897
+				$share = $this->shareManager->getShareById('ocMailShare:'.$id);
898 898
 				return $share;
899 899
 			}
900 900
 		} catch (ShareNotFound $e) {
@@ -904,7 +904,7 @@  discard block
 block discarded – undo
904 904
 		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
905 905
 			throw new ShareNotFound();
906 906
 		}
907
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
907
+		$share = $this->shareManager->getShareById('ocFederatedSharing:'.$id);
908 908
 
909 909
 		return $share;
910 910
 	}
Please login to merge, or discard this patch.
apps/files_sharing/lib/Migration.php 1 patch
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -39,270 +39,270 @@
 block discarded – undo
39 39
  */
40 40
 class Migration {
41 41
 
42
-	/** @var IDBConnection */
43
-	private $connection;
44
-
45
-	/** @var  IConfig */
46
-	private $config;
47
-
48
-	/** @var  ICache with all shares we already saw */
49
-	private $shareCache;
50
-
51
-	/** @var string */
52
-	private $table = 'share';
53
-
54
-	public function __construct(IDBConnection $connection, IConfig $config) {
55
-		$this->connection = $connection;
56
-		$this->config = $config;
57
-
58
-		// We cache up to 10k share items (~20MB)
59
-		$this->shareCache = new CappedMemoryCache(10000);
60
-	}
61
-
62
-	/**
63
-	 * move all re-shares to the owner in order to have a flat list of shares
64
-	 * upgrade from oC 8.2 to 9.0 with the new sharing
65
-	 */
66
-	public function removeReShares() {
67
-
68
-		$stmt = $this->getReShares();
69
-
70
-		$owners = [];
71
-		while($share = $stmt->fetch()) {
72
-
73
-			$this->shareCache[$share['id']] = $share;
74
-
75
-			$owners[$share['id']] = [
76
-					'owner' => $this->findOwner($share),
77
-					'initiator' => $share['uid_owner'],
78
-					'type' => $share['share_type'],
79
-			];
80
-
81
-			if (count($owners) === 1000) {
82
-				$this->updateOwners($owners);
83
-				$owners = [];
84
-			}
85
-		}
86
-
87
-		$stmt->closeCursor();
88
-
89
-		if (count($owners)) {
90
-			$this->updateOwners($owners);
91
-		}
92
-	}
93
-
94
-	/**
95
-	 * update all owner information so that all shares have an owner
96
-	 * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
97
-	 */
98
-	public function updateInitiatorInfo() {
99
-		while (true) {
100
-			$shares = $this->getMissingInitiator(1000);
101
-
102
-			if (empty($shares)) {
103
-				break;
104
-			}
105
-
106
-			$owners = [];
107
-			foreach ($shares as $share) {
108
-				$owners[$share['id']] = [
109
-					'owner' => $share['uid_owner'],
110
-					'initiator' => $share['uid_owner'],
111
-					'type' => $share['share_type'],
112
-				];
113
-			}
114
-			$this->updateOwners($owners);
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * this was dropped for Nextcloud 11 in favour of share by mail
120
-	 */
121
-	public function removeSendMailOption() {
122
-		$this->config->deleteAppValue('core', 'shareapi_allow_mail_notification');
123
-		$this->config->deleteAppValue('core', 'shareapi_allow_public_notification');
124
-	}
125
-
126
-	public function addPasswordColumn() {
127
-		$query = $this->connection->getQueryBuilder();
128
-		$query
129
-			->update('share')
130
-			->set('password', 'share_with')
131
-			->where($query->expr()->eq('share_type', $query->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
132
-			->andWhere($query->expr()->isNotNull('share_with'));
133
-		$query->execute();
134
-
135
-		$clearQuery = $this->connection->getQueryBuilder();
136
-		$clearQuery
137
-			->update('share')->set('share_with', $query->createNamedParameter(''))
138
-			->where($query->expr()->eq('share_type', $query->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
139
-
140
-		$clearQuery->execute();
141
-
142
-	}
143
-
144
-	/**
145
-	 * find the owner of a re-shared file/folder
146
-	 *
147
-	 * @param array $share
148
-	 * @return array
149
-	 */
150
-	private function findOwner($share) {
151
-		$currentShare = $share;
152
-		while(!is_null($currentShare['parent'])) {
153
-			if (isset($this->shareCache[$currentShare['parent']])) {
154
-				$currentShare = $this->shareCache[$currentShare['parent']];
155
-			} else {
156
-				$currentShare = $this->getShare((int)$currentShare['parent']);
157
-				$this->shareCache[$currentShare['id']] = $currentShare;
158
-			}
159
-		}
160
-
161
-		return $currentShare['uid_owner'];
162
-	}
163
-
164
-	/**
165
-	 * Get $n re-shares from the database
166
-	 *
167
-	 * @param int $n The max number of shares to fetch
168
-	 * @return \Doctrine\DBAL\Driver\Statement
169
-	 */
170
-	private function getReShares() {
171
-		$query = $this->connection->getQueryBuilder();
172
-		$query->select(['id', 'parent', 'uid_owner', 'share_type'])
173
-			->from($this->table)
174
-			->where($query->expr()->in(
175
-				'share_type',
176
-				$query->createNamedParameter(
177
-					[
178
-						\OCP\Share::SHARE_TYPE_USER,
179
-						\OCP\Share::SHARE_TYPE_GROUP,
180
-						\OCP\Share::SHARE_TYPE_LINK,
181
-						\OCP\Share::SHARE_TYPE_REMOTE,
182
-					],
183
-					Connection::PARAM_INT_ARRAY
184
-				)
185
-			))
186
-			->andWhere($query->expr()->in(
187
-				'item_type',
188
-				$query->createNamedParameter(
189
-					['file', 'folder'],
190
-					Connection::PARAM_STR_ARRAY
191
-				)
192
-			))
193
-			->andWhere($query->expr()->isNotNull('parent'))
194
-			->orderBy('id', 'asc');
195
-		return $query->execute();
196
-
197
-
198
-		$shares = $result->fetchAll();
199
-		$result->closeCursor();
200
-
201
-		$ordered = [];
202
-		foreach ($shares as $share) {
203
-			$ordered[(int)$share['id']] = $share;
204
-		}
205
-
206
-		return $ordered;
207
-	}
208
-
209
-	/**
210
-	 * Get $n re-shares from the database
211
-	 *
212
-	 * @param int $n The max number of shares to fetch
213
-	 * @return array
214
-	 */
215
-	private function getMissingInitiator($n = 1000) {
216
-		$query = $this->connection->getQueryBuilder();
217
-		$query->select(['id', 'uid_owner', 'share_type'])
218
-			->from($this->table)
219
-			->where($query->expr()->in(
220
-				'share_type',
221
-				$query->createNamedParameter(
222
-					[
223
-						\OCP\Share::SHARE_TYPE_USER,
224
-						\OCP\Share::SHARE_TYPE_GROUP,
225
-						\OCP\Share::SHARE_TYPE_LINK,
226
-						\OCP\Share::SHARE_TYPE_REMOTE,
227
-					],
228
-					Connection::PARAM_INT_ARRAY
229
-				)
230
-			))
231
-			->andWhere($query->expr()->in(
232
-				'item_type',
233
-				$query->createNamedParameter(
234
-					['file', 'folder'],
235
-					Connection::PARAM_STR_ARRAY
236
-				)
237
-			))
238
-			->andWhere($query->expr()->isNull('uid_initiator'))
239
-			->orderBy('id', 'asc')
240
-			->setMaxResults($n);
241
-		$result = $query->execute();
242
-		$shares = $result->fetchAll();
243
-		$result->closeCursor();
244
-
245
-		$ordered = [];
246
-		foreach ($shares as $share) {
247
-			$ordered[(int)$share['id']] = $share;
248
-		}
249
-
250
-		return $ordered;
251
-	}
252
-
253
-	/**
254
-	 * get a specific share
255
-	 *
256
-	 * @param int $id
257
-	 * @return array
258
-	 */
259
-	private function getShare($id) {
260
-		$query = $this->connection->getQueryBuilder();
261
-		$query->select(['id', 'parent', 'uid_owner'])
262
-			->from($this->table)
263
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
264
-		$result = $query->execute();
265
-		$share = $result->fetchAll();
266
-		$result->closeCursor();
267
-
268
-		return $share[0];
269
-	}
270
-
271
-	/**
272
-	 * update database with the new owners
273
-	 *
274
-	 * @param array $owners
275
-	 * @throws \Exception
276
-	 */
277
-	private function updateOwners($owners) {
278
-
279
-		$this->connection->beginTransaction();
280
-
281
-		try {
282
-
283
-			foreach ($owners as $id => $owner) {
284
-				$query = $this->connection->getQueryBuilder();
285
-				$query->update($this->table)
286
-					->set('uid_owner', $query->createNamedParameter($owner['owner']))
287
-					->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
288
-
289
-
290
-				if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
291
-					$query->set('parent', $query->createNamedParameter(null));
292
-				}
293
-
294
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
295
-
296
-				$query->execute();
297
-			}
298
-
299
-			$this->connection->commit();
300
-
301
-		} catch (\Exception $e) {
302
-			$this->connection->rollBack();
303
-			throw $e;
304
-		}
305
-
306
-	}
42
+    /** @var IDBConnection */
43
+    private $connection;
44
+
45
+    /** @var  IConfig */
46
+    private $config;
47
+
48
+    /** @var  ICache with all shares we already saw */
49
+    private $shareCache;
50
+
51
+    /** @var string */
52
+    private $table = 'share';
53
+
54
+    public function __construct(IDBConnection $connection, IConfig $config) {
55
+        $this->connection = $connection;
56
+        $this->config = $config;
57
+
58
+        // We cache up to 10k share items (~20MB)
59
+        $this->shareCache = new CappedMemoryCache(10000);
60
+    }
61
+
62
+    /**
63
+     * move all re-shares to the owner in order to have a flat list of shares
64
+     * upgrade from oC 8.2 to 9.0 with the new sharing
65
+     */
66
+    public function removeReShares() {
67
+
68
+        $stmt = $this->getReShares();
69
+
70
+        $owners = [];
71
+        while($share = $stmt->fetch()) {
72
+
73
+            $this->shareCache[$share['id']] = $share;
74
+
75
+            $owners[$share['id']] = [
76
+                    'owner' => $this->findOwner($share),
77
+                    'initiator' => $share['uid_owner'],
78
+                    'type' => $share['share_type'],
79
+            ];
80
+
81
+            if (count($owners) === 1000) {
82
+                $this->updateOwners($owners);
83
+                $owners = [];
84
+            }
85
+        }
86
+
87
+        $stmt->closeCursor();
88
+
89
+        if (count($owners)) {
90
+            $this->updateOwners($owners);
91
+        }
92
+    }
93
+
94
+    /**
95
+     * update all owner information so that all shares have an owner
96
+     * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
97
+     */
98
+    public function updateInitiatorInfo() {
99
+        while (true) {
100
+            $shares = $this->getMissingInitiator(1000);
101
+
102
+            if (empty($shares)) {
103
+                break;
104
+            }
105
+
106
+            $owners = [];
107
+            foreach ($shares as $share) {
108
+                $owners[$share['id']] = [
109
+                    'owner' => $share['uid_owner'],
110
+                    'initiator' => $share['uid_owner'],
111
+                    'type' => $share['share_type'],
112
+                ];
113
+            }
114
+            $this->updateOwners($owners);
115
+        }
116
+    }
117
+
118
+    /**
119
+     * this was dropped for Nextcloud 11 in favour of share by mail
120
+     */
121
+    public function removeSendMailOption() {
122
+        $this->config->deleteAppValue('core', 'shareapi_allow_mail_notification');
123
+        $this->config->deleteAppValue('core', 'shareapi_allow_public_notification');
124
+    }
125
+
126
+    public function addPasswordColumn() {
127
+        $query = $this->connection->getQueryBuilder();
128
+        $query
129
+            ->update('share')
130
+            ->set('password', 'share_with')
131
+            ->where($query->expr()->eq('share_type', $query->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
132
+            ->andWhere($query->expr()->isNotNull('share_with'));
133
+        $query->execute();
134
+
135
+        $clearQuery = $this->connection->getQueryBuilder();
136
+        $clearQuery
137
+            ->update('share')->set('share_with', $query->createNamedParameter(''))
138
+            ->where($query->expr()->eq('share_type', $query->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
139
+
140
+        $clearQuery->execute();
141
+
142
+    }
143
+
144
+    /**
145
+     * find the owner of a re-shared file/folder
146
+     *
147
+     * @param array $share
148
+     * @return array
149
+     */
150
+    private function findOwner($share) {
151
+        $currentShare = $share;
152
+        while(!is_null($currentShare['parent'])) {
153
+            if (isset($this->shareCache[$currentShare['parent']])) {
154
+                $currentShare = $this->shareCache[$currentShare['parent']];
155
+            } else {
156
+                $currentShare = $this->getShare((int)$currentShare['parent']);
157
+                $this->shareCache[$currentShare['id']] = $currentShare;
158
+            }
159
+        }
160
+
161
+        return $currentShare['uid_owner'];
162
+    }
163
+
164
+    /**
165
+     * Get $n re-shares from the database
166
+     *
167
+     * @param int $n The max number of shares to fetch
168
+     * @return \Doctrine\DBAL\Driver\Statement
169
+     */
170
+    private function getReShares() {
171
+        $query = $this->connection->getQueryBuilder();
172
+        $query->select(['id', 'parent', 'uid_owner', 'share_type'])
173
+            ->from($this->table)
174
+            ->where($query->expr()->in(
175
+                'share_type',
176
+                $query->createNamedParameter(
177
+                    [
178
+                        \OCP\Share::SHARE_TYPE_USER,
179
+                        \OCP\Share::SHARE_TYPE_GROUP,
180
+                        \OCP\Share::SHARE_TYPE_LINK,
181
+                        \OCP\Share::SHARE_TYPE_REMOTE,
182
+                    ],
183
+                    Connection::PARAM_INT_ARRAY
184
+                )
185
+            ))
186
+            ->andWhere($query->expr()->in(
187
+                'item_type',
188
+                $query->createNamedParameter(
189
+                    ['file', 'folder'],
190
+                    Connection::PARAM_STR_ARRAY
191
+                )
192
+            ))
193
+            ->andWhere($query->expr()->isNotNull('parent'))
194
+            ->orderBy('id', 'asc');
195
+        return $query->execute();
196
+
197
+
198
+        $shares = $result->fetchAll();
199
+        $result->closeCursor();
200
+
201
+        $ordered = [];
202
+        foreach ($shares as $share) {
203
+            $ordered[(int)$share['id']] = $share;
204
+        }
205
+
206
+        return $ordered;
207
+    }
208
+
209
+    /**
210
+     * Get $n re-shares from the database
211
+     *
212
+     * @param int $n The max number of shares to fetch
213
+     * @return array
214
+     */
215
+    private function getMissingInitiator($n = 1000) {
216
+        $query = $this->connection->getQueryBuilder();
217
+        $query->select(['id', 'uid_owner', 'share_type'])
218
+            ->from($this->table)
219
+            ->where($query->expr()->in(
220
+                'share_type',
221
+                $query->createNamedParameter(
222
+                    [
223
+                        \OCP\Share::SHARE_TYPE_USER,
224
+                        \OCP\Share::SHARE_TYPE_GROUP,
225
+                        \OCP\Share::SHARE_TYPE_LINK,
226
+                        \OCP\Share::SHARE_TYPE_REMOTE,
227
+                    ],
228
+                    Connection::PARAM_INT_ARRAY
229
+                )
230
+            ))
231
+            ->andWhere($query->expr()->in(
232
+                'item_type',
233
+                $query->createNamedParameter(
234
+                    ['file', 'folder'],
235
+                    Connection::PARAM_STR_ARRAY
236
+                )
237
+            ))
238
+            ->andWhere($query->expr()->isNull('uid_initiator'))
239
+            ->orderBy('id', 'asc')
240
+            ->setMaxResults($n);
241
+        $result = $query->execute();
242
+        $shares = $result->fetchAll();
243
+        $result->closeCursor();
244
+
245
+        $ordered = [];
246
+        foreach ($shares as $share) {
247
+            $ordered[(int)$share['id']] = $share;
248
+        }
249
+
250
+        return $ordered;
251
+    }
252
+
253
+    /**
254
+     * get a specific share
255
+     *
256
+     * @param int $id
257
+     * @return array
258
+     */
259
+    private function getShare($id) {
260
+        $query = $this->connection->getQueryBuilder();
261
+        $query->select(['id', 'parent', 'uid_owner'])
262
+            ->from($this->table)
263
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
264
+        $result = $query->execute();
265
+        $share = $result->fetchAll();
266
+        $result->closeCursor();
267
+
268
+        return $share[0];
269
+    }
270
+
271
+    /**
272
+     * update database with the new owners
273
+     *
274
+     * @param array $owners
275
+     * @throws \Exception
276
+     */
277
+    private function updateOwners($owners) {
278
+
279
+        $this->connection->beginTransaction();
280
+
281
+        try {
282
+
283
+            foreach ($owners as $id => $owner) {
284
+                $query = $this->connection->getQueryBuilder();
285
+                $query->update($this->table)
286
+                    ->set('uid_owner', $query->createNamedParameter($owner['owner']))
287
+                    ->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
288
+
289
+
290
+                if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
291
+                    $query->set('parent', $query->createNamedParameter(null));
292
+                }
293
+
294
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
295
+
296
+                $query->execute();
297
+            }
298
+
299
+            $this->connection->commit();
300
+
301
+        } catch (\Exception $e) {
302
+            $this->connection->rollBack();
303
+            throw $e;
304
+        }
305
+
306
+    }
307 307
 
308 308
 }
Please login to merge, or discard this patch.
apps/sharebymail/templates/altmailpassword.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -6,5 +6,5 @@
 block discarded – undo
6 6
 ?>
7 7
 
8 8
 	--
9
-<?php p($theme->getName() . ' - ' . $theme->getSlogan()); ?>
9
+<?php p($theme->getName().' - '.$theme->getSlogan()); ?>
10 10
 <?php print_unescaped("\n".$theme->getBaseUrl());
Please login to merge, or discard this patch.
apps/sharebymail/templates/mailpassword.php 2 patches
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -36,10 +36,10 @@
 block discarded – undo
36 36
 					<td width="20px">&nbsp;</td>
37 37
 					<td style="font-weight:normal; font-size:0.8em; line-height:1.2em; font-family:verdana,'arial',sans;">
38 38
 						<?php
39
-						print_unescaped($l->t('Hey there,<br><br>%s shared <i>%s</i> with you.<br>You should have already received a separate mail with a link to access it.<br><br>It is protected with the following password: %s<br><br>', [$_['initiator'], $_['filename'], $_['password']]));
40
-						// TRANSLATORS term at the end of a mail
41
-						p($l->t('Cheers!'));
42
-						?>
39
+                        print_unescaped($l->t('Hey there,<br><br>%s shared <i>%s</i> with you.<br>You should have already received a separate mail with a link to access it.<br><br>It is protected with the following password: %s<br><br>', [$_['initiator'], $_['filename'], $_['password']]));
40
+                        // TRANSLATORS term at the end of a mail
41
+                        p($l->t('Cheers!'));
42
+                        ?>
43 43
 					</td>
44 44
 				</tr>
45 45
 				<tr><td colspan="2">&nbsp;</td></tr>
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
 	<tr><td>
7 7
 			<table cellspacing="0" cellpadding="0" border="0" width="600px">
8 8
 				<tr>
9
-					<td colspan="2" bgcolor="<?php p($theme->getMailHeaderColor());?>">
9
+					<td colspan="2" bgcolor="<?php p($theme->getMailHeaderColor()); ?>">
10 10
 						<img src="<?php p(\OC::$server->getURLGenerator()->getAbsoluteURL(image_path('', 'logo-mail.png'))); ?>" alt="<?php p($theme->getName()); ?>"/>
11 11
 					</td>
12 12
 				</tr>
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 					<td style="font-weight:normal; font-size:0.8em; line-height:1.2em; font-family:verdana,'arial',sans;">--<br>
28 28
 						<?php p($theme->getName()); ?> -
29 29
 						<?php p($theme->getSlogan()); ?>
30
-						<br><a href="<?php p($theme->getBaseUrl()); ?>"><?php p($theme->getBaseUrl());?></a>
30
+						<br><a href="<?php p($theme->getBaseUrl()); ?>"><?php p($theme->getBaseUrl()); ?></a>
31 31
 					</td>
32 32
 				</tr>
33 33
 				<tr>
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -40,225 +40,225 @@
 block discarded – undo
40 40
  */
41 41
 class ProviderFactory implements IProviderFactory {
42 42
 
43
-	/** @var IServerContainer */
44
-	private $serverContainer;
45
-	/** @var DefaultShareProvider */
46
-	private $defaultProvider = null;
47
-	/** @var FederatedShareProvider */
48
-	private $federatedProvider = null;
49
-	/** @var  ShareByMailProvider */
50
-	private $shareByMailProvider;
51
-	/** @var  \OCA\Circles\ShareByCircleProvider;
52
-	 * ShareByCircleProvider */
53
-	private $shareByCircleProvider;
54
-
55
-	/**
56
-	 * IProviderFactory constructor.
57
-	 *
58
-	 * @param IServerContainer $serverContainer
59
-	 */
60
-	public function __construct(IServerContainer $serverContainer) {
61
-		$this->serverContainer = $serverContainer;
62
-	}
63
-
64
-	/**
65
-	 * Create the default share provider.
66
-	 *
67
-	 * @return DefaultShareProvider
68
-	 */
69
-	protected function defaultShareProvider() {
70
-		if ($this->defaultProvider === null) {
71
-			$this->defaultProvider = new DefaultShareProvider(
72
-				$this->serverContainer->getDatabaseConnection(),
73
-				$this->serverContainer->getUserManager(),
74
-				$this->serverContainer->getGroupManager(),
75
-				$this->serverContainer->getLazyRootFolder()
76
-			);
77
-		}
78
-
79
-		return $this->defaultProvider;
80
-	}
81
-
82
-	/**
83
-	 * Create the federated share provider
84
-	 *
85
-	 * @return FederatedShareProvider
86
-	 */
87
-	protected function federatedShareProvider() {
88
-		if ($this->federatedProvider === null) {
89
-			/*
43
+    /** @var IServerContainer */
44
+    private $serverContainer;
45
+    /** @var DefaultShareProvider */
46
+    private $defaultProvider = null;
47
+    /** @var FederatedShareProvider */
48
+    private $federatedProvider = null;
49
+    /** @var  ShareByMailProvider */
50
+    private $shareByMailProvider;
51
+    /** @var  \OCA\Circles\ShareByCircleProvider;
52
+     * ShareByCircleProvider */
53
+    private $shareByCircleProvider;
54
+
55
+    /**
56
+     * IProviderFactory constructor.
57
+     *
58
+     * @param IServerContainer $serverContainer
59
+     */
60
+    public function __construct(IServerContainer $serverContainer) {
61
+        $this->serverContainer = $serverContainer;
62
+    }
63
+
64
+    /**
65
+     * Create the default share provider.
66
+     *
67
+     * @return DefaultShareProvider
68
+     */
69
+    protected function defaultShareProvider() {
70
+        if ($this->defaultProvider === null) {
71
+            $this->defaultProvider = new DefaultShareProvider(
72
+                $this->serverContainer->getDatabaseConnection(),
73
+                $this->serverContainer->getUserManager(),
74
+                $this->serverContainer->getGroupManager(),
75
+                $this->serverContainer->getLazyRootFolder()
76
+            );
77
+        }
78
+
79
+        return $this->defaultProvider;
80
+    }
81
+
82
+    /**
83
+     * Create the federated share provider
84
+     *
85
+     * @return FederatedShareProvider
86
+     */
87
+    protected function federatedShareProvider() {
88
+        if ($this->federatedProvider === null) {
89
+            /*
90 90
 			 * Check if the app is enabled
91 91
 			 */
92
-			$appManager = $this->serverContainer->getAppManager();
93
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
94
-				return null;
95
-			}
92
+            $appManager = $this->serverContainer->getAppManager();
93
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
94
+                return null;
95
+            }
96 96
 
97
-			/*
97
+            /*
98 98
 			 * TODO: add factory to federated sharing app
99 99
 			 */
100
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
101
-			$addressHandler = new AddressHandler(
102
-				$this->serverContainer->getURLGenerator(),
103
-				$l,
104
-				$this->serverContainer->getCloudIdManager()
105
-			);
106
-			$discoveryManager = new DiscoveryManager(
107
-				$this->serverContainer->getMemCacheFactory(),
108
-				$this->serverContainer->getHTTPClientService()
109
-			);
110
-			$notifications = new Notifications(
111
-				$addressHandler,
112
-				$this->serverContainer->getHTTPClientService(),
113
-				$discoveryManager,
114
-				$this->serverContainer->getJobList()
115
-			);
116
-			$tokenHandler = new TokenHandler(
117
-				$this->serverContainer->getSecureRandom()
118
-			);
119
-
120
-			$this->federatedProvider = new FederatedShareProvider(
121
-				$this->serverContainer->getDatabaseConnection(),
122
-				$addressHandler,
123
-				$notifications,
124
-				$tokenHandler,
125
-				$l,
126
-				$this->serverContainer->getLogger(),
127
-				$this->serverContainer->getLazyRootFolder(),
128
-				$this->serverContainer->getConfig(),
129
-				$this->serverContainer->getUserManager(),
130
-				$this->serverContainer->getCloudIdManager()
131
-			);
132
-		}
133
-
134
-		return $this->federatedProvider;
135
-	}
136
-
137
-	/**
138
-	 * Create the federated share provider
139
-	 *
140
-	 * @return ShareByMailProvider
141
-	 */
142
-	protected function getShareByMailProvider() {
143
-		if ($this->shareByMailProvider === null) {
144
-			/*
100
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
101
+            $addressHandler = new AddressHandler(
102
+                $this->serverContainer->getURLGenerator(),
103
+                $l,
104
+                $this->serverContainer->getCloudIdManager()
105
+            );
106
+            $discoveryManager = new DiscoveryManager(
107
+                $this->serverContainer->getMemCacheFactory(),
108
+                $this->serverContainer->getHTTPClientService()
109
+            );
110
+            $notifications = new Notifications(
111
+                $addressHandler,
112
+                $this->serverContainer->getHTTPClientService(),
113
+                $discoveryManager,
114
+                $this->serverContainer->getJobList()
115
+            );
116
+            $tokenHandler = new TokenHandler(
117
+                $this->serverContainer->getSecureRandom()
118
+            );
119
+
120
+            $this->federatedProvider = new FederatedShareProvider(
121
+                $this->serverContainer->getDatabaseConnection(),
122
+                $addressHandler,
123
+                $notifications,
124
+                $tokenHandler,
125
+                $l,
126
+                $this->serverContainer->getLogger(),
127
+                $this->serverContainer->getLazyRootFolder(),
128
+                $this->serverContainer->getConfig(),
129
+                $this->serverContainer->getUserManager(),
130
+                $this->serverContainer->getCloudIdManager()
131
+            );
132
+        }
133
+
134
+        return $this->federatedProvider;
135
+    }
136
+
137
+    /**
138
+     * Create the federated share provider
139
+     *
140
+     * @return ShareByMailProvider
141
+     */
142
+    protected function getShareByMailProvider() {
143
+        if ($this->shareByMailProvider === null) {
144
+            /*
145 145
 			 * Check if the app is enabled
146 146
 			 */
147
-			$appManager = $this->serverContainer->getAppManager();
148
-			if (!$appManager->isEnabledForUser('sharebymail')) {
149
-				return null;
150
-			}
151
-
152
-			$l = $this->serverContainer->getL10N('sharebymail');
153
-
154
-			$this->shareByMailProvider = new ShareByMailProvider(
155
-				$this->serverContainer->getDatabaseConnection(),
156
-				$this->serverContainer->getSecureRandom(),
157
-				$this->serverContainer->getUserManager(),
158
-				$this->serverContainer->getLazyRootFolder(),
159
-				$l,
160
-				$this->serverContainer->getLogger(),
161
-				$this->serverContainer->getMailer(),
162
-				$this->serverContainer->getURLGenerator(),
163
-				$this->serverContainer->getActivityManager(),
164
-				$this->serverContainer->getHasher()
165
-			);
166
-		}
167
-
168
-		return $this->shareByMailProvider;
169
-	}
170
-
171
-
172
-	/**
173
-	 * Create the circle share provider
174
-	 *
175
-	 * @return FederatedShareProvider
176
-	 */
177
-	protected function getShareByCircleProvider() {
178
-
179
-		$appManager = $this->serverContainer->getAppManager();
180
-		if (!$appManager->isEnabledForUser('circles')) {
181
-			return null;
182
-		}
183
-
184
-
185
-		if ($this->shareByCircleProvider === null) {
186
-
187
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
188
-				$this->serverContainer->getDatabaseConnection(),
189
-				$this->serverContainer->getSecureRandom(),
190
-				$this->serverContainer->getUserManager(),
191
-				$this->serverContainer->getLazyRootFolder(),
192
-				$this->serverContainer->getL10N('circles'),
193
-				$this->serverContainer->getLogger(),
194
-				$this->serverContainer->getURLGenerator()
195
-			);
196
-		}
197
-
198
-		return $this->shareByCircleProvider;
199
-	}
200
-
201
-
202
-	/**
203
-	 * @inheritdoc
204
-	 */
205
-	public function getProvider($id) {
206
-		$provider = null;
207
-		if ($id === 'ocinternal') {
208
-			$provider = $this->defaultShareProvider();
209
-		} else if ($id === 'ocFederatedSharing') {
210
-			$provider = $this->federatedShareProvider();
211
-		} else if ($id === 'ocMailShare') {
212
-			$provider = $this->getShareByMailProvider();
213
-		} else if ($id === 'ocCircleShare') {
214
-			$provider = $this->getShareByCircleProvider();
215
-		}
216
-
217
-		if ($provider === null) {
218
-			throw new ProviderException('No provider with id .' . $id . ' found.');
219
-		}
220
-
221
-		return $provider;
222
-	}
223
-
224
-	/**
225
-	 * @inheritdoc
226
-	 */
227
-	public function getProviderForType($shareType) {
228
-		$provider = null;
229
-
230
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
231
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
232
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
233
-		) {
234
-			$provider = $this->defaultShareProvider();
235
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
236
-			$provider = $this->federatedShareProvider();
237
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
238
-			$provider = $this->getShareByMailProvider();
239
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
240
-			$provider = $this->getShareByCircleProvider();
241
-		}
242
-
243
-
244
-		if ($provider === null) {
245
-			throw new ProviderException('No share provider for share type ' . $shareType);
246
-		}
247
-
248
-		return $provider;
249
-	}
250
-
251
-	public function getAllProviders() {
252
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
253
-		$shareByMail = $this->getShareByMailProvider();
254
-		if ($shareByMail !== null) {
255
-			$shares[] = $shareByMail;
256
-		}
257
-		$shareByCircle = $this->getShareByCircleProvider();
258
-		if ($shareByCircle !== null) {
259
-			$shares[] = $shareByCircle;
260
-		}
261
-
262
-		return $shares;
263
-	}
147
+            $appManager = $this->serverContainer->getAppManager();
148
+            if (!$appManager->isEnabledForUser('sharebymail')) {
149
+                return null;
150
+            }
151
+
152
+            $l = $this->serverContainer->getL10N('sharebymail');
153
+
154
+            $this->shareByMailProvider = new ShareByMailProvider(
155
+                $this->serverContainer->getDatabaseConnection(),
156
+                $this->serverContainer->getSecureRandom(),
157
+                $this->serverContainer->getUserManager(),
158
+                $this->serverContainer->getLazyRootFolder(),
159
+                $l,
160
+                $this->serverContainer->getLogger(),
161
+                $this->serverContainer->getMailer(),
162
+                $this->serverContainer->getURLGenerator(),
163
+                $this->serverContainer->getActivityManager(),
164
+                $this->serverContainer->getHasher()
165
+            );
166
+        }
167
+
168
+        return $this->shareByMailProvider;
169
+    }
170
+
171
+
172
+    /**
173
+     * Create the circle share provider
174
+     *
175
+     * @return FederatedShareProvider
176
+     */
177
+    protected function getShareByCircleProvider() {
178
+
179
+        $appManager = $this->serverContainer->getAppManager();
180
+        if (!$appManager->isEnabledForUser('circles')) {
181
+            return null;
182
+        }
183
+
184
+
185
+        if ($this->shareByCircleProvider === null) {
186
+
187
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
188
+                $this->serverContainer->getDatabaseConnection(),
189
+                $this->serverContainer->getSecureRandom(),
190
+                $this->serverContainer->getUserManager(),
191
+                $this->serverContainer->getLazyRootFolder(),
192
+                $this->serverContainer->getL10N('circles'),
193
+                $this->serverContainer->getLogger(),
194
+                $this->serverContainer->getURLGenerator()
195
+            );
196
+        }
197
+
198
+        return $this->shareByCircleProvider;
199
+    }
200
+
201
+
202
+    /**
203
+     * @inheritdoc
204
+     */
205
+    public function getProvider($id) {
206
+        $provider = null;
207
+        if ($id === 'ocinternal') {
208
+            $provider = $this->defaultShareProvider();
209
+        } else if ($id === 'ocFederatedSharing') {
210
+            $provider = $this->federatedShareProvider();
211
+        } else if ($id === 'ocMailShare') {
212
+            $provider = $this->getShareByMailProvider();
213
+        } else if ($id === 'ocCircleShare') {
214
+            $provider = $this->getShareByCircleProvider();
215
+        }
216
+
217
+        if ($provider === null) {
218
+            throw new ProviderException('No provider with id .' . $id . ' found.');
219
+        }
220
+
221
+        return $provider;
222
+    }
223
+
224
+    /**
225
+     * @inheritdoc
226
+     */
227
+    public function getProviderForType($shareType) {
228
+        $provider = null;
229
+
230
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
231
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
232
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
233
+        ) {
234
+            $provider = $this->defaultShareProvider();
235
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
236
+            $provider = $this->federatedShareProvider();
237
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
238
+            $provider = $this->getShareByMailProvider();
239
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
240
+            $provider = $this->getShareByCircleProvider();
241
+        }
242
+
243
+
244
+        if ($provider === null) {
245
+            throw new ProviderException('No share provider for share type ' . $shareType);
246
+        }
247
+
248
+        return $provider;
249
+    }
250
+
251
+    public function getAllProviders() {
252
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
253
+        $shareByMail = $this->getShareByMailProvider();
254
+        if ($shareByMail !== null) {
255
+            $shares[] = $shareByMail;
256
+        }
257
+        $shareByCircle = $this->getShareByCircleProvider();
258
+        if ($shareByCircle !== null) {
259
+            $shares[] = $shareByCircle;
260
+        }
261
+
262
+        return $shares;
263
+    }
264 264
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1256 added lines, -1256 removed lines patch added patch discarded remove patch
@@ -57,1283 +57,1283 @@
 block discarded – undo
57 57
  */
58 58
 class Manager implements IManager {
59 59
 
60
-	/** @var IProviderFactory */
61
-	private $factory;
62
-	/** @var ILogger */
63
-	private $logger;
64
-	/** @var IConfig */
65
-	private $config;
66
-	/** @var ISecureRandom */
67
-	private $secureRandom;
68
-	/** @var IHasher */
69
-	private $hasher;
70
-	/** @var IMountManager */
71
-	private $mountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IL10N */
75
-	private $l;
76
-	/** @var IUserManager */
77
-	private $userManager;
78
-	/** @var IRootFolder */
79
-	private $rootFolder;
80
-	/** @var CappedMemoryCache */
81
-	private $sharingDisabledForUsersCache;
82
-	/** @var EventDispatcher */
83
-	private $eventDispatcher;
84
-	/** @var LegacyHooks */
85
-	private $legacyHooks;
86
-
87
-
88
-	/**
89
-	 * Manager constructor.
90
-	 *
91
-	 * @param ILogger $logger
92
-	 * @param IConfig $config
93
-	 * @param ISecureRandom $secureRandom
94
-	 * @param IHasher $hasher
95
-	 * @param IMountManager $mountManager
96
-	 * @param IGroupManager $groupManager
97
-	 * @param IL10N $l
98
-	 * @param IProviderFactory $factory
99
-	 * @param IUserManager $userManager
100
-	 * @param IRootFolder $rootFolder
101
-	 * @param EventDispatcher $eventDispatcher
102
-	 */
103
-	public function __construct(
104
-			ILogger $logger,
105
-			IConfig $config,
106
-			ISecureRandom $secureRandom,
107
-			IHasher $hasher,
108
-			IMountManager $mountManager,
109
-			IGroupManager $groupManager,
110
-			IL10N $l,
111
-			IProviderFactory $factory,
112
-			IUserManager $userManager,
113
-			IRootFolder $rootFolder,
114
-			EventDispatcher $eventDispatcher
115
-	) {
116
-		$this->logger = $logger;
117
-		$this->config = $config;
118
-		$this->secureRandom = $secureRandom;
119
-		$this->hasher = $hasher;
120
-		$this->mountManager = $mountManager;
121
-		$this->groupManager = $groupManager;
122
-		$this->l = $l;
123
-		$this->factory = $factory;
124
-		$this->userManager = $userManager;
125
-		$this->rootFolder = $rootFolder;
126
-		$this->eventDispatcher = $eventDispatcher;
127
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
128
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
129
-	}
130
-
131
-	/**
132
-	 * Convert from a full share id to a tuple (providerId, shareId)
133
-	 *
134
-	 * @param string $id
135
-	 * @return string[]
136
-	 */
137
-	private function splitFullId($id) {
138
-		return explode(':', $id, 2);
139
-	}
140
-
141
-	/**
142
-	 * Verify if a password meets all requirements
143
-	 *
144
-	 * @param string $password
145
-	 * @throws \Exception
146
-	 */
147
-	protected function verifyPassword($password) {
148
-		if ($password === null) {
149
-			// No password is set, check if this is allowed.
150
-			if ($this->shareApiLinkEnforcePassword()) {
151
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
152
-			}
153
-
154
-			return;
155
-		}
156
-
157
-		// Let others verify the password
158
-		try {
159
-			$event = new GenericEvent($password);
160
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
161
-		} catch (HintException $e) {
162
-			throw new \Exception($e->getHint());
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * Check for generic requirements before creating a share
168
-	 *
169
-	 * @param \OCP\Share\IShare $share
170
-	 * @throws \InvalidArgumentException
171
-	 * @throws GenericShareException
172
-	 */
173
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
174
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
175
-			// We expect a valid user as sharedWith for user shares
176
-			if (!$this->userManager->userExists($share->getSharedWith())) {
177
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
178
-			}
179
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
180
-			// We expect a valid group as sharedWith for group shares
181
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
182
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
183
-			}
184
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
185
-			if ($share->getSharedWith() !== null) {
186
-				throw new \InvalidArgumentException('SharedWith should be empty');
187
-			}
188
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
189
-			if ($share->getSharedWith() === null) {
190
-				throw new \InvalidArgumentException('SharedWith should not be empty');
191
-			}
192
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
193
-			if ($share->getSharedWith() === null) {
194
-				throw new \InvalidArgumentException('SharedWith should not be empty');
195
-			}
196
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
198
-			if ($circle === null) {
199
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
200
-			}
201
-		} else {
202
-			// We can't handle other types yet
203
-			throw new \InvalidArgumentException('unknown share type');
204
-		}
205
-
206
-		// Verify the initiator of the share is set
207
-		if ($share->getSharedBy() === null) {
208
-			throw new \InvalidArgumentException('SharedBy should be set');
209
-		}
210
-
211
-		// Cannot share with yourself
212
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
213
-			$share->getSharedWith() === $share->getSharedBy()) {
214
-			throw new \InvalidArgumentException('Can\'t share with yourself');
215
-		}
216
-
217
-		// The path should be set
218
-		if ($share->getNode() === null) {
219
-			throw new \InvalidArgumentException('Path should be set');
220
-		}
221
-
222
-		// And it should be a file or a folder
223
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
224
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
225
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
226
-		}
227
-
228
-		// And you can't share your rootfolder
229
-		if ($this->userManager->userExists($share->getSharedBy())) {
230
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
231
-		} else {
232
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
233
-		}
234
-		if ($sharedPath === $share->getNode()->getPath()) {
235
-			throw new \InvalidArgumentException('You can\'t share your root folder');
236
-		}
237
-
238
-		// Check if we actually have share permissions
239
-		if (!$share->getNode()->isShareable()) {
240
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
241
-			throw new GenericShareException($message_t, $message_t, 404);
242
-		}
243
-
244
-		// Permissions should be set
245
-		if ($share->getPermissions() === null) {
246
-			throw new \InvalidArgumentException('A share requires permissions');
247
-		}
248
-
249
-		/*
60
+    /** @var IProviderFactory */
61
+    private $factory;
62
+    /** @var ILogger */
63
+    private $logger;
64
+    /** @var IConfig */
65
+    private $config;
66
+    /** @var ISecureRandom */
67
+    private $secureRandom;
68
+    /** @var IHasher */
69
+    private $hasher;
70
+    /** @var IMountManager */
71
+    private $mountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IL10N */
75
+    private $l;
76
+    /** @var IUserManager */
77
+    private $userManager;
78
+    /** @var IRootFolder */
79
+    private $rootFolder;
80
+    /** @var CappedMemoryCache */
81
+    private $sharingDisabledForUsersCache;
82
+    /** @var EventDispatcher */
83
+    private $eventDispatcher;
84
+    /** @var LegacyHooks */
85
+    private $legacyHooks;
86
+
87
+
88
+    /**
89
+     * Manager constructor.
90
+     *
91
+     * @param ILogger $logger
92
+     * @param IConfig $config
93
+     * @param ISecureRandom $secureRandom
94
+     * @param IHasher $hasher
95
+     * @param IMountManager $mountManager
96
+     * @param IGroupManager $groupManager
97
+     * @param IL10N $l
98
+     * @param IProviderFactory $factory
99
+     * @param IUserManager $userManager
100
+     * @param IRootFolder $rootFolder
101
+     * @param EventDispatcher $eventDispatcher
102
+     */
103
+    public function __construct(
104
+            ILogger $logger,
105
+            IConfig $config,
106
+            ISecureRandom $secureRandom,
107
+            IHasher $hasher,
108
+            IMountManager $mountManager,
109
+            IGroupManager $groupManager,
110
+            IL10N $l,
111
+            IProviderFactory $factory,
112
+            IUserManager $userManager,
113
+            IRootFolder $rootFolder,
114
+            EventDispatcher $eventDispatcher
115
+    ) {
116
+        $this->logger = $logger;
117
+        $this->config = $config;
118
+        $this->secureRandom = $secureRandom;
119
+        $this->hasher = $hasher;
120
+        $this->mountManager = $mountManager;
121
+        $this->groupManager = $groupManager;
122
+        $this->l = $l;
123
+        $this->factory = $factory;
124
+        $this->userManager = $userManager;
125
+        $this->rootFolder = $rootFolder;
126
+        $this->eventDispatcher = $eventDispatcher;
127
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
128
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
129
+    }
130
+
131
+    /**
132
+     * Convert from a full share id to a tuple (providerId, shareId)
133
+     *
134
+     * @param string $id
135
+     * @return string[]
136
+     */
137
+    private function splitFullId($id) {
138
+        return explode(':', $id, 2);
139
+    }
140
+
141
+    /**
142
+     * Verify if a password meets all requirements
143
+     *
144
+     * @param string $password
145
+     * @throws \Exception
146
+     */
147
+    protected function verifyPassword($password) {
148
+        if ($password === null) {
149
+            // No password is set, check if this is allowed.
150
+            if ($this->shareApiLinkEnforcePassword()) {
151
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
152
+            }
153
+
154
+            return;
155
+        }
156
+
157
+        // Let others verify the password
158
+        try {
159
+            $event = new GenericEvent($password);
160
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
161
+        } catch (HintException $e) {
162
+            throw new \Exception($e->getHint());
163
+        }
164
+    }
165
+
166
+    /**
167
+     * Check for generic requirements before creating a share
168
+     *
169
+     * @param \OCP\Share\IShare $share
170
+     * @throws \InvalidArgumentException
171
+     * @throws GenericShareException
172
+     */
173
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
174
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
175
+            // We expect a valid user as sharedWith for user shares
176
+            if (!$this->userManager->userExists($share->getSharedWith())) {
177
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
178
+            }
179
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
180
+            // We expect a valid group as sharedWith for group shares
181
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
182
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
183
+            }
184
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
185
+            if ($share->getSharedWith() !== null) {
186
+                throw new \InvalidArgumentException('SharedWith should be empty');
187
+            }
188
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
189
+            if ($share->getSharedWith() === null) {
190
+                throw new \InvalidArgumentException('SharedWith should not be empty');
191
+            }
192
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
193
+            if ($share->getSharedWith() === null) {
194
+                throw new \InvalidArgumentException('SharedWith should not be empty');
195
+            }
196
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
198
+            if ($circle === null) {
199
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
200
+            }
201
+        } else {
202
+            // We can't handle other types yet
203
+            throw new \InvalidArgumentException('unknown share type');
204
+        }
205
+
206
+        // Verify the initiator of the share is set
207
+        if ($share->getSharedBy() === null) {
208
+            throw new \InvalidArgumentException('SharedBy should be set');
209
+        }
210
+
211
+        // Cannot share with yourself
212
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
213
+            $share->getSharedWith() === $share->getSharedBy()) {
214
+            throw new \InvalidArgumentException('Can\'t share with yourself');
215
+        }
216
+
217
+        // The path should be set
218
+        if ($share->getNode() === null) {
219
+            throw new \InvalidArgumentException('Path should be set');
220
+        }
221
+
222
+        // And it should be a file or a folder
223
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
224
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
225
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
226
+        }
227
+
228
+        // And you can't share your rootfolder
229
+        if ($this->userManager->userExists($share->getSharedBy())) {
230
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
231
+        } else {
232
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
233
+        }
234
+        if ($sharedPath === $share->getNode()->getPath()) {
235
+            throw new \InvalidArgumentException('You can\'t share your root folder');
236
+        }
237
+
238
+        // Check if we actually have share permissions
239
+        if (!$share->getNode()->isShareable()) {
240
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
241
+            throw new GenericShareException($message_t, $message_t, 404);
242
+        }
243
+
244
+        // Permissions should be set
245
+        if ($share->getPermissions() === null) {
246
+            throw new \InvalidArgumentException('A share requires permissions');
247
+        }
248
+
249
+        /*
250 250
 		 * Quick fix for #23536
251 251
 		 * Non moveable mount points do not have update and delete permissions
252 252
 		 * while we 'most likely' do have that on the storage.
253 253
 		 */
254
-		$permissions = $share->getNode()->getPermissions();
255
-		$mount = $share->getNode()->getMountPoint();
256
-		if (!($mount instanceof MoveableMount)) {
257
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
258
-		}
259
-
260
-		// Check that we do not share with more permissions than we have
261
-		if ($share->getPermissions() & ~$permissions) {
262
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
263
-			throw new GenericShareException($message_t, $message_t, 404);
264
-		}
265
-
266
-
267
-		// Check that read permissions are always set
268
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
269
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
270
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
271
-			throw new \InvalidArgumentException('Shares need at least read permissions');
272
-		}
273
-
274
-		if ($share->getNode() instanceof \OCP\Files\File) {
275
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
276
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
277
-				throw new GenericShareException($message_t);
278
-			}
279
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
280
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
281
-				throw new GenericShareException($message_t);
282
-			}
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * Validate if the expiration date fits the system settings
288
-	 *
289
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
290
-	 * @return \OCP\Share\IShare The modified share object
291
-	 * @throws GenericShareException
292
-	 * @throws \InvalidArgumentException
293
-	 * @throws \Exception
294
-	 */
295
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
296
-
297
-		$expirationDate = $share->getExpirationDate();
298
-
299
-		if ($expirationDate !== null) {
300
-			//Make sure the expiration date is a date
301
-			$expirationDate->setTime(0, 0, 0);
302
-
303
-			$date = new \DateTime();
304
-			$date->setTime(0, 0, 0);
305
-			if ($date >= $expirationDate) {
306
-				$message = $this->l->t('Expiration date is in the past');
307
-				throw new GenericShareException($message, $message, 404);
308
-			}
309
-		}
310
-
311
-		// If expiredate is empty set a default one if there is a default
312
-		$fullId = null;
313
-		try {
314
-			$fullId = $share->getFullId();
315
-		} catch (\UnexpectedValueException $e) {
316
-			// This is a new share
317
-		}
318
-
319
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
320
-			$expirationDate = new \DateTime();
321
-			$expirationDate->setTime(0,0,0);
322
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
323
-		}
324
-
325
-		// If we enforce the expiration date check that is does not exceed
326
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
327
-			if ($expirationDate === null) {
328
-				throw new \InvalidArgumentException('Expiration date is enforced');
329
-			}
330
-
331
-			$date = new \DateTime();
332
-			$date->setTime(0, 0, 0);
333
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
334
-			if ($date < $expirationDate) {
335
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
336
-				throw new GenericShareException($message, $message, 404);
337
-			}
338
-		}
339
-
340
-		$accepted = true;
341
-		$message = '';
342
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
343
-			'expirationDate' => &$expirationDate,
344
-			'accepted' => &$accepted,
345
-			'message' => &$message,
346
-			'passwordSet' => $share->getPassword() !== null,
347
-		]);
348
-
349
-		if (!$accepted) {
350
-			throw new \Exception($message);
351
-		}
352
-
353
-		$share->setExpirationDate($expirationDate);
354
-
355
-		return $share;
356
-	}
357
-
358
-	/**
359
-	 * Check for pre share requirements for user shares
360
-	 *
361
-	 * @param \OCP\Share\IShare $share
362
-	 * @throws \Exception
363
-	 */
364
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
365
-		// Check if we can share with group members only
366
-		if ($this->shareWithGroupMembersOnly()) {
367
-			$sharedBy = $this->userManager->get($share->getSharedBy());
368
-			$sharedWith = $this->userManager->get($share->getSharedWith());
369
-			// Verify we can share with this user
370
-			$groups = array_intersect(
371
-					$this->groupManager->getUserGroupIds($sharedBy),
372
-					$this->groupManager->getUserGroupIds($sharedWith)
373
-			);
374
-			if (empty($groups)) {
375
-				throw new \Exception('Only sharing with group members is allowed');
376
-			}
377
-		}
378
-
379
-		/*
254
+        $permissions = $share->getNode()->getPermissions();
255
+        $mount = $share->getNode()->getMountPoint();
256
+        if (!($mount instanceof MoveableMount)) {
257
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
258
+        }
259
+
260
+        // Check that we do not share with more permissions than we have
261
+        if ($share->getPermissions() & ~$permissions) {
262
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
263
+            throw new GenericShareException($message_t, $message_t, 404);
264
+        }
265
+
266
+
267
+        // Check that read permissions are always set
268
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
269
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
270
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
271
+            throw new \InvalidArgumentException('Shares need at least read permissions');
272
+        }
273
+
274
+        if ($share->getNode() instanceof \OCP\Files\File) {
275
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
276
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
277
+                throw new GenericShareException($message_t);
278
+            }
279
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
280
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
281
+                throw new GenericShareException($message_t);
282
+            }
283
+        }
284
+    }
285
+
286
+    /**
287
+     * Validate if the expiration date fits the system settings
288
+     *
289
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
290
+     * @return \OCP\Share\IShare The modified share object
291
+     * @throws GenericShareException
292
+     * @throws \InvalidArgumentException
293
+     * @throws \Exception
294
+     */
295
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
296
+
297
+        $expirationDate = $share->getExpirationDate();
298
+
299
+        if ($expirationDate !== null) {
300
+            //Make sure the expiration date is a date
301
+            $expirationDate->setTime(0, 0, 0);
302
+
303
+            $date = new \DateTime();
304
+            $date->setTime(0, 0, 0);
305
+            if ($date >= $expirationDate) {
306
+                $message = $this->l->t('Expiration date is in the past');
307
+                throw new GenericShareException($message, $message, 404);
308
+            }
309
+        }
310
+
311
+        // If expiredate is empty set a default one if there is a default
312
+        $fullId = null;
313
+        try {
314
+            $fullId = $share->getFullId();
315
+        } catch (\UnexpectedValueException $e) {
316
+            // This is a new share
317
+        }
318
+
319
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
320
+            $expirationDate = new \DateTime();
321
+            $expirationDate->setTime(0,0,0);
322
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
323
+        }
324
+
325
+        // If we enforce the expiration date check that is does not exceed
326
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
327
+            if ($expirationDate === null) {
328
+                throw new \InvalidArgumentException('Expiration date is enforced');
329
+            }
330
+
331
+            $date = new \DateTime();
332
+            $date->setTime(0, 0, 0);
333
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
334
+            if ($date < $expirationDate) {
335
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
336
+                throw new GenericShareException($message, $message, 404);
337
+            }
338
+        }
339
+
340
+        $accepted = true;
341
+        $message = '';
342
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
343
+            'expirationDate' => &$expirationDate,
344
+            'accepted' => &$accepted,
345
+            'message' => &$message,
346
+            'passwordSet' => $share->getPassword() !== null,
347
+        ]);
348
+
349
+        if (!$accepted) {
350
+            throw new \Exception($message);
351
+        }
352
+
353
+        $share->setExpirationDate($expirationDate);
354
+
355
+        return $share;
356
+    }
357
+
358
+    /**
359
+     * Check for pre share requirements for user shares
360
+     *
361
+     * @param \OCP\Share\IShare $share
362
+     * @throws \Exception
363
+     */
364
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
365
+        // Check if we can share with group members only
366
+        if ($this->shareWithGroupMembersOnly()) {
367
+            $sharedBy = $this->userManager->get($share->getSharedBy());
368
+            $sharedWith = $this->userManager->get($share->getSharedWith());
369
+            // Verify we can share with this user
370
+            $groups = array_intersect(
371
+                    $this->groupManager->getUserGroupIds($sharedBy),
372
+                    $this->groupManager->getUserGroupIds($sharedWith)
373
+            );
374
+            if (empty($groups)) {
375
+                throw new \Exception('Only sharing with group members is allowed');
376
+            }
377
+        }
378
+
379
+        /*
380 380
 		 * TODO: Could be costly, fix
381 381
 		 *
382 382
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
383 383
 		 */
384
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
385
-		$existingShares = $provider->getSharesByPath($share->getNode());
386
-		foreach($existingShares as $existingShare) {
387
-			// Ignore if it is the same share
388
-			try {
389
-				if ($existingShare->getFullId() === $share->getFullId()) {
390
-					continue;
391
-				}
392
-			} catch (\UnexpectedValueException $e) {
393
-				//Shares are not identical
394
-			}
395
-
396
-			// Identical share already existst
397
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
398
-				throw new \Exception('Path already shared with this user');
399
-			}
400
-
401
-			// The share is already shared with this user via a group share
402
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
403
-				$group = $this->groupManager->get($existingShare->getSharedWith());
404
-				if (!is_null($group)) {
405
-					$user = $this->userManager->get($share->getSharedWith());
406
-
407
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
408
-						throw new \Exception('Path already shared with this user');
409
-					}
410
-				}
411
-			}
412
-		}
413
-	}
414
-
415
-	/**
416
-	 * Check for pre share requirements for group shares
417
-	 *
418
-	 * @param \OCP\Share\IShare $share
419
-	 * @throws \Exception
420
-	 */
421
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
422
-		// Verify group shares are allowed
423
-		if (!$this->allowGroupSharing()) {
424
-			throw new \Exception('Group sharing is now allowed');
425
-		}
426
-
427
-		// Verify if the user can share with this group
428
-		if ($this->shareWithGroupMembersOnly()) {
429
-			$sharedBy = $this->userManager->get($share->getSharedBy());
430
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
431
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
432
-				throw new \Exception('Only sharing within your own groups is allowed');
433
-			}
434
-		}
435
-
436
-		/*
384
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
385
+        $existingShares = $provider->getSharesByPath($share->getNode());
386
+        foreach($existingShares as $existingShare) {
387
+            // Ignore if it is the same share
388
+            try {
389
+                if ($existingShare->getFullId() === $share->getFullId()) {
390
+                    continue;
391
+                }
392
+            } catch (\UnexpectedValueException $e) {
393
+                //Shares are not identical
394
+            }
395
+
396
+            // Identical share already existst
397
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
398
+                throw new \Exception('Path already shared with this user');
399
+            }
400
+
401
+            // The share is already shared with this user via a group share
402
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
403
+                $group = $this->groupManager->get($existingShare->getSharedWith());
404
+                if (!is_null($group)) {
405
+                    $user = $this->userManager->get($share->getSharedWith());
406
+
407
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
408
+                        throw new \Exception('Path already shared with this user');
409
+                    }
410
+                }
411
+            }
412
+        }
413
+    }
414
+
415
+    /**
416
+     * Check for pre share requirements for group shares
417
+     *
418
+     * @param \OCP\Share\IShare $share
419
+     * @throws \Exception
420
+     */
421
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
422
+        // Verify group shares are allowed
423
+        if (!$this->allowGroupSharing()) {
424
+            throw new \Exception('Group sharing is now allowed');
425
+        }
426
+
427
+        // Verify if the user can share with this group
428
+        if ($this->shareWithGroupMembersOnly()) {
429
+            $sharedBy = $this->userManager->get($share->getSharedBy());
430
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
431
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
432
+                throw new \Exception('Only sharing within your own groups is allowed');
433
+            }
434
+        }
435
+
436
+        /*
437 437
 		 * TODO: Could be costly, fix
438 438
 		 *
439 439
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
440 440
 		 */
441
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
442
-		$existingShares = $provider->getSharesByPath($share->getNode());
443
-		foreach($existingShares as $existingShare) {
444
-			try {
445
-				if ($existingShare->getFullId() === $share->getFullId()) {
446
-					continue;
447
-				}
448
-			} catch (\UnexpectedValueException $e) {
449
-				//It is a new share so just continue
450
-			}
451
-
452
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
453
-				throw new \Exception('Path already shared with this group');
454
-			}
455
-		}
456
-	}
457
-
458
-	/**
459
-	 * Check for pre share requirements for link shares
460
-	 *
461
-	 * @param \OCP\Share\IShare $share
462
-	 * @throws \Exception
463
-	 */
464
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
465
-		// Are link shares allowed?
466
-		if (!$this->shareApiAllowLinks()) {
467
-			throw new \Exception('Link sharing not allowed');
468
-		}
469
-
470
-		// Link shares by definition can't have share permissions
471
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
472
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
473
-		}
474
-
475
-		// Check if public upload is allowed
476
-		if (!$this->shareApiLinkAllowPublicUpload() &&
477
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
478
-			throw new \InvalidArgumentException('Public upload not allowed');
479
-		}
480
-	}
481
-
482
-	/**
483
-	 * To make sure we don't get invisible link shares we set the parent
484
-	 * of a link if it is a reshare. This is a quick word around
485
-	 * until we can properly display multiple link shares in the UI
486
-	 *
487
-	 * See: https://github.com/owncloud/core/issues/22295
488
-	 *
489
-	 * FIXME: Remove once multiple link shares can be properly displayed
490
-	 *
491
-	 * @param \OCP\Share\IShare $share
492
-	 */
493
-	protected function setLinkParent(\OCP\Share\IShare $share) {
494
-
495
-		// No sense in checking if the method is not there.
496
-		if (method_exists($share, 'setParent')) {
497
-			$storage = $share->getNode()->getStorage();
498
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
499
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
500
-				$share->setParent($storage->getShareId());
501
-			}
502
-		};
503
-	}
504
-
505
-	/**
506
-	 * @param File|Folder $path
507
-	 */
508
-	protected function pathCreateChecks($path) {
509
-		// Make sure that we do not share a path that contains a shared mountpoint
510
-		if ($path instanceof \OCP\Files\Folder) {
511
-			$mounts = $this->mountManager->findIn($path->getPath());
512
-			foreach($mounts as $mount) {
513
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
514
-					throw new \InvalidArgumentException('Path contains files shared with you');
515
-				}
516
-			}
517
-		}
518
-	}
519
-
520
-	/**
521
-	 * Check if the user that is sharing can actually share
522
-	 *
523
-	 * @param \OCP\Share\IShare $share
524
-	 * @throws \Exception
525
-	 */
526
-	protected function canShare(\OCP\Share\IShare $share) {
527
-		if (!$this->shareApiEnabled()) {
528
-			throw new \Exception('The share API is disabled');
529
-		}
530
-
531
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
532
-			throw new \Exception('You are not allowed to share');
533
-		}
534
-	}
535
-
536
-	/**
537
-	 * Share a path
538
-	 *
539
-	 * @param \OCP\Share\IShare $share
540
-	 * @return Share The share object
541
-	 * @throws \Exception
542
-	 *
543
-	 * TODO: handle link share permissions or check them
544
-	 */
545
-	public function createShare(\OCP\Share\IShare $share) {
546
-		$this->canShare($share);
547
-
548
-		$this->generalCreateChecks($share);
549
-
550
-		// Verify if there are any issues with the path
551
-		$this->pathCreateChecks($share->getNode());
552
-
553
-		/*
441
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
442
+        $existingShares = $provider->getSharesByPath($share->getNode());
443
+        foreach($existingShares as $existingShare) {
444
+            try {
445
+                if ($existingShare->getFullId() === $share->getFullId()) {
446
+                    continue;
447
+                }
448
+            } catch (\UnexpectedValueException $e) {
449
+                //It is a new share so just continue
450
+            }
451
+
452
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
453
+                throw new \Exception('Path already shared with this group');
454
+            }
455
+        }
456
+    }
457
+
458
+    /**
459
+     * Check for pre share requirements for link shares
460
+     *
461
+     * @param \OCP\Share\IShare $share
462
+     * @throws \Exception
463
+     */
464
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
465
+        // Are link shares allowed?
466
+        if (!$this->shareApiAllowLinks()) {
467
+            throw new \Exception('Link sharing not allowed');
468
+        }
469
+
470
+        // Link shares by definition can't have share permissions
471
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
472
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
473
+        }
474
+
475
+        // Check if public upload is allowed
476
+        if (!$this->shareApiLinkAllowPublicUpload() &&
477
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
478
+            throw new \InvalidArgumentException('Public upload not allowed');
479
+        }
480
+    }
481
+
482
+    /**
483
+     * To make sure we don't get invisible link shares we set the parent
484
+     * of a link if it is a reshare. This is a quick word around
485
+     * until we can properly display multiple link shares in the UI
486
+     *
487
+     * See: https://github.com/owncloud/core/issues/22295
488
+     *
489
+     * FIXME: Remove once multiple link shares can be properly displayed
490
+     *
491
+     * @param \OCP\Share\IShare $share
492
+     */
493
+    protected function setLinkParent(\OCP\Share\IShare $share) {
494
+
495
+        // No sense in checking if the method is not there.
496
+        if (method_exists($share, 'setParent')) {
497
+            $storage = $share->getNode()->getStorage();
498
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
499
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
500
+                $share->setParent($storage->getShareId());
501
+            }
502
+        };
503
+    }
504
+
505
+    /**
506
+     * @param File|Folder $path
507
+     */
508
+    protected function pathCreateChecks($path) {
509
+        // Make sure that we do not share a path that contains a shared mountpoint
510
+        if ($path instanceof \OCP\Files\Folder) {
511
+            $mounts = $this->mountManager->findIn($path->getPath());
512
+            foreach($mounts as $mount) {
513
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
514
+                    throw new \InvalidArgumentException('Path contains files shared with you');
515
+                }
516
+            }
517
+        }
518
+    }
519
+
520
+    /**
521
+     * Check if the user that is sharing can actually share
522
+     *
523
+     * @param \OCP\Share\IShare $share
524
+     * @throws \Exception
525
+     */
526
+    protected function canShare(\OCP\Share\IShare $share) {
527
+        if (!$this->shareApiEnabled()) {
528
+            throw new \Exception('The share API is disabled');
529
+        }
530
+
531
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
532
+            throw new \Exception('You are not allowed to share');
533
+        }
534
+    }
535
+
536
+    /**
537
+     * Share a path
538
+     *
539
+     * @param \OCP\Share\IShare $share
540
+     * @return Share The share object
541
+     * @throws \Exception
542
+     *
543
+     * TODO: handle link share permissions or check them
544
+     */
545
+    public function createShare(\OCP\Share\IShare $share) {
546
+        $this->canShare($share);
547
+
548
+        $this->generalCreateChecks($share);
549
+
550
+        // Verify if there are any issues with the path
551
+        $this->pathCreateChecks($share->getNode());
552
+
553
+        /*
554 554
 		 * On creation of a share the owner is always the owner of the path
555 555
 		 * Except for mounted federated shares.
556 556
 		 */
557
-		$storage = $share->getNode()->getStorage();
558
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
559
-			$parent = $share->getNode()->getParent();
560
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
561
-				$parent = $parent->getParent();
562
-			}
563
-			$share->setShareOwner($parent->getOwner()->getUID());
564
-		} else {
565
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
566
-		}
567
-
568
-		//Verify share type
569
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
570
-			$this->userCreateChecks($share);
571
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
572
-			$this->groupCreateChecks($share);
573
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
574
-			$this->linkCreateChecks($share);
575
-			$this->setLinkParent($share);
576
-
577
-			/*
557
+        $storage = $share->getNode()->getStorage();
558
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
559
+            $parent = $share->getNode()->getParent();
560
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
561
+                $parent = $parent->getParent();
562
+            }
563
+            $share->setShareOwner($parent->getOwner()->getUID());
564
+        } else {
565
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
566
+        }
567
+
568
+        //Verify share type
569
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
570
+            $this->userCreateChecks($share);
571
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
572
+            $this->groupCreateChecks($share);
573
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
574
+            $this->linkCreateChecks($share);
575
+            $this->setLinkParent($share);
576
+
577
+            /*
578 578
 			 * For now ignore a set token.
579 579
 			 */
580
-			$share->setToken(
581
-				$this->secureRandom->generate(
582
-					\OC\Share\Constants::TOKEN_LENGTH,
583
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
584
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
585
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
586
-				)
587
-			);
588
-
589
-			//Verify the expiration date
590
-			$this->validateExpirationDate($share);
591
-
592
-			//Verify the password
593
-			$this->verifyPassword($share->getPassword());
594
-
595
-			// If a password is set. Hash it!
596
-			if ($share->getPassword() !== null) {
597
-				$share->setPassword($this->hasher->hash($share->getPassword()));
598
-			}
599
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
600
-			$share->setToken(
601
-				$this->secureRandom->generate(
602
-					\OC\Share\Constants::TOKEN_LENGTH,
603
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
604
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
605
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
606
-				)
607
-			);
608
-		}
609
-
610
-		// Cannot share with the owner
611
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
612
-			$share->getSharedWith() === $share->getShareOwner()) {
613
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
614
-		}
615
-
616
-		// Generate the target
617
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
618
-		$target = \OC\Files\Filesystem::normalizePath($target);
619
-		$share->setTarget($target);
620
-
621
-		// Pre share hook
622
-		$run = true;
623
-		$error = '';
624
-		$preHookData = [
625
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
626
-			'itemSource' => $share->getNode()->getId(),
627
-			'shareType' => $share->getShareType(),
628
-			'uidOwner' => $share->getSharedBy(),
629
-			'permissions' => $share->getPermissions(),
630
-			'fileSource' => $share->getNode()->getId(),
631
-			'expiration' => $share->getExpirationDate(),
632
-			'token' => $share->getToken(),
633
-			'itemTarget' => $share->getTarget(),
634
-			'shareWith' => $share->getSharedWith(),
635
-			'run' => &$run,
636
-			'error' => &$error,
637
-		];
638
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
639
-
640
-		if ($run === false) {
641
-			throw new \Exception($error);
642
-		}
643
-
644
-		$oldShare = $share;
645
-		$provider = $this->factory->getProviderForType($share->getShareType());
646
-		$share = $provider->create($share);
647
-		//reuse the node we already have
648
-		$share->setNode($oldShare->getNode());
649
-
650
-		// Post share hook
651
-		$postHookData = [
652
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
653
-			'itemSource' => $share->getNode()->getId(),
654
-			'shareType' => $share->getShareType(),
655
-			'uidOwner' => $share->getSharedBy(),
656
-			'permissions' => $share->getPermissions(),
657
-			'fileSource' => $share->getNode()->getId(),
658
-			'expiration' => $share->getExpirationDate(),
659
-			'token' => $share->getToken(),
660
-			'id' => $share->getId(),
661
-			'shareWith' => $share->getSharedWith(),
662
-			'itemTarget' => $share->getTarget(),
663
-			'fileTarget' => $share->getTarget(),
664
-		];
665
-
666
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
667
-
668
-		return $share;
669
-	}
670
-
671
-	/**
672
-	 * Update a share
673
-	 *
674
-	 * @param \OCP\Share\IShare $share
675
-	 * @return \OCP\Share\IShare The share object
676
-	 * @throws \InvalidArgumentException
677
-	 */
678
-	public function updateShare(\OCP\Share\IShare $share) {
679
-		$expirationDateUpdated = false;
680
-
681
-		$this->canShare($share);
682
-
683
-		try {
684
-			$originalShare = $this->getShareById($share->getFullId());
685
-		} catch (\UnexpectedValueException $e) {
686
-			throw new \InvalidArgumentException('Share does not have a full id');
687
-		}
688
-
689
-		// We can't change the share type!
690
-		if ($share->getShareType() !== $originalShare->getShareType()) {
691
-			throw new \InvalidArgumentException('Can\'t change share type');
692
-		}
693
-
694
-		// We can only change the recipient on user shares
695
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
696
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
697
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
698
-		}
699
-
700
-		// Cannot share with the owner
701
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
702
-			$share->getSharedWith() === $share->getShareOwner()) {
703
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
704
-		}
705
-
706
-		$this->generalCreateChecks($share);
707
-
708
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
709
-			$this->userCreateChecks($share);
710
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
711
-			$this->groupCreateChecks($share);
712
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
713
-			$this->linkCreateChecks($share);
714
-
715
-			// Password updated.
716
-			if ($share->getPassword() !== $originalShare->getPassword()) {
717
-				//Verify the password
718
-				$this->verifyPassword($share->getPassword());
719
-
720
-				// If a password is set. Hash it!
721
-				if ($share->getPassword() !== null) {
722
-					$share->setPassword($this->hasher->hash($share->getPassword()));
723
-				}
724
-			}
725
-
726
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
727
-				//Verify the expiration date
728
-				$this->validateExpirationDate($share);
729
-				$expirationDateUpdated = true;
730
-			}
731
-		}
732
-
733
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
734
-			// Password updated.
735
-			if ($share->getPassword() !== $originalShare->getPassword()) {
736
-				//Verify the password
737
-				$this->verifyPassword($share->getPassword());
738
-
739
-				// If a password is set. Hash it!
740
-				if ($share->getPassword() !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
741
-					$share->setPassword($this->hasher->hash($share->getPassword()));
742
-				}
743
-			}
744
-		}
745
-
746
-		$this->pathCreateChecks($share->getNode());
747
-
748
-		// Now update the share!
749
-		$provider = $this->factory->getProviderForType($share->getShareType());
750
-		$share = $provider->update($share);
751
-
752
-		if ($expirationDateUpdated === true) {
753
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
754
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
755
-				'itemSource' => $share->getNode()->getId(),
756
-				'date' => $share->getExpirationDate(),
757
-				'uidOwner' => $share->getSharedBy(),
758
-			]);
759
-		}
760
-
761
-		if ($share->getPassword() !== $originalShare->getPassword()) {
762
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
763
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
764
-				'itemSource' => $share->getNode()->getId(),
765
-				'uidOwner' => $share->getSharedBy(),
766
-				'token' => $share->getToken(),
767
-				'disabled' => is_null($share->getPassword()),
768
-			]);
769
-		}
770
-
771
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
772
-			if ($this->userManager->userExists($share->getShareOwner())) {
773
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
774
-			} else {
775
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
776
-			}
777
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
778
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
779
-				'itemSource' => $share->getNode()->getId(),
780
-				'shareType' => $share->getShareType(),
781
-				'shareWith' => $share->getSharedWith(),
782
-				'uidOwner' => $share->getSharedBy(),
783
-				'permissions' => $share->getPermissions(),
784
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
785
-			));
786
-		}
787
-
788
-		return $share;
789
-	}
790
-
791
-	/**
792
-	 * Delete all the children of this share
793
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
794
-	 *
795
-	 * @param \OCP\Share\IShare $share
796
-	 * @return \OCP\Share\IShare[] List of deleted shares
797
-	 */
798
-	protected function deleteChildren(\OCP\Share\IShare $share) {
799
-		$deletedShares = [];
800
-
801
-		$provider = $this->factory->getProviderForType($share->getShareType());
802
-
803
-		foreach ($provider->getChildren($share) as $child) {
804
-			$deletedChildren = $this->deleteChildren($child);
805
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
806
-
807
-			$provider->delete($child);
808
-			$deletedShares[] = $child;
809
-		}
810
-
811
-		return $deletedShares;
812
-	}
813
-
814
-	/**
815
-	 * Delete a share
816
-	 *
817
-	 * @param \OCP\Share\IShare $share
818
-	 * @throws ShareNotFound
819
-	 * @throws \InvalidArgumentException
820
-	 */
821
-	public function deleteShare(\OCP\Share\IShare $share) {
822
-
823
-		try {
824
-			$share->getFullId();
825
-		} catch (\UnexpectedValueException $e) {
826
-			throw new \InvalidArgumentException('Share does not have a full id');
827
-		}
828
-
829
-		$event = new GenericEvent($share);
830
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
831
-
832
-		// Get all children and delete them as well
833
-		$deletedShares = $this->deleteChildren($share);
834
-
835
-		// Do the actual delete
836
-		$provider = $this->factory->getProviderForType($share->getShareType());
837
-		$provider->delete($share);
838
-
839
-		// All the deleted shares caused by this delete
840
-		$deletedShares[] = $share;
841
-
842
-		// Emit post hook
843
-		$event->setArgument('deletedShares', $deletedShares);
844
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
845
-	}
846
-
847
-
848
-	/**
849
-	 * Unshare a file as the recipient.
850
-	 * This can be different from a regular delete for example when one of
851
-	 * the users in a groups deletes that share. But the provider should
852
-	 * handle this.
853
-	 *
854
-	 * @param \OCP\Share\IShare $share
855
-	 * @param string $recipientId
856
-	 */
857
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
858
-		list($providerId, ) = $this->splitFullId($share->getFullId());
859
-		$provider = $this->factory->getProvider($providerId);
860
-
861
-		$provider->deleteFromSelf($share, $recipientId);
862
-	}
863
-
864
-	/**
865
-	 * @inheritdoc
866
-	 */
867
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
868
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
869
-			throw new \InvalidArgumentException('Can\'t change target of link share');
870
-		}
871
-
872
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
873
-			throw new \InvalidArgumentException('Invalid recipient');
874
-		}
875
-
876
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
877
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
878
-			if (is_null($sharedWith)) {
879
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
880
-			}
881
-			$recipient = $this->userManager->get($recipientId);
882
-			if (!$sharedWith->inGroup($recipient)) {
883
-				throw new \InvalidArgumentException('Invalid recipient');
884
-			}
885
-		}
886
-
887
-		list($providerId, ) = $this->splitFullId($share->getFullId());
888
-		$provider = $this->factory->getProvider($providerId);
889
-
890
-		$provider->move($share, $recipientId);
891
-	}
892
-
893
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
894
-		$providers = $this->factory->getAllProviders();
895
-
896
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
897
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
898
-			foreach ($newShares as $fid => $data) {
899
-				if (!isset($shares[$fid])) {
900
-					$shares[$fid] = [];
901
-				}
902
-
903
-				$shares[$fid] = array_merge($shares[$fid], $data);
904
-			}
905
-			return $shares;
906
-		}, []);
907
-	}
908
-
909
-	/**
910
-	 * @inheritdoc
911
-	 */
912
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
913
-		if ($path !== null &&
914
-				!($path instanceof \OCP\Files\File) &&
915
-				!($path instanceof \OCP\Files\Folder)) {
916
-			throw new \InvalidArgumentException('invalid path');
917
-		}
918
-
919
-		try {
920
-			$provider = $this->factory->getProviderForType($shareType);
921
-		} catch (ProviderException $e) {
922
-			return [];
923
-		}
924
-
925
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
926
-
927
-		/*
580
+            $share->setToken(
581
+                $this->secureRandom->generate(
582
+                    \OC\Share\Constants::TOKEN_LENGTH,
583
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
584
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
585
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
586
+                )
587
+            );
588
+
589
+            //Verify the expiration date
590
+            $this->validateExpirationDate($share);
591
+
592
+            //Verify the password
593
+            $this->verifyPassword($share->getPassword());
594
+
595
+            // If a password is set. Hash it!
596
+            if ($share->getPassword() !== null) {
597
+                $share->setPassword($this->hasher->hash($share->getPassword()));
598
+            }
599
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
600
+            $share->setToken(
601
+                $this->secureRandom->generate(
602
+                    \OC\Share\Constants::TOKEN_LENGTH,
603
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
604
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
605
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
606
+                )
607
+            );
608
+        }
609
+
610
+        // Cannot share with the owner
611
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
612
+            $share->getSharedWith() === $share->getShareOwner()) {
613
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
614
+        }
615
+
616
+        // Generate the target
617
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
618
+        $target = \OC\Files\Filesystem::normalizePath($target);
619
+        $share->setTarget($target);
620
+
621
+        // Pre share hook
622
+        $run = true;
623
+        $error = '';
624
+        $preHookData = [
625
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
626
+            'itemSource' => $share->getNode()->getId(),
627
+            'shareType' => $share->getShareType(),
628
+            'uidOwner' => $share->getSharedBy(),
629
+            'permissions' => $share->getPermissions(),
630
+            'fileSource' => $share->getNode()->getId(),
631
+            'expiration' => $share->getExpirationDate(),
632
+            'token' => $share->getToken(),
633
+            'itemTarget' => $share->getTarget(),
634
+            'shareWith' => $share->getSharedWith(),
635
+            'run' => &$run,
636
+            'error' => &$error,
637
+        ];
638
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
639
+
640
+        if ($run === false) {
641
+            throw new \Exception($error);
642
+        }
643
+
644
+        $oldShare = $share;
645
+        $provider = $this->factory->getProviderForType($share->getShareType());
646
+        $share = $provider->create($share);
647
+        //reuse the node we already have
648
+        $share->setNode($oldShare->getNode());
649
+
650
+        // Post share hook
651
+        $postHookData = [
652
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
653
+            'itemSource' => $share->getNode()->getId(),
654
+            'shareType' => $share->getShareType(),
655
+            'uidOwner' => $share->getSharedBy(),
656
+            'permissions' => $share->getPermissions(),
657
+            'fileSource' => $share->getNode()->getId(),
658
+            'expiration' => $share->getExpirationDate(),
659
+            'token' => $share->getToken(),
660
+            'id' => $share->getId(),
661
+            'shareWith' => $share->getSharedWith(),
662
+            'itemTarget' => $share->getTarget(),
663
+            'fileTarget' => $share->getTarget(),
664
+        ];
665
+
666
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
667
+
668
+        return $share;
669
+    }
670
+
671
+    /**
672
+     * Update a share
673
+     *
674
+     * @param \OCP\Share\IShare $share
675
+     * @return \OCP\Share\IShare The share object
676
+     * @throws \InvalidArgumentException
677
+     */
678
+    public function updateShare(\OCP\Share\IShare $share) {
679
+        $expirationDateUpdated = false;
680
+
681
+        $this->canShare($share);
682
+
683
+        try {
684
+            $originalShare = $this->getShareById($share->getFullId());
685
+        } catch (\UnexpectedValueException $e) {
686
+            throw new \InvalidArgumentException('Share does not have a full id');
687
+        }
688
+
689
+        // We can't change the share type!
690
+        if ($share->getShareType() !== $originalShare->getShareType()) {
691
+            throw new \InvalidArgumentException('Can\'t change share type');
692
+        }
693
+
694
+        // We can only change the recipient on user shares
695
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
696
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
697
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
698
+        }
699
+
700
+        // Cannot share with the owner
701
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
702
+            $share->getSharedWith() === $share->getShareOwner()) {
703
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
704
+        }
705
+
706
+        $this->generalCreateChecks($share);
707
+
708
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
709
+            $this->userCreateChecks($share);
710
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
711
+            $this->groupCreateChecks($share);
712
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
713
+            $this->linkCreateChecks($share);
714
+
715
+            // Password updated.
716
+            if ($share->getPassword() !== $originalShare->getPassword()) {
717
+                //Verify the password
718
+                $this->verifyPassword($share->getPassword());
719
+
720
+                // If a password is set. Hash it!
721
+                if ($share->getPassword() !== null) {
722
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
723
+                }
724
+            }
725
+
726
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
727
+                //Verify the expiration date
728
+                $this->validateExpirationDate($share);
729
+                $expirationDateUpdated = true;
730
+            }
731
+        }
732
+
733
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
734
+            // Password updated.
735
+            if ($share->getPassword() !== $originalShare->getPassword()) {
736
+                //Verify the password
737
+                $this->verifyPassword($share->getPassword());
738
+
739
+                // If a password is set. Hash it!
740
+                if ($share->getPassword() !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
741
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
742
+                }
743
+            }
744
+        }
745
+
746
+        $this->pathCreateChecks($share->getNode());
747
+
748
+        // Now update the share!
749
+        $provider = $this->factory->getProviderForType($share->getShareType());
750
+        $share = $provider->update($share);
751
+
752
+        if ($expirationDateUpdated === true) {
753
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
754
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
755
+                'itemSource' => $share->getNode()->getId(),
756
+                'date' => $share->getExpirationDate(),
757
+                'uidOwner' => $share->getSharedBy(),
758
+            ]);
759
+        }
760
+
761
+        if ($share->getPassword() !== $originalShare->getPassword()) {
762
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
763
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
764
+                'itemSource' => $share->getNode()->getId(),
765
+                'uidOwner' => $share->getSharedBy(),
766
+                'token' => $share->getToken(),
767
+                'disabled' => is_null($share->getPassword()),
768
+            ]);
769
+        }
770
+
771
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
772
+            if ($this->userManager->userExists($share->getShareOwner())) {
773
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
774
+            } else {
775
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
776
+            }
777
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
778
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
779
+                'itemSource' => $share->getNode()->getId(),
780
+                'shareType' => $share->getShareType(),
781
+                'shareWith' => $share->getSharedWith(),
782
+                'uidOwner' => $share->getSharedBy(),
783
+                'permissions' => $share->getPermissions(),
784
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
785
+            ));
786
+        }
787
+
788
+        return $share;
789
+    }
790
+
791
+    /**
792
+     * Delete all the children of this share
793
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
794
+     *
795
+     * @param \OCP\Share\IShare $share
796
+     * @return \OCP\Share\IShare[] List of deleted shares
797
+     */
798
+    protected function deleteChildren(\OCP\Share\IShare $share) {
799
+        $deletedShares = [];
800
+
801
+        $provider = $this->factory->getProviderForType($share->getShareType());
802
+
803
+        foreach ($provider->getChildren($share) as $child) {
804
+            $deletedChildren = $this->deleteChildren($child);
805
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
806
+
807
+            $provider->delete($child);
808
+            $deletedShares[] = $child;
809
+        }
810
+
811
+        return $deletedShares;
812
+    }
813
+
814
+    /**
815
+     * Delete a share
816
+     *
817
+     * @param \OCP\Share\IShare $share
818
+     * @throws ShareNotFound
819
+     * @throws \InvalidArgumentException
820
+     */
821
+    public function deleteShare(\OCP\Share\IShare $share) {
822
+
823
+        try {
824
+            $share->getFullId();
825
+        } catch (\UnexpectedValueException $e) {
826
+            throw new \InvalidArgumentException('Share does not have a full id');
827
+        }
828
+
829
+        $event = new GenericEvent($share);
830
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
831
+
832
+        // Get all children and delete them as well
833
+        $deletedShares = $this->deleteChildren($share);
834
+
835
+        // Do the actual delete
836
+        $provider = $this->factory->getProviderForType($share->getShareType());
837
+        $provider->delete($share);
838
+
839
+        // All the deleted shares caused by this delete
840
+        $deletedShares[] = $share;
841
+
842
+        // Emit post hook
843
+        $event->setArgument('deletedShares', $deletedShares);
844
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
845
+    }
846
+
847
+
848
+    /**
849
+     * Unshare a file as the recipient.
850
+     * This can be different from a regular delete for example when one of
851
+     * the users in a groups deletes that share. But the provider should
852
+     * handle this.
853
+     *
854
+     * @param \OCP\Share\IShare $share
855
+     * @param string $recipientId
856
+     */
857
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
858
+        list($providerId, ) = $this->splitFullId($share->getFullId());
859
+        $provider = $this->factory->getProvider($providerId);
860
+
861
+        $provider->deleteFromSelf($share, $recipientId);
862
+    }
863
+
864
+    /**
865
+     * @inheritdoc
866
+     */
867
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
868
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
869
+            throw new \InvalidArgumentException('Can\'t change target of link share');
870
+        }
871
+
872
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
873
+            throw new \InvalidArgumentException('Invalid recipient');
874
+        }
875
+
876
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
877
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
878
+            if (is_null($sharedWith)) {
879
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
880
+            }
881
+            $recipient = $this->userManager->get($recipientId);
882
+            if (!$sharedWith->inGroup($recipient)) {
883
+                throw new \InvalidArgumentException('Invalid recipient');
884
+            }
885
+        }
886
+
887
+        list($providerId, ) = $this->splitFullId($share->getFullId());
888
+        $provider = $this->factory->getProvider($providerId);
889
+
890
+        $provider->move($share, $recipientId);
891
+    }
892
+
893
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
894
+        $providers = $this->factory->getAllProviders();
895
+
896
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
897
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
898
+            foreach ($newShares as $fid => $data) {
899
+                if (!isset($shares[$fid])) {
900
+                    $shares[$fid] = [];
901
+                }
902
+
903
+                $shares[$fid] = array_merge($shares[$fid], $data);
904
+            }
905
+            return $shares;
906
+        }, []);
907
+    }
908
+
909
+    /**
910
+     * @inheritdoc
911
+     */
912
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
913
+        if ($path !== null &&
914
+                !($path instanceof \OCP\Files\File) &&
915
+                !($path instanceof \OCP\Files\Folder)) {
916
+            throw new \InvalidArgumentException('invalid path');
917
+        }
918
+
919
+        try {
920
+            $provider = $this->factory->getProviderForType($shareType);
921
+        } catch (ProviderException $e) {
922
+            return [];
923
+        }
924
+
925
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
926
+
927
+        /*
928 928
 		 * Work around so we don't return expired shares but still follow
929 929
 		 * proper pagination.
930 930
 		 */
931
-		if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
932
-			$shares2 = [];
933
-			$today = new \DateTime();
934
-
935
-			while(true) {
936
-				$added = 0;
937
-				foreach ($shares as $share) {
938
-					// Check if the share is expired and if so delete it
939
-					if ($share->getExpirationDate() !== null &&
940
-						$share->getExpirationDate() <= $today
941
-					) {
942
-						try {
943
-							$this->deleteShare($share);
944
-						} catch (NotFoundException $e) {
945
-							//Ignore since this basically means the share is deleted
946
-						}
947
-						continue;
948
-					}
949
-					$added++;
950
-					$shares2[] = $share;
951
-
952
-					if (count($shares2) === $limit) {
953
-						break;
954
-					}
955
-				}
956
-
957
-				if (count($shares2) === $limit) {
958
-					break;
959
-				}
960
-
961
-				// If there was no limit on the select we are done
962
-				if ($limit === -1) {
963
-					break;
964
-				}
965
-
966
-				$offset += $added;
967
-
968
-				// Fetch again $limit shares
969
-				$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
970
-
971
-				// No more shares means we are done
972
-				if (empty($shares)) {
973
-					break;
974
-				}
975
-			}
976
-
977
-			$shares = $shares2;
978
-		}
979
-
980
-		return $shares;
981
-	}
982
-
983
-	/**
984
-	 * @inheritdoc
985
-	 */
986
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
987
-		try {
988
-			$provider = $this->factory->getProviderForType($shareType);
989
-		} catch (ProviderException $e) {
990
-			return [];
991
-		}
992
-
993
-		return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
994
-	}
995
-
996
-	/**
997
-	 * @inheritdoc
998
-	 */
999
-	public function getShareById($id, $recipient = null) {
1000
-		if ($id === null) {
1001
-			throw new ShareNotFound();
1002
-		}
1003
-
1004
-		list($providerId, $id) = $this->splitFullId($id);
1005
-
1006
-		try {
1007
-			$provider = $this->factory->getProvider($providerId);
1008
-		} catch (ProviderException $e) {
1009
-			throw new ShareNotFound();
1010
-		}
1011
-
1012
-		$share = $provider->getShareById($id, $recipient);
1013
-
1014
-		// Validate link shares expiration date
1015
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1016
-			$share->getExpirationDate() !== null &&
1017
-			$share->getExpirationDate() <= new \DateTime()) {
1018
-			$this->deleteShare($share);
1019
-			throw new ShareNotFound();
1020
-		}
1021
-
1022
-		return $share;
1023
-	}
1024
-
1025
-	/**
1026
-	 * Get all the shares for a given path
1027
-	 *
1028
-	 * @param \OCP\Files\Node $path
1029
-	 * @param int $page
1030
-	 * @param int $perPage
1031
-	 *
1032
-	 * @return Share[]
1033
-	 */
1034
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1035
-		return [];
1036
-	}
1037
-
1038
-	/**
1039
-	 * Get the share by token possible with password
1040
-	 *
1041
-	 * @param string $token
1042
-	 * @return Share
1043
-	 *
1044
-	 * @throws ShareNotFound
1045
-	 */
1046
-	public function getShareByToken($token) {
1047
-		$share = null;
1048
-		try {
1049
-			if($this->shareApiAllowLinks()) {
1050
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1051
-				$share = $provider->getShareByToken($token);
1052
-			}
1053
-		} catch (ProviderException $e) {
1054
-		} catch (ShareNotFound $e) {
1055
-		}
1056
-
1057
-
1058
-		// If it is not a link share try to fetch a federated share by token
1059
-		if ($share === null) {
1060
-			try {
1061
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1062
-				$share = $provider->getShareByToken($token);
1063
-			} catch (ProviderException $e) {
1064
-			} catch (ShareNotFound $e) {
1065
-			}
1066
-		}
1067
-
1068
-		// If it is not a link share try to fetch a mail share by token
1069
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1070
-			try {
1071
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1072
-				$share = $provider->getShareByToken($token);
1073
-			} catch (ProviderException $e) {
1074
-			} catch (ShareNotFound $e) {
1075
-			}
1076
-		}
1077
-
1078
-		if ($share === null) {
1079
-			throw new ShareNotFound();
1080
-		}
1081
-
1082
-		if ($share->getExpirationDate() !== null &&
1083
-			$share->getExpirationDate() <= new \DateTime()) {
1084
-			$this->deleteShare($share);
1085
-			throw new ShareNotFound();
1086
-		}
1087
-
1088
-		/*
931
+        if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
932
+            $shares2 = [];
933
+            $today = new \DateTime();
934
+
935
+            while(true) {
936
+                $added = 0;
937
+                foreach ($shares as $share) {
938
+                    // Check if the share is expired and if so delete it
939
+                    if ($share->getExpirationDate() !== null &&
940
+                        $share->getExpirationDate() <= $today
941
+                    ) {
942
+                        try {
943
+                            $this->deleteShare($share);
944
+                        } catch (NotFoundException $e) {
945
+                            //Ignore since this basically means the share is deleted
946
+                        }
947
+                        continue;
948
+                    }
949
+                    $added++;
950
+                    $shares2[] = $share;
951
+
952
+                    if (count($shares2) === $limit) {
953
+                        break;
954
+                    }
955
+                }
956
+
957
+                if (count($shares2) === $limit) {
958
+                    break;
959
+                }
960
+
961
+                // If there was no limit on the select we are done
962
+                if ($limit === -1) {
963
+                    break;
964
+                }
965
+
966
+                $offset += $added;
967
+
968
+                // Fetch again $limit shares
969
+                $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
970
+
971
+                // No more shares means we are done
972
+                if (empty($shares)) {
973
+                    break;
974
+                }
975
+            }
976
+
977
+            $shares = $shares2;
978
+        }
979
+
980
+        return $shares;
981
+    }
982
+
983
+    /**
984
+     * @inheritdoc
985
+     */
986
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
987
+        try {
988
+            $provider = $this->factory->getProviderForType($shareType);
989
+        } catch (ProviderException $e) {
990
+            return [];
991
+        }
992
+
993
+        return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
994
+    }
995
+
996
+    /**
997
+     * @inheritdoc
998
+     */
999
+    public function getShareById($id, $recipient = null) {
1000
+        if ($id === null) {
1001
+            throw new ShareNotFound();
1002
+        }
1003
+
1004
+        list($providerId, $id) = $this->splitFullId($id);
1005
+
1006
+        try {
1007
+            $provider = $this->factory->getProvider($providerId);
1008
+        } catch (ProviderException $e) {
1009
+            throw new ShareNotFound();
1010
+        }
1011
+
1012
+        $share = $provider->getShareById($id, $recipient);
1013
+
1014
+        // Validate link shares expiration date
1015
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1016
+            $share->getExpirationDate() !== null &&
1017
+            $share->getExpirationDate() <= new \DateTime()) {
1018
+            $this->deleteShare($share);
1019
+            throw new ShareNotFound();
1020
+        }
1021
+
1022
+        return $share;
1023
+    }
1024
+
1025
+    /**
1026
+     * Get all the shares for a given path
1027
+     *
1028
+     * @param \OCP\Files\Node $path
1029
+     * @param int $page
1030
+     * @param int $perPage
1031
+     *
1032
+     * @return Share[]
1033
+     */
1034
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1035
+        return [];
1036
+    }
1037
+
1038
+    /**
1039
+     * Get the share by token possible with password
1040
+     *
1041
+     * @param string $token
1042
+     * @return Share
1043
+     *
1044
+     * @throws ShareNotFound
1045
+     */
1046
+    public function getShareByToken($token) {
1047
+        $share = null;
1048
+        try {
1049
+            if($this->shareApiAllowLinks()) {
1050
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1051
+                $share = $provider->getShareByToken($token);
1052
+            }
1053
+        } catch (ProviderException $e) {
1054
+        } catch (ShareNotFound $e) {
1055
+        }
1056
+
1057
+
1058
+        // If it is not a link share try to fetch a federated share by token
1059
+        if ($share === null) {
1060
+            try {
1061
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1062
+                $share = $provider->getShareByToken($token);
1063
+            } catch (ProviderException $e) {
1064
+            } catch (ShareNotFound $e) {
1065
+            }
1066
+        }
1067
+
1068
+        // If it is not a link share try to fetch a mail share by token
1069
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1070
+            try {
1071
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1072
+                $share = $provider->getShareByToken($token);
1073
+            } catch (ProviderException $e) {
1074
+            } catch (ShareNotFound $e) {
1075
+            }
1076
+        }
1077
+
1078
+        if ($share === null) {
1079
+            throw new ShareNotFound();
1080
+        }
1081
+
1082
+        if ($share->getExpirationDate() !== null &&
1083
+            $share->getExpirationDate() <= new \DateTime()) {
1084
+            $this->deleteShare($share);
1085
+            throw new ShareNotFound();
1086
+        }
1087
+
1088
+        /*
1089 1089
 		 * Reduce the permissions for link shares if public upload is not enabled
1090 1090
 		 */
1091
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1092
-			!$this->shareApiLinkAllowPublicUpload()) {
1093
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1094
-		}
1095
-
1096
-		return $share;
1097
-	}
1098
-
1099
-	/**
1100
-	 * Verify the password of a public share
1101
-	 *
1102
-	 * @param \OCP\Share\IShare $share
1103
-	 * @param string $password
1104
-	 * @return bool
1105
-	 */
1106
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1107
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
1108
-			//TODO maybe exception?
1109
-			return false;
1110
-		}
1111
-
1112
-		if ($password === null || $share->getPassword() === null) {
1113
-			return false;
1114
-		}
1115
-
1116
-		$newHash = '';
1117
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1118
-			return false;
1119
-		}
1120
-
1121
-		if (!empty($newHash)) {
1122
-			$share->setPassword($newHash);
1123
-			$provider = $this->factory->getProviderForType($share->getShareType());
1124
-			$provider->update($share);
1125
-		}
1126
-
1127
-		return true;
1128
-	}
1129
-
1130
-	/**
1131
-	 * @inheritdoc
1132
-	 */
1133
-	public function userDeleted($uid) {
1134
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1135
-
1136
-		foreach ($types as $type) {
1137
-			try {
1138
-				$provider = $this->factory->getProviderForType($type);
1139
-			} catch (ProviderException $e) {
1140
-				continue;
1141
-			}
1142
-			$provider->userDeleted($uid, $type);
1143
-		}
1144
-	}
1145
-
1146
-	/**
1147
-	 * @inheritdoc
1148
-	 */
1149
-	public function groupDeleted($gid) {
1150
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1151
-		$provider->groupDeleted($gid);
1152
-	}
1153
-
1154
-	/**
1155
-	 * @inheritdoc
1156
-	 */
1157
-	public function userDeletedFromGroup($uid, $gid) {
1158
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1159
-		$provider->userDeletedFromGroup($uid, $gid);
1160
-	}
1161
-
1162
-	/**
1163
-	 * Get access list to a path. This means
1164
-	 * all the users and groups that can access a given path.
1165
-	 *
1166
-	 * Consider:
1167
-	 * -root
1168
-	 * |-folder1
1169
-	 *  |-folder2
1170
-	 *   |-fileA
1171
-	 *
1172
-	 * fileA is shared with user1
1173
-	 * folder2 is shared with group2
1174
-	 * folder1 is shared with user2
1175
-	 *
1176
-	 * Then the access list will to '/folder1/folder2/fileA' is:
1177
-	 * [
1178
-	 * 	'users' => ['user1', 'user2'],
1179
-	 *  'groups' => ['group2']
1180
-	 * ]
1181
-	 *
1182
-	 * This is required for encryption
1183
-	 *
1184
-	 * @param \OCP\Files\Node $path
1185
-	 */
1186
-	public function getAccessList(\OCP\Files\Node $path) {
1187
-	}
1188
-
1189
-	/**
1190
-	 * Create a new share
1191
-	 * @return \OCP\Share\IShare;
1192
-	 */
1193
-	public function newShare() {
1194
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1195
-	}
1196
-
1197
-	/**
1198
-	 * Is the share API enabled
1199
-	 *
1200
-	 * @return bool
1201
-	 */
1202
-	public function shareApiEnabled() {
1203
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1204
-	}
1205
-
1206
-	/**
1207
-	 * Is public link sharing enabled
1208
-	 *
1209
-	 * @return bool
1210
-	 */
1211
-	public function shareApiAllowLinks() {
1212
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1213
-	}
1214
-
1215
-	/**
1216
-	 * Is password on public link requires
1217
-	 *
1218
-	 * @return bool
1219
-	 */
1220
-	public function shareApiLinkEnforcePassword() {
1221
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1222
-	}
1223
-
1224
-	/**
1225
-	 * Is default expire date enabled
1226
-	 *
1227
-	 * @return bool
1228
-	 */
1229
-	public function shareApiLinkDefaultExpireDate() {
1230
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1231
-	}
1232
-
1233
-	/**
1234
-	 * Is default expire date enforced
1235
-	 *`
1236
-	 * @return bool
1237
-	 */
1238
-	public function shareApiLinkDefaultExpireDateEnforced() {
1239
-		return $this->shareApiLinkDefaultExpireDate() &&
1240
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1241
-	}
1242
-
1243
-	/**
1244
-	 * Number of default expire days
1245
-	 *shareApiLinkAllowPublicUpload
1246
-	 * @return int
1247
-	 */
1248
-	public function shareApiLinkDefaultExpireDays() {
1249
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1250
-	}
1251
-
1252
-	/**
1253
-	 * Allow public upload on link shares
1254
-	 *
1255
-	 * @return bool
1256
-	 */
1257
-	public function shareApiLinkAllowPublicUpload() {
1258
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1259
-	}
1260
-
1261
-	/**
1262
-	 * check if user can only share with group members
1263
-	 * @return bool
1264
-	 */
1265
-	public function shareWithGroupMembersOnly() {
1266
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1267
-	}
1268
-
1269
-	/**
1270
-	 * Check if users can share with groups
1271
-	 * @return bool
1272
-	 */
1273
-	public function allowGroupSharing() {
1274
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1275
-	}
1276
-
1277
-	/**
1278
-	 * Copied from \OC_Util::isSharingDisabledForUser
1279
-	 *
1280
-	 * TODO: Deprecate fuction from OC_Util
1281
-	 *
1282
-	 * @param string $userId
1283
-	 * @return bool
1284
-	 */
1285
-	public function sharingDisabledForUser($userId) {
1286
-		if ($userId === null) {
1287
-			return false;
1288
-		}
1289
-
1290
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1291
-			return $this->sharingDisabledForUsersCache[$userId];
1292
-		}
1293
-
1294
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1295
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1296
-			$excludedGroups = json_decode($groupsList);
1297
-			if (is_null($excludedGroups)) {
1298
-				$excludedGroups = explode(',', $groupsList);
1299
-				$newValue = json_encode($excludedGroups);
1300
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1301
-			}
1302
-			$user = $this->userManager->get($userId);
1303
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1304
-			if (!empty($usersGroups)) {
1305
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1306
-				// if the user is only in groups which are disabled for sharing then
1307
-				// sharing is also disabled for the user
1308
-				if (empty($remainingGroups)) {
1309
-					$this->sharingDisabledForUsersCache[$userId] = true;
1310
-					return true;
1311
-				}
1312
-			}
1313
-		}
1314
-
1315
-		$this->sharingDisabledForUsersCache[$userId] = false;
1316
-		return false;
1317
-	}
1318
-
1319
-	/**
1320
-	 * @inheritdoc
1321
-	 */
1322
-	public function outgoingServer2ServerSharesAllowed() {
1323
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1324
-	}
1325
-
1326
-	/**
1327
-	 * @inheritdoc
1328
-	 */
1329
-	public function shareProviderExists($shareType) {
1330
-		try {
1331
-			$this->factory->getProviderForType($shareType);
1332
-		} catch (ProviderException $e) {
1333
-			return false;
1334
-		}
1335
-
1336
-		return true;
1337
-	}
1091
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1092
+            !$this->shareApiLinkAllowPublicUpload()) {
1093
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1094
+        }
1095
+
1096
+        return $share;
1097
+    }
1098
+
1099
+    /**
1100
+     * Verify the password of a public share
1101
+     *
1102
+     * @param \OCP\Share\IShare $share
1103
+     * @param string $password
1104
+     * @return bool
1105
+     */
1106
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1107
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
1108
+            //TODO maybe exception?
1109
+            return false;
1110
+        }
1111
+
1112
+        if ($password === null || $share->getPassword() === null) {
1113
+            return false;
1114
+        }
1115
+
1116
+        $newHash = '';
1117
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1118
+            return false;
1119
+        }
1120
+
1121
+        if (!empty($newHash)) {
1122
+            $share->setPassword($newHash);
1123
+            $provider = $this->factory->getProviderForType($share->getShareType());
1124
+            $provider->update($share);
1125
+        }
1126
+
1127
+        return true;
1128
+    }
1129
+
1130
+    /**
1131
+     * @inheritdoc
1132
+     */
1133
+    public function userDeleted($uid) {
1134
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1135
+
1136
+        foreach ($types as $type) {
1137
+            try {
1138
+                $provider = $this->factory->getProviderForType($type);
1139
+            } catch (ProviderException $e) {
1140
+                continue;
1141
+            }
1142
+            $provider->userDeleted($uid, $type);
1143
+        }
1144
+    }
1145
+
1146
+    /**
1147
+     * @inheritdoc
1148
+     */
1149
+    public function groupDeleted($gid) {
1150
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1151
+        $provider->groupDeleted($gid);
1152
+    }
1153
+
1154
+    /**
1155
+     * @inheritdoc
1156
+     */
1157
+    public function userDeletedFromGroup($uid, $gid) {
1158
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1159
+        $provider->userDeletedFromGroup($uid, $gid);
1160
+    }
1161
+
1162
+    /**
1163
+     * Get access list to a path. This means
1164
+     * all the users and groups that can access a given path.
1165
+     *
1166
+     * Consider:
1167
+     * -root
1168
+     * |-folder1
1169
+     *  |-folder2
1170
+     *   |-fileA
1171
+     *
1172
+     * fileA is shared with user1
1173
+     * folder2 is shared with group2
1174
+     * folder1 is shared with user2
1175
+     *
1176
+     * Then the access list will to '/folder1/folder2/fileA' is:
1177
+     * [
1178
+     * 	'users' => ['user1', 'user2'],
1179
+     *  'groups' => ['group2']
1180
+     * ]
1181
+     *
1182
+     * This is required for encryption
1183
+     *
1184
+     * @param \OCP\Files\Node $path
1185
+     */
1186
+    public function getAccessList(\OCP\Files\Node $path) {
1187
+    }
1188
+
1189
+    /**
1190
+     * Create a new share
1191
+     * @return \OCP\Share\IShare;
1192
+     */
1193
+    public function newShare() {
1194
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1195
+    }
1196
+
1197
+    /**
1198
+     * Is the share API enabled
1199
+     *
1200
+     * @return bool
1201
+     */
1202
+    public function shareApiEnabled() {
1203
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1204
+    }
1205
+
1206
+    /**
1207
+     * Is public link sharing enabled
1208
+     *
1209
+     * @return bool
1210
+     */
1211
+    public function shareApiAllowLinks() {
1212
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1213
+    }
1214
+
1215
+    /**
1216
+     * Is password on public link requires
1217
+     *
1218
+     * @return bool
1219
+     */
1220
+    public function shareApiLinkEnforcePassword() {
1221
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1222
+    }
1223
+
1224
+    /**
1225
+     * Is default expire date enabled
1226
+     *
1227
+     * @return bool
1228
+     */
1229
+    public function shareApiLinkDefaultExpireDate() {
1230
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1231
+    }
1232
+
1233
+    /**
1234
+     * Is default expire date enforced
1235
+     *`
1236
+     * @return bool
1237
+     */
1238
+    public function shareApiLinkDefaultExpireDateEnforced() {
1239
+        return $this->shareApiLinkDefaultExpireDate() &&
1240
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1241
+    }
1242
+
1243
+    /**
1244
+     * Number of default expire days
1245
+     *shareApiLinkAllowPublicUpload
1246
+     * @return int
1247
+     */
1248
+    public function shareApiLinkDefaultExpireDays() {
1249
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1250
+    }
1251
+
1252
+    /**
1253
+     * Allow public upload on link shares
1254
+     *
1255
+     * @return bool
1256
+     */
1257
+    public function shareApiLinkAllowPublicUpload() {
1258
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1259
+    }
1260
+
1261
+    /**
1262
+     * check if user can only share with group members
1263
+     * @return bool
1264
+     */
1265
+    public function shareWithGroupMembersOnly() {
1266
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1267
+    }
1268
+
1269
+    /**
1270
+     * Check if users can share with groups
1271
+     * @return bool
1272
+     */
1273
+    public function allowGroupSharing() {
1274
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1275
+    }
1276
+
1277
+    /**
1278
+     * Copied from \OC_Util::isSharingDisabledForUser
1279
+     *
1280
+     * TODO: Deprecate fuction from OC_Util
1281
+     *
1282
+     * @param string $userId
1283
+     * @return bool
1284
+     */
1285
+    public function sharingDisabledForUser($userId) {
1286
+        if ($userId === null) {
1287
+            return false;
1288
+        }
1289
+
1290
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1291
+            return $this->sharingDisabledForUsersCache[$userId];
1292
+        }
1293
+
1294
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1295
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1296
+            $excludedGroups = json_decode($groupsList);
1297
+            if (is_null($excludedGroups)) {
1298
+                $excludedGroups = explode(',', $groupsList);
1299
+                $newValue = json_encode($excludedGroups);
1300
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1301
+            }
1302
+            $user = $this->userManager->get($userId);
1303
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1304
+            if (!empty($usersGroups)) {
1305
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1306
+                // if the user is only in groups which are disabled for sharing then
1307
+                // sharing is also disabled for the user
1308
+                if (empty($remainingGroups)) {
1309
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1310
+                    return true;
1311
+                }
1312
+            }
1313
+        }
1314
+
1315
+        $this->sharingDisabledForUsersCache[$userId] = false;
1316
+        return false;
1317
+    }
1318
+
1319
+    /**
1320
+     * @inheritdoc
1321
+     */
1322
+    public function outgoingServer2ServerSharesAllowed() {
1323
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1324
+    }
1325
+
1326
+    /**
1327
+     * @inheritdoc
1328
+     */
1329
+    public function shareProviderExists($shareType) {
1330
+        try {
1331
+            $this->factory->getProviderForType($shareType);
1332
+        } catch (ProviderException $e) {
1333
+            return false;
1334
+        }
1335
+
1336
+        return true;
1337
+    }
1338 1338
 
1339 1339
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 1 patch
Indentation   +987 added lines, -987 removed lines patch added patch discarded remove patch
@@ -47,1024 +47,1024 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->execute();
206
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
-			$qb = $this->dbConn->getQueryBuilder();
208
-			$qb->update('share')
209
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->execute();
216
-
217
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->execute();
206
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
+            $qb = $this->dbConn->getQueryBuilder();
208
+            $qb->update('share')
209
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->execute();
216
+
217
+            /*
218 218
 			 * Update all user defined group shares
219 219
 			 */
220
-			$qb = $this->dbConn->getQueryBuilder();
221
-			$qb->update('share')
222
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
223
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
224
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
225
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
226
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
227
-				->execute();
228
-
229
-			/*
220
+            $qb = $this->dbConn->getQueryBuilder();
221
+            $qb->update('share')
222
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
223
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
224
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
225
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
226
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
227
+                ->execute();
228
+
229
+            /*
230 230
 			 * Now update the permissions for all children that have not set it to 0
231 231
 			 */
232
-			$qb = $this->dbConn->getQueryBuilder();
233
-			$qb->update('share')
234
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
235
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
236
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
237
-				->execute();
238
-
239
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
240
-			$qb = $this->dbConn->getQueryBuilder();
241
-			$qb->update('share')
242
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
243
-				->set('password', $qb->createNamedParameter($share->getPassword()))
244
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
245
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
246
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
247
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
248
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
249
-				->set('token', $qb->createNamedParameter($share->getToken()))
250
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
251
-				->execute();
252
-		}
253
-
254
-		return $share;
255
-	}
256
-
257
-	/**
258
-	 * Get all children of this share
259
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
260
-	 *
261
-	 * @param \OCP\Share\IShare $parent
262
-	 * @return \OCP\Share\IShare[]
263
-	 */
264
-	public function getChildren(\OCP\Share\IShare $parent) {
265
-		$children = [];
266
-
267
-		$qb = $this->dbConn->getQueryBuilder();
268
-		$qb->select('*')
269
-			->from('share')
270
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
271
-			->andWhere(
272
-				$qb->expr()->in(
273
-					'share_type',
274
-					$qb->createNamedParameter([
275
-						\OCP\Share::SHARE_TYPE_USER,
276
-						\OCP\Share::SHARE_TYPE_GROUP,
277
-						\OCP\Share::SHARE_TYPE_LINK,
278
-					], IQueryBuilder::PARAM_INT_ARRAY)
279
-				)
280
-			)
281
-			->andWhere($qb->expr()->orX(
282
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
283
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
284
-			))
285
-			->orderBy('id');
286
-
287
-		$cursor = $qb->execute();
288
-		while($data = $cursor->fetch()) {
289
-			$children[] = $this->createShare($data);
290
-		}
291
-		$cursor->closeCursor();
292
-
293
-		return $children;
294
-	}
295
-
296
-	/**
297
-	 * Delete a share
298
-	 *
299
-	 * @param \OCP\Share\IShare $share
300
-	 */
301
-	public function delete(\OCP\Share\IShare $share) {
302
-		$qb = $this->dbConn->getQueryBuilder();
303
-		$qb->delete('share')
304
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
305
-
306
-		/*
232
+            $qb = $this->dbConn->getQueryBuilder();
233
+            $qb->update('share')
234
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
235
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
236
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
237
+                ->execute();
238
+
239
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
240
+            $qb = $this->dbConn->getQueryBuilder();
241
+            $qb->update('share')
242
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
243
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
244
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
245
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
246
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
247
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
248
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
249
+                ->set('token', $qb->createNamedParameter($share->getToken()))
250
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
251
+                ->execute();
252
+        }
253
+
254
+        return $share;
255
+    }
256
+
257
+    /**
258
+     * Get all children of this share
259
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
260
+     *
261
+     * @param \OCP\Share\IShare $parent
262
+     * @return \OCP\Share\IShare[]
263
+     */
264
+    public function getChildren(\OCP\Share\IShare $parent) {
265
+        $children = [];
266
+
267
+        $qb = $this->dbConn->getQueryBuilder();
268
+        $qb->select('*')
269
+            ->from('share')
270
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
271
+            ->andWhere(
272
+                $qb->expr()->in(
273
+                    'share_type',
274
+                    $qb->createNamedParameter([
275
+                        \OCP\Share::SHARE_TYPE_USER,
276
+                        \OCP\Share::SHARE_TYPE_GROUP,
277
+                        \OCP\Share::SHARE_TYPE_LINK,
278
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
279
+                )
280
+            )
281
+            ->andWhere($qb->expr()->orX(
282
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
283
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
284
+            ))
285
+            ->orderBy('id');
286
+
287
+        $cursor = $qb->execute();
288
+        while($data = $cursor->fetch()) {
289
+            $children[] = $this->createShare($data);
290
+        }
291
+        $cursor->closeCursor();
292
+
293
+        return $children;
294
+    }
295
+
296
+    /**
297
+     * Delete a share
298
+     *
299
+     * @param \OCP\Share\IShare $share
300
+     */
301
+    public function delete(\OCP\Share\IShare $share) {
302
+        $qb = $this->dbConn->getQueryBuilder();
303
+        $qb->delete('share')
304
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
305
+
306
+        /*
307 307
 		 * If the share is a group share delete all possible
308 308
 		 * user defined groups shares.
309 309
 		 */
310
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
311
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
312
-		}
313
-
314
-		$qb->execute();
315
-	}
316
-
317
-	/**
318
-	 * Unshare a share from the recipient. If this is a group share
319
-	 * this means we need a special entry in the share db.
320
-	 *
321
-	 * @param \OCP\Share\IShare $share
322
-	 * @param string $recipient UserId of recipient
323
-	 * @throws BackendError
324
-	 * @throws ProviderException
325
-	 */
326
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
327
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
328
-
329
-			$group = $this->groupManager->get($share->getSharedWith());
330
-			$user = $this->userManager->get($recipient);
331
-
332
-			if (is_null($group)) {
333
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
334
-			}
335
-
336
-			if (!$group->inGroup($user)) {
337
-				throw new ProviderException('Recipient not in receiving group');
338
-			}
339
-
340
-			// Try to fetch user specific share
341
-			$qb = $this->dbConn->getQueryBuilder();
342
-			$stmt = $qb->select('*')
343
-				->from('share')
344
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
345
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
346
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
347
-				->andWhere($qb->expr()->orX(
348
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
349
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
350
-				))
351
-				->execute();
352
-
353
-			$data = $stmt->fetch();
354
-
355
-			/*
310
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
311
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
312
+        }
313
+
314
+        $qb->execute();
315
+    }
316
+
317
+    /**
318
+     * Unshare a share from the recipient. If this is a group share
319
+     * this means we need a special entry in the share db.
320
+     *
321
+     * @param \OCP\Share\IShare $share
322
+     * @param string $recipient UserId of recipient
323
+     * @throws BackendError
324
+     * @throws ProviderException
325
+     */
326
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
327
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
328
+
329
+            $group = $this->groupManager->get($share->getSharedWith());
330
+            $user = $this->userManager->get($recipient);
331
+
332
+            if (is_null($group)) {
333
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
334
+            }
335
+
336
+            if (!$group->inGroup($user)) {
337
+                throw new ProviderException('Recipient not in receiving group');
338
+            }
339
+
340
+            // Try to fetch user specific share
341
+            $qb = $this->dbConn->getQueryBuilder();
342
+            $stmt = $qb->select('*')
343
+                ->from('share')
344
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
345
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
346
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
347
+                ->andWhere($qb->expr()->orX(
348
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
349
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
350
+                ))
351
+                ->execute();
352
+
353
+            $data = $stmt->fetch();
354
+
355
+            /*
356 356
 			 * Check if there already is a user specific group share.
357 357
 			 * If there is update it (if required).
358 358
 			 */
359
-			if ($data === false) {
360
-				$qb = $this->dbConn->getQueryBuilder();
361
-
362
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
363
-
364
-				//Insert new share
365
-				$qb->insert('share')
366
-					->values([
367
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
368
-						'share_with' => $qb->createNamedParameter($recipient),
369
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
370
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
371
-						'parent' => $qb->createNamedParameter($share->getId()),
372
-						'item_type' => $qb->createNamedParameter($type),
373
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
374
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
375
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
376
-						'permissions' => $qb->createNamedParameter(0),
377
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
378
-					])->execute();
379
-
380
-			} else if ($data['permissions'] !== 0) {
381
-
382
-				// Update existing usergroup share
383
-				$qb = $this->dbConn->getQueryBuilder();
384
-				$qb->update('share')
385
-					->set('permissions', $qb->createNamedParameter(0))
386
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
387
-					->execute();
388
-			}
389
-
390
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
391
-
392
-			if ($share->getSharedWith() !== $recipient) {
393
-				throw new ProviderException('Recipient does not match');
394
-			}
395
-
396
-			// We can just delete user and link shares
397
-			$this->delete($share);
398
-		} else {
399
-			throw new ProviderException('Invalid shareType');
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @inheritdoc
405
-	 */
406
-	public function move(\OCP\Share\IShare $share, $recipient) {
407
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
408
-			// Just update the target
409
-			$qb = $this->dbConn->getQueryBuilder();
410
-			$qb->update('share')
411
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
412
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
413
-				->execute();
414
-
415
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
416
-
417
-			// Check if there is a usergroup share
418
-			$qb = $this->dbConn->getQueryBuilder();
419
-			$stmt = $qb->select('id')
420
-				->from('share')
421
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
422
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
423
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
424
-				->andWhere($qb->expr()->orX(
425
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
426
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
427
-				))
428
-				->setMaxResults(1)
429
-				->execute();
430
-
431
-			$data = $stmt->fetch();
432
-			$stmt->closeCursor();
433
-
434
-			if ($data === false) {
435
-				// No usergroup share yet. Create one.
436
-				$qb = $this->dbConn->getQueryBuilder();
437
-				$qb->insert('share')
438
-					->values([
439
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
440
-						'share_with' => $qb->createNamedParameter($recipient),
441
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
442
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
443
-						'parent' => $qb->createNamedParameter($share->getId()),
444
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
445
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
446
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
447
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
448
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
449
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
450
-					])->execute();
451
-			} else {
452
-				// Already a usergroup share. Update it.
453
-				$qb = $this->dbConn->getQueryBuilder();
454
-				$qb->update('share')
455
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
456
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
457
-					->execute();
458
-			}
459
-		}
460
-
461
-		return $share;
462
-	}
463
-
464
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
465
-		$qb = $this->dbConn->getQueryBuilder();
466
-		$qb->select('*')
467
-			->from('share', 's')
468
-			->andWhere($qb->expr()->orX(
469
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
470
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
471
-			));
472
-
473
-		$qb->andWhere($qb->expr()->orX(
474
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
475
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
476
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
477
-		));
478
-
479
-		/**
480
-		 * Reshares for this user are shares where they are the owner.
481
-		 */
482
-		if ($reshares === false) {
483
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
484
-		} else {
485
-			$qb->andWhere(
486
-				$qb->expr()->orX(
487
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
488
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
489
-				)
490
-			);
491
-		}
492
-
493
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
494
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495
-
496
-		$qb->orderBy('id');
497
-
498
-		$cursor = $qb->execute();
499
-		$shares = [];
500
-		while ($data = $cursor->fetch()) {
501
-			$shares[$data['fileid']][] = $this->createShare($data);
502
-		}
503
-		$cursor->closeCursor();
504
-
505
-		return $shares;
506
-	}
507
-
508
-	/**
509
-	 * @inheritdoc
510
-	 */
511
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
512
-		$qb = $this->dbConn->getQueryBuilder();
513
-		$qb->select('*')
514
-			->from('share')
515
-			->andWhere($qb->expr()->orX(
516
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
517
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
518
-			));
519
-
520
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
521
-
522
-		/**
523
-		 * Reshares for this user are shares where they are the owner.
524
-		 */
525
-		if ($reshares === false) {
526
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
527
-		} else {
528
-			$qb->andWhere(
529
-				$qb->expr()->orX(
530
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
531
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
532
-				)
533
-			);
534
-		}
535
-
536
-		if ($node !== null) {
537
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
538
-		}
539
-
540
-		if ($limit !== -1) {
541
-			$qb->setMaxResults($limit);
542
-		}
543
-
544
-		$qb->setFirstResult($offset);
545
-		$qb->orderBy('id');
546
-
547
-		$cursor = $qb->execute();
548
-		$shares = [];
549
-		while($data = $cursor->fetch()) {
550
-			$shares[] = $this->createShare($data);
551
-		}
552
-		$cursor->closeCursor();
553
-
554
-		return $shares;
555
-	}
556
-
557
-	/**
558
-	 * @inheritdoc
559
-	 */
560
-	public function getShareById($id, $recipientId = null) {
561
-		$qb = $this->dbConn->getQueryBuilder();
562
-
563
-		$qb->select('*')
564
-			->from('share')
565
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
566
-			->andWhere(
567
-				$qb->expr()->in(
568
-					'share_type',
569
-					$qb->createNamedParameter([
570
-						\OCP\Share::SHARE_TYPE_USER,
571
-						\OCP\Share::SHARE_TYPE_GROUP,
572
-						\OCP\Share::SHARE_TYPE_LINK,
573
-					], IQueryBuilder::PARAM_INT_ARRAY)
574
-				)
575
-			)
576
-			->andWhere($qb->expr()->orX(
577
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
578
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
579
-			));
580
-
581
-		$cursor = $qb->execute();
582
-		$data = $cursor->fetch();
583
-		$cursor->closeCursor();
584
-
585
-		if ($data === false) {
586
-			throw new ShareNotFound();
587
-		}
588
-
589
-		try {
590
-			$share = $this->createShare($data);
591
-		} catch (InvalidShare $e) {
592
-			throw new ShareNotFound();
593
-		}
594
-
595
-		// If the recipient is set for a group share resolve to that user
596
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
597
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
598
-		}
599
-
600
-		return $share;
601
-	}
602
-
603
-	/**
604
-	 * Get shares for a given path
605
-	 *
606
-	 * @param \OCP\Files\Node $path
607
-	 * @return \OCP\Share\IShare[]
608
-	 */
609
-	public function getSharesByPath(Node $path) {
610
-		$qb = $this->dbConn->getQueryBuilder();
611
-
612
-		$cursor = $qb->select('*')
613
-			->from('share')
614
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
615
-			->andWhere(
616
-				$qb->expr()->orX(
617
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
618
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
619
-				)
620
-			)
621
-			->andWhere($qb->expr()->orX(
622
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
623
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
624
-			))
625
-			->execute();
626
-
627
-		$shares = [];
628
-		while($data = $cursor->fetch()) {
629
-			$shares[] = $this->createShare($data);
630
-		}
631
-		$cursor->closeCursor();
632
-
633
-		return $shares;
634
-	}
635
-
636
-	/**
637
-	 * Returns whether the given database result can be interpreted as
638
-	 * a share with accessible file (not trashed, not deleted)
639
-	 */
640
-	private function isAccessibleResult($data) {
641
-		// exclude shares leading to deleted file entries
642
-		if ($data['fileid'] === null) {
643
-			return false;
644
-		}
645
-
646
-		// exclude shares leading to trashbin on home storages
647
-		$pathSections = explode('/', $data['path'], 2);
648
-		// FIXME: would not detect rare md5'd home storage case properly
649
-		if ($pathSections[0] !== 'files'
650
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
651
-			return false;
652
-		}
653
-		return true;
654
-	}
655
-
656
-	/**
657
-	 * @inheritdoc
658
-	 */
659
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
660
-		/** @var Share[] $shares */
661
-		$shares = [];
662
-
663
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
664
-			//Get shares directly with this user
665
-			$qb = $this->dbConn->getQueryBuilder();
666
-			$qb->select('s.*',
667
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
668
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
669
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
670
-			)
671
-				->selectAlias('st.id', 'storage_string_id')
672
-				->from('share', 's')
673
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
674
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
675
-
676
-			// Order by id
677
-			$qb->orderBy('s.id');
678
-
679
-			// Set limit and offset
680
-			if ($limit !== -1) {
681
-				$qb->setMaxResults($limit);
682
-			}
683
-			$qb->setFirstResult($offset);
684
-
685
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
686
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
687
-				->andWhere($qb->expr()->orX(
688
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
689
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
690
-				));
691
-
692
-			// Filter by node if provided
693
-			if ($node !== null) {
694
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
695
-			}
696
-
697
-			$cursor = $qb->execute();
698
-
699
-			while($data = $cursor->fetch()) {
700
-				if ($this->isAccessibleResult($data)) {
701
-					$shares[] = $this->createShare($data);
702
-				}
703
-			}
704
-			$cursor->closeCursor();
705
-
706
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
707
-			$user = $this->userManager->get($userId);
708
-			$allGroups = $this->groupManager->getUserGroups($user);
709
-
710
-			/** @var Share[] $shares2 */
711
-			$shares2 = [];
712
-
713
-			$start = 0;
714
-			while(true) {
715
-				$groups = array_slice($allGroups, $start, 100);
716
-				$start += 100;
717
-
718
-				if ($groups === []) {
719
-					break;
720
-				}
721
-
722
-				$qb = $this->dbConn->getQueryBuilder();
723
-				$qb->select('s.*',
724
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
725
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
726
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
727
-				)
728
-					->selectAlias('st.id', 'storage_string_id')
729
-					->from('share', 's')
730
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
731
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
732
-					->orderBy('s.id')
733
-					->setFirstResult(0);
734
-
735
-				if ($limit !== -1) {
736
-					$qb->setMaxResults($limit - count($shares));
737
-				}
738
-
739
-				// Filter by node if provided
740
-				if ($node !== null) {
741
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
742
-				}
743
-
744
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
745
-
746
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
747
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
748
-						$groups,
749
-						IQueryBuilder::PARAM_STR_ARRAY
750
-					)))
751
-					->andWhere($qb->expr()->orX(
752
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
753
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
754
-					));
755
-
756
-				$cursor = $qb->execute();
757
-				while($data = $cursor->fetch()) {
758
-					if ($offset > 0) {
759
-						$offset--;
760
-						continue;
761
-					}
762
-
763
-					if ($this->isAccessibleResult($data)) {
764
-						$shares2[] = $this->createShare($data);
765
-					}
766
-				}
767
-				$cursor->closeCursor();
768
-			}
769
-
770
-			/*
359
+            if ($data === false) {
360
+                $qb = $this->dbConn->getQueryBuilder();
361
+
362
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
363
+
364
+                //Insert new share
365
+                $qb->insert('share')
366
+                    ->values([
367
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
368
+                        'share_with' => $qb->createNamedParameter($recipient),
369
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
370
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
371
+                        'parent' => $qb->createNamedParameter($share->getId()),
372
+                        'item_type' => $qb->createNamedParameter($type),
373
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
374
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
375
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
376
+                        'permissions' => $qb->createNamedParameter(0),
377
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
378
+                    ])->execute();
379
+
380
+            } else if ($data['permissions'] !== 0) {
381
+
382
+                // Update existing usergroup share
383
+                $qb = $this->dbConn->getQueryBuilder();
384
+                $qb->update('share')
385
+                    ->set('permissions', $qb->createNamedParameter(0))
386
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
387
+                    ->execute();
388
+            }
389
+
390
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
391
+
392
+            if ($share->getSharedWith() !== $recipient) {
393
+                throw new ProviderException('Recipient does not match');
394
+            }
395
+
396
+            // We can just delete user and link shares
397
+            $this->delete($share);
398
+        } else {
399
+            throw new ProviderException('Invalid shareType');
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @inheritdoc
405
+     */
406
+    public function move(\OCP\Share\IShare $share, $recipient) {
407
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
408
+            // Just update the target
409
+            $qb = $this->dbConn->getQueryBuilder();
410
+            $qb->update('share')
411
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
412
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
413
+                ->execute();
414
+
415
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
416
+
417
+            // Check if there is a usergroup share
418
+            $qb = $this->dbConn->getQueryBuilder();
419
+            $stmt = $qb->select('id')
420
+                ->from('share')
421
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
422
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
423
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
424
+                ->andWhere($qb->expr()->orX(
425
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
426
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
427
+                ))
428
+                ->setMaxResults(1)
429
+                ->execute();
430
+
431
+            $data = $stmt->fetch();
432
+            $stmt->closeCursor();
433
+
434
+            if ($data === false) {
435
+                // No usergroup share yet. Create one.
436
+                $qb = $this->dbConn->getQueryBuilder();
437
+                $qb->insert('share')
438
+                    ->values([
439
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
440
+                        'share_with' => $qb->createNamedParameter($recipient),
441
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
442
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
443
+                        'parent' => $qb->createNamedParameter($share->getId()),
444
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
445
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
446
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
447
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
448
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
449
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
450
+                    ])->execute();
451
+            } else {
452
+                // Already a usergroup share. Update it.
453
+                $qb = $this->dbConn->getQueryBuilder();
454
+                $qb->update('share')
455
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
456
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
457
+                    ->execute();
458
+            }
459
+        }
460
+
461
+        return $share;
462
+    }
463
+
464
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
465
+        $qb = $this->dbConn->getQueryBuilder();
466
+        $qb->select('*')
467
+            ->from('share', 's')
468
+            ->andWhere($qb->expr()->orX(
469
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
470
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
471
+            ));
472
+
473
+        $qb->andWhere($qb->expr()->orX(
474
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
475
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
476
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
477
+        ));
478
+
479
+        /**
480
+         * Reshares for this user are shares where they are the owner.
481
+         */
482
+        if ($reshares === false) {
483
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
484
+        } else {
485
+            $qb->andWhere(
486
+                $qb->expr()->orX(
487
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
488
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
489
+                )
490
+            );
491
+        }
492
+
493
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
494
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495
+
496
+        $qb->orderBy('id');
497
+
498
+        $cursor = $qb->execute();
499
+        $shares = [];
500
+        while ($data = $cursor->fetch()) {
501
+            $shares[$data['fileid']][] = $this->createShare($data);
502
+        }
503
+        $cursor->closeCursor();
504
+
505
+        return $shares;
506
+    }
507
+
508
+    /**
509
+     * @inheritdoc
510
+     */
511
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
512
+        $qb = $this->dbConn->getQueryBuilder();
513
+        $qb->select('*')
514
+            ->from('share')
515
+            ->andWhere($qb->expr()->orX(
516
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
517
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
518
+            ));
519
+
520
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
521
+
522
+        /**
523
+         * Reshares for this user are shares where they are the owner.
524
+         */
525
+        if ($reshares === false) {
526
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
527
+        } else {
528
+            $qb->andWhere(
529
+                $qb->expr()->orX(
530
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
531
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
532
+                )
533
+            );
534
+        }
535
+
536
+        if ($node !== null) {
537
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
538
+        }
539
+
540
+        if ($limit !== -1) {
541
+            $qb->setMaxResults($limit);
542
+        }
543
+
544
+        $qb->setFirstResult($offset);
545
+        $qb->orderBy('id');
546
+
547
+        $cursor = $qb->execute();
548
+        $shares = [];
549
+        while($data = $cursor->fetch()) {
550
+            $shares[] = $this->createShare($data);
551
+        }
552
+        $cursor->closeCursor();
553
+
554
+        return $shares;
555
+    }
556
+
557
+    /**
558
+     * @inheritdoc
559
+     */
560
+    public function getShareById($id, $recipientId = null) {
561
+        $qb = $this->dbConn->getQueryBuilder();
562
+
563
+        $qb->select('*')
564
+            ->from('share')
565
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
566
+            ->andWhere(
567
+                $qb->expr()->in(
568
+                    'share_type',
569
+                    $qb->createNamedParameter([
570
+                        \OCP\Share::SHARE_TYPE_USER,
571
+                        \OCP\Share::SHARE_TYPE_GROUP,
572
+                        \OCP\Share::SHARE_TYPE_LINK,
573
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
574
+                )
575
+            )
576
+            ->andWhere($qb->expr()->orX(
577
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
578
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
579
+            ));
580
+
581
+        $cursor = $qb->execute();
582
+        $data = $cursor->fetch();
583
+        $cursor->closeCursor();
584
+
585
+        if ($data === false) {
586
+            throw new ShareNotFound();
587
+        }
588
+
589
+        try {
590
+            $share = $this->createShare($data);
591
+        } catch (InvalidShare $e) {
592
+            throw new ShareNotFound();
593
+        }
594
+
595
+        // If the recipient is set for a group share resolve to that user
596
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
597
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
598
+        }
599
+
600
+        return $share;
601
+    }
602
+
603
+    /**
604
+     * Get shares for a given path
605
+     *
606
+     * @param \OCP\Files\Node $path
607
+     * @return \OCP\Share\IShare[]
608
+     */
609
+    public function getSharesByPath(Node $path) {
610
+        $qb = $this->dbConn->getQueryBuilder();
611
+
612
+        $cursor = $qb->select('*')
613
+            ->from('share')
614
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
615
+            ->andWhere(
616
+                $qb->expr()->orX(
617
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
618
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
619
+                )
620
+            )
621
+            ->andWhere($qb->expr()->orX(
622
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
623
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
624
+            ))
625
+            ->execute();
626
+
627
+        $shares = [];
628
+        while($data = $cursor->fetch()) {
629
+            $shares[] = $this->createShare($data);
630
+        }
631
+        $cursor->closeCursor();
632
+
633
+        return $shares;
634
+    }
635
+
636
+    /**
637
+     * Returns whether the given database result can be interpreted as
638
+     * a share with accessible file (not trashed, not deleted)
639
+     */
640
+    private function isAccessibleResult($data) {
641
+        // exclude shares leading to deleted file entries
642
+        if ($data['fileid'] === null) {
643
+            return false;
644
+        }
645
+
646
+        // exclude shares leading to trashbin on home storages
647
+        $pathSections = explode('/', $data['path'], 2);
648
+        // FIXME: would not detect rare md5'd home storage case properly
649
+        if ($pathSections[0] !== 'files'
650
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
651
+            return false;
652
+        }
653
+        return true;
654
+    }
655
+
656
+    /**
657
+     * @inheritdoc
658
+     */
659
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
660
+        /** @var Share[] $shares */
661
+        $shares = [];
662
+
663
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
664
+            //Get shares directly with this user
665
+            $qb = $this->dbConn->getQueryBuilder();
666
+            $qb->select('s.*',
667
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
668
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
669
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
670
+            )
671
+                ->selectAlias('st.id', 'storage_string_id')
672
+                ->from('share', 's')
673
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
674
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
675
+
676
+            // Order by id
677
+            $qb->orderBy('s.id');
678
+
679
+            // Set limit and offset
680
+            if ($limit !== -1) {
681
+                $qb->setMaxResults($limit);
682
+            }
683
+            $qb->setFirstResult($offset);
684
+
685
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
686
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
687
+                ->andWhere($qb->expr()->orX(
688
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
689
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
690
+                ));
691
+
692
+            // Filter by node if provided
693
+            if ($node !== null) {
694
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
695
+            }
696
+
697
+            $cursor = $qb->execute();
698
+
699
+            while($data = $cursor->fetch()) {
700
+                if ($this->isAccessibleResult($data)) {
701
+                    $shares[] = $this->createShare($data);
702
+                }
703
+            }
704
+            $cursor->closeCursor();
705
+
706
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
707
+            $user = $this->userManager->get($userId);
708
+            $allGroups = $this->groupManager->getUserGroups($user);
709
+
710
+            /** @var Share[] $shares2 */
711
+            $shares2 = [];
712
+
713
+            $start = 0;
714
+            while(true) {
715
+                $groups = array_slice($allGroups, $start, 100);
716
+                $start += 100;
717
+
718
+                if ($groups === []) {
719
+                    break;
720
+                }
721
+
722
+                $qb = $this->dbConn->getQueryBuilder();
723
+                $qb->select('s.*',
724
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
725
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
726
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
727
+                )
728
+                    ->selectAlias('st.id', 'storage_string_id')
729
+                    ->from('share', 's')
730
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
731
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
732
+                    ->orderBy('s.id')
733
+                    ->setFirstResult(0);
734
+
735
+                if ($limit !== -1) {
736
+                    $qb->setMaxResults($limit - count($shares));
737
+                }
738
+
739
+                // Filter by node if provided
740
+                if ($node !== null) {
741
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
742
+                }
743
+
744
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
745
+
746
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
747
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
748
+                        $groups,
749
+                        IQueryBuilder::PARAM_STR_ARRAY
750
+                    )))
751
+                    ->andWhere($qb->expr()->orX(
752
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
753
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
754
+                    ));
755
+
756
+                $cursor = $qb->execute();
757
+                while($data = $cursor->fetch()) {
758
+                    if ($offset > 0) {
759
+                        $offset--;
760
+                        continue;
761
+                    }
762
+
763
+                    if ($this->isAccessibleResult($data)) {
764
+                        $shares2[] = $this->createShare($data);
765
+                    }
766
+                }
767
+                $cursor->closeCursor();
768
+            }
769
+
770
+            /*
771 771
  			 * Resolve all group shares to user specific shares
772 772
  			 */
773
-			$shares = $this->resolveGroupShares($shares2, $userId);
774
-		} else {
775
-			throw new BackendError('Invalid backend');
776
-		}
777
-
778
-
779
-		return $shares;
780
-	}
781
-
782
-	/**
783
-	 * Get a share by token
784
-	 *
785
-	 * @param string $token
786
-	 * @return \OCP\Share\IShare
787
-	 * @throws ShareNotFound
788
-	 */
789
-	public function getShareByToken($token) {
790
-		$qb = $this->dbConn->getQueryBuilder();
791
-
792
-		$cursor = $qb->select('*')
793
-			->from('share')
794
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
795
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
796
-			->andWhere($qb->expr()->orX(
797
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
798
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
799
-			))
800
-			->execute();
801
-
802
-		$data = $cursor->fetch();
803
-
804
-		if ($data === false) {
805
-			throw new ShareNotFound();
806
-		}
807
-
808
-		try {
809
-			$share = $this->createShare($data);
810
-		} catch (InvalidShare $e) {
811
-			throw new ShareNotFound();
812
-		}
813
-
814
-		return $share;
815
-	}
816
-
817
-	/**
818
-	 * Create a share object from an database row
819
-	 *
820
-	 * @param mixed[] $data
821
-	 * @return \OCP\Share\IShare
822
-	 * @throws InvalidShare
823
-	 */
824
-	private function createShare($data) {
825
-		$share = new Share($this->rootFolder, $this->userManager);
826
-		$share->setId((int)$data['id'])
827
-			->setShareType((int)$data['share_type'])
828
-			->setPermissions((int)$data['permissions'])
829
-			->setTarget($data['file_target'])
830
-			->setMailSend((bool)$data['mail_send']);
831
-
832
-		$shareTime = new \DateTime();
833
-		$shareTime->setTimestamp((int)$data['stime']);
834
-		$share->setShareTime($shareTime);
835
-
836
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
837
-			$share->setSharedWith($data['share_with']);
838
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
839
-			$share->setSharedWith($data['share_with']);
840
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
841
-			$share->setPassword($data['password']);
842
-			$share->setToken($data['token']);
843
-		}
844
-
845
-		$share->setSharedBy($data['uid_initiator']);
846
-		$share->setShareOwner($data['uid_owner']);
847
-
848
-		$share->setNodeId((int)$data['file_source']);
849
-		$share->setNodeType($data['item_type']);
850
-
851
-		if ($data['expiration'] !== null) {
852
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
853
-			$share->setExpirationDate($expiration);
854
-		}
855
-
856
-		if (isset($data['f_permissions'])) {
857
-			$entryData = $data;
858
-			$entryData['permissions'] = $entryData['f_permissions'];
859
-			$entryData['parent'] = $entryData['f_parent'];;
860
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861
-				\OC::$server->getMimeTypeLoader()));
862
-		}
863
-
864
-		$share->setProviderId($this->identifier());
865
-
866
-		return $share;
867
-	}
868
-
869
-	/**
870
-	 * @param Share[] $shares
871
-	 * @param $userId
872
-	 * @return Share[] The updates shares if no update is found for a share return the original
873
-	 */
874
-	private function resolveGroupShares($shares, $userId) {
875
-		$result = [];
876
-
877
-		$start = 0;
878
-		while(true) {
879
-			/** @var Share[] $shareSlice */
880
-			$shareSlice = array_slice($shares, $start, 100);
881
-			$start += 100;
882
-
883
-			if ($shareSlice === []) {
884
-				break;
885
-			}
886
-
887
-			/** @var int[] $ids */
888
-			$ids = [];
889
-			/** @var Share[] $shareMap */
890
-			$shareMap = [];
891
-
892
-			foreach ($shareSlice as $share) {
893
-				$ids[] = (int)$share->getId();
894
-				$shareMap[$share->getId()] = $share;
895
-			}
896
-
897
-			$qb = $this->dbConn->getQueryBuilder();
898
-
899
-			$query = $qb->select('*')
900
-				->from('share')
901
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
902
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
903
-				->andWhere($qb->expr()->orX(
904
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
905
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
906
-				));
907
-
908
-			$stmt = $query->execute();
909
-
910
-			while($data = $stmt->fetch()) {
911
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
912
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
913
-			}
914
-
915
-			$stmt->closeCursor();
916
-
917
-			foreach ($shareMap as $share) {
918
-				$result[] = $share;
919
-			}
920
-		}
921
-
922
-		return $result;
923
-	}
924
-
925
-	/**
926
-	 * A user is deleted from the system
927
-	 * So clean up the relevant shares.
928
-	 *
929
-	 * @param string $uid
930
-	 * @param int $shareType
931
-	 */
932
-	public function userDeleted($uid, $shareType) {
933
-		$qb = $this->dbConn->getQueryBuilder();
934
-
935
-		$qb->delete('share');
936
-
937
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
938
-			/*
773
+            $shares = $this->resolveGroupShares($shares2, $userId);
774
+        } else {
775
+            throw new BackendError('Invalid backend');
776
+        }
777
+
778
+
779
+        return $shares;
780
+    }
781
+
782
+    /**
783
+     * Get a share by token
784
+     *
785
+     * @param string $token
786
+     * @return \OCP\Share\IShare
787
+     * @throws ShareNotFound
788
+     */
789
+    public function getShareByToken($token) {
790
+        $qb = $this->dbConn->getQueryBuilder();
791
+
792
+        $cursor = $qb->select('*')
793
+            ->from('share')
794
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
795
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
796
+            ->andWhere($qb->expr()->orX(
797
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
798
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
799
+            ))
800
+            ->execute();
801
+
802
+        $data = $cursor->fetch();
803
+
804
+        if ($data === false) {
805
+            throw new ShareNotFound();
806
+        }
807
+
808
+        try {
809
+            $share = $this->createShare($data);
810
+        } catch (InvalidShare $e) {
811
+            throw new ShareNotFound();
812
+        }
813
+
814
+        return $share;
815
+    }
816
+
817
+    /**
818
+     * Create a share object from an database row
819
+     *
820
+     * @param mixed[] $data
821
+     * @return \OCP\Share\IShare
822
+     * @throws InvalidShare
823
+     */
824
+    private function createShare($data) {
825
+        $share = new Share($this->rootFolder, $this->userManager);
826
+        $share->setId((int)$data['id'])
827
+            ->setShareType((int)$data['share_type'])
828
+            ->setPermissions((int)$data['permissions'])
829
+            ->setTarget($data['file_target'])
830
+            ->setMailSend((bool)$data['mail_send']);
831
+
832
+        $shareTime = new \DateTime();
833
+        $shareTime->setTimestamp((int)$data['stime']);
834
+        $share->setShareTime($shareTime);
835
+
836
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
837
+            $share->setSharedWith($data['share_with']);
838
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
839
+            $share->setSharedWith($data['share_with']);
840
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
841
+            $share->setPassword($data['password']);
842
+            $share->setToken($data['token']);
843
+        }
844
+
845
+        $share->setSharedBy($data['uid_initiator']);
846
+        $share->setShareOwner($data['uid_owner']);
847
+
848
+        $share->setNodeId((int)$data['file_source']);
849
+        $share->setNodeType($data['item_type']);
850
+
851
+        if ($data['expiration'] !== null) {
852
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
853
+            $share->setExpirationDate($expiration);
854
+        }
855
+
856
+        if (isset($data['f_permissions'])) {
857
+            $entryData = $data;
858
+            $entryData['permissions'] = $entryData['f_permissions'];
859
+            $entryData['parent'] = $entryData['f_parent'];;
860
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861
+                \OC::$server->getMimeTypeLoader()));
862
+        }
863
+
864
+        $share->setProviderId($this->identifier());
865
+
866
+        return $share;
867
+    }
868
+
869
+    /**
870
+     * @param Share[] $shares
871
+     * @param $userId
872
+     * @return Share[] The updates shares if no update is found for a share return the original
873
+     */
874
+    private function resolveGroupShares($shares, $userId) {
875
+        $result = [];
876
+
877
+        $start = 0;
878
+        while(true) {
879
+            /** @var Share[] $shareSlice */
880
+            $shareSlice = array_slice($shares, $start, 100);
881
+            $start += 100;
882
+
883
+            if ($shareSlice === []) {
884
+                break;
885
+            }
886
+
887
+            /** @var int[] $ids */
888
+            $ids = [];
889
+            /** @var Share[] $shareMap */
890
+            $shareMap = [];
891
+
892
+            foreach ($shareSlice as $share) {
893
+                $ids[] = (int)$share->getId();
894
+                $shareMap[$share->getId()] = $share;
895
+            }
896
+
897
+            $qb = $this->dbConn->getQueryBuilder();
898
+
899
+            $query = $qb->select('*')
900
+                ->from('share')
901
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
902
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
903
+                ->andWhere($qb->expr()->orX(
904
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
905
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
906
+                ));
907
+
908
+            $stmt = $query->execute();
909
+
910
+            while($data = $stmt->fetch()) {
911
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
912
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
913
+            }
914
+
915
+            $stmt->closeCursor();
916
+
917
+            foreach ($shareMap as $share) {
918
+                $result[] = $share;
919
+            }
920
+        }
921
+
922
+        return $result;
923
+    }
924
+
925
+    /**
926
+     * A user is deleted from the system
927
+     * So clean up the relevant shares.
928
+     *
929
+     * @param string $uid
930
+     * @param int $shareType
931
+     */
932
+    public function userDeleted($uid, $shareType) {
933
+        $qb = $this->dbConn->getQueryBuilder();
934
+
935
+        $qb->delete('share');
936
+
937
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
938
+            /*
939 939
 			 * Delete all user shares that are owned by this user
940 940
 			 * or that are received by this user
941 941
 			 */
942 942
 
943
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
943
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
944 944
 
945
-			$qb->andWhere(
946
-				$qb->expr()->orX(
947
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
948
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
949
-				)
950
-			);
951
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
952
-			/*
945
+            $qb->andWhere(
946
+                $qb->expr()->orX(
947
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
948
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
949
+                )
950
+            );
951
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
952
+            /*
953 953
 			 * Delete all group shares that are owned by this user
954 954
 			 * Or special user group shares that are received by this user
955 955
 			 */
956
-			$qb->where(
957
-				$qb->expr()->andX(
958
-					$qb->expr()->orX(
959
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
960
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
961
-					),
962
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
963
-				)
964
-			);
965
-
966
-			$qb->orWhere(
967
-				$qb->expr()->andX(
968
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
969
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
970
-				)
971
-			);
972
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
973
-			/*
956
+            $qb->where(
957
+                $qb->expr()->andX(
958
+                    $qb->expr()->orX(
959
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
960
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
961
+                    ),
962
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
963
+                )
964
+            );
965
+
966
+            $qb->orWhere(
967
+                $qb->expr()->andX(
968
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
969
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
970
+                )
971
+            );
972
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
973
+            /*
974 974
 			 * Delete all link shares owned by this user.
975 975
 			 * And all link shares initiated by this user (until #22327 is in)
976 976
 			 */
977
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
978
-
979
-			$qb->andWhere(
980
-				$qb->expr()->orX(
981
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
982
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
983
-				)
984
-			);
985
-		}
986
-
987
-		$qb->execute();
988
-	}
989
-
990
-	/**
991
-	 * Delete all shares received by this group. As well as any custom group
992
-	 * shares for group members.
993
-	 *
994
-	 * @param string $gid
995
-	 */
996
-	public function groupDeleted($gid) {
997
-		/*
977
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
978
+
979
+            $qb->andWhere(
980
+                $qb->expr()->orX(
981
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
982
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
983
+                )
984
+            );
985
+        }
986
+
987
+        $qb->execute();
988
+    }
989
+
990
+    /**
991
+     * Delete all shares received by this group. As well as any custom group
992
+     * shares for group members.
993
+     *
994
+     * @param string $gid
995
+     */
996
+    public function groupDeleted($gid) {
997
+        /*
998 998
 		 * First delete all custom group shares for group members
999 999
 		 */
1000
-		$qb = $this->dbConn->getQueryBuilder();
1001
-		$qb->select('id')
1002
-			->from('share')
1003
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1004
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1005
-
1006
-		$cursor = $qb->execute();
1007
-		$ids = [];
1008
-		while($row = $cursor->fetch()) {
1009
-			$ids[] = (int)$row['id'];
1010
-		}
1011
-		$cursor->closeCursor();
1012
-
1013
-		if (!empty($ids)) {
1014
-			$chunks = array_chunk($ids, 100);
1015
-			foreach ($chunks as $chunk) {
1016
-				$qb->delete('share')
1017
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1018
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1019
-				$qb->execute();
1020
-			}
1021
-		}
1022
-
1023
-		/*
1000
+        $qb = $this->dbConn->getQueryBuilder();
1001
+        $qb->select('id')
1002
+            ->from('share')
1003
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1004
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1005
+
1006
+        $cursor = $qb->execute();
1007
+        $ids = [];
1008
+        while($row = $cursor->fetch()) {
1009
+            $ids[] = (int)$row['id'];
1010
+        }
1011
+        $cursor->closeCursor();
1012
+
1013
+        if (!empty($ids)) {
1014
+            $chunks = array_chunk($ids, 100);
1015
+            foreach ($chunks as $chunk) {
1016
+                $qb->delete('share')
1017
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1018
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1019
+                $qb->execute();
1020
+            }
1021
+        }
1022
+
1023
+        /*
1024 1024
 		 * Now delete all the group shares
1025 1025
 		 */
1026
-		$qb = $this->dbConn->getQueryBuilder();
1027
-		$qb->delete('share')
1028
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1029
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1030
-		$qb->execute();
1031
-	}
1032
-
1033
-	/**
1034
-	 * Delete custom group shares to this group for this user
1035
-	 *
1036
-	 * @param string $uid
1037
-	 * @param string $gid
1038
-	 */
1039
-	public function userDeletedFromGroup($uid, $gid) {
1040
-		/*
1026
+        $qb = $this->dbConn->getQueryBuilder();
1027
+        $qb->delete('share')
1028
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1029
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1030
+        $qb->execute();
1031
+    }
1032
+
1033
+    /**
1034
+     * Delete custom group shares to this group for this user
1035
+     *
1036
+     * @param string $uid
1037
+     * @param string $gid
1038
+     */
1039
+    public function userDeletedFromGroup($uid, $gid) {
1040
+        /*
1041 1041
 		 * Get all group shares
1042 1042
 		 */
1043
-		$qb = $this->dbConn->getQueryBuilder();
1044
-		$qb->select('id')
1045
-			->from('share')
1046
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1047
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1048
-
1049
-		$cursor = $qb->execute();
1050
-		$ids = [];
1051
-		while($row = $cursor->fetch()) {
1052
-			$ids[] = (int)$row['id'];
1053
-		}
1054
-		$cursor->closeCursor();
1055
-
1056
-		if (!empty($ids)) {
1057
-			$chunks = array_chunk($ids, 100);
1058
-			foreach ($chunks as $chunk) {
1059
-				/*
1043
+        $qb = $this->dbConn->getQueryBuilder();
1044
+        $qb->select('id')
1045
+            ->from('share')
1046
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1047
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1048
+
1049
+        $cursor = $qb->execute();
1050
+        $ids = [];
1051
+        while($row = $cursor->fetch()) {
1052
+            $ids[] = (int)$row['id'];
1053
+        }
1054
+        $cursor->closeCursor();
1055
+
1056
+        if (!empty($ids)) {
1057
+            $chunks = array_chunk($ids, 100);
1058
+            foreach ($chunks as $chunk) {
1059
+                /*
1060 1060
 				 * Delete all special shares wit this users for the found group shares
1061 1061
 				 */
1062
-				$qb->delete('share')
1063
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1064
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1065
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1066
-				$qb->execute();
1067
-			}
1068
-		}
1069
-	}
1062
+                $qb->delete('share')
1063
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1064
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1065
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1066
+                $qb->execute();
1067
+            }
1068
+        }
1069
+    }
1070 1070
 }
Please login to merge, or discard this patch.