Completed
Pull Request — master (#6322)
by Morris
26:35 queued 12:06
created
apps/files_sharing/appinfo/routes.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -27,107 +27,107 @@
 block discarded – undo
27 27
  */
28 28
 
29 29
 return [
30
-	'resources' => [
31
-		'ExternalShares' => ['url' => '/api/externalShares'],
32
-	],
33
-	'routes' => [
34
-		[
35
-			'name' => 'externalShares#testRemote',
36
-			'url' => '/testremote',
37
-			'verb' => 'GET'
38
-		],
39
-		[
40
-			'name' => 'PublicPreview#getPreview',
41
-			'url' => '/publicpreview',
42
-			'verb' => 'GET',
43
-		],
30
+    'resources' => [
31
+        'ExternalShares' => ['url' => '/api/externalShares'],
32
+    ],
33
+    'routes' => [
34
+        [
35
+            'name' => 'externalShares#testRemote',
36
+            'url' => '/testremote',
37
+            'verb' => 'GET'
38
+        ],
39
+        [
40
+            'name' => 'PublicPreview#getPreview',
41
+            'url' => '/publicpreview',
42
+            'verb' => 'GET',
43
+        ],
44 44
 
45
-		[
46
-			'name' => 'PublicPreview#getPreview',
47
-			'url' => '/ajax/publicpreview.php',
48
-			'verb' => 'GET',
49
-		],
45
+        [
46
+            'name' => 'PublicPreview#getPreview',
47
+            'url' => '/ajax/publicpreview.php',
48
+            'verb' => 'GET',
49
+        ],
50 50
 
51
-		[
52
-			'name' => 'ShareInfo#info',
53
-			'url' => '/shareinfo',
54
-			'verb' => 'POST',
55
-		],
56
-	],
57
-	'ocs' => [
58
-		/*
51
+        [
52
+            'name' => 'ShareInfo#info',
53
+            'url' => '/shareinfo',
54
+            'verb' => 'POST',
55
+        ],
56
+    ],
57
+    'ocs' => [
58
+        /*
59 59
 		 * OCS Share API
60 60
 		 */
61
-		[
62
-			'name' => 'ShareAPI#getShares',
63
-			'url'  => '/api/v1/shares',
64
-			'verb' => 'GET',
65
-		],
66
-		[
67
-			'name' => 'ShareAPI#createShare',
68
-			'url'  => '/api/v1/shares',
69
-			'verb' => 'POST',
70
-		],
71
-		[
72
-			'name' => 'ShareAPI#resendMailNotification',
73
-			'url'  => '/api/v1/shares/{id}/resendMailNotification',
74
-			'verb' => 'POST',
75
-		],
76
-		[
77
-			'name' => 'ShareAPI#getShare',
78
-			'url'  => '/api/v1/shares/{id}',
79
-			'verb' => 'GET',
80
-		],
81
-		[
82
-			'name' => 'ShareAPI#updateShare',
83
-			'url'  => '/api/v1/shares/{id}',
84
-			'verb' => 'PUT',
85
-		],
86
-		[
87
-			'name' => 'ShareAPI#deleteShare',
88
-			'url'  => '/api/v1/shares/{id}',
89
-			'verb' => 'DELETE',
90
-		],
91
-		/*
61
+        [
62
+            'name' => 'ShareAPI#getShares',
63
+            'url'  => '/api/v1/shares',
64
+            'verb' => 'GET',
65
+        ],
66
+        [
67
+            'name' => 'ShareAPI#createShare',
68
+            'url'  => '/api/v1/shares',
69
+            'verb' => 'POST',
70
+        ],
71
+        [
72
+            'name' => 'ShareAPI#resendMailNotification',
73
+            'url'  => '/api/v1/shares/{id}/resendMailNotification',
74
+            'verb' => 'POST',
75
+        ],
76
+        [
77
+            'name' => 'ShareAPI#getShare',
78
+            'url'  => '/api/v1/shares/{id}',
79
+            'verb' => 'GET',
80
+        ],
81
+        [
82
+            'name' => 'ShareAPI#updateShare',
83
+            'url'  => '/api/v1/shares/{id}',
84
+            'verb' => 'PUT',
85
+        ],
86
+        [
87
+            'name' => 'ShareAPI#deleteShare',
88
+            'url'  => '/api/v1/shares/{id}',
89
+            'verb' => 'DELETE',
90
+        ],
91
+        /*
92 92
 		 * OCS Sharee API
93 93
 		 */
94
-		[
95
-			'name' => 'ShareesAPI#search',
96
-			'url' => '/api/v1/sharees',
97
-			'verb' => 'GET',
98
-		],
99
-		/*
94
+        [
95
+            'name' => 'ShareesAPI#search',
96
+            'url' => '/api/v1/sharees',
97
+            'verb' => 'GET',
98
+        ],
99
+        /*
100 100
 		 * Remote Shares
101 101
 		 */
102
-		[
103
-			'name' => 'Remote#getShares',
104
-			'url' => '/api/v1/remote_shares',
105
-			'verb' => 'GET',
106
-		],
107
-		[
108
-			'name' => 'Remote#getOpenShares',
109
-			'url' => '/api/v1/remote_shares/pending',
110
-			'verb' => 'GET',
111
-		],
112
-		[
113
-			'name' => 'Remote#acceptShare',
114
-			'url' => '/api/v1/remote_shares/pending/{id}',
115
-			'verb' => 'POST',
116
-		],
117
-		[
118
-			'name' => 'Remote#declineShare',
119
-			'url' => '/api/v1/remote_shares/pending/{id}',
120
-			'verb' => 'DELETE',
121
-		],
122
-		[
123
-			'name' => 'Remote#getShare',
124
-			'url' => '/api/v1/remote_shares/{id}',
125
-			'verb' => 'GET',
126
-		],
127
-		[
128
-			'name' => 'Remote#unshare',
129
-			'url' => '/api/v1/remote_shares/{id}',
130
-			'verb' => 'DELETE',
131
-		],
132
-	],
102
+        [
103
+            'name' => 'Remote#getShares',
104
+            'url' => '/api/v1/remote_shares',
105
+            'verb' => 'GET',
106
+        ],
107
+        [
108
+            'name' => 'Remote#getOpenShares',
109
+            'url' => '/api/v1/remote_shares/pending',
110
+            'verb' => 'GET',
111
+        ],
112
+        [
113
+            'name' => 'Remote#acceptShare',
114
+            'url' => '/api/v1/remote_shares/pending/{id}',
115
+            'verb' => 'POST',
116
+        ],
117
+        [
118
+            'name' => 'Remote#declineShare',
119
+            'url' => '/api/v1/remote_shares/pending/{id}',
120
+            'verb' => 'DELETE',
121
+        ],
122
+        [
123
+            'name' => 'Remote#getShare',
124
+            'url' => '/api/v1/remote_shares/{id}',
125
+            'verb' => 'GET',
126
+        ],
127
+        [
128
+            'name' => 'Remote#unshare',
129
+            'url' => '/api/v1/remote_shares/{id}',
130
+            'verb' => 'DELETE',
131
+        ],
132
+    ],
133 133
 ];
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 1 patch
Indentation   +749 added lines, -749 removed lines patch added patch discarded remove patch
@@ -43,753 +43,753 @@
 block discarded – undo
43 43
 
44 44
 class ShareesAPIController extends OCSController {
45 45
 
46
-	/** @var IGroupManager */
47
-	protected $groupManager;
48
-
49
-	/** @var IUserManager */
50
-	protected $userManager;
51
-
52
-	/** @var IManager */
53
-	protected $contactsManager;
54
-
55
-	/** @var IConfig */
56
-	protected $config;
57
-
58
-	/** @var IUserSession */
59
-	protected $userSession;
60
-
61
-	/** @var IURLGenerator */
62
-	protected $urlGenerator;
63
-
64
-	/** @var ILogger */
65
-	protected $logger;
66
-
67
-	/** @var \OCP\Share\IManager */
68
-	protected $shareManager;
69
-
70
-	/** @var IClientService */
71
-	protected $clientService;
72
-
73
-	/** @var ICloudIdManager  */
74
-	protected $cloudIdManager;
75
-
76
-	/** @var bool */
77
-	protected $shareWithGroupOnly = false;
78
-
79
-	/** @var bool */
80
-	protected $shareeEnumeration = true;
81
-
82
-	/** @var int */
83
-	protected $offset = 0;
84
-
85
-	/** @var int */
86
-	protected $limit = 10;
87
-
88
-	/** @var array */
89
-	protected $result = [
90
-		'exact' => [
91
-			'users' => [],
92
-			'groups' => [],
93
-			'remotes' => [],
94
-			'emails' => [],
95
-			'circles' => [],
96
-		],
97
-		'users' => [],
98
-		'groups' => [],
99
-		'remotes' => [],
100
-		'emails' => [],
101
-		'lookup' => [],
102
-		'circles' => [],
103
-	];
104
-
105
-	protected $reachedEndFor = [];
106
-
107
-	/**
108
-	 * @param string $appName
109
-	 * @param IRequest $request
110
-	 * @param IGroupManager $groupManager
111
-	 * @param IUserManager $userManager
112
-	 * @param IManager $contactsManager
113
-	 * @param IConfig $config
114
-	 * @param IUserSession $userSession
115
-	 * @param IURLGenerator $urlGenerator
116
-	 * @param ILogger $logger
117
-	 * @param \OCP\Share\IManager $shareManager
118
-	 * @param IClientService $clientService
119
-	 * @param ICloudIdManager $cloudIdManager
120
-	 */
121
-	public function __construct($appName,
122
-								IRequest $request,
123
-								IGroupManager $groupManager,
124
-								IUserManager $userManager,
125
-								IManager $contactsManager,
126
-								IConfig $config,
127
-								IUserSession $userSession,
128
-								IURLGenerator $urlGenerator,
129
-								ILogger $logger,
130
-								\OCP\Share\IManager $shareManager,
131
-								IClientService $clientService,
132
-								ICloudIdManager $cloudIdManager
133
-	) {
134
-		parent::__construct($appName, $request);
135
-
136
-		$this->groupManager = $groupManager;
137
-		$this->userManager = $userManager;
138
-		$this->contactsManager = $contactsManager;
139
-		$this->config = $config;
140
-		$this->userSession = $userSession;
141
-		$this->urlGenerator = $urlGenerator;
142
-		$this->logger = $logger;
143
-		$this->shareManager = $shareManager;
144
-		$this->clientService = $clientService;
145
-		$this->cloudIdManager = $cloudIdManager;
146
-	}
147
-
148
-	/**
149
-	 * @param string $search
150
-	 */
151
-	protected function getUsers($search) {
152
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
153
-
154
-		$userGroups = [];
155
-		if ($this->shareWithGroupOnly) {
156
-			// Search in all the groups this user is part of
157
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
-			foreach ($userGroups as $userGroup) {
159
-				$usersTmp = $this->groupManager->usersInGroup($userGroup, $search, $this->limit, $this->offset);
160
-				foreach ($usersTmp as $uid => $user) {
161
-					$users[$uid] = $user;
162
-				}
163
-			}
164
-		} else {
165
-			// Search in all users
166
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
-
168
-			foreach ($usersTmp as $user) {
169
-				$users[$user->getUID()] = $user;
170
-			}
171
-		}
172
-
173
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
-			$this->reachedEndFor[] = 'users';
175
-		}
176
-
177
-		$foundUserById = false;
178
-		$lowerSearch = strtolower($search);
179
-		foreach ($users as $uid => $user) {
180
-			if (strtolower($uid) === $lowerSearch || strtolower($user->getDisplayName()) === $lowerSearch) {
181
-				if (strtolower($uid) === $lowerSearch) {
182
-					$foundUserById = true;
183
-				}
184
-				$userData = [
185
-					'label' => $user->getDisplayName(),
186
-					'value' => [
187
-						'shareType' => Share::SHARE_TYPE_USER,
188
-						'shareWith' => $uid,
189
-					],
190
-				];
191
-				if ($user->getEMailAddress()) {
192
-					$userData['value']['emailAddress'] = $user->getEMailAddress();
193
-				}
194
-				$this->result['exact']['users'][] = $userData;
195
-			} else {
196
-				$userData = [
197
-					'label' => $user->getDisplayName(),
198
-					'value' => [
199
-						'shareType' => Share::SHARE_TYPE_USER,
200
-						'shareWith' => $uid,
201
-					],
202
-				];
203
-				if ($user->getEMailAddress()) {
204
-					$userData['value']['emailAddress'] = $user->getEMailAddress();
205
-				}
206
-				$this->result['users'][] = $userData;
207
-			}
208
-		}
209
-
210
-		if ($this->offset === 0 && !$foundUserById) {
211
-			// On page one we try if the search result has a direct hit on the
212
-			// user id and if so, we add that to the exact match list
213
-			$user = $this->userManager->get($search);
214
-			if ($user instanceof IUser) {
215
-				$addUser = true;
216
-
217
-				if ($this->shareWithGroupOnly) {
218
-					// Only add, if we have a common group
219
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
220
-					$addUser = !empty($commonGroups);
221
-				}
222
-
223
-				if ($addUser) {
224
-					$userData = [
225
-						'label' => $user->getDisplayName(),
226
-						'value' => [
227
-							'shareType' => Share::SHARE_TYPE_USER,
228
-							'shareWith' => $user->getUID(),
229
-						],
230
-					];
231
-					if ($user->getEMailAddress()) {
232
-						$userData['value']['emailAddress'] = $user->getEMailAddress();
233
-					}
234
-					$this->result['exact']['users'][] = $userData;
235
-				}
236
-			}
237
-		}
238
-
239
-		if (!$this->shareeEnumeration) {
240
-			$this->result['users'] = [];
241
-		}
242
-	}
243
-
244
-	/**
245
-	 * @param string $search
246
-	 */
247
-	protected function getGroups($search) {
248
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
249
-
250
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
251
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
252
-
253
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
254
-			$this->reachedEndFor[] = 'groups';
255
-		}
256
-
257
-		$userGroups =  [];
258
-		if (!empty($groups) && $this->shareWithGroupOnly) {
259
-			// Intersect all the groups that match with the groups this user is a member of
260
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
261
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
262
-			$groupIds = array_intersect($groupIds, $userGroups);
263
-		}
264
-
265
-		$lowerSearch = strtolower($search);
266
-		foreach ($groups as $group) {
267
-			// FIXME: use a more efficient approach
268
-			$gid = $group->getGID();
269
-			if (!in_array($gid, $groupIds)) {
270
-				continue;
271
-			}
272
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
273
-				$this->result['exact']['groups'][] = [
274
-					'label' => $group->getDisplayName(),
275
-					'value' => [
276
-						'shareType' => Share::SHARE_TYPE_GROUP,
277
-						'shareWith' => $gid,
278
-					],
279
-				];
280
-			} else {
281
-				$this->result['groups'][] = [
282
-					'label' => $group->getDisplayName(),
283
-					'value' => [
284
-						'shareType' => Share::SHARE_TYPE_GROUP,
285
-						'shareWith' => $gid,
286
-					],
287
-				];
288
-			}
289
-		}
290
-
291
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
292
-			// On page one we try if the search result has a direct hit on the
293
-			// user id and if so, we add that to the exact match list
294
-			$group = $this->groupManager->get($search);
295
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
296
-				array_push($this->result['exact']['groups'], [
297
-					'label' => $group->getDisplayName(),
298
-					'value' => [
299
-						'shareType' => Share::SHARE_TYPE_GROUP,
300
-						'shareWith' => $group->getGID(),
301
-					],
302
-				]);
303
-			}
304
-		}
305
-
306
-		if (!$this->shareeEnumeration) {
307
-			$this->result['groups'] = [];
308
-		}
309
-	}
310
-
311
-
312
-	/**
313
-	 * @param string $search
314
-	 * @suppress PhanUndeclaredClassMethod
315
-	 */
316
-	protected function getCircles($search) {
317
-		$this->result['circles'] = $this->result['exact']['circles'] = [];
318
-
319
-		$result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
320
-		if (array_key_exists('circles', $result['exact'])) {
321
-			$this->result['exact']['circles'] = $result['exact']['circles'];
322
-		}
323
-		if (array_key_exists('circles', $result)) {
324
-			$this->result['circles'] = $result['circles'];
325
-		}
326
-	}
327
-
328
-
329
-	/**
330
-	 * @param string $search
331
-	 * @return array
332
-	 */
333
-	protected function getRemote($search) {
334
-		$result = ['results' => [], 'exact' => []];
335
-
336
-		// Search in contacts
337
-		//@todo Pagination missing
338
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
339
-		$result['exactIdMatch'] = false;
340
-		foreach ($addressBookContacts as $contact) {
341
-			if (isset($contact['isLocalSystemBook'])) {
342
-				continue;
343
-			}
344
-			if (isset($contact['CLOUD'])) {
345
-				$cloudIds = $contact['CLOUD'];
346
-				if (!is_array($cloudIds)) {
347
-					$cloudIds = [$cloudIds];
348
-				}
349
-				$lowerSearch = strtolower($search);
350
-				foreach ($cloudIds as $cloudId) {
351
-					try {
352
-						list(, $serverUrl) = $this->splitUserRemote($cloudId);
353
-					} catch (\InvalidArgumentException $e) {
354
-						continue;
355
-					}
356
-
357
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
358
-						if (strtolower($cloudId) === $lowerSearch) {
359
-							$result['exactIdMatch'] = true;
360
-						}
361
-						$result['exact'][] = [
362
-							'label' => $contact['FN'] . " ($cloudId)",
363
-							'value' => [
364
-								'shareType' => Share::SHARE_TYPE_REMOTE,
365
-								'shareWith' => $cloudId,
366
-								'server' => $serverUrl,
367
-							],
368
-						];
369
-					} else {
370
-						$result['results'][] = [
371
-							'label' => $contact['FN'] . " ($cloudId)",
372
-							'value' => [
373
-								'shareType' => Share::SHARE_TYPE_REMOTE,
374
-								'shareWith' => $cloudId,
375
-								'server' => $serverUrl,
376
-							],
377
-						];
378
-					}
379
-				}
380
-			}
381
-		}
382
-
383
-		if (!$this->shareeEnumeration) {
384
-			$result['results'] = [];
385
-		}
386
-
387
-		if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
388
-			$result['exact'][] = [
389
-				'label' => $search,
390
-				'value' => [
391
-					'shareType' => Share::SHARE_TYPE_REMOTE,
392
-					'shareWith' => $search,
393
-				],
394
-			];
395
-		}
396
-
397
-		$this->reachedEndFor[] = 'remotes';
398
-
399
-		return $result;
400
-	}
401
-
402
-	/**
403
-	 * split user and remote from federated cloud id
404
-	 *
405
-	 * @param string $address federated share address
406
-	 * @return array [user, remoteURL]
407
-	 * @throws \InvalidArgumentException
408
-	 */
409
-	public function splitUserRemote($address) {
410
-		try {
411
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
412
-			return [$cloudId->getUser(), $cloudId->getRemote()];
413
-		} catch (\InvalidArgumentException $e) {
414
-			throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
415
-		}
416
-	}
417
-
418
-	/**
419
-	 * Strips away a potential file names and trailing slashes:
420
-	 * - http://localhost
421
-	 * - http://localhost/
422
-	 * - http://localhost/index.php
423
-	 * - http://localhost/index.php/s/{shareToken}
424
-	 *
425
-	 * all return: http://localhost
426
-	 *
427
-	 * @param string $remote
428
-	 * @return string
429
-	 */
430
-	protected function fixRemoteURL($remote) {
431
-		$remote = str_replace('\\', '/', $remote);
432
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
433
-			$remote = substr($remote, 0, $fileNamePosition);
434
-		}
435
-		$remote = rtrim($remote, '/');
436
-
437
-		return $remote;
438
-	}
439
-
440
-	/**
441
-	 * @NoAdminRequired
442
-	 *
443
-	 * @param string $search
444
-	 * @param string $itemType
445
-	 * @param int $page
446
-	 * @param int $perPage
447
-	 * @param int|int[] $shareType
448
-	 * @param bool $lookup
449
-	 * @return DataResponse
450
-	 * @throws OCSBadRequestException
451
-	 */
452
-	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
453
-
454
-		// only search for string larger than a given threshold
455
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
456
-		if (strlen($search) < $threshold) {
457
-			return new DataResponse($this->result);
458
-		}
459
-
460
-		// never return more than the max. number of results configured in the config.php
461
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
462
-		if ($maxResults > 0) {
463
-			$perPage = min($perPage, $maxResults);
464
-		}
465
-		if ($perPage <= 0) {
466
-			throw new OCSBadRequestException('Invalid perPage argument');
467
-		}
468
-		if ($page <= 0) {
469
-			throw new OCSBadRequestException('Invalid page');
470
-		}
471
-
472
-		$shareTypes = [
473
-			Share::SHARE_TYPE_USER,
474
-		];
475
-
476
-		if ($itemType === 'file' || $itemType === 'folder') {
477
-			if ($this->shareManager->allowGroupSharing()) {
478
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
479
-			}
480
-
481
-			if ($this->isRemoteSharingAllowed($itemType)) {
482
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
483
-			}
484
-
485
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
486
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
487
-			}
488
-		} else {
489
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
490
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
491
-		}
492
-
493
-		if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
494
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
495
-		}
496
-
497
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
498
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
499
-			sort($shareTypes);
500
-		} else if (is_numeric($shareType)) {
501
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
502
-			sort($shareTypes);
503
-		}
504
-
505
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
506
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
507
-		$this->limit = (int) $perPage;
508
-		$this->offset = $perPage * ($page - 1);
509
-
510
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
511
-	}
512
-
513
-	/**
514
-	 * Method to get out the static call for better testing
515
-	 *
516
-	 * @param string $itemType
517
-	 * @return bool
518
-	 */
519
-	protected function isRemoteSharingAllowed($itemType) {
520
-		try {
521
-			$backend = \OC\Share\Share::getBackend($itemType);
522
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
523
-		} catch (\Exception $e) {
524
-			return false;
525
-		}
526
-	}
527
-
528
-	/**
529
-	 * Testable search function that does not need globals
530
-	 *
531
-	 * @param string $search
532
-	 * @param string $itemType
533
-	 * @param array $shareTypes
534
-	 * @param int $page
535
-	 * @param int $perPage
536
-	 * @param bool $lookup
537
-	 * @return DataResponse
538
-	 * @throws OCSBadRequestException
539
-	 */
540
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
541
-		// Verify arguments
542
-		if ($itemType === null) {
543
-			throw new OCSBadRequestException('Missing itemType');
544
-		}
545
-
546
-		// Get users
547
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
548
-			$this->getUsers($search);
549
-		}
550
-
551
-		// Get groups
552
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
553
-			$this->getGroups($search);
554
-		}
555
-
556
-		// Get circles
557
-		if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
558
-			$this->getCircles($search);
559
-		}
560
-
561
-
562
-		// Get remote
563
-		$remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
564
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
565
-			$remoteResults = $this->getRemote($search);
566
-		}
567
-
568
-		// Get emails
569
-		$mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
570
-		if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
571
-			$mailResults = $this->getEmail($search);
572
-		}
573
-
574
-		// Get from lookup server
575
-		if ($lookup) {
576
-			$this->getLookup($search);
577
-		}
578
-
579
-		// if we have a exact match, either for the federated cloud id or for the
580
-		// email address we only return the exact match. It is highly unlikely
581
-		// that the exact same email address and federated cloud id exists
582
-		if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
583
-			$this->result['emails'] = $mailResults['results'];
584
-			$this->result['exact']['emails'] = $mailResults['exact'];
585
-		} else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
586
-			$this->result['remotes'] = $remoteResults['results'];
587
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
588
-		} else {
589
-			$this->result['remotes'] = $remoteResults['results'];
590
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
591
-			$this->result['emails'] = $mailResults['results'];
592
-			$this->result['exact']['emails'] = $mailResults['exact'];
593
-		}
594
-
595
-		$response = new DataResponse($this->result);
596
-
597
-		if (sizeof($this->reachedEndFor) < 3) {
598
-			$response->addHeader('Link', $this->getPaginationLink($page, [
599
-				'search' => $search,
600
-				'itemType' => $itemType,
601
-				'shareType' => $shareTypes,
602
-				'perPage' => $perPage,
603
-			]));
604
-		}
605
-
606
-		return $response;
607
-	}
608
-
609
-	/**
610
-	 * @param string $search
611
-	 * @return array
612
-	 */
613
-	protected function getEmail($search) {
614
-		$result = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
615
-
616
-		// Search in contacts
617
-		//@todo Pagination missing
618
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
619
-		$lowerSearch = strtolower($search);
620
-		foreach ($addressBookContacts as $contact) {
621
-			if (isset($contact['EMAIL'])) {
622
-				$emailAddresses = $contact['EMAIL'];
623
-				if (!is_array($emailAddresses)) {
624
-					$emailAddresses = [$emailAddresses];
625
-				}
626
-				foreach ($emailAddresses as $emailAddress) {
627
-					$exactEmailMatch = strtolower($emailAddress) === $lowerSearch;
628
-
629
-					if (isset($contact['isLocalSystemBook'])) {
630
-						if ($exactEmailMatch) {
631
-							try {
632
-								$cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
633
-							} catch (\InvalidArgumentException $e) {
634
-								continue;
635
-							}
636
-
637
-							if (!$this->hasUserInResult($cloud->getUser())) {
638
-								$this->result['exact']['users'][] = [
639
-									'label' => $contact['FN'] . " ($emailAddress)",
640
-									'value' => [
641
-										'shareType' => Share::SHARE_TYPE_USER,
642
-										'shareWith' => $cloud->getUser(),
643
-									],
644
-								];
645
-							}
646
-							return ['results' => [], 'exact' => [], 'exactIdMatch' => true];
647
-						}
648
-
649
-						if ($this->shareeEnumeration) {
650
-							try {
651
-								$cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
652
-							} catch (\InvalidArgumentException $e) {
653
-								continue;
654
-							}
655
-
656
-							if (!$this->hasUserInResult($cloud->getUser())) {
657
-								$this->result['users'][] = [
658
-									'label' => $contact['FN'] . " ($emailAddress)",
659
-									'value' => [
660
-										'shareType' => Share::SHARE_TYPE_USER,
661
-										'shareWith' => $cloud->getUser(),
662
-									],
663
-								];
664
-							}
665
-						}
666
-						continue;
667
-					}
668
-
669
-					if ($exactEmailMatch || strtolower($contact['FN']) === $lowerSearch) {
670
-						if ($exactEmailMatch) {
671
-							$result['exactIdMatch'] = true;
672
-						}
673
-						$result['exact'][] = [
674
-							'label' => $contact['FN'] . " ($emailAddress)",
675
-							'value' => [
676
-								'shareType' => Share::SHARE_TYPE_EMAIL,
677
-								'shareWith' => $emailAddress,
678
-							],
679
-						];
680
-					} else {
681
-						$result['results'][] = [
682
-							'label' => $contact['FN'] . " ($emailAddress)",
683
-							'value' => [
684
-								'shareType' => Share::SHARE_TYPE_EMAIL,
685
-								'shareWith' => $emailAddress,
686
-							],
687
-						];
688
-					}
689
-				}
690
-			}
691
-		}
692
-
693
-		if (!$this->shareeEnumeration) {
694
-			$result['results'] = [];
695
-		}
696
-
697
-		if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
698
-			$result['exact'][] = [
699
-				'label' => $search,
700
-				'value' => [
701
-					'shareType' => Share::SHARE_TYPE_EMAIL,
702
-					'shareWith' => $search,
703
-				],
704
-			];
705
-		}
706
-
707
-		$this->reachedEndFor[] = 'emails';
708
-
709
-		return $result;
710
-	}
711
-
712
-	protected function getLookup($search) {
713
-		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
714
-		$lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
715
-		$lookupServerUrl = rtrim($lookupServerUrl, '/');
716
-		$result = [];
717
-
718
-		if($isEnabled === 'yes') {
719
-			try {
720
-				$client = $this->clientService->newClient();
721
-				$response = $client->get(
722
-					$lookupServerUrl . '/users?search=' . urlencode($search),
723
-					[
724
-						'timeout' => 10,
725
-						'connect_timeout' => 3,
726
-					]
727
-				);
728
-
729
-				$body = json_decode($response->getBody(), true);
730
-
731
-				$result = [];
732
-				foreach ($body as $lookup) {
733
-					$result[] = [
734
-						'label' => $lookup['federationId'],
735
-						'value' => [
736
-							'shareType' => Share::SHARE_TYPE_REMOTE,
737
-							'shareWith' => $lookup['federationId'],
738
-						],
739
-						'extra' => $lookup,
740
-					];
741
-				}
742
-			} catch (\Exception $e) {}
743
-		}
744
-
745
-		$this->result['lookup'] = $result;
746
-	}
747
-
748
-	/**
749
-	 * Check if a given user is already part of the result
750
-	 *
751
-	 * @param string $userId
752
-	 * @return bool
753
-	 */
754
-	protected function hasUserInResult($userId) {
755
-		foreach ($this->result['exact']['users'] as $result) {
756
-			if ($result['value']['shareWith'] === $userId) {
757
-				return true;
758
-			}
759
-		}
760
-
761
-		foreach ($this->result['users'] as $result) {
762
-			if ($result['value']['shareWith'] === $userId) {
763
-				return true;
764
-			}
765
-		}
766
-
767
-		return false;
768
-	}
769
-
770
-	/**
771
-	 * Generates a bunch of pagination links for the current page
772
-	 *
773
-	 * @param int $page Current page
774
-	 * @param array $params Parameters for the URL
775
-	 * @return string
776
-	 */
777
-	protected function getPaginationLink($page, array $params) {
778
-		if ($this->isV2()) {
779
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
780
-		} else {
781
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
782
-		}
783
-		$params['page'] = $page + 1;
784
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
785
-
786
-		return $link;
787
-	}
788
-
789
-	/**
790
-	 * @return bool
791
-	 */
792
-	protected function isV2() {
793
-		return $this->request->getScriptName() === '/ocs/v2.php';
794
-	}
46
+    /** @var IGroupManager */
47
+    protected $groupManager;
48
+
49
+    /** @var IUserManager */
50
+    protected $userManager;
51
+
52
+    /** @var IManager */
53
+    protected $contactsManager;
54
+
55
+    /** @var IConfig */
56
+    protected $config;
57
+
58
+    /** @var IUserSession */
59
+    protected $userSession;
60
+
61
+    /** @var IURLGenerator */
62
+    protected $urlGenerator;
63
+
64
+    /** @var ILogger */
65
+    protected $logger;
66
+
67
+    /** @var \OCP\Share\IManager */
68
+    protected $shareManager;
69
+
70
+    /** @var IClientService */
71
+    protected $clientService;
72
+
73
+    /** @var ICloudIdManager  */
74
+    protected $cloudIdManager;
75
+
76
+    /** @var bool */
77
+    protected $shareWithGroupOnly = false;
78
+
79
+    /** @var bool */
80
+    protected $shareeEnumeration = true;
81
+
82
+    /** @var int */
83
+    protected $offset = 0;
84
+
85
+    /** @var int */
86
+    protected $limit = 10;
87
+
88
+    /** @var array */
89
+    protected $result = [
90
+        'exact' => [
91
+            'users' => [],
92
+            'groups' => [],
93
+            'remotes' => [],
94
+            'emails' => [],
95
+            'circles' => [],
96
+        ],
97
+        'users' => [],
98
+        'groups' => [],
99
+        'remotes' => [],
100
+        'emails' => [],
101
+        'lookup' => [],
102
+        'circles' => [],
103
+    ];
104
+
105
+    protected $reachedEndFor = [];
106
+
107
+    /**
108
+     * @param string $appName
109
+     * @param IRequest $request
110
+     * @param IGroupManager $groupManager
111
+     * @param IUserManager $userManager
112
+     * @param IManager $contactsManager
113
+     * @param IConfig $config
114
+     * @param IUserSession $userSession
115
+     * @param IURLGenerator $urlGenerator
116
+     * @param ILogger $logger
117
+     * @param \OCP\Share\IManager $shareManager
118
+     * @param IClientService $clientService
119
+     * @param ICloudIdManager $cloudIdManager
120
+     */
121
+    public function __construct($appName,
122
+                                IRequest $request,
123
+                                IGroupManager $groupManager,
124
+                                IUserManager $userManager,
125
+                                IManager $contactsManager,
126
+                                IConfig $config,
127
+                                IUserSession $userSession,
128
+                                IURLGenerator $urlGenerator,
129
+                                ILogger $logger,
130
+                                \OCP\Share\IManager $shareManager,
131
+                                IClientService $clientService,
132
+                                ICloudIdManager $cloudIdManager
133
+    ) {
134
+        parent::__construct($appName, $request);
135
+
136
+        $this->groupManager = $groupManager;
137
+        $this->userManager = $userManager;
138
+        $this->contactsManager = $contactsManager;
139
+        $this->config = $config;
140
+        $this->userSession = $userSession;
141
+        $this->urlGenerator = $urlGenerator;
142
+        $this->logger = $logger;
143
+        $this->shareManager = $shareManager;
144
+        $this->clientService = $clientService;
145
+        $this->cloudIdManager = $cloudIdManager;
146
+    }
147
+
148
+    /**
149
+     * @param string $search
150
+     */
151
+    protected function getUsers($search) {
152
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
153
+
154
+        $userGroups = [];
155
+        if ($this->shareWithGroupOnly) {
156
+            // Search in all the groups this user is part of
157
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
158
+            foreach ($userGroups as $userGroup) {
159
+                $usersTmp = $this->groupManager->usersInGroup($userGroup, $search, $this->limit, $this->offset);
160
+                foreach ($usersTmp as $uid => $user) {
161
+                    $users[$uid] = $user;
162
+                }
163
+            }
164
+        } else {
165
+            // Search in all users
166
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
167
+
168
+            foreach ($usersTmp as $user) {
169
+                $users[$user->getUID()] = $user;
170
+            }
171
+        }
172
+
173
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
174
+            $this->reachedEndFor[] = 'users';
175
+        }
176
+
177
+        $foundUserById = false;
178
+        $lowerSearch = strtolower($search);
179
+        foreach ($users as $uid => $user) {
180
+            if (strtolower($uid) === $lowerSearch || strtolower($user->getDisplayName()) === $lowerSearch) {
181
+                if (strtolower($uid) === $lowerSearch) {
182
+                    $foundUserById = true;
183
+                }
184
+                $userData = [
185
+                    'label' => $user->getDisplayName(),
186
+                    'value' => [
187
+                        'shareType' => Share::SHARE_TYPE_USER,
188
+                        'shareWith' => $uid,
189
+                    ],
190
+                ];
191
+                if ($user->getEMailAddress()) {
192
+                    $userData['value']['emailAddress'] = $user->getEMailAddress();
193
+                }
194
+                $this->result['exact']['users'][] = $userData;
195
+            } else {
196
+                $userData = [
197
+                    'label' => $user->getDisplayName(),
198
+                    'value' => [
199
+                        'shareType' => Share::SHARE_TYPE_USER,
200
+                        'shareWith' => $uid,
201
+                    ],
202
+                ];
203
+                if ($user->getEMailAddress()) {
204
+                    $userData['value']['emailAddress'] = $user->getEMailAddress();
205
+                }
206
+                $this->result['users'][] = $userData;
207
+            }
208
+        }
209
+
210
+        if ($this->offset === 0 && !$foundUserById) {
211
+            // On page one we try if the search result has a direct hit on the
212
+            // user id and if so, we add that to the exact match list
213
+            $user = $this->userManager->get($search);
214
+            if ($user instanceof IUser) {
215
+                $addUser = true;
216
+
217
+                if ($this->shareWithGroupOnly) {
218
+                    // Only add, if we have a common group
219
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
220
+                    $addUser = !empty($commonGroups);
221
+                }
222
+
223
+                if ($addUser) {
224
+                    $userData = [
225
+                        'label' => $user->getDisplayName(),
226
+                        'value' => [
227
+                            'shareType' => Share::SHARE_TYPE_USER,
228
+                            'shareWith' => $user->getUID(),
229
+                        ],
230
+                    ];
231
+                    if ($user->getEMailAddress()) {
232
+                        $userData['value']['emailAddress'] = $user->getEMailAddress();
233
+                    }
234
+                    $this->result['exact']['users'][] = $userData;
235
+                }
236
+            }
237
+        }
238
+
239
+        if (!$this->shareeEnumeration) {
240
+            $this->result['users'] = [];
241
+        }
242
+    }
243
+
244
+    /**
245
+     * @param string $search
246
+     */
247
+    protected function getGroups($search) {
248
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
249
+
250
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
251
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
252
+
253
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
254
+            $this->reachedEndFor[] = 'groups';
255
+        }
256
+
257
+        $userGroups =  [];
258
+        if (!empty($groups) && $this->shareWithGroupOnly) {
259
+            // Intersect all the groups that match with the groups this user is a member of
260
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
261
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
262
+            $groupIds = array_intersect($groupIds, $userGroups);
263
+        }
264
+
265
+        $lowerSearch = strtolower($search);
266
+        foreach ($groups as $group) {
267
+            // FIXME: use a more efficient approach
268
+            $gid = $group->getGID();
269
+            if (!in_array($gid, $groupIds)) {
270
+                continue;
271
+            }
272
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
273
+                $this->result['exact']['groups'][] = [
274
+                    'label' => $group->getDisplayName(),
275
+                    'value' => [
276
+                        'shareType' => Share::SHARE_TYPE_GROUP,
277
+                        'shareWith' => $gid,
278
+                    ],
279
+                ];
280
+            } else {
281
+                $this->result['groups'][] = [
282
+                    'label' => $group->getDisplayName(),
283
+                    'value' => [
284
+                        'shareType' => Share::SHARE_TYPE_GROUP,
285
+                        'shareWith' => $gid,
286
+                    ],
287
+                ];
288
+            }
289
+        }
290
+
291
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
292
+            // On page one we try if the search result has a direct hit on the
293
+            // user id and if so, we add that to the exact match list
294
+            $group = $this->groupManager->get($search);
295
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
296
+                array_push($this->result['exact']['groups'], [
297
+                    'label' => $group->getDisplayName(),
298
+                    'value' => [
299
+                        'shareType' => Share::SHARE_TYPE_GROUP,
300
+                        'shareWith' => $group->getGID(),
301
+                    ],
302
+                ]);
303
+            }
304
+        }
305
+
306
+        if (!$this->shareeEnumeration) {
307
+            $this->result['groups'] = [];
308
+        }
309
+    }
310
+
311
+
312
+    /**
313
+     * @param string $search
314
+     * @suppress PhanUndeclaredClassMethod
315
+     */
316
+    protected function getCircles($search) {
317
+        $this->result['circles'] = $this->result['exact']['circles'] = [];
318
+
319
+        $result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset);
320
+        if (array_key_exists('circles', $result['exact'])) {
321
+            $this->result['exact']['circles'] = $result['exact']['circles'];
322
+        }
323
+        if (array_key_exists('circles', $result)) {
324
+            $this->result['circles'] = $result['circles'];
325
+        }
326
+    }
327
+
328
+
329
+    /**
330
+     * @param string $search
331
+     * @return array
332
+     */
333
+    protected function getRemote($search) {
334
+        $result = ['results' => [], 'exact' => []];
335
+
336
+        // Search in contacts
337
+        //@todo Pagination missing
338
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
339
+        $result['exactIdMatch'] = false;
340
+        foreach ($addressBookContacts as $contact) {
341
+            if (isset($contact['isLocalSystemBook'])) {
342
+                continue;
343
+            }
344
+            if (isset($contact['CLOUD'])) {
345
+                $cloudIds = $contact['CLOUD'];
346
+                if (!is_array($cloudIds)) {
347
+                    $cloudIds = [$cloudIds];
348
+                }
349
+                $lowerSearch = strtolower($search);
350
+                foreach ($cloudIds as $cloudId) {
351
+                    try {
352
+                        list(, $serverUrl) = $this->splitUserRemote($cloudId);
353
+                    } catch (\InvalidArgumentException $e) {
354
+                        continue;
355
+                    }
356
+
357
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
358
+                        if (strtolower($cloudId) === $lowerSearch) {
359
+                            $result['exactIdMatch'] = true;
360
+                        }
361
+                        $result['exact'][] = [
362
+                            'label' => $contact['FN'] . " ($cloudId)",
363
+                            'value' => [
364
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
365
+                                'shareWith' => $cloudId,
366
+                                'server' => $serverUrl,
367
+                            ],
368
+                        ];
369
+                    } else {
370
+                        $result['results'][] = [
371
+                            'label' => $contact['FN'] . " ($cloudId)",
372
+                            'value' => [
373
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
374
+                                'shareWith' => $cloudId,
375
+                                'server' => $serverUrl,
376
+                            ],
377
+                        ];
378
+                    }
379
+                }
380
+            }
381
+        }
382
+
383
+        if (!$this->shareeEnumeration) {
384
+            $result['results'] = [];
385
+        }
386
+
387
+        if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
388
+            $result['exact'][] = [
389
+                'label' => $search,
390
+                'value' => [
391
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
392
+                    'shareWith' => $search,
393
+                ],
394
+            ];
395
+        }
396
+
397
+        $this->reachedEndFor[] = 'remotes';
398
+
399
+        return $result;
400
+    }
401
+
402
+    /**
403
+     * split user and remote from federated cloud id
404
+     *
405
+     * @param string $address federated share address
406
+     * @return array [user, remoteURL]
407
+     * @throws \InvalidArgumentException
408
+     */
409
+    public function splitUserRemote($address) {
410
+        try {
411
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
412
+            return [$cloudId->getUser(), $cloudId->getRemote()];
413
+        } catch (\InvalidArgumentException $e) {
414
+            throw new \InvalidArgumentException('Invalid Federated Cloud ID', 0, $e);
415
+        }
416
+    }
417
+
418
+    /**
419
+     * Strips away a potential file names and trailing slashes:
420
+     * - http://localhost
421
+     * - http://localhost/
422
+     * - http://localhost/index.php
423
+     * - http://localhost/index.php/s/{shareToken}
424
+     *
425
+     * all return: http://localhost
426
+     *
427
+     * @param string $remote
428
+     * @return string
429
+     */
430
+    protected function fixRemoteURL($remote) {
431
+        $remote = str_replace('\\', '/', $remote);
432
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
433
+            $remote = substr($remote, 0, $fileNamePosition);
434
+        }
435
+        $remote = rtrim($remote, '/');
436
+
437
+        return $remote;
438
+    }
439
+
440
+    /**
441
+     * @NoAdminRequired
442
+     *
443
+     * @param string $search
444
+     * @param string $itemType
445
+     * @param int $page
446
+     * @param int $perPage
447
+     * @param int|int[] $shareType
448
+     * @param bool $lookup
449
+     * @return DataResponse
450
+     * @throws OCSBadRequestException
451
+     */
452
+    public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
453
+
454
+        // only search for string larger than a given threshold
455
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
456
+        if (strlen($search) < $threshold) {
457
+            return new DataResponse($this->result);
458
+        }
459
+
460
+        // never return more than the max. number of results configured in the config.php
461
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
462
+        if ($maxResults > 0) {
463
+            $perPage = min($perPage, $maxResults);
464
+        }
465
+        if ($perPage <= 0) {
466
+            throw new OCSBadRequestException('Invalid perPage argument');
467
+        }
468
+        if ($page <= 0) {
469
+            throw new OCSBadRequestException('Invalid page');
470
+        }
471
+
472
+        $shareTypes = [
473
+            Share::SHARE_TYPE_USER,
474
+        ];
475
+
476
+        if ($itemType === 'file' || $itemType === 'folder') {
477
+            if ($this->shareManager->allowGroupSharing()) {
478
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
479
+            }
480
+
481
+            if ($this->isRemoteSharingAllowed($itemType)) {
482
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
483
+            }
484
+
485
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
486
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
487
+            }
488
+        } else {
489
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
490
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
491
+        }
492
+
493
+        if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
494
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
495
+        }
496
+
497
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
498
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
499
+            sort($shareTypes);
500
+        } else if (is_numeric($shareType)) {
501
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
502
+            sort($shareTypes);
503
+        }
504
+
505
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
506
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
507
+        $this->limit = (int) $perPage;
508
+        $this->offset = $perPage * ($page - 1);
509
+
510
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
511
+    }
512
+
513
+    /**
514
+     * Method to get out the static call for better testing
515
+     *
516
+     * @param string $itemType
517
+     * @return bool
518
+     */
519
+    protected function isRemoteSharingAllowed($itemType) {
520
+        try {
521
+            $backend = \OC\Share\Share::getBackend($itemType);
522
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
523
+        } catch (\Exception $e) {
524
+            return false;
525
+        }
526
+    }
527
+
528
+    /**
529
+     * Testable search function that does not need globals
530
+     *
531
+     * @param string $search
532
+     * @param string $itemType
533
+     * @param array $shareTypes
534
+     * @param int $page
535
+     * @param int $perPage
536
+     * @param bool $lookup
537
+     * @return DataResponse
538
+     * @throws OCSBadRequestException
539
+     */
540
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
541
+        // Verify arguments
542
+        if ($itemType === null) {
543
+            throw new OCSBadRequestException('Missing itemType');
544
+        }
545
+
546
+        // Get users
547
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
548
+            $this->getUsers($search);
549
+        }
550
+
551
+        // Get groups
552
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
553
+            $this->getGroups($search);
554
+        }
555
+
556
+        // Get circles
557
+        if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) {
558
+            $this->getCircles($search);
559
+        }
560
+
561
+
562
+        // Get remote
563
+        $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
564
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
565
+            $remoteResults = $this->getRemote($search);
566
+        }
567
+
568
+        // Get emails
569
+        $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
570
+        if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
571
+            $mailResults = $this->getEmail($search);
572
+        }
573
+
574
+        // Get from lookup server
575
+        if ($lookup) {
576
+            $this->getLookup($search);
577
+        }
578
+
579
+        // if we have a exact match, either for the federated cloud id or for the
580
+        // email address we only return the exact match. It is highly unlikely
581
+        // that the exact same email address and federated cloud id exists
582
+        if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
583
+            $this->result['emails'] = $mailResults['results'];
584
+            $this->result['exact']['emails'] = $mailResults['exact'];
585
+        } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
586
+            $this->result['remotes'] = $remoteResults['results'];
587
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
588
+        } else {
589
+            $this->result['remotes'] = $remoteResults['results'];
590
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
591
+            $this->result['emails'] = $mailResults['results'];
592
+            $this->result['exact']['emails'] = $mailResults['exact'];
593
+        }
594
+
595
+        $response = new DataResponse($this->result);
596
+
597
+        if (sizeof($this->reachedEndFor) < 3) {
598
+            $response->addHeader('Link', $this->getPaginationLink($page, [
599
+                'search' => $search,
600
+                'itemType' => $itemType,
601
+                'shareType' => $shareTypes,
602
+                'perPage' => $perPage,
603
+            ]));
604
+        }
605
+
606
+        return $response;
607
+    }
608
+
609
+    /**
610
+     * @param string $search
611
+     * @return array
612
+     */
613
+    protected function getEmail($search) {
614
+        $result = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
615
+
616
+        // Search in contacts
617
+        //@todo Pagination missing
618
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
619
+        $lowerSearch = strtolower($search);
620
+        foreach ($addressBookContacts as $contact) {
621
+            if (isset($contact['EMAIL'])) {
622
+                $emailAddresses = $contact['EMAIL'];
623
+                if (!is_array($emailAddresses)) {
624
+                    $emailAddresses = [$emailAddresses];
625
+                }
626
+                foreach ($emailAddresses as $emailAddress) {
627
+                    $exactEmailMatch = strtolower($emailAddress) === $lowerSearch;
628
+
629
+                    if (isset($contact['isLocalSystemBook'])) {
630
+                        if ($exactEmailMatch) {
631
+                            try {
632
+                                $cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
633
+                            } catch (\InvalidArgumentException $e) {
634
+                                continue;
635
+                            }
636
+
637
+                            if (!$this->hasUserInResult($cloud->getUser())) {
638
+                                $this->result['exact']['users'][] = [
639
+                                    'label' => $contact['FN'] . " ($emailAddress)",
640
+                                    'value' => [
641
+                                        'shareType' => Share::SHARE_TYPE_USER,
642
+                                        'shareWith' => $cloud->getUser(),
643
+                                    ],
644
+                                ];
645
+                            }
646
+                            return ['results' => [], 'exact' => [], 'exactIdMatch' => true];
647
+                        }
648
+
649
+                        if ($this->shareeEnumeration) {
650
+                            try {
651
+                                $cloud = $this->cloudIdManager->resolveCloudId($contact['CLOUD'][0]);
652
+                            } catch (\InvalidArgumentException $e) {
653
+                                continue;
654
+                            }
655
+
656
+                            if (!$this->hasUserInResult($cloud->getUser())) {
657
+                                $this->result['users'][] = [
658
+                                    'label' => $contact['FN'] . " ($emailAddress)",
659
+                                    'value' => [
660
+                                        'shareType' => Share::SHARE_TYPE_USER,
661
+                                        'shareWith' => $cloud->getUser(),
662
+                                    ],
663
+                                ];
664
+                            }
665
+                        }
666
+                        continue;
667
+                    }
668
+
669
+                    if ($exactEmailMatch || strtolower($contact['FN']) === $lowerSearch) {
670
+                        if ($exactEmailMatch) {
671
+                            $result['exactIdMatch'] = true;
672
+                        }
673
+                        $result['exact'][] = [
674
+                            'label' => $contact['FN'] . " ($emailAddress)",
675
+                            'value' => [
676
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
677
+                                'shareWith' => $emailAddress,
678
+                            ],
679
+                        ];
680
+                    } else {
681
+                        $result['results'][] = [
682
+                            'label' => $contact['FN'] . " ($emailAddress)",
683
+                            'value' => [
684
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
685
+                                'shareWith' => $emailAddress,
686
+                            ],
687
+                        ];
688
+                    }
689
+                }
690
+            }
691
+        }
692
+
693
+        if (!$this->shareeEnumeration) {
694
+            $result['results'] = [];
695
+        }
696
+
697
+        if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
698
+            $result['exact'][] = [
699
+                'label' => $search,
700
+                'value' => [
701
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
702
+                    'shareWith' => $search,
703
+                ],
704
+            ];
705
+        }
706
+
707
+        $this->reachedEndFor[] = 'emails';
708
+
709
+        return $result;
710
+    }
711
+
712
+    protected function getLookup($search) {
713
+        $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
714
+        $lookupServerUrl = $this->config->getSystemValue('lookup_server', 'https://lookup.nextcloud.com');
715
+        $lookupServerUrl = rtrim($lookupServerUrl, '/');
716
+        $result = [];
717
+
718
+        if($isEnabled === 'yes') {
719
+            try {
720
+                $client = $this->clientService->newClient();
721
+                $response = $client->get(
722
+                    $lookupServerUrl . '/users?search=' . urlencode($search),
723
+                    [
724
+                        'timeout' => 10,
725
+                        'connect_timeout' => 3,
726
+                    ]
727
+                );
728
+
729
+                $body = json_decode($response->getBody(), true);
730
+
731
+                $result = [];
732
+                foreach ($body as $lookup) {
733
+                    $result[] = [
734
+                        'label' => $lookup['federationId'],
735
+                        'value' => [
736
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
737
+                            'shareWith' => $lookup['federationId'],
738
+                        ],
739
+                        'extra' => $lookup,
740
+                    ];
741
+                }
742
+            } catch (\Exception $e) {}
743
+        }
744
+
745
+        $this->result['lookup'] = $result;
746
+    }
747
+
748
+    /**
749
+     * Check if a given user is already part of the result
750
+     *
751
+     * @param string $userId
752
+     * @return bool
753
+     */
754
+    protected function hasUserInResult($userId) {
755
+        foreach ($this->result['exact']['users'] as $result) {
756
+            if ($result['value']['shareWith'] === $userId) {
757
+                return true;
758
+            }
759
+        }
760
+
761
+        foreach ($this->result['users'] as $result) {
762
+            if ($result['value']['shareWith'] === $userId) {
763
+                return true;
764
+            }
765
+        }
766
+
767
+        return false;
768
+    }
769
+
770
+    /**
771
+     * Generates a bunch of pagination links for the current page
772
+     *
773
+     * @param int $page Current page
774
+     * @param array $params Parameters for the URL
775
+     * @return string
776
+     */
777
+    protected function getPaginationLink($page, array $params) {
778
+        if ($this->isV2()) {
779
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
780
+        } else {
781
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
782
+        }
783
+        $params['page'] = $page + 1;
784
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
785
+
786
+        return $link;
787
+    }
788
+
789
+    /**
790
+     * @return bool
791
+     */
792
+    protected function isV2() {
793
+        return $this->request->getScriptName() === '/ocs/v2.php';
794
+    }
795 795
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareAPIController.php 1 patch
Indentation   +903 added lines, -903 removed lines patch added patch discarded remove patch
@@ -52,916 +52,916 @@
 block discarded – undo
