Passed
Push — master ( 581704...2efa00 )
by Roeland
11:12 queued 11s
created
lib/public/Share/IManager.php 1 patch
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -43,389 +43,389 @@
 block discarded – undo
43 43
  */
44 44
 interface IManager {
45 45
 
46
-	/**
47
-	 * Create a Share
48
-	 *
49
-	 * @param IShare $share
50
-	 * @return IShare The share object
51
-	 * @throws \Exception
52
-	 * @since 9.0.0
53
-	 */
54
-	public function createShare(IShare $share);
55
-
56
-	/**
57
-	 * Update a share.
58
-	 * The target of the share can't be changed this way: use moveShare
59
-	 * The share can't be removed this way (permission 0): use deleteShare
60
-	 * The state can't be changed this way: use acceptShare
61
-	 *
62
-	 * @param IShare $share
63
-	 * @return IShare The share object
64
-	 * @throws \InvalidArgumentException
65
-	 * @since 9.0.0
66
-	 */
67
-	public function updateShare(IShare $share);
68
-
69
-	/**
70
-	 * Accept a share.
71
-	 *
72
-	 * @param IShare $share
73
-	 * @param string $recipientId
74
-	 * @return IShare The share object
75
-	 * @throws \InvalidArgumentException
76
-	 * @since 18.0.0
77
-	 */
78
-	public function acceptShare(IShare $share, string $recipientId): IShare;
79
-
80
-	/**
81
-	 * Delete a share
82
-	 *
83
-	 * @param IShare $share
84
-	 * @throws ShareNotFound
85
-	 * @throws \InvalidArgumentException
86
-	 * @since 9.0.0
87
-	 */
88
-	public function deleteShare(IShare $share);
89
-
90
-	/**
91
-	 * Unshare a file as the recipient.
92
-	 * This can be different from a regular delete for example when one of
93
-	 * the users in a groups deletes that share. But the provider should
94
-	 * handle this.
95
-	 *
96
-	 * @param IShare $share
97
-	 * @param string $recipientId
98
-	 * @since 9.0.0
99
-	 */
100
-	public function deleteFromSelf(IShare $share, $recipientId);
101
-
102
-	/**
103
-	 * Restore the share when it has been deleted
104
-	 * Certain share types can be restored when they have been deleted
105
-	 * but the provider should properly handle this\
106
-	 *
107
-	 * @param IShare $share The share to restore
108
-	 * @param string $recipientId The user to restore the share for
109
-	 * @return IShare The restored share object
110
-	 * @throws GenericShareException In case restoring the share failed
111
-	 *
112
-	 * @since 14.0.0
113
-	 */
114
-	public function restoreShare(IShare $share, string $recipientId): IShare;
115
-
116
-	/**
117
-	 * Move the share as a recipient of the share.
118
-	 * This is updating the share target. So where the recipient has the share mounted.
119
-	 *
120
-	 * @param IShare $share
121
-	 * @param string $recipientId
122
-	 * @return IShare
123
-	 * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
124
-	 * @since 9.0.0
125
-	 */
126
-	public function moveShare(IShare $share, $recipientId);
127
-
128
-	/**
129
-	 * Get all shares shared by (initiated) by the provided user in a folder.
130
-	 *
131
-	 * @param string $userId
132
-	 * @param Folder $node
133
-	 * @param bool $reshares
134
-	 * @return IShare[][] [$fileId => IShare[], ...]
135
-	 * @since 11.0.0
136
-	 */
137
-	public function getSharesInFolder($userId, Folder $node, $reshares = false);
138
-
139
-	/**
140
-	 * Get shares shared by (initiated) by the provided user.
141
-	 *
142
-	 * @param string $userId
143
-	 * @param int $shareType
144
-	 * @param Node|null $path
145
-	 * @param bool $reshares
146
-	 * @param int $limit The maximum number of returned results, -1 for all results
147
-	 * @param int $offset
148
-	 * @return IShare[]
149
-	 * @since 9.0.0
150
-	 */
151
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
152
-
153
-	/**
154
-	 * Get shares shared with $user.
155
-	 * Filter by $node if provided
156
-	 *
157
-	 * @param string $userId
158
-	 * @param int $shareType
159
-	 * @param Node|null $node
160
-	 * @param int $limit The maximum number of shares returned, -1 for all
161
-	 * @param int $offset
162
-	 * @return IShare[]
163
-	 * @since 9.0.0
164
-	 */
165
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
166
-
167
-	/**
168
-	 * Get deleted shares shared with $user.
169
-	 * Filter by $node if provided
170
-	 *
171
-	 * @param string $userId
172
-	 * @param int $shareType
173
-	 * @param Node|null $node
174
-	 * @param int $limit The maximum number of shares returned, -1 for all
175
-	 * @param int $offset
176
-	 * @return IShare[]
177
-	 * @since 14.0.0
178
-	 */
179
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
180
-
181
-	/**
182
-	 * Retrieve a share by the share id.
183
-	 * If the recipient is set make sure to retrieve the file for that user.
184
-	 * This makes sure that if a user has moved/deleted a group share this
185
-	 * is reflected.
186
-	 *
187
-	 * @param string $id
188
-	 * @param string|null $recipient userID of the recipient
189
-	 * @return IShare
190
-	 * @throws ShareNotFound
191
-	 * @since 9.0.0
192
-	 */
193
-	public function getShareById($id, $recipient = null);
194
-
195
-	/**
196
-	 * Get the share by token possible with password
197
-	 *
198
-	 * @param string $token
199
-	 * @return IShare
200
-	 * @throws ShareNotFound
201
-	 * @since 9.0.0
202
-	 */
203
-	public function getShareByToken($token);
204
-
205
-	/**
206
-	 * Verify the password of a public share
207
-	 *
208
-	 * @param IShare $share
209
-	 * @param string $password
210
-	 * @return bool
211
-	 * @since 9.0.0
212
-	 */
213
-	public function checkPassword(IShare $share, $password);
214
-
215
-	/**
216
-	 * The user with UID is deleted.
217
-	 * All share providers have to cleanup the shares with this user as well
218
-	 * as shares owned by this user.
219
-	 * Shares only initiated by this user are fine.
220
-	 *
221
-	 * @param string $uid
222
-	 * @since 9.1.0
223
-	 */
224
-	public function userDeleted($uid);
225
-
226
-	/**
227
-	 * The group with $gid is deleted
228
-	 * We need to clear up all shares to this group
229
-	 *
230
-	 * @param string $gid
231
-	 * @since 9.1.0
232
-	 */
233
-	public function groupDeleted($gid);
234
-
235
-	/**
236
-	 * The user $uid is deleted from the group $gid
237
-	 * All user specific group shares have to be removed
238
-	 *
239
-	 * @param string $uid
240
-	 * @param string $gid
241
-	 * @since 9.1.0
242
-	 */
243
-	public function userDeletedFromGroup($uid, $gid);
244
-
245
-	/**
246
-	 * Get access list to a path. This means
247
-	 * all the users that can access a given path.
248
-	 *
249
-	 * Consider:
250
-	 * -root
251
-	 * |-folder1 (23)
252
-	 *  |-folder2 (32)
253
-	 *   |-fileA (42)
254
-	 *
255
-	 * fileA is shared with user1 and user1@server1
256
-	 * folder2 is shared with group2 (user4 is a member of group2)
257
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
258
-	 *
259
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
260
-	 * [
261
-	 *  users  => [
262
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
263
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
264
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
265
-	 *  ],
266
-	 *  remote => [
267
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
268
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
269
-	 *  ],
270
-	 *  public => bool
271
-	 *  mail => bool
272
-	 * ]
273
-	 *
274
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
275
-	 * [
276
-	 *  users  => ['user1', 'user2', 'user4'],
277
-	 *  remote => bool,
278
-	 *  public => bool
279
-	 *  mail => bool
280
-	 * ]
281
-	 *
282
-	 * This is required for encryption/activity
283
-	 *
284
-	 * @param \OCP\Files\Node $path
285
-	 * @param bool $recursive Should we check all parent folders as well
286
-	 * @param bool $currentAccess Should the user have currently access to the file
287
-	 * @return array
288
-	 * @since 12
289
-	 */
290
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
291
-
292
-	/**
293
-	 * Instantiates a new share object. This is to be passed to
294
-	 * createShare.
295
-	 *
296
-	 * @return IShare
297
-	 * @since 9.0.0
298
-	 */
299
-	public function newShare();
300
-
301
-	/**
302
-	 * Is the share API enabled
303
-	 *
304
-	 * @return bool
305
-	 * @since 9.0.0
306
-	 */
307
-	public function shareApiEnabled();
308
-
309
-	/**
310
-	 * Is public link sharing enabled
311
-	 *
312
-	 * @return bool
313
-	 * @since 9.0.0
314
-	 */
315
-	public function shareApiAllowLinks();
316
-
317
-	/**
318
-	 * Is password on public link requires
319
-	 *
320
-	 * @return bool
321
-	 * @since 9.0.0
322
-	 */
323
-	public function shareApiLinkEnforcePassword();
324
-
325
-	/**
326
-	 * Is default expire date enabled
327
-	 *
328
-	 * @return bool
329
-	 * @since 9.0.0
330
-	 */
331
-	public function shareApiLinkDefaultExpireDate();
332
-
333
-	/**
334
-	 * Is default expire date enforced
335
-	 *`
336
-	 * @return bool
337
-	 * @since 9.0.0
338
-	 */
339
-	public function shareApiLinkDefaultExpireDateEnforced();
340
-
341
-	/**
342
-	 * Number of default expire days
343
-	 *
344
-	 * @return int
345
-	 * @since 9.0.0
346
-	 */
347
-	public function shareApiLinkDefaultExpireDays();
348
-
349
-	/**
350
-	 * Allow public upload on link shares
351
-	 *
352
-	 * @return bool
353
-	 * @since 9.0.0
354
-	 */
355
-	public function shareApiLinkAllowPublicUpload();
356
-
357
-	/**
358
-	 * check if user can only share with group members
359
-	 * @return bool
360
-	 * @since 9.0.0
361
-	 */
362
-	public function shareWithGroupMembersOnly();
363
-
364
-	/**
365
-	 * Check if users can share with groups
366
-	 * @return bool
367
-	 * @since 9.0.1
368
-	 */
369
-	public function allowGroupSharing();
370
-
371
-	/**
372
-	 * Check if user enumeration is allowed
373
-	 *
374
-	 * @return bool
375
-	 * @since 19.0.0
376
-	 */
377
-	public function allowEnumeration(): bool;
378
-
379
-	/**
380
-	 * Check if user enumeration is limited to the users groups
381
-	 *
382
-	 * @return bool
383
-	 * @since 19.0.0
384
-	 */
385
-	public function limitEnumerationToGroups(): bool;
386
-
387
-	/**
388
-	 * Check if sharing is disabled for the given user
389
-	 *
390
-	 * @param string $userId
391
-	 * @return bool
392
-	 * @since 9.0.0
393
-	 */
394
-	public function sharingDisabledForUser($userId);
395
-
396
-	/**
397
-	 * Check if outgoing server2server shares are allowed
398
-	 * @return bool
399
-	 * @since 9.0.0
400
-	 */
401
-	public function outgoingServer2ServerSharesAllowed();
402
-
403
-	/**
404
-	 * Check if outgoing server2server shares are allowed
405
-	 * @return bool
406
-	 * @since 14.0.0
407
-	 */
408
-	public function outgoingServer2ServerGroupSharesAllowed();
409
-
410
-
411
-	/**
412
-	 * Check if a given share provider exists
413
-	 * @param int $shareType
414
-	 * @return bool
415
-	 * @since 11.0.0
416
-	 */
417
-	public function shareProviderExists($shareType);
418
-
419
-	/**
420
-	 * @Internal
421
-	 *
422
-	 * Get all the shares as iterable to reduce memory overhead
423
-	 * Note, since this opens up database cursors the iterable should
424
-	 * be fully itterated.
425
-	 *
426
-	 * @return iterable
427
-	 * @since 18.0.0
428
-	 */
429
-	public function getAllShares(): iterable;
46
+    /**
47
+     * Create a Share
48
+     *
49
+     * @param IShare $share
50
+     * @return IShare The share object
51
+     * @throws \Exception
52
+     * @since 9.0.0
53
+     */
54
+    public function createShare(IShare $share);
55
+
56
+    /**
57
+     * Update a share.
58
+     * The target of the share can't be changed this way: use moveShare
59
+     * The share can't be removed this way (permission 0): use deleteShare
60
+     * The state can't be changed this way: use acceptShare
61
+     *
62
+     * @param IShare $share
63
+     * @return IShare The share object
64
+     * @throws \InvalidArgumentException
65
+     * @since 9.0.0
66
+     */
67
+    public function updateShare(IShare $share);
68
+
69
+    /**
70
+     * Accept a share.
71
+     *
72
+     * @param IShare $share
73
+     * @param string $recipientId
74
+     * @return IShare The share object
75
+     * @throws \InvalidArgumentException
76
+     * @since 18.0.0
77
+     */
78
+    public function acceptShare(IShare $share, string $recipientId): IShare;
79
+
80
+    /**
81
+     * Delete a share
82
+     *
83
+     * @param IShare $share
84
+     * @throws ShareNotFound
85
+     * @throws \InvalidArgumentException
86
+     * @since 9.0.0
87
+     */
88
+    public function deleteShare(IShare $share);
89
+
90
+    /**
91
+     * Unshare a file as the recipient.
92
+     * This can be different from a regular delete for example when one of
93
+     * the users in a groups deletes that share. But the provider should
94
+     * handle this.
95
+     *
96
+     * @param IShare $share
97
+     * @param string $recipientId
98
+     * @since 9.0.0
99
+     */
100
+    public function deleteFromSelf(IShare $share, $recipientId);
101
+
102
+    /**
103
+     * Restore the share when it has been deleted
104
+     * Certain share types can be restored when they have been deleted
105
+     * but the provider should properly handle this\
106
+     *
107
+     * @param IShare $share The share to restore
108
+     * @param string $recipientId The user to restore the share for
109
+     * @return IShare The restored share object
110
+     * @throws GenericShareException In case restoring the share failed
111
+     *
112
+     * @since 14.0.0
113
+     */
114
+    public function restoreShare(IShare $share, string $recipientId): IShare;
115
+
116
+    /**
117
+     * Move the share as a recipient of the share.
118
+     * This is updating the share target. So where the recipient has the share mounted.
119
+     *
120
+     * @param IShare $share
121
+     * @param string $recipientId
122
+     * @return IShare
123
+     * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
124
+     * @since 9.0.0
125
+     */
126
+    public function moveShare(IShare $share, $recipientId);
127
+
128
+    /**
129
+     * Get all shares shared by (initiated) by the provided user in a folder.
130
+     *
131
+     * @param string $userId
132
+     * @param Folder $node
133
+     * @param bool $reshares
134
+     * @return IShare[][] [$fileId => IShare[], ...]
135
+     * @since 11.0.0
136
+     */
137
+    public function getSharesInFolder($userId, Folder $node, $reshares = false);
138
+
139
+    /**
140
+     * Get shares shared by (initiated) by the provided user.
141
+     *
142
+     * @param string $userId
143
+     * @param int $shareType
144
+     * @param Node|null $path
145
+     * @param bool $reshares
146
+     * @param int $limit The maximum number of returned results, -1 for all results
147
+     * @param int $offset
148
+     * @return IShare[]
149
+     * @since 9.0.0
150
+     */
151
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
152
+
153
+    /**
154
+     * Get shares shared with $user.
155
+     * Filter by $node if provided
156
+     *
157
+     * @param string $userId
158
+     * @param int $shareType
159
+     * @param Node|null $node
160
+     * @param int $limit The maximum number of shares returned, -1 for all
161
+     * @param int $offset
162
+     * @return IShare[]
163
+     * @since 9.0.0
164
+     */
165
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
166
+
167
+    /**
168
+     * Get deleted shares shared with $user.
169
+     * Filter by $node if provided
170
+     *
171
+     * @param string $userId
172
+     * @param int $shareType
173
+     * @param Node|null $node
174
+     * @param int $limit The maximum number of shares returned, -1 for all
175
+     * @param int $offset
176
+     * @return IShare[]
177
+     * @since 14.0.0
178
+     */
179
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
180
+
181
+    /**
182
+     * Retrieve a share by the share id.
183
+     * If the recipient is set make sure to retrieve the file for that user.
184
+     * This makes sure that if a user has moved/deleted a group share this
185
+     * is reflected.
186
+     *
187
+     * @param string $id
188
+     * @param string|null $recipient userID of the recipient
189
+     * @return IShare
190
+     * @throws ShareNotFound
191
+     * @since 9.0.0
192
+     */
193
+    public function getShareById($id, $recipient = null);
194
+
195
+    /**
196
+     * Get the share by token possible with password
197
+     *
198
+     * @param string $token
199
+     * @return IShare
200
+     * @throws ShareNotFound
201
+     * @since 9.0.0
202
+     */
203
+    public function getShareByToken($token);
204
+
205
+    /**
206
+     * Verify the password of a public share
207
+     *
208
+     * @param IShare $share
209
+     * @param string $password
210
+     * @return bool
211
+     * @since 9.0.0
212
+     */
213
+    public function checkPassword(IShare $share, $password);
214
+
215
+    /**
216
+     * The user with UID is deleted.
217
+     * All share providers have to cleanup the shares with this user as well
218
+     * as shares owned by this user.
219
+     * Shares only initiated by this user are fine.
220
+     *
221
+     * @param string $uid
222
+     * @since 9.1.0
223
+     */
224
+    public function userDeleted($uid);
225
+
226
+    /**
227
+     * The group with $gid is deleted
228
+     * We need to clear up all shares to this group
229
+     *
230
+     * @param string $gid
231
+     * @since 9.1.0
232
+     */
233
+    public function groupDeleted($gid);
234
+
235
+    /**
236
+     * The user $uid is deleted from the group $gid
237
+     * All user specific group shares have to be removed
238
+     *
239
+     * @param string $uid
240
+     * @param string $gid
241
+     * @since 9.1.0
242
+     */
243
+    public function userDeletedFromGroup($uid, $gid);
244
+
245
+    /**
246
+     * Get access list to a path. This means
247
+     * all the users that can access a given path.
248
+     *
249
+     * Consider:
250
+     * -root
251
+     * |-folder1 (23)
252
+     *  |-folder2 (32)
253
+     *   |-fileA (42)
254
+     *
255
+     * fileA is shared with user1 and user1@server1
256
+     * folder2 is shared with group2 (user4 is a member of group2)
257
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
258
+     *
259
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
260
+     * [
261
+     *  users  => [
262
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
263
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
264
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
265
+     *  ],
266
+     *  remote => [
267
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
268
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
269
+     *  ],
270
+     *  public => bool
271
+     *  mail => bool
272
+     * ]
273
+     *
274
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
275
+     * [
276
+     *  users  => ['user1', 'user2', 'user4'],
277
+     *  remote => bool,
278
+     *  public => bool
279
+     *  mail => bool
280
+     * ]
281
+     *
282
+     * This is required for encryption/activity
283
+     *
284
+     * @param \OCP\Files\Node $path
285
+     * @param bool $recursive Should we check all parent folders as well
286
+     * @param bool $currentAccess Should the user have currently access to the file
287
+     * @return array
288
+     * @since 12
289
+     */
290
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
291
+
292
+    /**
293
+     * Instantiates a new share object. This is to be passed to
294
+     * createShare.
295
+     *
296
+     * @return IShare
297
+     * @since 9.0.0
298
+     */
299
+    public function newShare();
300
+
301
+    /**
302
+     * Is the share API enabled
303
+     *
304
+     * @return bool
305
+     * @since 9.0.0
306
+     */
307
+    public function shareApiEnabled();
308
+
309
+    /**
310
+     * Is public link sharing enabled
311
+     *
312
+     * @return bool
313
+     * @since 9.0.0
314
+     */
315
+    public function shareApiAllowLinks();
316
+
317
+    /**
318
+     * Is password on public link requires
319
+     *
320
+     * @return bool
321
+     * @since 9.0.0
322
+     */
323
+    public function shareApiLinkEnforcePassword();
324
+
325
+    /**
326
+     * Is default expire date enabled
327
+     *
328
+     * @return bool
329
+     * @since 9.0.0
330
+     */
331
+    public function shareApiLinkDefaultExpireDate();
332
+
333
+    /**
334
+     * Is default expire date enforced
335
+     *`
336
+     * @return bool
337
+     * @since 9.0.0
338
+     */
339
+    public function shareApiLinkDefaultExpireDateEnforced();
340
+
341
+    /**
342
+     * Number of default expire days
343
+     *
344
+     * @return int
345
+     * @since 9.0.0
346
+     */
347
+    public function shareApiLinkDefaultExpireDays();
348
+
349
+    /**
350
+     * Allow public upload on link shares
351
+     *
352
+     * @return bool
353
+     * @since 9.0.0
354
+     */
355
+    public function shareApiLinkAllowPublicUpload();
356
+
357
+    /**
358
+     * check if user can only share with group members
359
+     * @return bool
360
+     * @since 9.0.0
361
+     */
362
+    public function shareWithGroupMembersOnly();
363
+
364
+    /**
365
+     * Check if users can share with groups
366
+     * @return bool
367
+     * @since 9.0.1
368
+     */
369
+    public function allowGroupSharing();
370
+
371
+    /**
372
+     * Check if user enumeration is allowed
373
+     *
374
+     * @return bool
375
+     * @since 19.0.0
376
+     */
377
+    public function allowEnumeration(): bool;
378
+
379
+    /**
380
+     * Check if user enumeration is limited to the users groups
381
+     *
382
+     * @return bool
383
+     * @since 19.0.0
384
+     */
385
+    public function limitEnumerationToGroups(): bool;
386
+
387
+    /**
388
+     * Check if sharing is disabled for the given user
389
+     *
390
+     * @param string $userId
391
+     * @return bool
392
+     * @since 9.0.0
393
+     */
394
+    public function sharingDisabledForUser($userId);
395
+
396
+    /**
397
+     * Check if outgoing server2server shares are allowed
398
+     * @return bool
399
+     * @since 9.0.0
400
+     */
401
+    public function outgoingServer2ServerSharesAllowed();
402
+
403
+    /**
404
+     * Check if outgoing server2server shares are allowed
405
+     * @return bool
406
+     * @since 14.0.0
407
+     */
408
+    public function outgoingServer2ServerGroupSharesAllowed();
409
+
410
+
411
+    /**
412
+     * Check if a given share provider exists
413
+     * @param int $shareType
414
+     * @return bool
415
+     * @since 11.0.0
416
+     */
417
+    public function shareProviderExists($shareType);
418
+
419
+    /**
420
+     * @Internal
421
+     *
422
+     * Get all the shares as iterable to reduce memory overhead
423
+     * Note, since this opens up database cursors the iterable should
424
+     * be fully itterated.
425
+     *
426
+     * @return iterable
427
+     * @since 18.0.0
428
+     */
429
+    public function getAllShares(): iterable;
430 430
 
431 431
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1749 added lines, -1749 removed lines patch added patch discarded remove patch
@@ -77,1776 +77,1776 @@
 block discarded – undo
77 77
  */
78 78
 class Manager implements IManager {
79 79
 
80
-	/** @var IProviderFactory */
81
-	private $factory;
82
-	/** @var ILogger */
83
-	private $logger;
84
-	/** @var IConfig */
85
-	private $config;
86
-	/** @var ISecureRandom */
87
-	private $secureRandom;
88
-	/** @var IHasher */
89
-	private $hasher;
90
-	/** @var IMountManager */
91
-	private $mountManager;
92
-	/** @var IGroupManager */
93
-	private $groupManager;
94
-	/** @var IL10N */
95
-	private $l;
96
-	/** @var IFactory */
97
-	private $l10nFactory;
98
-	/** @var IUserManager */
99
-	private $userManager;
100
-	/** @var IRootFolder */
101
-	private $rootFolder;
102
-	/** @var CappedMemoryCache */
103
-	private $sharingDisabledForUsersCache;
104
-	/** @var EventDispatcherInterface */
105
-	private $legacyDispatcher;
106
-	/** @var LegacyHooks */
107
-	private $legacyHooks;
108
-	/** @var IMailer */
109
-	private $mailer;
110
-	/** @var IURLGenerator */
111
-	private $urlGenerator;
112
-	/** @var \OC_Defaults */
113
-	private $defaults;
114
-	/** @var IEventDispatcher */
115
-	private $dispatcher;
116
-
117
-
118
-	/**
119
-	 * Manager constructor.
120
-	 *
121
-	 * @param ILogger $logger
122
-	 * @param IConfig $config
123
-	 * @param ISecureRandom $secureRandom
124
-	 * @param IHasher $hasher
125
-	 * @param IMountManager $mountManager
126
-	 * @param IGroupManager $groupManager
127
-	 * @param IL10N $l
128
-	 * @param IFactory $l10nFactory
129
-	 * @param IProviderFactory $factory
130
-	 * @param IUserManager $userManager
131
-	 * @param IRootFolder $rootFolder
132
-	 * @param EventDispatcherInterface $eventDispatcher
133
-	 * @param IMailer $mailer
134
-	 * @param IURLGenerator $urlGenerator
135
-	 * @param \OC_Defaults $defaults
136
-	 */
137
-	public function __construct(
138
-			ILogger $logger,
139
-			IConfig $config,
140
-			ISecureRandom $secureRandom,
141
-			IHasher $hasher,
142
-			IMountManager $mountManager,
143
-			IGroupManager $groupManager,
144
-			IL10N $l,
145
-			IFactory $l10nFactory,
146
-			IProviderFactory $factory,
147
-			IUserManager $userManager,
148
-			IRootFolder $rootFolder,
149
-			EventDispatcherInterface $legacyDispatcher,
150
-			IMailer $mailer,
151
-			IURLGenerator $urlGenerator,
152
-			\OC_Defaults $defaults,
153
-			IEventDispatcher $dispatcher
154
-	) {
155
-		$this->logger = $logger;
156
-		$this->config = $config;
157
-		$this->secureRandom = $secureRandom;
158
-		$this->hasher = $hasher;
159
-		$this->mountManager = $mountManager;
160
-		$this->groupManager = $groupManager;
161
-		$this->l = $l;
162
-		$this->l10nFactory = $l10nFactory;
163
-		$this->factory = $factory;
164
-		$this->userManager = $userManager;
165
-		$this->rootFolder = $rootFolder;
166
-		$this->legacyDispatcher = $legacyDispatcher;
167
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
168
-		$this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
169
-		$this->mailer = $mailer;
170
-		$this->urlGenerator = $urlGenerator;
171
-		$this->defaults = $defaults;
172
-		$this->dispatcher = $dispatcher;
173
-	}
174
-
175
-	/**
176
-	 * Convert from a full share id to a tuple (providerId, shareId)
177
-	 *
178
-	 * @param string $id
179
-	 * @return string[]
180
-	 */
181
-	private function splitFullId($id) {
182
-		return explode(':', $id, 2);
183
-	}
184
-
185
-	/**
186
-	 * Verify if a password meets all requirements
187
-	 *
188
-	 * @param string $password
189
-	 * @throws \Exception
190
-	 */
191
-	protected function verifyPassword($password) {
192
-		if ($password === null) {
193
-			// No password is set, check if this is allowed.
194
-			if ($this->shareApiLinkEnforcePassword()) {
195
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
196
-			}
197
-
198
-			return;
199
-		}
200
-
201
-		// Let others verify the password
202
-		try {
203
-			$this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
204
-		} catch (HintException $e) {
205
-			throw new \Exception($e->getHint());
206
-		}
207
-	}
208
-
209
-	/**
210
-	 * Check for generic requirements before creating a share
211
-	 *
212
-	 * @param \OCP\Share\IShare $share
213
-	 * @throws \InvalidArgumentException
214
-	 * @throws GenericShareException
215
-	 *
216
-	 * @suppress PhanUndeclaredClassMethod
217
-	 */
218
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
219
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
220
-			// We expect a valid user as sharedWith for user shares
221
-			if (!$this->userManager->userExists($share->getSharedWith())) {
222
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
223
-			}
224
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
225
-			// We expect a valid group as sharedWith for group shares
226
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
227
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
228
-			}
229
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
230
-			if ($share->getSharedWith() !== null) {
231
-				throw new \InvalidArgumentException('SharedWith should be empty');
232
-			}
233
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
234
-			if ($share->getSharedWith() === null) {
235
-				throw new \InvalidArgumentException('SharedWith should not be empty');
236
-			}
237
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238
-			if ($share->getSharedWith() === null) {
239
-				throw new \InvalidArgumentException('SharedWith should not be empty');
240
-			}
241
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
242
-			if ($share->getSharedWith() === null) {
243
-				throw new \InvalidArgumentException('SharedWith should not be empty');
244
-			}
245
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
246
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
247
-			if ($circle === null) {
248
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
249
-			}
250
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
251
-		} else {
252
-			// We can't handle other types yet
253
-			throw new \InvalidArgumentException('unknown share type');
254
-		}
255
-
256
-		// Verify the initiator of the share is set
257
-		if ($share->getSharedBy() === null) {
258
-			throw new \InvalidArgumentException('SharedBy should be set');
259
-		}
260
-
261
-		// Cannot share with yourself
262
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
263
-			$share->getSharedWith() === $share->getSharedBy()) {
264
-			throw new \InvalidArgumentException('Can’t share with yourself');
265
-		}
266
-
267
-		// The path should be set
268
-		if ($share->getNode() === null) {
269
-			throw new \InvalidArgumentException('Path should be set');
270
-		}
271
-
272
-		// And it should be a file or a folder
273
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
274
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
275
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
276
-		}
277
-
278
-		// And you can't share your rootfolder
279
-		if ($this->userManager->userExists($share->getSharedBy())) {
280
-			$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
281
-			$userFolderPath = $userFolder->getPath();
282
-		} else {
283
-			$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
284
-			$userFolderPath = $userFolder->getPath();
285
-		}
286
-		if ($userFolderPath === $share->getNode()->getPath()) {
287
-			throw new \InvalidArgumentException('You can’t share your root folder');
288
-		}
289
-
290
-		// Check if we actually have share permissions
291
-		if (!$share->getNode()->isShareable()) {
292
-			$path = $userFolder->getRelativePath($share->getNode()->getPath());
293
-			$message_t = $this->l->t('You are not allowed to share %s', [$path]);
294
-			throw new GenericShareException($message_t, $message_t, 404);
295
-		}
296
-
297
-		// Permissions should be set
298
-		if ($share->getPermissions() === null) {
299
-			throw new \InvalidArgumentException('A share requires permissions');
300
-		}
301
-
302
-		$isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
303
-		$permissions = 0;
304
-		$mount = $share->getNode()->getMountPoint();
305
-		if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
306
-			// When it's a reshare use the parent share permissions as maximum
307
-			$userMountPointId = $mount->getStorageRootId();
308
-			$userMountPoints = $userFolder->getById($userMountPointId);
309
-			$userMountPoint = array_shift($userMountPoints);
310
-
311
-			/* Check if this is an incoming share */
312
-			$incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
313
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
314
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
315
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
316
-
317
-			/** @var \OCP\Share\IShare[] $incomingShares */
318
-			if (!empty($incomingShares)) {
319
-				foreach ($incomingShares as $incomingShare) {
320
-					$permissions |= $incomingShare->getPermissions();
321
-				}
322
-			}
323
-		} else {
324
-			/*
80
+    /** @var IProviderFactory */
81
+    private $factory;
82
+    /** @var ILogger */
83
+    private $logger;
84
+    /** @var IConfig */
85
+    private $config;
86
+    /** @var ISecureRandom */
87
+    private $secureRandom;
88
+    /** @var IHasher */
89
+    private $hasher;
90
+    /** @var IMountManager */
91
+    private $mountManager;
92
+    /** @var IGroupManager */
93
+    private $groupManager;
94
+    /** @var IL10N */
95
+    private $l;
96
+    /** @var IFactory */
97
+    private $l10nFactory;
98
+    /** @var IUserManager */
99
+    private $userManager;
100
+    /** @var IRootFolder */
101
+    private $rootFolder;
102
+    /** @var CappedMemoryCache */
103
+    private $sharingDisabledForUsersCache;
104
+    /** @var EventDispatcherInterface */
105
+    private $legacyDispatcher;
106
+    /** @var LegacyHooks */
107
+    private $legacyHooks;
108
+    /** @var IMailer */
109
+    private $mailer;
110
+    /** @var IURLGenerator */
111
+    private $urlGenerator;
112
+    /** @var \OC_Defaults */
113
+    private $defaults;
114
+    /** @var IEventDispatcher */
115
+    private $dispatcher;
116
+
117
+
118
+    /**
119
+     * Manager constructor.
120
+     *
121
+     * @param ILogger $logger
122
+     * @param IConfig $config
123
+     * @param ISecureRandom $secureRandom
124
+     * @param IHasher $hasher
125
+     * @param IMountManager $mountManager
126
+     * @param IGroupManager $groupManager
127
+     * @param IL10N $l
128
+     * @param IFactory $l10nFactory
129
+     * @param IProviderFactory $factory
130
+     * @param IUserManager $userManager
131
+     * @param IRootFolder $rootFolder
132
+     * @param EventDispatcherInterface $eventDispatcher
133
+     * @param IMailer $mailer
134
+     * @param IURLGenerator $urlGenerator
135
+     * @param \OC_Defaults $defaults
136
+     */
137
+    public function __construct(
138
+            ILogger $logger,
139
+            IConfig $config,
140
+            ISecureRandom $secureRandom,
141
+            IHasher $hasher,
142
+            IMountManager $mountManager,
143
+            IGroupManager $groupManager,
144
+            IL10N $l,
145
+            IFactory $l10nFactory,
146
+            IProviderFactory $factory,
147
+            IUserManager $userManager,
148
+            IRootFolder $rootFolder,
149
+            EventDispatcherInterface $legacyDispatcher,
150
+            IMailer $mailer,
151
+            IURLGenerator $urlGenerator,
152
+            \OC_Defaults $defaults,
153
+            IEventDispatcher $dispatcher
154
+    ) {
155
+        $this->logger = $logger;
156
+        $this->config = $config;
157
+        $this->secureRandom = $secureRandom;
158
+        $this->hasher = $hasher;
159
+        $this->mountManager = $mountManager;
160
+        $this->groupManager = $groupManager;
161
+        $this->l = $l;
162
+        $this->l10nFactory = $l10nFactory;
163
+        $this->factory = $factory;
164
+        $this->userManager = $userManager;
165
+        $this->rootFolder = $rootFolder;
166
+        $this->legacyDispatcher = $legacyDispatcher;
167
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
168
+        $this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
169
+        $this->mailer = $mailer;
170
+        $this->urlGenerator = $urlGenerator;
171
+        $this->defaults = $defaults;
172
+        $this->dispatcher = $dispatcher;
173
+    }
174
+
175
+    /**
176
+     * Convert from a full share id to a tuple (providerId, shareId)
177
+     *
178
+     * @param string $id
179
+     * @return string[]
180
+     */
181
+    private function splitFullId($id) {
182
+        return explode(':', $id, 2);
183
+    }
184
+
185
+    /**
186
+     * Verify if a password meets all requirements
187
+     *
188
+     * @param string $password
189
+     * @throws \Exception
190
+     */
191
+    protected function verifyPassword($password) {
192
+        if ($password === null) {
193
+            // No password is set, check if this is allowed.
194
+            if ($this->shareApiLinkEnforcePassword()) {
195
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
196
+            }
197
+
198
+            return;
199
+        }
200
+
201
+        // Let others verify the password
202
+        try {
203
+            $this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
204
+        } catch (HintException $e) {
205
+            throw new \Exception($e->getHint());
206
+        }
207
+    }
208
+
209
+    /**
210
+     * Check for generic requirements before creating a share
211
+     *
212
+     * @param \OCP\Share\IShare $share
213
+     * @throws \InvalidArgumentException
214
+     * @throws GenericShareException
215
+     *
216
+     * @suppress PhanUndeclaredClassMethod
217
+     */
218
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
219
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
220
+            // We expect a valid user as sharedWith for user shares
221
+            if (!$this->userManager->userExists($share->getSharedWith())) {
222
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
223
+            }
224
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
225
+            // We expect a valid group as sharedWith for group shares
226
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
227
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
228
+            }
229
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
230
+            if ($share->getSharedWith() !== null) {
231
+                throw new \InvalidArgumentException('SharedWith should be empty');
232
+            }
233
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
234
+            if ($share->getSharedWith() === null) {
235
+                throw new \InvalidArgumentException('SharedWith should not be empty');
236
+            }
237
+        }  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238
+            if ($share->getSharedWith() === null) {
239
+                throw new \InvalidArgumentException('SharedWith should not be empty');
240
+            }
241
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
242
+            if ($share->getSharedWith() === null) {
243
+                throw new \InvalidArgumentException('SharedWith should not be empty');
244
+            }
245
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
246
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
247
+            if ($circle === null) {
248
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
249
+            }
250
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
251
+        } else {
252
+            // We can't handle other types yet
253
+            throw new \InvalidArgumentException('unknown share type');
254
+        }
255
+
256
+        // Verify the initiator of the share is set
257
+        if ($share->getSharedBy() === null) {
258
+            throw new \InvalidArgumentException('SharedBy should be set');
259
+        }
260
+
261
+        // Cannot share with yourself
262
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
263
+            $share->getSharedWith() === $share->getSharedBy()) {
264
+            throw new \InvalidArgumentException('Can’t share with yourself');
265
+        }
266
+
267
+        // The path should be set
268
+        if ($share->getNode() === null) {
269
+            throw new \InvalidArgumentException('Path should be set');
270
+        }
271
+
272
+        // And it should be a file or a folder
273
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
274
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
275
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
276
+        }
277
+
278
+        // And you can't share your rootfolder
279
+        if ($this->userManager->userExists($share->getSharedBy())) {
280
+            $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
281
+            $userFolderPath = $userFolder->getPath();
282
+        } else {
283
+            $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
284
+            $userFolderPath = $userFolder->getPath();
285
+        }
286
+        if ($userFolderPath === $share->getNode()->getPath()) {
287
+            throw new \InvalidArgumentException('You can’t share your root folder');
288
+        }
289
+
290
+        // Check if we actually have share permissions
291
+        if (!$share->getNode()->isShareable()) {
292
+            $path = $userFolder->getRelativePath($share->getNode()->getPath());
293
+            $message_t = $this->l->t('You are not allowed to share %s', [$path]);
294
+            throw new GenericShareException($message_t, $message_t, 404);
295
+        }
296
+
297
+        // Permissions should be set
298
+        if ($share->getPermissions() === null) {
299
+            throw new \InvalidArgumentException('A share requires permissions');
300
+        }
301
+
302
+        $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
303
+        $permissions = 0;
304
+        $mount = $share->getNode()->getMountPoint();
305
+        if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
306
+            // When it's a reshare use the parent share permissions as maximum
307
+            $userMountPointId = $mount->getStorageRootId();
308
+            $userMountPoints = $userFolder->getById($userMountPointId);
309
+            $userMountPoint = array_shift($userMountPoints);
310
+
311
+            /* Check if this is an incoming share */
312
+            $incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
313
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
314
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
315
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
316
+
317
+            /** @var \OCP\Share\IShare[] $incomingShares */
318
+            if (!empty($incomingShares)) {
319
+                foreach ($incomingShares as $incomingShare) {
320
+                    $permissions |= $incomingShare->getPermissions();
321
+                }
322
+            }
323
+        } else {
324
+            /*
325 325
 			 * Quick fix for #23536
326 326
 			 * Non moveable mount points do not have update and delete permissions
327 327
 			 * while we 'most likely' do have that on the storage.
328 328
 			 */
329
-			$permissions = $share->getNode()->getPermissions();
330
-			if (!($mount instanceof MoveableMount)) {
331
-				$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
332
-			}
333
-		}
334
-
335
-		// Check that we do not share with more permissions than we have
336
-		if ($share->getPermissions() & ~$permissions) {
337
-			$path = $userFolder->getRelativePath($share->getNode()->getPath());
338
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$path]);
339
-			throw new GenericShareException($message_t, $message_t, 404);
340
-		}
341
-
342
-
343
-		// Check that read permissions are always set
344
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
345
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
346
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
347
-		if (!$noReadPermissionRequired &&
348
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
349
-			throw new \InvalidArgumentException('Shares need at least read permissions');
350
-		}
351
-
352
-		if ($share->getNode() instanceof \OCP\Files\File) {
353
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
354
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
355
-				throw new GenericShareException($message_t);
356
-			}
357
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
358
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
359
-				throw new GenericShareException($message_t);
360
-			}
361
-		}
362
-	}
363
-
364
-	/**
365
-	 * Validate if the expiration date fits the system settings
366
-	 *
367
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
368
-	 * @return \OCP\Share\IShare The modified share object
369
-	 * @throws GenericShareException
370
-	 * @throws \InvalidArgumentException
371
-	 * @throws \Exception
372
-	 */
373
-	protected function validateExpirationDateInternal(\OCP\Share\IShare $share) {
374
-		$expirationDate = $share->getExpirationDate();
375
-
376
-		if ($expirationDate !== null) {
377
-			//Make sure the expiration date is a date
378
-			$expirationDate->setTime(0, 0, 0);
379
-
380
-			$date = new \DateTime();
381
-			$date->setTime(0, 0, 0);
382
-			if ($date >= $expirationDate) {
383
-				$message = $this->l->t('Expiration date is in the past');
384
-				throw new GenericShareException($message, $message, 404);
385
-			}
386
-		}
387
-
388
-		// If expiredate is empty set a default one if there is a default
389
-		$fullId = null;
390
-		try {
391
-			$fullId = $share->getFullId();
392
-		} catch (\UnexpectedValueException $e) {
393
-			// This is a new share
394
-		}
395
-
396
-		if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397
-			$expirationDate = new \DateTime();
398
-			$expirationDate->setTime(0,0,0);
399
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400
-		}
401
-
402
-		// If we enforce the expiration date check that is does not exceed
403
-		if ($this->shareApiInternalDefaultExpireDateEnforced()) {
404
-			if ($expirationDate === null) {
405
-				throw new \InvalidArgumentException('Expiration date is enforced');
406
-			}
407
-
408
-			$date = new \DateTime();
409
-			$date->setTime(0, 0, 0);
410
-			$date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
411
-			if ($date < $expirationDate) {
412
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413
-				throw new GenericShareException($message, $message, 404);
414
-			}
415
-		}
416
-
417
-		$accepted = true;
418
-		$message = '';
419
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
420
-			'expirationDate' => &$expirationDate,
421
-			'accepted' => &$accepted,
422
-			'message' => &$message,
423
-			'passwordSet' => $share->getPassword() !== null,
424
-		]);
425
-
426
-		if (!$accepted) {
427
-			throw new \Exception($message);
428
-		}
429
-
430
-		$share->setExpirationDate($expirationDate);
431
-
432
-		return $share;
433
-	}
434
-
435
-	/**
436
-	 * Validate if the expiration date fits the system settings
437
-	 *
438
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
439
-	 * @return \OCP\Share\IShare The modified share object
440
-	 * @throws GenericShareException
441
-	 * @throws \InvalidArgumentException
442
-	 * @throws \Exception
443
-	 */
444
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
445
-
446
-		$expirationDate = $share->getExpirationDate();
447
-
448
-		if ($expirationDate !== null) {
449
-			//Make sure the expiration date is a date
450
-			$expirationDate->setTime(0, 0, 0);
451
-
452
-			$date = new \DateTime();
453
-			$date->setTime(0, 0, 0);
454
-			if ($date >= $expirationDate) {
455
-				$message = $this->l->t('Expiration date is in the past');
456
-				throw new GenericShareException($message, $message, 404);
457
-			}
458
-		}
459
-
460
-		// If expiredate is empty set a default one if there is a default
461
-		$fullId = null;
462
-		try {
463
-			$fullId = $share->getFullId();
464
-		} catch (\UnexpectedValueException $e) {
465
-			// This is a new share
466
-		}
467
-
468
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469
-			$expirationDate = new \DateTime();
470
-			$expirationDate->setTime(0,0,0);
471
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472
-		}
473
-
474
-		// If we enforce the expiration date check that is does not exceed
475
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
476
-			if ($expirationDate === null) {
477
-				throw new \InvalidArgumentException('Expiration date is enforced');
478
-			}
479
-
480
-			$date = new \DateTime();
481
-			$date->setTime(0, 0, 0);
482
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
483
-			if ($date < $expirationDate) {
484
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485
-				throw new GenericShareException($message, $message, 404);
486
-			}
487
-		}
488
-
489
-		$accepted = true;
490
-		$message = '';
491
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
492
-			'expirationDate' => &$expirationDate,
493
-			'accepted' => &$accepted,
494
-			'message' => &$message,
495
-			'passwordSet' => $share->getPassword() !== null,
496
-		]);
497
-
498
-		if (!$accepted) {
499
-			throw new \Exception($message);
500
-		}
501
-
502
-		$share->setExpirationDate($expirationDate);
503
-
504
-		return $share;
505
-	}
506
-
507
-	/**
508
-	 * Check for pre share requirements for user shares
509
-	 *
510
-	 * @param \OCP\Share\IShare $share
511
-	 * @throws \Exception
512
-	 */
513
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
514
-		// Check if we can share with group members only
515
-		if ($this->shareWithGroupMembersOnly()) {
516
-			$sharedBy = $this->userManager->get($share->getSharedBy());
517
-			$sharedWith = $this->userManager->get($share->getSharedWith());
518
-			// Verify we can share with this user
519
-			$groups = array_intersect(
520
-					$this->groupManager->getUserGroupIds($sharedBy),
521
-					$this->groupManager->getUserGroupIds($sharedWith)
522
-			);
523
-			if (empty($groups)) {
524
-				throw new \Exception('Sharing is only allowed with group members');
525
-			}
526
-		}
527
-
528
-		/*
329
+            $permissions = $share->getNode()->getPermissions();
330
+            if (!($mount instanceof MoveableMount)) {
331
+                $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
332
+            }
333
+        }
334
+
335
+        // Check that we do not share with more permissions than we have
336
+        if ($share->getPermissions() & ~$permissions) {
337
+            $path = $userFolder->getRelativePath($share->getNode()->getPath());
338
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$path]);
339
+            throw new GenericShareException($message_t, $message_t, 404);
340
+        }
341
+
342
+
343
+        // Check that read permissions are always set
344
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
345
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
346
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
347
+        if (!$noReadPermissionRequired &&
348
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
349
+            throw new \InvalidArgumentException('Shares need at least read permissions');
350
+        }
351
+
352
+        if ($share->getNode() instanceof \OCP\Files\File) {
353
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
354
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
355
+                throw new GenericShareException($message_t);
356
+            }
357
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
358
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
359
+                throw new GenericShareException($message_t);
360
+            }
361
+        }
362
+    }
363
+
364
+    /**
365
+     * Validate if the expiration date fits the system settings
366
+     *
367
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
368
+     * @return \OCP\Share\IShare The modified share object
369
+     * @throws GenericShareException
370
+     * @throws \InvalidArgumentException
371
+     * @throws \Exception
372
+     */
373
+    protected function validateExpirationDateInternal(\OCP\Share\IShare $share) {
374
+        $expirationDate = $share->getExpirationDate();
375
+
376
+        if ($expirationDate !== null) {
377
+            //Make sure the expiration date is a date
378
+            $expirationDate->setTime(0, 0, 0);
379
+
380
+            $date = new \DateTime();
381
+            $date->setTime(0, 0, 0);
382
+            if ($date >= $expirationDate) {
383
+                $message = $this->l->t('Expiration date is in the past');
384
+                throw new GenericShareException($message, $message, 404);
385
+            }
386
+        }
387
+
388
+        // If expiredate is empty set a default one if there is a default
389
+        $fullId = null;
390
+        try {
391
+            $fullId = $share->getFullId();
392
+        } catch (\UnexpectedValueException $e) {
393
+            // This is a new share
394
+        }
395
+
396
+        if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397
+            $expirationDate = new \DateTime();
398
+            $expirationDate->setTime(0,0,0);
399
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400
+        }
401
+
402
+        // If we enforce the expiration date check that is does not exceed
403
+        if ($this->shareApiInternalDefaultExpireDateEnforced()) {
404
+            if ($expirationDate === null) {
405
+                throw new \InvalidArgumentException('Expiration date is enforced');
406
+            }
407
+
408
+            $date = new \DateTime();
409
+            $date->setTime(0, 0, 0);
410
+            $date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
411
+            if ($date < $expirationDate) {
412
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413
+                throw new GenericShareException($message, $message, 404);
414
+            }
415
+        }
416
+
417
+        $accepted = true;
418
+        $message = '';
419
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
420
+            'expirationDate' => &$expirationDate,
421
+            'accepted' => &$accepted,
422
+            'message' => &$message,
423
+            'passwordSet' => $share->getPassword() !== null,
424
+        ]);
425
+
426
+        if (!$accepted) {
427
+            throw new \Exception($message);
428
+        }
429
+
430
+        $share->setExpirationDate($expirationDate);
431
+
432
+        return $share;
433
+    }
434
+
435
+    /**
436
+     * Validate if the expiration date fits the system settings
437
+     *
438
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
439
+     * @return \OCP\Share\IShare The modified share object
440
+     * @throws GenericShareException
441
+     * @throws \InvalidArgumentException
442
+     * @throws \Exception
443
+     */
444
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
445
+
446
+        $expirationDate = $share->getExpirationDate();
447
+
448
+        if ($expirationDate !== null) {
449
+            //Make sure the expiration date is a date
450
+            $expirationDate->setTime(0, 0, 0);
451
+
452
+            $date = new \DateTime();
453
+            $date->setTime(0, 0, 0);
454
+            if ($date >= $expirationDate) {
455
+                $message = $this->l->t('Expiration date is in the past');
456
+                throw new GenericShareException($message, $message, 404);
457
+            }
458
+        }
459
+
460
+        // If expiredate is empty set a default one if there is a default
461
+        $fullId = null;
462
+        try {
463
+            $fullId = $share->getFullId();
464
+        } catch (\UnexpectedValueException $e) {
465
+            // This is a new share
466
+        }
467
+
468
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469
+            $expirationDate = new \DateTime();
470
+            $expirationDate->setTime(0,0,0);
471
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472
+        }
473
+
474
+        // If we enforce the expiration date check that is does not exceed
475
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
476
+            if ($expirationDate === null) {
477
+                throw new \InvalidArgumentException('Expiration date is enforced');
478
+            }
479
+
480
+            $date = new \DateTime();
481
+            $date->setTime(0, 0, 0);
482
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
483
+            if ($date < $expirationDate) {
484
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485
+                throw new GenericShareException($message, $message, 404);
486
+            }
487
+        }
488
+
489
+        $accepted = true;
490
+        $message = '';
491
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
492
+            'expirationDate' => &$expirationDate,
493
+            'accepted' => &$accepted,
494
+            'message' => &$message,
495
+            'passwordSet' => $share->getPassword() !== null,
496
+        ]);
497
+
498
+        if (!$accepted) {
499
+            throw new \Exception($message);
500
+        }
501
+
502
+        $share->setExpirationDate($expirationDate);
503
+
504
+        return $share;
505
+    }
506
+
507
+    /**
508
+     * Check for pre share requirements for user shares
509
+     *
510
+     * @param \OCP\Share\IShare $share
511
+     * @throws \Exception
512
+     */
513
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
514
+        // Check if we can share with group members only
515
+        if ($this->shareWithGroupMembersOnly()) {
516
+            $sharedBy = $this->userManager->get($share->getSharedBy());
517
+            $sharedWith = $this->userManager->get($share->getSharedWith());
518
+            // Verify we can share with this user
519
+            $groups = array_intersect(
520
+                    $this->groupManager->getUserGroupIds($sharedBy),
521
+                    $this->groupManager->getUserGroupIds($sharedWith)
522
+            );
523
+            if (empty($groups)) {
524
+                throw new \Exception('Sharing is only allowed with group members');
525
+            }
526
+        }
527
+
528
+        /*
529 529
 		 * TODO: Could be costly, fix
530 530
 		 *
531 531
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
532 532
 		 */
