Passed
Push — master ( 4ebb20...72b7c9 )
by Roeland
12:19
created
apps/files_sharing/lib/Controller/ShareAPIController.php 2 patches
Indentation   +1126 added lines, -1126 removed lines patch added patch discarded remove patch
@@ -65,1137 +65,1137 @@
 block discarded – undo
65 65
  */
66 66
 class ShareAPIController extends OCSController {
67 67
 
68
-	/** @var IManager */
69
-	private $shareManager;
70
-	/** @var IGroupManager */
71
-	private $groupManager;
72
-	/** @var IUserManager */
73
-	private $userManager;
74
-	/** @var IRootFolder */
75
-	private $rootFolder;
76
-	/** @var IURLGenerator */
77
-	private $urlGenerator;
78
-	/** @var string */
79
-	private $currentUser;
80
-	/** @var IL10N */
81
-	private $l;
82
-	/** @var \OCP\Files\Node */
83
-	private $lockedNode;
84
-	/** @var IConfig */
85
-	private $config;
86
-	/** @var IAppManager */
87
-	private $appManager;
88
-	/** @var IServerContainer */
89
-	private $serverContainer;
90
-
91
-	/**
92
-	 * Share20OCS constructor.
93
-	 *
94
-	 * @param string $appName
95
-	 * @param IRequest $request
96
-	 * @param IManager $shareManager
97
-	 * @param IGroupManager $groupManager
98
-	 * @param IUserManager $userManager
99
-	 * @param IRootFolder $rootFolder
100
-	 * @param IURLGenerator $urlGenerator
101
-	 * @param string $userId
102
-	 * @param IL10N $l10n
103
-	 * @param IConfig $config
104
-	 * @param IAppManager $appManager
105
-	 * @param IServerContainer $serverContainer
106
-	 */
107
-	public function __construct(
108
-		string $appName,
109
-		IRequest $request,
110
-		IManager $shareManager,
111
-		IGroupManager $groupManager,
112
-		IUserManager $userManager,
113
-		IRootFolder $rootFolder,
114
-		IURLGenerator $urlGenerator,
115
-		string $userId = null,
116
-		IL10N $l10n,
117
-		IConfig $config,
118
-		IAppManager $appManager,
119
-		IServerContainer $serverContainer
120
-	) {
121
-		parent::__construct($appName, $request);
122
-
123
-		$this->shareManager = $shareManager;
124
-		$this->userManager = $userManager;
125
-		$this->groupManager = $groupManager;
126
-		$this->request = $request;
127
-		$this->rootFolder = $rootFolder;
128
-		$this->urlGenerator = $urlGenerator;
129
-		$this->currentUser = $userId;
130
-		$this->l = $l10n;
131
-		$this->config = $config;
132
-		$this->appManager = $appManager;
133
-		$this->serverContainer = $serverContainer;
134
-	}
135
-
136
-	/**
137
-	 * Convert an IShare to an array for OCS output
138
-	 *
139
-	 * @param \OCP\Share\IShare $share
140
-	 * @param Node|null $recipientNode
141
-	 * @return array
142
-	 * @throws NotFoundException In case the node can't be resolved.
143
-	 *
144
-	 * @suppress PhanUndeclaredClassMethod
145
-	 */
146
-	protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null): array {
147
-		$sharedBy = $this->userManager->get($share->getSharedBy());
148
-		$shareOwner = $this->userManager->get($share->getShareOwner());
149
-
150
-		$result = [
151
-			'id' => $share->getId(),
152
-			'share_type' => $share->getShareType(),
153
-			'uid_owner' => $share->getSharedBy(),
154
-			'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
155
-			'permissions' => $share->getPermissions(),
156
-			'stime' => $share->getShareTime()->getTimestamp(),
157
-			'parent' => null,
158
-			'expiration' => null,
159
-			'token' => null,
160
-			'uid_file_owner' => $share->getShareOwner(),
161
-			'note' => $share->getNote(),
162
-			'label' => $share->getLabel(),
163
-			'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
164
-		];
165
-
166
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
167
-		if ($recipientNode) {
168
-			$node = $recipientNode;
169
-		} else {
170
-			$nodes = $userFolder->getById($share->getNodeId());
171
-			if (empty($nodes)) {
172
-				// fallback to guessing the path
173
-				$node = $userFolder->get($share->getTarget());
174
-				if ($node === null || $share->getTarget() === '') {
175
-					throw new NotFoundException();
176
-				}
177
-			} else {
178
-				$node = $nodes[0];
179
-			}
180
-		}
181
-
182
-		$result['path'] = $userFolder->getRelativePath($node->getPath());
183
-		if ($node instanceOf \OCP\Files\Folder) {
184
-			$result['item_type'] = 'folder';
185
-		} else {
186
-			$result['item_type'] = 'file';
187
-		}
188
-		$result['mimetype'] = $node->getMimetype();
189
-		$result['storage_id'] = $node->getStorage()->getId();
190
-		$result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
191
-		$result['item_source'] = $node->getId();
192
-		$result['file_source'] = $node->getId();
193
-		$result['file_parent'] = $node->getParent()->getId();
194
-		$result['file_target'] = $share->getTarget();
195
-
196
-		$expiration = $share->getExpirationDate();
197
-		if ($expiration !== null) {
198
-			$result['expiration'] = $expiration->format('Y-m-d 00:00:00');
199
-		}
200
-
201
-		if ($share->getShareType() === Share::SHARE_TYPE_USER) {
202
-			$sharedWith = $this->userManager->get($share->getSharedWith());
203
-			$result['share_with'] = $share->getSharedWith();
204
-			$result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
205
-		} else if ($share->getShareType() === Share::SHARE_TYPE_GROUP) {
206
-			$group = $this->groupManager->get($share->getSharedWith());
207
-			$result['share_with'] = $share->getSharedWith();
208
-			$result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
209
-		} else if ($share->getShareType() === Share::SHARE_TYPE_LINK) {
210
-
211
-			$result['share_with'] = $share->getPassword();
212
-			$result['share_with_displayname'] = $share->getPassword();
213
-
214
-			$result['send_password_by_talk'] = $share->getSendPasswordByTalk();
215
-
216
-			$result['token'] = $share->getToken();
217
-			$result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
218
-
219
-		} else if ($share->getShareType() === Share::SHARE_TYPE_REMOTE || $share->getShareType() === Share::SHARE_TYPE_REMOTE_GROUP) {
220
-			$result['share_with'] = $share->getSharedWith();
221
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
222
-			$result['token'] = $share->getToken();
223
-		} else if ($share->getShareType() === Share::SHARE_TYPE_EMAIL) {
224
-			$result['share_with'] = $share->getSharedWith();
225
-			$result['password'] = $share->getPassword();
226
-			$result['send_password_by_talk'] = $share->getSendPasswordByTalk();
227
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
228
-			$result['token'] = $share->getToken();
229
-		} else if ($share->getShareType() === Share::SHARE_TYPE_CIRCLE) {
230
-			// getSharedWith() returns either "name (type, owner)" or
231
-			// "name (type, owner) [id]", depending on the Circles app version.
232
-			$hasCircleId = (substr($share->getSharedWith(), -1) === ']');
233
-
234
-			$result['share_with_displayname'] = $share->getSharedWithDisplayName();
235
-			if (empty($result['share_with_displayname'])) {
236
-				$displayNameLength = ($hasCircleId? strrpos($share->getSharedWith(), ' '): strlen($share->getSharedWith()));
237
-				$result['share_with_displayname'] = substr($share->getSharedWith(), 0, $displayNameLength);
238
-			}
239
-
240
-			$result['share_with_avatar'] = $share->getSharedWithAvatar();
241
-
242
-			$shareWithStart = ($hasCircleId? strrpos($share->getSharedWith(), '[') + 1: 0);
243
-			$shareWithLength = ($hasCircleId? -1: strpos($share->getSharedWith(), ' '));
244
-			if (is_bool($shareWithLength)) {
245
-				$shareWithLength = -1;
246
-			}
247
-			$result['share_with'] = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
248
-		} else if ($share->getShareType() === Share::SHARE_TYPE_ROOM) {
249
-			$result['share_with'] = $share->getSharedWith();
250
-			$result['share_with_displayname'] = '';
251
-
252
-			try {
253
-				$result = array_merge($result, $this->getRoomShareHelper()->formatShare($share));
254
-			} catch (QueryException $e) {
255
-			}
256
-		}
257
-
258
-
259
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
260
-		$result['hide_download'] = $share->getHideDownload() ? 1 : 0;
261
-
262
-		return $result;
263
-	}
264
-
265
-	/**
266
-	 * Check if one of the users address books knows the exact property, if
267
-	 * yes we return the full name.
268
-	 *
269
-	 * @param string $query
270
-	 * @param string $property
271
-	 * @return string
272
-	 */
273
-	private function getDisplayNameFromAddressBook(string $query, string $property): string {
274
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
275
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
276
-		foreach ($result as $r) {
277
-			foreach($r[$property] as $value) {
278
-				if ($value === $query) {
279
-					return $r['FN'];
280
-				}
281
-			}
282
-		}
283
-
284
-		return $query;
285
-	}
286
-
287
-	/**
288
-	 * Get a specific share by id
289
-	 *
290
-	 * @NoAdminRequired
291
-	 *
292
-	 * @param string $id
293
-	 * @return DataResponse
294
-	 * @throws OCSNotFoundException
295
-	 */
296
-	public function getShare(string $id): DataResponse {
297
-		try {
298
-			$share = $this->getShareById($id);
299
-		} catch (ShareNotFound $e) {
300
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
301
-		}
302
-
303
-		if ($this->canAccessShare($share)) {
304
-			try {
305
-				$share = $this->formatShare($share);
306
-				return new DataResponse([$share]);
307
-			} catch (NotFoundException $e) {
308
-				//Fall trough
309
-			}
310
-		}
311
-
312
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
313
-	}
314
-
315
-	/**
316
-	 * Delete a share
317
-	 *
318
-	 * @NoAdminRequired
319
-	 *
320
-	 * @param string $id
321
-	 * @return DataResponse
322
-	 * @throws OCSNotFoundException
323
-	 */
324
-	public function deleteShare(string $id): DataResponse {
325
-		try {
326
-			$share = $this->getShareById($id);
327
-		} catch (ShareNotFound $e) {
328
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
329
-		}
330
-
331
-		try {
332
-			$this->lock($share->getNode());
333
-		} catch (LockedException $e) {
334
-			throw new OCSNotFoundException($this->l->t('could not delete share'));
335
-		}
336
-
337
-		if (!$this->canAccessShare($share)) {
338
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
339
-		}
340
-
341
-		if (($share->getShareType() === Share::SHARE_TYPE_GROUP ||
342
-				$share->getShareType() === Share::SHARE_TYPE_ROOM) &&
343
-			$share->getShareOwner() !== $this->currentUser &&
344
-			$share->getSharedBy() !== $this->currentUser) {
345
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
346
-		} else {
347
-			$this->shareManager->deleteShare($share);
348
-		}
349
-
350
-		return new DataResponse();
351
-	}
352
-
353
-	/**
354
-	 * @NoAdminRequired
355
-	 *
356
-	 * @param string $path
357
-	 * @param int $permissions
358
-	 * @param int $shareType
359
-	 * @param string $shareWith
360
-	 * @param string $publicUpload
361
-	 * @param string $password
362
-	 * @param string $sendPasswordByTalk
363
-	 * @param string $expireDate
364
-	 * @param string $label
365
-	 *
366
-	 * @return DataResponse
367
-	 * @throws NotFoundException
368
-	 * @throws OCSBadRequestException
369
-	 * @throws OCSException
370
-	 * @throws OCSForbiddenException
371
-	 * @throws OCSNotFoundException
372
-	 * @throws \OCP\Files\InvalidPathException
373
-	 * @suppress PhanUndeclaredClassMethod
374
-	 */
375
-	public function createShare(
376
-		string $path = null,
377
-		int $permissions = null,
378
-		int $shareType = -1,
379
-		string $shareWith = null,
380
-		string $publicUpload = 'false',
381
-		string $password = '',
382
-		string $sendPasswordByTalk = null,
383
-		string $expireDate = '',
384
-		string $label = ''
385
-	): DataResponse {
386
-		$share = $this->shareManager->newShare();
387
-
388
-		if ($permissions === null) {
389
-			$permissions = $this->config->getAppValue('core', 'shareapi_default_permissions', Constants::PERMISSION_ALL);
390
-		}
391
-
392
-		// Verify path
393
-		if ($path === null) {
394
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
395
-		}
396
-
397
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
398
-		try {
399
-			$path = $userFolder->get($path);
400
-		} catch (NotFoundException $e) {
401
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
402
-		}
403
-
404
-		$share->setNode($path);
405
-
406
-		try {
407
-			$this->lock($share->getNode());
408
-		} catch (LockedException $e) {
409
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
410
-		}
411
-
412
-		if ($permissions < 0 || $permissions > Constants::PERMISSION_ALL) {
413
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
414
-		}
415
-
416
-		// Shares always require read permissions
417
-		$permissions |= Constants::PERMISSION_READ;
418
-
419
-		if ($path instanceof \OCP\Files\File) {
420
-			// Single file shares should never have delete or create permissions
421
-			$permissions &= ~Constants::PERMISSION_DELETE;
422
-			$permissions &= ~Constants::PERMISSION_CREATE;
423
-		}
424
-
425
-		/*
68
+    /** @var IManager */
69
+    private $shareManager;
70
+    /** @var IGroupManager */
71
+    private $groupManager;
72
+    /** @var IUserManager */
73
+    private $userManager;
74
+    /** @var IRootFolder */
75
+    private $rootFolder;
76
+    /** @var IURLGenerator */
77
+    private $urlGenerator;
78
+    /** @var string */
79
+    private $currentUser;
80
+    /** @var IL10N */
81
+    private $l;
82
+    /** @var \OCP\Files\Node */
83
+    private $lockedNode;
84
+    /** @var IConfig */
85
+    private $config;
86
+    /** @var IAppManager */
87
+    private $appManager;
88
+    /** @var IServerContainer */
89
+    private $serverContainer;
90
+
91
+    /**
92
+     * Share20OCS constructor.
93
+     *
94
+     * @param string $appName
95
+     * @param IRequest $request
96
+     * @param IManager $shareManager
97
+     * @param IGroupManager $groupManager
98
+     * @param IUserManager $userManager
99
+     * @param IRootFolder $rootFolder
100
+     * @param IURLGenerator $urlGenerator
101
+     * @param string $userId
102
+     * @param IL10N $l10n
103
+     * @param IConfig $config
104
+     * @param IAppManager $appManager
105
+     * @param IServerContainer $serverContainer
106
+     */
107
+    public function __construct(
108
+        string $appName,
109
+        IRequest $request,
110
+        IManager $shareManager,
111
+        IGroupManager $groupManager,
112
+        IUserManager $userManager,
113
+        IRootFolder $rootFolder,
114
+        IURLGenerator $urlGenerator,
115
+        string $userId = null,
116
+        IL10N $l10n,
117
+        IConfig $config,
118
+        IAppManager $appManager,
119
+        IServerContainer $serverContainer
120
+    ) {
121
+        parent::__construct($appName, $request);
122
+
123
+        $this->shareManager = $shareManager;
124
+        $this->userManager = $userManager;
125
+        $this->groupManager = $groupManager;
126
+        $this->request = $request;
127
+        $this->rootFolder = $rootFolder;
128
+        $this->urlGenerator = $urlGenerator;
129
+        $this->currentUser = $userId;
130
+        $this->l = $l10n;
131
+        $this->config = $config;
132
+        $this->appManager = $appManager;
133
+        $this->serverContainer = $serverContainer;
134
+    }
135
+
136
+    /**
137
+     * Convert an IShare to an array for OCS output
138
+     *
139
+     * @param \OCP\Share\IShare $share
140
+     * @param Node|null $recipientNode
141
+     * @return array
142
+     * @throws NotFoundException In case the node can't be resolved.
143
+     *
144
+     * @suppress PhanUndeclaredClassMethod
145
+     */
146
+    protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null): array {
147
+        $sharedBy = $this->userManager->get($share->getSharedBy());
148
+        $shareOwner = $this->userManager->get($share->getShareOwner());
149
+
150
+        $result = [
151
+            'id' => $share->getId(),
152
+            'share_type' => $share->getShareType(),
153
+            'uid_owner' => $share->getSharedBy(),
154
+            'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
155
+            'permissions' => $share->getPermissions(),
156
+            'stime' => $share->getShareTime()->getTimestamp(),
157
+            'parent' => null,
158
+            'expiration' => null,
159
+            'token' => null,
160
+            'uid_file_owner' => $share->getShareOwner(),
161
+            'note' => $share->getNote(),
162
+            'label' => $share->getLabel(),
163
+            'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
164
+        ];
165
+
166
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
167
+        if ($recipientNode) {
168
+            $node = $recipientNode;
169
+        } else {
170
+            $nodes = $userFolder->getById($share->getNodeId());
171
+            if (empty($nodes)) {
172
+                // fallback to guessing the path
173
+                $node = $userFolder->get($share->getTarget());
174
+                if ($node === null || $share->getTarget() === '') {
175
+                    throw new NotFoundException();
176
+                }
177
+            } else {
178
+                $node = $nodes[0];
179
+            }
180
+        }
181
+
182
+        $result['path'] = $userFolder->getRelativePath($node->getPath());
183
+        if ($node instanceOf \OCP\Files\Folder) {
184
+            $result['item_type'] = 'folder';
185
+        } else {
186
+            $result['item_type'] = 'file';
187
+        }
188
+        $result['mimetype'] = $node->getMimetype();
189
+        $result['storage_id'] = $node->getStorage()->getId();
190
+        $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
191
+        $result['item_source'] = $node->getId();
192
+        $result['file_source'] = $node->getId();
193
+        $result['file_parent'] = $node->getParent()->getId();
194
+        $result['file_target'] = $share->getTarget();
195
+
196
+        $expiration = $share->getExpirationDate();
197
+        if ($expiration !== null) {
198
+            $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
199
+        }
200
+
201
+        if ($share->getShareType() === Share::SHARE_TYPE_USER) {
202
+            $sharedWith = $this->userManager->get($share->getSharedWith());
203
+            $result['share_with'] = $share->getSharedWith();
204
+            $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
205
+        } else if ($share->getShareType() === Share::SHARE_TYPE_GROUP) {
206
+            $group = $this->groupManager->get($share->getSharedWith());
207
+            $result['share_with'] = $share->getSharedWith();
208
+            $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
209
+        } else if ($share->getShareType() === Share::SHARE_TYPE_LINK) {
210
+
211
+            $result['share_with'] = $share->getPassword();
212
+            $result['share_with_displayname'] = $share->getPassword();
213
+
214
+            $result['send_password_by_talk'] = $share->getSendPasswordByTalk();
215
+
216
+            $result['token'] = $share->getToken();
217
+            $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
218
+
219
+        } else if ($share->getShareType() === Share::SHARE_TYPE_REMOTE || $share->getShareType() === Share::SHARE_TYPE_REMOTE_GROUP) {
220
+            $result['share_with'] = $share->getSharedWith();
221
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
222
+            $result['token'] = $share->getToken();
223
+        } else if ($share->getShareType() === Share::SHARE_TYPE_EMAIL) {
224
+            $result['share_with'] = $share->getSharedWith();
225
+            $result['password'] = $share->getPassword();
226
+            $result['send_password_by_talk'] = $share->getSendPasswordByTalk();
227
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
228
+            $result['token'] = $share->getToken();
229
+        } else if ($share->getShareType() === Share::SHARE_TYPE_CIRCLE) {
230
+            // getSharedWith() returns either "name (type, owner)" or
231
+            // "name (type, owner) [id]", depending on the Circles app version.
232
+            $hasCircleId = (substr($share->getSharedWith(), -1) === ']');
233
+
234
+            $result['share_with_displayname'] = $share->getSharedWithDisplayName();
235
+            if (empty($result['share_with_displayname'])) {
236
+                $displayNameLength = ($hasCircleId? strrpos($share->getSharedWith(), ' '): strlen($share->getSharedWith()));
237
+                $result['share_with_displayname'] = substr($share->getSharedWith(), 0, $displayNameLength);
238
+            }
239
+
240
+            $result['share_with_avatar'] = $share->getSharedWithAvatar();
241
+
242
+            $shareWithStart = ($hasCircleId? strrpos($share->getSharedWith(), '[') + 1: 0);
243
+            $shareWithLength = ($hasCircleId? -1: strpos($share->getSharedWith(), ' '));
244
+            if (is_bool($shareWithLength)) {
245
+                $shareWithLength = -1;
246
+            }
247
+            $result['share_with'] = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
248
+        } else if ($share->getShareType() === Share::SHARE_TYPE_ROOM) {
249
+            $result['share_with'] = $share->getSharedWith();
250
+            $result['share_with_displayname'] = '';
251
+
252
+            try {
253
+                $result = array_merge($result, $this->getRoomShareHelper()->formatShare($share));
254
+            } catch (QueryException $e) {
255
+            }
256
+        }
257
+
258
+
259
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
260
+        $result['hide_download'] = $share->getHideDownload() ? 1 : 0;
261
+
262
+        return $result;
263
+    }
264
+
265
+    /**
266
+     * Check if one of the users address books knows the exact property, if
267
+     * yes we return the full name.
268
+     *
269
+     * @param string $query
270
+     * @param string $property
271
+     * @return string
272
+     */
273
+    private function getDisplayNameFromAddressBook(string $query, string $property): string {
274
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
275
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
276
+        foreach ($result as $r) {
277
+            foreach($r[$property] as $value) {
278
+                if ($value === $query) {
279
+                    return $r['FN'];
280
+                }
281
+            }
282
+        }
283
+
284
+        return $query;
285
+    }
286
+
287
+    /**
288
+     * Get a specific share by id
289
+     *
290
+     * @NoAdminRequired
291
+     *
292
+     * @param string $id
293
+     * @return DataResponse
294
+     * @throws OCSNotFoundException
295
+     */
296
+    public function getShare(string $id): DataResponse {
297
+        try {
298
+            $share = $this->getShareById($id);
299
+        } catch (ShareNotFound $e) {
300
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
301
+        }
302
+
303
+        if ($this->canAccessShare($share)) {
304
+            try {
305
+                $share = $this->formatShare($share);
306
+                return new DataResponse([$share]);
307
+            } catch (NotFoundException $e) {
308
+                //Fall trough
309
+            }
310
+        }
311
+
312
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
313
+    }
314
+
315
+    /**
316
+     * Delete a share
317
+     *
318
+     * @NoAdminRequired
319
+     *
320
+     * @param string $id
321
+     * @return DataResponse
322
+     * @throws OCSNotFoundException
323
+     */
324
+    public function deleteShare(string $id): DataResponse {
325
+        try {
326
+            $share = $this->getShareById($id);
327
+        } catch (ShareNotFound $e) {
328
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
329
+        }
330
+
331
+        try {
332
+            $this->lock($share->getNode());
333
+        } catch (LockedException $e) {
334
+            throw new OCSNotFoundException($this->l->t('could not delete share'));
335
+        }
336
+
337
+        if (!$this->canAccessShare($share)) {
338
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
339
+        }
340
+
341
+        if (($share->getShareType() === Share::SHARE_TYPE_GROUP ||
342
+                $share->getShareType() === Share::SHARE_TYPE_ROOM) &&
343
+            $share->getShareOwner() !== $this->currentUser &&
344
+            $share->getSharedBy() !== $this->currentUser) {
345
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
346
+        } else {
347
+            $this->shareManager->deleteShare($share);
348
+        }
349
+
350
+        return new DataResponse();
351
+    }
352
+
353
+    /**
354
+     * @NoAdminRequired
355
+     *
356
+     * @param string $path
357
+     * @param int $permissions
358
+     * @param int $shareType
359
+     * @param string $shareWith
360
+     * @param string $publicUpload
361
+     * @param string $password
362
+     * @param string $sendPasswordByTalk
363
+     * @param string $expireDate
364
+     * @param string $label
365
+     *
366
+     * @return DataResponse
367
+     * @throws NotFoundException
368
+     * @throws OCSBadRequestException
369
+     * @throws OCSException
370
+     * @throws OCSForbiddenException
371
+     * @throws OCSNotFoundException
372
+     * @throws \OCP\Files\InvalidPathException
373
+     * @suppress PhanUndeclaredClassMethod
374
+     */
375
+    public function createShare(
376
+        string $path = null,
377
+        int $permissions = null,
378
+        int $shareType = -1,
379
+        string $shareWith = null,
380
+        string $publicUpload = 'false',
381
+        string $password = '',
382
+        string $sendPasswordByTalk = null,
383
+        string $expireDate = '',
384
+        string $label = ''
385
+    ): DataResponse {
386
+        $share = $this->shareManager->newShare();
387
+
388
+        if ($permissions === null) {
389
+            $permissions = $this->config->getAppValue('core', 'shareapi_default_permissions', Constants::PERMISSION_ALL);
390
+        }
391
+
392
+        // Verify path
393
+        if ($path === null) {
394
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
395
+        }
396
+
397
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
398
+        try {
399
+            $path = $userFolder->get($path);
400
+        } catch (NotFoundException $e) {
401
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
402
+        }
403
+
404
+        $share->setNode($path);
405
+
406
+        try {
407
+            $this->lock($share->getNode());
408
+        } catch (LockedException $e) {
409
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
410
+        }
411
+
412
+        if ($permissions < 0 || $permissions > Constants::PERMISSION_ALL) {
413
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
414
+        }
415
+
416
+        // Shares always require read permissions
417
+        $permissions |= Constants::PERMISSION_READ;
418
+
419
+        if ($path instanceof \OCP\Files\File) {
420
+            // Single file shares should never have delete or create permissions
421
+            $permissions &= ~Constants::PERMISSION_DELETE;
422
+            $permissions &= ~Constants::PERMISSION_CREATE;
423
+        }
424
+
425
+        /*
426 426
 		 * Hack for https://github.com/owncloud/core/issues/22587
427 427
 		 * We check the permissions via webdav. But the permissions of the mount point
428 428
 		 * do not equal the share permissions. Here we fix that for federated mounts.
429 429
 		 */
430
-		if ($path->getStorage()->instanceOfStorage(Storage::class)) {
431
-			$permissions &= ~($permissions & ~$path->getPermissions());
432
-		}
433
-
434
-		if ($shareType === Share::SHARE_TYPE_USER) {
435
-			// Valid user is required to share
436
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
437
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
438
-			}
439
-			$share->setSharedWith($shareWith);
440
-			$share->setPermissions($permissions);
441
-		} else if ($shareType === Share::SHARE_TYPE_GROUP) {
442
-			if (!$this->shareManager->allowGroupSharing()) {
443
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
444
-			}
445
-
446
-			// Valid group is required to share
447
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
448
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
449
-			}
450
-			$share->setSharedWith($shareWith);
451
-			$share->setPermissions($permissions);
452
-		} else if ($shareType === Share::SHARE_TYPE_LINK) {
453
-			//Can we even share links?
454
-			if (!$this->shareManager->shareApiAllowLinks()) {
455
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
456
-			}
457
-
458
-			if ($publicUpload === 'true') {
459
-				// Check if public upload is allowed
460
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
461
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
462
-				}
463
-
464
-				// Public upload can only be set for folders
465
-				if ($path instanceof \OCP\Files\File) {
466
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
467
-				}
468
-
469
-				$share->setPermissions(
470
-					Constants::PERMISSION_READ |
471
-					Constants::PERMISSION_CREATE |
472
-					Constants::PERMISSION_UPDATE |
473
-					Constants::PERMISSION_DELETE
474
-				);
475
-			} else {
476
-				$share->setPermissions(Constants::PERMISSION_READ);
477
-			}
478
-
479
-			// Set password
480
-			if ($password !== '') {
481
-				$share->setPassword($password);
482
-			}
483
-
484
-
485
-			if (!empty($label)) {
486
-				$share->setLabel($label);
487
-			}
488
-
489
-			if ($sendPasswordByTalk === 'true') {
490
-				if (!$this->appManager->isEnabledForUser('spreed')) {
491
-					throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$path->getPath()]));
492
-				}
493
-
494
-				$share->setSendPasswordByTalk(true);
495
-			}
496
-
497
-			//Expire date
498
-			if ($expireDate !== '') {
499
-				try {
500
-					$expireDate = $this->parseDate($expireDate);
501
-					$share->setExpirationDate($expireDate);
502
-				} catch (\Exception $e) {
503
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
504
-				}
505
-			}
506
-
507
-		} else if ($shareType === Share::SHARE_TYPE_REMOTE) {
508
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
509
-				throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
510
-			}
511
-
512
-			$share->setSharedWith($shareWith);
513
-			$share->setPermissions($permissions);
514
-		}  else if ($shareType === Share::SHARE_TYPE_REMOTE_GROUP) {
515
-			if (!$this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
516
-				throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
517
-			}
518
-
519
-			$share->setSharedWith($shareWith);
520
-			$share->setPermissions($permissions);
521
-		} else if ($shareType === Share::SHARE_TYPE_EMAIL) {
522
-			if ($share->getNodeType() === 'file') {
523
-				$share->setPermissions(Constants::PERMISSION_READ);
524
-			} else {
525
-				$share->setPermissions($permissions);
526
-			}
527
-			$share->setSharedWith($shareWith);
528
-
529
-			if ($sendPasswordByTalk === 'true') {
530
-				if (!$this->appManager->isEnabledForUser('spreed')) {
531
-					throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$path->getPath()]));
532
-				}
533
-
534
-				$share->setSendPasswordByTalk(true);
535
-			}
536
-		} else if ($shareType === Share::SHARE_TYPE_CIRCLE) {
537
-			if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
538
-				throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
539
-			}
540
-
541
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
542
-
543
-			// Valid circle is required to share
544
-			if ($circle === null) {
545
-				throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
546
-			}
547
-			$share->setSharedWith($shareWith);
548
-			$share->setPermissions($permissions);
549
-		} else if ($shareType === Share::SHARE_TYPE_ROOM) {
550
-			try {
551
-				$this->getRoomShareHelper()->createShare($share, $shareWith, $permissions, $expireDate);
552
-			} catch (QueryException $e) {
553
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$path->getPath()]));
554
-			}
555
-		} else {
556
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
557
-		}
558
-
559
-		$share->setShareType($shareType);
560
-		$share->setSharedBy($this->currentUser);
561
-
562
-		try {
563
-			$share = $this->shareManager->createShare($share);
564
-		} catch (GenericShareException $e) {
565
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
566
-			throw new OCSException($e->getHint(), $code);
567
-		} catch (\Exception $e) {
568
-			throw new OCSForbiddenException($e->getMessage(), $e);
569
-		}
570
-
571
-		$output = $this->formatShare($share);
572
-
573
-		return new DataResponse($output);
574
-	}
575
-
576
-	/**
577
-	 * @param \OCP\Files\File|\OCP\Files\Folder $node
578
-	 * @param boolean $includeTags
579
-	 * @return DataResponse
580
-	 */
581
-	private function getSharedWithMe($node = null, bool $includeTags): DataResponse {
582
-
583
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_USER, $node, -1, 0);
584
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_GROUP, $node, -1, 0);
585
-		$circleShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
586
-		$roomShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_ROOM, $node, -1, 0);
587
-
588
-		$shares = array_merge($userShares, $groupShares, $circleShares, $roomShares);
589
-
590
-		$shares = array_filter($shares, function (IShare $share) {
591
-			return $share->getShareOwner() !== $this->currentUser;
592
-		});
593
-
594
-		$formatted = [];
595
-		foreach ($shares as $share) {
596
-			if ($this->canAccessShare($share)) {
597
-				try {
598
-					$formatted[] = $this->formatShare($share);
599
-				} catch (NotFoundException $e) {
600
-					// Ignore this share
601
-				}
602
-			}
603
-		}
604
-
605
-		if ($includeTags) {
606
-			$formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
607
-		}
608
-
609
-		return new DataResponse($formatted);
610
-	}
611
-
612
-	/**
613
-	 * @param \OCP\Files\Folder $folder
614
-	 * @return DataResponse
615
-	 * @throws OCSBadRequestException
616
-	 */
617
-	private function getSharesInDir(Node $folder): DataResponse {
618
-		if (!($folder instanceof \OCP\Files\Folder)) {
619
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
620
-		}
621
-
622
-		$nodes = $folder->getDirectoryListing();
623
-		/** @var \OCP\Share\IShare[] $shares */
624
-		$shares = [];
625
-		foreach ($nodes as $node) {
626
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_USER, $node, false, -1, 0));
627
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
628
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_LINK, $node, false, -1, 0));
629
-			if($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
630
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
631
-			}
632
-			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
633
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
634
-			}
635
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_ROOM, $node, false, -1, 0));
636
-		}
637
-
638
-		$formatted = [];
639
-		foreach ($shares as $share) {
640
-			try {
641
-				$formatted[] = $this->formatShare($share);
642
-			} catch (NotFoundException $e) {
643
-				//Ignore this share
644
-			}
645
-		}
646
-
647
-		return new DataResponse($formatted);
648
-	}
649
-
650
-	/**
651
-	 * The getShares function.
652
-	 *
653
-	 * @NoAdminRequired
654
-	 *
655
-	 * @param string $shared_with_me
656
-	 * @param string $reshares
657
-	 * @param string $subfiles
658
-	 * @param string $path
659
-	 *
660
-	 * - Get shares by the current user
661
-	 * - Get shares by the current user and reshares (?reshares=true)
662
-	 * - Get shares with the current user (?shared_with_me=true)
663
-	 * - Get shares for a specific path (?path=...)
664
-	 * - Get all shares in a folder (?subfiles=true&path=..)
665
-	 *
666
-	 * @return DataResponse
667
-	 * @throws OCSNotFoundException
668
-	 */
669
-	public function getShares(
670
-		string $shared_with_me = 'false',
671
-		string $reshares = 'false',
672
-		string $subfiles = 'false',
673
-		string $path = null,
674
-		string $include_tags = 'false'
675
-	): DataResponse {
676
-
677
-		if ($path !== null) {
678
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
679
-			try {
680
-				$path = $userFolder->get($path);
681
-				$this->lock($path);
682
-			} catch (\OCP\Files\NotFoundException $e) {
683
-				throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
684
-			} catch (LockedException $e) {
685
-				throw new OCSNotFoundException($this->l->t('Could not lock path'));
686
-			}
687
-		}
688
-
689
-		$include_tags = $include_tags === 'true';
690
-
691
-		if ($shared_with_me === 'true') {
692
-			$result = $this->getSharedWithMe($path, $include_tags);
693
-			return $result;
694
-		}
695
-
696
-		if ($subfiles === 'true') {
697
-			$result = $this->getSharesInDir($path);
698
-			return $result;
699
-		}
700
-
701
-		if ($reshares === 'true') {
702
-			$reshares = true;
703
-		} else {
704
-			$reshares = false;
705
-		}
706
-
707
-		// Get all shares
708
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
709
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
710
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
711
-		if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
712
-			$mailShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
713
-		} else {
714
-			$mailShares = [];
715
-		}
716
-		if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_CIRCLE)) {
717
-			$circleShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
718
-		} else {
719
-			$circleShares = [];
720
-		}
721
-		$roomShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_ROOM, $path, $reshares, -1, 0);
722
-
723
-		$shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares, $roomShares);
724
-
725
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
726
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
727
-			$shares = array_merge($shares, $federatedShares);
728
-		}
729
-
730
-		if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
731
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_REMOTE_GROUP, $path, $reshares, -1, 0);
732
-			$shares = array_merge($shares, $federatedShares);
733
-		}
734
-
735
-		$formatted = $miniFormatted = [];
736
-		$resharingRight = false;
737
-		foreach ($shares as $share) {
738
-			/** @var IShare $share */
739
-			try {
740
-				$format = $this->formatShare($share, $path);
741
-				$formatted[] = $format;
742
-				if ($share->getSharedBy() === $this->currentUser) {
743
-					$miniFormatted[] = $format;
744
-				}
745
-
746
-				if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $path)) {
747
-					$resharingRight = true;
748
-				}
749
-			} catch (\Exception $e) {
750
-				//Ignore share
751
-			}
752
-		}
753
-
754
-		if (!$resharingRight) {
755
-			$formatted = $miniFormatted;
756
-		}
757
-
758
-		if ($include_tags) {
759
-			$formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
760
-		}
761
-
762
-		return new DataResponse($formatted);
763
-	}
764
-
765
-	/**
766
-	 * @NoAdminRequired
767
-	 *
768
-	 * @param string $id
769
-	 * @param int $permissions
770
-	 * @param string $password
771
-	 * @param string $sendPasswordByTalk
772
-	 * @param string $publicUpload
773
-	 * @param string $expireDate
774
-	 * @param string $note
775
-	 * @param string $label
776
-	 * @param string $hideDownload
777
-	 * @return DataResponse
778
-	 * @throws LockedException
779
-	 * @throws NotFoundException
780
-	 * @throws OCSBadRequestException
781
-	 * @throws OCSForbiddenException
782
-	 * @throws OCSNotFoundException
783
-	 */
784
-	public function updateShare(
785
-		string $id,
786
-		int $permissions = null,
787
-		string $password = null,
788
-		string $sendPasswordByTalk = null,
789
-		string $publicUpload = null,
790
-		string $expireDate = null,
791
-		string $note = null,
792
-		string $label = null,
793
-		string $hideDownload = null
794
-	): DataResponse {
795
-		try {
796
-			$share = $this->getShareById($id);
797
-		} catch (ShareNotFound $e) {
798
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
799
-		}
800
-
801
-		$this->lock($share->getNode());
802
-
803
-		if (!$this->canAccessShare($share, false)) {
804
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
805
-		}
806
-
807
-		if ($permissions === null &&
808
-			$password === null &&
809
-			$sendPasswordByTalk === null &&
810
-			$publicUpload === null &&
811
-			$expireDate === null &&
812
-			$note === null &&
813
-			$label === null &&
814
-			$hideDownload === null
815
-		) {
816
-			throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
817
-		}
818
-
819
-		if($note !== null) {
820
-			$share->setNote($note);
821
-		}
822
-
823
-		/*
430
+        if ($path->getStorage()->instanceOfStorage(Storage::class)) {
431
+            $permissions &= ~($permissions & ~$path->getPermissions());
432
+        }
433
+
434
+        if ($shareType === Share::SHARE_TYPE_USER) {
435
+            // Valid user is required to share
436
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
437
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
438
+            }
439
+            $share->setSharedWith($shareWith);
440
+            $share->setPermissions($permissions);
441
+        } else if ($shareType === Share::SHARE_TYPE_GROUP) {
442
+            if (!$this->shareManager->allowGroupSharing()) {
443
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
444
+            }
445
+
446
+            // Valid group is required to share
447
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
448
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
449
+            }
450
+            $share->setSharedWith($shareWith);
451
+            $share->setPermissions($permissions);
452
+        } else if ($shareType === Share::SHARE_TYPE_LINK) {
453
+            //Can we even share links?
454
+            if (!$this->shareManager->shareApiAllowLinks()) {
455
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
456
+            }
457
+
458
+            if ($publicUpload === 'true') {
459
+                // Check if public upload is allowed
460
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
461
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
462
+                }
463
+
464
+                // Public upload can only be set for folders
465
+                if ($path instanceof \OCP\Files\File) {
466
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
467
+                }
468
+
469
+                $share->setPermissions(
470
+                    Constants::PERMISSION_READ |
471
+                    Constants::PERMISSION_CREATE |
472
+                    Constants::PERMISSION_UPDATE |
473
+                    Constants::PERMISSION_DELETE
474
+                );
475
+            } else {
476
+                $share->setPermissions(Constants::PERMISSION_READ);
477
+            }
478
+
479
+            // Set password
480
+            if ($password !== '') {
481
+                $share->setPassword($password);
482
+            }
483
+
484
+
485
+            if (!empty($label)) {
486
+                $share->setLabel($label);
487
+            }
488
+
489
+            if ($sendPasswordByTalk === 'true') {
490
+                if (!$this->appManager->isEnabledForUser('spreed')) {
491
+                    throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$path->getPath()]));
492
+                }
493
+
494
+                $share->setSendPasswordByTalk(true);
495
+            }
496
+
497
+            //Expire date
498
+            if ($expireDate !== '') {
499
+                try {
500
+                    $expireDate = $this->parseDate($expireDate);
501
+                    $share->setExpirationDate($expireDate);
502
+                } catch (\Exception $e) {
503
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
504
+                }
505
+            }
506
+
507
+        } else if ($shareType === Share::SHARE_TYPE_REMOTE) {
508
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
509
+                throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
510
+            }
511
+
512
+            $share->setSharedWith($shareWith);
513
+            $share->setPermissions($permissions);
514
+        }  else if ($shareType === Share::SHARE_TYPE_REMOTE_GROUP) {
515
+            if (!$this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
516
+                throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
517
+            }
518
+
519
+            $share->setSharedWith($shareWith);
520
+            $share->setPermissions($permissions);
521
+        } else if ($shareType === Share::SHARE_TYPE_EMAIL) {
522
+            if ($share->getNodeType() === 'file') {
523
+                $share->setPermissions(Constants::PERMISSION_READ);
524
+            } else {
525
+                $share->setPermissions($permissions);
526
+            }
527
+            $share->setSharedWith($shareWith);
528
+
529
+            if ($sendPasswordByTalk === 'true') {
530
+                if (!$this->appManager->isEnabledForUser('spreed')) {
531
+                    throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$path->getPath()]));
532
+                }
533
+
534
+                $share->setSendPasswordByTalk(true);
535
+            }
536
+        } else if ($shareType === Share::SHARE_TYPE_CIRCLE) {
537
+            if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
538
+                throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
539
+            }
540
+
541
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
542
+
543
+            // Valid circle is required to share
544
+            if ($circle === null) {
545
+                throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
546
+            }
547
+            $share->setSharedWith($shareWith);
548
+            $share->setPermissions($permissions);
549
+        } else if ($shareType === Share::SHARE_TYPE_ROOM) {
550
+            try {
551
+                $this->getRoomShareHelper()->createShare($share, $shareWith, $permissions, $expireDate);
552
+            } catch (QueryException $e) {
553
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$path->getPath()]));
554
+            }
555
+        } else {
556
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
557
+        }
558
+
559
+        $share->setShareType($shareType);
560
+        $share->setSharedBy($this->currentUser);
561
+
562
+        try {
563
+            $share = $this->shareManager->createShare($share);
564
+        } catch (GenericShareException $e) {
565
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
566
+            throw new OCSException($e->getHint(), $code);
567
+        } catch (\Exception $e) {
568
+            throw new OCSForbiddenException($e->getMessage(), $e);
569
+        }
570
+
571
+        $output = $this->formatShare($share);
572
+
573
+        return new DataResponse($output);
574
+    }
575
+
576
+    /**
577
+     * @param \OCP\Files\File|\OCP\Files\Folder $node
578
+     * @param boolean $includeTags
579
+     * @return DataResponse
580
+     */
581
+    private function getSharedWithMe($node = null, bool $includeTags): DataResponse {
582
+
583
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_USER, $node, -1, 0);
584
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_GROUP, $node, -1, 0);
585
+        $circleShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
586
+        $roomShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_ROOM, $node, -1, 0);
587
+
588
+        $shares = array_merge($userShares, $groupShares, $circleShares, $roomShares);
589
+
590
+        $shares = array_filter($shares, function (IShare $share) {
591
+            return $share->getShareOwner() !== $this->currentUser;
592
+        });
593
+
594
+        $formatted = [];
595
+        foreach ($shares as $share) {
596
+            if ($this->canAccessShare($share)) {
597
+                try {
598
+                    $formatted[] = $this->formatShare($share);
599
+                } catch (NotFoundException $e) {
600
+                    // Ignore this share
601
+                }
602
+            }
603
+        }
604
+
605
+        if ($includeTags) {
606
+            $formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
607
+        }
608
+
609
+        return new DataResponse($formatted);
610
+    }
611
+
612
+    /**
613
+     * @param \OCP\Files\Folder $folder
614
+     * @return DataResponse
615
+     * @throws OCSBadRequestException
616
+     */
617
+    private function getSharesInDir(Node $folder): DataResponse {
618
+        if (!($folder instanceof \OCP\Files\Folder)) {
619
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
620
+        }
621
+
622
+        $nodes = $folder->getDirectoryListing();
623
+        /** @var \OCP\Share\IShare[] $shares */
624
+        $shares = [];
625
+        foreach ($nodes as $node) {
626
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_USER, $node, false, -1, 0));
627
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
628
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_LINK, $node, false, -1, 0));
629
+            if($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
630
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
631
+            }
632
+            if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
633
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
634
+            }
635
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_ROOM, $node, false, -1, 0));
636
+        }
637
+
638
+        $formatted = [];
639
+        foreach ($shares as $share) {
640
+            try {
641
+                $formatted[] = $this->formatShare($share);
642
+            } catch (NotFoundException $e) {
643
+                //Ignore this share
644
+            }
645
+        }
646
+
647
+        return new DataResponse($formatted);
648
+    }
649
+
650
+    /**
651
+     * The getShares function.
652
+     *
653
+     * @NoAdminRequired
654
+     *
655
+     * @param string $shared_with_me
656
+     * @param string $reshares
657
+     * @param string $subfiles
658
+     * @param string $path
659
+     *
660
+     * - Get shares by the current user
661
+     * - Get shares by the current user and reshares (?reshares=true)
662
+     * - Get shares with the current user (?shared_with_me=true)
663
+     * - Get shares for a specific path (?path=...)
664
+     * - Get all shares in a folder (?subfiles=true&path=..)
665
+     *
666
+     * @return DataResponse
667
+     * @throws OCSNotFoundException
668
+     */
669
+    public function getShares(
670
+        string $shared_with_me = 'false',
671
+        string $reshares = 'false',
672
+        string $subfiles = 'false',
673
+        string $path = null,
674
+        string $include_tags = 'false'
675
+    ): DataResponse {
676
+
677
+        if ($path !== null) {
678
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
679
+            try {
680
+                $path = $userFolder->get($path);
681
+                $this->lock($path);
682
+            } catch (\OCP\Files\NotFoundException $e) {
683
+                throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
684
+            } catch (LockedException $e) {
685
+                throw new OCSNotFoundException($this->l->t('Could not lock path'));
686
+            }
687
+        }
688
+
689
+        $include_tags = $include_tags === 'true';
690
+
691
+        if ($shared_with_me === 'true') {
692
+            $result = $this->getSharedWithMe($path, $include_tags);
693
+            return $result;
694
+        }
695
+
696
+        if ($subfiles === 'true') {
697
+            $result = $this->getSharesInDir($path);
698
+            return $result;
699
+        }
700
+
701
+        if ($reshares === 'true') {
702
+            $reshares = true;
703
+        } else {
704
+            $reshares = false;
705
+        }
706
+
707
+        // Get all shares
708
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
709
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
710
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
711
+        if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
712
+            $mailShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
713
+        } else {
714
+            $mailShares = [];
715
+        }
716
+        if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_CIRCLE)) {
717
+            $circleShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
718
+        } else {
719
+            $circleShares = [];
720
+        }
721
+        $roomShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_ROOM, $path, $reshares, -1, 0);
722
+
723
+        $shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares, $roomShares);
724
+
725
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
726
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
727
+            $shares = array_merge($shares, $federatedShares);
728
+        }
729
+
730
+        if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
731
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_REMOTE_GROUP, $path, $reshares, -1, 0);
732
+            $shares = array_merge($shares, $federatedShares);
733
+        }
734
+
735
+        $formatted = $miniFormatted = [];
736
+        $resharingRight = false;
737
+        foreach ($shares as $share) {
738
+            /** @var IShare $share */
739
+            try {
740
+                $format = $this->formatShare($share, $path);
741
+                $formatted[] = $format;
742
+                if ($share->getSharedBy() === $this->currentUser) {
743
+                    $miniFormatted[] = $format;
744
+                }
745
+
746
+                if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $path)) {
747
+                    $resharingRight = true;
748
+                }
749
+            } catch (\Exception $e) {
750
+                //Ignore share
751
+            }
752
+        }
753
+
754
+        if (!$resharingRight) {
755
+            $formatted = $miniFormatted;
756
+        }
757
+
758
+        if ($include_tags) {
759
+            $formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
760
+        }
761
+
762
+        return new DataResponse($formatted);
763
+    }
764
+
765
+    /**
766
+     * @NoAdminRequired
767
+     *
768
+     * @param string $id
769
+     * @param int $permissions
770
+     * @param string $password
771
+     * @param string $sendPasswordByTalk
772
+     * @param string $publicUpload
773
+     * @param string $expireDate
774
+     * @param string $note
775
+     * @param string $label
776
+     * @param string $hideDownload
777
+     * @return DataResponse
778
+     * @throws LockedException
779
+     * @throws NotFoundException
780
+     * @throws OCSBadRequestException
781
+     * @throws OCSForbiddenException
782
+     * @throws OCSNotFoundException
783
+     */
784
+    public function updateShare(
785
+        string $id,
786
+        int $permissions = null,
787
+        string $password = null,
788
+        string $sendPasswordByTalk = null,
789
+        string $publicUpload = null,
790
+        string $expireDate = null,
791
+        string $note = null,
792
+        string $label = null,
793
+        string $hideDownload = null
794
+    ): DataResponse {
795
+        try {
796
+            $share = $this->getShareById($id);
797
+        } catch (ShareNotFound $e) {
798
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
799
+        }
800
+
801
+        $this->lock($share->getNode());
802
+
803
+        if (!$this->canAccessShare($share, false)) {
804
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
805
+        }
806
+
807
+        if ($permissions === null &&
808
+            $password === null &&
809
+            $sendPasswordByTalk === null &&
810
+            $publicUpload === null &&
811
+            $expireDate === null &&
812
+            $note === null &&
813
+            $label === null &&
814
+            $hideDownload === null
815
+        ) {
816
+            throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
817
+        }
818
+
819
+        if($note !== null) {
820
+            $share->setNote($note);
821
+        }
822
+
823
+        /*
824 824
 		 * expirationdate, password and publicUpload only make sense for link shares
825 825
 		 */
826
-		if ($share->getShareType() === Share::SHARE_TYPE_LINK) {
827
-
828
-			// Update hide download state
829
-			if ($hideDownload === 'true') {
830
-				$share->setHideDownload(true);
831
-			} else if ($hideDownload === 'false') {
832
-				$share->setHideDownload(false);
833
-			}
834
-
835
-			$newPermissions = null;
836
-			if ($publicUpload === 'true') {
837
-				$newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
838
-			} else if ($publicUpload === 'false') {
839
-				$newPermissions = Constants::PERMISSION_READ;
840
-			}
841
-
842
-			if ($permissions !== null) {
843
-				$newPermissions = (int)$permissions;
844
-				$newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;
845
-			}
846
-
847
-			if ($newPermissions !== null &&
848
-				!in_array($newPermissions, [
849
-					Constants::PERMISSION_READ,
850
-					Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE, // legacy
851
-					Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE, // correct
852
-					Constants::PERMISSION_CREATE, // hidden file list
853
-					Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE, // allow to edit single files
854
-				], true)
855
-			) {
856
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
857
-			}
858
-
859
-			if (
860
-				// legacy
861
-				$newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE) ||
862
-				// correct
863
-				$newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
864
-			) {
865
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
866
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
867
-				}
868
-
869
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
870
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
871
-				}
872
-
873
-				// normalize to correct public upload permissions
874
-				$newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
875
-			}
876
-
877
-			if ($newPermissions !== null) {
878
-				$share->setPermissions($newPermissions);
879
-				$permissions = $newPermissions;
880
-			}
881
-
882
-			if ($expireDate === '') {
883
-				$share->setExpirationDate(null);
884
-			} else if ($expireDate !== null) {
885
-				try {
886
-					$expireDate = $this->parseDate($expireDate);
887
-				} catch (\Exception $e) {
888
-					throw new OCSBadRequestException($e->getMessage(), $e);
889
-				}
890
-				$share->setExpirationDate($expireDate);
891
-			}
892
-
893
-			if ($password === '') {
894
-				$share->setPassword(null);
895
-			} else if ($password !== null) {
896
-				$share->setPassword($password);
897
-			}
898
-
899
-			if ($label !== null) {
900
-				$share->setLabel($label);
901
-			}
902
-
903
-			if ($sendPasswordByTalk === 'true') {
904
-				if (!$this->appManager->isEnabledForUser('spreed')) {
905
-					throw new OCSForbiddenException($this->l->t('Sharing sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled'));
906
-				}
907
-
908
-				$share->setSendPasswordByTalk(true);
909
-			} else if ($sendPasswordByTalk !== null) {
910
-				$share->setSendPasswordByTalk(false);
911
-			}
912
-		} else {
913
-			if ($permissions !== null) {
914
-				$permissions = (int)$permissions;
915
-				$share->setPermissions($permissions);
916
-			}
917
-
918
-			if ($share->getShareType() === Share::SHARE_TYPE_EMAIL) {
919
-				if ($password === '') {
920
-					$share->setPassword(null);
921
-				} else if ($password !== null) {
922
-					$share->setPassword($password);
923
-				}
924
-
925
-				if ($sendPasswordByTalk === 'true') {
926
-					if (!$this->appManager->isEnabledForUser('spreed')) {
927
-						throw new OCSForbiddenException($this->l->t('Sharing sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled'));
928
-					}
929
-
930
-					$share->setSendPasswordByTalk(true);
931
-				} else {
932
-					$share->setSendPasswordByTalk(false);
933
-				}
934
-			}
935
-
936
-			if ($expireDate === '') {
937
-				$share->setExpirationDate(null);
938
-			} else if ($expireDate !== null) {
939
-				try {
940
-					$expireDate = $this->parseDate($expireDate);
941
-				} catch (\Exception $e) {
942
-					throw new OCSBadRequestException($e->getMessage(), $e);
943
-				}
944
-				$share->setExpirationDate($expireDate);
945
-			}
946
-
947
-		}
948
-
949
-		if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
950
-			/* Check if this is an incomming share */
951
-			$incomingShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
952
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
953
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_ROOM, $share->getNode(), -1, 0));
954
-
955
-			/** @var \OCP\Share\IShare[] $incomingShares */
956
-			if (!empty($incomingShares)) {
957
-				$maxPermissions = 0;
958
-				foreach ($incomingShares as $incomingShare) {
959
-					$maxPermissions |= $incomingShare->getPermissions();
960
-				}
961
-
962
-				if ($share->getPermissions() & ~$maxPermissions) {
963
-					throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
964
-				}
965
-			}
966
-		}
967
-
968
-
969
-		try {
970
-			$share = $this->shareManager->updateShare($share);
971
-		} catch (\Exception $e) {
972
-			throw new OCSBadRequestException($e->getMessage(), $e);
973
-		}
974
-
975
-		return new DataResponse($this->formatShare($share));
976
-	}
977
-
978
-	/**
979
-	 * @suppress PhanUndeclaredClassMethod
980
-	 */
981
-	protected function canAccessShare(\OCP\Share\IShare $share, bool $checkGroups = true): bool {
982
-		// A file with permissions 0 can't be accessed by us. So Don't show it
983
-		if ($share->getPermissions() === 0) {
984
-			return false;
985
-		}
986
-
987
-		// Owner of the file and the sharer of the file can always get share
988
-		if ($share->getShareOwner() === $this->currentUser ||
989
-			$share->getSharedBy() === $this->currentUser
990
-		) {
991
-			return true;
992
-		}
993
-
994
-		// If the share is shared with you (or a group you are a member of)
995
-		if ($share->getShareType() === Share::SHARE_TYPE_USER &&
996
-			$share->getSharedWith() === $this->currentUser
997
-		) {
998
-			return true;
999
-		}
1000
-
1001
-		if ($checkGroups && $share->getShareType() === Share::SHARE_TYPE_GROUP) {
1002
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1003
-			$user = $this->userManager->get($this->currentUser);
1004
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
1005
-				return true;
1006
-			}
1007
-		}
1008
-
1009
-		if ($share->getShareType() === Share::SHARE_TYPE_CIRCLE) {
1010
-			// TODO: have a sanity check like above?
1011
-			return true;
1012
-		}
1013
-
1014
-		if ($share->getShareType() === Share::SHARE_TYPE_ROOM) {
1015
-			try {
1016
-				return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
1017
-			} catch (QueryException $e) {
1018
-				return false;
1019
-			}
1020
-		}
1021
-
1022
-		return false;
1023
-	}
1024
-
1025
-	/**
1026
-	 * Make sure that the passed date is valid ISO 8601
1027
-	 * So YYYY-MM-DD
1028
-	 * If not throw an exception
1029
-	 *
1030
-	 * @param string $expireDate
1031
-	 *
1032
-	 * @throws \Exception
1033
-	 * @return \DateTime
1034
-	 */
1035
-	private function parseDate(string $expireDate): \DateTime {
1036
-		try {
1037
-			$date = new \DateTime($expireDate);
1038
-		} catch (\Exception $e) {
1039
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
1040
-		}
1041
-
1042
-		if ($date === false) {
1043
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
1044
-		}
1045
-
1046
-		$date->setTime(0, 0, 0);
1047
-
1048
-		return $date;
1049
-	}
1050
-
1051
-	/**
1052
-	 * Since we have multiple providers but the OCS Share API v1 does
1053
-	 * not support this we need to check all backends.
1054
-	 *
1055
-	 * @param string $id
1056
-	 * @return \OCP\Share\IShare
1057
-	 * @throws ShareNotFound
1058
-	 */
1059
-	private function getShareById(string $id): IShare {
1060
-		$share = null;
1061
-
1062
-		// First check if it is an internal share.
1063
-		try {
1064
-			$share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
1065
-			return $share;
1066
-		} catch (ShareNotFound $e) {
1067
-			// Do nothing, just try the other share type
1068
-		}
1069
-
1070
-
1071
-		try {
1072
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_CIRCLE)) {
1073
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
1074
-				return $share;
1075
-			}
1076
-		} catch (ShareNotFound $e) {
1077
-			// Do nothing, just try the other share type
1078
-		}
1079
-
1080
-		try {
1081
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
1082
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
1083
-				return $share;
1084
-			}
1085
-		} catch (ShareNotFound $e) {
1086
-			// Do nothing, just try the other share type
1087
-		}
1088
-
1089
-		try {
1090
-			$share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
1091
-			return $share;
1092
-		} catch (ShareNotFound $e) {
1093
-			// Do nothing, just try the other share type
1094
-		}
1095
-
1096
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
1097
-			throw new ShareNotFound();
1098
-		}
1099
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
1100
-
1101
-		return $share;
1102
-	}
1103
-
1104
-	/**
1105
-	 * Lock a Node
1106
-	 *
1107
-	 * @param \OCP\Files\Node $node
1108
-	 * @throws LockedException
1109
-	 */
1110
-	private function lock(\OCP\Files\Node $node) {
1111
-		$node->lock(ILockingProvider::LOCK_SHARED);
1112
-		$this->lockedNode = $node;
1113
-	}
1114
-
1115
-	/**
1116
-	 * Cleanup the remaining locks
1117
-	 * @throws @LockedException
1118
-	 */
1119
-	public function cleanup() {
1120
-		if ($this->lockedNode !== null) {
1121
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
1122
-		}
1123
-	}
1124
-
1125
-	/**
1126
-	 * Returns the helper of ShareAPIController for room shares.
1127
-	 *
1128
-	 * If the Talk application is not enabled or the helper is not available
1129
-	 * a QueryException is thrown instead.
1130
-	 *
1131
-	 * @return \OCA\Spreed\Share\Helper\ShareAPIController
1132
-	 * @throws QueryException
1133
-	 */
1134
-	private function getRoomShareHelper() {
1135
-		if (!$this->appManager->isEnabledForUser('spreed')) {
1136
-			throw new QueryException();
1137
-		}
1138
-
1139
-		return $this->serverContainer->query('\OCA\Spreed\Share\Helper\ShareAPIController');
1140
-	}
1141
-
1142
-
1143
-	/**
1144
-	 * Returns if we can find resharing rights in an IShare object for a specific user.
1145
-	 *
1146
-	 * @suppress PhanUndeclaredClassMethod
1147
-	 *
1148
-	 * @param string $userId
1149
-	 * @param IShare $share
1150
-	 * @param Node $node
1151
-	 * @return bool
1152
-	 * @throws NotFoundException
1153
-	 * @throws \OCP\Files\InvalidPathException
1154
-	 */
1155
-	private function shareProviderResharingRights(string $userId, IShare $share, $node): bool {
1156
-
1157
-		if ($share->getShareOwner() === $userId) {
1158
-			return true;
1159
-		}
1160
-
1161
-		// we check that current user have parent resharing rights on the current file
1162
-		if ($node !== null && ($node->getPermissions() & \OCP\Constants::PERMISSION_SHARE) !== 0) {
1163
-			return true;
1164
-		}
1165
-
1166
-		if ((\OCP\Constants::PERMISSION_SHARE & $share->getPermissions()) === 0) {
1167
-			return false;
1168
-		}
1169
-
1170
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $userId) {
1171
-			return true;
1172
-		}
1173
-
1174
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP && $this->groupManager->isInGroup($userId, $share->getSharedWith())) {
1175
-			return true;
1176
-		}
1177
-
1178
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles') &&
1179
-			class_exists('\OCA\Circles\Api\v1\Circles')) {
1180
-			$hasCircleId = (substr($share->getSharedWith(), -1) === ']');
1181
-			$shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
1182
-			$shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
1183
-			if (is_bool($shareWithLength)) {
1184
-				$shareWithLength = -1;
1185
-			}
1186
-			$sharedWith = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
1187
-			try {
1188
-				$member = \OCA\Circles\Api\v1\Circles::getMember($sharedWith, $userId, 1);
1189
-				if ($member->getLevel() >= 4) {
1190
-					return true;
1191
-				}
1192
-				return false;
1193
-			} catch (QueryException $e) {
1194
-				return false;
1195
-			}
1196
-		}
1197
-
1198
-		return false;
1199
-	}
826
+        if ($share->getShareType() === Share::SHARE_TYPE_LINK) {
827
+
828
+            // Update hide download state
829
+            if ($hideDownload === 'true') {
830
+                $share->setHideDownload(true);
831
+            } else if ($hideDownload === 'false') {
832
+                $share->setHideDownload(false);
833
+            }
834
+
835
+            $newPermissions = null;
836
+            if ($publicUpload === 'true') {
837
+                $newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
838
+            } else if ($publicUpload === 'false') {
839
+                $newPermissions = Constants::PERMISSION_READ;
840
+            }
841
+
842
+            if ($permissions !== null) {
843
+                $newPermissions = (int)$permissions;
844
+                $newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;
845
+            }
846
+
847
+            if ($newPermissions !== null &&
848
+                !in_array($newPermissions, [
849
+                    Constants::PERMISSION_READ,
850
+                    Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE, // legacy
851
+                    Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE, // correct
852
+                    Constants::PERMISSION_CREATE, // hidden file list
853
+                    Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE, // allow to edit single files
854
+                ], true)
855
+            ) {
856
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
857
+            }
858
+
859
+            if (
860
+                // legacy
861
+                $newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE) ||
862
+                // correct
863
+                $newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
864
+            ) {
865
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
866
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
867
+                }
868
+
869
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
870
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
871
+                }
872
+
873
+                // normalize to correct public upload permissions
874
+                $newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
875
+            }
876
+
877
+            if ($newPermissions !== null) {
878
+                $share->setPermissions($newPermissions);
879
+                $permissions = $newPermissions;
880
+            }
881
+
882
+            if ($expireDate === '') {
883
+                $share->setExpirationDate(null);
884
+            } else if ($expireDate !== null) {
885
+                try {
886
+                    $expireDate = $this->parseDate($expireDate);
887
+                } catch (\Exception $e) {
888
+                    throw new OCSBadRequestException($e->getMessage(), $e);
889
+                }
890
+                $share->setExpirationDate($expireDate);
891
+            }
892
+
893
+            if ($password === '') {
894
+                $share->setPassword(null);
895
+            } else if ($password !== null) {
896
+                $share->setPassword($password);
897
+            }
898
+
899
+            if ($label !== null) {
900
+                $share->setLabel($label);
901
+            }
902
+
903
+            if ($sendPasswordByTalk === 'true') {
904
+                if (!$this->appManager->isEnabledForUser('spreed')) {
905
+                    throw new OCSForbiddenException($this->l->t('Sharing sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled'));
906
+                }
907
+
908
+                $share->setSendPasswordByTalk(true);
909
+            } else if ($sendPasswordByTalk !== null) {
910
+                $share->setSendPasswordByTalk(false);
911
+            }
912
+        } else {
913
+            if ($permissions !== null) {
914
+                $permissions = (int)$permissions;
915
+                $share->setPermissions($permissions);
916
+            }
917
+
918
+            if ($share->getShareType() === Share::SHARE_TYPE_EMAIL) {
919
+                if ($password === '') {
920
+                    $share->setPassword(null);
921
+                } else if ($password !== null) {
922
+                    $share->setPassword($password);
923
+                }
924
+
925
+                if ($sendPasswordByTalk === 'true') {
926
+                    if (!$this->appManager->isEnabledForUser('spreed')) {
927
+                        throw new OCSForbiddenException($this->l->t('Sharing sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled'));
928
+                    }
929
+
930
+                    $share->setSendPasswordByTalk(true);
931
+                } else {
932
+                    $share->setSendPasswordByTalk(false);
933
+                }
934
+            }
935
+
936
+            if ($expireDate === '') {
937
+                $share->setExpirationDate(null);
938
+            } else if ($expireDate !== null) {
939
+                try {
940
+                    $expireDate = $this->parseDate($expireDate);
941
+                } catch (\Exception $e) {
942
+                    throw new OCSBadRequestException($e->getMessage(), $e);
943
+                }
944
+                $share->setExpirationDate($expireDate);
945
+            }
946
+
947
+        }
948
+
949
+        if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
950
+            /* Check if this is an incomming share */
951
+            $incomingShares = $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
952
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
953
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, Share::SHARE_TYPE_ROOM, $share->getNode(), -1, 0));
954
+
955
+            /** @var \OCP\Share\IShare[] $incomingShares */
956
+            if (!empty($incomingShares)) {
957
+                $maxPermissions = 0;
958
+                foreach ($incomingShares as $incomingShare) {
959
+                    $maxPermissions |= $incomingShare->getPermissions();
960
+                }
961
+
962
+                if ($share->getPermissions() & ~$maxPermissions) {
963
+                    throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
964
+                }
965
+            }
966
+        }
967
+
968
+
969
+        try {
970
+            $share = $this->shareManager->updateShare($share);
971
+        } catch (\Exception $e) {
972
+            throw new OCSBadRequestException($e->getMessage(), $e);
973
+        }
974
+
975
+        return new DataResponse($this->formatShare($share));
976
+    }
977
+
978
+    /**
979
+     * @suppress PhanUndeclaredClassMethod
980
+     */
981
+    protected function canAccessShare(\OCP\Share\IShare $share, bool $checkGroups = true): bool {
982
+        // A file with permissions 0 can't be accessed by us. So Don't show it
983
+        if ($share->getPermissions() === 0) {
984
+            return false;
985
+        }
986
+
987
+        // Owner of the file and the sharer of the file can always get share
988
+        if ($share->getShareOwner() === $this->currentUser ||
989
+            $share->getSharedBy() === $this->currentUser
990
+        ) {
991
+            return true;
992
+        }
993
+
994
+        // If the share is shared with you (or a group you are a member of)
995
+        if ($share->getShareType() === Share::SHARE_TYPE_USER &&
996
+            $share->getSharedWith() === $this->currentUser
997
+        ) {
998
+            return true;
999
+        }
1000
+
1001
+        if ($checkGroups && $share->getShareType() === Share::SHARE_TYPE_GROUP) {
1002
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1003
+            $user = $this->userManager->get($this->currentUser);
1004
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
1005
+                return true;
1006
+            }
1007
+        }
1008
+
1009
+        if ($share->getShareType() === Share::SHARE_TYPE_CIRCLE) {
1010
+            // TODO: have a sanity check like above?
1011
+            return true;
1012
+        }
1013
+
1014
+        if ($share->getShareType() === Share::SHARE_TYPE_ROOM) {
1015
+            try {
1016
+                return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
1017
+            } catch (QueryException $e) {
1018
+                return false;
1019
+            }
1020
+        }
1021
+
1022
+        return false;
1023
+    }
1024
+
1025
+    /**
1026
+     * Make sure that the passed date is valid ISO 8601
1027
+     * So YYYY-MM-DD
1028
+     * If not throw an exception
1029
+     *
1030
+     * @param string $expireDate
1031
+     *
1032
+     * @throws \Exception
1033
+     * @return \DateTime
1034
+     */
1035
+    private function parseDate(string $expireDate): \DateTime {
1036
+        try {
1037
+            $date = new \DateTime($expireDate);
1038
+        } catch (\Exception $e) {
1039
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
1040
+        }
1041
+
1042
+        if ($date === false) {
1043
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
1044
+        }
1045
+
1046
+        $date->setTime(0, 0, 0);
1047
+
1048
+        return $date;
1049
+    }
1050
+
1051
+    /**
1052
+     * Since we have multiple providers but the OCS Share API v1 does
1053
+     * not support this we need to check all backends.
1054
+     *
1055
+     * @param string $id
1056
+     * @return \OCP\Share\IShare
1057
+     * @throws ShareNotFound
1058
+     */
1059
+    private function getShareById(string $id): IShare {
1060
+        $share = null;
1061
+
1062
+        // First check if it is an internal share.
1063
+        try {
1064
+            $share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
1065
+            return $share;
1066
+        } catch (ShareNotFound $e) {
1067
+            // Do nothing, just try the other share type
1068
+        }
1069
+
1070
+
1071
+        try {
1072
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_CIRCLE)) {
1073
+                $share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
1074
+                return $share;
1075
+            }
1076
+        } catch (ShareNotFound $e) {
1077
+            // Do nothing, just try the other share type
1078
+        }
1079
+
1080
+        try {
1081
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
1082
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
1083
+                return $share;
1084
+            }
1085
+        } catch (ShareNotFound $e) {
1086
+            // Do nothing, just try the other share type
1087
+        }
1088
+
1089
+        try {
1090
+            $share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
1091
+            return $share;
1092
+        } catch (ShareNotFound $e) {
1093
+            // Do nothing, just try the other share type
1094
+        }
1095
+
1096
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
1097
+            throw new ShareNotFound();
1098
+        }
1099
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
1100
+
1101
+        return $share;
1102
+    }
1103
+
1104
+    /**
1105
+     * Lock a Node
1106
+     *
1107
+     * @param \OCP\Files\Node $node
1108
+     * @throws LockedException
1109
+     */
1110
+    private function lock(\OCP\Files\Node $node) {
1111
+        $node->lock(ILockingProvider::LOCK_SHARED);
1112
+        $this->lockedNode = $node;
1113
+    }
1114
+
1115
+    /**
1116
+     * Cleanup the remaining locks
1117
+     * @throws @LockedException
1118
+     */
1119
+    public function cleanup() {
1120
+        if ($this->lockedNode !== null) {
1121
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
1122
+        }
1123
+    }
1124
+
1125
+    /**
1126
+     * Returns the helper of ShareAPIController for room shares.
1127
+     *
1128
+     * If the Talk application is not enabled or the helper is not available
1129
+     * a QueryException is thrown instead.
1130
+     *
1131
+     * @return \OCA\Spreed\Share\Helper\ShareAPIController
1132
+     * @throws QueryException
1133
+     */
1134
+    private function getRoomShareHelper() {
1135
+        if (!$this->appManager->isEnabledForUser('spreed')) {
1136
+            throw new QueryException();
1137
+        }
1138
+
1139
+        return $this->serverContainer->query('\OCA\Spreed\Share\Helper\ShareAPIController');
1140
+    }
1141
+
1142
+
1143
+    /**
1144
+     * Returns if we can find resharing rights in an IShare object for a specific user.
1145
+     *
1146
+     * @suppress PhanUndeclaredClassMethod
1147
+     *
1148
+     * @param string $userId
1149
+     * @param IShare $share
1150
+     * @param Node $node
1151
+     * @return bool
1152
+     * @throws NotFoundException
1153
+     * @throws \OCP\Files\InvalidPathException
1154
+     */
1155
+    private function shareProviderResharingRights(string $userId, IShare $share, $node): bool {
1156
+
1157
+        if ($share->getShareOwner() === $userId) {
1158
+            return true;
1159
+        }
1160
+
1161
+        // we check that current user have parent resharing rights on the current file
1162
+        if ($node !== null && ($node->getPermissions() & \OCP\Constants::PERMISSION_SHARE) !== 0) {
1163
+            return true;
1164
+        }
1165
+
1166
+        if ((\OCP\Constants::PERMISSION_SHARE & $share->getPermissions()) === 0) {
1167
+            return false;
1168
+        }
1169
+
1170
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $userId) {
1171
+            return true;
1172
+        }
1173
+
1174
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP && $this->groupManager->isInGroup($userId, $share->getSharedWith())) {
1175
+            return true;
1176
+        }
1177
+
1178
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles') &&
1179
+            class_exists('\OCA\Circles\Api\v1\Circles')) {
1180
+            $hasCircleId = (substr($share->getSharedWith(), -1) === ']');
1181
+            $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
1182
+            $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
1183
+            if (is_bool($shareWithLength)) {
1184
+                $shareWithLength = -1;
1185
+            }
1186
+            $sharedWith = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
1187
+            try {
1188
+                $member = \OCA\Circles\Api\v1\Circles::getMember($sharedWith, $userId, 1);
1189
+                if ($member->getLevel() >= 4) {
1190
+                    return true;
1191
+                }
1192
+                return false;
1193
+            } catch (QueryException $e) {
1194
+                return false;
1195
+            }
1196
+        }
1197
+
1198
+        return false;
1199
+    }
1200 1200
 