52 52
  */
53 53
 class ShareAPIController extends OCSController {
54 54
 
55
-	/** @var IManager */
56
-	private $shareManager;
57
-	/** @var IGroupManager */
58
-	private $groupManager;
59
-	/** @var IUserManager */
60
-	private $userManager;
61
-	/** @var IRequest */
62
-	protected $request;
63
-	/** @var IRootFolder */
64
-	private $rootFolder;
65
-	/** @var IURLGenerator */
66
-	private $urlGenerator;
67
-	/** @var string */
68
-	private $currentUser;
69
-	/** @var IL10N */
70
-	private $l;
71
-	/** @var \OCP\Files\Node */
72
-	private $lockedNode;
73
-
74
-	/**
75
-	 * Share20OCS constructor.
76
-	 *
77
-	 * @param string $appName
78
-	 * @param IRequest $request
79
-	 * @param IManager $shareManager
80
-	 * @param IGroupManager $groupManager
81
-	 * @param IUserManager $userManager
82
-	 * @param IRootFolder $rootFolder
83
-	 * @param IURLGenerator $urlGenerator
84
-	 * @param string $userId
85
-	 * @param IL10N $l10n
86
-	 */
87
-	public function __construct(
88
-		$appName,
89
-		IRequest $request,
90
-		IManager $shareManager,
91
-		IGroupManager $groupManager,
92
-		IUserManager $userManager,
93
-		IRootFolder $rootFolder,
94
-		IURLGenerator $urlGenerator,
95
-		$userId,
96
-		IL10N $l10n
97
-	) {
98
-		parent::__construct($appName, $request);
99
-
100
-		$this->shareManager = $shareManager;
101
-		$this->userManager = $userManager;
102
-		$this->groupManager = $groupManager;
103
-		$this->request = $request;
104
-		$this->rootFolder = $rootFolder;
105
-		$this->urlGenerator = $urlGenerator;
106
-		$this->currentUser = $userId;
107
-		$this->l = $l10n;
108
-	}
109
-
110
-	/**
111
-	 * Convert an IShare to an array for OCS output
112
-	 *
113
-	 * @param \OCP\Share\IShare $share
114
-	 * @param Node|null $recipientNode
115
-	 * @return array
116
-	 * @throws NotFoundException In case the node can't be resolved.
117
-	 */
118
-	protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
119
-		$sharedBy = $this->userManager->get($share->getSharedBy());
120
-		$shareOwner = $this->userManager->get($share->getShareOwner());
121
-
122
-		$result = [
123
-			'id' => $share->getId(),
124
-			'share_type' => $share->getShareType(),
125
-			'uid_owner' => $share->getSharedBy(),
126
-			'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
127
-			'permissions' => $share->getPermissions(),
128
-			'stime' => $share->getShareTime()->getTimestamp(),
129
-			'parent' => null,
130
-			'expiration' => null,
131
-			'token' => null,
132
-			'uid_file_owner' => $share->getShareOwner(),
133
-			'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
134
-		];
135
-
136
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
137
-		if ($recipientNode) {
138
-			$node = $recipientNode;
139
-		} else {
140
-			$nodes = $userFolder->getById($share->getNodeId());
141
-
142
-			if (empty($nodes)) {
143
-				// fallback to guessing the path
144
-				$node = $userFolder->get($share->getTarget());
145
-				if ($node === null) {
146
-					throw new NotFoundException();
147
-				}
148
-			} else {
149
-				$node = $nodes[0];
150
-			}
151
-		}
152
-
153
-		$result['path'] = $userFolder->getRelativePath($node->getPath());
154
-		if ($node instanceOf \OCP\Files\Folder) {
155
-			$result['item_type'] = 'folder';
156
-		} else {
157
-			$result['item_type'] = 'file';
158
-		}
159
-		$result['mimetype'] = $node->getMimetype();
160
-		$result['storage_id'] = $node->getStorage()->getId();
161
-		$result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
162
-		$result['item_source'] = $node->getId();
163
-		$result['file_source'] = $node->getId();
164
-		$result['file_parent'] = $node->getParent()->getId();
165
-		$result['file_target'] = $share->getTarget();
166
-
167
-		$expiration = $share->getExpirationDate();
168
-		if ($expiration !== null) {
169
-			$result['expiration'] = $expiration->format('Y-m-d 00:00:00');
170
-		}
171
-
172
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
173
-			$sharedWith = $this->userManager->get($share->getSharedWith());
174
-			$result['share_with'] = $share->getSharedWith();
175
-			$result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
176
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
177
-			$group = $this->groupManager->get($share->getSharedWith());
178
-			$result['share_with'] = $share->getSharedWith();
179
-			$result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
180
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
181
-
182
-			$result['share_with'] = $share->getPassword();
183
-			$result['share_with_displayname'] = $share->getPassword();
184
-
185
-			$result['token'] = $share->getToken();
186
-			$result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
187
-
188
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
189
-			$result['share_with'] = $share->getSharedWith();
190
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
191
-			$result['token'] = $share->getToken();
192
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
193
-			$result['share_with'] = $share->getSharedWith();
194
-			$result['password'] = $share->getPassword();
195
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
196
-			$result['token'] = $share->getToken();
197
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
198
-			$result['share_with_displayname'] = $share->getSharedWith();
199
-			$result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
200
-		}
201
-
202
-
203
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
204
-
205
-		return $result;
206
-	}
207
-
208
-	/**
209
-	 * Check if one of the users address books knows the exact property, if
210
-	 * yes we return the full name.
211
-	 *
212
-	 * @param string $query
213
-	 * @param string $property
214
-	 * @return string
215
-	 */
216
-	private function getDisplayNameFromAddressBook($query, $property) {
217
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
218
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
219
-		foreach ($result as $r) {
220
-			foreach($r[$property] as $value) {
221
-				if ($value === $query) {
222
-					return $r['FN'];
223
-				}
224
-			}
225
-		}
226
-
227
-		return $query;
228
-	}
229
-
230
-	/**
231
-	 * Get a specific share by id
232
-	 *
233
-	 * @NoAdminRequired
234
-	 *
235
-	 * @param string $id
236
-	 * @return DataResponse
237
-	 * @throws OCSNotFoundException
238
-	 */
239
-	public function getShare($id) {
240
-		try {
241
-			$share = $this->getShareById($id);
242
-		} catch (ShareNotFound $e) {
243
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
244
-		}
245
-
246
-		if ($this->canAccessShare($share)) {
247
-			try {
248
-				$share = $this->formatShare($share);
249
-				return new DataResponse([$share]);
250
-			} catch (NotFoundException $e) {
251
-				//Fall trough
252
-			}
253
-		}
254
-
255
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
256
-	}
257
-
258
-	/**
259
-	 * Delete a share
260
-	 *
261
-	 * @NoAdminRequired
262
-	 *
263
-	 * @param string $id
264
-	 * @return DataResponse
265
-	 * @throws OCSNotFoundException
266
-	 */
267
-	public function deleteShare($id) {
268
-		try {
269
-			$share = $this->getShareById($id);
270
-		} catch (ShareNotFound $e) {
271
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
272
-		}
273
-
274
-		try {
275
-			$this->lock($share->getNode());
276
-		} catch (LockedException $e) {
277
-			throw new OCSNotFoundException($this->l->t('could not delete share'));
278
-		}
279
-
280
-		if (!$this->canAccessShare($share)) {
281
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
282
-		}
283
-
284
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
285
-			$share->getShareOwner() !== $this->currentUser &&
286
-			$share->getSharedBy() !== $this->currentUser) {
287
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
288
-		} else {
289
-			$this->shareManager->deleteShare($share);
290
-		}
291
-
292
-		return new DataResponse();
293
-	}
294
-
295
-	/**
296
-	 * @NoAdminRequired
297
-	 *
298
-	 * @param string $path
299
-	 * @param int $permissions
300
-	 * @param int $shareType
301
-	 * @param string $shareWith
302
-	 * @param string $publicUpload
303
-	 * @param string $password
304
-	 * @param string $expireDate
305
-	 *
306
-	 * @return DataResponse
307
-	 * @throws OCSNotFoundException
308
-	 * @throws OCSForbiddenException
309
-	 * @throws OCSBadRequestException
310
-	 * @throws OCSException
311
-	 *
312
-	 * @suppress PhanUndeclaredClassMethod
313
-	 */
314
-	public function createShare(
315
-		$path = null,
316
-		$permissions = \OCP\Constants::PERMISSION_ALL,
317
-		$shareType = -1,
318
-		$shareWith = null,
319
-		$publicUpload = 'false',
320
-		$password = '',
321
-		$expireDate = ''
322
-	) {
323
-		$share = $this->shareManager->newShare();
324
-
325
-		// Verify path
326
-		if ($path === null) {
327
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
328
-		}
329
-
330
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
331
-		try {
332
-			$path = $userFolder->get($path);
333
-		} catch (NotFoundException $e) {
334
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
335
-		}
336
-
337
-		$share->setNode($path);
338
-
339
-		try {
340
-			$this->lock($share->getNode());
341
-		} catch (LockedException $e) {
342
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
343
-		}
344
-
345
-		if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
346
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
347
-		}
348
-
349
-		// Shares always require read permissions
350
-		$permissions |= \OCP\Constants::PERMISSION_READ;
351
-
352
-		if ($path instanceof \OCP\Files\File) {
353
-			// Single file shares should never have delete or create permissions
354
-			$permissions &= ~\OCP\Constants::PERMISSION_DELETE;
355
-			$permissions &= ~\OCP\Constants::PERMISSION_CREATE;
356
-		}
357
-
358
-		/*
55
+    /** @var IManager */
56
+    private $shareManager;
57
+    /** @var IGroupManager */
58
+    private $groupManager;
59
+    /** @var IUserManager */
60
+    private $userManager;
61
+    /** @var IRequest */
62
+    protected $request;
63
+    /** @var IRootFolder */
64
+    private $rootFolder;
65
+    /** @var IURLGenerator */
66
+    private $urlGenerator;
67
+    /** @var string */
68
+    private $currentUser;
69
+    /** @var IL10N */
70
+    private $l;
71
+    /** @var \OCP\Files\Node */
72
+    private $lockedNode;
73
+
74
+    /**
75
+     * Share20OCS constructor.
76
+     *
77
+     * @param string $appName
78
+     * @param IRequest $request
79
+     * @param IManager $shareManager
80
+     * @param IGroupManager $groupManager
81
+     * @param IUserManager $userManager
82
+     * @param IRootFolder $rootFolder
83
+     * @param IURLGenerator $urlGenerator
84
+     * @param string $userId
85
+     * @param IL10N $l10n
86
+     */
87
+    public function __construct(
88
+        $appName,
89
+        IRequest $request,
90
+        IManager $shareManager,
91
+        IGroupManager $groupManager,
92
+        IUserManager $userManager,
93
+        IRootFolder $rootFolder,
94
+        IURLGenerator $urlGenerator,
95
+        $userId,
96
+        IL10N $l10n
97
+    ) {
98
+        parent::__construct($appName, $request);
99
+
100
+        $this->shareManager = $shareManager;
101
+        $this->userManager = $userManager;
102
+        $this->groupManager = $groupManager;
103
+        $this->request = $request;
104
+        $this->rootFolder = $rootFolder;
105
+        $this->urlGenerator = $urlGenerator;
106
+        $this->currentUser = $userId;
107
+        $this->l = $l10n;
108
+    }
109
+
110
+    /**
111
+     * Convert an IShare to an array for OCS output
112
+     *
113
+     * @param \OCP\Share\IShare $share
114
+     * @param Node|null $recipientNode
115
+     * @return array
116
+     * @throws NotFoundException In case the node can't be resolved.
117
+     */
118
+    protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
119
+        $sharedBy = $this->userManager->get($share->getSharedBy());
120
+        $shareOwner = $this->userManager->get($share->getShareOwner());
121
+
122
+        $result = [
123
+            'id' => $share->getId(),
124
+            'share_type' => $share->getShareType(),
125
+            'uid_owner' => $share->getSharedBy(),
126
+            'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
127
+            'permissions' => $share->getPermissions(),
128
+            'stime' => $share->getShareTime()->getTimestamp(),
129
+            'parent' => null,
130
+            'expiration' => null,
131
+            'token' => null,
132
+            'uid_file_owner' => $share->getShareOwner(),
133
+            'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
134
+        ];
135
+
136
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
137
+        if ($recipientNode) {
138
+            $node = $recipientNode;
139
+        } else {
140
+            $nodes = $userFolder->getById($share->getNodeId());
141
+
142
+            if (empty($nodes)) {
143
+                // fallback to guessing the path
144
+                $node = $userFolder->get($share->getTarget());
145
+                if ($node === null) {
146
+                    throw new NotFoundException();
147
+                }
148
+            } else {
149
+                $node = $nodes[0];
150
+            }
151
+        }
152
+
153
+        $result['path'] = $userFolder->getRelativePath($node->getPath());
154
+        if ($node instanceOf \OCP\Files\Folder) {
155
+            $result['item_type'] = 'folder';
156
+        } else {
157
+            $result['item_type'] = 'file';
158
+        }
159
+        $result['mimetype'] = $node->getMimetype();
160
+        $result['storage_id'] = $node->getStorage()->getId();
161
+        $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
162
+        $result['item_source'] = $node->getId();
163
+        $result['file_source'] = $node->getId();
164
+        $result['file_parent'] = $node->getParent()->getId();
165
+        $result['file_target'] = $share->getTarget();
166
+
167
+        $expiration = $share->getExpirationDate();
168
+        if ($expiration !== null) {
169
+            $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
170
+        }
171
+
172
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
173
+            $sharedWith = $this->userManager->get($share->getSharedWith());
174
+            $result['share_with'] = $share->getSharedWith();
175
+            $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
176
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
177
+            $group = $this->groupManager->get($share->getSharedWith());
178
+            $result['share_with'] = $share->getSharedWith();
179
+            $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
180
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
181
+
182
+            $result['share_with'] = $share->getPassword();
183
+            $result['share_with_displayname'] = $share->getPassword();
184
+
185
+            $result['token'] = $share->getToken();
186
+            $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
187
+
188
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
189
+            $result['share_with'] = $share->getSharedWith();
190
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
191
+            $result['token'] = $share->getToken();
192
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
193
+            $result['share_with'] = $share->getSharedWith();
194
+            $result['password'] = $share->getPassword();
195
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
196
+            $result['token'] = $share->getToken();
197
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
198
+            $result['share_with_displayname'] = $share->getSharedWith();
199
+            $result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
200
+        }
201
+
202
+
203
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
204
+
205
+        return $result;
206
+    }
207
+
208
+    /**
209
+     * Check if one of the users address books knows the exact property, if
210
+     * yes we return the full name.
211
+     *
212
+     * @param string $query
213
+     * @param string $property
214
+     * @return string
215
+     */
216
+    private function getDisplayNameFromAddressBook($query, $property) {
217
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
218
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
219
+        foreach ($result as $r) {
220
+            foreach($r[$property] as $value) {
221
+                if ($value === $query) {
222
+                    return $r['FN'];
223
+                }
224
+            }
225
+        }
226
+
227
+        return $query;
228
+    }
229
+
230
+    /**
231
+     * Get a specific share by id
232
+     *
233
+     * @NoAdminRequired
234
+     *
235
+     * @param string $id
236
+     * @return DataResponse
237
+     * @throws OCSNotFoundException
238
+     */
239
+    public function getShare($id) {
240
+        try {
241
+            $share = $this->getShareById($id);
242
+        } catch (ShareNotFound $e) {
243
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
244
+        }
245
+
246
+        if ($this->canAccessShare($share)) {
247
+            try {
248
+                $share = $this->formatShare($share);
249
+                return new DataResponse([$share]);
250
+            } catch (NotFoundException $e) {
251
+                //Fall trough
252
+            }
253
+        }
254
+
255
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
256
+    }
257
+
258
+    /**
259
+     * Delete a share
260
+     *
261
+     * @NoAdminRequired
262
+     *
263
+     * @param string $id
264
+     * @return DataResponse
265
+     * @throws OCSNotFoundException
266
+     */
267
+    public function deleteShare($id) {
268
+        try {
269
+            $share = $this->getShareById($id);
270
+        } catch (ShareNotFound $e) {
271
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
272
+        }
273
+
274
+        try {
275
+            $this->lock($share->getNode());
276
+        } catch (LockedException $e) {
277
+            throw new OCSNotFoundException($this->l->t('could not delete share'));
278
+        }
279
+
280
+        if (!$this->canAccessShare($share)) {
281
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
282
+        }
283
+
284
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
285
+            $share->getShareOwner() !== $this->currentUser &&
286
+            $share->getSharedBy() !== $this->currentUser) {
287
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
288
+        } else {
289
+            $this->shareManager->deleteShare($share);
290
+        }
291
+
292
+        return new DataResponse();
293
+    }
294
+
295
+    /**
296
+     * @NoAdminRequired
297
+     *
298
+     * @param string $path
299
+     * @param int $permissions
300
+     * @param int $shareType
301
+     * @param string $shareWith
302
+     * @param string $publicUpload
303
+     * @param string $password
304
+     * @param string $expireDate
305
+     *
306
+     * @return DataResponse
307
+     * @throws OCSNotFoundException
308
+     * @throws OCSForbiddenException
309
+     * @throws OCSBadRequestException
310
+     * @throws OCSException
311
+     *
312
+     * @suppress PhanUndeclaredClassMethod
313
+     */
314
+    public function createShare(
315
+        $path = null,
316
+        $permissions = \OCP\Constants::PERMISSION_ALL,
317
+        $shareType = -1,
318
+        $shareWith = null,
319
+        $publicUpload = 'false',
320
+        $password = '',
321
+        $expireDate = ''
322
+    ) {
323
+        $share = $this->shareManager->newShare();
324
+
325
+        // Verify path
326
+        if ($path === null) {
327
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
328
+        }
329
+
330
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
331
+        try {
332
+            $path = $userFolder->get($path);
333
+        } catch (NotFoundException $e) {
334
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
335
+        }
336
+
337
+        $share->setNode($path);
338
+
339
+        try {
340
+            $this->lock($share->getNode());
341
+        } catch (LockedException $e) {
342
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
343
+        }
344
+
345
+        if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
346
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
347
+        }
348
+
349
+        // Shares always require read permissions
350
+        $permissions |= \OCP\Constants::PERMISSION_READ;
351
+
352
+        if ($path instanceof \OCP\Files\File) {
353
+            // Single file shares should never have delete or create permissions
354
+            $permissions &= ~\OCP\Constants::PERMISSION_DELETE;
355
+            $permissions &= ~\OCP\Constants::PERMISSION_CREATE;
356
+        }
357
+
358
+        /*
359 359
 		 * Hack for https://github.com/owncloud/core/issues/22587
360 360
 		 * We check the permissions via webdav. But the permissions of the mount point
361 361
 		 * do not equal the share permissions. Here we fix that for federated mounts.
362 362
 		 */