533
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534
-		$existingShares = $provider->getSharesByPath($share->getNode());
535
-		foreach($existingShares as $existingShare) {
536
-			// Ignore if it is the same share
537
-			try {
538
-				if ($existingShare->getFullId() === $share->getFullId()) {
539
-					continue;
540
-				}
541
-			} catch (\UnexpectedValueException $e) {
542
-				//Shares are not identical
543
-			}
544
-
545
-			// Identical share already existst
546
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
547
-				throw new \Exception('Path is already shared with this user');
548
-			}
549
-
550
-			// The share is already shared with this user via a group share
551
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
552
-				$group = $this->groupManager->get($existingShare->getSharedWith());
553
-				if (!is_null($group)) {
554
-					$user = $this->userManager->get($share->getSharedWith());
555
-
556
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
557
-						throw new \Exception('Path is already shared with this user');
558
-					}
559
-				}
560
-			}
561
-		}
562
-	}
563
-
564
-	/**
565
-	 * Check for pre share requirements for group shares
566
-	 *
567
-	 * @param \OCP\Share\IShare $share
568
-	 * @throws \Exception
569
-	 */
570
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
571
-		// Verify group shares are allowed
572
-		if (!$this->allowGroupSharing()) {
573
-			throw new \Exception('Group sharing is now allowed');
574
-		}
575
-
576
-		// Verify if the user can share with this group
577
-		if ($this->shareWithGroupMembersOnly()) {
578
-			$sharedBy = $this->userManager->get($share->getSharedBy());
579
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
580
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
581
-				throw new \Exception('Sharing is only allowed within your own groups');
582
-			}
583
-		}
584
-
585
-		/*
533
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534
+        $existingShares = $provider->getSharesByPath($share->getNode());
535
+        foreach($existingShares as $existingShare) {
536
+            // Ignore if it is the same share
537
+            try {
538
+                if ($existingShare->getFullId() === $share->getFullId()) {
539
+                    continue;
540
+                }
541
+            } catch (\UnexpectedValueException $e) {
542
+                //Shares are not identical
543
+            }
544
+
545
+            // Identical share already existst
546
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
547
+                throw new \Exception('Path is already shared with this user');
548
+            }
549
+
550
+            // The share is already shared with this user via a group share
551
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
552
+                $group = $this->groupManager->get($existingShare->getSharedWith());
553
+                if (!is_null($group)) {
554
+                    $user = $this->userManager->get($share->getSharedWith());
555
+
556
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
557
+                        throw new \Exception('Path is already shared with this user');
558
+                    }
559
+                }
560
+            }
561
+        }
562
+    }
563
+
564
+    /**
565
+     * Check for pre share requirements for group shares
566
+     *
567
+     * @param \OCP\Share\IShare $share
568
+     * @throws \Exception
569
+     */
570
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
571
+        // Verify group shares are allowed
572
+        if (!$this->allowGroupSharing()) {
573
+            throw new \Exception('Group sharing is now allowed');
574
+        }
575
+
576
+        // Verify if the user can share with this group
577
+        if ($this->shareWithGroupMembersOnly()) {
578
+            $sharedBy = $this->userManager->get($share->getSharedBy());
579
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
580
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
581
+                throw new \Exception('Sharing is only allowed within your own groups');
582
+            }
583
+        }
584
+
585
+        /*
586 586
 		 * TODO: Could be costly, fix
587 587
 		 *
588 588
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
589 589
 		 */