1201 1201
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -233,14 +233,14 @@  discard block
 block discarded – undo
233 233
 
234 234
 			$result['share_with_displayname'] = $share->getSharedWithDisplayName();
235 235
 			if (empty($result['share_with_displayname'])) {
236
-				$displayNameLength = ($hasCircleId? strrpos($share->getSharedWith(), ' '): strlen($share->getSharedWith()));
236
+				$displayNameLength = ($hasCircleId ? strrpos($share->getSharedWith(), ' ') : strlen($share->getSharedWith()));
237 237
 				$result['share_with_displayname'] = substr($share->getSharedWith(), 0, $displayNameLength);
238 238
 			}
239 239
 
240 240
 			$result['share_with_avatar'] = $share->getSharedWithAvatar();
241 241
 
242
-			$shareWithStart = ($hasCircleId? strrpos($share->getSharedWith(), '[') + 1: 0);
243
-			$shareWithLength = ($hasCircleId? -1: strpos($share->getSharedWith(), ' '));
242
+			$shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
243
+			$shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
244 244
 			if (is_bool($shareWithLength)) {
245 245
 				$shareWithLength = -1;
246 246
 			}
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
275 275
 		$result = \OC::$server->getContactsManager()->search($query, [$property]);
276 276
 		foreach ($result as $r) {
277
-			foreach($r[$property] as $value) {
277
+			foreach ($r[$property] as $value) {
278 278
 				if ($value === $query) {
279 279
 					return $r['FN'];
280 280
 				}
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
 
512 512
 			$share->setSharedWith($shareWith);
513 513
 			$share->setPermissions($permissions);
514
-		}  else if ($shareType === Share::SHARE_TYPE_REMOTE_GROUP) {
514
+		} else if ($shareType === Share::SHARE_TYPE_REMOTE_GROUP) {
515 515
 			if (!$this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
516 516
 				throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$path->getPath(), $shareType]));
517 517
 			}
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
 