363
-		if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
364
-			$permissions &= ~($permissions & ~$path->getPermissions());
365
-		}
366
-
367
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
368
-			// Valid user is required to share
369
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
370
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
371
-			}
372
-			$share->setSharedWith($shareWith);
373
-			$share->setPermissions($permissions);
374
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
375
-			if (!$this->shareManager->allowGroupSharing()) {
376
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
377
-			}
378
-
379
-			// Valid group is required to share
380
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
381
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
382
-			}
383
-			$share->setSharedWith($shareWith);
384
-			$share->setPermissions($permissions);
385
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
386
-			//Can we even share links?
387
-			if (!$this->shareManager->shareApiAllowLinks()) {
388
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
389
-			}
390
-
391
-			/*
363
+        if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
364
+            $permissions &= ~($permissions & ~$path->getPermissions());
365
+        }
366
+
367
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
368
+            // Valid user is required to share
369
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
370
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
371
+            }
372
+            $share->setSharedWith($shareWith);
373
+            $share->setPermissions($permissions);
374
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
375
+            if (!$this->shareManager->allowGroupSharing()) {
376
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
377
+            }
378
+
379
+            // Valid group is required to share
380
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
381
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
382
+            }
383
+            $share->setSharedWith($shareWith);
384
+            $share->setPermissions($permissions);
385
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
386
+            //Can we even share links?
387
+            if (!$this->shareManager->shareApiAllowLinks()) {
388
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
389
+            }
390
+
391
+            /*
392 392
 			 * For now we only allow 1 link share.
393 393
 			 * Return the existing link share if this is a duplicate
394 394
 			 */
395
-			$existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
396
-			if (!empty($existingShares)) {
397
-				return new DataResponse($this->formatShare($existingShares[0]));
398
-			}
399
-
400
-			if ($publicUpload === 'true') {
401
-				// Check if public upload is allowed
402
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
403
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
404
-				}
405
-
406
-				// Public upload can only be set for folders
407
-				if ($path instanceof \OCP\Files\File) {
408
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
409
-				}
410
-
411
-				$share->setPermissions(
412
-					\OCP\Constants::PERMISSION_READ |
413
-					\OCP\Constants::PERMISSION_CREATE |
414
-					\OCP\Constants::PERMISSION_UPDATE |
415
-					\OCP\Constants::PERMISSION_DELETE
416
-				);
417
-			} else {
418
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
419
-			}
420
-
421
-			// Set password
422
-			if ($password !== '') {
423
-				$share->setPassword($password);
424
-			}
425
-
426
-			//Expire date
427
-			if ($expireDate !== '') {
428
-				try {
429
-					$expireDate = $this->parseDate($expireDate);
430
-					$share->setExpirationDate($expireDate);
431
-				} catch (\Exception $e) {
432
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
433
-				}
434
-			}
435
-
436
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
437
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
438
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
439
-			}
440
-
441
-			$share->setSharedWith($shareWith);
442
-			$share->setPermissions($permissions);
443
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
444
-			if ($share->getNodeType() === 'file') {
445
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
446
-			} else {
447
-				$share->setPermissions(
448
-					\OCP\Constants::PERMISSION_READ |
449
-					\OCP\Constants::PERMISSION_CREATE |
450
-					\OCP\Constants::PERMISSION_UPDATE |
451
-					\OCP\Constants::PERMISSION_DELETE);
452
-			}
453
-			$share->setSharedWith($shareWith);
454
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
455
-			if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
456
-				throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
457
-			}
458
-
459
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
460
-
461
-			// Valid circle is required to share
462
-			if ($circle === null) {
463
-				throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
464
-			}
465
-			$share->setSharedWith($shareWith);
466
-			$share->setPermissions($permissions);
467
-		} else {
468
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
469
-		}
470
-
471
-		$share->setShareType($shareType);
472
-		$share->setSharedBy($this->currentUser);
473
-
474
-		try {
475
-			$share = $this->shareManager->createShare($share);
476
-		} catch (GenericShareException $e) {
477
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
478
-			throw new OCSException($e->getHint(), $code);
479
-		} catch (\Exception $e) {
480
-			throw new OCSForbiddenException($e->getMessage());
481
-		}
482
-
483
-		$output = $this->formatShare($share);
484
-
485
-		return new DataResponse($output);
486
-	}
487
-
488
-	/**
489
-	 * Sends again the e-mail notification for a share
490
-	 *
491
-	 * @NoAdminRequired
492
-	 *
493
-	 * @param string $id
494
-	 * @return DataResponse
495
-	 * @throws OCSNotFoundException
496
-	 */
497
-	public function resendMailNotification($id) {
498
-		try {
499
-			$share = $this->getShareById($id);
500
-		} catch (ShareNotFound $e) {
501
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist', $id));
502
-		}
503
-
504
-		if (!$this->canAccessShare($share)) {
505
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist', $id));
506
-		}
507
-
508
-		$this->shareManager->resendMailNotification($share);
509
-
510
-		return new DataResponse();
511
-	}
512
-
513
-	/**
514
-	 * @param \OCP\Files\File|\OCP\Files\Folder $node
515
-	 * @param boolean $includeTags
516
-	 * @return DataResponse
517
-	 */
518
-	private function getSharedWithMe($node = null, $includeTags) {
519
-
520
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
521
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
522
-		$circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
523
-
524
-		$shares = array_merge($userShares, $groupShares, $circleShares);
525
-
526
-		$shares = array_filter($shares, function (IShare $share) {
527
-			return $share->getShareOwner() !== $this->currentUser;
528
-		});
529
-
530
-		$formatted = [];
531
-		foreach ($shares as $share) {
532
-			if ($this->canAccessShare($share)) {
533
-				try {
534
-					$formatted[] = $this->formatShare($share);
535
-				} catch (NotFoundException $e) {
536
-					// Ignore this share
537
-				}
538
-			}
539
-		}
540
-
541
-		if ($includeTags) {
542
-			$formatted = Helper::populateTags($formatted, 'file_source');
543
-		}
544
-
545
-		return new DataResponse($formatted);
546
-	}
547
-
548
-	/**
549
-	 * @param \OCP\Files\Folder $folder
550
-	 * @return DataResponse
551
-	 * @throws OCSBadRequestException
552
-	 */
553
-	private function getSharesInDir($folder) {
554
-		if (!($folder instanceof \OCP\Files\Folder)) {
555
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
556
-		}
557
-
558
-		$nodes = $folder->getDirectoryListing();
559
-		/** @var \OCP\Share\IShare[] $shares */
560
-		$shares = [];
561
-		foreach ($nodes as $node) {
562
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
563
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
564
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
565
-			if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
566
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
567
-			}
568
-			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
569
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
570
-			}
571
-		}
572
-
573
-		$formatted = [];
574
-		foreach ($shares as $share) {
575
-			try {
576
-				$formatted[] = $this->formatShare($share);
577
-			} catch (NotFoundException $e) {
578
-				//Ignore this share
579
-			}
580
-		}
581
-
582
-		return new DataResponse($formatted);
583
-	}
584
-
585
-	/**
586
-	 * The getShares function.
587
-	 *
588
-	 * @NoAdminRequired
589
-	 *
590
-	 * @param string $shared_with_me
591
-	 * @param string $reshares
592
-	 * @param string $subfiles
593
-	 * @param string $path
594
-	 *
595
-	 * - Get shares by the current user
596
-	 * - Get shares by the current user and reshares (?reshares=true)
597
-	 * - Get shares with the current user (?shared_with_me=true)
598
-	 * - Get shares for a specific path (?path=...)
599
-	 * - Get all shares in a folder (?subfiles=true&path=..)
600
-	 *
601
-	 * @return DataResponse
602
-	 * @throws OCSNotFoundException
603
-	 */
604
-	public function getShares(
605
-		$shared_with_me = 'false',
606
-		$reshares = 'false',
607
-		$subfiles = 'false',
608
-		$path = null,
609
-		$include_tags = 'false'
610
-	) {
611
-
612
-		if ($path !== null) {
613
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
614
-			try {
615
-				$path = $userFolder->get($path);
616
-				$this->lock($path);
617
-			} catch (\OCP\Files\NotFoundException $e) {
618
-				throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
619
-			} catch (LockedException $e) {
620
-				throw new OCSNotFoundException($this->l->t('Could not lock path'));
621
-			}
622
-		}
623
-
624
-		if ($shared_with_me === 'true') {
625
-			$result = $this->getSharedWithMe($path, $include_tags);
626
-			return $result;
627
-		}
628
-
629
-		if ($subfiles === 'true') {
630
-			$result = $this->getSharesInDir($path);
631
-			return $result;
632
-		}
633
-
634
-		if ($reshares === 'true') {
635
-			$reshares = true;
636
-		} else {
637
-			$reshares = false;
638
-		}
639
-
640
-		// Get all shares
641
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
642
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
643
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
644
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
645
-			$mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
646
-		} else {
647
-			$mailShares = [];
648
-		}
649
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
650
-			$circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
651
-		} else {
652
-			$circleShares = [];
653
-		}
654
-
655
-		$shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
656
-
657
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
658
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
659
-			$shares = array_merge($shares, $federatedShares);
660
-		}
661
-
662
-		$formatted = [];
663
-		foreach ($shares as $share) {
664
-			try {
665
-				$formatted[] = $this->formatShare($share, $path);
666
-			} catch (NotFoundException $e) {
667
-				//Ignore share
668
-			}
669
-		}
670
-
671
-		if ($include_tags) {
672
-			$formatted = Helper::populateTags($formatted, 'file_source');
673
-		}
674
-
675
-		return new DataResponse($formatted);
676
-	}
677
-
678
-	/**
679
-	 * @NoAdminRequired
680
-	 *
681
-	 * @param int $id
682
-	 * @param int $permissions
683
-	 * @param string $password
684
-	 * @param string $publicUpload
685
-	 * @param string $expireDate
686
-	 * @return DataResponse
687
-	 * @throws OCSNotFoundException
688
-	 * @throws OCSBadRequestException
689
-	 * @throws OCSForbiddenException
690
-	 */
691
-	public function updateShare(
692
-		$id,
693
-		$permissions = null,
694
-		$password = null,
695
-		$publicUpload = null,
696
-		$expireDate = null
697
-	) {
698
-		try {
699
-			$share = $this->getShareById($id);
700
-		} catch (ShareNotFound $e) {
701
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
702
-		}
703
-
704
-		$this->lock($share->getNode());
705
-
706
-		if (!$this->canAccessShare($share, false)) {
707
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
708
-		}
709
-
710
-		if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
711
-			throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
712
-		}
713
-
714
-		/*
395
+            $existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
396
+            if (!empty($existingShares)) {
397
+                return new DataResponse($this->formatShare($existingShares[0]));
398
+            }
399
+
400
+            if ($publicUpload === 'true') {
401
+                // Check if public upload is allowed
402
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
403
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
404
+                }
405
+
406
+                // Public upload can only be set for folders
407
+                if ($path instanceof \OCP\Files\File) {
408
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
409
+                }
410
+
411
+                $share->setPermissions(
412
+                    \OCP\Constants::PERMISSION_READ |
413
+                    \OCP\Constants::PERMISSION_CREATE |
414
+                    \OCP\Constants::PERMISSION_UPDATE |
415
+                    \OCP\Constants::PERMISSION_DELETE
416
+                );
417
+            } else {
418
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
419
+            }
420
+
421
+            // Set password
422
+            if ($password !== '') {
423
+                $share->setPassword($password);
424
+            }
425
+
426
+            //Expire date
427
+            if ($expireDate !== '') {
428
+                try {
429
+                    $expireDate = $this->parseDate($expireDate);
430
+                    $share->setExpirationDate($expireDate);
431
+                } catch (\Exception $e) {
432
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
433
+                }
434
+            }
435
+
436
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
437
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
438
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
439
+            }
440
+
441
+            $share->setSharedWith($shareWith);
442
+            $share->setPermissions($permissions);
443
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
444
+            if ($share->getNodeType() === 'file') {
445
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
446
+            } else {
447
+                $share->setPermissions(
448
+                    \OCP\Constants::PERMISSION_READ |
449
+                    \OCP\Constants::PERMISSION_CREATE |
450
+                    \OCP\Constants::PERMISSION_UPDATE |
451
+                    \OCP\Constants::PERMISSION_DELETE);
452
+            }
453
+            $share->setSharedWith($shareWith);
454
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
455
+            if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
456
+                throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
457
+            }
458
+
459
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
460
+
461
+            // Valid circle is required to share
462
+            if ($circle === null) {
463
+                throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
464
+            }
465
+            $share->setSharedWith($shareWith);
466
+            $share->setPermissions($permissions);
467
+        } else {
468
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
469
+        }
470
+
471
+        $share->setShareType($shareType);
472
+        $share->setSharedBy($this->currentUser);
473
+
474
+        try {
475
+            $share = $this->shareManager->createShare($share);
476
+        } catch (GenericShareException $e) {
477
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
478
+            throw new OCSException($e->getHint(), $code);
479
+        } catch (\Exception $e) {
480
+            throw new OCSForbiddenException($e->getMessage());
481
+        }
482
+
483
+        $output = $this->formatShare($share);
484
+
485
+        return new DataResponse($output);
486
+    }
487
+
488
+    /**
489
+     * Sends again the e-mail notification for a share
490
+     *
491
+     * @NoAdminRequired
492
+     *
493
+     * @param string $id
494
+     * @return DataResponse
495
+     * @throws OCSNotFoundException
496
+     */
497
+    public function resendMailNotification($id) {
498
+        try {
499
+            $share = $this->getShareById($id);
500
+        } catch (ShareNotFound $e) {
501
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist', $id));
502
+        }
503
+
504
+        if (!$this->canAccessShare($share)) {
505
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist', $id));
506
+        }
507
+
508
+        $this->shareManager->resendMailNotification($share);
509
+
510
+        return new DataResponse();
511
+    }
512
+
513
+    /**
514
+     * @param \OCP\Files\File|\OCP\Files\Folder $node
515
+     * @param boolean $includeTags
516
+     * @return DataResponse
517
+     */
518
+    private function getSharedWithMe($node = null, $includeTags) {
519
+
520
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
521
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
522
+        $circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
523
+
524
+        $shares = array_merge($userShares, $groupShares, $circleShares);
525
+
526
+        $shares = array_filter($shares, function (IShare $share) {
527
+            return $share->getShareOwner() !== $this->currentUser;
528
+        });
529
+
530
+        $formatted = [];
531
+        foreach ($shares as $share) {
532
+            if ($this->canAccessShare($share)) {
533
+                try {
534
+                    $formatted[] = $this->formatShare($share);
535
+                } catch (NotFoundException $e) {
536
+                    // Ignore this share
537
+                }
538
+            }
539
+        }
540
+
541
+        if ($includeTags) {
542
+            $formatted = Helper::populateTags($formatted, 'file_source');
543
+        }
544
+
545
+        return new DataResponse($formatted);
546
+    }
547
+
548
+    /**
549
+     * @param \OCP\Files\Folder $folder
550
+     * @return DataResponse
551
+     * @throws OCSBadRequestException
552
+     */
553
+    private function getSharesInDir($folder) {
554
+        if (!($folder instanceof \OCP\Files\Folder)) {
555
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
556
+        }
557
+
558
+        $nodes = $folder->getDirectoryListing();
559
+        /** @var \OCP\Share\IShare[] $shares */
560
+        $shares = [];
561
+        foreach ($nodes as $node) {
562
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
563
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
564
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
565
+            if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
566
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
567
+            }
568
+            if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
569
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
570
+            }
571
+        }
572
+
573
+        $formatted = [];
574
+        foreach ($shares as $share) {
575
+            try {
576
+                $formatted[] = $this->formatShare($share);
577
+            } catch (NotFoundException $e) {
578
+                //Ignore this share
579
+            }
580
+        }
581
+
582
+        return new DataResponse($formatted);
583
+    }
584
+
585
+    /**
586
+     * The getShares function.
587
+     *
588
+     * @NoAdminRequired
589
+     *
590
+     * @param string $shared_with_me
591
+     * @param string $reshares
592
+     * @param string $subfiles
593
+     * @param string $path
594
+     *
595
+     * - Get shares by the current user
596
+     * - Get shares by the current user and reshares (?reshares=true)
597
+     * - Get shares with the current user (?shared_with_me=true)
598
+     * - Get shares for a specific path (?path=...)
599
+     * - Get all shares in a folder (?subfiles=true&path=..)
600
+     *
601
+     * @return DataResponse
602
+     * @throws OCSNotFoundException
603
+     */
604
+    public function getShares(
605
+        $shared_with_me = 'false',
606
+        $reshares = 'false',
607
+        $subfiles = 'false',
608
+        $path = null,
609
+        $include_tags = 'false'
610
+    ) {
611
+
612
+        if ($path !== null) {
613
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
614
+            try {
615
+                $path = $userFolder->get($path);
616
+                $this->lock($path);
617
+            } catch (\OCP\Files\NotFoundException $e) {
618
+                throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
619
+            } catch (LockedException $e) {
620
+                throw new OCSNotFoundException($this->l->t('Could not lock path'));
621
+            }
622
+        }
623
+
624
+        if ($shared_with_me === 'true') {
625
+            $result = $this->getSharedWithMe($path, $include_tags);
626
+            return $result;
627
+        }
628
+
629
+        if ($subfiles === 'true') {
630
+            $result = $this->getSharesInDir($path);
631
+            return $result;
632
+        }
633
+
634
+        if ($reshares === 'true') {
635
+            $reshares = true;
636
+        } else {
637
+            $reshares = false;
638
+        }
639
+
640
+        // Get all shares
641
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
642
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
643
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
644
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
645
+            $mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
646
+        } else {
647
+            $mailShares = [];
648
+        }
649
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
650
+            $circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
651
+        } else {
652
+            $circleShares = [];
653
+        }
654
+
655
+        $shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
656
+
657
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
658
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
659
+            $shares = array_merge($shares, $federatedShares);
660
+        }
661
+
662
+        $formatted = [];
663
+        foreach ($shares as $share) {
664
+            try {
665
+                $formatted[] = $this->formatShare($share, $path);
666
+            } catch (NotFoundException $e) {
667
+                //Ignore share
668
+            }
669
+        }
670
+
671
+        if ($include_tags) {
672
+            $formatted = Helper::populateTags($formatted, 'file_source');
673
+        }
674
+
675
+        return new DataResponse($formatted);
676
+    }
677
+
678
+    /**
679
+     * @NoAdminRequired
680
+     *
681
+     * @param int $id
682
+     * @param int $permissions
683
+     * @param string $password
684
+     * @param string $publicUpload
685
+     * @param string $expireDate
686
+     * @return DataResponse
687
+     * @throws OCSNotFoundException
688
+     * @throws OCSBadRequestException
689
+     * @throws OCSForbiddenException
690
+     */
691
+    public function updateShare(
692
+        $id,
693
+        $permissions = null,
694
+        $password = null,
695
+        $publicUpload = null,
696
+        $expireDate = null
697
+    ) {
698
+        try {
699
+            $share = $this->getShareById($id);
700
+        } catch (ShareNotFound $e) {
701
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
702
+        }
703
+
704
+        $this->lock($share->getNode());
705
+
706
+        if (!$this->canAccessShare($share, false)) {
707
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
708
+        }
709
+
710
+        if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
711
+            throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
712
+        }
713
+
714
+        /*
715 715
 		 * expirationdate, password and publicUpload only make sense for link shares
716 716
 		 */