590
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591
-		$existingShares = $provider->getSharesByPath($share->getNode());
592
-		foreach($existingShares as $existingShare) {
593
-			try {
594
-				if ($existingShare->getFullId() === $share->getFullId()) {
595
-					continue;
596
-				}
597
-			} catch (\UnexpectedValueException $e) {
598
-				//It is a new share so just continue
599
-			}
600
-
601
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
602
-				throw new \Exception('Path is already shared with this group');
603
-			}
604
-		}
605
-	}
606
-
607
-	/**
608
-	 * Check for pre share requirements for link shares
609
-	 *
610
-	 * @param \OCP\Share\IShare $share
611
-	 * @throws \Exception
612
-	 */
613
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
614
-		// Are link shares allowed?
615
-		if (!$this->shareApiAllowLinks()) {
616
-			throw new \Exception('Link sharing is not allowed');
617
-		}
618
-
619
-		// Link shares by definition can't have share permissions
620
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
621
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
622
-		}
623
-
624
-		// Check if public upload is allowed
625
-		if (!$this->shareApiLinkAllowPublicUpload() &&
626
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
627
-			throw new \InvalidArgumentException('Public upload is not allowed');
628
-		}
629
-	}
630
-
631
-	/**
632
-	 * To make sure we don't get invisible link shares we set the parent
633
-	 * of a link if it is a reshare. This is a quick word around
634
-	 * until we can properly display multiple link shares in the UI
635
-	 *
636
-	 * See: https://github.com/owncloud/core/issues/22295
637
-	 *
638
-	 * FIXME: Remove once multiple link shares can be properly displayed
639
-	 *
640
-	 * @param \OCP\Share\IShare $share
641
-	 */
642
-	protected function setLinkParent(\OCP\Share\IShare $share) {
643
-
644
-		// No sense in checking if the method is not there.
645
-		if (method_exists($share, 'setParent')) {
646
-			$storage = $share->getNode()->getStorage();
647
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
648
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
649
-				$share->setParent($storage->getShareId());
650
-			}
651
-		}
652
-	}
653
-
654
-	/**
655
-	 * @param File|Folder $path
656
-	 */
657
-	protected function pathCreateChecks($path) {
658
-		// Make sure that we do not share a path that contains a shared mountpoint
659
-		if ($path instanceof \OCP\Files\Folder) {
660
-			$mounts = $this->mountManager->findIn($path->getPath());
661
-			foreach($mounts as $mount) {
662
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663
-					throw new \InvalidArgumentException('Path contains files shared with you');
664
-				}
665
-			}
666
-		}
667
-	}
668
-
669
-	/**
670
-	 * Check if the user that is sharing can actually share
671
-	 *
672
-	 * @param \OCP\Share\IShare $share
673
-	 * @throws \Exception
674
-	 */
675
-	protected function canShare(\OCP\Share\IShare $share) {
676
-		if (!$this->shareApiEnabled()) {
677
-			throw new \Exception('Sharing is disabled');
678
-		}
679
-
680
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
681
-			throw new \Exception('Sharing is disabled for you');
682
-		}
683
-	}
684
-
685
-	/**
686
-	 * Share a path
687
-	 *
688
-	 * @param \OCP\Share\IShare $share
689
-	 * @return Share The share object
690
-	 * @throws \Exception
691
-	 *
692
-	 * TODO: handle link share permissions or check them
693
-	 */
694
-	public function createShare(\OCP\Share\IShare $share) {
695
-		$this->canShare($share);
696
-
697
-		$this->generalCreateChecks($share);
698
-
699
-		// Verify if there are any issues with the path
700
-		$this->pathCreateChecks($share->getNode());
701
-
702
-		/*
590
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591
+        $existingShares = $provider->getSharesByPath($share->getNode());
592
+        foreach($existingShares as $existingShare) {
593
+            try {
594
+                if ($existingShare->getFullId() === $share->getFullId()) {
595
+                    continue;
596
+                }
597
+            } catch (\UnexpectedValueException $e) {
598
+                //It is a new share so just continue
599
+            }
600
+
601
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
602
+                throw new \Exception('Path is already shared with this group');
603
+            }
604
+        }
605
+    }
606
+
607
+    /**
608
+     * Check for pre share requirements for link shares
609
+     *
610
+     * @param \OCP\Share\IShare $share
611
+     * @throws \Exception
612
+     */
613
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
614
+        // Are link shares allowed?
615
+        if (!$this->shareApiAllowLinks()) {
616
+            throw new \Exception('Link sharing is not allowed');
617
+        }
618
+
619
+        // Link shares by definition can't have share permissions
620
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
621
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
622
+        }
623
+
624
+        // Check if public upload is allowed
625
+        if (!$this->shareApiLinkAllowPublicUpload() &&
626
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
627
+            throw new \InvalidArgumentException('Public upload is not allowed');
628
+        }
629
+    }
630
+
631
+    /**
632
+     * To make sure we don't get invisible link shares we set the parent
633
+     * of a link if it is a reshare. This is a quick word around
634
+     * until we can properly display multiple link shares in the UI
635
+     *
636
+     * See: https://github.com/owncloud/core/issues/22295
637
+     *
638
+     * FIXME: Remove once multiple link shares can be properly displayed
639
+     *
640
+     * @param \OCP\Share\IShare $share
641
+     */
642
+    protected function setLinkParent(\OCP\Share\IShare $share) {
643
+
644
+        // No sense in checking if the method is not there.
645
+        if (method_exists($share, 'setParent')) {
646
+            $storage = $share->getNode()->getStorage();
647
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
648
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
649
+                $share->setParent($storage->getShareId());
650
+            }
651
+        }
652
+    }
653
+
654
+    /**
655
+     * @param File|Folder $path
656
+     */
657
+    protected function pathCreateChecks($path) {
658
+        // Make sure that we do not share a path that contains a shared mountpoint
659
+        if ($path instanceof \OCP\Files\Folder) {
660
+            $mounts = $this->mountManager->findIn($path->getPath());
661
+            foreach($mounts as $mount) {
662
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663
+                    throw new \InvalidArgumentException('Path contains files shared with you');
664
+                }
665
+            }
666
+        }
667
+    }
668
+
669
+    /**
670
+     * Check if the user that is sharing can actually share
671
+     *
672
+     * @param \OCP\Share\IShare $share
673
+     * @throws \Exception
674
+     */
675
+    protected function canShare(\OCP\Share\IShare $share) {
676
+        if (!$this->shareApiEnabled()) {
677
+            throw new \Exception('Sharing is disabled');
678
+        }
679
+
680
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
681
+            throw new \Exception('Sharing is disabled for you');
682
+        }
683
+    }
684
+
685
+    /**
686
+     * Share a path
687
+     *
688
+     * @param \OCP\Share\IShare $share
689
+     * @return Share The share object
690
+     * @throws \Exception
691
+     *
692
+     * TODO: handle link share permissions or check them
693
+     */
694
+    public function createShare(\OCP\Share\IShare $share) {
695
+        $this->canShare($share);
696
+
697
+        $this->generalCreateChecks($share);
698
+
699
+        // Verify if there are any issues with the path
700
+        $this->pathCreateChecks($share->getNode());
701
+
702
+        /*
703 703
 		 * On creation of a share the owner is always the owner of the path
704 704
 		 * Except for mounted federated shares.
705 705
 		 */
706
-		$storage = $share->getNode()->getStorage();
707
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708
-			$parent = $share->getNode()->getParent();
709
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710
-				$parent = $parent->getParent();
711
-			}
712
-			$share->setShareOwner($parent->getOwner()->getUID());
713
-		} else {
714
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
715
-		}
716
-
717
-		//Verify share type
718
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
719
-			$this->userCreateChecks($share);
720
-
721
-			//Verify the expiration date
722
-			$share = $this->validateExpirationDateInternal($share);
723
-
724
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
725
-			$this->groupCreateChecks($share);
726
-
727
-			//Verify the expiration date
728
-			$share = $this->validateExpirationDateInternal($share);
729
-
730
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
731
-			$this->linkCreateChecks($share);
732
-			$this->setLinkParent($share);
733
-
734
-			/*
706
+        $storage = $share->getNode()->getStorage();
707
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708
+            $parent = $share->getNode()->getParent();
709
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710
+                $parent = $parent->getParent();
711
+            }
712
+            $share->setShareOwner($parent->getOwner()->getUID());
713
+        } else {
714
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
715
+        }
716
+
717
+        //Verify share type
718
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
719
+            $this->userCreateChecks($share);
720
+
721
+            //Verify the expiration date
722
+            $share = $this->validateExpirationDateInternal($share);
723
+
724
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
725
+            $this->groupCreateChecks($share);
726
+
727
+            //Verify the expiration date
728
+            $share = $this->validateExpirationDateInternal($share);
729
+
730
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
731
+            $this->linkCreateChecks($share);
732
+            $this->setLinkParent($share);
733
+
734
+            /*
735 735
 			 * For now ignore a set token.
736 736
 			 */
737
-			$share->setToken(
738
-				$this->secureRandom->generate(
739
-					\OC\Share\Constants::TOKEN_LENGTH,
740
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
741
-				)
742
-			);
743
-
744
-			//Verify the expiration date
745
-			$share = $this->validateExpirationDate($share);
746
-
747
-			//Verify the password
748
-			$this->verifyPassword($share->getPassword());
749
-
750
-			// If a password is set. Hash it!
751
-			if ($share->getPassword() !== null) {
752
-				$share->setPassword($this->hasher->hash($share->getPassword()));
753
-			}
754
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
-			$share->setToken(
756
-				$this->secureRandom->generate(
757
-					\OC\Share\Constants::TOKEN_LENGTH,
758
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
-				)
760
-			);
761
-		}
762
-
763
-		// Cannot share with the owner
764
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
765
-			$share->getSharedWith() === $share->getShareOwner()) {
766
-			throw new \InvalidArgumentException('Can’t share with the share owner');
767
-		}
768
-
769
-		// Generate the target
770
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
771
-		$target = \OC\Files\Filesystem::normalizePath($target);
772
-		$share->setTarget($target);
773
-
774
-		// Pre share event
775
-		$event = new GenericEvent($share);
776
-		$this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
777
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
778
-			throw new \Exception($event->getArgument('error'));
779
-		}
780
-
781
-		$oldShare = $share;
782
-		$provider = $this->factory->getProviderForType($share->getShareType());
783
-		$share = $provider->create($share);
784
-		//reuse the node we already have
785
-		$share->setNode($oldShare->getNode());
786
-
787
-		// Reset the target if it is null for the new share
788
-		if ($share->getTarget() === '') {
789
-			$share->setTarget($target);
790
-		}
791
-
792
-		// Post share event
793
-		$event = new GenericEvent($share);
794
-		$this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
795
-
796
-		$this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
797
-
798
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799
-			$mailSend = $share->getMailSend();
800
-			if($mailSend === true) {
801
-				$user = $this->userManager->get($share->getSharedWith());
802
-				if ($user !== null) {
803
-					$emailAddress = $user->getEMailAddress();
804
-					if ($emailAddress !== null && $emailAddress !== '') {
805
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
806
-						$l = $this->l10nFactory->get('lib', $userLang);
807
-						$this->sendMailNotification(
808
-							$l,
809
-							$share->getNode()->getName(),
810
-							$this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
811
-							$share->getSharedBy(),
812
-							$emailAddress,
813
-							$share->getExpirationDate()
814
-						);
815
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
816
-					} else {
817
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
818
-					}
819
-				} else {
820
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
821
-				}
822
-			} else {
823
-				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
824
-			}
825
-		}
826
-
827
-		return $share;
828
-	}
829
-
830
-	/**
831
-	 * Send mail notifications
832
-	 *
833
-	 * This method will catch and log mail transmission errors
834
-	 *
835
-	 * @param IL10N $l Language of the recipient
836
-	 * @param string $filename file/folder name
837
-	 * @param string $link link to the file/folder
838
-	 * @param string $initiator user ID of share sender
839
-	 * @param string $shareWith email address of share receiver
840
-	 * @param \DateTime|null $expiration
841
-	 */
842
-	protected function sendMailNotification(IL10N $l,
843
-											$filename,
844
-											$link,
845
-											$initiator,
846
-											$shareWith,
847
-											\DateTime $expiration = null) {
848
-		$initiatorUser = $this->userManager->get($initiator);
849
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
850
-
851
-		$message = $this->mailer->createMessage();
852
-
853
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
854
-			'filename' => $filename,
855
-			'link' => $link,
856
-			'initiator' => $initiatorDisplayName,
857
-			'expiration' => $expiration,
858
-			'shareWith' => $shareWith,
859
-		]);
860
-
861
-		$emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
862
-		$emailTemplate->addHeader();
863
-		$emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
864
-		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865
-
866
-		$emailTemplate->addBodyText(
867
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
868
-			$text
869
-		);
870
-		$emailTemplate->addBodyButton(
871
-			$l->t('Open »%s«', [$filename]),
872
-			$link
873
-		);
874
-
875
-		$message->setTo([$shareWith]);
876
-
877
-		// The "From" contains the sharers name
878
-		$instanceName = $this->defaults->getName();
879
-		$senderName = $l->t(
880
-			'%1$s via %2$s',
881
-			[
882
-				$initiatorDisplayName,
883
-				$instanceName
884
-			]
885
-		);
886
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
887
-
888
-		// The "Reply-To" is set to the sharer if an mail address is configured
889
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
890
-		$initiatorEmail = $initiatorUser->getEMailAddress();
891
-		if($initiatorEmail !== null) {
892
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
894
-		} else {
895
-			$emailTemplate->addFooter();
896
-		}
897
-
898
-		$message->useTemplate($emailTemplate);
899
-		try {
900
-			$failedRecipients = $this->mailer->send($message);
901
-			if(!empty($failedRecipients)) {
902
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
903
-				return;
904
-			}
905
-		} catch (\Exception $e) {
906
-			$this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
907
-		}
908
-	}
909
-
910
-	/**
911
-	 * Update a share
912
-	 *
913
-	 * @param \OCP\Share\IShare $share
914
-	 * @return \OCP\Share\IShare The share object
915
-	 * @throws \InvalidArgumentException
916
-	 */
917
-	public function updateShare(\OCP\Share\IShare $share) {
918
-		$expirationDateUpdated = false;
919
-
920
-		$this->canShare($share);
921
-
922
-		try {
923
-			$originalShare = $this->getShareById($share->getFullId());
924
-		} catch (\UnexpectedValueException $e) {
925
-			throw new \InvalidArgumentException('Share does not have a full id');
926
-		}
927
-
928
-		// We can't change the share type!
929
-		if ($share->getShareType() !== $originalShare->getShareType()) {
930
-			throw new \InvalidArgumentException('Can’t change share type');
931
-		}
932
-
933
-		// We can only change the recipient on user shares
934
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
935
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
936
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
937
-		}
938
-
939
-		// Cannot share with the owner
940
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
941
-			$share->getSharedWith() === $share->getShareOwner()) {
942
-			throw new \InvalidArgumentException('Can’t share with the share owner');
943
-		}
944
-
945
-		$this->generalCreateChecks($share);
946
-
947
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
948
-			$this->userCreateChecks($share);
949
-
950
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
951
-				//Verify the expiration date
952
-				$this->validateExpirationDate($share);
953
-				$expirationDateUpdated = true;
954
-			}
955
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
956
-			$this->groupCreateChecks($share);
957
-
958
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
959
-				//Verify the expiration date
960
-				$this->validateExpirationDate($share);
961
-				$expirationDateUpdated = true;
962
-			}
963
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
964
-			$this->linkCreateChecks($share);
965
-
966
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
967
-
968
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
969
-				//Verify the expiration date
970
-				$this->validateExpirationDate($share);
971
-				$expirationDateUpdated = true;
972
-			}
973
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
974
-			// The new password is not set again if it is the same as the old
975
-			// one, unless when switching from sending by Talk to sending by
976
-			// mail.
977
-			$plainTextPassword = $share->getPassword();
978
-			if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
979
-					!($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
980
-				$plainTextPassword = null;
981
-			}
982
-			if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
983
-				// If the same password was already sent by mail the recipient
984
-				// would already have access to the share without having to call
985
-				// the sharer to verify her identity
986
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
987
-			}
988
-		}
989
-
990
-		$this->pathCreateChecks($share->getNode());
991
-
992
-		// Now update the share!
993
-		$provider = $this->factory->getProviderForType($share->getShareType());
994
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
995
-			$share = $provider->update($share, $plainTextPassword);
996
-		} else {
997
-			$share = $provider->update($share);
998
-		}
999
-
1000
-		if ($expirationDateUpdated === true) {
1001
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1002
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1003
-				'itemSource' => $share->getNode()->getId(),
1004
-				'date' => $share->getExpirationDate(),
1005
-				'uidOwner' => $share->getSharedBy(),
1006
-			]);
1007
-		}
1008
-
1009
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1010
-			\OC_Hook::emit(Share::class, 'post_update_password', [
1011
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1012
-				'itemSource' => $share->getNode()->getId(),
1013
-				'uidOwner' => $share->getSharedBy(),
1014
-				'token' => $share->getToken(),
1015
-				'disabled' => is_null($share->getPassword()),
1016
-			]);
1017
-		}
1018
-
1019
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
1020
-			if ($this->userManager->userExists($share->getShareOwner())) {
1021
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1022
-			} else {
1023
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1024
-			}
1025
-			\OC_Hook::emit(Share::class, 'post_update_permissions', array(
1026
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1027
-				'itemSource' => $share->getNode()->getId(),
1028
-				'shareType' => $share->getShareType(),
1029
-				'shareWith' => $share->getSharedWith(),
1030
-				'uidOwner' => $share->getSharedBy(),
1031
-				'permissions' => $share->getPermissions(),
1032
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1033
-			));
1034
-		}
1035
-
1036
-		return $share;
1037
-	}
1038
-
1039
-	/**
1040
-	 * Accept a share.
1041
-	 *
1042
-	 * @param IShare $share
1043
-	 * @param string $recipientId
1044
-	 * @return IShare The share object
1045
-	 * @throws \InvalidArgumentException
1046
-	 * @since 9.0.0
1047
-	 */
1048
-	public function acceptShare(IShare $share, string $recipientId): IShare {
1049
-		[$providerId, ] = $this->splitFullId($share->getFullId());
1050
-		$provider = $this->factory->getProvider($providerId);
1051
-
1052
-		if (!method_exists($provider, 'acceptShare')) {
1053
-			// TODO FIX ME
1054
-			throw new \InvalidArgumentException('Share provider does not support accepting');
1055
-		}
1056
-		$provider->acceptShare($share, $recipientId);
1057
-		$event = new GenericEvent($share);
1058
-		$this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1059
-
1060
-		return $share;
1061
-	}
1062
-
1063
-	/**
1064
-	 * Updates the password of the given share if it is not the same as the
1065
-	 * password of the original share.
1066
-	 *
1067
-	 * @param \OCP\Share\IShare $share the share to update its password.
1068
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
1069
-	 *        password with.
1070
-	 * @return boolean whether the password was updated or not.
1071
-	 */
1072
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
1073
-		// Password updated.
1074
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1075
-			//Verify the password
1076
-			$this->verifyPassword($share->getPassword());
1077
-
1078
-			// If a password is set. Hash it!
1079
-			if ($share->getPassword() !== null) {
1080
-				$share->setPassword($this->hasher->hash($share->getPassword()));
1081
-
1082
-				return true;
1083
-			}
1084
-		}
1085
-
1086
-		return false;
1087
-	}
1088
-
1089
-	/**
1090
-	 * Delete all the children of this share
1091
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1092
-	 *
1093
-	 * @param \OCP\Share\IShare $share
1094
-	 * @return \OCP\Share\IShare[] List of deleted shares
1095
-	 */
1096
-	protected function deleteChildren(\OCP\Share\IShare $share) {
1097
-		$deletedShares = [];
1098
-
1099
-		$provider = $this->factory->getProviderForType($share->getShareType());
1100
-
1101
-		foreach ($provider->getChildren($share) as $child) {
1102
-			$deletedChildren = $this->deleteChildren($child);
1103
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
1104
-
1105
-			$provider->delete($child);
1106
-			$deletedShares[] = $child;
1107
-		}
1108
-
1109
-		return $deletedShares;
1110
-	}
1111
-
1112
-	/**
1113
-	 * Delete a share
1114
-	 *
1115
-	 * @param \OCP\Share\IShare $share
1116
-	 * @throws ShareNotFound
1117
-	 * @throws \InvalidArgumentException
1118
-	 */
1119
-	public function deleteShare(\OCP\Share\IShare $share) {
1120
-
1121
-		try {
1122
-			$share->getFullId();
1123
-		} catch (\UnexpectedValueException $e) {
1124
-			throw new \InvalidArgumentException('Share does not have a full id');
1125
-		}
1126
-
1127
-		$event = new GenericEvent($share);
1128
-		$this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1129
-
1130
-		// Get all children and delete them as well
1131
-		$deletedShares = $this->deleteChildren($share);
1132
-
1133
-		// Do the actual delete
1134
-		$provider = $this->factory->getProviderForType($share->getShareType());
1135
-		$provider->delete($share);
1136
-
1137
-		// All the deleted shares caused by this delete
1138
-		$deletedShares[] = $share;
1139
-
1140
-		// Emit post hook
1141
-		$event->setArgument('deletedShares', $deletedShares);
1142
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1143
-	}
1144
-
1145
-
1146
-	/**
1147
-	 * Unshare a file as the recipient.
1148
-	 * This can be different from a regular delete for example when one of
1149
-	 * the users in a groups deletes that share. But the provider should
1150
-	 * handle this.
1151
-	 *
1152
-	 * @param \OCP\Share\IShare $share
1153
-	 * @param string $recipientId
1154
-	 */
1155
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1157
-		$provider = $this->factory->getProvider($providerId);
1158
-
1159
-		$provider->deleteFromSelf($share, $recipientId);
1160
-		$event = new GenericEvent($share);
1161
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1162
-	}
1163
-
1164
-	public function restoreShare(IShare $share, string $recipientId): IShare {
1165
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1166
-		$provider = $this->factory->getProvider($providerId);
1167
-
1168
-		return $provider->restore($share, $recipientId);
1169
-	}
1170
-
1171
-	/**
1172
-	 * @inheritdoc
1173
-	 */
1174
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1175
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1176
-			throw new \InvalidArgumentException('Can’t change target of link share');
1177
-		}
1178
-
1179
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1180
-			throw new \InvalidArgumentException('Invalid recipient');
1181
-		}
1182
-
1183
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1185
-			if (is_null($sharedWith)) {
1186
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1187
-			}
1188
-			$recipient = $this->userManager->get($recipientId);
1189
-			if (!$sharedWith->inGroup($recipient)) {
1190
-				throw new \InvalidArgumentException('Invalid recipient');
1191
-			}
1192
-		}
1193
-
1194
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1195
-		$provider = $this->factory->getProvider($providerId);
1196
-
1197
-		$provider->move($share, $recipientId);
1198
-	}
1199
-
1200
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201
-		$providers = $this->factory->getAllProviders();
1202
-
1203
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205
-			foreach ($newShares as $fid => $data) {
1206
-				if (!isset($shares[$fid])) {
1207
-					$shares[$fid] = [];
1208
-				}
1209
-
1210
-				$shares[$fid] = array_merge($shares[$fid], $data);
1211
-			}
1212
-			return $shares;
1213
-		}, []);
1214
-	}
1215
-
1216
-	/**
1217
-	 * @inheritdoc
1218
-	 */
1219
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1220
-		if ($path !== null &&
1221
-				!($path instanceof \OCP\Files\File) &&
1222
-				!($path instanceof \OCP\Files\Folder)) {
1223
-			throw new \InvalidArgumentException('invalid path');
1224
-		}
1225
-
1226
-		try {
1227
-			$provider = $this->factory->getProviderForType($shareType);
1228
-		} catch (ProviderException $e) {
1229
-			return [];
1230
-		}
1231
-
1232
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1233
-
1234
-		/*
737
+            $share->setToken(
738
+                $this->secureRandom->generate(
739
+                    \OC\Share\Constants::TOKEN_LENGTH,
740
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
741
+                )
742
+            );
743
+
744
+            //Verify the expiration date
745
+            $share = $this->validateExpirationDate($share);
746
+
747
+            //Verify the password
748
+            $this->verifyPassword($share->getPassword());
749
+
750
+            // If a password is set. Hash it!
751
+            if ($share->getPassword() !== null) {
752
+                $share->setPassword($this->hasher->hash($share->getPassword()));
753
+            }
754
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
+            $share->setToken(
756
+                $this->secureRandom->generate(
757
+                    \OC\Share\Constants::TOKEN_LENGTH,
758
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
+                )
760
+            );
761
+        }
762
+
763
+        // Cannot share with the owner
764
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
765
+            $share->getSharedWith() === $share->getShareOwner()) {
766
+            throw new \InvalidArgumentException('Can’t share with the share owner');
767
+        }
768
+
769
+        // Generate the target
770
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
771
+        $target = \OC\Files\Filesystem::normalizePath($target);
772
+        $share->setTarget($target);
773
+
774
+        // Pre share event
775
+        $event = new GenericEvent($share);
776
+        $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
777
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
778
+            throw new \Exception($event->getArgument('error'));
779
+        }
780
+
781
+        $oldShare = $share;
782
+        $provider = $this->factory->getProviderForType($share->getShareType());
783
+        $share = $provider->create($share);
784
+        //reuse the node we already have
785
+        $share->setNode($oldShare->getNode());
786
+
787
+        // Reset the target if it is null for the new share
788
+        if ($share->getTarget() === '') {
789
+            $share->setTarget($target);
790
+        }
791
+
792
+        // Post share event
793
+        $event = new GenericEvent($share);
794
+        $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
795
+
796
+        $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
797
+
798
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799
+            $mailSend = $share->getMailSend();
800
+            if($mailSend === true) {
801
+                $user = $this->userManager->get($share->getSharedWith());
802
+                if ($user !== null) {
803
+                    $emailAddress = $user->getEMailAddress();
804
+                    if ($emailAddress !== null && $emailAddress !== '') {
805
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
806
+                        $l = $this->l10nFactory->get('lib', $userLang);
807
+                        $this->sendMailNotification(
808
+                            $l,
809
+                            $share->getNode()->getName(),
810
+                            $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
811
+                            $share->getSharedBy(),
812
+                            $emailAddress,
813
+                            $share->getExpirationDate()
814
+                        );
815
+                        $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
816
+                    } else {
817
+                        $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
818
+                    }
819
+                } else {
820
+                    $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
821
+                }
822
+            } else {
823
+                $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
824
+            }
825
+        }
826
+
827
+        return $share;
828
+    }
829
+
830
+    /**
831
+     * Send mail notifications
832
+     *
833
+     * This method will catch and log mail transmission errors
834
+     *
835
+     * @param IL10N $l Language of the recipient
836
+     * @param string $filename file/folder name
837
+     * @param string $link link to the file/folder
838
+     * @param string $initiator user ID of share sender
839
+     * @param string $shareWith email address of share receiver
840
+     * @param \DateTime|null $expiration
841
+     */
842
+    protected function sendMailNotification(IL10N $l,
843
+                                            $filename,
844
+                                            $link,
845
+                                            $initiator,
846
+                                            $shareWith,
847
+                                            \DateTime $expiration = null) {
848
+        $initiatorUser = $this->userManager->get($initiator);
849
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
850
+
851
+        $message = $this->mailer->createMessage();
852
+
853
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
854
+            'filename' => $filename,
855
+            'link' => $link,
856
+            'initiator' => $initiatorDisplayName,
857
+            'expiration' => $expiration,
858
+            'shareWith' => $shareWith,
859
+        ]);
860
+
861
+        $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
862
+        $emailTemplate->addHeader();
863
+        $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
864
+        $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865
+
866
+        $emailTemplate->addBodyText(
867
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
868
+            $text
869
+        );
870
+        $emailTemplate->addBodyButton(
871
+            $l->t('Open »%s«', [$filename]),
872
+            $link
873
+        );
874
+
875
+        $message->setTo([$shareWith]);
876
+
877
+        // The "From" contains the sharers name
878
+        $instanceName = $this->defaults->getName();
879
+        $senderName = $l->t(
880
+            '%1$s via %2$s',
881
+            [
882
+                $initiatorDisplayName,
883
+                $instanceName
884
+            ]
885
+        );
886
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
887
+
888
+        // The "Reply-To" is set to the sharer if an mail address is configured
889
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
890
+        $initiatorEmail = $initiatorUser->getEMailAddress();
891
+        if($initiatorEmail !== null) {
892
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
894
+        } else {
895
+            $emailTemplate->addFooter();
896
+        }
897
+
898
+        $message->useTemplate($emailTemplate);
899
+        try {
900
+            $failedRecipients = $this->mailer->send($message);
901
+            if(!empty($failedRecipients)) {
902
+                $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
903
+                return;
904
+            }
905
+        } catch (\Exception $e) {
906
+            $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
907
+        }
908
+    }
909
+
910
+    /**
911
+     * Update a share
912
+     *
913
+     * @param \OCP\Share\IShare $share
914
+     * @return \OCP\Share\IShare The share object
915
+     * @throws \InvalidArgumentException
916
+     */
917
+    public function updateShare(\OCP\Share\IShare $share) {
918
+        $expirationDateUpdated = false;
919
+
920
+        $this->canShare($share);
921
+
922
+        try {
923
+            $originalShare = $this->getShareById($share->getFullId());
924
+        } catch (\UnexpectedValueException $e) {
925
+            throw new \InvalidArgumentException('Share does not have a full id');
926
+        }
927
+
928
+        // We can't change the share type!
929
+        if ($share->getShareType() !== $originalShare->getShareType()) {
930
+            throw new \InvalidArgumentException('Can’t change share type');
931
+        }
932
+
933
+        // We can only change the recipient on user shares
934
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
935
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
936
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
937
+        }
938
+
939
+        // Cannot share with the owner
940
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
941
+            $share->getSharedWith() === $share->getShareOwner()) {
942
+            throw new \InvalidArgumentException('Can’t share with the share owner');
943
+        }
944
+
945
+        $this->generalCreateChecks($share);
946
+
947
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
948
+            $this->userCreateChecks($share);
949
+
950
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
951
+                //Verify the expiration date
952
+                $this->validateExpirationDate($share);
953
+                $expirationDateUpdated = true;
954
+            }
955
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
956
+            $this->groupCreateChecks($share);
957
+
958
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
959
+                //Verify the expiration date
960
+                $this->validateExpirationDate($share);
961
+                $expirationDateUpdated = true;
962
+            }
963
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
964
+            $this->linkCreateChecks($share);
965
+
966
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
967
+
968
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
969
+                //Verify the expiration date
970
+                $this->validateExpirationDate($share);
971
+                $expirationDateUpdated = true;
972
+            }
973
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
974
+            // The new password is not set again if it is the same as the old
975
+            // one, unless when switching from sending by Talk to sending by
976
+            // mail.
977
+            $plainTextPassword = $share->getPassword();
978
+            if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
979
+                    !($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
980
+                $plainTextPassword = null;
981
+            }
982
+            if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
983
+                // If the same password was already sent by mail the recipient
984
+                // would already have access to the share without having to call
985
+                // the sharer to verify her identity
986
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
987
+            }
988
+        }
989
+
990
+        $this->pathCreateChecks($share->getNode());
991
+
992
+        // Now update the share!
993
+        $provider = $this->factory->getProviderForType($share->getShareType());
994
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
995
+            $share = $provider->update($share, $plainTextPassword);
996
+        } else {
997
+            $share = $provider->update($share);
998
+        }
999
+
1000
+        if ($expirationDateUpdated === true) {
1001
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1002
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1003
+                'itemSource' => $share->getNode()->getId(),
1004
+                'date' => $share->getExpirationDate(),
1005
+                'uidOwner' => $share->getSharedBy(),
1006
+            ]);
1007
+        }
1008
+
1009
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1010
+            \OC_Hook::emit(Share::class, 'post_update_password', [
1011
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1012
+                'itemSource' => $share->getNode()->getId(),
1013
+                'uidOwner' => $share->getSharedBy(),
1014
+                'token' => $share->getToken(),
1015
+                'disabled' => is_null($share->getPassword()),
1016
+            ]);
1017
+        }
1018
+
1019
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
1020
+            if ($this->userManager->userExists($share->getShareOwner())) {
1021
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1022
+            } else {
1023
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1024
+            }
1025
+            \OC_Hook::emit(Share::class, 'post_update_permissions', array(
1026
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1027
+                'itemSource' => $share->getNode()->getId(),
1028
+                'shareType' => $share->getShareType(),
1029
+                'shareWith' => $share->getSharedWith(),
1030
+                'uidOwner' => $share->getSharedBy(),
1031
+                'permissions' => $share->getPermissions(),
1032
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1033
+            ));
1034
+        }
1035
+
1036
+        return $share;
1037
+    }
1038
+
1039
+    /**
1040
+     * Accept a share.
1041
+     *
1042
+     * @param IShare $share
1043
+     * @param string $recipientId
1044
+     * @return IShare The share object
1045
+     * @throws \InvalidArgumentException
1046
+     * @since 9.0.0
1047
+     */
1048
+    public function acceptShare(IShare $share, string $recipientId): IShare {
1049
+        [$providerId, ] = $this->splitFullId($share->getFullId());
1050
+        $provider = $this->factory->getProvider($providerId);
1051
+
1052
+        if (!method_exists($provider, 'acceptShare')) {
1053
+            // TODO FIX ME
1054
+            throw new \InvalidArgumentException('Share provider does not support accepting');
1055
+        }
1056
+        $provider->acceptShare($share, $recipientId);
1057
+        $event = new GenericEvent($share);
1058
+        $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1059
+
1060
+        return $share;
1061
+    }
1062
+
1063
+    /**
1064
+     * Updates the password of the given share if it is not the same as the
1065
+     * password of the original share.
1066
+     *
1067
+     * @param \OCP\Share\IShare $share the share to update its password.
1068
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
1069
+     *        password with.
1070
+     * @return boolean whether the password was updated or not.
1071
+     */
1072
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
1073
+        // Password updated.
1074
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1075
+            //Verify the password
1076
+            $this->verifyPassword($share->getPassword());
1077
+
1078
+            // If a password is set. Hash it!
1079
+            if ($share->getPassword() !== null) {
1080
+                $share->setPassword($this->hasher->hash($share->getPassword()));
1081
+
1082
+                return true;
1083
+            }
1084
+        }
1085
+
1086
+        return false;
1087
+    }
1088
+
1089
+    /**
1090
+     * Delete all the children of this share
1091
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1092
+     *
1093
+     * @param \OCP\Share\IShare $share
1094
+     * @return \OCP\Share\IShare[] List of deleted shares
1095
+     */
1096
+    protected function deleteChildren(\OCP\Share\IShare $share) {
1097
+        $deletedShares = [];
1098
+
1099
+        $provider = $this->factory->getProviderForType($share->getShareType());
1100
+
1101
+        foreach ($provider->getChildren($share) as $child) {
1102
+            $deletedChildren = $this->deleteChildren($child);
1103
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
1104
+
1105
+            $provider->delete($child);
1106
+            $deletedShares[] = $child;
1107
+        }
1108
+
1109
+        return $deletedShares;
1110
+    }
1111
+
1112
+    /**
1113
+     * Delete a share
1114
+     *
1115
+     * @param \OCP\Share\IShare $share
1116
+     * @throws ShareNotFound
1117
+     * @throws \InvalidArgumentException
1118
+     */
1119
+    public function deleteShare(\OCP\Share\IShare $share) {
1120
+
1121
+        try {
1122
+            $share->getFullId();
1123
+        } catch (\UnexpectedValueException $e) {
1124
+            throw new \InvalidArgumentException('Share does not have a full id');
1125
+        }
1126
+
1127
+        $event = new GenericEvent($share);
1128
+        $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1129
+
1130
+        // Get all children and delete them as well
1131
+        $deletedShares = $this->deleteChildren($share);
1132
+
1133
+        // Do the actual delete
1134
+        $provider = $this->factory->getProviderForType($share->getShareType());
1135
+        $provider->delete($share);
1136
+
1137
+        // All the deleted shares caused by this delete
1138
+        $deletedShares[] = $share;
1139
+
1140
+        // Emit post hook
1141
+        $event->setArgument('deletedShares', $deletedShares);
1142
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1143
+    }
1144
+
1145
+
1146
+    /**
1147
+     * Unshare a file as the recipient.
1148
+     * This can be different from a regular delete for example when one of
1149
+     * the users in a groups deletes that share. But the provider should
1150
+     * handle this.
1151
+     *
1152
+     * @param \OCP\Share\IShare $share
1153
+     * @param string $recipientId
1154
+     */
1155
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1157
+        $provider = $this->factory->getProvider($providerId);
1158
+
1159
+        $provider->deleteFromSelf($share, $recipientId);
1160
+        $event = new GenericEvent($share);
1161
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1162
+    }
1163
+
1164
+    public function restoreShare(IShare $share, string $recipientId): IShare {
1165
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1166
+        $provider = $this->factory->getProvider($providerId);
1167
+
1168
+        return $provider->restore($share, $recipientId);
1169
+    }
1170
+
1171
+    /**
1172
+     * @inheritdoc
1173
+     */
1174
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1175
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1176
+            throw new \InvalidArgumentException('Can’t change target of link share');
1177
+        }
1178
+
1179
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1180
+            throw new \InvalidArgumentException('Invalid recipient');
1181
+        }
1182
+
1183
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1185
+            if (is_null($sharedWith)) {
1186
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1187
+            }
1188
+            $recipient = $this->userManager->get($recipientId);
1189
+            if (!$sharedWith->inGroup($recipient)) {
1190
+                throw new \InvalidArgumentException('Invalid recipient');
1191
+            }
1192
+        }
1193
+
1194
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1195
+        $provider = $this->factory->getProvider($providerId);
1196
+
1197
+        $provider->move($share, $recipientId);
1198
+    }
1199
+
1200
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201
+        $providers = $this->factory->getAllProviders();
1202
+
1203
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205
+            foreach ($newShares as $fid => $data) {
1206
+                if (!isset($shares[$fid])) {
1207
+                    $shares[$fid] = [];
1208
+                }
1209
+
1210
+                $shares[$fid] = array_merge($shares[$fid], $data);
1211
+            }
1212
+            return $shares;
1213
+        }, []);
1214
+    }
1215
+
1216
+    /**
1217
+     * @inheritdoc
1218
+     */
1219
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1220
+        if ($path !== null &&
1221
+                !($path instanceof \OCP\Files\File) &&
1222
+                !($path instanceof \OCP\Files\Folder)) {
1223
+            throw new \InvalidArgumentException('invalid path');
1224
+        }
1225
+
1226
+        try {
1227
+            $provider = $this->factory->getProviderForType($shareType);
1228
+        } catch (ProviderException $e) {
1229
+            return [];
1230
+        }
1231
+
1232
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1233
+
1234
+        /*
1235 1235
 		 * Work around so we don't return expired shares but still follow
1236 1236
 		 * proper pagination.
1237 1237
 		 */