588 588
 		$shares = array_merge($userShares, $groupShares, $circleShares, $roomShares);
589 589
 
590
-		$shares = array_filter($shares, function (IShare $share) {
590
+		$shares = array_filter($shares, function(IShare $share) {
591 591
 			return $share->getShareOwner() !== $this->currentUser;
592 592
 		});
593 593
 
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_USER, $node, false, -1, 0));
627 627
 			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
628 628
 			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_LINK, $node, false, -1, 0));
629
-			if($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
629
+			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
630 630
 				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
631 631
 			}
632 632
 			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
 			throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
817 817
 		}
818 818
 
819
-		if($note !== null) {
819
+		if ($note !== null) {
820 820
 			$share->setNote($note);
821 821
 		}
822 822
 
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
 			}
841 841
 
842 842
 			if ($permissions !== null) {
843
-				$newPermissions = (int)$permissions;
843
+				$newPermissions = (int) $permissions;
844 844
 				$newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;
845 845
 			}
846 846
 
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 			}
912 912
 		} else {
913 913
 			if ($permissions !== null) {
914
-				$permissions = (int)$permissions;
914
+				$permissions = (int) $permissions;
915 915
 				$share->setPermissions($permissions);
916 916
 			}
917 917
 
@@ -1061,7 +1061,7 @@  discard block
 block discarded – undo
1061 1061
 
1062 1062
 		// First check if it is an internal share.
1063 1063
 		try {
1064
-			$share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
1064
+			$share = $this->shareManager->getShareById('ocinternal:'.$id, $this->currentUser);
1065 1065
 			return $share;
1066 1066
 		} catch (ShareNotFound $e) {
1067 1067
 			// Do nothing, just try the other share type
@@ -1070,7 +1070,7 @@  discard block
 block discarded – undo
1070 1070
 
1071 1071
 		try {
1072 1072
 			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_CIRCLE)) {
1073
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
1073
+				$share = $this->shareManager->getShareById('ocCircleShare:'.$id, $this->currentUser);
1074 1074
 				return $share;
1075 1075
 			}
1076 1076
 		} catch (ShareNotFound $e) {
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
 
1080 1080
 		try {
1081 1081
 			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
1082
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
1082
+				$share = $this->shareManager->getShareById('ocMailShare:'.$id, $this->currentUser);
1083 1083
 				return $share;
1084 1084
 			}
1085 1085
 		} catch (ShareNotFound $e) {
@@ -1087,7 +1087,7 @@  discard block
 block discarded – undo
1087 1087
 		}