717
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
718
-
719
-			$newPermissions = null;
720
-			if ($publicUpload === 'true') {
721
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
722
-			} else if ($publicUpload === 'false') {
723
-				$newPermissions = \OCP\Constants::PERMISSION_READ;
724
-			}
725
-
726
-			if ($permissions !== null) {
727
-				$newPermissions = (int)$permissions;
728
-			}
729
-
730
-			if ($newPermissions !== null &&
731
-				!in_array($newPermissions, [
732
-					\OCP\Constants::PERMISSION_READ,
733
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
734
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
735
-					\OCP\Constants::PERMISSION_CREATE, // hidden file list
736
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
737
-				])
738
-			) {
739
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
740
-			}
741
-
742
-			if (
743
-				// legacy
744
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
745
-				// correct
746
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
747
-			) {
748
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
749
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
750
-				}
751
-
752
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
753
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
754
-				}
755
-
756
-				// normalize to correct public upload permissions
757
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
758
-			}
759
-
760
-			if ($newPermissions !== null) {
761
-				$share->setPermissions($newPermissions);
762
-				$permissions = $newPermissions;
763
-			}
764
-
765
-			if ($expireDate === '') {
766
-				$share->setExpirationDate(null);
767
-			} else if ($expireDate !== null) {
768
-				try {
769
-					$expireDate = $this->parseDate($expireDate);
770
-				} catch (\Exception $e) {
771
-					throw new OCSBadRequestException($e->getMessage());
772
-				}
773
-				$share->setExpirationDate($expireDate);
774
-			}
775
-
776
-			if ($password === '') {
777
-				$share->setPassword(null);
778
-			} else if ($password !== null) {
779
-				$share->setPassword($password);
780
-			}
781
-
782
-		} else {
783
-			if ($permissions !== null) {
784
-				$permissions = (int)$permissions;
785
-				$share->setPermissions($permissions);
786
-			}
787
-
788
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
789
-				if ($password === '') {
790
-					$share->setPassword(null);
791
-				} else if ($password !== null) {
792
-					$share->setPassword($password);
793
-				}
794
-			}
795
-
796
-			if ($expireDate === '') {
797
-				$share->setExpirationDate(null);
798
-			} else if ($expireDate !== null) {
799
-				try {
800
-					$expireDate = $this->parseDate($expireDate);
801
-				} catch (\Exception $e) {
802
-					throw new OCSBadRequestException($e->getMessage());
803
-				}
804
-				$share->setExpirationDate($expireDate);
805
-			}
806
-
807
-		}
808
-
809
-		if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
810
-			/* Check if this is an incomming share */
811
-			$incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
812
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
813
-
814
-			/** @var \OCP\Share\IShare[] $incomingShares */
815
-			if (!empty($incomingShares)) {
816
-				$maxPermissions = 0;
817
-				foreach ($incomingShares as $incomingShare) {
818
-					$maxPermissions |= $incomingShare->getPermissions();
819
-				}
820
-
821
-				if ($share->getPermissions() & ~$maxPermissions) {
822
-					throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
823
-				}
824
-			}
825
-		}
826
-
827
-
828
-		try {
829
-			$share = $this->shareManager->updateShare($share);
830
-		} catch (\Exception $e) {
831
-			throw new OCSBadRequestException($e->getMessage());
832
-		}
833
-
834
-		return new DataResponse($this->formatShare($share));
835
-	}
836
-
837
-	/**
838
-	 * @param \OCP\Share\IShare $share
839
-	 * @return bool
840
-	 */
841
-	protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
842
-		// A file with permissions 0 can't be accessed by us. So Don't show it
843
-		if ($share->getPermissions() === 0) {
844
-			return false;
845
-		}
846
-
847
-		// Owner of the file and the sharer of the file can always get share
848
-		if ($share->getShareOwner() === $this->currentUser ||
849
-			$share->getSharedBy() === $this->currentUser
850
-		) {
851
-			return true;
852
-		}
853
-
854
-		// If the share is shared with you (or a group you are a member of)
855
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
856
-			$share->getSharedWith() === $this->currentUser
857
-		) {
858
-			return true;
859
-		}
860
-
861
-		if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
862
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
863
-			$user = $this->userManager->get($this->currentUser);
864
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
865
-				return true;
866
-			}
867
-		}
868
-
869
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
870
-			// TODO: have a sanity check like above?
871
-			return true;
872
-		}
873
-
874
-		return false;
875
-	}
876
-
877
-	/**
878
-	 * Make sure that the passed date is valid ISO 8601
879
-	 * So YYYY-MM-DD
880
-	 * If not throw an exception
881
-	 *
882
-	 * @param string $expireDate
883
-	 *
884
-	 * @throws \Exception
885
-	 * @return \DateTime
886
-	 */
887
-	private function parseDate($expireDate) {
888
-		try {
889
-			$date = new \DateTime($expireDate);
890
-		} catch (\Exception $e) {
891
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
892
-		}
893
-
894
-		if ($date === false) {
895
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
896
-		}
897
-
898
-		$date->setTime(0, 0, 0);
899
-
900
-		return $date;
901
-	}
902
-
903
-	/**
904
-	 * Since we have multiple providers but the OCS Share API v1 does
905
-	 * not support this we need to check all backends.
906
-	 *
907
-	 * @param string $id
908
-	 * @return \OCP\Share\IShare
909
-	 * @throws ShareNotFound
910
-	 */
911
-	private function getShareById($id) {
912
-		$share = null;
913
-
914
-		// First check if it is an internal share.
915
-		try {
916
-			$share = $this->shareManager->getShareById('ocinternal:' . $id);
917
-			return $share;
918
-		} catch (ShareNotFound $e) {
919
-			// Do nothing, just try the other share type
920
-		}
921
-
922
-
923
-		try {
924
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
925
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id);
926
-				return $share;
927
-			}
928
-		} catch (ShareNotFound $e) {
929
-			// Do nothing, just try the other share type
930
-		}
931
-
932
-		try {
933
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
934
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id);
935
-				return $share;
936
-			}
937
-		} catch (ShareNotFound $e) {
938
-			// Do nothing, just try the other share type
939
-		}
940
-
941
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
942
-			throw new ShareNotFound();
943
-		}
944
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
945
-
946
-		return $share;
947
-	}
948
-
949
-	/**
950
-	 * Lock a Node
951
-	 *
952
-	 * @param \OCP\Files\Node $node
953
-	 */
954
-	private function lock(\OCP\Files\Node $node) {
955
-		$node->lock(ILockingProvider::LOCK_SHARED);
956
-		$this->lockedNode = $node;
957
-	}
958
-
959
-	/**
960
-	 * Cleanup the remaining locks
961
-	 */
962
-	public function cleanup() {
963
-		if ($this->lockedNode !== null) {
964
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
965
-		}
966
-	}
717
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
718
+
719
+            $newPermissions = null;
720
+            if ($publicUpload === 'true') {
721
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
722
+            } else if ($publicUpload === 'false') {
723
+                $newPermissions = \OCP\Constants::PERMISSION_READ;
724
+            }
725
+
726
+            if ($permissions !== null) {
727
+                $newPermissions = (int)$permissions;
728
+            }
729
+
730
+            if ($newPermissions !== null &&
731
+                !in_array($newPermissions, [
732
+                    \OCP\Constants::PERMISSION_READ,
733
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
734
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
735
+                    \OCP\Constants::PERMISSION_CREATE, // hidden file list
736
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
737
+                ])
738
+            ) {
739
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
740
+            }
741
+
742
+            if (
743
+                // legacy
744
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
745
+                // correct
746
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
747
+            ) {
748
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
749
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
750
+                }
751
+
752
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
753
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
754
+                }
755
+
756
+                // normalize to correct public upload permissions
757
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
758
+            }
759
+
760
+            if ($newPermissions !== null) {
761
+                $share->setPermissions($newPermissions);
762
+                $permissions = $newPermissions;
763
+            }
764
+
765
+            if ($expireDate === '') {
766
+                $share->setExpirationDate(null);
767
+            } else if ($expireDate !== null) {
768
+                try {
769
+                    $expireDate = $this->parseDate($expireDate);
770
+                } catch (\Exception $e) {
771
+                    throw new OCSBadRequestException($e->getMessage());
772
+                }
773
+                $share->setExpirationDate($expireDate);
774
+            }
775
+
776
+            if ($password === '') {
777
+                $share->setPassword(null);
778
+            } else if ($password !== null) {
779
+                $share->setPassword($password);
780
+            }
781
+
782
+        } else {
783
+            if ($permissions !== null) {
784
+                $permissions = (int)$permissions;
785
+                $share->setPermissions($permissions);
786
+            }
787
+
788
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
789
+                if ($password === '') {
790
+                    $share->setPassword(null);
791
+                } else if ($password !== null) {
792
+                    $share->setPassword($password);
793
+                }
794
+            }
795
+
796
+            if ($expireDate === '') {
797
+                $share->setExpirationDate(null);
798
+            } else if ($expireDate !== null) {
799
+                try {
800
+                    $expireDate = $this->parseDate($expireDate);
801
+                } catch (\Exception $e) {
802
+                    throw new OCSBadRequestException($e->getMessage());
803
+                }
804
+                $share->setExpirationDate($expireDate);
805
+            }
806
+
807
+        }
808
+
809
+        if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
810
+            /* Check if this is an incomming share */
811
+            $incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
812
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
813
+
814
+            /** @var \OCP\Share\IShare[] $incomingShares */
815
+            if (!empty($incomingShares)) {
816
+                $maxPermissions = 0;
817
+                foreach ($incomingShares as $incomingShare) {
818
+                    $maxPermissions |= $incomingShare->getPermissions();
819
+                }
820
+
821
+                if ($share->getPermissions() & ~$maxPermissions) {
822
+                    throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
823
+                }
824
+            }
825
+        }
826
+
827
+
828
+        try {
829
+            $share = $this->shareManager->updateShare($share);
830
+        } catch (\Exception $e) {
831
+            throw new OCSBadRequestException($e->getMessage());
832
+        }
833
+
834
+        return new DataResponse($this->formatShare($share));
835
+    }
836
+
837
+    /**
838
+     * @param \OCP\Share\IShare $share
839
+     * @return bool
840
+     */
841
+    protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
842
+        // A file with permissions 0 can't be accessed by us. So Don't show it
843
+        if ($share->getPermissions() === 0) {
844
+            return false;
845
+        }
846
+
847
+        // Owner of the file and the sharer of the file can always get share
848
+        if ($share->getShareOwner() === $this->currentUser ||
849
+            $share->getSharedBy() === $this->currentUser
850
+        ) {
851
+            return true;
852
+        }
853
+
854
+        // If the share is shared with you (or a group you are a member of)
855
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
856
+            $share->getSharedWith() === $this->currentUser
857
+        ) {
858
+            return true;
859
+        }
860
+
861
+        if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
862
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
863
+            $user = $this->userManager->get($this->currentUser);
864
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
865
+                return true;
866
+            }
867
+        }
868
+
869
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
870
+            // TODO: have a sanity check like above?
871
+            return true;
872
+        }
873
+
874
+        return false;
875
+    }
876
+
877
+    /**
878
+     * Make sure that the passed date is valid ISO 8601
879
+     * So YYYY-MM-DD
880
+     * If not throw an exception
881
+     *
882
+     * @param string $expireDate
883
+     *
884
+     * @throws \Exception
885
+     * @return \DateTime
886
+     */
887
+    private function parseDate($expireDate) {
888
+        try {
889
+            $date = new \DateTime($expireDate);
890
+        } catch (\Exception $e) {
891
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
892
+        }
893
+
894
+        if ($date === false) {
895
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
896
+        }
897
+
898
+        $date->setTime(0, 0, 0);
899
+
900
+        return $date;
901
+    }
902
+
903
+    /**
904
+     * Since we have multiple providers but the OCS Share API v1 does
905
+     * not support this we need to check all backends.
906
+     *
907
+     * @param string $id
908
+     * @return \OCP\Share\IShare
909
+     * @throws ShareNotFound
910
+     */
911
+    private function getShareById($id) {
912
+        $share = null;
913
+
914
+        // First check if it is an internal share.
915
+        try {
916
+            $share = $this->shareManager->getShareById('ocinternal:' . $id);
917
+            return $share;
918
+        } catch (ShareNotFound $e) {
919
+            // Do nothing, just try the other share type
920
+        }
921
+
922
+
923
+        try {
924
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
925
+                $share = $this->shareManager->getShareById('ocCircleShare:' . $id);
926
+                return $share;
927
+            }
928
+        } catch (ShareNotFound $e) {
929
+            // Do nothing, just try the other share type
930
+        }
931
+
932
+        try {
933
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
934
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id);
935
+                return $share;
936
+            }
937
+        } catch (ShareNotFound $e) {
938
+            // Do nothing, just try the other share type
939
+        }
940
+
941
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
942
+            throw new ShareNotFound();
943
+        }
944
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
945
+
946
+        return $share;
947
+    }
948
+
949
+    /**
950
+     * Lock a Node
951
+     *
952
+     * @param \OCP\Files\Node $node
953
+     */
954
+    private function lock(\OCP\Files\Node $node) {
955
+        $node->lock(ILockingProvider::LOCK_SHARED);
956
+        $this->lockedNode = $node;
957
+    }
958
+
959
+    /**
960
+     * Cleanup the remaining locks
961
+     */
962
+    public function cleanup() {
963
+        if ($this->lockedNode !== null) {
964
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
965
+        }
966
+    }
967 967
 }
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 2 patches
Indentation   +334 added lines, -334 removed lines patch added patch discarded remove patch
@@ -58,339 +58,339 @@
 block discarded – undo
58 58
  * @package OC\Group
59 59
  */
60 60
 class Manager extends PublicEmitter implements IGroupManager {
61
-	/**
62
-	 * @var GroupInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\Manager $userManager
68
-	 */
69
-	private $userManager;
70
-
71
-	/**
72
-	 * @var \OC\Group\Group[]
73
-	 */
74
-	private $cachedGroups = array();
75
-
76
-	/**
77
-	 * @var \OC\Group\Group[][]
78
-	 */
79
-	private $cachedUserGroups = array();
80
-
81
-	/** @var \OC\SubAdmin */
82
-	private $subAdmin = null;
83
-
84
-	/** @var ILogger */
85
-	private $logger;
86
-
87
-	/**
88
-	 * @param \OC\User\Manager $userManager
89
-	 * @param ILogger $logger
90
-	 */
91
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
-		$this->userManager = $userManager;
93
-		$this->logger = $logger;
94
-		$cachedGroups = & $this->cachedGroups;
95
-		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
-			/**
98
-			 * @var \OC\Group\Group $group
99
-			 */
100
-			unset($cachedGroups[$group->getGID()]);
101
-			$cachedUserGroups = array();
102
-		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
-			/**
105
-			 * @var \OC\Group\Group $group
106
-			 */
107
-			$cachedUserGroups = array();
108
-		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
-			/**
111
-			 * @var \OC\Group\Group $group
112
-			 */
113
-			$cachedUserGroups = array();
114
-		});
115
-	}
116
-
117
-	/**
118
-	 * Checks whether a given backend is used
119
-	 *
120
-	 * @param string $backendClass Full classname including complete namespace
121
-	 * @return bool
122
-	 */
123
-	public function isBackendUsed($backendClass) {
124
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
125
-
126
-		foreach ($this->backends as $backend) {
127
-			if (strtolower(get_class($backend)) === $backendClass) {
128
-				return true;
129
-			}
130
-		}
131
-
132
-		return false;
133
-	}
134
-
135
-	/**
136
-	 * @param \OCP\GroupInterface $backend
137
-	 */
138
-	public function addBackend($backend) {
139
-		$this->backends[] = $backend;
140
-		$this->clearCaches();
141
-	}
142
-
143
-	public function clearBackends() {
144
-		$this->backends = array();
145
-		$this->clearCaches();
146
-	}
61
+    /**
62
+     * @var GroupInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\Manager $userManager
68
+     */
69
+    private $userManager;
70
+
71
+    /**
72
+     * @var \OC\Group\Group[]
73
+     */
74
+    private $cachedGroups = array();
75
+
76
+    /**
77
+     * @var \OC\Group\Group[][]
78
+     */
79
+    private $cachedUserGroups = array();
80
+
81
+    /** @var \OC\SubAdmin */
82
+    private $subAdmin = null;
83
+
84
+    /** @var ILogger */
85
+    private $logger;
86
+
87
+    /**
88
+     * @param \OC\User\Manager $userManager
89
+     * @param ILogger $logger
90
+     */
91
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
+        $this->userManager = $userManager;
93
+        $this->logger = $logger;
94
+        $cachedGroups = & $this->cachedGroups;
95
+        $cachedUserGroups = & $this->cachedUserGroups;
96
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
+            /**
98
+             * @var \OC\Group\Group $group
99
+             */
100
+            unset($cachedGroups[$group->getGID()]);
101
+            $cachedUserGroups = array();
102
+        });
103
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
+            /**
105
+             * @var \OC\Group\Group $group
106
+             */
107
+            $cachedUserGroups = array();
108
+        });
109
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
+            /**
111
+             * @var \OC\Group\Group $group
112
+             */
113
+            $cachedUserGroups = array();
114
+        });
115
+    }
116
+
117
+    /**
118
+     * Checks whether a given backend is used
119
+     *
120
+     * @param string $backendClass Full classname including complete namespace
121
+     * @return bool
122
+     */
123
+    public function isBackendUsed($backendClass) {
124
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
125
+
126
+        foreach ($this->backends as $backend) {
127
+            if (strtolower(get_class($backend)) === $backendClass) {
128
+                return true;
129
+            }
130
+        }
131
+
132
+        return false;
133
+    }
134
+
135
+    /**
136
+     * @param \OCP\GroupInterface $backend
137
+     */
138
+    public function addBackend($backend) {
139
+        $this->backends[] = $backend;
140
+        $this->clearCaches();
141
+    }
142
+
143
+    public function clearBackends() {
144
+        $this->backends = array();
145
+        $this->clearCaches();
146
+    }
147 147
 	
148
-	protected function clearCaches() {
149
-		$this->cachedGroups = array();
150
-		$this->cachedUserGroups = array();
151
-	}
152
-
153
-	/**
154
-	 * @param string $gid
155
-	 * @return \OC\Group\Group
156
-	 */
157
-	public function get($gid) {
158
-		if (isset($this->cachedGroups[$gid])) {
159
-			return $this->cachedGroups[$gid];
160
-		}
161
-		return $this->getGroupObject($gid);
162
-	}
163
-
164
-	/**
165
-	 * @param string $gid
166
-	 * @param string $displayName
167
-	 * @return \OCP\IGroup
168
-	 */
169
-	protected function getGroupObject($gid, $displayName = null) {
170
-		$backends = array();
171
-		foreach ($this->backends as $backend) {
172
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
-				$groupData = $backend->getGroupDetails($gid);
174
-				if (is_array($groupData)) {
175
-					// take the display name from the first backend that has a non-null one
176
-					if (is_null($displayName) && isset($groupData['displayName'])) {
177
-						$displayName = $groupData['displayName'];
178
-					}
179
-					$backends[] = $backend;
180
-				}
181
-			} else if ($backend->groupExists($gid)) {
182
-				$backends[] = $backend;
183
-			}
184
-		}
185
-		if (count($backends) === 0) {
186
-			return null;
187
-		}
188
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
-		return $this->cachedGroups[$gid];
190
-	}
191
-
192
-	/**
193
-	 * @param string $gid
194
-	 * @return bool
195
-	 */
196
-	public function groupExists($gid) {
197
-		return $this->get($gid) instanceof IGroup;
198
-	}
199
-
200
-	/**
201
-	 * @param string $gid
202
-	 * @return \OC\Group\Group
203
-	 */
204
-	public function createGroup($gid) {
205
-		if ($gid === '' || $gid === null) {
206
-			return false;
207
-		} else if ($group = $this->get($gid)) {
208
-			return $group;
209
-		} else {
210
-			$this->emit('\OC\Group', 'preCreate', array($gid));
211
-			foreach ($this->backends as $backend) {
212
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
-					$backend->createGroup($gid);
214
-					$group = $this->getGroupObject($gid);
215
-					$this->emit('\OC\Group', 'postCreate', array($group));
216
-					return $group;
217
-				}
218
-			}
219
-			return null;
220
-		}
221
-	}
222
-
223
-	/**
224
-	 * @param string $search
225
-	 * @param int $limit
226
-	 * @param int $offset
227
-	 * @return \OC\Group\Group[]
228
-	 */
229
-	public function search($search, $limit = null, $offset = null) {
230
-		$groups = array();
231
-		foreach ($this->backends as $backend) {
232
-			$groupIds = $backend->getGroups($search, $limit, $offset);
233
-			foreach ($groupIds as $groupId) {
234
-				$aGroup = $this->get($groupId);
235
-				if ($aGroup instanceof IGroup) {
236
-					$groups[$groupId] = $aGroup;
237
-				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
-				}
240
-			}
241
-			if (!is_null($limit) and $limit <= 0) {
242
-				return array_values($groups);
243
-			}
244
-		}
245
-		return array_values($groups);
246
-	}
247
-
248
-	/**
249
-	 * @param IUser|null $user
250
-	 * @return \OC\Group\Group[]
251
-	 */
252
-	public function getUserGroups(IUser $user= null) {
253
-		if (!$user instanceof IUser) {
254
-			return [];
255
-		}
256
-		return $this->getUserIdGroups($user->getUID());
257
-	}
258
-
259
-	/**
260
-	 * @param string $uid the user id
261
-	 * @return \OC\Group\Group[]
262
-	 */
263
-	public function getUserIdGroups($uid) {
264
-		if (isset($this->cachedUserGroups[$uid])) {
265
-			return $this->cachedUserGroups[$uid];
266
-		}
267
-		$groups = array();
268
-		foreach ($this->backends as $backend) {
269
-			$groupIds = $backend->getUserGroups($uid);
270
-			if (is_array($groupIds)) {
271
-				foreach ($groupIds as $groupId) {
272
-					$aGroup = $this->get($groupId);
273
-					if ($aGroup instanceof IGroup) {
274
-						$groups[$groupId] = $aGroup;
275
-					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
-					}
278
-				}
279
-			}
280
-		}
281
-		$this->cachedUserGroups[$uid] = $groups;
282
-		return $this->cachedUserGroups[$uid];
283
-	}
284
-
285
-	/**
286
-	 * Checks if a userId is in the admin group
287
-	 * @param string $userId
288
-	 * @return bool if admin
289
-	 */
290
-	public function isAdmin($userId) {
291
-		return $this->isInGroup($userId, 'admin');
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in a group
296
-	 * @param string $userId
297
-	 * @param string $group
298
-	 * @return bool if in group
299
-	 */
300
-	public function isInGroup($userId, $group) {
301
-		return array_key_exists($group, $this->getUserIdGroups($userId));
302
-	}
303
-
304
-	/**
305
-	 * get a list of group ids for a user
306
-	 * @param IUser $user
307
-	 * @return array with group ids
308
-	 */
309
-	public function getUserGroupIds(IUser $user) {
310
-		return array_map(function($value) {
311
-			return (string) $value;
312
-		}, array_keys($this->getUserGroups($user)));
313
-	}
314
-
315
-	/**
316
-	 * get a list of all users in a group
317
-	 * @param string $gid
318
-	 * @param string $search
319
-	 * @param int $limit
320
-	 * @param int $offset
321
-	 * @return array an array of users (value) and user ids (key)
322
-	 */
323
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
-		$group = $this->get($gid);
325
-		if(is_null($group)) {
326
-			return array();
327
-		}
328
-
329
-		$search = trim($search);
330
-		$groupUsers = array();
331
-
332
-		if(!empty($search)) {
333
-			// only user backends have the capability to do a complex search for users
334
-			$searchOffset = 0;
335
-			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
337
-				$searchLimit = 500;
338
-			}
339
-
340
-			do {
341
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
345
-					}
346
-				}
347
-				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
-
350
-			if($limit === -1) {
351
-				$groupUsers = array_slice($groupUsers, $offset);
352
-			} else {
353
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
354
-			}
355
-		} else {
356
-			$groupUsers = $group->searchUsers('', $limit, $offset);
357
-		}
358
-
359
-		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
361
-			$matchingUsers[$groupUser->getUID()] = $groupUser;
362
-		}
363
-		return $matchingUsers;
364
-	}
365
-
366
-	/**
367
-	 * get a list of all display names in a group
368
-	 * @param string $gid
369
-	 * @param string $search
370
-	 * @param int $limit
371
-	 * @param int $offset
372
-	 * @return array an array of display names (value) and user ids (key)
373
-	 */
374
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
375
-		$matchingUsers = array();
376
-		foreach($this->usersInGroup($gid, $search, $limit, $offset) as $uid => $user) {
377
-			$matchingUsers[$uid] = $user->getDisplayName();
378
-		}
379
-		return $matchingUsers;
380
-	}
381
-
382
-	/**
383
-	 * @return \OC\SubAdmin
384
-	 */
385
-	public function getSubAdmin() {
386
-		if (!$this->subAdmin) {
387
-			$this->subAdmin = new \OC\SubAdmin(
388
-				$this->userManager,
389
-				$this,
390
-				\OC::$server->getDatabaseConnection()
391
-			);
392
-		}
393
-
394
-		return $this->subAdmin;
395
-	}
148
+    protected function clearCaches() {
149
+        $this->cachedGroups = array();
150
+        $this->cachedUserGroups = array();
151
+    }
152
+
153
+    /**
154
+     * @param string $gid
155
+     * @return \OC\Group\Group
156
+     */
157
+    public function get($gid) {
158
+        if (isset($this->cachedGroups[$gid])) {
159
+            return $this->cachedGroups[$gid];
160
+        }
161
+        return $this->getGroupObject($gid);
162
+    }
163
+
164
+    /**
165
+     * @param string $gid
166
+     * @param string $displayName
167
+     * @return \OCP\IGroup
168
+     */
169
+    protected function getGroupObject($gid, $displayName = null) {
170
+        $backends = array();
171
+        foreach ($this->backends as $backend) {
172
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
+                $groupData = $backend->getGroupDetails($gid);
174
+                if (is_array($groupData)) {
175
+                    // take the display name from the first backend that has a non-null one
176
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
177
+                        $displayName = $groupData['displayName'];
178
+                    }
179
+                    $backends[] = $backend;
180
+                }
181
+            } else if ($backend->groupExists($gid)) {
182
+                $backends[] = $backend;
183
+            }
184
+        }
185
+        if (count($backends) === 0) {
186
+            return null;
187
+        }
188
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
+        return $this->cachedGroups[$gid];
190
+    }
191
+
192
+    /**
193
+     * @param string $gid
194
+     * @return bool
195
+     */
196
+    public function groupExists($gid) {
197
+        return $this->get($gid) instanceof IGroup;
198
+    }
199
+
200
+    /**
201
+     * @param string $gid
202
+     * @return \OC\Group\Group
203
+     */
204
+    public function createGroup($gid) {
205
+        if ($gid === '' || $gid === null) {
206
+            return false;
207
+        } else if ($group = $this->get($gid)) {
208
+            return $group;
209
+        } else {
210
+            $this->emit('\OC\Group', 'preCreate', array($gid));
211
+            foreach ($this->backends as $backend) {
212
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
+                    $backend->createGroup($gid);
214
+                    $group = $this->getGroupObject($gid);
215
+                    $this->emit('\OC\Group', 'postCreate', array($group));
216
+                    return $group;
217
+                }
218
+            }
219
+            return null;
220
+        }
221
+    }
222
+
223
+    /**
224
+     * @param string $search
225
+     * @param int $limit
226
+     * @param int $offset
227
+     * @return \OC\Group\Group[]
228
+     */
229
+    public function search($search, $limit = null, $offset = null) {
230
+        $groups = array();
231
+        foreach ($this->backends as $backend) {
232
+            $groupIds = $backend->getGroups($search, $limit, $offset);
233
+            foreach ($groupIds as $groupId) {
234
+                $aGroup = $this->get($groupId);
235
+                if ($aGroup instanceof IGroup) {
236
+                    $groups[$groupId] = $aGroup;
237
+                } else {
238
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
+                }
240
+            }
241
+            if (!is_null($limit) and $limit <= 0) {
242
+                return array_values($groups);
243
+            }
244
+        }
245
+        return array_values($groups);
246
+    }
247
+
248
+    /**
249
+     * @param IUser|null $user
250
+     * @return \OC\Group\Group[]
251
+     */
252
+    public function getUserGroups(IUser $user= null) {
253
+        if (!$user instanceof IUser) {
254
+            return [];
255
+        }
256
+        return $this->getUserIdGroups($user->getUID());
257
+    }
258
+
259
+    /**
260
+     * @param string $uid the user id
261
+     * @return \OC\Group\Group[]
262
+     */
263
+    public function getUserIdGroups($uid) {
264
+        if (isset($this->cachedUserGroups[$uid])) {
265
+            return $this->cachedUserGroups[$uid];
266
+        }
267
+        $groups = array();
268
+        foreach ($this->backends as $backend) {
269
+            $groupIds = $backend->getUserGroups($uid);
270
+            if (is_array($groupIds)) {
271
+                foreach ($groupIds as $groupId) {
272
+                    $aGroup = $this->get($groupId);
273
+                    if ($aGroup instanceof IGroup) {
274
+                        $groups[$groupId] = $aGroup;
275
+                    } else {
276
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
+                    }
278
+                }
279
+            }
280
+        }
281
+        $this->cachedUserGroups[$uid] = $groups;
282
+        return $this->cachedUserGroups[$uid];
283
+    }
284
+
285
+    /**
286
+     * Checks if a userId is in the admin group
287
+     * @param string $userId
288
+     * @return bool if admin
289
+     */
290
+    public function isAdmin($userId) {
291
+        return $this->isInGroup($userId, 'admin');
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in a group
296
+     * @param string $userId
297
+     * @param string $group
298
+     * @return bool if in group
299
+     */
300
+    public function isInGroup($userId, $group) {
301
+        return array_key_exists($group, $this->getUserIdGroups($userId));
302
+    }
303
+
304
+    /**
305
+     * get a list of group ids for a user
306
+     * @param IUser $user
307
+     * @return array with group ids
308
+     */
309
+    public function getUserGroupIds(IUser $user) {
310
+        return array_map(function($value) {
311
+            return (string) $value;
312
+        }, array_keys($this->getUserGroups($user)));
313
+    }
314
+
315
+    /**
316
+     * get a list of all users in a group
317
+     * @param string $gid
318
+     * @param string $search
319
+     * @param int $limit
320
+     * @param int $offset
321
+     * @return array an array of users (value) and user ids (key)
322
+     */
323
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
+        $group = $this->get($gid);
325
+        if(is_null($group)) {
326
+            return array();
327
+        }
328
+
329
+        $search = trim($search);
330
+        $groupUsers = array();
331
+
332
+        if(!empty($search)) {
333
+            // only user backends have the capability to do a complex search for users
334
+            $searchOffset = 0;
335
+            $searchLimit = $limit * 100;
336
+            if($limit === -1) {
337
+                $searchLimit = 500;
338
+            }
339
+
340
+            do {
341
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
+                foreach($filteredUsers as $filteredUser) {
343
+                    if($group->inGroup($filteredUser)) {
344
+                        $groupUsers[]= $filteredUser;
345
+                    }
346
+                }
347
+                $searchOffset += $searchLimit;
348
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
+
350
+            if($limit === -1) {
351
+                $groupUsers = array_slice($groupUsers, $offset);
352
+            } else {
353
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
354
+            }
355
+        } else {
356
+            $groupUsers = $group->searchUsers('', $limit, $offset);
357
+        }
358
+
359
+        $matchingUsers = array();
360
+        foreach($groupUsers as $groupUser) {
361
+            $matchingUsers[$groupUser->getUID()] = $groupUser;
362
+        }
363
+        return $matchingUsers;
364
+    }
365
+
366
+    /**
367
+     * get a list of all display names in a group
368
+     * @param string $gid
369
+     * @param string $search
370
+     * @param int $limit
371
+     * @param int $offset
372
+     * @return array an array of display names (value) and user ids (key)
373
+     */
374
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
375
+        $matchingUsers = array();
376
+        foreach($this->usersInGroup($gid, $search, $limit, $offset) as $uid => $user) {
377
+            $matchingUsers[$uid] = $user->getDisplayName();
378
+        }
379
+        return $matchingUsers;
380
+    }
381
+
382
+    /**
383
+     * @return \OC\SubAdmin
384
+     */
385
+    public function getSubAdmin() {
386
+        if (!$this->subAdmin) {
387
+            $this->subAdmin = new \OC\SubAdmin(
388
+                $this->userManager,
389
+                $this,
390
+                \OC::$server->getDatabaseConnection()
391
+            );
392
+        }
393
+
394
+        return $this->subAdmin;
395
+    }
396 396
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 	 * @param IUser|null $user
250 250
 	 * @return \OC\Group\Group[]