1238 1238
 
1239
-		$shares2 = [];
1240
-
1241
-		while(true) {
1242
-			$added = 0;
1243
-			foreach ($shares as $share) {
1244
-
1245
-				try {
1246
-					$this->checkExpireDate($share);
1247
-				} catch (ShareNotFound $e) {
1248
-					//Ignore since this basically means the share is deleted
1249
-					continue;
1250
-				}
1251
-
1252
-				$added++;
1253
-				$shares2[] = $share;
1254
-
1255
-				if (count($shares2) === $limit) {
1256
-					break;
1257
-				}
1258
-			}
1259
-
1260
-			// If we did not fetch more shares than the limit then there are no more shares
1261
-			if (count($shares) < $limit) {
1262
-				break;
1263
-			}
1264
-
1265
-			if (count($shares2) === $limit) {
1266
-				break;
1267
-			}
1268
-
1269
-			// If there was no limit on the select we are done
1270
-			if ($limit === -1) {
1271
-				break;
1272
-			}
1273
-
1274
-			$offset += $added;
1275
-
1276
-			// Fetch again $limit shares
1277
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1278
-
1279
-			// No more shares means we are done
1280
-			if (empty($shares)) {
1281
-				break;
1282
-			}
1283
-		}
1284
-
1285
-		$shares = $shares2;
1286
-
1287
-		return $shares;
1288
-	}
1289
-
1290
-	/**
1291
-	 * @inheritdoc
1292
-	 */
1293
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1294
-		try {
1295
-			$provider = $this->factory->getProviderForType($shareType);
1296
-		} catch (ProviderException $e) {
1297
-			return [];
1298
-		}
1299
-
1300
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1301
-
1302
-		// remove all shares which are already expired
1303
-		foreach ($shares as $key => $share) {
1304
-			try {
1305
-				$this->checkExpireDate($share);
1306
-			} catch (ShareNotFound $e) {
1307
-				unset($shares[$key]);
1308
-			}
1309
-		}
1310
-
1311
-		return $shares;
1312
-	}
1313
-
1314
-	/**
1315
-	 * @inheritdoc
1316
-	 */
1317
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1318
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319
-
1320
-		// Only get deleted shares
1321
-		$shares = array_filter($shares, function(IShare $share) {
1322
-			return $share->getPermissions() === 0;
1323
-		});
1324
-
1325
-		// Only get shares where the owner still exists
1326
-		$shares = array_filter($shares, function (IShare $share) {
1327
-			return $this->userManager->userExists($share->getShareOwner());
1328
-		});
1329
-
1330
-		return $shares;
1331
-	}
1332
-
1333
-	/**
1334
-	 * @inheritdoc
1335
-	 */
1336
-	public function getShareById($id, $recipient = null) {
1337
-		if ($id === null) {
1338
-			throw new ShareNotFound();
1339
-		}
1340
-
1341
-		list($providerId, $id) = $this->splitFullId($id);
1342
-
1343
-		try {
1344
-			$provider = $this->factory->getProvider($providerId);
1345
-		} catch (ProviderException $e) {
1346
-			throw new ShareNotFound();
1347
-		}
1348
-
1349
-		$share = $provider->getShareById($id, $recipient);
1350
-
1351
-		$this->checkExpireDate($share);
1352
-
1353
-		return $share;
1354
-	}
1355
-
1356
-	/**
1357
-	 * Get all the shares for a given path
1358
-	 *
1359
-	 * @param \OCP\Files\Node $path
1360
-	 * @param int $page
1361
-	 * @param int $perPage
1362
-	 *
1363
-	 * @return Share[]
1364
-	 */
1365
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1366
-		return [];
1367
-	}
1368
-
1369
-	/**
1370
-	 * Get the share by token possible with password
1371
-	 *
1372
-	 * @param string $token
1373
-	 * @return Share
1374
-	 *
1375
-	 * @throws ShareNotFound
1376
-	 */
1377
-	public function getShareByToken($token) {
1378
-		// tokens can't be valid local user names
1379
-		if ($this->userManager->userExists($token)) {
1380
-			throw new ShareNotFound();
1381
-		}
1382
-		$share = null;
1383
-		try {
1384
-			if($this->shareApiAllowLinks()) {
1385
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386
-				$share = $provider->getShareByToken($token);
1387
-			}
1388
-		} catch (ProviderException $e) {
1389
-		} catch (ShareNotFound $e) {
1390
-		}
1391
-
1392
-
1393
-		// If it is not a link share try to fetch a federated share by token
1394
-		if ($share === null) {
1395
-			try {
1396
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1397
-				$share = $provider->getShareByToken($token);
1398
-			} catch (ProviderException $e) {
1399
-			} catch (ShareNotFound $e) {
1400
-			}
1401
-		}
1402
-
1403
-		// If it is not a link share try to fetch a mail share by token
1404
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1405
-			try {
1406
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1407
-				$share = $provider->getShareByToken($token);
1408
-			} catch (ProviderException $e) {
1409
-			} catch (ShareNotFound $e) {
1410
-			}
1411
-		}
1412
-
1413
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1414
-			try {
1415
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1416
-				$share = $provider->getShareByToken($token);
1417
-			} catch (ProviderException $e) {
1418
-			} catch (ShareNotFound $e) {
1419
-			}
1420
-		}
1421
-
1422
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1423
-			try {
1424
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1425
-				$share = $provider->getShareByToken($token);
1426
-			} catch (ProviderException $e) {
1427
-			} catch (ShareNotFound $e) {
1428
-			}
1429
-		}
1430
-
1431
-		if ($share === null) {
1432
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1433
-		}
1434
-
1435
-		$this->checkExpireDate($share);
1436
-
1437
-		/*
1239
+        $shares2 = [];
1240
+
1241
+        while(true) {
1242
+            $added = 0;
1243
+            foreach ($shares as $share) {
1244
+
1245
+                try {
1246
+                    $this->checkExpireDate($share);
1247
+                } catch (ShareNotFound $e) {
1248
+                    //Ignore since this basically means the share is deleted
1249
+                    continue;
1250
+                }
1251
+
1252
+                $added++;
1253
+                $shares2[] = $share;
1254
+
1255
+                if (count($shares2) === $limit) {
1256
+                    break;
1257
+                }
1258
+            }
1259
+
1260
+            // If we did not fetch more shares than the limit then there are no more shares
1261
+            if (count($shares) < $limit) {
1262
+                break;
1263
+            }
1264
+
1265
+            if (count($shares2) === $limit) {
1266
+                break;
1267
+            }
1268
+
1269
+            // If there was no limit on the select we are done
1270
+            if ($limit === -1) {
1271
+                break;
1272
+            }
1273
+
1274
+            $offset += $added;
1275
+
1276
+            // Fetch again $limit shares
1277
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1278
+
1279
+            // No more shares means we are done
1280
+            if (empty($shares)) {
1281
+                break;
1282
+            }
1283
+        }
1284
+
1285
+        $shares = $shares2;
1286
+
1287
+        return $shares;
1288
+    }
1289
+
1290
+    /**
1291
+     * @inheritdoc
1292
+     */
1293
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1294
+        try {
1295
+            $provider = $this->factory->getProviderForType($shareType);
1296
+        } catch (ProviderException $e) {
1297
+            return [];
1298
+        }
1299
+
1300
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1301
+
1302
+        // remove all shares which are already expired
1303
+        foreach ($shares as $key => $share) {
1304
+            try {
1305
+                $this->checkExpireDate($share);
1306
+            } catch (ShareNotFound $e) {
1307
+                unset($shares[$key]);
1308
+            }
1309
+        }
1310
+
1311
+        return $shares;
1312
+    }
1313
+
1314
+    /**
1315
+     * @inheritdoc
1316
+     */
1317
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1318
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319
+
1320
+        // Only get deleted shares
1321
+        $shares = array_filter($shares, function(IShare $share) {
1322
+            return $share->getPermissions() === 0;
1323
+        });
1324
+
1325
+        // Only get shares where the owner still exists
1326
+        $shares = array_filter($shares, function (IShare $share) {
1327
+            return $this->userManager->userExists($share->getShareOwner());
1328
+        });
1329
+
1330
+        return $shares;
1331
+    }
1332
+
1333
+    /**
1334
+     * @inheritdoc
1335
+     */
1336
+    public function getShareById($id, $recipient = null) {
1337
+        if ($id === null) {
1338
+            throw new ShareNotFound();
1339
+        }
1340
+
1341
+        list($providerId, $id) = $this->splitFullId($id);
1342
+
1343
+        try {
1344
+            $provider = $this->factory->getProvider($providerId);
1345
+        } catch (ProviderException $e) {
1346
+            throw new ShareNotFound();
1347
+        }
1348
+
1349
+        $share = $provider->getShareById($id, $recipient);
1350
+
1351
+        $this->checkExpireDate($share);
1352
+
1353
+        return $share;
1354
+    }
1355
+
1356
+    /**
1357
+     * Get all the shares for a given path
1358
+     *
1359
+     * @param \OCP\Files\Node $path
1360
+     * @param int $page
1361
+     * @param int $perPage
1362
+     *
1363
+     * @return Share[]
1364
+     */
1365
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1366
+        return [];
1367
+    }
1368
+
1369
+    /**
1370
+     * Get the share by token possible with password
1371
+     *
1372
+     * @param string $token
1373
+     * @return Share
1374
+     *
1375
+     * @throws ShareNotFound
1376
+     */
1377
+    public function getShareByToken($token) {
1378
+        // tokens can't be valid local user names
1379
+        if ($this->userManager->userExists($token)) {
1380
+            throw new ShareNotFound();
1381
+        }
1382
+        $share = null;
1383
+        try {
1384
+            if($this->shareApiAllowLinks()) {
1385
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386
+                $share = $provider->getShareByToken($token);
1387
+            }
1388
+        } catch (ProviderException $e) {
1389
+        } catch (ShareNotFound $e) {
1390
+        }
1391
+
1392
+
1393
+        // If it is not a link share try to fetch a federated share by token
1394
+        if ($share === null) {
1395
+            try {
1396
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1397
+                $share = $provider->getShareByToken($token);
1398
+            } catch (ProviderException $e) {
1399
+            } catch (ShareNotFound $e) {
1400
+            }
1401
+        }
1402
+
1403
+        // If it is not a link share try to fetch a mail share by token
1404
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1405
+            try {
1406
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1407
+                $share = $provider->getShareByToken($token);
1408
+            } catch (ProviderException $e) {
1409
+            } catch (ShareNotFound $e) {
1410
+            }
1411
+        }
1412
+
1413
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1414
+            try {
1415
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1416
+                $share = $provider->getShareByToken($token);
1417
+            } catch (ProviderException $e) {
1418
+            } catch (ShareNotFound $e) {
1419
+            }
1420
+        }
1421
+
1422
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1423
+            try {
1424
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1425
+                $share = $provider->getShareByToken($token);
1426
+            } catch (ProviderException $e) {
1427
+            } catch (ShareNotFound $e) {
1428
+            }
1429
+        }
1430
+
1431
+        if ($share === null) {
1432
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1433
+        }
1434
+
1435
+        $this->checkExpireDate($share);
1436
+
1437
+        /*
1438 1438
 		 * Reduce the permissions for link shares if public upload is not enabled
1439 1439
 		 */
1440
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1441
-			!$this->shareApiLinkAllowPublicUpload()) {
1442
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1443
-		}
1444
-
1445
-		return $share;
1446
-	}
1447
-
1448
-	protected function checkExpireDate($share) {
1449
-		if ($share->isExpired()) {
1450
-			$this->deleteShare($share);
1451
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1452
-		}
1453
-
1454
-	}
1455
-
1456
-	/**
1457
-	 * Verify the password of a public share
1458
-	 *
1459
-	 * @param \OCP\Share\IShare $share
1460
-	 * @param string $password
1461
-	 * @return bool
1462
-	 */
1463
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1464
-		$passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1465
-							 || $share->getShareType() !== IShare::TYPE_EMAIL
1466
-							 || $share->getShareType() !== IShare::TYPE_CIRCLE;
1467
-		if (!$passwordProtected) {
1468
-			//TODO maybe exception?
1469
-			return false;
1470
-		}
1471
-
1472
-		if ($password === null || $share->getPassword() === null) {
1473
-			return false;
1474
-		}
1475
-
1476
-		$newHash = '';
1477
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1478
-			return false;
1479
-		}
1480
-
1481
-		if (!empty($newHash)) {
1482
-			$share->setPassword($newHash);
1483
-			$provider = $this->factory->getProviderForType($share->getShareType());
1484
-			$provider->update($share);
1485
-		}
1486
-
1487
-		return true;
1488
-	}
1489
-
1490
-	/**
1491
-	 * @inheritdoc
1492
-	 */
1493
-	public function userDeleted($uid) {
1494
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1495
-
1496
-		foreach ($types as $type) {
1497
-			try {
1498
-				$provider = $this->factory->getProviderForType($type);
1499
-			} catch (ProviderException $e) {
1500
-				continue;
1501
-			}
1502
-			$provider->userDeleted($uid, $type);
1503
-		}
1504
-	}
1505
-
1506
-	/**
1507
-	 * @inheritdoc
1508
-	 */
1509
-	public function groupDeleted($gid) {
1510
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1511
-		$provider->groupDeleted($gid);
1512
-	}
1513
-
1514
-	/**
1515
-	 * @inheritdoc
1516
-	 */
1517
-	public function userDeletedFromGroup($uid, $gid) {
1518
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1519
-		$provider->userDeletedFromGroup($uid, $gid);
1520
-	}
1521
-
1522
-	/**
1523
-	 * Get access list to a path. This means
1524
-	 * all the users that can access a given path.
1525
-	 *
1526
-	 * Consider:
1527
-	 * -root
1528
-	 * |-folder1 (23)
1529
-	 *  |-folder2 (32)
1530
-	 *   |-fileA (42)
1531
-	 *
1532
-	 * fileA is shared with user1 and user1@server1
1533
-	 * folder2 is shared with group2 (user4 is a member of group2)
1534
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1535
-	 *
1536
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1537
-	 * [
1538
-	 *  users  => [
1539
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1540
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1541
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1542
-	 *  ],
1543
-	 *  remote => [
1544
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1545
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1546
-	 *  ],
1547
-	 *  public => bool
1548
-	 *  mail => bool
1549
-	 * ]
1550
-	 *
1551
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1552
-	 * [
1553
-	 *  users  => ['user1', 'user2', 'user4'],
1554
-	 *  remote => bool,
1555
-	 *  public => bool
1556
-	 *  mail => bool
1557
-	 * ]
1558
-	 *
1559
-	 * This is required for encryption/activity
1560
-	 *
1561
-	 * @param \OCP\Files\Node $path
1562
-	 * @param bool $recursive Should we check all parent folders as well
1563
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1564
-	 * @return array
1565
-	 */
1566
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1567
-		$owner = $path->getOwner();
1568
-
1569
-		if ($owner === null) {
1570
-			return [];
1571
-		}
1572
-
1573
-		$owner = $owner->getUID();
1574
-
1575
-		if ($currentAccess) {
1576
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1577
-		} else {
1578
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1579
-		}
1580
-		if (!$this->userManager->userExists($owner)) {
1581
-			return $al;
1582
-		}
1583
-
1584
-		//Get node for the owner and correct the owner in case of external storages
1585
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1586
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1587
-			$nodes = $userFolder->getById($path->getId());
1588
-			$path = array_shift($nodes);
1589
-			if ($path->getOwner() === null) {
1590
-				return [];
1591
-			}
1592
-			$owner = $path->getOwner()->getUID();
1593
-		}
1594
-
1595
-		$providers = $this->factory->getAllProviders();
1596
-
1597
-		/** @var Node[] $nodes */
1598
-		$nodes = [];
1599
-
1600
-
1601
-		if ($currentAccess) {
1602
-			$ownerPath = $path->getPath();
1603
-			$ownerPath = explode('/', $ownerPath, 4);
1604
-			if (count($ownerPath) < 4) {
1605
-				$ownerPath = '';
1606
-			} else {
1607
-				$ownerPath = $ownerPath[3];
1608
-			}
1609
-			$al['users'][$owner] = [
1610
-				'node_id' => $path->getId(),
1611
-				'node_path' => '/' . $ownerPath,
1612
-			];
1613
-		} else {
1614
-			$al['users'][] = $owner;
1615
-		}
1616
-
1617
-		// Collect all the shares
1618
-		while ($path->getPath() !== $userFolder->getPath()) {
1619
-			$nodes[] = $path;
1620
-			if (!$recursive) {
1621
-				break;
1622
-			}
1623
-			$path = $path->getParent();
1624
-		}
1625
-
1626
-		foreach ($providers as $provider) {
1627
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1628
-
1629
-			foreach ($tmp as $k => $v) {
1630
-				if (isset($al[$k])) {
1631
-					if (is_array($al[$k])) {
1632
-						if ($currentAccess) {
1633
-							$al[$k] += $v;
1634
-						} else {
1635
-							$al[$k] = array_merge($al[$k], $v);
1636
-							$al[$k] = array_unique($al[$k]);
1637
-							$al[$k] = array_values($al[$k]);
1638
-						}
1639
-					} else {
1640
-						$al[$k] = $al[$k] || $v;
1641
-					}
1642
-				} else {
1643
-					$al[$k] = $v;
1644
-				}
1645
-			}
1646
-		}
1647
-
1648
-		return $al;
1649
-	}
1650
-
1651
-	/**
1652
-	 * Create a new share
1653
-	 * @return \OCP\Share\IShare
1654
-	 */
1655
-	public function newShare() {
1656
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1657
-	}
1658
-
1659
-	/**
1660
-	 * Is the share API enabled
1661
-	 *
1662
-	 * @return bool
1663
-	 */
1664
-	public function shareApiEnabled() {
1665
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1666
-	}
1667
-
1668
-	/**
1669
-	 * Is public link sharing enabled
1670
-	 *
1671
-	 * @return bool
1672
-	 */
1673
-	public function shareApiAllowLinks() {
1674
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1675
-	}
1676
-
1677
-	/**
1678
-	 * Is password on public link requires
1679
-	 *
1680
-	 * @return bool
1681
-	 */
1682
-	public function shareApiLinkEnforcePassword() {
1683
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1684
-	}
1685
-
1686
-	/**
1687
-	 * Is default link expire date enabled
1688
-	 *
1689
-	 * @return bool
1690
-	 */
1691
-	public function shareApiLinkDefaultExpireDate() {
1692
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1693
-	}
1694
-
1695
-	/**
1696
-	 * Is default link expire date enforced
1697
-	 *`
1698
-	 * @return bool
1699
-	 */
1700
-	public function shareApiLinkDefaultExpireDateEnforced() {
1701
-		return $this->shareApiLinkDefaultExpireDate() &&
1702
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1703
-	}
1704
-
1705
-
1706
-	/**
1707
-	 * Number of default link expire days
1708
-	 * @return int
1709
-	 */
1710
-	public function shareApiLinkDefaultExpireDays() {
1711
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712
-	}
1713
-
1714
-	/**
1715
-	 * Is default internal expire date enabled
1716
-	 *
1717
-	 * @return bool
1718
-	 */
1719
-	public function shareApiInternalDefaultExpireDate(): bool {
1720
-		return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1721
-	}
1722
-
1723
-	/**
1724
-	 * Is default expire date enforced
1725
-	 *`
1726
-	 * @return bool
1727
-	 */
1728
-	public function shareApiInternalDefaultExpireDateEnforced(): bool {
1729
-		return $this->shareApiInternalDefaultExpireDate() &&
1730
-			$this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1731
-	}
1732
-
1733
-
1734
-	/**
1735
-	 * Number of default expire days
1736
-	 * @return int
1737
-	 */
1738
-	public function shareApiInternalDefaultExpireDays(): int {
1739
-		return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740
-	}
1741
-
1742
-	/**
1743
-	 * Allow public upload on link shares
1744
-	 *
1745
-	 * @return bool
1746
-	 */
1747
-	public function shareApiLinkAllowPublicUpload() {
1748
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1749
-	}
1750
-
1751
-	/**
1752
-	 * check if user can only share with group members
1753
-	 * @return bool
1754
-	 */
1755
-	public function shareWithGroupMembersOnly() {
1756
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1757
-	}
1758
-
1759
-	/**
1760
-	 * Check if users can share with groups
1761
-	 * @return bool
1762
-	 */
1763
-	public function allowGroupSharing() {
1764
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1765
-	}
1766
-
1767
-	public function allowEnumeration(): bool {
1768
-		return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1769
-	}
1770
-
1771
-	public function limitEnumerationToGroups(): bool {
1772
-		return $this->allowEnumeration() &&
1773
-			$this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1774
-	}
1775
-
1776
-	/**
1777
-	 * Copied from \OC_Util::isSharingDisabledForUser
1778
-	 *
1779
-	 * TODO: Deprecate fuction from OC_Util
1780
-	 *
1781
-	 * @param string $userId
1782
-	 * @return bool
1783
-	 */
1784
-	public function sharingDisabledForUser($userId) {
1785
-		if ($userId === null) {
1786
-			return false;
1787
-		}
1788
-
1789
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1790
-			return $this->sharingDisabledForUsersCache[$userId];
1791
-		}
1792
-
1793
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1794
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1795
-			$excludedGroups = json_decode($groupsList);
1796
-			if (is_null($excludedGroups)) {
1797
-				$excludedGroups = explode(',', $groupsList);
1798
-				$newValue = json_encode($excludedGroups);
1799
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1800
-			}
1801
-			$user = $this->userManager->get($userId);
1802
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1803
-			if (!empty($usersGroups)) {
1804
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1805
-				// if the user is only in groups which are disabled for sharing then
1806
-				// sharing is also disabled for the user
1807
-				if (empty($remainingGroups)) {
1808
-					$this->sharingDisabledForUsersCache[$userId] = true;
1809
-					return true;
1810
-				}
1811
-			}
1812
-		}
1813
-
1814
-		$this->sharingDisabledForUsersCache[$userId] = false;
1815
-		return false;
1816
-	}
1817
-
1818
-	/**
1819
-	 * @inheritdoc
1820
-	 */
1821
-	public function outgoingServer2ServerSharesAllowed() {
1822
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1823
-	}
1824
-
1825
-	/**
1826
-	 * @inheritdoc
1827
-	 */
1828
-	public function outgoingServer2ServerGroupSharesAllowed() {
1829
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1830
-	}
1831
-
1832
-	/**
1833
-	 * @inheritdoc
1834
-	 */
1835
-	public function shareProviderExists($shareType) {
1836
-		try {
1837
-			$this->factory->getProviderForType($shareType);
1838
-		} catch (ProviderException $e) {
1839
-			return false;
1840
-		}
1841
-
1842
-		return true;
1843
-	}
1844
-
1845
-	public function getAllShares(): iterable {
1846
-		$providers = $this->factory->getAllProviders();
1847
-
1848
-		foreach ($providers as $provider) {
1849
-			yield from $provider->getAllShares();
1850
-		}
1851
-	}
1440
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1441
+            !$this->shareApiLinkAllowPublicUpload()) {
1442
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1443
+        }
1444
+
1445
+        return $share;
1446
+    }
1447
+
1448
+    protected function checkExpireDate($share) {
1449
+        if ($share->isExpired()) {
1450
+            $this->deleteShare($share);
1451
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1452
+        }
1453
+
1454
+    }
1455
+
1456
+    /**
1457
+     * Verify the password of a public share
1458
+     *
1459
+     * @param \OCP\Share\IShare $share
1460
+     * @param string $password
1461
+     * @return bool
1462
+     */
1463
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1464
+        $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1465
+                             || $share->getShareType() !== IShare::TYPE_EMAIL
1466
+                             || $share->getShareType() !== IShare::TYPE_CIRCLE;
1467
+        if (!$passwordProtected) {
1468
+            //TODO maybe exception?
1469
+            return false;
1470
+        }
1471
+
1472
+        if ($password === null || $share->getPassword() === null) {
1473
+            return false;
1474
+        }
1475
+
1476
+        $newHash = '';
1477
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1478
+            return false;
1479
+        }
1480
+
1481
+        if (!empty($newHash)) {
1482
+            $share->setPassword($newHash);
1483
+            $provider = $this->factory->getProviderForType($share->getShareType());
1484
+            $provider->update($share);
1485
+        }
1486
+
1487
+        return true;
1488
+    }
1489
+
1490
+    /**
1491
+     * @inheritdoc
1492
+     */
1493
+    public function userDeleted($uid) {
1494
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1495
+
1496
+        foreach ($types as $type) {
1497
+            try {
1498
+                $provider = $this->factory->getProviderForType($type);
1499
+            } catch (ProviderException $e) {
1500
+                continue;
1501
+            }
1502
+            $provider->userDeleted($uid, $type);
1503
+        }
1504
+    }
1505
+
1506
+    /**
1507
+     * @inheritdoc
1508
+     */
1509
+    public function groupDeleted($gid) {
1510
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1511
+        $provider->groupDeleted($gid);
1512
+    }
1513
+
1514
+    /**
1515
+     * @inheritdoc
1516
+     */
1517
+    public function userDeletedFromGroup($uid, $gid) {
1518
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1519
+        $provider->userDeletedFromGroup($uid, $gid);
1520
+    }
1521
+
1522
+    /**
1523
+     * Get access list to a path. This means
1524
+     * all the users that can access a given path.
1525
+     *
1526
+     * Consider:
1527
+     * -root
1528
+     * |-folder1 (23)
1529
+     *  |-folder2 (32)
1530
+     *   |-fileA (42)
1531
+     *
1532
+     * fileA is shared with user1 and user1@server1
1533
+     * folder2 is shared with group2 (user4 is a member of group2)
1534
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1535
+     *
1536
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1537
+     * [
1538
+     *  users  => [
1539
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1540
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1541
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1542
+     *  ],
1543
+     *  remote => [
1544
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1545
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1546
+     *  ],
1547
+     *  public => bool
1548
+     *  mail => bool
1549
+     * ]
1550
+     *
1551
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1552
+     * [
1553
+     *  users  => ['user1', 'user2', 'user4'],
1554
+     *  remote => bool,
1555
+     *  public => bool
1556
+     *  mail => bool
1557
+     * ]
1558
+     *
1559
+     * This is required for encryption/activity
1560
+     *
1561
+     * @param \OCP\Files\Node $path
1562
+     * @param bool $recursive Should we check all parent folders as well
1563
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1564
+     * @return array
1565
+     */
1566
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1567
+        $owner = $path->getOwner();
1568
+
1569
+        if ($owner === null) {
1570
+            return [];
1571
+        }
1572
+
1573
+        $owner = $owner->getUID();
1574
+
1575
+        if ($currentAccess) {
1576
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1577
+        } else {
1578
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1579
+        }
1580
+        if (!$this->userManager->userExists($owner)) {
1581
+            return $al;
1582
+        }
1583
+
1584
+        //Get node for the owner and correct the owner in case of external storages
1585
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1586
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1587
+            $nodes = $userFolder->getById($path->getId());
1588
+            $path = array_shift($nodes);
1589
+            if ($path->getOwner() === null) {
1590
+                return [];
1591
+            }
1592
+            $owner = $path->getOwner()->getUID();
1593
+        }
1594
+
1595
+        $providers = $this->factory->getAllProviders();
1596
+
1597
+        /** @var Node[] $nodes */
1598
+        $nodes = [];
1599
+
1600
+
1601
+        if ($currentAccess) {
1602
+            $ownerPath = $path->getPath();
1603
+            $ownerPath = explode('/', $ownerPath, 4);
1604
+            if (count($ownerPath) < 4) {
1605
+                $ownerPath = '';
1606
+            } else {
1607
+                $ownerPath = $ownerPath[3];
1608
+            }
1609
+            $al['users'][$owner] = [
1610
+                'node_id' => $path->getId(),
1611
+                'node_path' => '/' . $ownerPath,
1612
+            ];
1613
+        } else {
1614
+            $al['users'][] = $owner;
1615
+        }
1616
+
1617
+        // Collect all the shares
1618
+        while ($path->getPath() !== $userFolder->getPath()) {
1619
+            $nodes[] = $path;
1620
+            if (!$recursive) {
1621
+                break;
1622
+            }
1623
+            $path = $path->getParent();
1624
+        }
1625
+
1626
+        foreach ($providers as $provider) {
1627
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1628
+
1629
+            foreach ($tmp as $k => $v) {
1630
+                if (isset($al[$k])) {
1631
+                    if (is_array($al[$k])) {
1632
+                        if ($currentAccess) {
1633
+                            $al[$k] += $v;
1634
+                        } else {
1635
+                            $al[$k] = array_merge($al[$k], $v);
1636
+                            $al[$k] = array_unique($al[$k]);
1637
+                            $al[$k] = array_values($al[$k]);
1638
+                        }
1639
+                    } else {
1640
+                        $al[$k] = $al[$k] || $v;
1641
+                    }
1642
+                } else {
1643
+                    $al[$k] = $v;
1644
+                }
1645
+            }
1646
+        }
1647
+
1648
+        return $al;
1649
+    }
1650
+
1651
+    /**
1652
+     * Create a new share
1653
+     * @return \OCP\Share\IShare
1654
+     */
1655
+    public function newShare() {
1656
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1657
+    }
1658
+
1659
+    /**
1660
+     * Is the share API enabled
1661
+     *
1662
+     * @return bool
1663
+     */
1664
+    public function shareApiEnabled() {
1665
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1666
+    }
1667
+
1668
+    /**
1669
+     * Is public link sharing enabled
1670
+     *
1671
+     * @return bool
1672
+     */
1673
+    public function shareApiAllowLinks() {
1674
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1675
+    }
1676
+
1677
+    /**
1678
+     * Is password on public link requires
1679
+     *
1680
+     * @return bool
1681
+     */
1682
+    public function shareApiLinkEnforcePassword() {
1683
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1684
+    }
1685
+
1686
+    /**
1687
+     * Is default link expire date enabled
1688
+     *
1689
+     * @return bool
1690
+     */
1691
+    public function shareApiLinkDefaultExpireDate() {
1692
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1693
+    }
1694
+
1695
+    /**
1696
+     * Is default link expire date enforced
1697
+     *`
1698
+     * @return bool
1699
+     */
1700
+    public function shareApiLinkDefaultExpireDateEnforced() {
1701
+        return $this->shareApiLinkDefaultExpireDate() &&
1702
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1703
+    }
1704
+
1705
+
1706
+    /**
1707
+     * Number of default link expire days
1708
+     * @return int
1709
+     */
1710
+    public function shareApiLinkDefaultExpireDays() {
1711
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712
+    }
1713
+
1714
+    /**
1715
+     * Is default internal expire date enabled
1716
+     *
1717
+     * @return bool
1718
+     */
1719
+    public function shareApiInternalDefaultExpireDate(): bool {
1720
+        return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1721
+    }
1722
+
1723
+    /**
1724
+     * Is default expire date enforced
1725
+     *`
1726
+     * @return bool
1727
+     */
1728
+    public function shareApiInternalDefaultExpireDateEnforced(): bool {
1729
+        return $this->shareApiInternalDefaultExpireDate() &&
1730
+            $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1731
+    }
1732
+
1733
+
1734
+    /**
1735
+     * Number of default expire days
1736
+     * @return int
1737
+     */
1738
+    public function shareApiInternalDefaultExpireDays(): int {
1739
+        return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740
+    }
1741
+
1742
+    /**
1743
+     * Allow public upload on link shares
1744
+     *
1745
+     * @return bool
1746
+     */
1747
+    public function shareApiLinkAllowPublicUpload() {
1748
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1749
+    }
1750
+
1751
+    /**
1752
+     * check if user can only share with group members
1753
+     * @return bool
1754
+     */
1755
+    public function shareWithGroupMembersOnly() {
1756
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1757
+    }
1758
+
1759
+    /**
1760
+     * Check if users can share with groups
1761
+     * @return bool
1762
+     */
1763
+    public function allowGroupSharing() {
1764
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1765
+    }
1766
+
1767
+    public function allowEnumeration(): bool {
1768
+        return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1769
+    }
1770
+
1771
+    public function limitEnumerationToGroups(): bool {
1772
+        return $this->allowEnumeration() &&
1773
+            $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1774
+    }
1775
+
1776
+    /**
1777
+     * Copied from \OC_Util::isSharingDisabledForUser
1778
+     *
1779
+     * TODO: Deprecate fuction from OC_Util
1780
+     *
1781
+     * @param string $userId
1782
+     * @return bool
1783
+     */
1784
+    public function sharingDisabledForUser($userId) {
1785
+        if ($userId === null) {
1786
+            return false;
1787
+        }
1788
+
1789
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1790
+            return $this->sharingDisabledForUsersCache[$userId];
1791
+        }
1792
+
1793
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1794
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1795
+            $excludedGroups = json_decode($groupsList);
1796
+            if (is_null($excludedGroups)) {
1797
+                $excludedGroups = explode(',', $groupsList);
1798
+                $newValue = json_encode($excludedGroups);
1799
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1800
+            }
1801
+            $user = $this->userManager->get($userId);
1802
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1803
+            if (!empty($usersGroups)) {
1804
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1805
+                // if the user is only in groups which are disabled for sharing then
1806
+                // sharing is also disabled for the user
1807
+                if (empty($remainingGroups)) {
1808
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1809
+                    return true;
1810
+                }
1811
+            }
1812
+        }
1813
+
1814
+        $this->sharingDisabledForUsersCache[$userId] = false;
1815
+        return false;
1816
+    }
1817
+
1818
+    /**
1819
+     * @inheritdoc
1820
+     */
1821
+    public function outgoingServer2ServerSharesAllowed() {
1822
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1823
+    }
1824
+
1825
+    /**
1826
+     * @inheritdoc
1827
+     */
1828
+    public function outgoingServer2ServerGroupSharesAllowed() {
1829
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1830
+    }
1831
+
1832
+    /**
1833
+     * @inheritdoc
1834
+     */
1835
+    public function shareProviderExists($shareType) {
1836
+        try {
1837
+            $this->factory->getProviderForType($shareType);
1838
+        } catch (ProviderException $e) {
1839
+            return false;
1840
+        }
1841
+
1842
+        return true;
1843
+    }
1844
+
1845
+    public function getAllShares(): iterable {
1846
+        $providers = $this->factory->getAllProviders();
1847
+
1848
+        foreach ($providers as $provider) {
1849
+            yield from $provider->getAllShares();
1850
+        }
1851
+    }
1852 1852
 }