1088 1088
 
1089 1089
 		try {
1090
-			$share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
1090
+			$share = $this->shareManager->getShareById('ocRoomShare:'.$id, $this->currentUser);
1091 1091
 			return $share;
1092 1092
 		} catch (ShareNotFound $e) {
1093 1093
 			// Do nothing, just try the other share type
@@ -1096,7 +1096,7 @@  discard block
 block discarded – undo
1096 1096
 		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
1097 1097
 			throw new ShareNotFound();
1098 1098
 		}
1099
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
1099
+		$share = $this->shareManager->getShareById('ocFederatedSharing:'.$id, $this->currentUser);
1100 1100
 
1101 1101
 		return $share;
1102 1102
 	}
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 1 patch
Indentation   +1286 added lines, -1286 removed lines patch added patch discarded remove patch
@@ -58,1323 +58,1323 @@
 block discarded – undo
58 58
  */
59 59
 class DefaultShareProvider implements IShareProvider {
60 60
 
61
-	// Special share type for user modified group shares
62
-	const SHARE_TYPE_USERGROUP = 2;
63
-
64
-	/** @var IDBConnection */
65
-	private $dbConn;
66
-
67
-	/** @var IUserManager */
68
-	private $userManager;
69
-
70
-	/** @var IGroupManager */
71
-	private $groupManager;
72
-
73
-	/** @var IRootFolder */
74
-	private $rootFolder;
75
-
76
-	/** @var IMailer */
77
-	private $mailer;
78
-
79
-	/** @var Defaults */
80
-	private $defaults;
81
-
82
-	/** @var IL10N */
83
-	private $l;
84
-
85
-	/** @var IURLGenerator */
86
-	private $urlGenerator;
87
-
88
-	/**
89
-	 * DefaultShareProvider constructor.
90
-	 *
91
-	 * @param IDBConnection $connection
92
-	 * @param IUserManager $userManager
93
-	 * @param IGroupManager $groupManager
94
-	 * @param IRootFolder $rootFolder
95
-	 * @param IMailer $mailer ;
96
-	 * @param Defaults $defaults
97
-	 * @param IL10N $l
98
-	 * @param IURLGenerator $urlGenerator
99
-	 */
100
-	public function __construct(
101
-			IDBConnection $connection,
102
-			IUserManager $userManager,
103
-			IGroupManager $groupManager,
104
-			IRootFolder $rootFolder,
105
-			IMailer $mailer,
106
-			Defaults $defaults,
107
-			IL10N $l,
108
-			IURLGenerator $urlGenerator) {
109
-		$this->dbConn = $connection;
110
-		$this->userManager = $userManager;
111
-		$this->groupManager = $groupManager;
112
-		$this->rootFolder = $rootFolder;
113
-		$this->mailer = $mailer;
114
-		$this->defaults = $defaults;
115
-		$this->l = $l;
116
-		$this->urlGenerator = $urlGenerator;
117
-	}
118
-
119
-	/**
120
-	 * Return the identifier of this provider.
121
-	 *
122
-	 * @return string Containing only [a-zA-Z0-9]
123
-	 */
124
-	public function identifier() {
125
-		return 'ocinternal';
126
-	}
127
-
128
-	/**
129
-	 * Share a path
130
-	 *
131
-	 * @param \OCP\Share\IShare $share
132
-	 * @return \OCP\Share\IShare The share object
133
-	 * @throws ShareNotFound
134
-	 * @throws \Exception
135
-	 */
136
-	public function create(\OCP\Share\IShare $share) {
137
-		$qb = $this->dbConn->getQueryBuilder();
138
-
139
-		$qb->insert('share');
140
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
141
-
142
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
143
-			//Set the UID of the user we share with
144
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
145
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
146
-			//Set the GID of the group we share with
147
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
148
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
149
-			//set label for public link
150
-			$qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
151
-			//Set the token of the share
152
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
153
-
154
-			//If a password is set store it
155
-			if ($share->getPassword() !== null) {
156
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
157
-			}
158
-
159
-			$qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
160
-
161
-			//If an expiration date is set store it
162
-			if ($share->getExpirationDate() !== null) {
163
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
164
-			}
165
-
166
-			if (method_exists($share, 'getParent')) {
167
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
168
-			}
169
-		} else {
170
-			throw new \Exception('invalid share type!');
171
-		}
172
-
173
-		// Set what is shares
174
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
175
-		if ($share->getNode() instanceof \OCP\Files\File) {
176
-			$qb->setParameter('itemType', 'file');
177
-		} else {
178
-			$qb->setParameter('itemType', 'folder');
179
-		}
180
-
181
-		// Set the file id
182
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
183
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
184
-
185
-		// set the permissions
186
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
187
-
188
-		// Set who created this share
189
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
190
-
191
-		// Set who is the owner of this file/folder (and this the owner of the share)
192
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
193
-
194
-		// Set the file target
195
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
196
-
197
-		// Set the time this share was created
198
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
199
-
200
-		// insert the data and fetch the id of the share
201
-		$this->dbConn->beginTransaction();
202
-		$qb->execute();
203
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
204
-
205
-		// Now fetch the inserted share and create a complete share object
206
-		$qb = $this->dbConn->getQueryBuilder();
207
-		$qb->select('*')
208
-			->from('share')
209
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
210
-
211
-		$cursor = $qb->execute();
212
-		$data = $cursor->fetch();
213
-		$this->dbConn->commit();
214
-		$cursor->closeCursor();
215
-
216
-		if ($data === false) {
217
-			throw new ShareNotFound();
218
-		}
219
-
220
-		$mailSendValue = $share->getMailSend();
221
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
222
-
223
-		$share = $this->createShare($data);
224
-		return $share;
225
-	}
226
-
227
-	/**
228
-	 * Update a share
229
-	 *
230
-	 * @param \OCP\Share\IShare $share
231
-	 * @return \OCP\Share\IShare The share object
232
-	 * @throws ShareNotFound
233
-	 * @throws \OCP\Files\InvalidPathException
234
-	 * @throws \OCP\Files\NotFoundException
235
-	 */
236
-	public function update(\OCP\Share\IShare $share) {
237
-
238
-		$originalShare = $this->getShareById($share->getId());
239
-
240
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
241
-			/*
61
+    // Special share type for user modified group shares
62
+    const SHARE_TYPE_USERGROUP = 2;
63
+
64
+    /** @var IDBConnection */
65
+    private $dbConn;
66
+
67
+    /** @var IUserManager */
68
+    private $userManager;
69
+
70
+    /** @var IGroupManager */
71
+    private $groupManager;
72
+
73
+    /** @var IRootFolder */
74
+    private $rootFolder;
75
+
76
+    /** @var IMailer */
77
+    private $mailer;
78
+
79
+    /** @var Defaults */
80
+    private $defaults;
81
+
82
+    /** @var IL10N */
83
+    private $l;
84
+
85
+    /** @var IURLGenerator */
86
+    private $urlGenerator;
87
+
88
+    /**
89
+     * DefaultShareProvider constructor.
90
+     *
91
+     * @param IDBConnection $connection
92
+     * @param IUserManager $userManager
93
+     * @param IGroupManager $groupManager
94
+     * @param IRootFolder $rootFolder
95
+     * @param IMailer $mailer ;
96
+     * @param Defaults $defaults
97
+     * @param IL10N $l
98
+     * @param IURLGenerator $urlGenerator
99
+     */
100
+    public function __construct(
101
+            IDBConnection $connection,
102
+            IUserManager $userManager,
103
+            IGroupManager $groupManager,
104
+            IRootFolder $rootFolder,
105
+            IMailer $mailer,
106
+            Defaults $defaults,
107
+            IL10N $l,
108
+            IURLGenerator $urlGenerator) {
109
+        $this->dbConn = $connection;
110
+        $this->userManager = $userManager;
111
+        $this->groupManager = $groupManager;
112
+        $this->rootFolder = $rootFolder;
113
+        $this->mailer = $mailer;
114
+        $this->defaults = $defaults;
115
+        $this->l = $l;
116
+        $this->urlGenerator = $urlGenerator;
117
+    }
118
+
119
+    /**
120
+     * Return the identifier of this provider.
121
+     *
122
+     * @return string Containing only [a-zA-Z0-9]
123
+     */
124
+    public function identifier() {
125
+        return 'ocinternal';
126
+    }
127
+
128
+    /**
129
+     * Share a path
130
+     *
131
+     * @param \OCP\Share\IShare $share
132
+     * @return \OCP\Share\IShare The share object
133
+     * @throws ShareNotFound
134
+     * @throws \Exception
135
+     */
136
+    public function create(\OCP\Share\IShare $share) {
137
+        $qb = $this->dbConn->getQueryBuilder();
138
+
139
+        $qb->insert('share');
140
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
141
+
142
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
143
+            //Set the UID of the user we share with
144
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
145
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
146
+            //Set the GID of the group we share with
147
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
148
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
149
+            //set label for public link
150
+            $qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
151
+            //Set the token of the share
152
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
153
+
154
+            //If a password is set store it
155
+            if ($share->getPassword() !== null) {
156
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
157
+            }
158
+
159
+            $qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
160
+
161
+            //If an expiration date is set store it
162
+            if ($share->getExpirationDate() !== null) {
163
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
164
+            }
165
+
166
+            if (method_exists($share, 'getParent')) {
167
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
168
+            }
169
+        } else {
170
+            throw new \Exception('invalid share type!');
171
+        }
172
+
173
+        // Set what is shares
174
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
175
+        if ($share->getNode() instanceof \OCP\Files\File) {
176
+            $qb->setParameter('itemType', 'file');
177
+        } else {
178
+            $qb->setParameter('itemType', 'folder');
179
+        }
180
+
181
+        // Set the file id
182
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
183
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
184
+
185
+        // set the permissions
186
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
187
+
188
+        // Set who created this share
189
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
190
+
191
+        // Set who is the owner of this file/folder (and this the owner of the share)
192
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
193
+
194
+        // Set the file target
195
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
196
+
197
+        // Set the time this share was created
198
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
199
+
200
+        // insert the data and fetch the id of the share
201
+        $this->dbConn->beginTransaction();
202
+        $qb->execute();
203
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
204
+
205
+        // Now fetch the inserted share and create a complete share object
206
+        $qb = $this->dbConn->getQueryBuilder();
207
+        $qb->select('*')
208
+            ->from('share')
209
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
210
+
211
+        $cursor = $qb->execute();
212
+        $data = $cursor->fetch();
213
+        $this->dbConn->commit();
214
+        $cursor->closeCursor();
215
+
216
+        if ($data === false) {
217
+            throw new ShareNotFound();
218
+        }
219
+
220
+        $mailSendValue = $share->getMailSend();
221
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
222
+
223
+        $share = $this->createShare($data);
224
+        return $share;
225
+    }
226
+
227
+    /**
228
+     * Update a share
229
+     *
230
+     * @param \OCP\Share\IShare $share
231
+     * @return \OCP\Share\IShare The share object
232
+     * @throws ShareNotFound
233
+     * @throws \OCP\Files\InvalidPathException
234
+     * @throws \OCP\Files\NotFoundException
235
+     */
236
+    public function update(\OCP\Share\IShare $share) {
237
+
238
+        $originalShare = $this->getShareById($share->getId());
239
+
240
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
241
+            /*
242 242
 			 * We allow updating the recipient on user shares.
243 243
 			 */
244
-			$qb = $this->dbConn->getQueryBuilder();
245
-			$qb->update('share')
246
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
247
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
248
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
249
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
250
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
251
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->set('note', $qb->createNamedParameter($share->getNote()))
255
-				->execute();
256
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
257
-			$qb = $this->dbConn->getQueryBuilder();
258
-			$qb->update('share')
259
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
260
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
261
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
262
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
263
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
264
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
265
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
266
-				->set('note', $qb->createNamedParameter($share->getNote()))
267
-				->execute();
268
-
269
-			/*
244
+            $qb = $this->dbConn->getQueryBuilder();
245
+            $qb->update('share')
246
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
247
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
248
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
249
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
250
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
251
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->set('note', $qb->createNamedParameter($share->getNote()))
255
+                ->execute();
256
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
257
+            $qb = $this->dbConn->getQueryBuilder();
258
+            $qb->update('share')
259
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
260
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
261
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
262
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
263
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
264
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
265
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
266
+                ->set('note', $qb->createNamedParameter($share->getNote()))
267
+                ->execute();
268
+
269
+            /*
270 270
 			 * Update all user defined group shares
271 271
 			 */
272
-			$qb = $this->dbConn->getQueryBuilder();
273
-			$qb->update('share')
274
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
275
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
276
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
277
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
278
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
279
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
280
-				->set('note', $qb->createNamedParameter($share->getNote()))
281
-				->execute();
282
-
283
-			/*
272
+            $qb = $this->dbConn->getQueryBuilder();
273
+            $qb->update('share')
274
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
275
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
276
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
277
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
278
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
279
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
280
+                ->set('note', $qb->createNamedParameter($share->getNote()))
281
+                ->execute();
282
+
283
+            /*
284 284
 			 * Now update the permissions for all children that have not set it to 0
285 285
 			 */
286
-			$qb = $this->dbConn->getQueryBuilder();
287
-			$qb->update('share')
288
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
289
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
290
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
291
-				->execute();
292
-
293
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
294
-			$qb = $this->dbConn->getQueryBuilder();
295
-			$qb->update('share')
296
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
297
-				->set('password', $qb->createNamedParameter($share->getPassword()))
298
-				->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
299
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
300
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
301
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
302
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
303
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
304
-				->set('token', $qb->createNamedParameter($share->getToken()))
305
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
306
-				->set('note', $qb->createNamedParameter($share->getNote()))
307
-				->set('label', $qb->createNamedParameter($share->getLabel()))
308
-				->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
309
-				->execute();
310
-		}
311
-
312
-		if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
313
-			$this->propagateNote($share);
314
-		}
315
-
316
-
317
-		return $share;
318
-	}
319
-
320
-	/**
321
-	 * Get all children of this share
322
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
323
-	 *
324
-	 * @param \OCP\Share\IShare $parent
325
-	 * @return \OCP\Share\IShare[]
326
-	 */
327
-	public function getChildren(\OCP\Share\IShare $parent) {
328
-		$children = [];
329
-
330
-		$qb = $this->dbConn->getQueryBuilder();
331
-		$qb->select('*')
332
-			->from('share')
333
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
334
-			->andWhere(
335
-				$qb->expr()->in(
336
-					'share_type',
337
-					$qb->createNamedParameter([
338
-						\OCP\Share::SHARE_TYPE_USER,
339
-						\OCP\Share::SHARE_TYPE_GROUP,
340
-						\OCP\Share::SHARE_TYPE_LINK,
341
-					], IQueryBuilder::PARAM_INT_ARRAY)
342
-				)
343
-			)
344
-			->andWhere($qb->expr()->orX(
345
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
346
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
347
-			))
348
-			->orderBy('id');
349
-
350
-		$cursor = $qb->execute();
351
-		while($data = $cursor->fetch()) {
352
-			$children[] = $this->createShare($data);
353
-		}
354
-		$cursor->closeCursor();
355
-
356
-		return $children;
357
-	}
358
-
359
-	/**
360
-	 * Delete a share
361
-	 *
362
-	 * @param \OCP\Share\IShare $share
363
-	 */
364
-	public function delete(\OCP\Share\IShare $share) {
365
-		$qb = $this->dbConn->getQueryBuilder();
366
-		$qb->delete('share')
367
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
368
-
369
-		/*
286
+            $qb = $this->dbConn->getQueryBuilder();
287
+            $qb->update('share')
288
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
289
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
290
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
291
+                ->execute();
292
+
293
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
294
+            $qb = $this->dbConn->getQueryBuilder();
295
+            $qb->update('share')
296
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
297
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
298
+                ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
299
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
300
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
301
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
302
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
303
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
304
+                ->set('token', $qb->createNamedParameter($share->getToken()))
305
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
306
+                ->set('note', $qb->createNamedParameter($share->getNote()))
307
+                ->set('label', $qb->createNamedParameter($share->getLabel()))
308
+                ->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
309
+                ->execute();
310
+        }
311
+
312
+        if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
313
+            $this->propagateNote($share);
314
+        }
315
+
316
+
317
+        return $share;
318
+    }
319
+
320
+    /**
321
+     * Get all children of this share
322
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
323
+     *
324
+     * @param \OCP\Share\IShare $parent
325
+     * @return \OCP\Share\IShare[]
326
+     */
327
+    public function getChildren(\OCP\Share\IShare $parent) {
328
+        $children = [];
329
+
330
+        $qb = $this->dbConn->getQueryBuilder();
331
+        $qb->select('*')
332
+            ->from('share')
333
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
334
+            ->andWhere(
335
+                $qb->expr()->in(
336
+                    'share_type',
337
+                    $qb->createNamedParameter([
338
+                        \OCP\Share::SHARE_TYPE_USER,
339
+                        \OCP\Share::SHARE_TYPE_GROUP,
340
+                        \OCP\Share::SHARE_TYPE_LINK,
341
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
342
+                )
343
+            )
344
+            ->andWhere($qb->expr()->orX(
345
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
346
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
347
+            ))
348
+            ->orderBy('id');
349
+
350
+        $cursor = $qb->execute();
351
+        while($data = $cursor->fetch()) {
352
+            $children[] = $this->createShare($data);
353
+        }
354
+        $cursor->closeCursor();
355
+
356
+        return $children;
357
+    }
358
+
359
+    /**
360
+     * Delete a share
361
+     *
362
+     * @param \OCP\Share\IShare $share
363
+     */
364
+    public function delete(\OCP\Share\IShare $share) {
365
+        $qb = $this->dbConn->getQueryBuilder();
366
+        $qb->delete('share')
367
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
368
+
369
+        /*
370 370
 		 * If the share is a group share delete all possible
371 371
 		 * user defined groups shares.
372 372
 		 */
373
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
374
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
375
-		}
376
-
377
-		$qb->execute();
378
-	}
379
-
380
-	/**
381
-	 * Unshare a share from the recipient. If this is a group share
382
-	 * this means we need a special entry in the share db.
383
-	 *
384
-	 * @param \OCP\Share\IShare $share
385
-	 * @param string $recipient UserId of recipient
386
-	 * @throws BackendError
387
-	 * @throws ProviderException
388
-	 */
389
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
390
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
391
-
392
-			$group = $this->groupManager->get($share->getSharedWith());
393
-			$user = $this->userManager->get($recipient);
394
-
395
-			if (is_null($group)) {
396
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
397
-			}
398
-
399
-			if (!$group->inGroup($user)) {
400
-				throw new ProviderException('Recipient not in receiving group');
401
-			}
402
-
403
-			// Try to fetch user specific share
404
-			$qb = $this->dbConn->getQueryBuilder();
405
-			$stmt = $qb->select('*')
406
-				->from('share')
407
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
408
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
409
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
410
-				->andWhere($qb->expr()->orX(
411
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
412
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
413
-				))
414
-				->execute();
415
-
416
-			$data = $stmt->fetch();
417
-
418
-			/*
373
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
374
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
375
+        }
376
+
377
+        $qb->execute();
378
+    }
379
+
380
+    /**
381
+     * Unshare a share from the recipient. If this is a group share
382
+     * this means we need a special entry in the share db.
383
+     *
384
+     * @param \OCP\Share\IShare $share
385
+     * @param string $recipient UserId of recipient
386
+     * @throws BackendError
387
+     * @throws ProviderException
388
+     */
389
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
390
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
391
+
392
+            $group = $this->groupManager->get($share->getSharedWith());
393
+            $user = $this->userManager->get($recipient);
394
+
395
+            if (is_null($group)) {
396
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
397
+            }
398
+
399
+            if (!$group->inGroup($user)) {
400
+                throw new ProviderException('Recipient not in receiving group');
401
+            }
402
+
403
+            // Try to fetch user specific share
404
+            $qb = $this->dbConn->getQueryBuilder();
405
+            $stmt = $qb->select('*')
406
+                ->from('share')
407
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
408
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
409
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
410
+                ->andWhere($qb->expr()->orX(
411
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
412
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
413
+                ))
414
+                ->execute();
415
+
416
+            $data = $stmt->fetch();
417
+
418
+            /*
419 419
 			 * Check if there already is a user specific group share.
420 420
 			 * If there is update it (if required).
421 421
 			 */
422
-			if ($data === false) {
423
-				$qb = $this->dbConn->getQueryBuilder();
424
-
425
-				$type = $share->getNodeType();
426
-
427
-				//Insert new share
428
-				$qb->insert('share')
429
-					->values([
430
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
431
-						'share_with' => $qb->createNamedParameter($recipient),
432
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
433
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
434
-						'parent' => $qb->createNamedParameter($share->getId()),
435
-						'item_type' => $qb->createNamedParameter($type),
436
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
437
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
438
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
439
-						'permissions' => $qb->createNamedParameter(0),
440
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
441
-					])->execute();
442
-
443
-			} else if ($data['permissions'] !== 0) {
444
-
445
-				// Update existing usergroup share
446
-				$qb = $this->dbConn->getQueryBuilder();
447
-				$qb->update('share')
448
-					->set('permissions', $qb->createNamedParameter(0))
449
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
450
-					->execute();
451
-			}
452
-
453
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
454
-
455
-			if ($share->getSharedWith() !== $recipient) {
456
-				throw new ProviderException('Recipient does not match');
457
-			}
458
-
459
-			// We can just delete user and link shares
460
-			$this->delete($share);
461
-		} else {
462
-			throw new ProviderException('Invalid shareType');
463
-		}
464
-	}
465
-
466
-	/**
467
-	 * @inheritdoc
468
-	 *
469
-	 * For now this only works for group shares
470
-	 * If this gets implemented for normal shares we have to extend it
471
-	 */
472
-	public function restore(IShare $share, string $recipient): IShare {
473
-		$qb = $this->dbConn->getQueryBuilder();
474
-		$qb->select('permissions')
475
-			->from('share')
476
-			->where(
477
-				$qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
478
-			);
479
-		$cursor = $qb->execute();
480
-		$data = $cursor->fetch();
481
-		$cursor->closeCursor();
482
-
483
-		$originalPermission = $data['permissions'];
484
-
485
-		$qb = $this->dbConn->getQueryBuilder();
486
-		$qb->update('share')
487
-			->set('permissions', $qb->createNamedParameter($originalPermission))
488
-			->where(
489
-				$qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
490
-			)->andWhere(
491
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
492
-			)->andWhere(
493
-				$qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
494
-			);
495
-
496
-		$qb->execute();
497
-
498
-		return $this->getShareById($share->getId(), $recipient);
499
-	}
500
-
501
-	/**
502
-	 * @inheritdoc
503
-	 */
504
-	public function move(\OCP\Share\IShare $share, $recipient) {
505
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
506
-			// Just update the target
507
-			$qb = $this->dbConn->getQueryBuilder();
508
-			$qb->update('share')
509
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
510
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
511
-				->execute();
512
-
513
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
514
-
515
-			// Check if there is a usergroup share
516
-			$qb = $this->dbConn->getQueryBuilder();
517
-			$stmt = $qb->select('id')
518
-				->from('share')
519
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
520
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
521
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
522
-				->andWhere($qb->expr()->orX(
523
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
524
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
525
-				))
526
-				->setMaxResults(1)
527
-				->execute();
528
-
529
-			$data = $stmt->fetch();
530
-			$stmt->closeCursor();
531
-
532
-			if ($data === false) {
533
-				// No usergroup share yet. Create one.
534
-				$qb = $this->dbConn->getQueryBuilder();
535
-				$qb->insert('share')
536
-					->values([
537
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
538
-						'share_with' => $qb->createNamedParameter($recipient),
539
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
540
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
541
-						'parent' => $qb->createNamedParameter($share->getId()),
542
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
543
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
544
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
545
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
546
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
547
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
548
-					])->execute();
549
-			} else {
550
-				// Already a usergroup share. Update it.
551
-				$qb = $this->dbConn->getQueryBuilder();
552
-				$qb->update('share')
553
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
554
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
555
-					->execute();
556
-			}
557
-		}
558
-
559
-		return $share;
560
-	}
561
-
562
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
563
-		$qb = $this->dbConn->getQueryBuilder();
564
-		$qb->select('*')
565
-			->from('share', 's')
566
-			->andWhere($qb->expr()->orX(
567
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
568
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
569
-			));
570
-
571
-		$qb->andWhere($qb->expr()->orX(
572
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
573
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
574
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
575
-		));
576
-
577
-		/**
578
-		 * Reshares for this user are shares where they are the owner.
579
-		 */
580
-		if ($reshares === false) {
581
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
582
-		} else {
583
-			$qb->andWhere(
584
-				$qb->expr()->orX(
585
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
586
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
587
-				)
588
-			);
589
-		}
590
-
591
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
592
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
593
-
594
-		$qb->orderBy('id');
595
-
596
-		$cursor = $qb->execute();
597
-		$shares = [];
598
-		while ($data = $cursor->fetch()) {
599
-			$shares[$data['fileid']][] = $this->createShare($data);
600
-		}
601
-		$cursor->closeCursor();
602
-
603
-		return $shares;
604
-	}
605
-
606
-	/**
607
-	 * @inheritdoc
608
-	 */
609
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
610
-		$qb = $this->dbConn->getQueryBuilder();
611
-		$qb->select('*')
612
-			->from('share')
613
-			->andWhere($qb->expr()->orX(
614
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
615
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
616
-			));
617
-
618
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
619
-
620
-		/**
621
-		 * Reshares for this user are shares where they are the owner.
622
-		 */
623
-		if ($reshares === false) {
624
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
625
-		} else {
626
-			if ($node === null) {
627
-				$qb->andWhere(
628
-					$qb->expr()->orX(
629
-						$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
630
-						$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
631
-					)
632
-				);
633
-			}
634
-		}
635
-
636
-		if ($node !== null) {
637
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
638
-		}
639
-
640
-		if ($limit !== -1) {
641
-			$qb->setMaxResults($limit);
642
-		}
643
-
644
-		$qb->setFirstResult($offset);
645
-		$qb->orderBy('id');
646
-
647
-		$cursor = $qb->execute();
648
-		$shares = [];
649
-		while($data = $cursor->fetch()) {
650
-			$shares[] = $this->createShare($data);
651
-		}
652
-		$cursor->closeCursor();
653
-
654
-		return $shares;
655
-	}
656
-
657
-	/**
658
-	 * @inheritdoc
659
-	 */
660
-	public function getShareById($id, $recipientId = null) {
661
-		$qb = $this->dbConn->getQueryBuilder();
662
-
663
-		$qb->select('*')
664
-			->from('share')
665
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
666
-			->andWhere(
667
-				$qb->expr()->in(
668
-					'share_type',
669
-					$qb->createNamedParameter([
670
-						\OCP\Share::SHARE_TYPE_USER,
671
-						\OCP\Share::SHARE_TYPE_GROUP,
672
-						\OCP\Share::SHARE_TYPE_LINK,
673
-					], IQueryBuilder::PARAM_INT_ARRAY)
674
-				)
675
-			)
676
-			->andWhere($qb->expr()->orX(
677
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
678
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
679
-			));
680
-
681
-		$cursor = $qb->execute();
682
-		$data = $cursor->fetch();
683
-		$cursor->closeCursor();
684
-
685
-		if ($data === false) {
686
-			throw new ShareNotFound();
687
-		}
688
-
689
-		try {
690
-			$share = $this->createShare($data);
691
-		} catch (InvalidShare $e) {
692
-			throw new ShareNotFound();
693
-		}
694
-
695
-		// If the recipient is set for a group share resolve to that user
696
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
697
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
698
-		}
699
-
700
-		return $share;
701
-	}
702
-
703
-	/**
704
-	 * Get shares for a given path
705
-	 *
706
-	 * @param \OCP\Files\Node $path
707
-	 * @return \OCP\Share\IShare[]
708
-	 */
709
-	public function getSharesByPath(Node $path) {
710
-		$qb = $this->dbConn->getQueryBuilder();
711
-
712
-		$cursor = $qb->select('*')
713
-			->from('share')
714
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
715
-			->andWhere(
716
-				$qb->expr()->orX(
717
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
718
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
719
-				)
720
-			)
721
-			->andWhere($qb->expr()->orX(
722
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
723
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
724
-			))
725
-			->execute();
726
-
727
-		$shares = [];
728
-		while($data = $cursor->fetch()) {
729
-			$shares[] = $this->createShare($data);
730
-		}
731
-		$cursor->closeCursor();
732
-
733
-		return $shares;
734
-	}
735
-
736
-	/**
737
-	 * Returns whether the given database result can be interpreted as
738
-	 * a share with accessible file (not trashed, not deleted)
739
-	 */
740
-	private function isAccessibleResult($data) {
741
-		// exclude shares leading to deleted file entries
742
-		if ($data['fileid'] === null) {
743
-			return false;
744
-		}
745
-
746
-		// exclude shares leading to trashbin on home storages
747
-		$pathSections = explode('/', $data['path'], 2);
748
-		// FIXME: would not detect rare md5'd home storage case properly
749
-		if ($pathSections[0] !== 'files'
750
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
751
-			return false;
752
-		}
753
-		return true;
754
-	}
755
-
756
-	/**
757
-	 * @inheritdoc
758
-	 */
759
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
760
-		/** @var Share[] $shares */
761
-		$shares = [];
762
-
763
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
764
-			//Get shares directly with this user
765
-			$qb = $this->dbConn->getQueryBuilder();
766
-			$qb->select('s.*',
767
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
768
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
769
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
770
-			)
771
-				->selectAlias('st.id', 'storage_string_id')
772
-				->from('share', 's')
773
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
774
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
775
-
776
-			// Order by id
777
-			$qb->orderBy('s.id');
778
-
779
-			// Set limit and offset
780
-			if ($limit !== -1) {
781
-				$qb->setMaxResults($limit);
782
-			}
783
-			$qb->setFirstResult($offset);
784
-
785
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
786
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
787
-				->andWhere($qb->expr()->orX(
788
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
789
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
790
-				));
791
-
792
-			// Filter by node if provided
793
-			if ($node !== null) {
794
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
795
-			}
796
-
797
-			$cursor = $qb->execute();
798
-
799
-			while($data = $cursor->fetch()) {
800
-				if ($this->isAccessibleResult($data)) {
801
-					$shares[] = $this->createShare($data);
802
-				}
803
-			}
804
-			$cursor->closeCursor();
805
-
806
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
807
-			$user = $this->userManager->get($userId);
808
-			$allGroups = $this->groupManager->getUserGroups($user);
809
-
810
-			/** @var Share[] $shares2 */
811
-			$shares2 = [];
812
-
813
-			$start = 0;
814
-			while(true) {
815
-				$groups = array_slice($allGroups, $start, 100);
816
-				$start += 100;
817
-
818
-				if ($groups === []) {
819
-					break;
820
-				}
821
-
822
-				$qb = $this->dbConn->getQueryBuilder();
823
-				$qb->select('s.*',
824
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
825
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
826
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
827
-				)
828
-					->selectAlias('st.id', 'storage_string_id')
829
-					->from('share', 's')
830
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
831
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
832
-					->orderBy('s.id')
833
-					->setFirstResult(0);
834
-
835
-				if ($limit !== -1) {
836
-					$qb->setMaxResults($limit - count($shares));
837
-				}
838
-
839
-				// Filter by node if provided
840
-				if ($node !== null) {
841
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
842
-				}
843
-
844
-
845
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
846
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
847
-
848
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
849
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
850
-						$groups,
851
-						IQueryBuilder::PARAM_STR_ARRAY
852
-					)))
853
-					->andWhere($qb->expr()->orX(
854
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
855
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
856
-					));
857
-
858
-				$cursor = $qb->execute();
859
-				while($data = $cursor->fetch()) {
860
-					if ($offset > 0) {
861
-						$offset--;
862
-						continue;
863
-					}
864
-
865
-					if ($this->isAccessibleResult($data)) {
866
-						$shares2[] = $this->createShare($data);
867
-					}
868
-				}
869
-				$cursor->closeCursor();
870
-			}
871
-
872
-			/*
422
+            if ($data === false) {
423
+                $qb = $this->dbConn->getQueryBuilder();
424
+
425
+                $type = $share->getNodeType();
426
+
427
+                //Insert new share
428
+                $qb->insert('share')
429
+                    ->values([
430
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
431
+                        'share_with' => $qb->createNamedParameter($recipient),
432
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
433
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
434
+                        'parent' => $qb->createNamedParameter($share->getId()),
435
+                        'item_type' => $qb->createNamedParameter($type),
436
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
437
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
438
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
439
+                        'permissions' => $qb->createNamedParameter(0),
440
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
441
+                    ])->execute();
442
+
443
+            } else if ($data['permissions'] !== 0) {
444
+
445
+                // Update existing usergroup share
446
+                $qb = $this->dbConn->getQueryBuilder();
447
+                $qb->update('share')
448
+                    ->set('permissions', $qb->createNamedParameter(0))
449
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
450
+                    ->execute();
451
+            }
452
+
453
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
454
+
455
+            if ($share->getSharedWith() !== $recipient) {
456
+                throw new ProviderException('Recipient does not match');
457
+            }
458
+
459
+            // We can just delete user and link shares
460
+            $this->delete($share);
461
+        } else {
462
+            throw new ProviderException('Invalid shareType');
463
+        }
464
+    }
465
+
466
+    /**
467
+     * @inheritdoc
468
+     *
469
+     * For now this only works for group shares
470
+     * If this gets implemented for normal shares we have to extend it
471
+     */
472
+    public function restore(IShare $share, string $recipient): IShare {
473
+        $qb = $this->dbConn->getQueryBuilder();
474
+        $qb->select('permissions')
475
+            ->from('share')
476
+            ->where(
477
+                $qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
478
+            );
479
+        $cursor = $qb->execute();
480
+        $data = $cursor->fetch();
481
+        $cursor->closeCursor();
482
+
483
+        $originalPermission = $data['permissions'];
484
+
485
+        $qb = $this->dbConn->getQueryBuilder();
486
+        $qb->update('share')
487
+            ->set('permissions', $qb->createNamedParameter($originalPermission))
488
+            ->where(
489
+                $qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
490
+            )->andWhere(
491
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
492
+            )->andWhere(
493
+                $qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
494
+            );
495
+
496
+        $qb->execute();
497
+
498
+        return $this->getShareById($share->getId(), $recipient);
499
+    }
500
+
501
+    /**
502
+     * @inheritdoc
503
+     */
504
+    public function move(\OCP\Share\IShare $share, $recipient) {
505
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
506
+            // Just update the target
507
+            $qb = $this->dbConn->getQueryBuilder();
508
+            $qb->update('share')
509
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
510
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
511
+                ->execute();
512
+
513
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
514
+
515
+            // Check if there is a usergroup share
516
+            $qb = $this->dbConn->getQueryBuilder();
517
+            $stmt = $qb->select('id')
518
+                ->from('share')
519
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
520
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
521
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
522
+                ->andWhere($qb->expr()->orX(
523
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
524
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
525
+                ))
526
+                ->setMaxResults(1)
527
+                ->execute();
528
+
529
+            $data = $stmt->fetch();
530
+            $stmt->closeCursor();
531
+
532
+            if ($data === false) {
533
+                // No usergroup share yet. Create one.
534
+                $qb = $this->dbConn->getQueryBuilder();
535
+                $qb->insert('share')
536
+                    ->values([
537
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
538
+                        'share_with' => $qb->createNamedParameter($recipient),
539
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
540
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
541
+                        'parent' => $qb->createNamedParameter($share->getId()),
542
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
543
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
544
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
545
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
546
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
547
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
548
+                    ])->execute();
549
+            } else {
550
+                // Already a usergroup share. Update it.
551
+                $qb = $this->dbConn->getQueryBuilder();
552
+                $qb->update('share')
553
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
554
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
555
+                    ->execute();
556
+            }
557
+        }
558
+
559
+        return $share;
560
+    }
561
+
562
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
563
+        $qb = $this->dbConn->getQueryBuilder();
564
+        $qb->select('*')
565
+            ->from('share', 's')
566
+            ->andWhere($qb->expr()->orX(
567
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
568
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
569
+            ));
570
+
571
+        $qb->andWhere($qb->expr()->orX(
572
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
573
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
574
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
575
+        ));
576
+
577
+        /**
578
+         * Reshares for this user are shares where they are the owner.
579
+         */
580
+        if ($reshares === false) {
581
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
582
+        } else {
583
+            $qb->andWhere(
584
+                $qb->expr()->orX(
585
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
586
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
587
+                )
588
+            );
589
+        }
590
+
591
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
592
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
593
+
594
+        $qb->orderBy('id');
595
+
596
+        $cursor = $qb->execute();
597
+        $shares = [];
598
+        while ($data = $cursor->fetch()) {
599
+            $shares[$data['fileid']][] = $this->createShare($data);
600
+        }
601
+        $cursor->closeCursor();
602
+
603
+        return $shares;
604
+    }
605
+
606
+    /**
607
+     * @inheritdoc
608
+     */
609
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
610
+        $qb = $this->dbConn->getQueryBuilder();
611
+        $qb->select('*')
612
+            ->from('share')
613
+            ->andWhere($qb->expr()->orX(
614
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
615
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
616
+            ));
617
+
618
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
619
+
620
+        /**
621
+         * Reshares for this user are shares where they are the owner.
622
+         */
623
+        if ($reshares === false) {
624
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
625
+        } else {
626
+            if ($node === null) {
627
+                $qb->andWhere(
628
+                    $qb->expr()->orX(
629
+                        $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
630
+                        $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
631
+                    )
632
+                );
633
+            }
634
+        }
635
+
636
+        if ($node !== null) {
637
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
638
+        }
639
+
640
+        if ($limit !== -1) {
641
+            $qb->setMaxResults($limit);
642
+        }
643
+
644
+        $qb->setFirstResult($offset);
645
+        $qb->orderBy('id');
646
+
647
+        $cursor = $qb->execute();
648
+        $shares = [];
649
+        while($data = $cursor->fetch()) {
650
+            $shares[] = $this->createShare($data);
651
+        }
652
+        $cursor->closeCursor();
653
+
654
+        return $shares;
655
+    }
656
+
657
+    /**
658
+     * @inheritdoc
659
+     */
660
+    public function getShareById($id, $recipientId = null) {
661
+        $qb = $this->dbConn->getQueryBuilder();
662
+
663
+        $qb->select('*')
664
+            ->from('share')
665
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
666
+            ->andWhere(
667
+                $qb->expr()->in(
668
+                    'share_type',
669
+                    $qb->createNamedParameter([
670
+                        \OCP\Share::SHARE_TYPE_USER,
671
+                        \OCP\Share::SHARE_TYPE_GROUP,
672
+                        \OCP\Share::SHARE_TYPE_LINK,
673
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
674
+                )
675
+            )
676
+            ->andWhere($qb->expr()->orX(
677
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
678
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
679
+            ));
680
+
681
+        $cursor = $qb->execute();
682
+        $data = $cursor->fetch();
683
+        $cursor->closeCursor();
684
+
685
+        if ($data === false) {
686
+            throw new ShareNotFound();
687
+        }
688
+
689
+        try {
690
+            $share = $this->createShare($data);
691
+        } catch (InvalidShare $e) {
692
+            throw new ShareNotFound();
693
+        }
694
+
695
+        // If the recipient is set for a group share resolve to that user
696
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
697
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
698
+        }
699
+
700
+        return $share;
701
+    }
702
+
703
+    /**
704
+     * Get shares for a given path
705
+     *
706
+     * @param \OCP\Files\Node $path
707
+     * @return \OCP\Share\IShare[]
708
+     */
709
+    public function getSharesByPath(Node $path) {
710
+        $qb = $this->dbConn->getQueryBuilder();
711
+
712
+        $cursor = $qb->select('*')
713
+            ->from('share')
714
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
715
+            ->andWhere(
716
+                $qb->expr()->orX(
717
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
718
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
719
+                )
720
+            )
721
+            ->andWhere($qb->expr()->orX(
722
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
723
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
724
+            ))
725
+            ->execute();
726
+
727
+        $shares = [];
728
+        while($data = $cursor->fetch()) {
729
+            $shares[] = $this->createShare($data);
730
+        }
731
+        $cursor->closeCursor();
732
+
733
+        return $shares;
734
+    }
735
+
736
+    /**
737
+     * Returns whether the given database result can be interpreted as
738
+     * a share with accessible file (not trashed, not deleted)
739
+     */
740
+    private function isAccessibleResult($data) {
741
+        // exclude shares leading to deleted file entries
742
+        if ($data['fileid'] === null) {
743
+            return false;
744
+        }
745
+
746
+        // exclude shares leading to trashbin on home storages
747
+        $pathSections = explode('/', $data['path'], 2);
748
+        // FIXME: would not detect rare md5'd home storage case properly
749
+        if ($pathSections[0] !== 'files'
750
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
751
+            return false;
752
+        }
753
+        return true;
754
+    }
755
+
756
+    /**
757
+     * @inheritdoc
758
+     */
759
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
760
+        /** @var Share[] $shares */
761
+        $shares = [];
762
+
763
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
764
+            //Get shares directly with this user
765
+            $qb = $this->dbConn->getQueryBuilder();
766
+            $qb->select('s.*',
767
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
768
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
769
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
770
+            )
771
+                ->selectAlias('st.id', 'storage_string_id')
772
+                ->from('share', 's')
773
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
774
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
775
+
776
+            // Order by id
777
+            $qb->orderBy('s.id');
778
+
779
+            // Set limit and offset
780
+            if ($limit !== -1) {
781
+                $qb->setMaxResults($limit);
782
+            }
783
+            $qb->setFirstResult($offset);
784
+
785
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
786
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
787
+                ->andWhere($qb->expr()->orX(
788
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
789
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
790
+                ));
791
+
792
+            // Filter by node if provided
793
+            if ($node !== null) {
794
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
795
+            }
796
+
797
+            $cursor = $qb->execute();
798
+
799
+            while($data = $cursor->fetch()) {
800
+                if ($this->isAccessibleResult($data)) {
801
+                    $shares[] = $this->createShare($data);
802
+                }
803
+            }
804
+            $cursor->closeCursor();
805
+
806
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
807
+            $user = $this->userManager->get($userId);
808
+            $allGroups = $this->groupManager->getUserGroups($user);
809
+
810
+            /** @var Share[] $shares2 */
811
+            $shares2 = [];
812
+
813
+            $start = 0;
814
+            while(true) {
815
+                $groups = array_slice($allGroups, $start, 100);
816
+                $start += 100;
817
+
818
+                if ($groups === []) {
819
+                    break;
820
+                }
821
+
822
+                $qb = $this->dbConn->getQueryBuilder();
823
+                $qb->select('s.*',
824
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
825
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
826
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
827
+                )
828
+                    ->selectAlias('st.id', 'storage_string_id')
829
+                    ->from('share', 's')
830
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
831
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
832
+                    ->orderBy('s.id')
833
+                    ->setFirstResult(0);
834
+
835
+                if ($limit !== -1) {
836
+                    $qb->setMaxResults($limit - count($shares));
837
+                }
838
+
839
+                // Filter by node if provided
840
+                if ($node !== null) {
841
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
842
+                }
843
+
844
+
845
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
846
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
847
+
848
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
849
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
850
+                        $groups,
851
+                        IQueryBuilder::PARAM_STR_ARRAY
852
+                    )))
853
+                    ->andWhere($qb->expr()->orX(
854
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
855
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
856
+                    ));
857
+
858
+                $cursor = $qb->execute();
859
+                while($data = $cursor->fetch()) {
860
+                    if ($offset > 0) {
861
+                        $offset--;
862
+                        continue;
863
+                    }
864
+
865
+                    if ($this->isAccessibleResult($data)) {
866
+                        $shares2[] = $this->createShare($data);
867
+                    }
868
+                }
869
+                $cursor->closeCursor();
870
+            }
871
+
872
+            /*
873 873
  			 * Resolve all group shares to user specific shares
874 874
  			 */