251 251
 	 */
252
-	public function getUserGroups(IUser $user= null) {
252
+	public function getUserGroups(IUser $user = null) {
253 253
 		if (!$user instanceof IUser) {
254 254
 			return [];
255 255
 		}
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser;
362 362
 		}
363 363
 		return $matchingUsers;
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 	 */
374 374
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
375 375
 		$matchingUsers = array();
376
-		foreach($this->usersInGroup($gid, $search, $limit, $offset) as $uid => $user) {
376
+		foreach ($this->usersInGroup($gid, $search, $limit, $offset) as $uid => $user) {
377 377
 			$matchingUsers[$uid] = $user->getDisplayName();
378 378
 		}
379 379
 		return $matchingUsers;
Please login to merge, or discard this patch.
lib/public/IGroupManager.php 1 patch
Indentation   +92 added lines, -92 removed lines patch added patch discarded remove patch
@@ -45,108 +45,108 @@
 block discarded – undo
45 45
  * @since 8.0.0
46 46
  */
47 47
 interface IGroupManager {
48
-	/**
49
-	 * Checks whether a given backend is used
50
-	 *
51
-	 * @param string $backendClass Full classname including complete namespace
52
-	 * @return bool
53
-	 * @since 8.1.0
54
-	 */
55
-	public function isBackendUsed($backendClass);
48
+    /**
49
+     * Checks whether a given backend is used
50
+     *
51
+     * @param string $backendClass Full classname including complete namespace
52
+     * @return bool
53
+     * @since 8.1.0
54
+     */
55
+    public function isBackendUsed($backendClass);
56 56
 
57
-	/**
58
-	 * @param \OCP\GroupInterface $backend
59
-	 * @since 8.0.0
60
-	 */
61
-	public function addBackend($backend);
57
+    /**
58
+     * @param \OCP\GroupInterface $backend
59
+     * @since 8.0.0
60
+     */
61
+    public function addBackend($backend);
62 62
 
63
-	/**
64
-	 * @since 8.0.0
65
-	 */
66
-	public function clearBackends();
63
+    /**
64
+     * @since 8.0.0
65
+     */
66
+    public function clearBackends();
67 67
 
68
-	/**
69
-	 * @param string $gid
70
-	 * @return \OCP\IGroup
71
-	 * @since 8.0.0
72
-	 */
73
-	public function get($gid);
68
+    /**
69
+     * @param string $gid
70
+     * @return \OCP\IGroup
71
+     * @since 8.0.0
72
+     */
73
+    public function get($gid);
74 74
 
75
-	/**
76
-	 * @param string $gid
77
-	 * @return bool
78
-	 * @since 8.0.0
79
-	 */
80
-	public function groupExists($gid);
75
+    /**
76
+     * @param string $gid
77
+     * @return bool
78
+     * @since 8.0.0
79
+     */
80
+    public function groupExists($gid);
81 81
 
82
-	/**
83
-	 * @param string $gid
84
-	 * @return \OCP\IGroup
85
-	 * @since 8.0.0
86
-	 */
87
-	public function createGroup($gid);
82
+    /**
83
+     * @param string $gid
84
+     * @return \OCP\IGroup
85
+     * @since 8.0.0
86
+     */
87
+    public function createGroup($gid);
88 88
 
89
-	/**
90
-	 * @param string $search
91
-	 * @param int $limit
92
-	 * @param int $offset
93
-	 * @return \OCP\IGroup[]
94
-	 * @since 8.0.0
95
-	 */
96
-	public function search($search, $limit = null, $offset = null);
89
+    /**
90
+     * @param string $search
91
+     * @param int $limit
92
+     * @param int $offset
93
+     * @return \OCP\IGroup[]
94
+     * @since 8.0.0
95
+     */
96
+    public function search($search, $limit = null, $offset = null);
97 97
 
98
-	/**
99
-	 * @param \OCP\IUser|null $user
100
-	 * @return \OCP\IGroup[]
101
-	 * @since 8.0.0
102
-	 */
103
-	public function getUserGroups(IUser $user = null);
98
+    /**
99
+     * @param \OCP\IUser|null $user
100
+     * @return \OCP\IGroup[]
101
+     * @since 8.0.0
102
+     */
103
+    public function getUserGroups(IUser $user = null);
104 104
 
105
-	/**
106
-	 * @param \OCP\IUser $user
107
-	 * @return array with group names
108
-	 * @since 8.0.0
109
-	 */
110
-	public function getUserGroupIds(IUser $user);
105
+    /**
106
+     * @param \OCP\IUser $user
107
+     * @return array with group names
108
+     * @since 8.0.0
109
+     */
110
+    public function getUserGroupIds(IUser $user);
111 111
 
112
-	/**
113
-	 * get a list of all users in a group
114
-	 *
115
-	 * @param string $gid
116
-	 * @param string $search
117
-	 * @param int $limit
118
-	 * @param int $offset
119
-	 * @return array an array of users (value) and user ids (key)
120
-	 * @since 13.0.0
121
-	 */
122
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0);
112
+    /**
113
+     * get a list of all users in a group
114
+     *
115
+     * @param string $gid
116
+     * @param string $search
117
+     * @param int $limit
118
+     * @param int $offset
119
+     * @return array an array of users (value) and user ids (key)
120
+     * @since 13.0.0
121
+     */
122
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0);
123 123
 
124
-	/**
125
-	 * get a list of all display names in a group
126
-	 *
127
-	 * @param string $gid
128
-	 * @param string $search
129
-	 * @param int $limit
130
-	 * @param int $offset
131
-	 * @return array an array of display names (value) and user ids (key)
132
-	 * @since 8.0.0
133
-	 */
134
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0);
124
+    /**
125
+     * get a list of all display names in a group
126
+     *
127
+     * @param string $gid
128
+     * @param string $search
129
+     * @param int $limit
130
+     * @param int $offset
131
+     * @return array an array of display names (value) and user ids (key)
132
+     * @since 8.0.0
133
+     */
134
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0);
135 135
 
136
-	/**
137
-	 * Checks if a userId is in the admin group
138
-	 * @param string $userId
139
-	 * @return bool if admin
140
-	 * @since 8.0.0
141
-	 */
142
-	public function isAdmin($userId);
136
+    /**
137
+     * Checks if a userId is in the admin group
138
+     * @param string $userId
139
+     * @return bool if admin
140
+     * @since 8.0.0
141
+     */
142
+    public function isAdmin($userId);
143 143
 
144
-	/**
145
-	 * Checks if a userId is in a group
146
-	 * @param string $userId
147
-	 * @param string $group
148
-	 * @return bool if in group
149
-	 * @since 8.0.0
150
-	 */
151
-	public function isInGroup($userId, $group);
144
+    /**
145
+     * Checks if a userId is in a group
146
+     * @param string $userId
147
+     * @param string $group
148
+     * @return bool if in group
149
+     * @since 8.0.0
150
+     */
151
+    public function isInGroup($userId, $group);
152 152
 }
Please login to merge, or discard this patch.
lib/public/Share/IManager.php 1 patch
Indentation   +317 added lines, -317 removed lines patch added patch discarded remove patch
@@ -35,322 +35,322 @@
 block discarded – undo
35 35
  */
36 36
 interface IManager {
37 37
 
38
-	/**
39
-	 * Create a Share
40
-	 *
41
-	 * @param IShare $share
42
-	 * @return IShare The share object
43
-	 * @since 9.0.0
44
-	 */
45
-	public function createShare(IShare $share);
46
-
47
-	/**
48
-	 * Sends again the e-mail notification for a share
49
-	 *
50
-	 * @param IShare $share
51
-	 * @return IShare The share object
52
-	 * @throws \InvalidArgumentException if share type does not support mail
53
-	 *         notifications or the sharee has no known e-mail address
54
-	 * @throws \Exception if mail could not be sent
55
-	 * @since 13.0.0
56
-	 */
57
-	public function resendMailNotification(IShare $share);
58
-
59
-	/**
60
-	 * Update a share.
61
-	 * The target of the share can't be changed this way: use moveShare
62
-	 * The share can't be removed this way (permission 0): use deleteShare
63
-	 *
64
-	 * @param IShare $share
65
-	 * @return IShare The share object
66
-	 * @since 9.0.0
67
-	 */
68
-	public function updateShare(IShare $share);
69
-
70
-	/**
71
-	 * Delete a share
72
-	 *
73
-	 * @param IShare $share
74
-	 * @throws ShareNotFound
75
-	 * @since 9.0.0
76
-	 */
77
-	public function deleteShare(IShare $share);
78
-
79
-	/**
80
-	 * Unshare a file as the recipient.
81
-	 * This can be different from a regular delete for example when one of
82
-	 * the users in a groups deletes that share. But the provider should
83
-	 * handle this.
84
-	 *
85
-	 * @param IShare $share
86
-	 * @param string $recipientId
87
-	 * @since 9.0.0
88
-	 */
89
-	public function deleteFromSelf(IShare $share, $recipientId);
90
-
91
-	/**
92
-	 * Move the share as a recipient of the share.
93
-	 * This is updating the share target. So where the recipient has the share mounted.
94
-	 *
95
-	 * @param IShare $share
96
-	 * @param string $recipientId
97
-	 * @return IShare
98
-	 * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
99
-	 * @since 9.0.0
100
-	 */
101
-	public function moveShare(IShare $share, $recipientId);
102
-
103
-	/**
104
-	 * Get all shares shared by (initiated) by the provided user in a folder.
105
-	 *
106
-	 * @param string $userId
107
-	 * @param Folder $node
108
-	 * @param bool $reshares
109
-	 * @return IShare[][] [$fileId => IShare[], ...]
110
-	 * @since 11.0.0
111
-	 */
112
-	public function getSharesInFolder($userId, Folder $node, $reshares = false);
113
-
114
-	/**
115
-	 * Get shares shared by (initiated) by the provided user.
116
-	 *
117
-	 * @param string $userId
118
-	 * @param int $shareType
119
-	 * @param Node|null $path
120
-	 * @param bool $reshares
121
-	 * @param int $limit The maximum number of returned results, -1 for all results
122
-	 * @param int $offset
123
-	 * @return IShare[]
124
-	 * @since 9.0.0
125
-	 */
126
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
127
-
128
-	/**
129
-	 * Get shares shared with $user.
130
-	 * Filter by $node if provided
131
-	 *
132
-	 * @param string $userId
133
-	 * @param int $shareType
134
-	 * @param Node|null $node
135
-	 * @param int $limit The maximum number of shares returned, -1 for all
136
-	 * @param int $offset
137
-	 * @return IShare[]
138
-	 * @since 9.0.0
139
-	 */
140
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
141
-
142
-	/**
143
-	 * Retrieve a share by the share id.
144
-	 * If the recipient is set make sure to retrieve the file for that user.
145
-	 * This makes sure that if a user has moved/deleted a group share this
146
-	 * is reflected.
147
-	 *
148
-	 * @param string $id
149
-	 * @param string|null $recipient userID of the recipient
150
-	 * @return IShare
151
-	 * @throws ShareNotFound
152
-	 * @since 9.0.0
153
-	 */
154
-	public function getShareById($id, $recipient = null);
155
-
156
-	/**
157
-	 * Get the share by token possible with password
158
-	 *
159
-	 * @param string $token
160
-	 * @return IShare
161
-	 * @throws ShareNotFound
162
-	 * @since 9.0.0
163
-	 */
164
-	public function getShareByToken($token);
165
-
166
-	/**
167
-	 * Verify the password of a public share
168
-	 *
169
-	 * @param IShare $share
170
-	 * @param string $password
171
-	 * @return bool
172
-	 * @since 9.0.0
173
-	 */
174
-	public function checkPassword(IShare $share, $password);
175
-
176
-	/**
177
-	 * The user with UID is deleted.
178
-	 * All share providers have to cleanup the shares with this user as well
179
-	 * as shares owned by this user.
180
-	 * Shares only initiated by this user are fine.
181
-	 *
182
-	 * @param string $uid
183
-	 * @since 9.1.0
184
-	 */
185
-	public function userDeleted($uid);
186
-
187
-	/**
188
-	 * The group with $gid is deleted
189
-	 * We need to clear up all shares to this group
190
-	 *
191
-	 * @param string $gid
192
-	 * @since 9.1.0
193
-	 */
194
-	public function groupDeleted($gid);
195
-
196
-	/**
197
-	 * The user $uid is deleted from the group $gid
198
-	 * All user specific group shares have to be removed
199
-	 *
200
-	 * @param string $uid
201
-	 * @param string $gid
202
-	 * @since 9.1.0
203
-	 */
204
-	public function userDeletedFromGroup($uid, $gid);
205
-
206
-	/**
207
-	 * Get access list to a path. This means
208
-	 * all the users that can access a given path.
209
-	 *
210
-	 * Consider:
211
-	 * -root
212
-	 * |-folder1 (23)
213
-	 *  |-folder2 (32)
214
-	 *   |-fileA (42)
215
-	 *
216
-	 * fileA is shared with user1 and user1@server1
217
-	 * folder2 is shared with group2 (user4 is a member of group2)
218
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
219
-	 *
220
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
221
-	 * [
222
-	 *  users  => [
223
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
224
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
225
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
226
-	 *  ],
227
-	 *  remote => [
228
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
229
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
230
-	 *  ],
231
-	 *  public => bool
232
-	 *  mail => bool
233
-	 * ]
234
-	 *
235
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
236
-	 * [
237
-	 *  users  => ['user1', 'user2', 'user4'],
238
-	 *  remote => bool,
239
-	 *  public => bool
240
-	 *  mail => bool
241
-	 * ]
242
-	 *
243
-	 * This is required for encryption/activity
244
-	 *
245
-	 * @param \OCP\Files\Node $path
246
-	 * @param bool $recursive Should we check all parent folders as well
247
-	 * @param bool $currentAccess Should the user have currently access to the file
248
-	 * @return array
249
-	 * @since 12
250
-	 */
251
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
252
-
253
-	/**
254
-	 * Instantiates a new share object. This is to be passed to
255
-	 * createShare.
256
-	 *
257
-	 * @return IShare
258
-	 * @since 9.0.0
259
-	 */
260
-	public function newShare();
261
-
262
-	/**
263
-	 * Is the share API enabled
264
-	 *
265
-	 * @return bool
266
-	 * @since 9.0.0
267
-	 */
268
-	public function shareApiEnabled();
269
-
270
-	/**
271
-	 * Is public link sharing enabled
272
-	 *
273
-	 * @return bool
274
-	 * @since 9.0.0
275
-	 */
276
-	public function shareApiAllowLinks();
277
-
278
-	/**
279
-	 * Is password on public link requires
280
-	 *
281
-	 * @return bool
282
-	 * @since 9.0.0
283
-	 */
284
-	public function shareApiLinkEnforcePassword();
285
-
286
-	/**
287
-	 * Is default expire date enabled
288
-	 *
289
-	 * @return bool
290
-	 * @since 9.0.0
291
-	 */
292
-	public function shareApiLinkDefaultExpireDate();
293
-
294
-	/**
295
-	 * Is default expire date enforced
296
-	 *`
297
-	 * @return bool
298
-	 * @since 9.0.0
299
-	 */
300
-	public function shareApiLinkDefaultExpireDateEnforced();
301
-
302
-	/**
303
-	 * Number of default expire days
304
-	 *
305
-	 * @return int
306
-	 * @since 9.0.0
307
-	 */
308
-	public function shareApiLinkDefaultExpireDays();
309
-
310
-	/**
311
-	 * Allow public upload on link shares
312
-	 *
313
-	 * @return bool
314
-	 * @since 9.0.0
315
-	 */
316
-	public function shareApiLinkAllowPublicUpload();
317
-
318
-	/**
319
-	 * check if user can only share with group members
320
-	 * @return bool
321
-	 * @since 9.0.0
322
-	 */
323
-	public function shareWithGroupMembersOnly();
324
-
325
-	/**
326
-	 * Check if users can share with groups
327
-	 * @return bool
328
-	 * @since 9.0.1
329
-	 */
330
-	public function allowGroupSharing();
331
-
332
-	/**
333
-	 * Check if sharing is disabled for the given user
334
-	 *
335
-	 * @param string $userId
336
-	 * @return bool
337
-	 * @since 9.0.0
338
-	 */
339
-	public function sharingDisabledForUser($userId);
340
-
341
-	/**
342
-	 * Check if outgoing server2server shares are allowed
343
-	 * @return bool
344
-	 * @since 9.0.0
345
-	 */
346
-	public function outgoingServer2ServerSharesAllowed();
347
-
348
-	/**
349
-	 * Check if a given share provider exists
350
-	 * @param int $shareType
351
-	 * @return bool
352
-	 * @since 11.0.0
353
-	 */
354
-	public function shareProviderExists($shareType);
38
+    /**
39
+     * Create a Share
40
+     *
41
+     * @param IShare $share
42
+     * @return IShare The share object
43
+     * @since 9.0.0
44
+     */
45
+    public function createShare(IShare $share);
46
+
47
+    /**
48
+     * Sends again the e-mail notification for a share
49
+     *
50
+     * @param IShare $share
51
+     * @return IShare The share object
52
+     * @throws \InvalidArgumentException if share type does not support mail
53
+     *         notifications or the sharee has no known e-mail address
54
+     * @throws \Exception if mail could not be sent
55
+     * @since 13.0.0
56
+     */
57
+    public function resendMailNotification(IShare $share);
58
+
59
+    /**
60
+     * Update a share.
61
+     * The target of the share can't be changed this way: use moveShare
62
+     * The share can't be removed this way (permission 0): use deleteShare
63
+     *
64
+     * @param IShare $share
65
+     * @return IShare The share object
66
+     * @since 9.0.0
67
+     */
68
+    public function updateShare(IShare $share);
69
+
70
+    /**
71
+     * Delete a share
72
+     *
73
+     * @param IShare $share
74
+     * @throws ShareNotFound
75
+     * @since 9.0.0
76
+     */
77
+    public function deleteShare(IShare $share);
78
+
79
+    /**
80
+     * Unshare a file as the recipient.
81
+     * This can be different from a regular delete for example when one of
82
+     * the users in a groups deletes that share. But the provider should
83
+     * handle this.
84
+     *
85
+     * @param IShare $share
86
+     * @param string $recipientId
87
+     * @since 9.0.0
88
+     */
89
+    public function deleteFromSelf(IShare $share, $recipientId);
90
+
91
+    /**
92
+     * Move the share as a recipient of the share.
93
+     * This is updating the share target. So where the recipient has the share mounted.
94
+     *
95
+     * @param IShare $share
96
+     * @param string $recipientId
97
+     * @return IShare
98
+     * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
99
+     * @since 9.0.0
100
+     */
101
+    public function moveShare(IShare $share, $recipientId);
102
+
103
+    /**
104
+     * Get all shares shared by (initiated) by the provided user in a folder.
105
+     *
106
+     * @param string $userId
107
+     * @param Folder $node
108
+     * @param bool $reshares
109
+     * @return IShare[][] [$fileId => IShare[], ...]
110
+     * @since 11.0.0
111
+     */
112
+    public function getSharesInFolder($userId, Folder $node, $reshares = false);
113
+
114
+    /**
115
+     * Get shares shared by (initiated) by the provided user.
116
+     *
117
+     * @param string $userId
118
+     * @param int $shareType
119
+     * @param Node|null $path
120
+     * @param bool $reshares
121
+     * @param int $limit The maximum number of returned results, -1 for all results
122
+     * @param int $offset
123
+     * @return IShare[]
124
+     * @since 9.0.0
125
+     */
126
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
127
+
128
+    /**
129
+     * Get shares shared with $user.
130
+     * Filter by $node if provided
131
+     *
132
+     * @param string $userId
133
+     * @param int $shareType
134
+     * @param Node|null $node
135
+     * @param int $limit The maximum number of shares returned, -1 for all
136
+     * @param int $offset
137
+     * @return IShare[]
138
+     * @since 9.0.0
139
+     */
140
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
141
+
142
+    /**
143
+     * Retrieve a share by the share id.
144
+     * If the recipient is set make sure to retrieve the file for that user.
145
+     * This makes sure that if a user has moved/deleted a group share this
146
+     * is reflected.
147
+     *
148
+     * @param string $id
149
+     * @param string|null $recipient userID of the recipient
150
+     * @return IShare
151
+     * @throws ShareNotFound
152
+     * @since 9.0.0
153
+     */
154
+    public function getShareById($id, $recipient = null);
155
+
156
+    /**
157
+     * Get the share by token possible with password
158
+     *
159
+     * @param string $token
160
+     * @return IShare
161
+     * @throws ShareNotFound
162
+     * @since 9.0.0
163
+     */
164
+    public function getShareByToken($token);
165
+
166
+    /**
167
+     * Verify the password of a public share
168
+     *
169
+     * @param IShare $share
170
+     * @param string $password
171
+     * @return bool
172
+     * @since 9.0.0
173
+     */
174
+    public function checkPassword(IShare $share, $password);
175
+
176
+    /**
177
+     * The user with UID is deleted.
178
+     * All share providers have to cleanup the shares with this user as well
179
+     * as shares owned by this user.
180
+     * Shares only initiated by this user are fine.
181
+     *
182
+     * @param string $uid
183
+     * @since 9.1.0
184
+     */
185
+    public function userDeleted($uid);
186
+
187
+    /**
188
+     * The group with $gid is deleted
189
+     * We need to clear up all shares to this group
190
+     *
191
+     * @param string $gid
192
+     * @since 9.1.0
193
+     */
194
+    public function groupDeleted($gid);
195
+
196
+    /**
197
+     * The user $uid is deleted from the group $gid
198
+     * All user specific group shares have to be removed
199
+     *
200
+     * @param string $uid
201
+     * @param string $gid
202
+     * @since 9.1.0
203
+     */
204
+    public function userDeletedFromGroup($uid, $gid);
205
+
206
+    /**
207
+     * Get access list to a path. This means
208
+     * all the users that can access a given path.
209
+     *
210
+     * Consider:
211
+     * -root
212
+     * |-folder1 (23)
213
+     *  |-folder2 (32)
214
+     *   |-fileA (42)
215
+     *
216
+     * fileA is shared with user1 and user1@server1
217
+     * folder2 is shared with group2 (user4 is a member of group2)
218
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
219
+     *
220
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
221
+     * [
222
+     *  users  => [
223
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
224
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
225
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
226
+     *  ],
227
+     *  remote => [
228
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
229
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
230
+     *  ],
231
+     *  public => bool
232
+     *  mail => bool
233
+     * ]
234
+     *
235
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
236
+     * [
237
+     *  users  => ['user1', 'user2', 'user4'],
238
+     *  remote => bool,
239
+     *  public => bool
240
+     *  mail => bool
241
+     * ]
242
+     *
243
+     * This is required for encryption/activity
244
+     *
245
+     * @param \OCP\Files\Node $path
246
+     * @param bool $recursive Should we check all parent folders as well
247
+     * @param bool $currentAccess Should the user have currently access to the file
248
+     * @return array
249
+     * @since 12
250
+     */
251
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
252
+
253
+    /**
254
+     * Instantiates a new share object. This is to be passed to
255
+     * createShare.
256
+     *
257
+     * @return IShare
258
+     * @since 9.0.0
259
+     */
260
+    public function newShare();
261
+
262
+    /**
263
+     * Is the share API enabled
264
+     *
265
+     * @return bool
266
+     * @since 9.0.0
267
+     */
268
+    public function shareApiEnabled();
269
+
270
+    /**
271
+     * Is public link sharing enabled
272
+     *
273
+     * @return bool
274
+     * @since 9.0.0
275
+     */
276
+    public function shareApiAllowLinks();
277
+
278
+    /**
279
+     * Is password on public link requires
280
+     *
281
+     * @return bool
282
+     * @since 9.0.0
283
+     */
284
+    public function shareApiLinkEnforcePassword();
285
+
286
+    /**
287
+     * Is default expire date enabled
288
+     *
289
+     * @return bool
290
+     * @since 9.0.0
291
+     */
292
+    public function shareApiLinkDefaultExpireDate();
293
+
294
+    /**
295
+     * Is default expire date enforced
296
+     *`
297
+     * @return bool
298
+     * @since 9.0.0
299
+     */
300
+    public function shareApiLinkDefaultExpireDateEnforced();
301
+
302
+    /**
303
+     * Number of default expire days
304
+     *
305
+     * @return int
306
+     * @since 9.0.0
307
+     */
308
+    public function shareApiLinkDefaultExpireDays();
309
+
310
+    /**
311
+     * Allow public upload on link shares
312
+     *
313
+     * @return bool
314
+     * @since 9.0.0
315
+     */
316
+    public function shareApiLinkAllowPublicUpload();
317
+
318
+    /**
319
+     * check if user can only share with group members
320
+     * @return bool
321
+     * @since 9.0.0
322
+     */
323
+    public function shareWithGroupMembersOnly();
324
+
325
+    /**
326
+     * Check if users can share with groups
327
+     * @return bool
328
+     * @since 9.0.1
329
+     */
330
+    public function allowGroupSharing();
331
+
332
+    /**
333
+     * Check if sharing is disabled for the given user
334
+     *
335
+     * @param string $userId
336
+     * @return bool
337
+     * @since 9.0.0
338
+     */
339
+    public function sharingDisabledForUser($userId);
340
+
341
+    /**
342
+     * Check if outgoing server2server shares are allowed
343
+     * @return bool
344
+     * @since 9.0.0
345
+     */
346
+    public function outgoingServer2ServerSharesAllowed();
347
+
348
+    /**
349
+     * Check if a given share provider exists
350
+     * @param int $shareType
351
+     * @return bool
352
+     * @since 11.0.0
353
+     */
354
+    public function shareProviderExists($shareType);
355 355
 
356 356
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 2 patches
Indentation   +1480 added lines, -1480 removed lines patch added patch discarded remove patch
@@ -60,1508 +60,1508 @@
 block discarded – undo
60 60
  */
61 61
 class Manager implements IManager {
62 62
 
63
-	/** @var IProviderFactory */
64
-	private $factory;
65
-	/** @var ILogger */
66
-	private $logger;
67
-	/** @var IConfig */
68
-	private $config;
69
-	/** @var ISecureRandom */
70
-	private $secureRandom;
71
-	/** @var IHasher */
72
-	private $hasher;
73
-	/** @var IMountManager */
74
-	private $mountManager;
75
-	/** @var IGroupManager */
76
-	private $groupManager;
77
-	/** @var IL10N */
78
-	private $l;
79
-	/** @var IUserManager */
80
-	private $userManager;
81
-	/** @var IRootFolder */
82
-	private $rootFolder;
83
-	/** @var CappedMemoryCache */
84
-	private $sharingDisabledForUsersCache;
85
-	/** @var EventDispatcher */
86
-	private $eventDispatcher;
87
-	/** @var LegacyHooks */
88
-	private $legacyHooks;
89
-	/** @var IMailer */
90
-	private $mailer;
91
-	/** @var IURLGenerator */
92
-	private $urlGenerator;
93
-	/** @var \OC_Defaults */
94
-	private $defaults;
95
-
96
-
97
-	/**
98
-	 * Manager constructor.
99
-	 *
100
-	 * @param ILogger $logger
101
-	 * @param IConfig $config
102
-	 * @param ISecureRandom $secureRandom
103
-	 * @param IHasher $hasher
104
-	 * @param IMountManager $mountManager
105
-	 * @param IGroupManager $groupManager
106
-	 * @param IL10N $l
107
-	 * @param IProviderFactory $factory
108
-	 * @param IUserManager $userManager
109
-	 * @param IRootFolder $rootFolder
110
-	 * @param EventDispatcher $eventDispatcher
111
-	 * @param IMailer $mailer
112
-	 * @param IURLGenerator $urlGenerator
113
-	 * @param \OC_Defaults $defaults
114
-	 */
115
-	public function __construct(
116
-			ILogger $logger,
117
-			IConfig $config,
118
-			ISecureRandom $secureRandom,
119
-			IHasher $hasher,
120
-			IMountManager $mountManager,
121
-			IGroupManager $groupManager,
122
-			IL10N $l,
123
-			IProviderFactory $factory,
124
-			IUserManager $userManager,
125
-			IRootFolder $rootFolder,
126
-			EventDispatcher $eventDispatcher,
127
-			IMailer $mailer,
128
-			IURLGenerator $urlGenerator,
129
-			\OC_Defaults $defaults
130
-	) {
131
-		$this->logger = $logger;
132
-		$this->config = $config;
133
-		$this->secureRandom = $secureRandom;
134
-		$this->hasher = $hasher;
135
-		$this->mountManager = $mountManager;
136
-		$this->groupManager = $groupManager;
137
-		$this->l = $l;
138
-		$this->factory = $factory;
139
-		$this->userManager = $userManager;
140
-		$this->rootFolder = $rootFolder;
141
-		$this->eventDispatcher = $eventDispatcher;
142
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
143
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
144
-		$this->mailer = $mailer;
145
-		$this->urlGenerator = $urlGenerator;
146
-		$this->defaults = $defaults;
147
-	}
148
-
149
-	/**
150
-	 * Convert from a full share id to a tuple (providerId, shareId)
151
-	 *
152
-	 * @param string $id
153
-	 * @return string[]
154
-	 */
155
-	private function splitFullId($id) {
156
-		return explode(':', $id, 2);
157
-	}
158
-
159
-	/**
160
-	 * Verify if a password meets all requirements
161
-	 *
162
-	 * @param string $password
163
-	 * @throws \Exception
164
-	 */
165
-	protected function verifyPassword($password) {
166
-		if ($password === null) {
167
-			// No password is set, check if this is allowed.
168
-			if ($this->shareApiLinkEnforcePassword()) {
169
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
170
-			}
171
-
172
-			return;
173
-		}
174
-
175
-		// Let others verify the password
176
-		try {
177
-			$event = new GenericEvent($password);
178
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
179
-		} catch (HintException $e) {
180
-			throw new \Exception($e->getHint());
181
-		}
182
-	}
183
-
184
-	/**
185
-	 * Check for generic requirements before creating a share
186
-	 *
187
-	 * @param \OCP\Share\IShare $share
188
-	 * @throws \InvalidArgumentException
189
-	 * @throws GenericShareException
190
-	 *
191
-	 * @suppress PhanUndeclaredClassMethod
192
-	 */
193
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
194
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
195
-			// We expect a valid user as sharedWith for user shares
196
-			if (!$this->userManager->userExists($share->getSharedWith())) {
197
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
198
-			}
199
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
200
-			// We expect a valid group as sharedWith for group shares
201
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
202
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
203
-			}
204
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
205
-			if ($share->getSharedWith() !== null) {
206
-				throw new \InvalidArgumentException('SharedWith should be empty');
207
-			}
208
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
209
-			if ($share->getSharedWith() === null) {
210
-				throw new \InvalidArgumentException('SharedWith should not be empty');
211
-			}
212
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
213
-			if ($share->getSharedWith() === null) {
214
-				throw new \InvalidArgumentException('SharedWith should not be empty');
215
-			}
216
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
217
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
218
-			if ($circle === null) {
219
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
220
-			}
221
-		} else {
222
-			// We can't handle other types yet
223
-			throw new \InvalidArgumentException('unknown share type');
224
-		}
225
-
226
-		// Verify the initiator of the share is set
227
-		if ($share->getSharedBy() === null) {
228
-			throw new \InvalidArgumentException('SharedBy should be set');
229
-		}
230
-
231
-		// Cannot share with yourself
232
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
233
-			$share->getSharedWith() === $share->getSharedBy()) {
234
-			throw new \InvalidArgumentException('Can’t share with yourself');
235
-		}
236
-
237
-		// The path should be set
238
-		if ($share->getNode() === null) {
239
-			throw new \InvalidArgumentException('Path should be set');
240
-		}
241
-
242
-		// And it should be a file or a folder
243
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
244
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
245
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
246
-		}
247
-
248
-		// And you can't share your rootfolder
249
-		if ($this->userManager->userExists($share->getSharedBy())) {
250
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
251
-		} else {
252
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
253
-		}
254
-		if ($sharedPath === $share->getNode()->getPath()) {
255
-			throw new \InvalidArgumentException('You can’t share your root folder');
256
-		}
257
-
258
-		// Check if we actually have share permissions
259
-		if (!$share->getNode()->isShareable()) {
260
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
261
-			throw new GenericShareException($message_t, $message_t, 404);
262
-		}
263
-
264
-		// Permissions should be set
265
-		if ($share->getPermissions() === null) {
266
-			throw new \InvalidArgumentException('A share requires permissions');
267
-		}
268
-
269
-		/*
63
+    /** @var IProviderFactory */
64
+    private $factory;
65
+    /** @var ILogger */
66
+    private $logger;
67
+    /** @var IConfig */
68
+    private $config;
69
+    /** @var ISecureRandom */
70
+    private $secureRandom;
71
+    /** @var IHasher */
72
+    private $hasher;
73
+    /** @var IMountManager */
74
+    private $mountManager;
75
+    /** @var IGroupManager */
76
+    private $groupManager;
77
+    /** @var IL10N */
78
+    private $l;
79
+    /** @var IUserManager */
80
+    private $userManager;
81
+    /** @var IRootFolder */
82
+    private $rootFolder;
83
+    /** @var CappedMemoryCache */
84
+    private $sharingDisabledForUsersCache;
85
+    /** @var EventDispatcher */
86
+    private $eventDispatcher;
87
+    /** @var LegacyHooks */
88
+    private $legacyHooks;
89
+    /** @var IMailer */
90
+    private $mailer;
91
+    /** @var IURLGenerator */
92
+    private $urlGenerator;
93
+    /** @var \OC_Defaults */
94
+    private $defaults;
95
+
96
+
97
+    /**
98
+     * Manager constructor.
99
+     *
100
+     * @param ILogger $logger
101
+     * @param IConfig $config
102
+     * @param ISecureRandom $secureRandom
103
+     * @param IHasher $hasher
104
+     * @param IMountManager $mountManager
105
+     * @param IGroupManager $groupManager
106
+     * @param IL10N $l
107
+     * @param IProviderFactory $factory
108
+     * @param IUserManager $userManager
109
+     * @param IRootFolder $rootFolder
110
+     * @param EventDispatcher $eventDispatcher
111
+     * @param IMailer $mailer
112
+     * @param IURLGenerator $urlGenerator
113
+     * @param \OC_Defaults $defaults
114
+     */
115
+    public function __construct(
116
+            ILogger $logger,
117
+            IConfig $config,
118
+            ISecureRandom $secureRandom,
119
+            IHasher $hasher,
120
+            IMountManager $mountManager,
121
+            IGroupManager $groupManager,
122
+            IL10N $l,
123
+            IProviderFactory $factory,
124
+            IUserManager $userManager,
125
+            IRootFolder $rootFolder,
126
+            EventDispatcher $eventDispatcher,
127
+            IMailer $mailer,
128
+            IURLGenerator $urlGenerator,
129
+            \OC_Defaults $defaults
130
+    ) {
131
+        $this->logger = $logger;
132
+        $this->config = $config;
133
+        $this->secureRandom = $secureRandom;
134
+        $this->hasher = $hasher;
135
+        $this->mountManager = $mountManager;
136
+        $this->groupManager = $groupManager;
137
+        $this->l = $l;
138
+        $this->factory = $factory;
139
+        $this->userManager = $userManager;
140
+        $this->rootFolder = $rootFolder;
141
+        $this->eventDispatcher = $eventDispatcher;
142
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
143
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
144
+        $this->mailer = $mailer;
145
+        $this->urlGenerator = $urlGenerator;
146
+        $this->defaults = $defaults;
147
+    }
148
+
149
+    /**
150
+     * Convert from a full share id to a tuple (providerId, shareId)
151
+     *
152
+     * @param string $id
153
+     * @return string[]
154
+     */
155
+    private function splitFullId($id) {
156
+        return explode(':', $id, 2);
157
+    }
158
+
159
+    /**
160
+     * Verify if a password meets all requirements
161
+     *
162
+     * @param string $password
163
+     * @throws \Exception
164
+     */
165
+    protected function verifyPassword($password) {
166
+        if ($password === null) {
167
+            // No password is set, check if this is allowed.
168
+            if ($this->shareApiLinkEnforcePassword()) {
169
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
170
+            }
171
+
172
+            return;
173
+        }
174
+
175
+        // Let others verify the password
176
+        try {
177
+            $event = new GenericEvent($password);
178
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
179
+        } catch (HintException $e) {
180
+            throw new \Exception($e->getHint());
181
+        }
182
+    }
183
+
184
+    /**
185
+     * Check for generic requirements before creating a share
186
+     *
187
+     * @param \OCP\Share\IShare $share
188
+     * @throws \InvalidArgumentException
189
+     * @throws GenericShareException
190
+     *
191
+     * @suppress PhanUndeclaredClassMethod
192
+     */
193
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
194
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
195
+            // We expect a valid user as sharedWith for user shares
196
+            if (!$this->userManager->userExists($share->getSharedWith())) {
197
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
198
+            }
199
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
200
+            // We expect a valid group as sharedWith for group shares
201
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
202
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
203
+            }
204
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
205
+            if ($share->getSharedWith() !== null) {
206
+                throw new \InvalidArgumentException('SharedWith should be empty');
207
+            }
208
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
209
+            if ($share->getSharedWith() === null) {
210
+                throw new \InvalidArgumentException('SharedWith should not be empty');
211
+            }
212
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
213
+            if ($share->getSharedWith() === null) {
214
+                throw new \InvalidArgumentException('SharedWith should not be empty');
215
+            }
216
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
217
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
218
+            if ($circle === null) {
219
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
220
+            }
221
+        } else {
222
+            // We can't handle other types yet
223
+            throw new \InvalidArgumentException('unknown share type');
224
+        }
225
+
226
+        // Verify the initiator of the share is set
227
+        if ($share->getSharedBy() === null) {
228
+            throw new \InvalidArgumentException('SharedBy should be set');
229
+        }
230
+
231
+        // Cannot share with yourself
232
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
233
+            $share->getSharedWith() === $share->getSharedBy()) {
234
+            throw new \InvalidArgumentException('Can’t share with yourself');
235
+        }
236
+
237
+        // The path should be set
238
+        if ($share->getNode() === null) {
239
+            throw new \InvalidArgumentException('Path should be set');
240
+        }
241
+
242
+        // And it should be a file or a folder
243
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
244
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
245
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
246
+        }
247
+
248
+        // And you can't share your rootfolder
249
+        if ($this->userManager->userExists($share->getSharedBy())) {
250
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
251
+        } else {
252
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
253
+        }
254
+        if ($sharedPath === $share->getNode()->getPath()) {
255
+            throw new \InvalidArgumentException('You can’t share your root folder');
256
+        }
257
+
258
+        // Check if we actually have share permissions
259
+        if (!$share->getNode()->isShareable()) {
260
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
261
+            throw new GenericShareException($message_t, $message_t, 404);
262
+        }
263
+
264
+        // Permissions should be set
265
+        if ($share->getPermissions() === null) {
266
+            throw new \InvalidArgumentException('A share requires permissions');
267
+        }
268
+
269
+        /*
270 270
 		 * Quick fix for #23536
271 271
 		 * Non moveable mount points do not have update and delete permissions
272 272
 		 * while we 'most likely' do have that on the storage.
273 273
 		 */