Please login to merge, or discard this patch.
lib/private/Contacts/ContactsMenu/ContactsStore.php 1 patch
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -38,228 +38,228 @@
 block discarded – undo
38 38
 
39 39
 class ContactsStore implements IContactsStore {
40 40
 
41
-	/** @var IManager */
42
-	private $contactsManager;
43
-
44
-	/** @var IConfig */
45
-	private $config;
46
-
47
-	/** @var IUserManager */
48
-	private $userManager;
49
-
50
-	/** @var IGroupManager */
51
-	private $groupManager;
52
-
53
-	/**
54
-	 * @param IManager $contactsManager
55
-	 * @param IConfig $config
56
-	 * @param IUserManager $userManager
57
-	 * @param IGroupManager $groupManager
58
-	 */
59
-	public function __construct(IManager $contactsManager,
60
-								IConfig $config,
61
-								IUserManager $userManager,
62
-								IGroupManager $groupManager) {
63
-		$this->contactsManager = $contactsManager;
64
-		$this->config = $config;
65
-		$this->userManager = $userManager;
66
-		$this->groupManager = $groupManager;
67
-	}
68
-
69
-	/**
70
-	 * @param IUser $user
71
-	 * @param string|null $filter
72
-	 * @return IEntry[]
73
-	 */
74
-	public function getContacts(IUser $user, $filter) {
75
-		$allContacts = $this->contactsManager->search($filter ?: '', [
76
-			'FN',
77
-			'EMAIL'
78
-		]);
79
-
80
-		$entries = array_map(function(array $contact) {
81
-			return $this->contactArrayToEntry($contact);
82
-		}, $allContacts);
83
-		return $this->filterContacts(
84
-			$user,
85
-			$entries,
86
-			$filter
87
-		);
88
-	}
89
-
90
-	/**
91
-	 * Filters the contacts. Applies 3 filters:
92
-	 *  1. filter the current user
93
-	 *  2. if the `shareapi_allow_share_dialog_user_enumeration` config option is
94
-	 * enabled it will filter all local users
95
-	 *  3. if the `shareapi_exclude_groups` config option is enabled and the
96
-	 * current user is in an excluded group it will filter all local users.
97
-	 *  4. if the `shareapi_only_share_with_group_members` config option is
98
-	 * enabled it will filter all users which doens't have a common group
99
-	 * with the current user.
100
-	 *
101
-	 * @param IUser $self
102
-	 * @param Entry[] $entries
103
-	 * @param string $filter
104
-	 * @return Entry[] the filtered contacts
105
-	 */
106
-	private function filterContacts(IUser $self,
107
-									array $entries,
108
-									$filter) {
109
-		$disallowEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') !== 'yes';
110
-		$restrictEnumeration = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'yes') === 'yes';
111
-		$excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes';
112
-
113
-		// whether to filter out local users
114
-		$skipLocal = false;
115
-		// whether to filter out all users which doesn't have the same group as the current user
116
-		$ownGroupsOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes' || $restrictEnumeration;
117
-
118
-		$selfGroups = $this->groupManager->getUserGroupIds($self);
119
-
120
-		if ($excludedGroups) {
121
-			$excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
122
-			$decodedExcludeGroups = json_decode($excludedGroups, true);
123
-			$excludeGroupsList = ($decodedExcludeGroups !== null) ? $decodedExcludeGroups :  [];
124
-
125
-			if (count(array_intersect($excludeGroupsList, $selfGroups)) !== 0) {
126
-				// a group of the current user is excluded -> filter all local users
127
-				$skipLocal = true;
128
-			}
129
-		}
130
-
131
-		$selfUID = $self->getUID();
132
-
133
-		return array_values(array_filter($entries, function(IEntry $entry) use ($self, $skipLocal, $ownGroupsOnly, $selfGroups, $selfUID, $disallowEnumeration, $filter) {
134
-			if ($skipLocal && $entry->getProperty('isLocalSystemBook') === true) {
135
-				return false;
136
-			}
137
-
138
-			// Prevent enumerating local users
139
-			if($disallowEnumeration && $entry->getProperty('isLocalSystemBook')) {
140
-				$filterUser = true;
141
-
142
-				$mailAddresses = $entry->getEMailAddresses();
143
-				foreach($mailAddresses as $mailAddress) {
144
-					if($mailAddress === $filter) {
145
-						$filterUser = false;
146
-						break;
147
-					}
148
-				}
149
-
150
-				if($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) {
151
-					$filterUser = false;
152
-				}
153
-
154
-				if($filterUser) {
155
-					return false;
156
-				}
157
-			}
158
-
159
-			if ($ownGroupsOnly && $entry->getProperty('isLocalSystemBook') === true) {
160
-				$uid = $this->userManager->get($entry->getProperty('UID'));
161
-
162
-				if ($uid === NULL) {
163
-					return false;
164
-				}
165
-
166
-				$contactGroups = $this->groupManager->getUserGroupIds($uid);
167
-				if (count(array_intersect($contactGroups, $selfGroups)) === 0) {
168
-					// no groups in common, so shouldn't see the contact
169
-					return false;
170
-				}
171
-			}
172
-
173
-			return $entry->getProperty('UID') !== $selfUID;
174
-		}));
175
-	}
176
-
177
-	/**
178
-	 * @param IUser $user
179
-	 * @param integer $shareType
180
-	 * @param string $shareWith
181
-	 * @return IEntry|null
182
-	 */
183
-	public function findOne(IUser $user, $shareType, $shareWith) {
184
-		switch($shareType) {
185
-			case 0:
186
-			case 6:
187
-				$filter = ['UID'];
188
-				break;
189
-			case 4:
190
-				$filter = ['EMAIL'];
191
-				break;
192
-			default:
193
-				return null;
194
-		}
195
-
196
-		$userId = $user->getUID();
197
-		$allContacts = $this->contactsManager->search($shareWith, $filter);
198
-		$contacts = array_filter($allContacts, function($contact) use ($userId) {
199
-			return $contact['UID'] !== $userId;
200
-		});
201
-		$match = null;
202
-
203
-		foreach ($contacts as $contact) {
204
-			if ($shareType === 4 && isset($contact['EMAIL'])) {
205
-				if (in_array($shareWith, $contact['EMAIL'])) {
206
-					$match = $contact;
207
-					break;
208
-				}
209
-			}
210
-			if ($shareType === 0 || $shareType === 6) {
211
-				$isLocal = $contact['isLocalSystemBook'] ?? false;
212
-				if ($contact['UID'] === $shareWith && $isLocal === true) {
213
-					$match = $contact;
214
-					break;
215
-				}
216
-			}
217
-		}
218
-
219
-		if ($match) {
220
-			$match = $this->filterContacts($user, [$this->contactArrayToEntry($match)], $shareWith);
221
-			if (count($match) === 1) {
222
-				$match = $match[0];
223
-			} else {
224
-				$match = null;
225
-			}
226
-
227
-		}
228
-
229
-		return $match;
230
-	}
231
-
232
-	/**
233
-	 * @param array $contact
234
-	 * @return Entry
235
-	 */
236
-	private function contactArrayToEntry(array $contact) {
237
-		$entry = new Entry();
238
-
239
-		if (isset($contact['id'])) {
240
-			$entry->setId($contact['id']);
241
-		}
242
-
243
-		if (isset($contact['FN'])) {
244
-			$entry->setFullName($contact['FN']);
245
-		}
246
-
247
-		$avatarPrefix = "VALUE=uri:";
248
-		if (isset($contact['PHOTO']) && strpos($contact['PHOTO'], $avatarPrefix) === 0) {
249
-			$entry->setAvatar(substr($contact['PHOTO'], strlen($avatarPrefix)));
250
-		}
251
-
252
-		if (isset($contact['EMAIL'])) {
253
-			foreach ($contact['EMAIL'] as $email) {
254
-				$entry->addEMailAddress($email);
255
-			}
256
-		}
257
-
258
-		// Attach all other properties to the entry too because some
259
-		// providers might make use of it.
260
-		$entry->setProperties($contact);
261
-
262
-		return $entry;
263
-	}
41
+    /** @var IManager */
42
+    private $contactsManager;
43
+
44
+    /** @var IConfig */
45
+    private $config;
46
+
47
+    /** @var IUserManager */
48
+    private $userManager;
49
+
50
+    /** @var IGroupManager */
51
+    private $groupManager;
52
+
53
+    /**
54
+     * @param IManager $contactsManager
55
+     * @param IConfig $config
56
+     * @param IUserManager $userManager
57
+     * @param IGroupManager $groupManager
58
+     */
59
+    public function __construct(IManager $contactsManager,
60
+                                IConfig $config,
61
+                                IUserManager $userManager,
62
+                                IGroupManager $groupManager) {
63
+        $this->contactsManager = $contactsManager;
64
+        $this->config = $config;
65
+        $this->userManager = $userManager;
66
+        $this->groupManager = $groupManager;
67
+    }
68
+
69
+    /**
70
+     * @param IUser $user
71
+     * @param string|null $filter
72
+     * @return IEntry[]
73
+     */
74
+    public function getContacts(IUser $user, $filter) {
75
+        $allContacts = $this->contactsManager->search($filter ?: '', [
76
+            'FN',
77
+            'EMAIL'
78
+        ]);
79
+
80
+        $entries = array_map(function(array $contact) {
81
+            return $this->contactArrayToEntry($contact);
82
+        }, $allContacts);
83
+        return $this->filterContacts(
84
+            $user,
85
+            $entries,
86
+            $filter
87
+        );
88
+    }
89
+
90
+    /**
91
+     * Filters the contacts. Applies 3 filters:
92
+     *  1. filter the current user
93
+     *  2. if the `shareapi_allow_share_dialog_user_enumeration` config option is
94
+     * enabled it will filter all local users
95
+     *  3. if the `shareapi_exclude_groups` config option is enabled and the
96
+     * current user is in an excluded group it will filter all local users.
97
+     *  4. if the `shareapi_only_share_with_group_members` config option is
98
+     * enabled it will filter all users which doens't have a common group
99
+     * with the current user.
100
+     *
101
+     * @param IUser $self
102
+     * @param Entry[] $entries
103
+     * @param string $filter
104
+     * @return Entry[] the filtered contacts
105
+     */
106
+    private function filterContacts(IUser $self,
107
+                                    array $entries,
108
+                                    $filter) {
109
+        $disallowEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') !== 'yes';
110
+        $restrictEnumeration = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'yes') === 'yes';
111
+        $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes';
112
+
113
+        // whether to filter out local users
114
+        $skipLocal = false;
115
+        // whether to filter out all users which doesn't have the same group as the current user
116
+        $ownGroupsOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes' || $restrictEnumeration;
117
+
118
+        $selfGroups = $this->groupManager->getUserGroupIds($self);
119
+
120
+        if ($excludedGroups) {
121
+            $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
122
+            $decodedExcludeGroups = json_decode($excludedGroups, true);
123
+            $excludeGroupsList = ($decodedExcludeGroups !== null) ? $decodedExcludeGroups :  [];
124
+
125
+            if (count(array_intersect($excludeGroupsList, $selfGroups)) !== 0) {
126
+                // a group of the current user is excluded -> filter all local users
127
+                $skipLocal = true;
128
+            }
129
+        }
130
+
131
+        $selfUID = $self->getUID();
132
+
133
+        return array_values(array_filter($entries, function(IEntry $entry) use ($self, $skipLocal, $ownGroupsOnly, $selfGroups, $selfUID, $disallowEnumeration, $filter) {
134
+            if ($skipLocal && $entry->getProperty('isLocalSystemBook') === true) {
135
+                return false;
136
+            }
137
+
138
+            // Prevent enumerating local users
139
+            if($disallowEnumeration && $entry->getProperty('isLocalSystemBook')) {
140
+                $filterUser = true;
141
+
142
+                $mailAddresses = $entry->getEMailAddresses();
143
+                foreach($mailAddresses as $mailAddress) {
144
+                    if($mailAddress === $filter) {
145
+                        $filterUser = false;
146
+                        break;
147
+                    }
148
+                }
149
+
150
+                if($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) {
151
+                    $filterUser = false;
152
+                }
153
+
154
+                if($filterUser) {
155
+                    return false;
156
+                }
157
+            }
158
+
159
+            if ($ownGroupsOnly && $entry->getProperty('isLocalSystemBook') === true) {
160
+                $uid = $this->userManager->get($entry->getProperty('UID'));
161
+
162
+                if ($uid === NULL) {
163
+                    return false;
164
+                }
165
+
166
+                $contactGroups = $this->groupManager->getUserGroupIds($uid);
167
+                if (count(array_intersect($contactGroups, $selfGroups)) === 0) {
168
+                    // no groups in common, so shouldn't see the contact
169
+                    return false;
170
+                }
171
+            }
172
+
173
+            return $entry->getProperty('UID') !== $selfUID;
174
+        }));
175
+    }
176
+
177
+    /**
178
+     * @param IUser $user
179
+     * @param integer $shareType
180
+     * @param string $shareWith
181
+     * @return IEntry|null
182
+     */
183
+    public function findOne(IUser $user, $shareType, $shareWith) {
184
+        switch($shareType) {
185
+            case 0:
186
+            case 6:
187
+                $filter = ['UID'];
188
+                break;
189
+            case 4:
190
+                $filter = ['EMAIL'];
191
+                break;
192
+            default:
193
+                return null;
194
+        }
195
+
196
+        $userId = $user->getUID();
197
+        $allContacts = $this->contactsManager->search($shareWith, $filter);
198
+        $contacts = array_filter($allContacts, function($contact) use ($userId) {
199
+            return $contact['UID'] !== $userId;
200
+        });
201
+        $match = null;
202
+
203
+        foreach ($contacts as $contact) {
204
+            if ($shareType === 4 && isset($contact['EMAIL'])) {
205
+                if (in_array($shareWith, $contact['EMAIL'])) {
206
+                    $match = $contact;
207
+                    break;
208
+                }
209
+            }
210
+            if ($shareType === 0 || $shareType === 6) {
211
+                $isLocal = $contact['isLocalSystemBook'] ?? false;
212
+                if ($contact['UID'] === $shareWith && $isLocal === true) {
213
+                    $match = $contact;
214
+                    break;
215
+                }
216
+            }
217
+        }
218
+
219
+        if ($match) {
220
+            $match = $this->filterContacts($user, [$this->contactArrayToEntry($match)], $shareWith);
221
+            if (count($match) === 1) {
222
+                $match = $match[0];
223
+            } else {
224
+                $match = null;
225
+            }
226
+
227
+        }
228
+
229
+        return $match;
230
+    }
231
+
232
+    /**
233
+     * @param array $contact
234
+     * @return Entry
235
+     */
236
+    private function contactArrayToEntry(array $contact) {
237
+        $entry = new Entry();
238
+
239
+        if (isset($contact['id'])) {
240
+            $entry->setId($contact['id']);
241
+        }
242
+
243
+        if (isset($contact['FN'])) {
244
+            $entry->setFullName($contact['FN']);
245
+        }
246
+
247
+        $avatarPrefix = "VALUE=uri:";
248
+        if (isset($contact['PHOTO']) && strpos($contact['PHOTO'], $avatarPrefix) === 0) {
249
+            $entry->setAvatar(substr($contact['PHOTO'], strlen($avatarPrefix)));
250
+        }
251
+
252
+        if (isset($contact['EMAIL'])) {
253
+            foreach ($contact['EMAIL'] as $email) {
254
+                $entry->addEMailAddress($email);
255
+            }
256
+        }
257
+
258
+        // Attach all other properties to the entry too because some
259
+        // providers might make use of it.
260
+        $entry->setProperties($contact);
261
+
262
+        return $entry;
263
+    }
264 264
 
265 265
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/UserPlugin.php 2 patches
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -39,155 +39,155 @@
 block discarded – undo
39 39
 use OCP\Share\IShare;
40 40
 