875
-			$shares = $this->resolveGroupShares($shares2, $userId);
876
-		} else {
877
-			throw new BackendError('Invalid backend');
878
-		}
879
-
880
-
881
-		return $shares;
882
-	}
883
-
884
-	/**
885
-	 * Get a share by token
886
-	 *
887
-	 * @param string $token
888
-	 * @return \OCP\Share\IShare
889
-	 * @throws ShareNotFound
890
-	 */
891
-	public function getShareByToken($token) {
892
-		$qb = $this->dbConn->getQueryBuilder();
893
-
894
-		$cursor = $qb->select('*')
895
-			->from('share')
896
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
897
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
898
-			->andWhere($qb->expr()->orX(
899
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
900
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
901
-			))
902
-			->execute();
903
-
904
-		$data = $cursor->fetch();
905
-
906
-		if ($data === false) {
907
-			throw new ShareNotFound();
908
-		}
909
-
910
-		try {
911
-			$share = $this->createShare($data);
912
-		} catch (InvalidShare $e) {
913
-			throw new ShareNotFound();
914
-		}
915
-
916
-		return $share;
917
-	}
918
-
919
-	/**
920
-	 * Create a share object from an database row
921
-	 *
922
-	 * @param mixed[] $data
923
-	 * @return \OCP\Share\IShare
924
-	 * @throws InvalidShare
925
-	 */
926
-	private function createShare($data) {
927
-		$share = new Share($this->rootFolder, $this->userManager);
928
-		$share->setId((int)$data['id'])
929
-			->setShareType((int)$data['share_type'])
930
-			->setPermissions((int)$data['permissions'])
931
-			->setTarget($data['file_target'])
932
-			->setNote($data['note'])
933
-			->setMailSend((bool)$data['mail_send'])
934
-			->setLabel($data['label']);
935
-
936
-		$shareTime = new \DateTime();
937
-		$shareTime->setTimestamp((int)$data['stime']);
938
-		$share->setShareTime($shareTime);
939
-
940
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
941
-			$share->setSharedWith($data['share_with']);
942
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
943
-			$share->setSharedWith($data['share_with']);
944
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
945
-			$share->setPassword($data['password']);
946
-			$share->setSendPasswordByTalk((bool)$data['password_by_talk']);
947
-			$share->setToken($data['token']);
948
-		}
949
-
950
-		$share->setSharedBy($data['uid_initiator']);
951
-		$share->setShareOwner($data['uid_owner']);
952
-
953
-		$share->setNodeId((int)$data['file_source']);
954
-		$share->setNodeType($data['item_type']);
955
-
956
-		if ($data['expiration'] !== null) {
957
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
958
-			$share->setExpirationDate($expiration);
959
-		}
960
-
961
-		if (isset($data['f_permissions'])) {
962
-			$entryData = $data;
963
-			$entryData['permissions'] = $entryData['f_permissions'];
964
-			$entryData['parent'] = $entryData['f_parent'];
965
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
966
-				\OC::$server->getMimeTypeLoader()));
967
-		}
968
-
969
-		$share->setProviderId($this->identifier());
970
-		$share->setHideDownload((int)$data['hide_download'] === 1);
971
-
972
-		return $share;
973
-	}
974
-
975
-	/**
976
-	 * @param Share[] $shares
977
-	 * @param $userId
978
-	 * @return Share[] The updates shares if no update is found for a share return the original
979
-	 */
980
-	private function resolveGroupShares($shares, $userId) {
981
-		$result = [];
982
-
983
-		$start = 0;
984
-		while(true) {
985
-			/** @var Share[] $shareSlice */
986
-			$shareSlice = array_slice($shares, $start, 100);
987
-			$start += 100;
988
-
989
-			if ($shareSlice === []) {
990
-				break;
991
-			}
992
-
993
-			/** @var int[] $ids */
994
-			$ids = [];
995
-			/** @var Share[] $shareMap */
996
-			$shareMap = [];
997
-
998
-			foreach ($shareSlice as $share) {
999
-				$ids[] = (int)$share->getId();
1000
-				$shareMap[$share->getId()] = $share;
1001
-			}
1002
-
1003
-			$qb = $this->dbConn->getQueryBuilder();
1004
-
1005
-			$query = $qb->select('*')
1006
-				->from('share')
1007
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1008
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
1009
-				->andWhere($qb->expr()->orX(
1010
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1011
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1012
-				));
1013
-
1014
-			$stmt = $query->execute();
1015
-
1016
-			while($data = $stmt->fetch()) {
1017
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1018
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
1019
-				$shareMap[$data['parent']]->setParent($data['parent']);
1020
-			}
1021
-
1022
-			$stmt->closeCursor();
1023
-
1024
-			foreach ($shareMap as $share) {
1025
-				$result[] = $share;
1026
-			}
1027
-		}
1028
-
1029
-		return $result;
1030
-	}
1031
-
1032
-	/**
1033
-	 * A user is deleted from the system
1034
-	 * So clean up the relevant shares.
1035
-	 *
1036
-	 * @param string $uid
1037
-	 * @param int $shareType
1038
-	 */
1039
-	public function userDeleted($uid, $shareType) {
1040
-		$qb = $this->dbConn->getQueryBuilder();
1041
-
1042
-		$qb->delete('share');
1043
-
1044
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1045
-			/*
875
+            $shares = $this->resolveGroupShares($shares2, $userId);
876
+        } else {
877
+            throw new BackendError('Invalid backend');
878
+        }
879
+
880
+
881
+        return $shares;
882
+    }
883
+
884
+    /**
885
+     * Get a share by token
886
+     *
887
+     * @param string $token
888
+     * @return \OCP\Share\IShare
889
+     * @throws ShareNotFound
890
+     */
891
+    public function getShareByToken($token) {
892
+        $qb = $this->dbConn->getQueryBuilder();
893
+
894
+        $cursor = $qb->select('*')
895
+            ->from('share')
896
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
897
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
898
+            ->andWhere($qb->expr()->orX(
899
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
900
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
901
+            ))
902
+            ->execute();
903
+
904
+        $data = $cursor->fetch();
905
+
906
+        if ($data === false) {
907
+            throw new ShareNotFound();
908
+        }
909
+
910
+        try {
911
+            $share = $this->createShare($data);
912
+        } catch (InvalidShare $e) {
913
+            throw new ShareNotFound();
914
+        }
915
+
916
+        return $share;
917
+    }
918
+
919
+    /**
920
+     * Create a share object from an database row
921
+     *
922
+     * @param mixed[] $data
923
+     * @return \OCP\Share\IShare
924
+     * @throws InvalidShare
925
+     */
926
+    private function createShare($data) {
927
+        $share = new Share($this->rootFolder, $this->userManager);
928
+        $share->setId((int)$data['id'])
929
+            ->setShareType((int)$data['share_type'])
930
+            ->setPermissions((int)$data['permissions'])
931
+            ->setTarget($data['file_target'])
932
+            ->setNote($data['note'])
933
+            ->setMailSend((bool)$data['mail_send'])
934
+            ->setLabel($data['label']);
935
+
936
+        $shareTime = new \DateTime();
937
+        $shareTime->setTimestamp((int)$data['stime']);
938
+        $share->setShareTime($shareTime);
939
+
940
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
941
+            $share->setSharedWith($data['share_with']);
942
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
943
+            $share->setSharedWith($data['share_with']);
944
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
945
+            $share->setPassword($data['password']);
946
+            $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
947
+            $share->setToken($data['token']);
948
+        }
949
+
950
+        $share->setSharedBy($data['uid_initiator']);
951
+        $share->setShareOwner($data['uid_owner']);
952
+
953
+        $share->setNodeId((int)$data['file_source']);
954
+        $share->setNodeType($data['item_type']);
955
+
956
+        if ($data['expiration'] !== null) {
957
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
958
+            $share->setExpirationDate($expiration);
959
+        }
960
+
961
+        if (isset($data['f_permissions'])) {
962
+            $entryData = $data;
963
+            $entryData['permissions'] = $entryData['f_permissions'];
964
+            $entryData['parent'] = $entryData['f_parent'];
965
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
966
+                \OC::$server->getMimeTypeLoader()));
967
+        }
968
+
969
+        $share->setProviderId($this->identifier());
970
+        $share->setHideDownload((int)$data['hide_download'] === 1);
971
+
972
+        return $share;
973
+    }
974
+
975
+    /**
976
+     * @param Share[] $shares
977
+     * @param $userId
978
+     * @return Share[] The updates shares if no update is found for a share return the original
979
+     */
980
+    private function resolveGroupShares($shares, $userId) {
981
+        $result = [];
982
+
983
+        $start = 0;
984
+        while(true) {
985
+            /** @var Share[] $shareSlice */
986
+            $shareSlice = array_slice($shares, $start, 100);
987
+            $start += 100;
988
+
989
+            if ($shareSlice === []) {
990
+                break;
991
+            }
992
+
993
+            /** @var int[] $ids */
994
+            $ids = [];
995
+            /** @var Share[] $shareMap */
996
+            $shareMap = [];
997
+
998
+            foreach ($shareSlice as $share) {
999
+                $ids[] = (int)$share->getId();
1000
+                $shareMap[$share->getId()] = $share;
1001
+            }
1002
+
1003
+            $qb = $this->dbConn->getQueryBuilder();
1004
+
1005
+            $query = $qb->select('*')
1006
+                ->from('share')
1007
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1008
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
1009
+                ->andWhere($qb->expr()->orX(
1010
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1011
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1012
+                ));
1013
+
1014
+            $stmt = $query->execute();
1015
+
1016
+            while($data = $stmt->fetch()) {
1017
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1018
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
1019
+                $shareMap[$data['parent']]->setParent($data['parent']);
1020
+            }
1021
+
1022
+            $stmt->closeCursor();
1023
+
1024
+            foreach ($shareMap as $share) {
1025
+                $result[] = $share;
1026
+            }
1027
+        }
1028
+
1029
+        return $result;
1030
+    }
1031
+
1032
+    /**
1033
+     * A user is deleted from the system
1034
+     * So clean up the relevant shares.
1035
+     *
1036
+     * @param string $uid
1037
+     * @param int $shareType
1038
+     */
1039
+    public function userDeleted($uid, $shareType) {
1040
+        $qb = $this->dbConn->getQueryBuilder();
1041
+
1042
+        $qb->delete('share');
1043
+
1044
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1045
+            /*
1046 1046
 			 * Delete all user shares that are owned by this user
1047 1047
 			 * or that are received by this user
1048 1048
 			 */
1049 1049
 
1050
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1050
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1051 1051
 
1052
-			$qb->andWhere(
1053
-				$qb->expr()->orX(
1054
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1055
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1056
-				)
1057
-			);
1058
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1059
-			/*
1052
+            $qb->andWhere(
1053
+                $qb->expr()->orX(
1054
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1055
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1056
+                )
1057
+            );
1058
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1059
+            /*
1060 1060
 			 * Delete all group shares that are owned by this user
1061 1061
 			 * Or special user group shares that are received by this user
1062 1062
 			 */
1063
-			$qb->where(
1064
-				$qb->expr()->andX(
1065
-					$qb->expr()->orX(
1066
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1067
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1068
-					),
1069
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1070
-				)
1071
-			);
1072
-
1073
-			$qb->orWhere(
1074
-				$qb->expr()->andX(
1075
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1076
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1077
-				)
1078
-			);
1079
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1080
-			/*
1063
+            $qb->where(
1064
+                $qb->expr()->andX(
1065
+                    $qb->expr()->orX(
1066
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1067
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1068
+                    ),
1069
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1070
+                )
1071
+            );
1072
+
1073
+            $qb->orWhere(
1074
+                $qb->expr()->andX(
1075
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1076
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1077
+                )
1078
+            );
1079
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1080
+            /*
1081 1081
 			 * Delete all link shares owned by this user.
1082 1082
 			 * And all link shares initiated by this user (until #22327 is in)
1083 1083
 			 */
1084
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1085
-
1086
-			$qb->andWhere(
1087
-				$qb->expr()->orX(
1088
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1089
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1090
-				)
1091
-			);
1092
-		}
1093
-
1094
-		$qb->execute();
1095
-	}
1096
-
1097
-	/**
1098
-	 * Delete all shares received by this group. As well as any custom group
1099
-	 * shares for group members.
1100
-	 *
1101
-	 * @param string $gid
1102
-	 */
1103
-	public function groupDeleted($gid) {
1104
-		/*
1084
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1085
+
1086
+            $qb->andWhere(
1087
+                $qb->expr()->orX(
1088
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1089
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1090
+                )
1091
+            );
1092
+        }
1093
+
1094
+        $qb->execute();
1095
+    }
1096
+
1097
+    /**
1098
+     * Delete all shares received by this group. As well as any custom group
1099
+     * shares for group members.
1100
+     *
1101
+     * @param string $gid
1102
+     */
1103
+    public function groupDeleted($gid) {
1104
+        /*
1105 1105
 		 * First delete all custom group shares for group members
1106 1106
 		 */
1107
-		$qb = $this->dbConn->getQueryBuilder();
1108
-		$qb->select('id')
1109
-			->from('share')
1110
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1111
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1112
-
1113
-		$cursor = $qb->execute();
1114
-		$ids = [];
1115
-		while($row = $cursor->fetch()) {
1116
-			$ids[] = (int)$row['id'];
1117
-		}
1118
-		$cursor->closeCursor();
1119
-
1120
-		if (!empty($ids)) {
1121
-			$chunks = array_chunk($ids, 100);
1122
-			foreach ($chunks as $chunk) {
1123
-				$qb->delete('share')
1124
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1125
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1126
-				$qb->execute();
1127
-			}
1128
-		}
1129
-
1130
-		/*
1107
+        $qb = $this->dbConn->getQueryBuilder();
1108
+        $qb->select('id')
1109
+            ->from('share')
1110
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1111
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1112
+
1113
+        $cursor = $qb->execute();
1114
+        $ids = [];
1115
+        while($row = $cursor->fetch()) {
1116
+            $ids[] = (int)$row['id'];
1117
+        }
1118
+        $cursor->closeCursor();
1119
+
1120
+        if (!empty($ids)) {
1121
+            $chunks = array_chunk($ids, 100);
1122
+            foreach ($chunks as $chunk) {
1123
+                $qb->delete('share')
1124
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1125
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1126
+                $qb->execute();
1127
+            }
1128
+        }
1129
+
1130
+        /*
1131 1131
 		 * Now delete all the group shares
1132 1132
 		 */
1133
-		$qb = $this->dbConn->getQueryBuilder();
1134
-		$qb->delete('share')
1135
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1136
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1137
-		$qb->execute();
1138
-	}
1139
-
1140
-	/**
1141
-	 * Delete custom group shares to this group for this user
1142
-	 *
1143
-	 * @param string $uid
1144
-	 * @param string $gid
1145
-	 */
1146
-	public function userDeletedFromGroup($uid, $gid) {
1147
-		/*
1133
+        $qb = $this->dbConn->getQueryBuilder();
1134
+        $qb->delete('share')
1135
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1136
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1137
+        $qb->execute();
1138
+    }
1139
+
1140
+    /**
1141
+     * Delete custom group shares to this group for this user
1142
+     *
1143
+     * @param string $uid
1144
+     * @param string $gid
1145
+     */
1146
+    public function userDeletedFromGroup($uid, $gid) {
1147
+        /*
1148 1148
 		 * Get all group shares
1149 1149
 		 */
1150
-		$qb = $this->dbConn->getQueryBuilder();
1151
-		$qb->select('id')
1152
-			->from('share')
1153
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1154
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1155
-
1156
-		$cursor = $qb->execute();
1157
-		$ids = [];
1158
-		while($row = $cursor->fetch()) {
1159
-			$ids[] = (int)$row['id'];
1160
-		}
1161
-		$cursor->closeCursor();
1162
-
1163
-		if (!empty($ids)) {
1164
-			$chunks = array_chunk($ids, 100);
1165
-			foreach ($chunks as $chunk) {
1166
-				/*
1150
+        $qb = $this->dbConn->getQueryBuilder();
1151
+        $qb->select('id')
1152
+            ->from('share')
1153
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1154
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1155
+
1156
+        $cursor = $qb->execute();
1157
+        $ids = [];
1158
+        while($row = $cursor->fetch()) {
1159
+            $ids[] = (int)$row['id'];
1160
+        }
1161
+        $cursor->closeCursor();
1162
+
1163
+        if (!empty($ids)) {
1164
+            $chunks = array_chunk($ids, 100);
1165
+            foreach ($chunks as $chunk) {
1166
+                /*
1167 1167
 				 * Delete all special shares wit this users for the found group shares
1168 1168
 				 */
1169
-				$qb->delete('share')
1170
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1171
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1172
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1173
-				$qb->execute();
1174
-			}
1175
-		}
1176
-	}
1177
-
1178
-	/**
1179
-	 * @inheritdoc
1180
-	 */
1181
-	public function getAccessList($nodes, $currentAccess) {
1182
-		$ids = [];
1183
-		foreach ($nodes as $node) {
1184
-			$ids[] = $node->getId();
1185
-		}
1186
-
1187
-		$qb = $this->dbConn->getQueryBuilder();
1188
-
1189
-		$or = $qb->expr()->orX(
1190
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1191
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1192
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1193
-		);
1194
-
1195
-		if ($currentAccess) {
1196
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1197
-		}
1198
-
1199
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1200
-			->from('share')
1201
-			->where(
1202
-				$or
1203
-			)
1204
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1205
-			->andWhere($qb->expr()->orX(
1206
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1207
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1208
-			));
1209
-		$cursor = $qb->execute();
1210
-
1211
-		$users = [];
1212
-		$link = false;
1213
-		while($row = $cursor->fetch()) {
1214
-			$type = (int)$row['share_type'];
1215
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1216
-				$uid = $row['share_with'];
1217
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1218
-				$users[$uid][$row['id']] = $row;
1219
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1220
-				$gid = $row['share_with'];
1221
-				$group = $this->groupManager->get($gid);
1222
-
1223
-				if ($group === null) {
1224
-					continue;
1225
-				}
1226
-
1227
-				$userList = $group->getUsers();
1228
-				foreach ($userList as $user) {
1229
-					$uid = $user->getUID();
1230
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1231
-					$users[$uid][$row['id']] = $row;
1232
-				}
1233
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1234
-				$link = true;
1235
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1236
-				$uid = $row['share_with'];
1237
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1238
-				$users[$uid][$row['id']] = $row;
1239
-			}
1240
-		}
1241
-		$cursor->closeCursor();
1242
-
1243
-		if ($currentAccess === true) {
1244
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1245
-			$users = array_filter($users);
1246
-		} else {
1247
-			$users = array_keys($users);
1248
-		}
1249
-
1250
-		return ['users' => $users, 'public' => $link];
1251
-	}
1252
-
1253
-	/**
1254
-	 * For each user the path with the fewest slashes is returned
1255
-	 * @param array $shares
1256
-	 * @return array
1257
-	 */
1258
-	protected function filterSharesOfUser(array $shares) {
1259
-		// Group shares when the user has a share exception
1260
-		foreach ($shares as $id => $share) {
1261
-			$type = (int) $share['share_type'];
1262
-			$permissions = (int) $share['permissions'];
1263
-
1264
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1265
-				unset($shares[$share['parent']]);
1266
-
1267
-				if ($permissions === 0) {
1268
-					unset($shares[$id]);
1269
-				}
1270
-			}
1271
-		}
1272
-
1273
-		$best = [];
1274
-		$bestDepth = 0;
1275
-		foreach ($shares as $id => $share) {
1276
-			$depth = substr_count($share['file_target'], '/');
1277
-			if (empty($best) || $depth < $bestDepth) {
1278
-				$bestDepth = $depth;
1279
-				$best = [
1280
-					'node_id' => $share['file_source'],
1281
-					'node_path' => $share['file_target'],
1282
-				];
1283
-			}
1284
-		}
1285
-
1286
-		return $best;
1287
-	}
1288
-
1289
-	/**
1290
-	 * propagate notes to the recipients
1291
-	 *
1292
-	 * @param IShare $share
1293
-	 * @throws \OCP\Files\NotFoundException
1294
-	 */
1295
-	private function propagateNote(IShare $share) {
1296
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1297
-			$user = $this->userManager->get($share->getSharedWith());
1298
-			$this->sendNote([$user], $share);
1299
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1300
-			$group = $this->groupManager->get($share->getSharedWith());
1301
-			$groupMembers = $group->getUsers();
1302
-			$this->sendNote($groupMembers, $share);
1303
-		}
1304
-	}
1305
-
1306
-	/**
1307
-	 * send note by mail
1308
-	 *
1309
-	 * @param array $recipients
1310
-	 * @param IShare $share
1311
-	 * @throws \OCP\Files\NotFoundException
1312
-	 */
1313
-	private function sendNote(array $recipients, IShare $share) {
1314
-
1315
-		$toList = [];
1316
-
1317
-		foreach ($recipients as $recipient) {
1318
-			/** @var IUser $recipient */
1319
-			$email = $recipient->getEMailAddress();
1320
-			if ($email) {
1321
-				$toList[$email] = $recipient->getDisplayName();
1322
-			}
1323
-		}
1324
-
1325
-		if (!empty($toList)) {
1326
-
1327
-			$filename = $share->getNode()->getName();
1328
-			$initiator = $share->getSharedBy();
1329
-			$note = $share->getNote();
1330
-
1331
-			$initiatorUser = $this->userManager->get($initiator);
1332
-			$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1333
-			$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1334
-			$plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1335
-			$htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1336
-			$message = $this->mailer->createMessage();
1337
-
1338
-			$emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1339
-
1340
-			$emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1341
-			$emailTemplate->addHeader();
1342
-			$emailTemplate->addHeading($htmlHeading, $plainHeading);
1343
-			$emailTemplate->addBodyText(htmlspecialchars($note), $note);
1344
-
1345
-			$link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1346
-			$emailTemplate->addBodyButton(
1347
-				$this->l->t('Open »%s«', [$filename]),
1348
-				$link
1349
-			);
1350
-
1351
-
1352
-			// The "From" contains the sharers name
1353
-			$instanceName = $this->defaults->getName();
1354
-			$senderName = $this->l->t(
1355
-				'%1$s via %2$s',
1356
-				[
1357
-					$initiatorDisplayName,
1358
-					$instanceName
1359
-				]
1360
-			);
1361
-			$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1362
-			if ($initiatorEmailAddress !== null) {
1363
-				$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1364
-				$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1365
-			} else {
1366
-				$emailTemplate->addFooter();
1367
-			}
1368
-
1369
-			if (count($toList) === 1) {
1370
-				$message->setTo($toList);
1371
-			} else {
1372
-				$message->setTo([]);
1373
-				$message->setBcc($toList);
1374
-			}
1375
-			$message->useTemplate($emailTemplate);
1376
-			$this->mailer->send($message);
1377
-		}
1378
-
1379
-	}
1169
+                $qb->delete('share')
1170
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1171
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1172
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1173
+                $qb->execute();
1174
+            }
1175
+        }
1176
+    }
1177
+
1178
+    /**
1179
+     * @inheritdoc
1180
+     */
1181
+    public function getAccessList($nodes, $currentAccess) {
1182
+        $ids = [];
1183
+        foreach ($nodes as $node) {
1184
+            $ids[] = $node->getId();
1185
+        }
1186
+
1187
+        $qb = $this->dbConn->getQueryBuilder();
1188
+
1189
+        $or = $qb->expr()->orX(
1190
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1191
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1192
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1193
+        );
1194
+
1195
+        if ($currentAccess) {
1196
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1197
+        }
1198
+
1199
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1200
+            ->from('share')
1201
+            ->where(
1202
+                $or
1203
+            )
1204
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1205
+            ->andWhere($qb->expr()->orX(
1206
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1207
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1208
+            ));
1209
+        $cursor = $qb->execute();
1210
+
1211
+        $users = [];
1212
+        $link = false;
1213
+        while($row = $cursor->fetch()) {
1214
+            $type = (int)$row['share_type'];
1215
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1216
+                $uid = $row['share_with'];
1217
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1218
+                $users[$uid][$row['id']] = $row;
1219
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1220
+                $gid = $row['share_with'];
1221
+                $group = $this->groupManager->get($gid);
1222
+
1223
+                if ($group === null) {
1224
+                    continue;
1225
+                }
1226
+
1227
+                $userList = $group->getUsers();
1228
+                foreach ($userList as $user) {
1229
+                    $uid = $user->getUID();
1230
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1231
+                    $users[$uid][$row['id']] = $row;
1232
+                }
1233
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1234
+                $link = true;
1235
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1236
+                $uid = $row['share_with'];
1237
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1238
+                $users[$uid][$row['id']] = $row;
1239
+            }
1240
+        }
1241
+        $cursor->closeCursor();
1242
+
1243
+        if ($currentAccess === true) {
1244
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1245
+            $users = array_filter($users);
1246
+        } else {
1247
+            $users = array_keys($users);
1248
+        }
1249
+
1250
+        return ['users' => $users, 'public' => $link];
1251
+    }
1252
+
1253
+    /**
1254
+     * For each user the path with the fewest slashes is returned
1255
+     * @param array $shares
1256
+     * @return array
1257
+     */
1258
+    protected function filterSharesOfUser(array $shares) {
1259
+        // Group shares when the user has a share exception
1260
+        foreach ($shares as $id => $share) {
1261
+            $type = (int) $share['share_type'];
1262
+            $permissions = (int) $share['permissions'];
1263
+
1264
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1265
+                unset($shares[$share['parent']]);
1266
+
1267
+                if ($permissions === 0) {
1268
+                    unset($shares[$id]);
1269
+                }
1270
+            }
1271
+        }
1272
+
1273
+        $best = [];
1274
+        $bestDepth = 0;
1275
+        foreach ($shares as $id => $share) {
1276
+            $depth = substr_count($share['file_target'], '/');
1277
+            if (empty($best) || $depth < $bestDepth) {
1278
+                $bestDepth = $depth;
1279
+                $best = [
1280
+                    'node_id' => $share['file_source'],
1281
+                    'node_path' => $share['file_target'],
1282
+                ];
1283
+            }
1284
+        }
1285
+
1286
+        return $best;
1287
+    }
1288
+
1289
+    /**
1290
+     * propagate notes to the recipients
1291
+     *
1292
+     * @param IShare $share
1293
+     * @throws \OCP\Files\NotFoundException
1294
+     */
1295
+    private function propagateNote(IShare $share) {
1296
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1297
+            $user = $this->userManager->get($share->getSharedWith());
1298
+            $this->sendNote([$user], $share);
1299
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1300
+            $group = $this->groupManager->get($share->getSharedWith());
1301
+            $groupMembers = $group->getUsers();
1302
+            $this->sendNote($groupMembers, $share);
1303
+        }
1304
+    }
1305
+
1306
+    /**
1307
+     * send note by mail
1308
+     *
1309
+     * @param array $recipients
1310
+     * @param IShare $share
1311
+     * @throws \OCP\Files\NotFoundException
1312
+     */
1313
+    private function sendNote(array $recipients, IShare $share) {
1314
+
1315
+        $toList = [];
1316
+
1317
+        foreach ($recipients as $recipient) {
1318
+            /** @var IUser $recipient */
1319
+            $email = $recipient->getEMailAddress();
1320
+            if ($email) {
1321
+                $toList[$email] = $recipient->getDisplayName();
1322
+            }
1323
+        }
1324
+
1325
+        if (!empty($toList)) {
1326
+
1327
+            $filename = $share->getNode()->getName();
1328
+            $initiator = $share->getSharedBy();
1329
+            $note = $share->getNote();
1330
+
1331
+            $initiatorUser = $this->userManager->get($initiator);
1332
+            $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1333
+            $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1334
+            $plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1335
+            $htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1336
+            $message = $this->mailer->createMessage();
1337
+
1338
+            $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1339
+
1340
+            $emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1341
+            $emailTemplate->addHeader();
1342
+            $emailTemplate->addHeading($htmlHeading, $plainHeading);
1343
+            $emailTemplate->addBodyText(htmlspecialchars($note), $note);
1344
+
1345
+            $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1346
+            $emailTemplate->addBodyButton(
1347
+                $this->l->t('Open »%s«', [$filename]),
1348
+                $link
1349
+            );
1350
+
1351
+
1352
+            // The "From" contains the sharers name
1353
+            $instanceName = $this->defaults->getName();
1354
+            $senderName = $this->l->t(
1355
+                '%1$s via %2$s',
1356
+                [
1357
+                    $initiatorDisplayName,
1358
+                    $instanceName
1359
+                ]
1360
+            );
1361
+            $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1362
+            if ($initiatorEmailAddress !== null) {
1363
+                $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1364
+                $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1365
+            } else {
1366
+                $emailTemplate->addFooter();
1367
+            }
1368
+
1369
+            if (count($toList) === 1) {
1370
+                $message->setTo($toList);
1371
+            } else {
1372
+                $message->setTo([]);
1373
+                $message->setBcc($toList);
1374
+            }
1375
+            $message->useTemplate($emailTemplate);
1376
+            $this->mailer->send($message);
1377
+        }
1378
+
1379
+    }
1380 1380
 }
Please login to merge, or discard this patch.