274
-		$permissions = $share->getNode()->getPermissions();
275
-		$mount = $share->getNode()->getMountPoint();
276
-		if (!($mount instanceof MoveableMount)) {
277
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
278
-		}
279
-
280
-		// Check that we do not share with more permissions than we have
281
-		if ($share->getPermissions() & ~$permissions) {
282
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
283
-			throw new GenericShareException($message_t, $message_t, 404);
284
-		}
285
-
286
-
287
-		// Check that read permissions are always set
288
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
289
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
290
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
291
-		if (!$noReadPermissionRequired &&
292
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
293
-			throw new \InvalidArgumentException('Shares need at least read permissions');
294
-		}
295
-
296
-		if ($share->getNode() instanceof \OCP\Files\File) {
297
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
298
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
299
-				throw new GenericShareException($message_t);
300
-			}
301
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
302
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
303
-				throw new GenericShareException($message_t);
304
-			}
305
-		}
306
-	}
307
-
308
-	/**
309
-	 * Validate if the expiration date fits the system settings
310
-	 *
311
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
312
-	 * @return \OCP\Share\IShare The modified share object
313
-	 * @throws GenericShareException
314
-	 * @throws \InvalidArgumentException
315
-	 * @throws \Exception
316
-	 */
317
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
318
-
319
-		$expirationDate = $share->getExpirationDate();
320
-
321
-		if ($expirationDate !== null) {
322
-			//Make sure the expiration date is a date
323
-			$expirationDate->setTime(0, 0, 0);
324
-
325
-			$date = new \DateTime();
326
-			$date->setTime(0, 0, 0);
327
-			if ($date >= $expirationDate) {
328
-				$message = $this->l->t('Expiration date is in the past');
329
-				throw new GenericShareException($message, $message, 404);
330
-			}
331
-		}
332
-
333
-		// If expiredate is empty set a default one if there is a default
334
-		$fullId = null;
335
-		try {
336
-			$fullId = $share->getFullId();
337
-		} catch (\UnexpectedValueException $e) {
338
-			// This is a new share
339
-		}
340
-
341
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
342
-			$expirationDate = new \DateTime();
343
-			$expirationDate->setTime(0,0,0);
344
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
345
-		}
346
-
347
-		// If we enforce the expiration date check that is does not exceed
348
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
349
-			if ($expirationDate === null) {
350
-				throw new \InvalidArgumentException('Expiration date is enforced');
351
-			}
352
-
353
-			$date = new \DateTime();
354
-			$date->setTime(0, 0, 0);
355
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
356
-			if ($date < $expirationDate) {
357
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
358
-				throw new GenericShareException($message, $message, 404);
359
-			}
360
-		}
361
-
362
-		$accepted = true;
363
-		$message = '';
364
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
365
-			'expirationDate' => &$expirationDate,
366
-			'accepted' => &$accepted,
367
-			'message' => &$message,
368
-			'passwordSet' => $share->getPassword() !== null,
369
-		]);
370
-
371
-		if (!$accepted) {
372
-			throw new \Exception($message);
373
-		}
374
-
375
-		$share->setExpirationDate($expirationDate);
376
-
377
-		return $share;
378
-	}
379
-
380
-	/**
381
-	 * Check for pre share requirements for user shares
382
-	 *
383
-	 * @param \OCP\Share\IShare $share
384
-	 * @throws \Exception
385
-	 */
386
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
387
-		// Check if we can share with group members only
388
-		if ($this->shareWithGroupMembersOnly()) {
389
-			$sharedBy = $this->userManager->get($share->getSharedBy());
390
-			$sharedWith = $this->userManager->get($share->getSharedWith());
391
-			// Verify we can share with this user
392
-			$groups = array_intersect(
393
-					$this->groupManager->getUserGroupIds($sharedBy),
394
-					$this->groupManager->getUserGroupIds($sharedWith)
395
-			);
396
-			if (empty($groups)) {
397
-				throw new \Exception('Sharing is only allowed with group members');
398
-			}
399
-		}
400
-
401
-		/*
274
+        $permissions = $share->getNode()->getPermissions();
275
+        $mount = $share->getNode()->getMountPoint();
276
+        if (!($mount instanceof MoveableMount)) {
277
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
278
+        }
279
+
280
+        // Check that we do not share with more permissions than we have
281
+        if ($share->getPermissions() & ~$permissions) {
282
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
283
+            throw new GenericShareException($message_t, $message_t, 404);
284
+        }
285
+
286
+
287
+        // Check that read permissions are always set
288
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
289
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
290
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
291
+        if (!$noReadPermissionRequired &&
292
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
293
+            throw new \InvalidArgumentException('Shares need at least read permissions');
294
+        }
295
+
296
+        if ($share->getNode() instanceof \OCP\Files\File) {
297
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
298
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
299
+                throw new GenericShareException($message_t);
300
+            }
301
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
302
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
303
+                throw new GenericShareException($message_t);
304
+            }
305
+        }
306
+    }
307
+
308
+    /**
309
+     * Validate if the expiration date fits the system settings
310
+     *
311
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
312
+     * @return \OCP\Share\IShare The modified share object
313
+     * @throws GenericShareException
314
+     * @throws \InvalidArgumentException
315
+     * @throws \Exception
316
+     */
317
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
318
+
319
+        $expirationDate = $share->getExpirationDate();
320
+
321
+        if ($expirationDate !== null) {
322
+            //Make sure the expiration date is a date
323
+            $expirationDate->setTime(0, 0, 0);
324
+
325
+            $date = new \DateTime();
326
+            $date->setTime(0, 0, 0);
327
+            if ($date >= $expirationDate) {
328
+                $message = $this->l->t('Expiration date is in the past');
329
+                throw new GenericShareException($message, $message, 404);
330
+            }
331
+        }
332
+
333
+        // If expiredate is empty set a default one if there is a default
334
+        $fullId = null;
335
+        try {
336
+            $fullId = $share->getFullId();
337
+        } catch (\UnexpectedValueException $e) {
338
+            // This is a new share
339
+        }
340
+
341
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
342
+            $expirationDate = new \DateTime();
343
+            $expirationDate->setTime(0,0,0);
344
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
345
+        }
346
+
347
+        // If we enforce the expiration date check that is does not exceed
348
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
349
+            if ($expirationDate === null) {
350
+                throw new \InvalidArgumentException('Expiration date is enforced');
351
+            }
352
+
353
+            $date = new \DateTime();
354
+            $date->setTime(0, 0, 0);
355
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
356
+            if ($date < $expirationDate) {
357
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
358
+                throw new GenericShareException($message, $message, 404);
359
+            }
360
+        }
361
+
362
+        $accepted = true;
363
+        $message = '';
364
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
365
+            'expirationDate' => &$expirationDate,
366
+            'accepted' => &$accepted,
367
+            'message' => &$message,
368
+            'passwordSet' => $share->getPassword() !== null,
369
+        ]);
370
+
371
+        if (!$accepted) {
372
+            throw new \Exception($message);
373
+        }
374
+
375
+        $share->setExpirationDate($expirationDate);
376
+
377
+        return $share;
378
+    }
379
+
380
+    /**
381
+     * Check for pre share requirements for user shares
382
+     *
383
+     * @param \OCP\Share\IShare $share
384
+     * @throws \Exception
385
+     */
386
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
387
+        // Check if we can share with group members only
388
+        if ($this->shareWithGroupMembersOnly()) {
389
+            $sharedBy = $this->userManager->get($share->getSharedBy());
390
+            $sharedWith = $this->userManager->get($share->getSharedWith());
391
+            // Verify we can share with this user
392
+            $groups = array_intersect(
393
+                    $this->groupManager->getUserGroupIds($sharedBy),
394
+                    $this->groupManager->getUserGroupIds($sharedWith)
395
+            );
396
+            if (empty($groups)) {
397
+                throw new \Exception('Sharing is only allowed with group members');
398
+            }
399
+        }
400
+
401
+        /*
402 402
 		 * TODO: Could be costly, fix
403 403
 		 *
404 404
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
405 405
 		 */
406
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
407
-		$existingShares = $provider->getSharesByPath($share->getNode());
408
-		foreach($existingShares as $existingShare) {
409
-			// Ignore if it is the same share
410
-			try {
411
-				if ($existingShare->getFullId() === $share->getFullId()) {
412
-					continue;
413
-				}
414
-			} catch (\UnexpectedValueException $e) {
415
-				//Shares are not identical
416
-			}
417
-
418
-			// Identical share already existst
419
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
420
-				throw new \Exception('Path is already shared with this user');
421
-			}
422
-
423
-			// The share is already shared with this user via a group share
424
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
425
-				$group = $this->groupManager->get($existingShare->getSharedWith());
426
-				if (!is_null($group)) {
427
-					$user = $this->userManager->get($share->getSharedWith());
428
-
429
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
430
-						throw new \Exception('Path is already shared with this user');
431
-					}
432
-				}
433
-			}
434
-		}
435
-	}
436
-
437
-	/**
438
-	 * Check for pre share requirements for group shares
439
-	 *
440
-	 * @param \OCP\Share\IShare $share
441
-	 * @throws \Exception
442
-	 */
443
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
444
-		// Verify group shares are allowed
445
-		if (!$this->allowGroupSharing()) {
446
-			throw new \Exception('Group sharing is now allowed');
447
-		}
448
-
449
-		// Verify if the user can share with this group
450
-		if ($this->shareWithGroupMembersOnly()) {
451
-			$sharedBy = $this->userManager->get($share->getSharedBy());
452
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
453
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
454
-				throw new \Exception('Sharing is only allowed within your own groups');
455
-			}
456
-		}
457
-
458
-		/*
406
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
407
+        $existingShares = $provider->getSharesByPath($share->getNode());
408
+        foreach($existingShares as $existingShare) {
409
+            // Ignore if it is the same share
410
+            try {
411
+                if ($existingShare->getFullId() === $share->getFullId()) {
412
+                    continue;
413
+                }
414
+            } catch (\UnexpectedValueException $e) {
415
+                //Shares are not identical
416
+            }
417
+
418
+            // Identical share already existst
419
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
420
+                throw new \Exception('Path is already shared with this user');
421
+            }
422
+
423
+            // The share is already shared with this user via a group share
424
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
425
+                $group = $this->groupManager->get($existingShare->getSharedWith());
426
+                if (!is_null($group)) {
427
+                    $user = $this->userManager->get($share->getSharedWith());
428
+
429
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
430
+                        throw new \Exception('Path is already shared with this user');
431
+                    }
432
+                }
433
+            }
434
+        }
435
+    }
436
+
437
+    /**
438
+     * Check for pre share requirements for group shares
439
+     *
440
+     * @param \OCP\Share\IShare $share
441
+     * @throws \Exception
442
+     */
443
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
444
+        // Verify group shares are allowed
445
+        if (!$this->allowGroupSharing()) {
446
+            throw new \Exception('Group sharing is now allowed');
447
+        }
448
+
449
+        // Verify if the user can share with this group
450
+        if ($this->shareWithGroupMembersOnly()) {
451
+            $sharedBy = $this->userManager->get($share->getSharedBy());
452
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
453
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
454
+                throw new \Exception('Sharing is only allowed within your own groups');
455
+            }
456
+        }
457
+
458
+        /*
459 459
 		 * TODO: Could be costly, fix
460 460
 		 *
461 461
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
462 462
 		 */
463
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
464
-		$existingShares = $provider->getSharesByPath($share->getNode());
465
-		foreach($existingShares as $existingShare) {
466
-			try {
467
-				if ($existingShare->getFullId() === $share->getFullId()) {
468
-					continue;
469
-				}
470
-			} catch (\UnexpectedValueException $e) {
471
-				//It is a new share so just continue
472
-			}
473
-
474
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
475
-				throw new \Exception('Path is already shared with this group');
476
-			}
477
-		}
478
-	}
479
-
480
-	/**
481
-	 * Check for pre share requirements for link shares
482
-	 *
483
-	 * @param \OCP\Share\IShare $share
484
-	 * @throws \Exception
485
-	 */
486
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
487
-		// Are link shares allowed?
488
-		if (!$this->shareApiAllowLinks()) {
489
-			throw new \Exception('Link sharing is not allowed');
490
-		}
491
-
492
-		// Link shares by definition can't have share permissions
493
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
494
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
495
-		}
496
-
497
-		// Check if public upload is allowed
498
-		if (!$this->shareApiLinkAllowPublicUpload() &&
499
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
500
-			throw new \InvalidArgumentException('Public upload is not allowed');
501
-		}
502
-	}
503
-
504
-	/**
505
-	 * To make sure we don't get invisible link shares we set the parent
506
-	 * of a link if it is a reshare. This is a quick word around
507
-	 * until we can properly display multiple link shares in the UI
508
-	 *
509
-	 * See: https://github.com/owncloud/core/issues/22295
510
-	 *
511
-	 * FIXME: Remove once multiple link shares can be properly displayed
512
-	 *
513
-	 * @param \OCP\Share\IShare $share
514
-	 */
515
-	protected function setLinkParent(\OCP\Share\IShare $share) {
516
-
517
-		// No sense in checking if the method is not there.
518
-		if (method_exists($share, 'setParent')) {
519
-			$storage = $share->getNode()->getStorage();
520
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
521
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
522
-				$share->setParent($storage->getShareId());
523
-			}
524
-		};
525
-	}
526
-
527
-	/**
528
-	 * @param File|Folder $path
529
-	 */
530
-	protected function pathCreateChecks($path) {
531
-		// Make sure that we do not share a path that contains a shared mountpoint
532
-		if ($path instanceof \OCP\Files\Folder) {
533
-			$mounts = $this->mountManager->findIn($path->getPath());
534
-			foreach($mounts as $mount) {
535
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536
-					throw new \InvalidArgumentException('Path contains files shared with you');
537
-				}
538
-			}
539
-		}
540
-	}
541
-
542
-	/**
543
-	 * Check if the user that is sharing can actually share
544
-	 *
545
-	 * @param \OCP\Share\IShare $share
546
-	 * @throws \Exception
547
-	 */
548
-	protected function canShare(\OCP\Share\IShare $share) {
549
-		if (!$this->shareApiEnabled()) {
550
-			throw new \Exception('Sharing is disabled');
551
-		}
552
-
553
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
554
-			throw new \Exception('Sharing is disabled for you');
555
-		}
556
-	}
557
-
558
-	/**
559
-	 * Share a path
560
-	 *
561
-	 * @param \OCP\Share\IShare $share
562
-	 * @return Share The share object
563
-	 * @throws \Exception
564
-	 *
565
-	 * TODO: handle link share permissions or check them
566
-	 */
567
-	public function createShare(\OCP\Share\IShare $share) {
568
-		$this->canShare($share);
569
-
570
-		$this->generalCreateChecks($share);
571
-
572
-		// Verify if there are any issues with the path
573
-		$this->pathCreateChecks($share->getNode());
574
-
575
-		/*
463
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
464
+        $existingShares = $provider->getSharesByPath($share->getNode());
465
+        foreach($existingShares as $existingShare) {
466
+            try {
467
+                if ($existingShare->getFullId() === $share->getFullId()) {
468
+                    continue;
469
+                }
470
+            } catch (\UnexpectedValueException $e) {
471
+                //It is a new share so just continue
472
+            }
473
+
474
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
475
+                throw new \Exception('Path is already shared with this group');
476
+            }
477
+        }
478
+    }
479
+
480
+    /**
481
+     * Check for pre share requirements for link shares
482
+     *
483
+     * @param \OCP\Share\IShare $share
484
+     * @throws \Exception
485
+     */
486
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
487
+        // Are link shares allowed?
488
+        if (!$this->shareApiAllowLinks()) {
489
+            throw new \Exception('Link sharing is not allowed');
490
+        }
491
+
492
+        // Link shares by definition can't have share permissions
493
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
494
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
495
+        }
496
+
497
+        // Check if public upload is allowed
498
+        if (!$this->shareApiLinkAllowPublicUpload() &&
499
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
500
+            throw new \InvalidArgumentException('Public upload is not allowed');
501
+        }
502
+    }
503
+
504
+    /**
505
+     * To make sure we don't get invisible link shares we set the parent
506
+     * of a link if it is a reshare. This is a quick word around
507
+     * until we can properly display multiple link shares in the UI
508
+     *
509
+     * See: https://github.com/owncloud/core/issues/22295
510
+     *
511
+     * FIXME: Remove once multiple link shares can be properly displayed
512
+     *
513
+     * @param \OCP\Share\IShare $share
514
+     */
515
+    protected function setLinkParent(\OCP\Share\IShare $share) {
516
+
517
+        // No sense in checking if the method is not there.
518
+        if (method_exists($share, 'setParent')) {
519
+            $storage = $share->getNode()->getStorage();
520
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
521
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
522
+                $share->setParent($storage->getShareId());
523
+            }
524
+        };
525
+    }
526
+
527
+    /**
528
+     * @param File|Folder $path
529
+     */
530
+    protected function pathCreateChecks($path) {
531
+        // Make sure that we do not share a path that contains a shared mountpoint
532
+        if ($path instanceof \OCP\Files\Folder) {
533
+            $mounts = $this->mountManager->findIn($path->getPath());
534
+            foreach($mounts as $mount) {
535
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536
+                    throw new \InvalidArgumentException('Path contains files shared with you');
537
+                }
538
+            }
539
+        }
540
+    }
541
+
542
+    /**
543
+     * Check if the user that is sharing can actually share
544
+     *
545
+     * @param \OCP\Share\IShare $share
546
+     * @throws \Exception
547
+     */
548
+    protected function canShare(\OCP\Share\IShare $share) {
549
+        if (!$this->shareApiEnabled()) {
550
+            throw new \Exception('Sharing is disabled');
551
+        }
552
+
553
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
554
+            throw new \Exception('Sharing is disabled for you');
555
+        }
556
+    }
557
+
558
+    /**
559
+     * Share a path
560
+     *
561
+     * @param \OCP\Share\IShare $share
562
+     * @return Share The share object
563
+     * @throws \Exception
564
+     *
565
+     * TODO: handle link share permissions or check them
566
+     */
567
+    public function createShare(\OCP\Share\IShare $share) {
568
+        $this->canShare($share);
569
+
570
+        $this->generalCreateChecks($share);
571
+
572
+        // Verify if there are any issues with the path
573
+        $this->pathCreateChecks($share->getNode());
574
+
575
+        /*
576 576
 		 * On creation of a share the owner is always the owner of the path
577 577
 		 * Except for mounted federated shares.
578 578
 		 */
579
-		$storage = $share->getNode()->getStorage();
580
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
581
-			$parent = $share->getNode()->getParent();
582
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
583
-				$parent = $parent->getParent();
584
-			}
585
-			$share->setShareOwner($parent->getOwner()->getUID());
586
-		} else {
587
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
588
-		}
589
-
590
-		//Verify share type
591
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
592
-			$this->userCreateChecks($share);
593
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
594
-			$this->groupCreateChecks($share);
595
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
596
-			$this->linkCreateChecks($share);
597
-			$this->setLinkParent($share);
598
-
599
-			/*
579
+        $storage = $share->getNode()->getStorage();
580
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
581
+            $parent = $share->getNode()->getParent();
582
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
583
+                $parent = $parent->getParent();
584
+            }
585
+            $share->setShareOwner($parent->getOwner()->getUID());
586
+        } else {
587
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
588
+        }
589
+
590
+        //Verify share type
591
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
592
+            $this->userCreateChecks($share);
593
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
594
+            $this->groupCreateChecks($share);
595
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
596
+            $this->linkCreateChecks($share);
597
+            $this->setLinkParent($share);
598
+
599
+            /*
600 600
 			 * For now ignore a set token.
601 601
 			 */