41 41
 class UserPlugin implements ISearchPlugin {
42
-	/* @var bool */
43
-	protected $shareWithGroupOnly;
44
-	protected $shareeEnumeration;
45
-	protected $shareeEnumerationInGroupOnly;
46
-
47
-	/** @var IConfig */
48
-	private $config;
49
-	/** @var IGroupManager */
50
-	private $groupManager;
51
-	/** @var IUserSession */
52
-	private $userSession;
53
-	/** @var IUserManager */
54
-	private $userManager;
55
-
56
-	public function __construct(IConfig $config, IUserManager $userManager, IGroupManager $groupManager, IUserSession $userSession) {
57
-		$this->config = $config;
58
-
59
-		$this->groupManager = $groupManager;
60
-		$this->userSession = $userSession;
61
-		$this->userManager = $userManager;
62
-
63
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
64
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
65
-		$this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
66
-	}
67
-
68
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
69
-		$result = ['wide' => [], 'exact' => []];
70
-		$users = [];
71
-		$autoCompleteUsers = [];
72
-		$hasMoreResults = false;
73
-
74
-		$userGroups = [];
75
-		if ($this->shareWithGroupOnly) {
76
-			// Search in all the groups this user is part of
77
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
78
-			foreach ($userGroups as $userGroup) {
79
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $limit, $offset);
80
-				foreach ($usersTmp as $uid => $userDisplayName) {
81
-					$users[(string) $uid] = $userDisplayName;
82
-				}
83
-			}
84
-		} else {
85
-			// Search in all users
86
-			$usersTmp = $this->userManager->searchDisplayName($search, $limit, $offset);
87
-			$currentUserGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
88
-			foreach ($usersTmp as $user) {
89
-				if ($user->isEnabled()) { // Don't keep deactivated users
90
-					$users[(string) $user->getUID()] = $user->getDisplayName();
91
-
92
-					$addToWideResults = false;
93
-					if ($this->shareeEnumeration && !$this->shareeEnumerationInGroupOnly) {
94
-						$addToWideResults = true;
95
-					}
96
-
97
-					if ($this->shareeEnumerationInGroupOnly) {
98
-						$commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
99
-						if (!empty($commonGroups)) {
100
-							$addToWideResults = true;
101
-						}
102
-					}
103
-
104
-					if ($addToWideResults) {
105
-						$autoCompleteUsers[] = [
106
-							'label' => $user->getDisplayName(),
107
-							'value' => [
108
-								'shareType' => IShare::TYPE_USER,
109
-								'shareWith' => (string)$user->getUID(),
110
-							],
111
-						];
112
-					}
113
-				}
114
-			}
115
-		}
116
-
117
-		$this->takeOutCurrentUser($users);
118
-
119
-		if (!$this->shareeEnumeration || count($users) < $limit) {
120
-			$hasMoreResults = true;
121
-		}
122
-
123
-		$foundUserById = false;
124
-		$lowerSearch = strtolower($search);
125
-		foreach ($users as $uid => $userDisplayName) {
126
-			$uid = (string) $uid;
127
-			if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
128
-				if (strtolower($uid) === $lowerSearch) {
129
-					$foundUserById = true;
130
-				}
131
-				$result['exact'][] = [
132
-					'label' => $userDisplayName,
133
-					'value' => [
134
-						'shareType' => Share::SHARE_TYPE_USER,
135
-						'shareWith' => $uid,
136
-					],
137
-				];
138
-			} else {
139
-				$result['wide'][] = [
140
-					'label' => $userDisplayName,
141
-					'value' => [
142
-						'shareType' => Share::SHARE_TYPE_USER,
143
-						'shareWith' => $uid,
144
-					],
145
-				];
146
-			}
147
-		}
148
-
149
-		if ($offset === 0 && !$foundUserById) {
150
-			// On page one we try if the search result has a direct hit on the
151
-			// user id and if so, we add that to the exact match list
152
-			$user = $this->userManager->get($search);
153
-			if ($user instanceof IUser) {
154
-				$addUser = true;
155
-
156
-				if ($this->shareWithGroupOnly) {
157
-					// Only add, if we have a common group
158
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
159
-					$addUser = !empty($commonGroups);
160
-				}
161
-
162
-				if ($addUser) {
163
-					$result['exact'][] = [
164
-						'label' => $user->getDisplayName(),
165
-						'value' => [
166
-							'shareType' => Share::SHARE_TYPE_USER,
167
-							'shareWith' => $user->getUID(),
168
-						],
169
-					];
170
-				}
171
-			}
172
-		}
173
-
174
-		// overwrite wide matches if they are limited
175
-		if (!$this->shareeEnumeration || $this->shareeEnumerationInGroupOnly) {
176
-			$result['wide'] = $autoCompleteUsers;
177
-		}
178
-
179
-		$type = new SearchResultType('users');
180
-		$searchResult->addResultSet($type, $result['wide'], $result['exact']);
181
-
182
-		return $hasMoreResults;
183
-	}
184
-
185
-	public function takeOutCurrentUser(array &$users) {
186
-		$currentUser = $this->userSession->getUser();
187
-		if(!is_null($currentUser)) {
188
-			if (isset($users[$currentUser->getUID()])) {
189
-				unset($users[$currentUser->getUID()]);
190
-			}
191
-		}
192
-	}
42
+    /* @var bool */
43
+    protected $shareWithGroupOnly;
44
+    protected $shareeEnumeration;
45
+    protected $shareeEnumerationInGroupOnly;
46
+
47
+    /** @var IConfig */
48
+    private $config;
49
+    /** @var IGroupManager */
50
+    private $groupManager;
51
+    /** @var IUserSession */
52
+    private $userSession;
53
+    /** @var IUserManager */
54
+    private $userManager;
55
+
56
+    public function __construct(IConfig $config, IUserManager $userManager, IGroupManager $groupManager, IUserSession $userSession) {
57
+        $this->config = $config;
58
+
59
+        $this->groupManager = $groupManager;
60
+        $this->userSession = $userSession;
61
+        $this->userManager = $userManager;
62
+
63
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
64
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
65
+        $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
66
+    }
67
+
68
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
69
+        $result = ['wide' => [], 'exact' => []];
70
+        $users = [];
71
+        $autoCompleteUsers = [];
72
+        $hasMoreResults = false;
73
+
74
+        $userGroups = [];
75
+        if ($this->shareWithGroupOnly) {
76
+            // Search in all the groups this user is part of
77
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
78
+            foreach ($userGroups as $userGroup) {
79
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $limit, $offset);
80
+                foreach ($usersTmp as $uid => $userDisplayName) {
81
+                    $users[(string) $uid] = $userDisplayName;
82
+                }
83
+            }
84
+        } else {
85
+            // Search in all users
86
+            $usersTmp = $this->userManager->searchDisplayName($search, $limit, $offset);
87
+            $currentUserGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
88
+            foreach ($usersTmp as $user) {
89
+                if ($user->isEnabled()) { // Don't keep deactivated users
90
+                    $users[(string) $user->getUID()] = $user->getDisplayName();
91
+
92
+                    $addToWideResults = false;
93
+                    if ($this->shareeEnumeration && !$this->shareeEnumerationInGroupOnly) {
94
+                        $addToWideResults = true;
95
+                    }
96
+
97
+                    if ($this->shareeEnumerationInGroupOnly) {
98
+                        $commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
99
+                        if (!empty($commonGroups)) {
100
+                            $addToWideResults = true;
101
+                        }
102
+                    }
103
+
104
+                    if ($addToWideResults) {
105
+                        $autoCompleteUsers[] = [
106
+                            'label' => $user->getDisplayName(),
107
+                            'value' => [
108
+                                'shareType' => IShare::TYPE_USER,
109
+                                'shareWith' => (string)$user->getUID(),
110
+                            ],
111
+                        ];
112
+                    }
113
+                }
114
+            }
115
+        }
116
+
117
+        $this->takeOutCurrentUser($users);
118
+
119
+        if (!$this->shareeEnumeration || count($users) < $limit) {
120
+            $hasMoreResults = true;
121
+        }
122
+
123
+        $foundUserById = false;
124
+        $lowerSearch = strtolower($search);
125
+        foreach ($users as $uid => $userDisplayName) {
126
+            $uid = (string) $uid;
127
+            if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
128
+                if (strtolower($uid) === $lowerSearch) {
129
+                    $foundUserById = true;
130
+                }
131
+                $result['exact'][] = [
132
+                    'label' => $userDisplayName,
133
+                    'value' => [
134
+                        'shareType' => Share::SHARE_TYPE_USER,
135
+                        'shareWith' => $uid,
136
+                    ],
137
+                ];
138
+            } else {
139
+                $result['wide'][] = [
140
+                    'label' => $userDisplayName,
141
+                    'value' => [
142
+                        'shareType' => Share::SHARE_TYPE_USER,
143
+                        'shareWith' => $uid,
144
+                    ],
145
+                ];
146
+            }
147
+        }
148
+
149
+        if ($offset === 0 && !$foundUserById) {
150
+            // On page one we try if the search result has a direct hit on the
151
+            // user id and if so, we add that to the exact match list
152
+            $user = $this->userManager->get($search);
153
+            if ($user instanceof IUser) {
154
+                $addUser = true;
155
+
156
+                if ($this->shareWithGroupOnly) {
157
+                    // Only add, if we have a common group
158
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
159
+                    $addUser = !empty($commonGroups);
160
+                }
161
+
162
+                if ($addUser) {
163
+                    $result['exact'][] = [
164
+                        'label' => $user->getDisplayName(),
165
+                        'value' => [
166
+                            'shareType' => Share::SHARE_TYPE_USER,
167
+                            'shareWith' => $user->getUID(),
168
+                        ],
169
+                    ];
170
+                }
171
+            }
172
+        }
173
+
174
+        // overwrite wide matches if they are limited
175
+        if (!$this->shareeEnumeration || $this->shareeEnumerationInGroupOnly) {
176
+            $result['wide'] = $autoCompleteUsers;
177
+        }
178
+
179
+        $type = new SearchResultType('users');
180
+        $searchResult->addResultSet($type, $result['wide'], $result['exact']);
181
+
182
+        return $hasMoreResults;
183
+    }
184
+
185
+    public function takeOutCurrentUser(array &$users) {
186
+        $currentUser = $this->userSession->getUser();
187
+        if(!is_null($currentUser)) {
188
+            if (isset($users[$currentUser->getUID()])) {
189
+                unset($users[$currentUser->getUID()]);
190
+            }
191
+        }
192
+    }
193 193
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 							'label' => $user->getDisplayName(),
107 107
 							'value' => [
108 108
 								'shareType' => IShare::TYPE_USER,
109
-								'shareWith' => (string)$user->getUID(),
109
+								'shareWith' => (string) $user->getUID(),
110 110
 							],
111 111
 						];
112 112
 					}
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 
185 185
 	public function takeOutCurrentUser(array &$users) {
186 186
 		$currentUser = $this->userSession->getUser();
187
-		if(!is_null($currentUser)) {
187
+		if (!is_null($currentUser)) {
188 188
 			if (isset($users[$currentUser->getUID()])) {
189 189
 				unset($users[$currentUser->getUID()]);
190 190
 			}
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/GroupPlugin.php 2 patches
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -35,100 +35,100 @@
 block discarded – undo
35 35
 use OCP\Share;
36 36
 
37 37
 class GroupPlugin implements ISearchPlugin {
38
-	protected $shareeEnumeration;
39
-	protected $shareWithGroupOnly;
40
-
41
-	/** @var IGroupManager */
42
-	private $groupManager;
43
-	/** @var IConfig */
44
-	private $config;
45
-	/** @var IUserSession */
46
-	private $userSession;
47
-
48
-	public function __construct(IConfig $config, IGroupManager $groupManager, IUserSession $userSession) {
49
-		$this->groupManager = $groupManager;
50
-		$this->config = $config;
51
-		$this->userSession = $userSession;
52
-
53
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
54
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
55
-		$this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
56
-	}
57
-
58
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
59
-		$hasMoreResults = false;
60
-		$result = ['wide' => [], 'exact' => []];
61
-
62
-		$groups = $this->groupManager->search($search, $limit, $offset);
63
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
64
-
65
-		if (!$this->shareeEnumeration || count($groups) < $limit) {
66
-			$hasMoreResults = true;
67
-		}
68
-
69
-		$userGroups =  [];
70
-		if (!empty($groups) && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) {
71
-			// Intersect all the groups that match with the groups this user is a member of
72
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
73
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
74
-			$groupIds = array_intersect($groupIds, $userGroups);
75
-		}
76
-
77
-		$lowerSearch = strtolower($search);
78
-		foreach ($groups as $group) {
79
-			if ($group->hideFromCollaboration()) {
80
-				continue;
81
-			}
82
-
83
-			// FIXME: use a more efficient approach
84
-			$gid = $group->getGID();
85
-			if (!in_array($gid, $groupIds)) {
86
-				continue;
87
-			}
88
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
89
-				$result['exact'][] = [
90
-					'label' => $group->getDisplayName(),
91
-					'value' => [
92
-						'shareType' => Share::SHARE_TYPE_GROUP,
93
-						'shareWith' => $gid,
94
-					],
95
-				];
96
-			} else {
97
-				if ($this->shareeEnumerationInGroupOnly && !in_array($group->getGID(), $userGroups, true)) {
98
-					continue;
99
-				}
100
-				$result['wide'][] = [
101
-					'label' => $group->getDisplayName(),
102
-					'value' => [
103
-						'shareType' => Share::SHARE_TYPE_GROUP,
104
-						'shareWith' => $gid,
105
-					],
106
-				];
107
-			}
108
-		}
109
-
110
-		if ($offset === 0 && empty($result['exact'])) {
111
-			// On page one we try if the search result has a direct hit on the
112
-			// user id and if so, we add that to the exact match list
113
-			$group = $this->groupManager->get($search);
114
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
115
-				$result['exact'][] = [
116
-					'label' => $group->getDisplayName(),
117
-					'value' => [
118
-						'shareType' => Share::SHARE_TYPE_GROUP,
119
-						'shareWith' => $group->getGID(),
120
-					],
121
-				];
122
-			}
123
-		}
124
-
125
-		if (!$this->shareeEnumeration) {
126
-			$result['wide'] = [];
127
-		}
128
-
129
-		$type = new SearchResultType('groups');
130
-		$searchResult->addResultSet($type, $result['wide'], $result['exact']);
131
-
132
-		return $hasMoreResults;
133
-	}
38
+    protected $shareeEnumeration;
39
+    protected $shareWithGroupOnly;
40
+
41
+    /** @var IGroupManager */
42
+    private $groupManager;
43
+    /** @var IConfig */
44
+    private $config;
45
+    /** @var IUserSession */
46
+    private $userSession;
47
+
48
+    public function __construct(IConfig $config, IGroupManager $groupManager, IUserSession $userSession) {
49
+        $this->groupManager = $groupManager;
50
+        $this->config = $config;
51
+        $this->userSession = $userSession;
52
+
53
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
54
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
55
+        $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
56
+    }
57
+
58
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
59
+        $hasMoreResults = false;
60
+        $result = ['wide' => [], 'exact' => []];
61
+
62
+        $groups = $this->groupManager->search($search, $limit, $offset);
63
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
64
+
65
+        if (!$this->shareeEnumeration || count($groups) < $limit) {
66
+            $hasMoreResults = true;
67
+        }
68
+
69
+        $userGroups =  [];
70
+        if (!empty($groups) && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) {
71
+            // Intersect all the groups that match with the groups this user is a member of
72
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
73
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
74
+            $groupIds = array_intersect($groupIds, $userGroups);
75
+        }
76
+
77
+        $lowerSearch = strtolower($search);
78
+        foreach ($groups as $group) {
79
+            if ($group->hideFromCollaboration()) {
80
+                continue;
81
+            }
82
+
83
+            // FIXME: use a more efficient approach
84
+            $gid = $group->getGID();
85
+            if (!in_array($gid, $groupIds)) {
86
+                continue;
87
+            }
88
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
89
+                $result['exact'][] = [
90
+                    'label' => $group->getDisplayName(),
91
+                    'value' => [
92
+                        'shareType' => Share::SHARE_TYPE_GROUP,
93
+                        'shareWith' => $gid,
94
+                    ],
95
+                ];
96
+            } else {
97
+                if ($this->shareeEnumerationInGroupOnly && !in_array($group->getGID(), $userGroups, true)) {
98
+                    continue;
99
+                }
100
+                $result['wide'][] = [
101
+                    'label' => $group->getDisplayName(),
102
+                    'value' => [
103
+                        'shareType' => Share::SHARE_TYPE_GROUP,
104
+                        'shareWith' => $gid,
105
+                    ],
106
+                ];
107
+            }
108
+        }
109
+
110
+        if ($offset === 0 && empty($result['exact'])) {
111
+            // On page one we try if the search result has a direct hit on the
112
+            // user id and if so, we add that to the exact match list
113
+            $group = $this->groupManager->get($search);
114
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
115
+                $result['exact'][] = [
116
+                    'label' => $group->getDisplayName(),
117
+                    'value' => [
118
+                        'shareType' => Share::SHARE_TYPE_GROUP,
119
+                        'shareWith' => $group->getGID(),
120
+                    ],
121
+                ];
122
+            }
123
+        }
124
+
125
+        if (!$this->shareeEnumeration) {
126
+            $result['wide'] = [];
127
+        }
128
+
129
+        $type = new SearchResultType('groups');
130
+        $searchResult->addResultSet($type, $result['wide'], $result['exact']);
131
+
132
+        return $hasMoreResults;
133
+    }
134 134
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -60,17 +60,17 @@
 block discarded – undo
60 60
 		$result = ['wide' => [], 'exact' => []];
61 61
 
62 62
 		$groups = $this->groupManager->search($search, $limit, $offset);
63
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
63
+		$groupIds = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
64 64
 
65 65
 		if (!$this->shareeEnumeration || count($groups) < $limit) {
66 66
 			$hasMoreResults = true;
67 67
 		}
68 68
 
69
-		$userGroups =  [];
69
+		$userGroups = [];
70 70
 		if (!empty($groups) && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) {
71 71
 			// Intersect all the groups that match with the groups this user is a member of
72 72
 			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
73
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
73
+			$userGroups = array_map(function(IGroup $group) { return $group->getGID(); }, $userGroups);
74 74
 			$groupIds = array_intersect($groupIds, $userGroups);
75 75
 		}
76 76
 
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/MailPlugin.php 1 patch
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -40,211 +40,211 @@
 block discarded – undo
40 40
 use OCP\Share;
41 41
 
42 42
 class MailPlugin implements ISearchPlugin {
43
-	protected $shareeEnumeration;
44
-	protected $shareWithGroupOnly;
45
-
46
-	/** @var IManager */
47
-	private $contactsManager;
48
-	/** @var ICloudIdManager */
49
-	private $cloudIdManager;
50
-	/** @var IConfig */
51
-	private $config;
52
-
53
-	/** @var IGroupManager */
54
-	private $groupManager;
55
-
56
-	/** @var IUserSession */
57
-	private $userSession;
58
-
59
-	public function __construct(IManager $contactsManager, ICloudIdManager $cloudIdManager, IConfig $config, IGroupManager $groupManager, IUserSession $userSession) {
60
-		$this->contactsManager = $contactsManager;
61
-		$this->cloudIdManager = $cloudIdManager;
62
-		$this->config = $config;
63
-		$this->groupManager = $groupManager;
64
-		$this->userSession = $userSession;
65
-
66
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
67
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
68
-		$this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
69
-
70
-	}
71
-
72
-	/**
73
-	 * @param $search
74
-	 * @param $limit
75
-	 * @param $offset
76
-	 * @param ISearchResult $searchResult
77
-	 * @return bool
78
-	 * @since 13.0.0
79
-	 */
80
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
81
-		$result = $userResults = ['wide' => [], 'exact' => []];
82
-		$userType = new SearchResultType('users');
83
-		$emailType = new SearchResultType('emails');
84
-
85
-		// Search in contacts
86
-		//@todo Pagination missing
87
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
88
-		$lowerSearch = strtolower($search);
89
-		foreach ($addressBookContacts as $contact) {
90
-			if (isset($contact['EMAIL'])) {
91
-				$emailAddresses = $contact['EMAIL'];
92
-				if (\is_string($emailAddresses)) {
93
-					$emailAddresses = [$emailAddresses];
94
-				}
95
-				foreach ($emailAddresses as $type => $emailAddress) {
96
-					$displayName = $emailAddress;
97
-					$emailAddressType = null;
98
-					if (\is_array($emailAddress)) {
99
-						$emailAddressData = $emailAddress;
100
-						$emailAddress = $emailAddressData['value'];
101
-						$emailAddressType = $emailAddressData['type'];
102
-					}
103
-					if (isset($contact['FN'])) 	{
104
-						$displayName = $contact['FN'] . ' (' . $emailAddress . ')';
105
-					}
106
-					$exactEmailMatch = strtolower($emailAddress) === $lowerSearch;
107
-
108
-					if (isset($contact['isLocalSystemBook'])) {
109
-						if ($this->shareWithGroupOnly) {
110
-							/*
43
+    protected $shareeEnumeration;
44
+    protected $shareWithGroupOnly;
45
+
46
+    /** @var IManager */
47
+    private $contactsManager;
48
+    /** @var ICloudIdManager */
49
+    private $cloudIdManager;
50
+    /** @var IConfig */
51
+    private $config;
52
+
53
+    /** @var IGroupManager */
54
+    private $groupManager;
55
+
56
+    /** @var IUserSession */
57
+    private $userSession;
58
+
59
+    public function __construct(IManager $contactsManager, ICloudIdManager $cloudIdManager, IConfig $config, IGroupManager $groupManager, IUserSession $userSession) {
60
+        $this->contactsManager = $contactsManager;
61
+        $this->cloudIdManager = $cloudIdManager;
62
+        $this->config = $config;
63
+        $this->groupManager = $groupManager;
64
+        $this->userSession = $userSession;
65
+
66
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
67
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
68
+        $this->shareeEnumerationInGroupOnly = $this->shareeEnumeration && $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
69
+
70
+    }
71
+
72
+    /**
73
+     * @param $search
74
+     * @param $limit
75
+     * @param $offset
76
+     * @param ISearchResult $searchResult
77
+     * @return bool
78
+     * @since 13.0.0
79
+     */
80
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
81
+        $result = $userResults = ['wide' => [], 'exact' => []];
82
+        $userType = new SearchResultType('users');
83
+        $emailType = new SearchResultType('emails');
84
+
85
+        // Search in contacts
86
+        //@todo Pagination missing
87
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
88
+        $lowerSearch = strtolower($search);
89
+        foreach ($addressBookContacts as $contact) {
90
+            if (isset($contact['EMAIL'])) {
91
+                $emailAddresses = $contact['EMAIL'];
92
+                if (\is_string($emailAddresses)) {
93
+                    $emailAddresses = [$emailAddresses];
94
+                }
95
+                foreach ($emailAddresses as $type => $emailAddress) {
96
+                    $displayName = $emailAddress;
97
+                    $emailAddressType = null;
98
+                    if (\is_array($emailAddress)) {
99
+                        $emailAddressData = $emailAddress;
100
+                        $emailAddress = $emailAddressData['value'];
101
+                        $emailAddressType = $emailAddressData['type'];
102
+                    }
103
+                    if (isset($contact['FN'])) 	{
104
+                        $displayName = $contact['FN'] . ' (' . $emailAddress . ')';
105
+                    }
106
+                    $exactEmailMatch = strtolower($emailAddress) === $lowerSearch;
107
+
108
+                    if (isset($contact['isLocalSystemBook'])) {
109
+                        if ($this->shareWithGroupOnly) {
110
+                            /*
111 111
 							 * Check if the user may share with the user associated with the e-mail of the just found contact
112 112
 							 */
113
-							$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
114
-							$found = false;
115
-							foreach ($userGroups as $userGroup) {
116
-								if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
117
-									$found = true;
118
-									break;
119
-								}
120
-							}
121
-							if (!$found) {
122
-								continue;
123
-							}
124
-						}
125
-						if ($exactEmailMatch) {
126
-							try {
127
-								$cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
128
-							} catch (\InvalidArgumentException $e) {
129
-								continue;
130
-							}
131
-
132
-							if (!$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
133
-								$singleResult = [[
134
-									'label' => $displayName,
135
-									'uuid' => $contact['UID'],
136
-									'name' => $contact['FN'],
137
-									'value' => [
138
-										'shareType' => Share::SHARE_TYPE_USER,
139
-										'shareWith' => $cloud->getUser(),
140
-									],
141
-								]];
142
-								$searchResult->addResultSet($userType, [], $singleResult);
143
-								$searchResult->markExactIdMatch($emailType);
144
-							}
145
-							return false;
146
-						}
147
-
148
-						if ($this->shareeEnumeration) {
149
-							try {
150
-								$cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
151
-							} catch (\InvalidArgumentException $e) {
152
-								continue;
153
-							}
154
-
155
-							$addToWide = !$this->shareeEnumerationInGroupOnly;
156
-							if ($this->shareeEnumerationInGroupOnly) {
157
-								$addToWide = false;
158
-								$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
159
-								foreach ($userGroups as $userGroup) {
160
-									if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
161
-										$addToWide = true;
162
-										break;
163
-									}
164
-								}
165
-							}
166
-							if ($addToWide && !$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
167
-								$userResults['wide'][] = [
168
-									'label' => $displayName,
169
-									'uuid' => $contact['UID'],
170
-									'name' => $contact['FN'],
171
-									'value' => [
172
-										'shareType' => Share::SHARE_TYPE_USER,
173
-										'shareWith' => $cloud->getUser(),
174
-									],
175
-								];
176
-								continue;
177
-							}
178
-						}
179
-						continue;
180
-					}
181
-
182
-					if ($exactEmailMatch
183
-						|| isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch)
184
-					{
185
-						if ($exactEmailMatch) {
186
-							$searchResult->markExactIdMatch($emailType);
187
-						}
188
-						$result['exact'][] = [
189
-							'label' => $displayName,
190
-							'uuid' => $contact['UID'],
191
-							'name' => $contact['FN'],
192
-							'type' => $emailAddressType ?? '',
193
-							'value' => [
194
-								'shareType' => Share::SHARE_TYPE_EMAIL,
195
-								'shareWith' => $emailAddress,
196
-							],
197
-						];
198
-					} else {
199
-						$result['wide'][] = [
200
-							'label' => $displayName,
201
-							'uuid' => $contact['UID'],
202
-							'name' => $contact['FN'],
203
-							'type' => $emailAddressType ?? '',
204
-							'value' => [
205
-								'shareType' => Share::SHARE_TYPE_EMAIL,
206
-								'shareWith' => $emailAddress,
207
-							],
208
-						];
209
-					}
210
-				}
211
-			}
212
-		}
213
-
214
-		$reachedEnd = true;
215
-		if (!$this->shareeEnumeration) {
216
-			$result['wide'] = [];
217
-			$userResults['wide'] = [];
218
-		} else {
219
-			$reachedEnd = (count($result['wide']) < $offset + $limit) &&
220
-				(count($userResults['wide']) < $offset + $limit);
221
-
222
-			$result['wide'] = array_slice($result['wide'], $offset, $limit);
223
-			$userResults['wide'] = array_slice($userResults['wide'], $offset, $limit);
224
-		}
225
-
226
-
227
-		if (!$searchResult->hasExactIdMatch($emailType) && filter_var($search, FILTER_VALIDATE_EMAIL)) {
228
-			$result['exact'][] = [
229
-				'label' => $search,
230
-				'uuid' => $search,
231
-				'value' => [
232
-					'shareType' => Share::SHARE_TYPE_EMAIL,
233
-					'shareWith' => $search,
234
-				],
235
-			];
236
-		}
237
-
238
-		if (!empty($userResults['wide'])) {
239
-			$searchResult->addResultSet($userType, $userResults['wide'], []);
240
-		}
241
-		$searchResult->addResultSet($emailType, $result['wide'], $result['exact']);
242
-
243
-		return !$reachedEnd;
244
-	}
245
-
246
-	public function isCurrentUser(ICloudId $cloud): bool {
247
-		$currentUser = $this->userSession->getUser();
248
-		return $currentUser instanceof IUser ? $currentUser->getUID() === $cloud->getUser() : false;
249
-	}
113
+                            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
114
+                            $found = false;
115
+                            foreach ($userGroups as $userGroup) {
116
+                                if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
117
+                                    $found = true;
118
+                                    break;
119
+                                }
120
+                            }
121
+                            if (!$found) {
122
+                                continue;
123
+                            }
124
+                        }
125
+                        if ($exactEmailMatch) {
126
+                            try {
127
+                                $cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
128
+                            } catch (\InvalidArgumentException $e) {
129
+                                continue;
130
+                            }
131
+
132
+                            if (!$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
133
+                                $singleResult = [[
134
+                                    'label' => $displayName,
135
+                                    'uuid' => $contact['UID'],
136
+                                    'name' => $contact['FN'],
137
+                                    'value' => [
138
+                                        'shareType' => Share::SHARE_TYPE_USER,
139
+                                        'shareWith' => $cloud->getUser(),
140
+                                    ],
141
+                                ]];
142
+                                $searchResult->addResultSet($userType, [], $singleResult);
143
+                                $searchResult->markExactIdMatch($emailType);
144
+                            }
145
+                            return false;
146
+                        }
147
+
148
+                        if ($this->shareeEnumeration) {
149
+                            try {
150
+                                $cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
151
+                            } catch (\InvalidArgumentException $e) {
152
+                                continue;
153
+                            }
154
+
155
+                            $addToWide = !$this->shareeEnumerationInGroupOnly;
156
+                            if ($this->shareeEnumerationInGroupOnly) {
157
+                                $addToWide = false;
158
+                                $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
159
+                                foreach ($userGroups as $userGroup) {
160
+                                    if ($this->groupManager->isInGroup($contact['UID'], $userGroup)) {
161
+                                        $addToWide = true;
162
+                                        break;
163
+                                    }
164
+                                }
165
+                            }
166
+                            if ($addToWide && !$this->isCurrentUser($cloud) && !$searchResult->hasResult($userType, $cloud->getUser())) {
167
+                                $userResults['wide'][] = [
168
+                                    'label' => $displayName,
169
+                                    'uuid' => $contact['UID'],
170
+                                    'name' => $contact['FN'],
171
+                                    'value' => [
172
+                                        'shareType' => Share::SHARE_TYPE_USER,
173
+                                        'shareWith' => $cloud->getUser(),
174
+                                    ],
175
+                                ];
176
+                                continue;
177
+                            }
178
+                        }
179
+                        continue;
180
+                    }
181
+
182
+                    if ($exactEmailMatch
183
+                        || isset($contact['FN']) && strtolower($contact['FN']) === $lowerSearch)
184
+                    {
185
+                        if ($exactEmailMatch) {
186
+                            $searchResult->markExactIdMatch($emailType);
187
+                        }
188
+                        $result['exact'][] = [
189
+                            'label' => $displayName,
190
+                            'uuid' => $contact['UID'],
191
+                            'name' => $contact['FN'],
192
+                            'type' => $emailAddressType ?? '',
193
+                            'value' => [
194
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
195
+                                'shareWith' => $emailAddress,
196
+                            ],
197
+                        ];
198
+                    } else {
199
+                        $result['wide'][] = [
200
+                            'label' => $displayName,
201
+                            'uuid' => $contact['UID'],
202
+                            'name' => $contact['FN'],
203
+                            'type' => $emailAddressType ?? '',
204
+                            'value' => [
205
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
206
+                                'shareWith' => $emailAddress,
207
+                            ],
208
+                        ];
209
+                    }
210
+                }
211
+            }
212
+        }
213
+
214
+        $reachedEnd = true;
215
+        if (!$this->shareeEnumeration) {
216
+            $result['wide'] = [];
217
+            $userResults['wide'] = [];
218
+        } else {
219
+            $reachedEnd = (count($result['wide']) < $offset + $limit) &&
220
+                (count($userResults['wide']) < $offset + $limit);
221
+
222
+            $result['wide'] = array_slice($result['wide'], $offset, $limit);
223
+            $userResults['wide'] = array_slice($userResults['wide'], $offset, $limit);
224
+        }
225
+
226
+
227
+        if (!$searchResult->hasExactIdMatch($emailType) && filter_var($search, FILTER_VALIDATE_EMAIL)) {
228
+            $result['exact'][] = [
229
+                'label' => $search,
230
+                'uuid' => $search,
231
+                'value' => [
232
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
233
+                    'shareWith' => $search,
234
+                ],
235
+            ];
236
+        }
237
+
238
+        if (!empty($userResults['wide'])) {
239
+            $searchResult->addResultSet($userType, $userResults['wide'], []);
240
+        }
241
+        $searchResult->addResultSet($emailType, $result['wide'], $result['exact']);
242
+
243
+        return !$reachedEnd;
244
+    }
245
+
246
+    public function isCurrentUser(ICloudId $cloud): bool {
247
+        $currentUser = $this->userSession->getUser();
248
+        return $currentUser instanceof IUser ? $currentUser->getUID() === $cloud->getUser() : false;
249
+    }
250 250
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/Principal.php 2 patches
Indentation   +478 added lines, -478 removed lines patch added patch discarded remove patch
@@ -51,482 +51,482 @@
 block discarded – undo