602
-			$share->setToken(
603
-				$this->secureRandom->generate(
604
-					\OC\Share\Constants::TOKEN_LENGTH,
605
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
606
-				)
607
-			);
608
-
609
-			//Verify the expiration date
610
-			$this->validateExpirationDate($share);
611
-
612
-			//Verify the password
613
-			$this->verifyPassword($share->getPassword());
614
-
615
-			// If a password is set. Hash it!
616
-			if ($share->getPassword() !== null) {
617
-				$share->setPassword($this->hasher->hash($share->getPassword()));
618
-			}
619
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
620
-			$share->setToken(
621
-				$this->secureRandom->generate(
622
-					\OC\Share\Constants::TOKEN_LENGTH,
623
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
624
-				)
625
-			);
626
-		}
627
-
628
-		// Cannot share with the owner
629
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
630
-			$share->getSharedWith() === $share->getShareOwner()) {
631
-			throw new \InvalidArgumentException('Can’t share with the share owner');
632
-		}
633
-
634
-		// Generate the target
635
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
636
-		$target = \OC\Files\Filesystem::normalizePath($target);
637
-		$share->setTarget($target);
638
-
639
-		// Pre share event
640
-		$event = new GenericEvent($share);
641
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
642
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
643
-			throw new \Exception($event->getArgument('error'));
644
-		}
645
-
646
-		$oldShare = $share;
647
-		$provider = $this->factory->getProviderForType($share->getShareType());
648
-		$share = $provider->create($share);
649
-		//reuse the node we already have
650
-		$share->setNode($oldShare->getNode());
651
-
652
-		// Post share event
653
-		$event = new GenericEvent($share);
654
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
655
-
656
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
657
-			$user = $this->userManager->get($share->getSharedWith());
658
-			if ($user !== null) {
659
-				$emailAddress = $user->getEMailAddress();
660
-				if ($emailAddress !== null && $emailAddress !== '') {
661
-					$this->sendMailNotification(
662
-						$share->getNode()->getName(),
663
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
664
-						$share->getSharedBy(),
665
-						$emailAddress,
666
-						$share->getExpirationDate()
667
-					);
668
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
669
-				} else {
670
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
671
-				}
672
-			} else {
673
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
674
-			}
675
-		}
676
-
677
-		return $share;
678
-	}
679
-
680
-	/**
681
-	 * Sends again the e-mail notification for a share
682
-	 *
683
-	 * @param \OCP\Share\IShare $share
684
-	 * @return \OCP\Share\IShare the share object
685
-	 * @throws \InvalidArgumentException if share type does not support mail
686
-	 *         notifications or the sharee has no known e-mail address
687
-	 * @throws \Exception if mail could not be sent
688
-	 */
689
-	public function resendMailNotification(\OCP\Share\IShare $share) {
690
-		$this->canShare($share);
691
-
692
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
693
-			throw new \InvalidArgumentException("Share mail notification can be sent only for user shares");
694
-		}
695
-
696
-		$user = $this->userManager->get($share->getSharedWith());
697
-		$emailAddress = $user->getEMailAddress();
698
-
699
-		if ($emailAddress === null || $emailAddress === '') {
700
-			throw new \InvalidArgumentException("Share mail notification can not be sent to a user without a mail");
701
-		}
702
-
703
-		$this->sendMailNotification(
704
-			$share->getNode()->getName(),
705
-			$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
706
-			$share->getSharedBy(),
707
-			$emailAddress
708
-		);
709
-
710
-		return $share;
711
-	}
712
-
713
-	/**
714
-	 * @param string $filename file/folder name
715
-	 * @param string $link link to the file/folder
716
-	 * @param string $initiator user ID of share sender
717
-	 * @param string $shareWith email address of share receiver
718
-	 * @param \DateTime|null $expiration
719
-	 * @throws \Exception If mail couldn't be sent
720
-	 */
721
-	protected function sendMailNotification($filename,
722
-											$link,
723
-											$initiator,
724
-											$shareWith,
725
-											\DateTime $expiration = null) {
726
-		$initiatorUser = $this->userManager->get($initiator);
727
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
728
-		$subject = (string)$this->l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
729
-
730
-		$message = $this->mailer->createMessage();
731
-
732
-		$emailTemplate = $this->mailer->createEMailTemplate();
733
-		$emailTemplate->setMetaData('files_sharing.RecipientNotification', [
734
-			'filename' => $filename,
735
-			'link' => $link,
736
-			'initiator' => $initiatorDisplayName,
737
-			'expiration' => $expiration,
738
-			'shareWith' => $shareWith,
739
-		]);
740
-
741
-		$emailTemplate->addHeader();
742
-		$emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
743
-		$text = $this->l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
744
-
745
-		$emailTemplate->addBodyText(
746
-			$text . ' ' . $this->l->t('Click the button below to open it.'),
747
-			$text
748
-		);
749
-		$emailTemplate->addBodyButton(
750
-			$this->l->t('Open »%s«', [$filename]),
751
-			$link
752
-		);
753
-
754
-		$message->setTo([$shareWith]);
755
-
756
-		// The "From" contains the sharers name
757
-		$instanceName = $this->defaults->getName();
758
-		$senderName = $this->l->t(
759
-			'%s via %s',
760
-			[
761
-				$initiatorDisplayName,
762
-				$instanceName
763
-			]
764
-		);
765
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
766
-
767
-		// The "Reply-To" is set to the sharer if an mail address is configured
768
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
769
-		$initiatorEmail = $initiatorUser->getEMailAddress();
770
-		if($initiatorEmail !== null) {
771
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
772
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
773
-		} else {
774
-			$emailTemplate->addFooter();
775
-		}
776
-
777
-		$message->setSubject($subject);
778
-		$message->setPlainBody($emailTemplate->renderText());
779
-		$message->setHtmlBody($emailTemplate->renderHtml());
780
-		$this->mailer->send($message);
781
-	}
782
-
783
-	/**
784
-	 * Update a share
785
-	 *
786
-	 * @param \OCP\Share\IShare $share
787
-	 * @return \OCP\Share\IShare The share object
788
-	 * @throws \InvalidArgumentException
789
-	 */
790
-	public function updateShare(\OCP\Share\IShare $share) {
791
-		$expirationDateUpdated = false;
792
-
793
-		$this->canShare($share);
794
-
795
-		try {
796
-			$originalShare = $this->getShareById($share->getFullId());
797
-		} catch (\UnexpectedValueException $e) {
798
-			throw new \InvalidArgumentException('Share does not have a full id');
799
-		}
800
-
801
-		// We can't change the share type!
802
-		if ($share->getShareType() !== $originalShare->getShareType()) {
803
-			throw new \InvalidArgumentException('Can’t change share type');
804
-		}
805
-
806
-		// We can only change the recipient on user shares
807
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
808
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
809
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
810
-		}
811
-
812
-		// Cannot share with the owner
813
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
814
-			$share->getSharedWith() === $share->getShareOwner()) {
815
-			throw new \InvalidArgumentException('Can’t share with the share owner');
816
-		}
817
-
818
-		$this->generalCreateChecks($share);
819
-
820
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
821
-			$this->userCreateChecks($share);
822
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
823
-			$this->groupCreateChecks($share);
824
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
825
-			$this->linkCreateChecks($share);
826
-
827
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
828
-
829
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
830
-				//Verify the expiration date
831
-				$this->validateExpirationDate($share);
832
-				$expirationDateUpdated = true;
833
-			}
834
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
835
-			$plainTextPassword = $share->getPassword();
836
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
837
-				$plainTextPassword = null;
838
-			}
839
-		}
840
-
841
-		$this->pathCreateChecks($share->getNode());
842
-
843
-		// Now update the share!
844
-		$provider = $this->factory->getProviderForType($share->getShareType());
845
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
846
-			$share = $provider->update($share, $plainTextPassword);
847
-		} else {
848
-			$share = $provider->update($share);
849
-		}
850
-
851
-		if ($expirationDateUpdated === true) {
852
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
853
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
854
-				'itemSource' => $share->getNode()->getId(),
855
-				'date' => $share->getExpirationDate(),
856
-				'uidOwner' => $share->getSharedBy(),
857
-			]);
858
-		}
859
-
860
-		if ($share->getPassword() !== $originalShare->getPassword()) {
861
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
862
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
863
-				'itemSource' => $share->getNode()->getId(),
864
-				'uidOwner' => $share->getSharedBy(),
865
-				'token' => $share->getToken(),
866
-				'disabled' => is_null($share->getPassword()),
867
-			]);
868
-		}
869
-
870
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
871
-			if ($this->userManager->userExists($share->getShareOwner())) {
872
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
873
-			} else {
874
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
875
-			}
876
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
877
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
878
-				'itemSource' => $share->getNode()->getId(),
879
-				'shareType' => $share->getShareType(),
880
-				'shareWith' => $share->getSharedWith(),
881
-				'uidOwner' => $share->getSharedBy(),
882
-				'permissions' => $share->getPermissions(),
883
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
884
-			));
885
-		}
886
-
887
-		return $share;
888
-	}
889
-
890
-	/**
891
-	 * Updates the password of the given share if it is not the same as the
892
-	 * password of the original share.
893
-	 *
894
-	 * @param \OCP\Share\IShare $share the share to update its password.
895
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
896
-	 *        password with.
897
-	 * @return boolean whether the password was updated or not.
898
-	 */
899
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
900
-		// Password updated.
901
-		if ($share->getPassword() !== $originalShare->getPassword()) {
902
-			//Verify the password
903
-			$this->verifyPassword($share->getPassword());
904
-
905
-			// If a password is set. Hash it!
906
-			if ($share->getPassword() !== null) {
907
-				$share->setPassword($this->hasher->hash($share->getPassword()));
908
-
909
-				return true;
910
-			}
911
-		}
912
-
913
-		return false;
914
-	}
915
-
916
-	/**
917
-	 * Delete all the children of this share
918
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
919
-	 *
920
-	 * @param \OCP\Share\IShare $share
921
-	 * @return \OCP\Share\IShare[] List of deleted shares
922
-	 */
923
-	protected function deleteChildren(\OCP\Share\IShare $share) {
924
-		$deletedShares = [];
925
-
926
-		$provider = $this->factory->getProviderForType($share->getShareType());
927
-
928
-		foreach ($provider->getChildren($share) as $child) {
929
-			$deletedChildren = $this->deleteChildren($child);
930
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
931
-
932
-			$provider->delete($child);
933
-			$deletedShares[] = $child;
934
-		}
935
-
936
-		return $deletedShares;
937
-	}
938
-
939
-	/**
940
-	 * Delete a share
941
-	 *
942
-	 * @param \OCP\Share\IShare $share
943
-	 * @throws ShareNotFound
944
-	 * @throws \InvalidArgumentException
945
-	 */
946
-	public function deleteShare(\OCP\Share\IShare $share) {
947
-
948
-		try {
949
-			$share->getFullId();
950
-		} catch (\UnexpectedValueException $e) {
951
-			throw new \InvalidArgumentException('Share does not have a full id');
952
-		}
953
-
954
-		$event = new GenericEvent($share);
955
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
956
-
957
-		// Get all children and delete them as well
958
-		$deletedShares = $this->deleteChildren($share);
959
-
960
-		// Do the actual delete
961
-		$provider = $this->factory->getProviderForType($share->getShareType());
962
-		$provider->delete($share);
963
-
964
-		// All the deleted shares caused by this delete
965
-		$deletedShares[] = $share;
966
-
967
-		// Emit post hook
968
-		$event->setArgument('deletedShares', $deletedShares);
969
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
970
-	}
971
-
972
-
973
-	/**
974
-	 * Unshare a file as the recipient.
975
-	 * This can be different from a regular delete for example when one of
976
-	 * the users in a groups deletes that share. But the provider should
977
-	 * handle this.
978
-	 *
979
-	 * @param \OCP\Share\IShare $share
980
-	 * @param string $recipientId
981
-	 */
982
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
983
-		list($providerId, ) = $this->splitFullId($share->getFullId());
984
-		$provider = $this->factory->getProvider($providerId);
985
-
986
-		$provider->deleteFromSelf($share, $recipientId);
987
-		$event = new GenericEvent($share);
988
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
989
-	}
990
-
991
-	/**
992
-	 * @inheritdoc
993
-	 */
994
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
995
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
996
-			throw new \InvalidArgumentException('Can’t change target of link share');
997
-		}
998
-
999
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1000
-			throw new \InvalidArgumentException('Invalid recipient');
1001
-		}
1002
-
1003
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1004
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1005
-			if (is_null($sharedWith)) {
1006
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1007
-			}
1008
-			$recipient = $this->userManager->get($recipientId);
1009
-			if (!$sharedWith->inGroup($recipient)) {
1010
-				throw new \InvalidArgumentException('Invalid recipient');
1011
-			}
1012
-		}
1013
-
1014
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1015
-		$provider = $this->factory->getProvider($providerId);
1016
-
1017
-		$provider->move($share, $recipientId);
1018
-	}
1019
-
1020
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1021
-		$providers = $this->factory->getAllProviders();
1022
-
1023
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1024
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1025
-			foreach ($newShares as $fid => $data) {
1026
-				if (!isset($shares[$fid])) {
1027
-					$shares[$fid] = [];
1028
-				}
1029
-
1030
-				$shares[$fid] = array_merge($shares[$fid], $data);
1031
-			}
1032
-			return $shares;
1033
-		}, []);
1034
-	}
1035
-
1036
-	/**
1037
-	 * @inheritdoc
1038
-	 */
1039
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1040
-		if ($path !== null &&
1041
-				!($path instanceof \OCP\Files\File) &&
1042
-				!($path instanceof \OCP\Files\Folder)) {
1043
-			throw new \InvalidArgumentException('invalid path');
1044
-		}
1045
-
1046
-		try {
1047
-			$provider = $this->factory->getProviderForType($shareType);
1048
-		} catch (ProviderException $e) {
1049
-			return [];
1050
-		}
1051
-
1052
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1053
-
1054
-		/*
602
+            $share->setToken(
603
+                $this->secureRandom->generate(
604
+                    \OC\Share\Constants::TOKEN_LENGTH,
605
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
606
+                )
607
+            );
608
+
609
+            //Verify the expiration date
610
+            $this->validateExpirationDate($share);
611
+
612
+            //Verify the password
613
+            $this->verifyPassword($share->getPassword());
614
+
615
+            // If a password is set. Hash it!
616
+            if ($share->getPassword() !== null) {
617
+                $share->setPassword($this->hasher->hash($share->getPassword()));
618
+            }
619
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
620
+            $share->setToken(
621
+                $this->secureRandom->generate(
622
+                    \OC\Share\Constants::TOKEN_LENGTH,
623
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
624
+                )
625
+            );
626
+        }
627
+
628
+        // Cannot share with the owner
629
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
630
+            $share->getSharedWith() === $share->getShareOwner()) {
631
+            throw new \InvalidArgumentException('Can’t share with the share owner');
632
+        }
633
+
634
+        // Generate the target
635
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
636
+        $target = \OC\Files\Filesystem::normalizePath($target);
637
+        $share->setTarget($target);
638
+
639
+        // Pre share event
640
+        $event = new GenericEvent($share);
641
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
642
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
643
+            throw new \Exception($event->getArgument('error'));
644
+        }
645
+
646
+        $oldShare = $share;
647
+        $provider = $this->factory->getProviderForType($share->getShareType());
648
+        $share = $provider->create($share);
649
+        //reuse the node we already have
650
+        $share->setNode($oldShare->getNode());
651
+
652
+        // Post share event
653
+        $event = new GenericEvent($share);
654
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
655
+
656
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
657
+            $user = $this->userManager->get($share->getSharedWith());
658
+            if ($user !== null) {
659
+                $emailAddress = $user->getEMailAddress();
660
+                if ($emailAddress !== null && $emailAddress !== '') {
661
+                    $this->sendMailNotification(
662
+                        $share->getNode()->getName(),
663
+                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
664
+                        $share->getSharedBy(),
665
+                        $emailAddress,
666
+                        $share->getExpirationDate()
667
+                    );
668
+                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
669
+                } else {
670
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
671
+                }
672
+            } else {
673
+                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
674
+            }
675
+        }
676
+
677
+        return $share;
678
+    }
679
+
680
+    /**
681
+     * Sends again the e-mail notification for a share
682
+     *
683
+     * @param \OCP\Share\IShare $share
684
+     * @return \OCP\Share\IShare the share object
685
+     * @throws \InvalidArgumentException if share type does not support mail
686
+     *         notifications or the sharee has no known e-mail address
687
+     * @throws \Exception if mail could not be sent
688
+     */
689
+    public function resendMailNotification(\OCP\Share\IShare $share) {
690
+        $this->canShare($share);
691
+
692
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
693
+            throw new \InvalidArgumentException("Share mail notification can be sent only for user shares");
694
+        }
695
+
696
+        $user = $this->userManager->get($share->getSharedWith());
697
+        $emailAddress = $user->getEMailAddress();
698
+
699
+        if ($emailAddress === null || $emailAddress === '') {
700
+            throw new \InvalidArgumentException("Share mail notification can not be sent to a user without a mail");
701
+        }
702
+
703
+        $this->sendMailNotification(
704
+            $share->getNode()->getName(),
705
+            $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
706
+            $share->getSharedBy(),
707
+            $emailAddress
708
+        );
709
+
710
+        return $share;
711
+    }
712
+
713
+    /**
714
+     * @param string $filename file/folder name
715
+     * @param string $link link to the file/folder
716
+     * @param string $initiator user ID of share sender
717
+     * @param string $shareWith email address of share receiver
718
+     * @param \DateTime|null $expiration
719
+     * @throws \Exception If mail couldn't be sent
720
+     */
721
+    protected function sendMailNotification($filename,
722
+                                            $link,
723
+                                            $initiator,
724
+                                            $shareWith,
725
+                                            \DateTime $expiration = null) {
726
+        $initiatorUser = $this->userManager->get($initiator);
727
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
728
+        $subject = (string)$this->l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
729
+
730
+        $message = $this->mailer->createMessage();
731
+
732
+        $emailTemplate = $this->mailer->createEMailTemplate();
733
+        $emailTemplate->setMetaData('files_sharing.RecipientNotification', [
734
+            'filename' => $filename,
735
+            'link' => $link,
736
+            'initiator' => $initiatorDisplayName,
737
+            'expiration' => $expiration,
738
+            'shareWith' => $shareWith,
739
+        ]);
740
+
741
+        $emailTemplate->addHeader();
742
+        $emailTemplate->addHeading($this->l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
743
+        $text = $this->l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
744
+
745
+        $emailTemplate->addBodyText(
746
+            $text . ' ' . $this->l->t('Click the button below to open it.'),
747
+            $text
748
+        );
749
+        $emailTemplate->addBodyButton(
750
+            $this->l->t('Open »%s«', [$filename]),
751
+            $link
752
+        );
753
+
754
+        $message->setTo([$shareWith]);
755
+
756
+        // The "From" contains the sharers name
757
+        $instanceName = $this->defaults->getName();
758
+        $senderName = $this->l->t(
759
+            '%s via %s',
760
+            [
761
+                $initiatorDisplayName,
762
+                $instanceName
763
+            ]
764
+        );
765
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
766
+
767
+        // The "Reply-To" is set to the sharer if an mail address is configured
768
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
769
+        $initiatorEmail = $initiatorUser->getEMailAddress();
770
+        if($initiatorEmail !== null) {
771
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
772
+            $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
773
+        } else {
774
+            $emailTemplate->addFooter();
775
+        }
776
+
777
+        $message->setSubject($subject);
778
+        $message->setPlainBody($emailTemplate->renderText());
779
+        $message->setHtmlBody($emailTemplate->renderHtml());
780
+        $this->mailer->send($message);
781
+    }
782
+
783
+    /**
784
+     * Update a share
785
+     *
786
+     * @param \OCP\Share\IShare $share
787
+     * @return \OCP\Share\IShare The share object
788
+     * @throws \InvalidArgumentException
789
+     */
790
+    public function updateShare(\OCP\Share\IShare $share) {
791
+        $expirationDateUpdated = false;
792
+
793
+        $this->canShare($share);
794
+
795
+        try {
796
+            $originalShare = $this->getShareById($share->getFullId());
797
+        } catch (\UnexpectedValueException $e) {
798
+            throw new \InvalidArgumentException('Share does not have a full id');
799
+        }
800
+
801
+        // We can't change the share type!
802
+        if ($share->getShareType() !== $originalShare->getShareType()) {
803
+            throw new \InvalidArgumentException('Can’t change share type');
804
+        }
805
+
806
+        // We can only change the recipient on user shares
807
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
808
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
809
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
810
+        }
811
+
812
+        // Cannot share with the owner
813
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
814
+            $share->getSharedWith() === $share->getShareOwner()) {
815
+            throw new \InvalidArgumentException('Can’t share with the share owner');
816
+        }
817
+
818
+        $this->generalCreateChecks($share);
819
+
820
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
821
+            $this->userCreateChecks($share);
822
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
823
+            $this->groupCreateChecks($share);
824
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
825
+            $this->linkCreateChecks($share);
826
+
827
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
828
+
829
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
830
+                //Verify the expiration date
831
+                $this->validateExpirationDate($share);
832
+                $expirationDateUpdated = true;
833
+            }
834
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
835
+            $plainTextPassword = $share->getPassword();
836
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
837
+                $plainTextPassword = null;
838
+            }
839
+        }
840
+
841
+        $this->pathCreateChecks($share->getNode());
842
+
843
+        // Now update the share!
844
+        $provider = $this->factory->getProviderForType($share->getShareType());
845
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
846
+            $share = $provider->update($share, $plainTextPassword);
847
+        } else {
848
+            $share = $provider->update($share);
849
+        }
850
+
851
+        if ($expirationDateUpdated === true) {
852
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
853
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
854
+                'itemSource' => $share->getNode()->getId(),
855
+                'date' => $share->getExpirationDate(),
856
+                'uidOwner' => $share->getSharedBy(),
857
+            ]);
858
+        }
859
+
860
+        if ($share->getPassword() !== $originalShare->getPassword()) {
861
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
862
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
863
+                'itemSource' => $share->getNode()->getId(),
864
+                'uidOwner' => $share->getSharedBy(),
865
+                'token' => $share->getToken(),
866
+                'disabled' => is_null($share->getPassword()),
867
+            ]);
868
+        }
869
+
870
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
871
+            if ($this->userManager->userExists($share->getShareOwner())) {
872
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
873
+            } else {
874
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
875
+            }
876
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
877
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
878
+                'itemSource' => $share->getNode()->getId(),
879
+                'shareType' => $share->getShareType(),
880
+                'shareWith' => $share->getSharedWith(),
881
+                'uidOwner' => $share->getSharedBy(),
882
+                'permissions' => $share->getPermissions(),
883
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
884
+            ));
885
+        }
886
+
887
+        return $share;
888
+    }
889
+
890
+    /**
891
+     * Updates the password of the given share if it is not the same as the
892
+     * password of the original share.
893
+     *
894
+     * @param \OCP\Share\IShare $share the share to update its password.
895
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
896
+     *        password with.
897
+     * @return boolean whether the password was updated or not.
898
+     */
899
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
900
+        // Password updated.
901
+        if ($share->getPassword() !== $originalShare->getPassword()) {
902
+            //Verify the password
903
+            $this->verifyPassword($share->getPassword());
904
+
905
+            // If a password is set. Hash it!
906
+            if ($share->getPassword() !== null) {
907
+                $share->setPassword($this->hasher->hash($share->getPassword()));
908
+
909
+                return true;
910
+            }
911
+        }
912
+
913
+        return false;
914
+    }
915
+
916
+    /**
917
+     * Delete all the children of this share
918
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
919
+     *
920
+     * @param \OCP\Share\IShare $share
921
+     * @return \OCP\Share\IShare[] List of deleted shares
922
+     */
923
+    protected function deleteChildren(\OCP\Share\IShare $share) {
924
+        $deletedShares = [];
925
+
926
+        $provider = $this->factory->getProviderForType($share->getShareType());
927
+
928
+        foreach ($provider->getChildren($share) as $child) {
929
+            $deletedChildren = $this->deleteChildren($child);
930
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
931
+
932
+            $provider->delete($child);
933
+            $deletedShares[] = $child;
934
+        }
935
+
936
+        return $deletedShares;
937
+    }
938
+
939
+    /**
940
+     * Delete a share
941
+     *
942
+     * @param \OCP\Share\IShare $share
943
+     * @throws ShareNotFound
944
+     * @throws \InvalidArgumentException
945
+     */
946
+    public function deleteShare(\OCP\Share\IShare $share) {
947
+
948
+        try {
949
+            $share->getFullId();
950
+        } catch (\UnexpectedValueException $e) {
951
+            throw new \InvalidArgumentException('Share does not have a full id');
952
+        }
953
+
954
+        $event = new GenericEvent($share);
955
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
956
+
957
+        // Get all children and delete them as well
958
+        $deletedShares = $this->deleteChildren($share);
959
+
960
+        // Do the actual delete
961
+        $provider = $this->factory->getProviderForType($share->getShareType());
962
+        $provider->delete($share);
963
+
964
+        // All the deleted shares caused by this delete
965
+        $deletedShares[] = $share;
966
+
967
+        // Emit post hook
968
+        $event->setArgument('deletedShares', $deletedShares);
969
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
970
+    }
971
+
972
+
973
+    /**
974
+     * Unshare a file as the recipient.
975
+     * This can be different from a regular delete for example when one of
976
+     * the users in a groups deletes that share. But the provider should
977
+     * handle this.
978
+     *
979
+     * @param \OCP\Share\IShare $share
980
+     * @param string $recipientId
981
+     */
982
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
983
+        list($providerId, ) = $this->splitFullId($share->getFullId());
984
+        $provider = $this->factory->getProvider($providerId);
985
+
986
+        $provider->deleteFromSelf($share, $recipientId);
987
+        $event = new GenericEvent($share);
988
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
989
+    }
990
+
991
+    /**
992
+     * @inheritdoc
993
+     */
994
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
995
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
996
+            throw new \InvalidArgumentException('Can’t change target of link share');
997
+        }
998
+
999
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1000
+            throw new \InvalidArgumentException('Invalid recipient');
1001
+        }
1002
+
1003
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1004
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1005
+            if (is_null($sharedWith)) {
1006
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1007
+            }
1008
+            $recipient = $this->userManager->get($recipientId);
1009
+            if (!$sharedWith->inGroup($recipient)) {
1010
+                throw new \InvalidArgumentException('Invalid recipient');
1011
+            }
1012
+        }
1013
+
1014
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1015
+        $provider = $this->factory->getProvider($providerId);
1016
+
1017
+        $provider->move($share, $recipientId);
1018
+    }
1019
+
1020
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1021
+        $providers = $this->factory->getAllProviders();
1022
+
1023
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1024
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1025
+            foreach ($newShares as $fid => $data) {
1026
+                if (!isset($shares[$fid])) {
1027
+                    $shares[$fid] = [];
1028
+                }
1029
+
1030
+                $shares[$fid] = array_merge($shares[$fid], $data);
1031
+            }
1032
+            return $shares;
1033
+        }, []);
1034
+    }
1035
+
1036
+    /**
1037
+     * @inheritdoc
1038
+     */
1039
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1040
+        if ($path !== null &&
1041
+                !($path instanceof \OCP\Files\File) &&
1042
+                !($path instanceof \OCP\Files\Folder)) {
1043
+            throw new \InvalidArgumentException('invalid path');
1044
+        }
1045
+
1046
+        try {
1047
+            $provider = $this->factory->getProviderForType($shareType);
1048
+        } catch (ProviderException $e) {
1049
+            return [];
1050
+        }
1051
+
1052
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1053
+
1054
+        /*
1055 1055
 		 * Work around so we don't return expired shares but still follow
1056 1056
 		 * proper pagination.
1057 1057
 		 */
1058 1058
 
1059
-		$shares2 = [];
1060
-
1061
-		while(true) {
1062
-			$added = 0;
1063
-			foreach ($shares as $share) {
1064
-
1065
-				try {
1066
-					$this->checkExpireDate($share);
1067
-				} catch (ShareNotFound $e) {
1068
-					//Ignore since this basically means the share is deleted
1069
-					continue;
1070
-				}
1071
-
1072
-				$added++;
1073
-				$shares2[] = $share;
1074
-
1075
-				if (count($shares2) === $limit) {
1076
-					break;
1077
-				}
1078
-			}
1079
-
1080
-			if (count($shares2) === $limit) {
1081
-				break;
1082
-			}
1083
-
1084
-			// If there was no limit on the select we are done
1085
-			if ($limit === -1) {
1086
-				break;
1087
-			}
1088
-
1089
-			$offset += $added;
1090
-
1091
-			// Fetch again $limit shares
1092
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1093
-
1094
-			// No more shares means we are done
1095
-			if (empty($shares)) {
1096
-				break;
1097
-			}
1098
-		}
1099
-
1100
-		$shares = $shares2;
1101
-
1102
-		return $shares;
1103
-	}
1104
-
1105
-	/**
1106
-	 * @inheritdoc
1107
-	 */
1108
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1109
-		try {
1110
-			$provider = $this->factory->getProviderForType($shareType);
1111
-		} catch (ProviderException $e) {
1112
-			return [];
1113
-		}
1114
-
1115
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1116
-
1117
-		// remove all shares which are already expired
1118
-		foreach ($shares as $key => $share) {
1119
-			try {
1120
-				$this->checkExpireDate($share);
1121
-			} catch (ShareNotFound $e) {
1122
-				unset($shares[$key]);
1123
-			}
1124
-		}
1125
-
1126
-		return $shares;
1127
-	}
1128
-
1129
-	/**
1130
-	 * @inheritdoc
1131
-	 */
1132
-	public function getShareById($id, $recipient = null) {
1133
-		if ($id === null) {
1134
-			throw new ShareNotFound();
1135
-		}
1136
-
1137
-		list($providerId, $id) = $this->splitFullId($id);
1138
-
1139
-		try {
1140
-			$provider = $this->factory->getProvider($providerId);
1141
-		} catch (ProviderException $e) {
1142
-			throw new ShareNotFound();
1143
-		}
1144
-
1145
-		$share = $provider->getShareById($id, $recipient);
1146
-
1147
-		$this->checkExpireDate($share);
1148
-
1149
-		return $share;
1150
-	}
1151
-
1152
-	/**
1153
-	 * Get all the shares for a given path
1154
-	 *
1155
-	 * @param \OCP\Files\Node $path
1156
-	 * @param int $page
1157
-	 * @param int $perPage
1158
-	 *
1159
-	 * @return Share[]
1160
-	 */
1161
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1162
-		return [];
1163
-	}
1164
-
1165
-	/**
1166
-	 * Get the share by token possible with password
1167
-	 *
1168
-	 * @param string $token
1169
-	 * @return Share
1170
-	 *
1171
-	 * @throws ShareNotFound
1172
-	 */
1173
-	public function getShareByToken($token) {
1174
-		$share = null;
1175
-		try {
1176
-			if($this->shareApiAllowLinks()) {
1177
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1178
-				$share = $provider->getShareByToken($token);
1179
-			}
1180
-		} catch (ProviderException $e) {
1181
-		} catch (ShareNotFound $e) {
1182
-		}
1183
-
1184
-
1185
-		// If it is not a link share try to fetch a federated share by token
1186
-		if ($share === null) {
1187
-			try {
1188
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1189
-				$share = $provider->getShareByToken($token);
1190
-			} catch (ProviderException $e) {
1191
-			} catch (ShareNotFound $e) {
1192
-			}
1193
-		}
1194
-
1195
-		// If it is not a link share try to fetch a mail share by token
1196
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1197
-			try {
1198
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1199
-				$share = $provider->getShareByToken($token);
1200
-			} catch (ProviderException $e) {
1201
-			} catch (ShareNotFound $e) {
1202
-			}
1203
-		}
1204
-
1205
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1206
-			try {
1207
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1208
-				$share = $provider->getShareByToken($token);
1209
-			} catch (ProviderException $e) {
1210
-			} catch (ShareNotFound $e) {
1211
-			}
1212
-		}
1213
-
1214
-		if ($share === null) {
1215
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1216
-		}
1217
-
1218
-		$this->checkExpireDate($share);
1219
-
1220
-		/*
1059
+        $shares2 = [];
1060
+
1061
+        while(true) {
1062
+            $added = 0;
1063
+            foreach ($shares as $share) {
1064
+
1065
+                try {
1066
+                    $this->checkExpireDate($share);
1067
+                } catch (ShareNotFound $e) {
1068
+                    //Ignore since this basically means the share is deleted
1069
+                    continue;
1070
+                }
1071
+
1072
+                $added++;
1073
+                $shares2[] = $share;
1074
+
1075
+                if (count($shares2) === $limit) {
1076
+                    break;
1077
+                }
1078
+            }
1079
+
1080
+            if (count($shares2) === $limit) {
1081
+                break;
1082
+            }
1083
+
1084
+            // If there was no limit on the select we are done
1085
+            if ($limit === -1) {
1086
+                break;
1087
+            }
1088
+
1089
+            $offset += $added;
1090
+
1091
+            // Fetch again $limit shares
1092
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1093
+
1094
+            // No more shares means we are done
1095
+            if (empty($shares)) {
1096
+                break;
1097
+            }
1098
+        }
1099
+
1100
+        $shares = $shares2;
1101
+
1102
+        return $shares;
1103
+    }
1104
+
1105
+    /**
1106
+     * @inheritdoc
1107
+     */
1108
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1109
+        try {
1110
+            $provider = $this->factory->getProviderForType($shareType);
1111
+        } catch (ProviderException $e) {
1112
+            return [];
1113
+        }
1114
+
1115
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1116
+
1117
+        // remove all shares which are already expired
1118
+        foreach ($shares as $key => $share) {
1119
+            try {
1120
+                $this->checkExpireDate($share);
1121
+            } catch (ShareNotFound $e) {
1122
+                unset($shares[$key]);
1123
+            }
1124
+        }
1125
+
1126
+        return $shares;
1127
+    }
1128
+
1129
+    /**
1130
+     * @inheritdoc
1131
+     */
1132
+    public function getShareById($id, $recipient = null) {
1133
+        if ($id === null) {
1134
+            throw new ShareNotFound();
1135
+        }
1136
+
1137
+        list($providerId, $id) = $this->splitFullId($id);
1138
+
1139
+        try {
1140
+            $provider = $this->factory->getProvider($providerId);
1141
+        } catch (ProviderException $e) {
1142
+            throw new ShareNotFound();
1143
+        }
1144
+
1145
+        $share = $provider->getShareById($id, $recipient);
1146
+
1147
+        $this->checkExpireDate($share);
1148
+
1149
+        return $share;
1150
+    }
1151
+
1152
+    /**
1153
+     * Get all the shares for a given path
1154
+     *
1155
+     * @param \OCP\Files\Node $path
1156
+     * @param int $page
1157
+     * @param int $perPage
1158
+     *
1159
+     * @return Share[]
1160
+     */
1161
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1162
+        return [];
1163
+    }
1164
+
1165
+    /**
1166
+     * Get the share by token possible with password
1167
+     *
1168
+     * @param string $token
1169
+     * @return Share
1170
+     *
1171
+     * @throws ShareNotFound
1172
+     */
1173
+    public function getShareByToken($token) {
1174
+        $share = null;
1175
+        try {
1176
+            if($this->shareApiAllowLinks()) {
1177
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1178
+                $share = $provider->getShareByToken($token);
1179
+            }
1180
+        } catch (ProviderException $e) {
1181
+        } catch (ShareNotFound $e) {
1182
+        }
1183
+
1184
+
1185
+        // If it is not a link share try to fetch a federated share by token
1186
+        if ($share === null) {
1187
+            try {
1188
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1189
+                $share = $provider->getShareByToken($token);
1190
+            } catch (ProviderException $e) {
1191
+            } catch (ShareNotFound $e) {
1192
+            }
1193
+        }
1194
+
1195
+        // If it is not a link share try to fetch a mail share by token
1196
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1197
+            try {
1198
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1199
+                $share = $provider->getShareByToken($token);
1200
+            } catch (ProviderException $e) {
1201
+            } catch (ShareNotFound $e) {
1202
+            }
1203
+        }
1204
+
1205
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1206
+            try {
1207
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1208
+                $share = $provider->getShareByToken($token);
1209
+            } catch (ProviderException $e) {
1210
+            } catch (ShareNotFound $e) {
1211
+            }
1212
+        }
1213
+
1214
+        if ($share === null) {
1215
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1216
+        }
1217
+
1218
+        $this->checkExpireDate($share);
1219
+
1220
+        /*
1221 1221
 		 * Reduce the permissions for link shares if public upload is not enabled
1222 1222
 		 */
1223
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1224
-			!$this->shareApiLinkAllowPublicUpload()) {
1225
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1226
-		}
1227
-
1228
-		return $share;
1229
-	}
1230
-
1231
-	protected function checkExpireDate($share) {
1232
-		if ($share->getExpirationDate() !== null &&
1233
-			$share->getExpirationDate() <= new \DateTime()) {
1234
-			$this->deleteShare($share);
1235
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1236
-		}
1237
-
1238
-	}
1239
-
1240
-	/**
1241
-	 * Verify the password of a public share
1242
-	 *
1243
-	 * @param \OCP\Share\IShare $share
1244
-	 * @param string $password
1245
-	 * @return bool
1246
-	 */
1247
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1248
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1249
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1250
-		if (!$passwordProtected) {
1251
-			//TODO maybe exception?
1252
-			return false;
1253
-		}
1254
-
1255
-		if ($password === null || $share->getPassword() === null) {
1256
-			return false;
1257
-		}
1258
-
1259
-		$newHash = '';
1260
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1261
-			return false;
1262
-		}
1263
-
1264
-		if (!empty($newHash)) {
1265
-			$share->setPassword($newHash);
1266
-			$provider = $this->factory->getProviderForType($share->getShareType());
1267
-			$provider->update($share);
1268
-		}
1269
-
1270
-		return true;
1271
-	}
1272
-
1273
-	/**
1274
-	 * @inheritdoc
1275
-	 */
1276
-	public function userDeleted($uid) {
1277
-		$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];
1278
-
1279
-		foreach ($types as $type) {
1280
-			try {
1281
-				$provider = $this->factory->getProviderForType($type);
1282
-			} catch (ProviderException $e) {
1283
-				continue;
1284
-			}
1285
-			$provider->userDeleted($uid, $type);
1286
-		}
1287
-	}
1288
-
1289
-	/**
1290
-	 * @inheritdoc
1291
-	 */
1292
-	public function groupDeleted($gid) {
1293
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1294
-		$provider->groupDeleted($gid);
1295
-	}
1296
-
1297
-	/**
1298
-	 * @inheritdoc
1299
-	 */
1300
-	public function userDeletedFromGroup($uid, $gid) {
1301
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1302
-		$provider->userDeletedFromGroup($uid, $gid);
1303
-	}
1304
-
1305
-	/**
1306
-	 * Get access list to a path. This means
1307
-	 * all the users that can access a given path.
1308
-	 *
1309
-	 * Consider:
1310
-	 * -root
1311
-	 * |-folder1 (23)
1312
-	 *  |-folder2 (32)
1313
-	 *   |-fileA (42)
1314
-	 *
1315
-	 * fileA is shared with user1 and user1@server1
1316
-	 * folder2 is shared with group2 (user4 is a member of group2)
1317
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1318
-	 *
1319
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1320
-	 * [
1321
-	 *  users  => [
1322
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1323
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1324
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1325
-	 *  ],
1326
-	 *  remote => [
1327
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1328
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1329
-	 *  ],
1330
-	 *  public => bool
1331
-	 *  mail => bool
1332
-	 * ]
1333
-	 *
1334
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1335
-	 * [
1336
-	 *  users  => ['user1', 'user2', 'user4'],
1337
-	 *  remote => bool,
1338
-	 *  public => bool
1339
-	 *  mail => bool
1340
-	 * ]
1341
-	 *
1342
-	 * This is required for encryption/activity
1343
-	 *
1344
-	 * @param \OCP\Files\Node $path
1345
-	 * @param bool $recursive Should we check all parent folders as well
1346
-	 * @param bool $currentAccess Should the user have currently access to the file
1347
-	 * @return array
1348
-	 */
1349
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1350
-		$owner = $path->getOwner()->getUID();
1351
-
1352
-		if ($currentAccess) {
1353
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1354
-		} else {
1355
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1356
-		}
1357
-		if (!$this->userManager->userExists($owner)) {
1358
-			return $al;
1359
-		}
1360
-
1361
-		//Get node for the owner
1362
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1363
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1364
-			$path = $userFolder->getById($path->getId())[0];
1365
-		}
1366
-
1367
-		$providers = $this->factory->getAllProviders();
1368
-
1369
-		/** @var Node[] $nodes */
1370
-		$nodes = [];
1371
-
1372
-
1373
-		if ($currentAccess) {
1374
-			$ownerPath = $path->getPath();
1375
-			$ownerPath = explode('/', $ownerPath, 4);
1376
-			if (count($ownerPath) < 4) {
1377
-				$ownerPath = '';
1378
-			} else {
1379
-				$ownerPath = $ownerPath[3];
1380
-			}
1381
-			$al['users'][$owner] = [
1382
-				'node_id' => $path->getId(),
1383
-				'node_path' => '/' . $ownerPath,
1384
-			];
1385
-		} else {
1386
-			$al['users'][] = $owner;
1387
-		}
1388
-
1389
-		// Collect all the shares
1390
-		while ($path->getPath() !== $userFolder->getPath()) {
1391
-			$nodes[] = $path;
1392
-			if (!$recursive) {
1393
-				break;
1394
-			}
1395
-			$path = $path->getParent();
1396
-		}
1397
-
1398
-		foreach ($providers as $provider) {
1399
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1400
-
1401
-			foreach ($tmp as $k => $v) {
1402
-				if (isset($al[$k])) {
1403
-					if (is_array($al[$k])) {
1404
-						$al[$k] = array_merge($al[$k], $v);
1405
-					} else {
1406
-						$al[$k] = $al[$k] || $v;
1407
-					}
1408
-				} else {
1409
-					$al[$k] = $v;
1410
-				}
1411
-			}
1412
-		}
1413
-
1414
-		return $al;
1415
-	}
1416
-
1417
-	/**
1418
-	 * Create a new share
1419
-	 * @return \OCP\Share\IShare;
1420
-	 */
1421
-	public function newShare() {
1422
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1423
-	}
1424
-
1425
-	/**
1426
-	 * Is the share API enabled
1427
-	 *
1428
-	 * @return bool
1429
-	 */
1430
-	public function shareApiEnabled() {
1431
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1432
-	}
1433
-
1434
-	/**
1435
-	 * Is public link sharing enabled
1436
-	 *
1437
-	 * @return bool
1438
-	 */
1439
-	public function shareApiAllowLinks() {
1440
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1441
-	}
1442
-
1443
-	/**
1444
-	 * Is password on public link requires
1445
-	 *
1446
-	 * @return bool
1447
-	 */
1448
-	public function shareApiLinkEnforcePassword() {
1449
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1450
-	}
1451
-
1452
-	/**
1453
-	 * Is default expire date enabled
1454
-	 *
1455
-	 * @return bool
1456
-	 */
1457
-	public function shareApiLinkDefaultExpireDate() {
1458
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1459
-	}
1460
-
1461
-	/**
1462
-	 * Is default expire date enforced
1463
-	 *`
1464
-	 * @return bool
1465
-	 */
1466
-	public function shareApiLinkDefaultExpireDateEnforced() {
1467
-		return $this->shareApiLinkDefaultExpireDate() &&
1468
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1469
-	}
1470
-
1471
-	/**
1472
-	 * Number of default expire days
1473
-	 *shareApiLinkAllowPublicUpload
1474
-	 * @return int
1475
-	 */
1476
-	public function shareApiLinkDefaultExpireDays() {
1477
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1478
-	}
1479
-
1480
-	/**
1481
-	 * Allow public upload on link shares
1482
-	 *
1483
-	 * @return bool
1484
-	 */
1485
-	public function shareApiLinkAllowPublicUpload() {
1486
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1487
-	}
1488
-
1489
-	/**
1490
-	 * check if user can only share with group members
1491
-	 * @return bool
1492
-	 */
1493
-	public function shareWithGroupMembersOnly() {
1494
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1495
-	}
1496
-
1497
-	/**
1498
-	 * Check if users can share with groups
1499
-	 * @return bool
1500
-	 */
1501
-	public function allowGroupSharing() {
1502
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1503
-	}
1504
-
1505
-	/**
1506
-	 * Copied from \OC_Util::isSharingDisabledForUser
1507
-	 *
1508
-	 * TODO: Deprecate fuction from OC_Util
1509
-	 *
1510
-	 * @param string $userId
1511
-	 * @return bool
1512
-	 */
1513
-	public function sharingDisabledForUser($userId) {
1514
-		if ($userId === null) {
1515
-			return false;
1516
-		}
1517
-
1518
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1519
-			return $this->sharingDisabledForUsersCache[$userId];
1520
-		}
1521
-
1522
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1523
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1524
-			$excludedGroups = json_decode($groupsList);
1525
-			if (is_null($excludedGroups)) {
1526
-				$excludedGroups = explode(',', $groupsList);
1527
-				$newValue = json_encode($excludedGroups);
1528
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1529
-			}
1530
-			$user = $this->userManager->get($userId);
1531
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1532
-			if (!empty($usersGroups)) {
1533
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1534
-				// if the user is only in groups which are disabled for sharing then
1535
-				// sharing is also disabled for the user
1536
-				if (empty($remainingGroups)) {
1537
-					$this->sharingDisabledForUsersCache[$userId] = true;
1538
-					return true;
1539
-				}
1540
-			}
1541
-		}
1542
-
1543
-		$this->sharingDisabledForUsersCache[$userId] = false;
1544
-		return false;
1545
-	}
1546
-
1547
-	/**
1548
-	 * @inheritdoc
1549
-	 */
1550
-	public function outgoingServer2ServerSharesAllowed() {
1551
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1552
-	}
1553
-
1554
-	/**
1555
-	 * @inheritdoc
1556
-	 */
1557
-	public function shareProviderExists($shareType) {
1558
-		try {
1559
-			$this->factory->getProviderForType($shareType);
1560
-		} catch (ProviderException $e) {
1561
-			return false;
1562
-		}
1563
-
1564
-		return true;
1565
-	}
1223
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1224
+            !$this->shareApiLinkAllowPublicUpload()) {
1225
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1226
+        }
1227
+
1228
+        return $share;
1229
+    }
1230
+
1231
+    protected function checkExpireDate($share) {
1232
+        if ($share->getExpirationDate() !== null &&
1233
+            $share->getExpirationDate() <= new \DateTime()) {
1234
+            $this->deleteShare($share);
1235
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1236
+        }
1237
+
1238
+    }
1239
+
1240
+    /**
1241
+     * Verify the password of a public share
1242
+     *
1243
+     * @param \OCP\Share\IShare $share
1244
+     * @param string $password
1245
+     * @return bool
1246
+     */
1247
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1248
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1249
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1250
+        if (!$passwordProtected) {
1251
+            //TODO maybe exception?
1252
+            return false;
1253
+        }
1254
+
1255
+        if ($password === null || $share->getPassword() === null) {
1256
+            return false;
1257
+        }
1258
+
1259
+        $newHash = '';
1260
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1261
+            return false;
1262
+        }
1263
+
1264
+        if (!empty($newHash)) {
1265
+            $share->setPassword($newHash);
1266
+            $provider = $this->factory->getProviderForType($share->getShareType());
1267
+            $provider->update($share);
1268
+        }
1269
+
1270
+        return true;
1271
+    }
1272
+
1273
+    /**
1274
+     * @inheritdoc
1275
+     */
1276
+    public function userDeleted($uid) {
1277
+        $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];
1278
+
1279
+        foreach ($types as $type) {
1280
+            try {
1281
+                $provider = $this->factory->getProviderForType($type);
1282
+            } catch (ProviderException $e) {
1283
+                continue;
1284
+            }
1285
+            $provider->userDeleted($uid, $type);
1286
+        }
1287
+    }
1288
+
1289
+    /**
1290
+     * @inheritdoc
1291
+     */
1292
+    public function groupDeleted($gid) {
1293
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1294
+        $provider->groupDeleted($gid);
1295
+    }
1296
+
1297
+    /**
1298
+     * @inheritdoc
1299
+     */
1300
+    public function userDeletedFromGroup($uid, $gid) {
1301
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1302
+        $provider->userDeletedFromGroup($uid, $gid);
1303
+    }
1304
+
1305
+    /**
1306
+     * Get access list to a path. This means
1307
+     * all the users that can access a given path.
1308
+     *
1309
+     * Consider:
1310
+     * -root
1311
+     * |-folder1 (23)
1312
+     *  |-folder2 (32)
1313
+     *   |-fileA (42)
1314
+     *
1315
+     * fileA is shared with user1 and user1@server1
1316
+     * folder2 is shared with group2 (user4 is a member of group2)
1317
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1318
+     *
1319
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1320
+     * [
1321
+     *  users  => [
1322
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1323
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1324
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1325
+     *  ],
1326
+     *  remote => [
1327
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1328
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1329
+     *  ],
1330
+     *  public => bool
1331
+     *  mail => bool
1332
+     * ]
1333
+     *
1334
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1335
+     * [
1336
+     *  users  => ['user1', 'user2', 'user4'],
1337
+     *  remote => bool,
1338
+     *  public => bool
1339
+     *  mail => bool
1340
+     * ]
1341
+     *
1342
+     * This is required for encryption/activity
1343
+     *
1344
+     * @param \OCP\Files\Node $path
1345
+     * @param bool $recursive Should we check all parent folders as well
1346
+     * @param bool $currentAccess Should the user have currently access to the file
1347
+     * @return array
1348
+     */
1349
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1350
+        $owner = $path->getOwner()->getUID();
1351
+
1352
+        if ($currentAccess) {
1353
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1354
+        } else {
1355
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1356
+        }
1357
+        if (!$this->userManager->userExists($owner)) {
1358
+            return $al;
1359
+        }
1360
+
1361
+        //Get node for the owner
1362
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1363
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1364
+            $path = $userFolder->getById($path->getId())[0];
1365
+        }
1366
+
1367
+        $providers = $this->factory->getAllProviders();
1368
+
1369
+        /** @var Node[] $nodes */
1370
+        $nodes = [];
1371
+
1372
+
1373
+        if ($currentAccess) {
1374
+            $ownerPath = $path->getPath();
1375
+            $ownerPath = explode('/', $ownerPath, 4);
1376
+            if (count($ownerPath) < 4) {
1377
+                $ownerPath = '';
1378
+            } else {
1379
+                $ownerPath = $ownerPath[3];
1380
+            }
1381
+            $al['users'][$owner] = [
1382
+                'node_id' => $path->getId(),
1383
+                'node_path' => '/' . $ownerPath,
1384
+            ];
1385
+        } else {
1386
+            $al['users'][] = $owner;
1387
+        }
1388
+
1389
+        // Collect all the shares
1390
+        while ($path->getPath() !== $userFolder->getPath()) {
1391
+            $nodes[] = $path;
1392
+            if (!$recursive) {
1393
+                break;
1394
+            }
1395
+            $path = $path->getParent();
1396
+        }
1397
+
1398
+        foreach ($providers as $provider) {
1399
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1400
+
1401
+            foreach ($tmp as $k => $v) {
1402
+                if (isset($al[$k])) {
1403
+                    if (is_array($al[$k])) {
1404
+                        $al[$k] = array_merge($al[$k], $v);
1405
+                    } else {
1406
+                        $al[$k] = $al[$k] || $v;
1407
+                    }
1408
+                } else {
1409
+                    $al[$k] = $v;
1410
+                }
1411
+            }
1412
+        }
1413
+
1414
+        return $al;
1415
+    }
1416
+
1417
+    /**
1418
+     * Create a new share
1419
+     * @return \OCP\Share\IShare;
1420
+     */
1421
+    public function newShare() {
1422
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1423
+    }
1424
+
1425
+    /**
1426
+     * Is the share API enabled
1427
+     *
1428
+     * @return bool
1429
+     */
1430
+    public function shareApiEnabled() {
1431
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1432
+    }
1433
+
1434
+    /**
1435
+     * Is public link sharing enabled
1436
+     *
1437
+     * @return bool
1438
+     */
1439
+    public function shareApiAllowLinks() {
1440
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1441
+    }
1442
+
1443
+    /**
1444
+     * Is password on public link requires
1445
+     *
1446
+     * @return bool
1447
+     */
1448
+    public function shareApiLinkEnforcePassword() {
1449
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1450
+    }
1451
+
1452
+    /**
1453
+     * Is default expire date enabled
1454
+     *
1455
+     * @return bool
1456
+     */
1457
+    public function shareApiLinkDefaultExpireDate() {
1458
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1459
+    }
1460
+
1461
+    /**
1462
+     * Is default expire date enforced
1463
+     *`
1464
+     * @return bool
1465
+     */
1466
+    public function shareApiLinkDefaultExpireDateEnforced() {
1467
+        return $this->shareApiLinkDefaultExpireDate() &&
1468
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1469
+    }
1470
+
1471
+    /**
1472
+     * Number of default expire days
1473
+     *shareApiLinkAllowPublicUpload
1474
+     * @return int
1475
+     */
1476
+    public function shareApiLinkDefaultExpireDays() {
1477
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1478
+    }
1479
+
1480
+    /**
1481
+     * Allow public upload on link shares
1482
+     *
1483
+     * @return bool
1484
+     */
1485
+    public function shareApiLinkAllowPublicUpload() {
1486
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1487
+    }
1488
+
1489
+    /**
1490
+     * check if user can only share with group members
1491
+     * @return bool
1492
+     */
1493
+    public function shareWithGroupMembersOnly() {
1494
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1495
+    }
1496
+
1497
+    /**
1498
+     * Check if users can share with groups
1499
+     * @return bool
1500
+     */
1501
+    public function allowGroupSharing() {
1502
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1503
+    }
1504
+
1505
+    /**
1506
+     * Copied from \OC_Util::isSharingDisabledForUser
1507
+     *
1508
+     * TODO: Deprecate fuction from OC_Util
1509
+     *
1510
+     * @param string $userId
1511
+     * @return bool
1512
+     */
1513
+    public function sharingDisabledForUser($userId) {
1514
+        if ($userId === null) {
1515
+            return false;
1516
+        }
1517
+
1518
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1519
+            return $this->sharingDisabledForUsersCache[$userId];
1520
+        }
1521
+
1522
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1523
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1524
+            $excludedGroups = json_decode($groupsList);
1525
+            if (is_null($excludedGroups)) {
1526
+                $excludedGroups = explode(',', $groupsList);
1527
+                $newValue = json_encode($excludedGroups);
1528
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1529
+            }
1530
+            $user = $this->userManager->get($userId);
1531
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1532
+            if (!empty($usersGroups)) {
1533
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1534
+                // if the user is only in groups which are disabled for sharing then
1535
+                // sharing is also disabled for the user
1536
+                if (empty($remainingGroups)) {
1537
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1538
+                    return true;
1539
+                }
1540
+            }
1541
+        }
1542
+
1543
+        $this->sharingDisabledForUsersCache[$userId] = false;
1544
+        return false;
1545
+    }
1546
+
1547
+    /**
1548
+     * @inheritdoc
1549
+     */
1550
+    public function outgoingServer2ServerSharesAllowed() {
1551
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1552
+    }
1553
+
1554
+    /**
1555
+     * @inheritdoc
1556
+     */
1557
+    public function shareProviderExists($shareType) {
1558
+        try {
1559
+            $this->factory->getProviderForType($shareType);
1560
+        } catch (ProviderException $e) {
1561
+            return false;
1562
+        }
1563
+
1564
+        return true;
1565
+    }
1566 1566
 
1567 1567
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 
341 341
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
342 342
 			$expirationDate = new \DateTime();
343
-			$expirationDate->setTime(0,0,0);
343
+			$expirationDate->setTime(0, 0, 0);
344 344
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
345 345
 		}
346 346
 
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 
353 353
 			$date = new \DateTime();
354 354
 			$date->setTime(0, 0, 0);
355
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
355
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
356 356
 			if ($date < $expirationDate) {
357 357
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
358 358
 				throw new GenericShareException($message, $message, 404);
@@ -405,7 +405,7 @@  discard block
 block discarded – undo
405 405
 		 */
406 406
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
407 407
 		$existingShares = $provider->getSharesByPath($share->getNode());
408
-		foreach($existingShares as $existingShare) {
408
+		foreach ($existingShares as $existingShare) {
409 409
 			// Ignore if it is the same share
410 410
 			try {
411 411
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
 		 */
463 463
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
464 464
 		$existingShares = $provider->getSharesByPath($share->getNode());
465
-		foreach($existingShares as $existingShare) {
465
+		foreach ($existingShares as $existingShare) {
466 466
 			try {
467 467
 				if ($existingShare->getFullId() === $share->getFullId()) {
468 468
 					continue;
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 		// Make sure that we do not share a path that contains a shared mountpoint
532 532
 		if ($path instanceof \OCP\Files\Folder) {
533 533
 			$mounts = $this->mountManager->findIn($path->getPath());
534
-			foreach($mounts as $mount) {
534
+			foreach ($mounts as $mount) {
535 535
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536 536
 					throw new \InvalidArgumentException('Path contains files shared with you');
537 537
 				}
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 		$storage = $share->getNode()->getStorage();
580 580
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
581 581
 			$parent = $share->getNode()->getParent();
582
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
582
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
583 583
 				$parent = $parent->getParent();
584 584
 			}
585 585
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 		}
633 633
 
634 634
 		// Generate the target
635
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
635
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
636 636
 		$target = \OC\Files\Filesystem::normalizePath($target);
637 637
 		$share->setTarget($target);
638 638
 
@@ -660,17 +660,17 @@  discard block
 block discarded – undo
660 660
 				if ($emailAddress !== null && $emailAddress !== '') {
661 661
 					$this->sendMailNotification(
662 662
 						$share->getNode()->getName(),
663
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
663
+						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
664 664
 						$share->getSharedBy(),
665 665
 						$emailAddress,
666 666
 						$share->getExpirationDate()
667 667
 					);
668
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
668
+					$this->logger->debug('Send share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']);
669 669
 				} else {
670
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
670
+					$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']);
671 671
 				}
672 672
 			} else {
673
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
673
+				$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']);
674 674
 			}
675 675
 		}
676 676
 
@@ -702,7 +702,7 @@  discard block
 block discarded – undo
702 702
 
703 703
 		$this->sendMailNotification(
704 704
 			$share->getNode()->getName(),
705
-			$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
705
+			$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
706 706
 			$share->getSharedBy(),
707 707
 			$emailAddress
708 708
 		);
@@ -725,7 +725,7 @@  discard block
 block discarded – undo
725 725
 											\DateTime $expiration = null) {
726 726
 		$initiatorUser = $this->userManager->get($initiator);
727 727
 		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
728
-		$subject = (string)$this->l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
728
+		$subject = (string) $this->l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename));
729 729
 
730 730
 		$message = $this->mailer->createMessage();
731 731
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
 		$text = $this->l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
744 744
 
745 745
 		$emailTemplate->addBodyText(
746
-			$text . ' ' . $this->l->t('Click the button below to open it.'),
746
+			$text.' '.$this->l->t('Click the button below to open it.'),
747 747
 			$text
748 748
 		);
749 749
 		$emailTemplate->addBodyButton(
@@ -767,9 +767,9 @@  discard block
 block discarded – undo
767 767
 		// The "Reply-To" is set to the sharer if an mail address is configured
768 768
 		// also the default footer contains a "Do not reply" which needs to be adjusted.
769 769
 		$initiatorEmail = $initiatorUser->getEMailAddress();
770
-		if($initiatorEmail !== null) {
770
+		if ($initiatorEmail !== null) {
771 771
 			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
772
-			$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
772
+			$emailTemplate->addFooter($instanceName.' - '.$this->defaults->getSlogan());
773 773
 		} else {
774 774
 			$emailTemplate->addFooter();
775 775
 		}
@@ -980,7 +980,7 @@  discard block
 block discarded – undo
980 980
 	 * @param string $recipientId
981 981
 	 */
982 982
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
983
-		list($providerId, ) = $this->splitFullId($share->getFullId());
983
+		list($providerId,) = $this->splitFullId($share->getFullId());
984 984
 		$provider = $this->factory->getProvider($providerId);
985 985
 
986 986
 		$provider->deleteFromSelf($share, $recipientId);
@@ -1003,7 +1003,7 @@  discard block
 block discarded – undo
1003 1003
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1004 1004
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
1005 1005
 			if (is_null($sharedWith)) {
1006
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1006
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
1007 1007
 			}
1008 1008
 			$recipient = $this->userManager->get($recipientId);
1009 1009
 			if (!$sharedWith->inGroup($recipient)) {
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
 			}
1012 1012
 		}
1013 1013
 
1014
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1014
+		list($providerId,) = $this->splitFullId($share->getFullId());
1015 1015
 		$provider = $this->factory->getProvider($providerId);
1016 1016
 
1017 1017
 		$provider->move($share, $recipientId);
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
 
1059 1059
 		$shares2 = [];
1060 1060
 
1061
-		while(true) {
1061
+		while (true) {
1062 1062
 			$added = 0;
1063 1063
 			foreach ($shares as $share) {
1064 1064
 
@@ -1158,7 +1158,7 @@  discard block
 block discarded – undo
1158 1158
 	 *
1159 1159
 	 * @return Share[]
1160 1160
 	 */
1161
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1161
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1162 1162
 		return [];
1163 1163
 	}
1164 1164
 
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
 	public function getShareByToken($token) {
1174 1174
 		$share = null;
1175 1175
 		try {
1176
-			if($this->shareApiAllowLinks()) {
1176
+			if ($this->shareApiAllowLinks()) {
1177 1177
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1178 1178
 				$share = $provider->getShareByToken($token);
1179 1179
 			}
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
 			}
1381 1381
 			$al['users'][$owner] = [
1382 1382
 				'node_id' => $path->getId(),
1383
-				'node_path' => '/' . $ownerPath,
1383
+				'node_path' => '/'.$ownerPath,
1384 1384
 			];
1385 1385
 		} else {
1386 1386
 			$al['users'][] = $owner;
@@ -1474,7 +1474,7 @@  discard block
 block discarded – undo
1474 1474
 	 * @return int
1475 1475
 	 */
1476 1476
 	public function shareApiLinkDefaultExpireDays() {
1477
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1477
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1478 1478
 	}
1479 1479
 
1480 1480
 	/**
Please login to merge, or discard this patch.