51 51
 
52 52
 class Principal implements BackendInterface {
53 53
 
54
-	/** @var IUserManager */
55
-	private $userManager;
56
-
57
-	/** @var IGroupManager */
58
-	private $groupManager;
59
-
60
-	/** @var IShareManager */
61
-	private $shareManager;
62
-
63
-	/** @var IUserSession */
64
-	private $userSession;
65
-
66
-	/** @var IAppManager */
67
-	private $appManager;
68
-
69
-	/** @var string */
70
-	private $principalPrefix;
71
-
72
-	/** @var bool */
73
-	private $hasGroups;
74
-
75
-	/** @var bool */
76
-	private $hasCircles;
77
-
78
-	/** @var ProxyMapper */
79
-	private $proxyMapper;
80
-
81
-	/** @var IConfig */
82
-	private $config;
83
-
84
-	/**
85
-	 * Principal constructor.
86
-	 *
87
-	 * @param IUserManager $userManager
88
-	 * @param IGroupManager $groupManager
89
-	 * @param IShareManager $shareManager
90
-	 * @param IUserSession $userSession
91
-	 * @param IAppManager $appManager
92
-	 * @param ProxyMapper $proxyMapper
93
-	 * @param IConfig $config
94
-	 * @param string $principalPrefix
95
-	 */
96
-	public function __construct(IUserManager $userManager,
97
-								IGroupManager $groupManager,
98
-								IShareManager $shareManager,
99
-								IUserSession $userSession,
100
-								IAppManager $appManager,
101
-								ProxyMapper $proxyMapper,
102
-								IConfig $config,
103
-								string $principalPrefix = 'principals/users/') {
104
-		$this->userManager = $userManager;
105
-		$this->groupManager = $groupManager;
106
-		$this->shareManager = $shareManager;
107
-		$this->userSession = $userSession;
108
-		$this->appManager = $appManager;
109
-		$this->principalPrefix = trim($principalPrefix, '/');
110
-		$this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/');
111
-		$this->proxyMapper = $proxyMapper;
112
-		$this->config = $config;
113
-	}
114
-
115
-	use PrincipalProxyTrait {
116
-		getGroupMembership as protected traitGetGroupMembership;
117
-	}
118
-
119
-	/**
120
-	 * Returns a list of principals based on a prefix.
121
-	 *
122
-	 * This prefix will often contain something like 'principals'. You are only
123
-	 * expected to return principals that are in this base path.
124
-	 *
125
-	 * You are expected to return at least a 'uri' for every user, you can
126
-	 * return any additional properties if you wish so. Common properties are:
127
-	 *   {DAV:}displayname
128
-	 *
129
-	 * @param string $prefixPath
130
-	 * @return string[]
131
-	 */
132
-	public function getPrincipalsByPrefix($prefixPath) {
133
-		$principals = [];
134
-
135
-		if ($prefixPath === $this->principalPrefix) {
136
-			foreach($this->userManager->search('') as $user) {
137
-				$principals[] = $this->userToPrincipal($user);
138
-			}
139
-		}
140
-
141
-		return $principals;
142
-	}
143
-
144
-	/**
145
-	 * Returns a specific principal, specified by it's path.
146
-	 * The returned structure should be the exact same as from
147
-	 * getPrincipalsByPrefix.
148
-	 *
149
-	 * @param string $path
150
-	 * @return array
151
-	 */
152
-	public function getPrincipalByPath($path) {
153
-		list($prefix, $name) = \Sabre\Uri\split($path);
154
-
155
-		if ($name === 'calendar-proxy-write' || $name === 'calendar-proxy-read') {
156
-			list($prefix2, $name2) = \Sabre\Uri\split($prefix);
157
-
158
-			if ($prefix2 === $this->principalPrefix) {
159
-				$user = $this->userManager->get($name2);
160
-
161
-				if ($user !== null) {
162
-					return [
163
-						'uri' => 'principals/users/' . $user->getUID() . '/' . $name,
164
-					];
165
-				}
166
-				return null;
167
-			}
168
-		}
169
-
170
-		if ($prefix === $this->principalPrefix) {
171
-			$user = $this->userManager->get($name);
172
-
173
-			if ($user !== null) {
174
-				return $this->userToPrincipal($user);
175
-			}
176
-		} else if ($prefix === 'principals/circles') {
177
-			try {
178
-				return $this->circleToPrincipal($name);
179
-			} catch (QueryException $e) {
180
-				return null;
181
-			}
182
-		}
183
-		return null;
184
-	}
185
-
186
-	/**
187
-	 * Returns the list of groups a principal is a member of
188
-	 *
189
-	 * @param string $principal
190
-	 * @param bool $needGroups
191
-	 * @return array
192
-	 * @throws Exception
193
-	 */
194
-	public function getGroupMembership($principal, $needGroups = false) {
195
-		list($prefix, $name) = \Sabre\Uri\split($principal);
196
-
197
-		if ($prefix !== $this->principalPrefix) {
198
-			return [];
199
-		}
200
-
201
-		$user = $this->userManager->get($name);
202
-		if (!$user) {
203
-			throw new Exception('Principal not found');
204
-		}
205
-
206
-		$groups = [];
207
-
208
-		if ($this->hasGroups || $needGroups) {
209
-			$userGroups = $this->groupManager->getUserGroups($user);
210
-			foreach($userGroups as $userGroup) {
211
-				$groups[] = 'principals/groups/' . urlencode($userGroup->getGID());
212
-			}
213
-		}
214
-
215
-		$groups = array_unique(array_merge(
216
-			$groups,
217
-			$this->traitGetGroupMembership($principal, $needGroups)
218
-		));
219
-
220
-		return $groups;
221
-	}
222
-
223
-	/**
224
-	 * @param string $path
225
-	 * @param PropPatch $propPatch
226
-	 * @return int
227
-	 */
228
-	function updatePrincipal($path, PropPatch $propPatch) {
229
-		return 0;
230
-	}
231
-
232
-	/**
233
-	 * Search user principals
234
-	 *
235
-	 * @param array $searchProperties
236
-	 * @param string $test
237
-	 * @return array
238
-	 */
239
-	protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
240
-		$results = [];
241
-
242
-		// If sharing is disabled, return the empty array
243
-		$shareAPIEnabled = $this->shareManager->shareApiEnabled();
244
-		if (!$shareAPIEnabled) {
245
-			return [];
246
-		}
247
-
248
-		$allowEnumeration = $this->shareManager->allowEnumeration();
249
-		$limitEnumeration = $this->shareManager->limitEnumerationToGroups();
250
-
251
-		// If sharing is restricted to group members only,
252
-		// return only members that have groups in common
253
-		$restrictGroups = false;
254
-		if ($this->shareManager->shareWithGroupMembersOnly()) {
255
-			$user = $this->userSession->getUser();
256
-			if (!$user) {
257
-				return [];
258
-			}
259
-
260
-			$restrictGroups = $this->groupManager->getUserGroupIds($user);
261
-		}
262
-
263
-		$currentUserGroups = [];
264
-		if ($limitEnumeration) {
265
-			$currentUser = $this->userSession->getUser();
266
-			if ($currentUser) {
267
-				$currentUserGroups = $this->groupManager->getUserGroupIds($currentUser);
268
-			}
269
-		}
270
-
271
-		foreach ($searchProperties as $prop => $value) {
272
-			switch ($prop) {
273
-				case '{http://sabredav.org/ns}email-address':
274
-					$users = $this->userManager->getByEmail($value);
275
-
276
-					if (!$allowEnumeration) {
277
-						$users = \array_filter($users, static function(IUser $user) use ($value) {
278
-							return $user->getEMailAddress() === $value;
279
-						});
280
-					}
281
-
282
-					if ($limitEnumeration) {
283
-						$users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
284
-							return !empty(array_intersect(
285
-									$this->groupManager->getUserGroupIds($user),
286
-									$currentUserGroups
287
-								)) || $user->getEMailAddress() === $value;
288
-						});
289
-					}
290
-
291
-					$results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
292
-						// is sharing restricted to groups only?
293
-						if ($restrictGroups !== false) {
294
-							$userGroups = $this->groupManager->getUserGroupIds($user);
295
-							if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
296
-								return $carry;
297
-							}
298
-						}
299
-
300
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
301
-						return $carry;
302
-					}, []);
303
-					break;
304
-
305
-				case '{DAV:}displayname':
306
-					$users = $this->userManager->searchDisplayName($value);
307
-
308
-					if (!$allowEnumeration) {
309
-						$users = \array_filter($users, static function(IUser $user) use ($value) {
310
-							return $user->getDisplayName() === $value;
311
-						});
312
-					}
313
-
314
-					if ($limitEnumeration) {
315
-						$users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
316
-							return !empty(array_intersect(
317
-									$this->groupManager->getUserGroupIds($user),
318
-									$currentUserGroups
319
-								)) || $user->getDisplayName() === $value;
320
-						});
321
-					}
322
-
323
-					$results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
324
-						// is sharing restricted to groups only?
325
-						if ($restrictGroups !== false) {
326
-							$userGroups = $this->groupManager->getUserGroupIds($user);
327
-							if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
328
-								return $carry;
329
-							}
330
-						}
331
-
332
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
333
-						return $carry;
334
-					}, []);
335
-					break;
336
-
337
-				case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
338
-					// If you add support for more search properties that qualify as a user-address,
339
-					// please also add them to the array below
340
-					$results[] = $this->searchUserPrincipals([
341
-						// In theory this should also search for principal:principals/users/...
342
-						// but that's used internally only anyway and i don't know of any client querying that
343
-						'{http://sabredav.org/ns}email-address' => $value,
344
-					], 'anyof');
345
-					break;
346
-
347
-				default:
348
-					$results[] = [];
349
-					break;
350
-			}
351
-		}
352
-
353
-		// results is an array of arrays, so this is not the first search result
354
-		// but the results of the first searchProperty
355
-		if (count($results) === 1) {
356
-			return $results[0];
357
-		}
358
-
359
-		switch ($test) {
360
-			case 'anyof':
361
-				return array_values(array_unique(array_merge(...$results)));
362
-
363
-			case 'allof':
364
-			default:
365
-				return array_values(array_intersect(...$results));
366
-		}
367
-	}
368
-
369
-	/**
370
-	 * @param string $prefixPath
371
-	 * @param array $searchProperties
372
-	 * @param string $test
373
-	 * @return array
374
-	 */
375
-	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
376
-		if (count($searchProperties) === 0) {
377
-			return [];
378
-		}
379
-
380
-		switch ($prefixPath) {
381
-			case 'principals/users':
382
-				return $this->searchUserPrincipals($searchProperties, $test);
383
-
384
-			default:
385
-				return [];
386
-		}
387
-	}
388
-
389
-	/**
390
-	 * @param string $uri
391
-	 * @param string $principalPrefix
392
-	 * @return string
393
-	 */
394
-	function findByUri($uri, $principalPrefix) {
395
-		// If sharing is disabled, return the empty array
396
-		$shareAPIEnabled = $this->shareManager->shareApiEnabled();
397
-		if (!$shareAPIEnabled) {
398
-			return null;
399
-		}
400
-
401
-		// If sharing is restricted to group members only,
402
-		// return only members that have groups in common
403
-		$restrictGroups = false;
404
-		if ($this->shareManager->shareWithGroupMembersOnly()) {
405
-			$user = $this->userSession->getUser();
406
-			if (!$user) {
407
-				return null;
408
-			}
409
-
410
-			$restrictGroups = $this->groupManager->getUserGroupIds($user);
411
-		}
412
-
413
-		if (strpos($uri, 'mailto:') === 0) {
414
-			if ($principalPrefix === 'principals/users') {
415
-				$users = $this->userManager->getByEmail(substr($uri, 7));
416
-				if (count($users) !== 1) {
417
-					return null;
418
-				}
419
-				$user = $users[0];
420
-
421
-				if ($restrictGroups !== false) {
422
-					$userGroups = $this->groupManager->getUserGroupIds($user);
423
-					if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
424
-						return null;
425
-					}
426
-				}
427
-
428
-				return $this->principalPrefix . '/' . $user->getUID();
429
-			}
430
-		}
431
-		if (substr($uri, 0, 10) === 'principal:') {
432
-			$principal = substr($uri, 10);
433
-			$principal = $this->getPrincipalByPath($principal);
434
-			if ($principal !== null) {
435
-				return $principal['uri'];
436
-			}
437
-		}
438
-
439
-		return null;
440
-	}
441
-
442
-	/**
443
-	 * @param IUser $user
444
-	 * @return array
445
-	 */
446
-	protected function userToPrincipal($user) {
447
-		$userId = $user->getUID();
448
-		$displayName = $user->getDisplayName();
449
-		$principal = [
450
-				'uri' => $this->principalPrefix . '/' . $userId,
451
-				'{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
452
-				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
453
-		];
454
-
455
-		$email = $user->getEMailAddress();
456
-		if (!empty($email)) {
457
-			$principal['{http://sabredav.org/ns}email-address'] = $email;
458
-		}
459
-
460
-		return $principal;
461
-	}
462
-
463
-	public function getPrincipalPrefix() {
464
-		return $this->principalPrefix;
465
-	}
466
-
467
-	/**
468
-	 * @param string $circleUniqueId
469
-	 * @return array|null
470
-	 * @throws \OCP\AppFramework\QueryException
471
-	 * @suppress PhanUndeclaredClassMethod
472
-	 * @suppress PhanUndeclaredClassCatch
473
-	 */
474
-	protected function circleToPrincipal($circleUniqueId) {
475
-		if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
476
-			return null;
477
-		}
478
-
479
-		try {
480
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
481
-		} catch(QueryException $ex) {
482
-			return null;
483
-		} catch(CircleDoesNotExistException $ex) {
484
-			return null;
485
-		}
486
-
487
-		if (!$circle) {
488
-			return null;
489
-		}
490
-
491
-		$principal = [
492
-			'uri' => 'principals/circles/' . $circleUniqueId,
493
-			'{DAV:}displayname' => $circle->getName(),
494
-		];
495
-
496
-		return $principal;
497
-	}
498
-
499
-	/**
500
-	 * Returns the list of circles a principal is a member of
501
-	 *
502
-	 * @param string $principal
503
-	 * @return array
504
-	 * @throws Exception
505
-	 * @throws \OCP\AppFramework\QueryException
506
-	 * @suppress PhanUndeclaredClassMethod
507
-	 */
508
-	public function getCircleMembership($principal):array {
509
-		if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
510
-			return [];
511
-		}
512
-
513
-		list($prefix, $name) = \Sabre\Uri\split($principal);
514
-		if ($this->hasCircles && $prefix === $this->principalPrefix) {
515
-			$user = $this->userManager->get($name);
516
-			if (!$user) {
517
-				throw new Exception('Principal not found');
518
-			}
519
-
520
-			$circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
521
-
522
-			$circles = array_map(function($circle) {
523
-				/** @var \OCA\Circles\Model\Circle $circle */
524
-				return 'principals/circles/' . urlencode($circle->getUniqueId());
525
-			}, $circles);
526
-
527
-			return $circles;
528
-		}
529
-
530
-		return [];
531
-	}
54
+    /** @var IUserManager */
55
+    private $userManager;
56
+
57
+    /** @var IGroupManager */
58
+    private $groupManager;
59
+
60
+    /** @var IShareManager */
61
+    private $shareManager;
62
+
63
+    /** @var IUserSession */
64
+    private $userSession;
65
+
66
+    /** @var IAppManager */
67
+    private $appManager;
68
+
69
+    /** @var string */
70
+    private $principalPrefix;
71
+
72
+    /** @var bool */
73
+    private $hasGroups;
74
+
75
+    /** @var bool */
76
+    private $hasCircles;
77
+
78
+    /** @var ProxyMapper */
79
+    private $proxyMapper;
80
+
81
+    /** @var IConfig */
82
+    private $config;
83
+
84
+    /**
85
+     * Principal constructor.
86
+     *
87
+     * @param IUserManager $userManager
88
+     * @param IGroupManager $groupManager
89
+     * @param IShareManager $shareManager
90
+     * @param IUserSession $userSession
91
+     * @param IAppManager $appManager
92
+     * @param ProxyMapper $proxyMapper
93
+     * @param IConfig $config
94
+     * @param string $principalPrefix
95
+     */
96
+    public function __construct(IUserManager $userManager,
97
+                                IGroupManager $groupManager,
98
+                                IShareManager $shareManager,
99
+                                IUserSession $userSession,
100
+                                IAppManager $appManager,
101
+                                ProxyMapper $proxyMapper,
102
+                                IConfig $config,
103
+                                string $principalPrefix = 'principals/users/') {
104
+        $this->userManager = $userManager;
105
+        $this->groupManager = $groupManager;
106
+        $this->shareManager = $shareManager;
107
+        $this->userSession = $userSession;
108
+        $this->appManager = $appManager;
109
+        $this->principalPrefix = trim($principalPrefix, '/');
110
+        $this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/');
111
+        $this->proxyMapper = $proxyMapper;
112
+        $this->config = $config;
113
+    }
114
+
115
+    use PrincipalProxyTrait {
116
+        getGroupMembership as protected traitGetGroupMembership;
117
+    }
118
+
119
+    /**
120
+     * Returns a list of principals based on a prefix.
121
+     *
122
+     * This prefix will often contain something like 'principals'. You are only
123
+     * expected to return principals that are in this base path.
124
+     *
125
+     * You are expected to return at least a 'uri' for every user, you can
126
+     * return any additional properties if you wish so. Common properties are:
127
+     *   {DAV:}displayname
128
+     *
129
+     * @param string $prefixPath
130
+     * @return string[]
131
+     */
132
+    public function getPrincipalsByPrefix($prefixPath) {
133
+        $principals = [];
134
+
135
+        if ($prefixPath === $this->principalPrefix) {
136
+            foreach($this->userManager->search('') as $user) {
137
+                $principals[] = $this->userToPrincipal($user);
138
+            }
139
+        }
140
+
141
+        return $principals;
142
+    }
143
+
144
+    /**
145
+     * Returns a specific principal, specified by it's path.
146
+     * The returned structure should be the exact same as from
147
+     * getPrincipalsByPrefix.
148
+     *
149
+     * @param string $path
150
+     * @return array
151
+     */
152
+    public function getPrincipalByPath($path) {
153
+        list($prefix, $name) = \Sabre\Uri\split($path);
154
+
155
+        if ($name === 'calendar-proxy-write' || $name === 'calendar-proxy-read') {
156
+            list($prefix2, $name2) = \Sabre\Uri\split($prefix);
157
+
158
+            if ($prefix2 === $this->principalPrefix) {
159
+                $user = $this->userManager->get($name2);
160
+
161
+                if ($user !== null) {
162
+                    return [
163
+                        'uri' => 'principals/users/' . $user->getUID() . '/' . $name,
164
+                    ];
165
+                }
166
+                return null;
167
+            }
168
+        }
169
+
170
+        if ($prefix === $this->principalPrefix) {
171
+            $user = $this->userManager->get($name);
172
+
173
+            if ($user !== null) {
174
+                return $this->userToPrincipal($user);
175
+            }
176
+        } else if ($prefix === 'principals/circles') {
177
+            try {
178
+                return $this->circleToPrincipal($name);
179
+            } catch (QueryException $e) {
180
+                return null;
181
+            }
182
+        }
183
+        return null;
184
+    }
185
+
186
+    /**
187
+     * Returns the list of groups a principal is a member of
188
+     *
189
+     * @param string $principal
190
+     * @param bool $needGroups
191
+     * @return array
192
+     * @throws Exception
193
+     */
194
+    public function getGroupMembership($principal, $needGroups = false) {
195
+        list($prefix, $name) = \Sabre\Uri\split($principal);
196
+
197
+        if ($prefix !== $this->principalPrefix) {
198
+            return [];
199
+        }
200
+
201
+        $user = $this->userManager->get($name);
202
+        if (!$user) {
203
+            throw new Exception('Principal not found');
204
+        }
205
+
206
+        $groups = [];
207
+
208
+        if ($this->hasGroups || $needGroups) {
209
+            $userGroups = $this->groupManager->getUserGroups($user);
210
+            foreach($userGroups as $userGroup) {
211
+                $groups[] = 'principals/groups/' . urlencode($userGroup->getGID());
212
+            }
213
+        }
214
+
215
+        $groups = array_unique(array_merge(
216
+            $groups,
217
+            $this->traitGetGroupMembership($principal, $needGroups)
218
+        ));
219
+
220
+        return $groups;
221
+    }
222
+
223
+    /**
224
+     * @param string $path
225
+     * @param PropPatch $propPatch
226
+     * @return int
227
+     */
228
+    function updatePrincipal($path, PropPatch $propPatch) {
229
+        return 0;
230
+    }
231
+
232
+    /**
233
+     * Search user principals
234
+     *
235
+     * @param array $searchProperties
236
+     * @param string $test
237
+     * @return array
238
+     */
239
+    protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
240
+        $results = [];
241
+
242
+        // If sharing is disabled, return the empty array
243
+        $shareAPIEnabled = $this->shareManager->shareApiEnabled();
244
+        if (!$shareAPIEnabled) {
245
+            return [];
246
+        }
247
+
248
+        $allowEnumeration = $this->shareManager->allowEnumeration();
249
+        $limitEnumeration = $this->shareManager->limitEnumerationToGroups();
250
+
251
+        // If sharing is restricted to group members only,
252
+        // return only members that have groups in common
253
+        $restrictGroups = false;
254
+        if ($this->shareManager->shareWithGroupMembersOnly()) {
255
+            $user = $this->userSession->getUser();
256
+            if (!$user) {
257
+                return [];
258
+            }
259
+
260
+            $restrictGroups = $this->groupManager->getUserGroupIds($user);
261
+        }
262
+
263
+        $currentUserGroups = [];
264
+        if ($limitEnumeration) {
265
+            $currentUser = $this->userSession->getUser();
266
+            if ($currentUser) {
267
+                $currentUserGroups = $this->groupManager->getUserGroupIds($currentUser);
268
+            }
269
+        }
270
+
271
+        foreach ($searchProperties as $prop => $value) {
272
+            switch ($prop) {
273
+                case '{http://sabredav.org/ns}email-address':
274
+                    $users = $this->userManager->getByEmail($value);
275
+
276
+                    if (!$allowEnumeration) {
277
+                        $users = \array_filter($users, static function(IUser $user) use ($value) {
278
+                            return $user->getEMailAddress() === $value;
279
+                        });
280
+                    }
281
+
282
+                    if ($limitEnumeration) {
283
+                        $users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
284
+                            return !empty(array_intersect(
285
+                                    $this->groupManager->getUserGroupIds($user),
286
+                                    $currentUserGroups
287
+                                )) || $user->getEMailAddress() === $value;
288
+                        });
289
+                    }
290
+
291
+                    $results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
292
+                        // is sharing restricted to groups only?
293
+                        if ($restrictGroups !== false) {
294
+                            $userGroups = $this->groupManager->getUserGroupIds($user);
295
+                            if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
296
+                                return $carry;
297
+                            }
298
+                        }
299
+
300
+                        $carry[] = $this->principalPrefix . '/' . $user->getUID();
301
+                        return $carry;
302
+                    }, []);
303
+                    break;
304
+
305
+                case '{DAV:}displayname':
306
+                    $users = $this->userManager->searchDisplayName($value);
307
+
308
+                    if (!$allowEnumeration) {
309
+                        $users = \array_filter($users, static function(IUser $user) use ($value) {
310
+                            return $user->getDisplayName() === $value;
311
+                        });
312
+                    }
313
+
314
+                    if ($limitEnumeration) {
315
+                        $users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
316
+                            return !empty(array_intersect(
317
+                                    $this->groupManager->getUserGroupIds($user),
318
+                                    $currentUserGroups
319
+                                )) || $user->getDisplayName() === $value;
320
+                        });
321
+                    }
322
+
323
+                    $results[] = array_reduce($users, function(array $carry, IUser $user) use ($restrictGroups) {
324
+                        // is sharing restricted to groups only?
325
+                        if ($restrictGroups !== false) {
326
+                            $userGroups = $this->groupManager->getUserGroupIds($user);
327
+                            if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
328
+                                return $carry;
329
+                            }
330
+                        }
331
+
332
+                        $carry[] = $this->principalPrefix . '/' . $user->getUID();
333
+                        return $carry;
334
+                    }, []);
335
+                    break;
336
+
337
+                case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
338
+                    // If you add support for more search properties that qualify as a user-address,
339
+                    // please also add them to the array below
340
+                    $results[] = $this->searchUserPrincipals([
341
+                        // In theory this should also search for principal:principals/users/...
342
+                        // but that's used internally only anyway and i don't know of any client querying that
343
+                        '{http://sabredav.org/ns}email-address' => $value,
344
+                    ], 'anyof');
345
+                    break;
346
+
347
+                default:
348
+                    $results[] = [];
349
+                    break;
350
+            }
351
+        }
352
+
353
+        // results is an array of arrays, so this is not the first search result
354
+        // but the results of the first searchProperty
355
+        if (count($results) === 1) {
356
+            return $results[0];
357
+        }
358
+
359
+        switch ($test) {
360
+            case 'anyof':
361
+                return array_values(array_unique(array_merge(...$results)));
362
+
363
+            case 'allof':
364
+            default:
365
+                return array_values(array_intersect(...$results));
366
+        }
367
+    }
368
+
369
+    /**
370
+     * @param string $prefixPath
371
+     * @param array $searchProperties
372
+     * @param string $test
373
+     * @return array
374
+     */
375
+    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
376
+        if (count($searchProperties) === 0) {
377
+            return [];
378
+        }
379
+
380
+        switch ($prefixPath) {
381
+            case 'principals/users':
382
+                return $this->searchUserPrincipals($searchProperties, $test);
383
+
384
+            default:
385
+                return [];
386
+        }
387
+    }
388
+
389
+    /**
390
+     * @param string $uri
391
+     * @param string $principalPrefix
392
+     * @return string
393
+     */
394
+    function findByUri($uri, $principalPrefix) {
395
+        // If sharing is disabled, return the empty array
396
+        $shareAPIEnabled = $this->shareManager->shareApiEnabled();
397
+        if (!$shareAPIEnabled) {
398
+            return null;
399
+        }
400
+
401
+        // If sharing is restricted to group members only,
402
+        // return only members that have groups in common
403
+        $restrictGroups = false;
404
+        if ($this->shareManager->shareWithGroupMembersOnly()) {
405
+            $user = $this->userSession->getUser();
406
+            if (!$user) {
407
+                return null;
408
+            }
409
+
410
+            $restrictGroups = $this->groupManager->getUserGroupIds($user);
411
+        }
412
+
413
+        if (strpos($uri, 'mailto:') === 0) {
414
+            if ($principalPrefix === 'principals/users') {
415
+                $users = $this->userManager->getByEmail(substr($uri, 7));
416
+                if (count($users) !== 1) {
417
+                    return null;
418
+                }
419
+                $user = $users[0];
420
+
421
+                if ($restrictGroups !== false) {
422
+                    $userGroups = $this->groupManager->getUserGroupIds($user);
423
+                    if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
424
+                        return null;
425
+                    }
426
+                }
427
+
428
+                return $this->principalPrefix . '/' . $user->getUID();
429
+            }
430
+        }
431
+        if (substr($uri, 0, 10) === 'principal:') {
432
+            $principal = substr($uri, 10);
433
+            $principal = $this->getPrincipalByPath($principal);
434
+            if ($principal !== null) {
435
+                return $principal['uri'];
436
+            }
437
+        }
438
+
439
+        return null;
440
+    }
441
+
442
+    /**
443
+     * @param IUser $user
444
+     * @return array
445
+     */
446
+    protected function userToPrincipal($user) {
447
+        $userId = $user->getUID();
448
+        $displayName = $user->getDisplayName();
449
+        $principal = [
450
+                'uri' => $this->principalPrefix . '/' . $userId,
451
+                '{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
452
+                '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
453
+        ];
454
+
455
+        $email = $user->getEMailAddress();
456
+        if (!empty($email)) {
457
+            $principal['{http://sabredav.org/ns}email-address'] = $email;
458
+        }
459
+
460
+        return $principal;
461
+    }
462
+
463
+    public function getPrincipalPrefix() {
464
+        return $this->principalPrefix;
465
+    }
466
+
467
+    /**
468
+     * @param string $circleUniqueId
469
+     * @return array|null
470
+     * @throws \OCP\AppFramework\QueryException
471
+     * @suppress PhanUndeclaredClassMethod
472
+     * @suppress PhanUndeclaredClassCatch
473
+     */
474
+    protected function circleToPrincipal($circleUniqueId) {
475
+        if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
476
+            return null;
477
+        }
478
+
479
+        try {
480
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
481
+        } catch(QueryException $ex) {
482
+            return null;
483
+        } catch(CircleDoesNotExistException $ex) {
484
+            return null;
485
+        }
486
+
487
+        if (!$circle) {
488
+            return null;
489
+        }
490
+
491
+        $principal = [
492
+            'uri' => 'principals/circles/' . $circleUniqueId,
493
+            '{DAV:}displayname' => $circle->getName(),
494
+        ];
495
+
496
+        return $principal;
497
+    }
498
+
499
+    /**
500
+     * Returns the list of circles a principal is a member of
501
+     *
502
+     * @param string $principal
503
+     * @return array
504
+     * @throws Exception
505
+     * @throws \OCP\AppFramework\QueryException
506
+     * @suppress PhanUndeclaredClassMethod
507
+     */
508
+    public function getCircleMembership($principal):array {
509
+        if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
510
+            return [];
511
+        }
512
+
513
+        list($prefix, $name) = \Sabre\Uri\split($principal);
514
+        if ($this->hasCircles && $prefix === $this->principalPrefix) {
515
+            $user = $this->userManager->get($name);
516
+            if (!$user) {
517
+                throw new Exception('Principal not found');
518
+            }
519
+
520
+            $circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
521
+
522
+            $circles = array_map(function($circle) {
523
+                /** @var \OCA\Circles\Model\Circle $circle */
524
+                return 'principals/circles/' . urlencode($circle->getUniqueId());
525
+            }, $circles);
526
+
527
+            return $circles;
528
+        }
529
+
530
+        return [];
531
+    }
532 532
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		$principals = [];
134 134
 
135 135
 		if ($prefixPath === $this->principalPrefix) {
136
-			foreach($this->userManager->search('') as $user) {
136
+			foreach ($this->userManager->search('') as $user) {
137 137
 				$principals[] = $this->userToPrincipal($user);
138 138
 			}
139 139
 		}
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 
161 161
 				if ($user !== null) {
162 162
 					return [
163
-						'uri' => 'principals/users/' . $user->getUID() . '/' . $name,
163
+						'uri' => 'principals/users/'.$user->getUID().'/'.$name,
164 164
 					];
165 165
 				}
166 166
 				return null;
@@ -207,8 +207,8 @@  discard block
 block discarded – undo
207 207
 
208 208
 		if ($this->hasGroups || $needGroups) {
209 209
 			$userGroups = $this->groupManager->getUserGroups($user);
210
-			foreach($userGroups as $userGroup) {
211
-				$groups[] = 'principals/groups/' . urlencode($userGroup->getGID());
210
+			foreach ($userGroups as $userGroup) {
211
+				$groups[] = 'principals/groups/'.urlencode($userGroup->getGID());
212 212
 			}
213 213
 		}
214 214
 
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 					}
281 281
 
282 282
 					if ($limitEnumeration) {
283
-						$users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
283
+						$users = \array_filter($users, function(IUser $user) use ($currentUserGroups, $value) {
284 284
 							return !empty(array_intersect(
285 285
 									$this->groupManager->getUserGroupIds($user),
286 286
 									$currentUserGroups
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 							}
298 298
 						}
299 299
 
300
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
300
+						$carry[] = $this->principalPrefix.'/'.$user->getUID();
301 301
 						return $carry;
302 302
 					}, []);
303 303
 					break;
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 					}
313 313
 
314 314
 					if ($limitEnumeration) {
315
-						$users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
315
+						$users = \array_filter($users, function(IUser $user) use ($currentUserGroups, $value) {
316 316
 							return !empty(array_intersect(
317 317
 									$this->groupManager->getUserGroupIds($user),
318 318
 									$currentUserGroups
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 							}
330 330
 						}
331 331
 
332
-						$carry[] = $this->principalPrefix . '/' . $user->getUID();
332
+						$carry[] = $this->principalPrefix.'/'.$user->getUID();
333 333
 						return $carry;
334 334
 					}, []);
335 335
 					break;
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 					}
426 426
 				}
427 427
 
428
-				return $this->principalPrefix . '/' . $user->getUID();
428
+				return $this->principalPrefix.'/'.$user->getUID();
429 429
 			}
430 430
 		}
431 431
 		if (substr($uri, 0, 10) === 'principal:') {
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 		$userId = $user->getUID();
448 448
 		$displayName = $user->getDisplayName();
449 449
 		$principal = [
450
-				'uri' => $this->principalPrefix . '/' . $userId,
450
+				'uri' => $this->principalPrefix.'/'.$userId,
451 451
 				'{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
452 452
 				'{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
453 453
 		];
@@ -478,9 +478,9 @@  discard block
 block discarded – undo
478 478
 
479 479
 		try {
480 480
 			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
481
-		} catch(QueryException $ex) {
481
+		} catch (QueryException $ex) {
482 482
 			return null;
483
-		} catch(CircleDoesNotExistException $ex) {
483
+		} catch (CircleDoesNotExistException $ex) {
484 484
 			return null;
485 485
 		}
486 486
 
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
 		}
490 490
 
491 491
 		$principal = [
492
-			'uri' => 'principals/circles/' . $circleUniqueId,
492
+			'uri' => 'principals/circles/'.$circleUniqueId,
493 493
 			'{DAV:}displayname' => $circle->getName(),
494 494
 		];
495 495
 
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 
522 522
 			$circles = array_map(function($circle) {
523 523
 				/** @var \OCA\Circles\Model\Circle $circle */
524
-				return 'principals/circles/' . urlencode($circle->getUniqueId());
524
+				return 'principals/circles/'.urlencode($circle->getUniqueId());
525 525
 			}, $circles);
526 526
 
527 527
 			return $circles;
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/SystemAddressbook.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -31,21 +31,21 @@
 block discarded – undo
31 31
 use Sabre\CardDAV\Backend\BackendInterface;
32 32
 
33 33
 class SystemAddressbook extends AddressBook {
34
-	/** @var IConfig */
35
-	private $config;
36
-
37
-	public function __construct(BackendInterface $carddavBackend, array $addressBookInfo, IL10N $l10n, IConfig $config) {
38
-		parent::__construct($carddavBackend, $addressBookInfo, $l10n);
39
-		$this->config = $config;
40
-	}
41
-
42
-	public function getChildren() {
43
-		$shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
44
-		$restrictShareEnumeration = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'yes') === 'yes';
45
-		if (!$shareEnumeration || ($shareEnumeration && $restrictShareEnumeration)) {
46
-			return [];
47
-		}
48
-
49
-		return parent::getChildren();
50
-	}
34
+    /** @var IConfig */
35
+    private $config;
36
+
37
+    public function __construct(BackendInterface $carddavBackend, array $addressBookInfo, IL10N $l10n, IConfig $config) {
38
+        parent::__construct($carddavBackend, $addressBookInfo, $l10n);
39
+        $this->config = $config;
40
+    }
41
+
42
+    public function getChildren() {
43
+        $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
44
+        $restrictShareEnumeration = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'yes') === 'yes';
45
+        if (!$shareEnumeration || ($shareEnumeration && $restrictShareEnumeration)) {
46
+            return [];
47
+        }
48
+
49
+        return parent::getChildren();
50
+    }
51 51
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 1 patch
Indentation   +369 added lines, -369 removed lines patch added patch discarded remove patch
@@ -54,373 +54,373 @@
 block discarded – undo
54 54
 
55 55
 class ShareesAPIController extends OCSController {
56 56
 
57
-	/** @var userId */
58
-	protected $userId;
59
-
60
-	/** @var IConfig */
61
-	protected $config;
62
-
63
-	/** @var IURLGenerator */
64
-	protected $urlGenerator;
65
-
66
-	/** @var IManager */
67
-	protected $shareManager;
68
-
69
-	/** @var int */
70
-	protected $offset = 0;
71
-
72
-	/** @var int */
73
-	protected $limit = 10;
74
-
75
-	/** @var array */
76
-	protected $result = [
77
-		'exact' => [
78
-			'users' => [],
79
-			'groups' => [],
80
-			'remotes' => [],
81
-			'remote_groups' => [],
82
-			'emails' => [],
83
-			'circles' => [],
84
-			'rooms' => [],
85
-		],
86
-		'users' => [],
87
-		'groups' => [],
88
-		'remotes' => [],
89
-		'remote_groups' => [],
90
-		'emails' => [],
91
-		'lookup' => [],
92
-		'circles' => [],
93
-		'rooms' => [],
94
-		'lookupEnabled' => false,
95
-	];
96
-
97
-	protected $reachedEndFor = [];
98
-	/** @var ISearch */
99
-	private $collaboratorSearch;
100
-
101
-	/**
102
-	 * @param string $UserId
103
-	 * @param string $appName
104
-	 * @param IRequest $request
105
-	 * @param IConfig $config
106
-	 * @param IURLGenerator $urlGenerator
107
-	 * @param IManager $shareManager
108
-	 * @param ISearch $collaboratorSearch
109
-	 */
110
-	public function __construct(
111
-		$UserId,
112
-		string $appName,
113
-		IRequest $request,
114
-		IConfig $config,
115
-		IURLGenerator $urlGenerator,
116
-		IManager $shareManager,
117
-		ISearch $collaboratorSearch
118
-	) {
119
-		parent::__construct($appName, $request);
120
-		$this->userId = $UserId;
121
-		$this->config = $config;
122
-		$this->urlGenerator = $urlGenerator;
123
-		$this->shareManager = $shareManager;
124
-		$this->collaboratorSearch = $collaboratorSearch;
125
-	}
126
-
127
-	/**
128
-	 * @NoAdminRequired
129
-	 *
130
-	 * @param string $search
131
-	 * @param string $itemType
132
-	 * @param int $page
133
-	 * @param int $perPage
134
-	 * @param int|int[] $shareType
135
-	 * @param bool $lookup
136
-	 * @return DataResponse
137
-	 * @throws OCSBadRequestException
138
-	 */
139
-	public function search(string $search = '', string $itemType = null, int $page = 1, int $perPage = 200, $shareType = null, bool $lookup = true): DataResponse {
140
-
141
-		// only search for string larger than a given threshold
142
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
143
-		if (strlen($search) < $threshold) {
144
-			return new DataResponse($this->result);
145
-		}
146
-
147
-		// never return more than the max. number of results configured in the config.php
148
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
149
-		if ($maxResults > 0) {
150
-			$perPage = min($perPage, $maxResults);
151
-		}
152
-		if ($perPage <= 0) {
153
-			throw new OCSBadRequestException('Invalid perPage argument');
154
-		}
155
-		if ($page <= 0) {
156
-			throw new OCSBadRequestException('Invalid page');
157
-		}
158
-
159
-		$shareTypes = [
160
-			Share::SHARE_TYPE_USER,
161
-		];
162
-
163
-		if ($itemType === null) {
164
-			throw new OCSBadRequestException('Missing itemType');
165
-		} elseif ($itemType === 'file' || $itemType === 'folder') {
166
-			if ($this->shareManager->allowGroupSharing()) {
167
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
168
-			}
169
-
170
-			if ($this->isRemoteSharingAllowed($itemType)) {
171
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
172
-			}
173
-
174
-			if ($this->isRemoteGroupSharingAllowed($itemType)) {
175
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE_GROUP;
176
-			}
177
-
178
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
179
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
180
-			}
181
-
182
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_ROOM)) {
183
-				$shareTypes[] = Share::SHARE_TYPE_ROOM;
184
-			}
185
-		} else {
186
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
187
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
188
-		}
189
-
190
-		// FIXME: DI
191
-		if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
192
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
193
-		}
194
-
195
-		if ($shareType !== null && is_array($shareType)) {
196
-			$shareTypes = array_intersect($shareTypes, $shareType);
197
-		} else if (is_numeric($shareType)) {
198
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
199
-		}
200
-		sort($shareTypes);
201
-
202
-		$this->limit = (int) $perPage;
203
-		$this->offset = $perPage * ($page - 1);
204
-
205
-		// In global scale mode we always search the loogup server
206
-		if ($this->config->getSystemValueBool('gs.enabled', false)) {
207
-			$lookup = true;
208
-			$this->result['lookupEnabled'] = true;
209
-		} else {
210
-			$this->result['lookupEnabled'] = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes') === 'yes';
211
-		}
212
-
213
-		list($result, $hasMoreResults) = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset);
214
-
215
-		// extra treatment for 'exact' subarray, with a single merge expected keys might be lost
216
-		if(isset($result['exact'])) {
217
-			$result['exact'] = array_merge($this->result['exact'], $result['exact']);
218
-		}
219
-		$this->result = array_merge($this->result, $result);
220
-		$response = new DataResponse($this->result);
221
-
222
-		if ($hasMoreResults) {
223
-			$response->addHeader('Link', $this->getPaginationLink($page, [
224
-				'search' => $search,
225
-				'itemType' => $itemType,
226
-				'shareType' => $shareTypes,
227
-				'perPage' => $perPage,
228
-			]));
229
-		}
230
-
231
-		return $response;
232
-	}
233
-
234
-	/**
235
-	 * @param string $user
236
-	 * @param int $shareType
237
-	 *
238
-	 * @return Generator<array<string>>
239
-	 */
240
-	private function getAllShareesByType(string $user, int $shareType): Generator {
241
-		$offset = 0;
242
-		$pageSize = 50;
243
-
244
-		while (count($page = $this->shareManager->getSharesBy(
245
-			$user,
246
-			$shareType,
247
-			null,
248
-			false,
249
-			$pageSize,
250
-			$offset
251
-		))) {
252
-			foreach ($page as $share) {
253
-				yield [$share->getSharedWith(), $share->getSharedWithDisplayName() ?? $share->getSharedWith()];
254
-			}
255
-
256
-			$offset += $pageSize;
257
-		}
258
-	}
259
-
260
-	private function sortShareesByFrequency(array $sharees): array {
261
-		usort($sharees, function(array $s1, array $s2) {
262
-			return $s2['count'] - $s1['count'];
263
-		});
264
-		return $sharees;
265
-	}
266
-
267
-	private $searchResultTypeMap = [
268
-		Share::SHARE_TYPE_USER => 'users',
269
-		Share::SHARE_TYPE_GROUP => 'groups',
270
-		Share::SHARE_TYPE_REMOTE => 'remotes',
271
-		Share::SHARE_TYPE_REMOTE_GROUP => 'remote_groups',
272
-		Share::SHARE_TYPE_EMAIL => 'emails',
273
-	];
274
-
275
-	private function getAllSharees(string $user, array $shareTypes): ISearchResult {
276
-		$result = [];
277
-		foreach ($shareTypes as $shareType) {
278
-			$sharees = $this->getAllShareesByType($user, $shareType);
279
-			$shareTypeResults = [];
280
-			foreach ($sharees as list($sharee, $displayname)) {
281
-				if (!isset($this->searchResultTypeMap[$shareType])) {
282
-					continue;
283
-				}
284
-
285
-				if (!isset($shareTypeResults[$sharee])) {
286
-					$shareTypeResults[$sharee] = [
287
-						'count' => 1,
288
-						'label' => $displayname,
289
-						'value' => [
290
-							'shareType' => $shareType,
291
-							'shareWith' => $sharee,
292
-						],
293
-					];
294
-				} else {
295
-					$shareTypeResults[$sharee]['count']++;
296
-				}
297
-			}
298
-			$result = array_merge($result, array_values($shareTypeResults));
299
-		}
300
-
301
-		$top5 = array_slice(
302
-			$this->sortShareesByFrequency($result),
303
-			0,
304
-			5
305
-		);
306
-
307
-		$searchResult = new SearchResult();
308
-		foreach ($this->searchResultTypeMap as $int => $str) {
309
-			$searchResult->addResultSet(new SearchResultType($str), [], []);
310
-			foreach ($top5 as $x) {
311
-				if ($x['value']['shareType'] === $int) {
312
-					$searchResult->addResultSet(new SearchResultType($str), [], [$x]);
313
-				}
314
-			}
315
-		}
316
-		return $searchResult;
317
-	}
318
-
319
-	/**
320
-	 * @NoAdminRequired
321
-	 *
322
-	 * @param string $itemType
323
-	 * @return DataResponse
324
-	 * @throws OCSBadRequestException
325
-	 */
326
-	public function findRecommended(string $itemType = null, $shareType = null): DataResponse {
327
-		$shareTypes = [
328
-			Share::SHARE_TYPE_USER,
329
-		];
330
-
331
-		if ($itemType === null) {
332
-			throw new OCSBadRequestException('Missing itemType');
333
-		} elseif ($itemType === 'file' || $itemType === 'folder') {
334
-			if ($this->shareManager->allowGroupSharing()) {
335
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
336
-			}
337
-
338
-			if ($this->isRemoteSharingAllowed($itemType)) {
339
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
340
-			}
341
-
342
-			if ($this->isRemoteGroupSharingAllowed($itemType)) {
343
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE_GROUP;
344
-			}
345
-
346
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
347
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
348
-			}
349
-
350
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_ROOM)) {
351
-				$shareTypes[] = Share::SHARE_TYPE_ROOM;
352
-			}
353
-		} else {
354
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
355
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
356
-		}
357
-
358
-		// FIXME: DI
359
-		if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
360
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
361
-		}
362
-
363
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
364
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
365
-			sort($shareTypes);
366
-		} else if (is_numeric($shareType)) {
367
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
368
-			sort($shareTypes);
369
-		}
370
-
371
-		return new DataResponse(
372
-			$this->getAllSharees($this->userId, $shareTypes)->asArray()
373
-		);
374
-	}
375
-
376
-	/**
377
-	 * Method to get out the static call for better testing
378
-	 *
379
-	 * @param string $itemType
380
-	 * @return bool
381
-	 */
382
-	protected function isRemoteSharingAllowed(string $itemType): bool {
383
-		try {
384
-			// FIXME: static foo makes unit testing unnecessarily difficult
385
-			$backend = \OC\Share\Share::getBackend($itemType);
386
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
387
-		} catch (\Exception $e) {
388
-			return false;
389
-		}
390
-	}
391
-
392
-	protected function isRemoteGroupSharingAllowed(string $itemType): bool {
393
-		try {
394
-			// FIXME: static foo makes unit testing unnecessarily difficult
395
-			$backend = \OC\Share\Share::getBackend($itemType);
396
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE_GROUP);
397
-		} catch (\Exception $e) {
398
-			return false;
399
-		}
400
-	}
401
-
402
-
403
-	/**
404
-	 * Generates a bunch of pagination links for the current page
405
-	 *
406
-	 * @param int $page Current page
407
-	 * @param array $params Parameters for the URL
408
-	 * @return string
409
-	 */
410
-	protected function getPaginationLink(int $page, array $params): string {
411
-		if ($this->isV2()) {
412
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
413
-		} else {
414
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
415
-		}
416
-		$params['page'] = $page + 1;
417
-		return '<' . $url . http_build_query($params) . '>; rel="next"';
418
-	}
419
-
420
-	/**
421
-	 * @return bool
422
-	 */
423
-	protected function isV2(): bool {
424
-		return $this->request->getScriptName() === '/ocs/v2.php';
425
-	}
57
+    /** @var userId */
58
+    protected $userId;
59
+
60
+    /** @var IConfig */
61
+    protected $config;
62
+
63
+    /** @var IURLGenerator */
64
+    protected $urlGenerator;
65
+
66
+    /** @var IManager */
67
+    protected $shareManager;
68
+
69
+    /** @var int */
70
+    protected $offset = 0;
71
+
72
+    /** @var int */
73
+    protected $limit = 10;
74
+
75
+    /** @var array */
76
+    protected $result = [
77
+        'exact' => [
78
+            'users' => [],
79
+            'groups' => [],
80
+            'remotes' => [],
81
+            'remote_groups' => [],
82
+            'emails' => [],
83
+            'circles' => [],
84
+            'rooms' => [],
85
+        ],
86
+        'users' => [],
87
+        'groups' => [],
88
+        'remotes' => [],
89
+        'remote_groups' => [],
90
+        'emails' => [],
91
+        'lookup' => [],
92
+        'circles' => [],
93
+        'rooms' => [],
94
+        'lookupEnabled' => false,
95
+    ];
96
+
97
+    protected $reachedEndFor = [];
98
+    /** @var ISearch */
99
+    private $collaboratorSearch;
100
+
101
+    /**
102
+     * @param string $UserId
103
+     * @param string $appName
104
+     * @param IRequest $request
105
+     * @param IConfig $config
106
+     * @param IURLGenerator $urlGenerator
107
+     * @param IManager $shareManager
108
+     * @param ISearch $collaboratorSearch
109
+     */
110
+    public function __construct(
111
+        $UserId,
112
+        string $appName,
113
+        IRequest $request,
114
+        IConfig $config,
115
+        IURLGenerator $urlGenerator,
116
+        IManager $shareManager,
117
+        ISearch $collaboratorSearch
118
+    ) {
119
+        parent::__construct($appName, $request);
120
+        $this->userId = $UserId;
121
+        $this->config = $config;
122
+        $this->urlGenerator = $urlGenerator;
123
+        $this->shareManager = $shareManager;
124
+        $this->collaboratorSearch = $collaboratorSearch;
125
+    }
126
+
127
+    /**
128
+     * @NoAdminRequired
129
+     *
130
+     * @param string $search
131
+     * @param string $itemType
132
+     * @param int $page
133
+     * @param int $perPage
134
+     * @param int|int[] $shareType
135
+     * @param bool $lookup
136
+     * @return DataResponse
137
+     * @throws OCSBadRequestException
138
+     */
139
+    public function search(string $search = '', string $itemType = null, int $page = 1, int $perPage = 200, $shareType = null, bool $lookup = true): DataResponse {
140
+
141
+        // only search for string larger than a given threshold
142
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
143
+        if (strlen($search) < $threshold) {
144
+            return new DataResponse($this->result);
145
+        }
146
+
147
+        // never return more than the max. number of results configured in the config.php
148
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
149
+        if ($maxResults > 0) {
150
+            $perPage = min($perPage, $maxResults);
151
+        }
152
+        if ($perPage <= 0) {
153
+            throw new OCSBadRequestException('Invalid perPage argument');
154
+        }
155
+        if ($page <= 0) {
156
+            throw new OCSBadRequestException('Invalid page');
157
+        }
158
+
159
+        $shareTypes = [
160
+            Share::SHARE_TYPE_USER,
161
+        ];
162
+
163
+        if ($itemType === null) {
164
+            throw new OCSBadRequestException('Missing itemType');
165
+        } elseif ($itemType === 'file' || $itemType === 'folder') {
166
+            if ($this->shareManager->allowGroupSharing()) {
167
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
168
+            }
169
+
170
+            if ($this->isRemoteSharingAllowed($itemType)) {
171
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
172
+            }
173
+
174
+            if ($this->isRemoteGroupSharingAllowed($itemType)) {
175
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE_GROUP;
176
+            }
177
+
178
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
179
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
180
+            }
181
+
182
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_ROOM)) {
183
+                $shareTypes[] = Share::SHARE_TYPE_ROOM;
184
+            }
185
+        } else {
186
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
187
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
188
+        }
189
+
190
+        // FIXME: DI
191
+        if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
192
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
193
+        }
194
+
195
+        if ($shareType !== null && is_array($shareType)) {
196
+            $shareTypes = array_intersect($shareTypes, $shareType);
197
+        } else if (is_numeric($shareType)) {
198
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
199
+        }
200
+        sort($shareTypes);
201
+
202
+        $this->limit = (int) $perPage;
203
+        $this->offset = $perPage * ($page - 1);
204
+
205
+        // In global scale mode we always search the loogup server
206
+        if ($this->config->getSystemValueBool('gs.enabled', false)) {
207
+            $lookup = true;
208
+            $this->result['lookupEnabled'] = true;
209
+        } else {
210
+            $this->result['lookupEnabled'] = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes') === 'yes';
211
+        }
212
+
213
+        list($result, $hasMoreResults) = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset);
214
+
215
+        // extra treatment for 'exact' subarray, with a single merge expected keys might be lost
216
+        if(isset($result['exact'])) {
217
+            $result['exact'] = array_merge($this->result['exact'], $result['exact']);
218
+        }
219
+        $this->result = array_merge($this->result, $result);
220
+        $response = new DataResponse($this->result);
221
+
222
+        if ($hasMoreResults) {
223
+            $response->addHeader('Link', $this->getPaginationLink($page, [
224
+                'search' => $search,
225
+                'itemType' => $itemType,
226
+                'shareType' => $shareTypes,
227
+                'perPage' => $perPage,
228
+            ]));
229
+        }
230
+
231
+        return $response;
232
+    }
233
+
234
+    /**
235
+     * @param string $user
236
+     * @param int $shareType
237
+     *
238
+     * @return Generator<array<string>>
239
+     */
240
+    private function getAllShareesByType(string $user, int $shareType): Generator {
241
+        $offset = 0;
242
+        $pageSize = 50;
243
+
244
+        while (count($page = $this->shareManager->getSharesBy(
245
+            $user,
246
+            $shareType,
247
+            null,
248
+            false,
249
+            $pageSize,
250
+            $offset
251
+        ))) {
252
+            foreach ($page as $share) {
253
+                yield [$share->getSharedWith(), $share->getSharedWithDisplayName() ?? $share->getSharedWith()];
254
+            }
255
+
256
+            $offset += $pageSize;
257
+        }
258
+    }
259
+
260
+    private function sortShareesByFrequency(array $sharees): array {
261
+        usort($sharees, function(array $s1, array $s2) {
262
+            return $s2['count'] - $s1['count'];
263
+        });
264
+        return $sharees;
265
+    }
266
+
267
+    private $searchResultTypeMap = [
268
+        Share::SHARE_TYPE_USER => 'users',
269
+        Share::SHARE_TYPE_GROUP => 'groups',
270
+        Share::SHARE_TYPE_REMOTE => 'remotes',
271
+        Share::SHARE_TYPE_REMOTE_GROUP => 'remote_groups',
272
+        Share::SHARE_TYPE_EMAIL => 'emails',
273
+    ];
274
+
275
+    private function getAllSharees(string $user, array $shareTypes): ISearchResult {
276
+        $result = [];
277
+        foreach ($shareTypes as $shareType) {
278
+            $sharees = $this->getAllShareesByType($user, $shareType);
279
+            $shareTypeResults = [];
280
+            foreach ($sharees as list($sharee, $displayname)) {
281
+                if (!isset($this->searchResultTypeMap[$shareType])) {
282
+                    continue;
283
+                }
284
+
285
+                if (!isset($shareTypeResults[$sharee])) {
286
+                    $shareTypeResults[$sharee] = [
287
+                        'count' => 1,
288
+                        'label' => $displayname,
289
+                        'value' => [
290
+                            'shareType' => $shareType,
291
+                            'shareWith' => $sharee,
292
+                        ],
293
+                    ];
294
+                } else {
295
+                    $shareTypeResults[$sharee]['count']++;
296
+                }
297
+            }
298
+            $result = array_merge($result, array_values($shareTypeResults));
299
+        }
300
+
301
+        $top5 = array_slice(
302
+            $this->sortShareesByFrequency($result),
303
+            0,
304
+            5
305
+        );
306
+
307
+        $searchResult = new SearchResult();
308
+        foreach ($this->searchResultTypeMap as $int => $str) {
309
+            $searchResult->addResultSet(new SearchResultType($str), [], []);
310
+            foreach ($top5 as $x) {
311
+                if ($x['value']['shareType'] === $int) {
312
+                    $searchResult->addResultSet(new SearchResultType($str), [], [$x]);
313
+                }
314
+            }
315
+        }
316
+        return $searchResult;
317
+    }
318
+
319
+    /**
320
+     * @NoAdminRequired
321
+     *
322
+     * @param string $itemType
323
+     * @return DataResponse
324
+     * @throws OCSBadRequestException
325
+     */
326
+    public function findRecommended(string $itemType = null, $shareType = null): DataResponse {
327
+        $shareTypes = [
328
+            Share::SHARE_TYPE_USER,
329
+        ];
330
+
331
+        if ($itemType === null) {
332
+            throw new OCSBadRequestException('Missing itemType');
333
+        } elseif ($itemType === 'file' || $itemType === 'folder') {
334
+            if ($this->shareManager->allowGroupSharing()) {
335
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
336
+            }
337
+
338
+            if ($this->isRemoteSharingAllowed($itemType)) {
339
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
340
+            }
341
+
342
+            if ($this->isRemoteGroupSharingAllowed($itemType)) {
343
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE_GROUP;
344
+            }
345
+
346
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
347
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
348
+            }
349
+
350
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_ROOM)) {
351
+                $shareTypes[] = Share::SHARE_TYPE_ROOM;
352
+            }
353
+        } else {
354
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
355
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
356
+        }
357
+
358
+        // FIXME: DI
359
+        if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
360
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
361
+        }
362
+
363
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
364
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
365
+            sort($shareTypes);
366
+        } else if (is_numeric($shareType)) {
367
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
368
+            sort($shareTypes);
369
+        }
370
+
371
+        return new DataResponse(
372
+            $this->getAllSharees($this->userId, $shareTypes)->asArray()
373
+        );
374
+    }
375
+
376
+    /**
377
+     * Method to get out the static call for better testing
378
+     *
379
+     * @param string $itemType
380
+     * @return bool
381
+     */
382
+    protected function isRemoteSharingAllowed(string $itemType): bool {
383
+        try {
384
+            // FIXME: static foo makes unit testing unnecessarily difficult
385
+            $backend = \OC\Share\Share::getBackend($itemType);
386
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
387
+        } catch (\Exception $e) {
388
+            return false;
389
+        }
390
+    }
391
+
392
+    protected function isRemoteGroupSharingAllowed(string $itemType): bool {
393
+        try {
394
+            // FIXME: static foo makes unit testing unnecessarily difficult
395
+            $backend = \OC\Share\Share::getBackend($itemType);
396
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE_GROUP);
397
+        } catch (\Exception $e) {
398
+            return false;
399
+        }
400
+    }
401
+
402
+
403
+    /**
404
+     * Generates a bunch of pagination links for the current page
405
+     *
406
+     * @param int $page Current page
407
+     * @param array $params Parameters for the URL
408
+     * @return string
409
+     */
410
+    protected function getPaginationLink(int $page, array $params): string {
411
+        if ($this->isV2()) {
412
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
413
+        } else {
414
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
415
+        }
416
+        $params['page'] = $page + 1;
417
+        return '<' . $url . http_build_query($params) . '>; rel="next"';
418
+    }
419
+
420
+    /**
421
+     * @return bool
422
+     */
423
+    protected function isV2(): bool {
424
+        return $this->request->getScriptName() === '/ocs/v2.php';
425
+    }
426 426
 }
Please login to merge, or discard this patch.