Completed
Pull Request — master (#3567)
by Björn
16:11
created
apps/files_sharing/lib/Controller/ShareesAPIController.php 1 patch
Indentation   +639 added lines, -639 removed lines patch added patch discarded remove patch
@@ -43,643 +43,643 @@
 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
-		],
96
-		'users' => [],
97
-		'groups' => [],
98
-		'remotes' => [],
99
-		'emails' => [],
100
-		'lookup' => [],
101
-	];
102
-
103
-	protected $reachedEndFor = [];
104
-
105
-	/**
106
-	 * @param string $appName
107
-	 * @param IRequest $request
108
-	 * @param IGroupManager $groupManager
109
-	 * @param IUserManager $userManager
110
-	 * @param IManager $contactsManager
111
-	 * @param IConfig $config
112
-	 * @param IUserSession $userSession
113
-	 * @param IURLGenerator $urlGenerator
114
-	 * @param ILogger $logger
115
-	 * @param \OCP\Share\IManager $shareManager
116
-	 * @param IClientService $clientService
117
-	 * @param ICloudIdManager $cloudIdManager
118
-	 */
119
-	public function __construct($appName,
120
-								IRequest $request,
121
-								IGroupManager $groupManager,
122
-								IUserManager $userManager,
123
-								IManager $contactsManager,
124
-								IConfig $config,
125
-								IUserSession $userSession,
126
-								IURLGenerator $urlGenerator,
127
-								ILogger $logger,
128
-								\OCP\Share\IManager $shareManager,
129
-								IClientService $clientService,
130
-								ICloudIdManager $cloudIdManager
131
-	) {
132
-		parent::__construct($appName, $request);
133
-
134
-		$this->groupManager = $groupManager;
135
-		$this->userManager = $userManager;
136
-		$this->contactsManager = $contactsManager;
137
-		$this->config = $config;
138
-		$this->userSession = $userSession;
139
-		$this->urlGenerator = $urlGenerator;
140
-		$this->logger = $logger;
141
-		$this->shareManager = $shareManager;
142
-		$this->clientService = $clientService;
143
-		$this->cloudIdManager = $cloudIdManager;
144
-	}
145
-
146
-	/**
147
-	 * @param string $search
148
-	 */
149
-	protected function getUsers($search) {
150
-		$this->result['users'] = $this->result['exact']['users'] = $users = [];
151
-
152
-		$userGroups = [];
153
-		if ($this->shareWithGroupOnly) {
154
-			// Search in all the groups this user is part of
155
-			$userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
156
-			foreach ($userGroups as $userGroup) {
157
-				$usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
158
-				foreach ($usersTmp as $uid => $userDisplayName) {
159
-					$users[$uid] = $userDisplayName;
160
-				}
161
-			}
162
-		} else {
163
-			// Search in all users
164
-			$usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
165
-
166
-			foreach ($usersTmp as $user) {
167
-				$users[$user->getUID()] = $user->getDisplayName();
168
-			}
169
-		}
170
-
171
-		if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
172
-			$this->reachedEndFor[] = 'users';
173
-		}
174
-
175
-		$foundUserById = false;
176
-		$lowerSearch = strtolower($search);
177
-		foreach ($users as $uid => $userDisplayName) {
178
-			if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
179
-				if (strtolower($uid) === $lowerSearch) {
180
-					$foundUserById = true;
181
-				}
182
-				$this->result['exact']['users'][] = [
183
-					'label' => $userDisplayName,
184
-					'value' => [
185
-						'shareType' => Share::SHARE_TYPE_USER,
186
-						'shareWith' => $uid,
187
-					],
188
-				];
189
-			} else {
190
-				$this->result['users'][] = [
191
-					'label' => $userDisplayName,
192
-					'value' => [
193
-						'shareType' => Share::SHARE_TYPE_USER,
194
-						'shareWith' => $uid,
195
-					],
196
-				];
197
-			}
198
-		}
199
-
200
-		if ($this->offset === 0 && !$foundUserById) {
201
-			// On page one we try if the search result has a direct hit on the
202
-			// user id and if so, we add that to the exact match list
203
-			$user = $this->userManager->get($search);
204
-			if ($user instanceof IUser) {
205
-				$addUser = true;
206
-
207
-				if ($this->shareWithGroupOnly) {
208
-					// Only add, if we have a common group
209
-					$commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
210
-					$addUser = !empty($commonGroups);
211
-				}
212
-
213
-				if ($addUser) {
214
-					array_push($this->result['exact']['users'], [
215
-						'label' => $user->getDisplayName(),
216
-						'value' => [
217
-							'shareType' => Share::SHARE_TYPE_USER,
218
-							'shareWith' => $user->getUID(),
219
-						],
220
-					]);
221
-				}
222
-			}
223
-		}
224
-
225
-		if (!$this->shareeEnumeration) {
226
-			$this->result['users'] = [];
227
-		}
228
-	}
229
-
230
-	/**
231
-	 * @param string $search
232
-	 */
233
-	protected function getGroups($search) {
234
-		$this->result['groups'] = $this->result['exact']['groups'] = [];
235
-
236
-		$groups = $this->groupManager->search($search, $this->limit, $this->offset);
237
-		$groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
238
-
239
-		if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
240
-			$this->reachedEndFor[] = 'groups';
241
-		}
242
-
243
-		$userGroups =  [];
244
-		if (!empty($groups) && $this->shareWithGroupOnly) {
245
-			// Intersect all the groups that match with the groups this user is a member of
246
-			$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
247
-			$userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
248
-			$groupIds = array_intersect($groupIds, $userGroups);
249
-		}
250
-
251
-		$lowerSearch = strtolower($search);
252
-		foreach ($groups as $group) {
253
-			// FIXME: use a more efficient approach
254
-			$gid = $group->getGID();
255
-			if (!in_array($gid, $groupIds)) {
256
-				continue;
257
-			}
258
-			if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
259
-				$this->result['exact']['groups'][] = [
260
-					'label' => $group->getDisplayName(),
261
-					'value' => [
262
-						'shareType' => Share::SHARE_TYPE_GROUP,
263
-						'shareWith' => $gid,
264
-					],
265
-				];
266
-			} else {
267
-				$this->result['groups'][] = [
268
-					'label' => $group->getDisplayName(),
269
-					'value' => [
270
-						'shareType' => Share::SHARE_TYPE_GROUP,
271
-						'shareWith' => $gid,
272
-					],
273
-				];
274
-			}
275
-		}
276
-
277
-		if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
278
-			// On page one we try if the search result has a direct hit on the
279
-			// user id and if so, we add that to the exact match list
280
-			$group = $this->groupManager->get($search);
281
-			if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
282
-				array_push($this->result['exact']['groups'], [
283
-					'label' => $group->getDisplayName(),
284
-					'value' => [
285
-						'shareType' => Share::SHARE_TYPE_GROUP,
286
-						'shareWith' => $group->getGID(),
287
-					],
288
-				]);
289
-			}
290
-		}
291
-
292
-		if (!$this->shareeEnumeration) {
293
-			$this->result['groups'] = [];
294
-		}
295
-	}
296
-
297
-	/**
298
-	 * @param string $search
299
-	 * @return array
300
-	 */
301
-	protected function getRemote($search) {
302
-		$result = ['results' => [], 'exact' => []];
303
-
304
-		// Search in contacts
305
-		//@todo Pagination missing
306
-		$addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
307
-		$result['exactIdMatch'] = false;
308
-		foreach ($addressBookContacts as $contact) {
309
-			if (isset($contact['isLocalSystemBook'])) {
310
-				continue;
311
-			}
312
-			if (isset($contact['CLOUD'])) {
313
-				$cloudIds = $contact['CLOUD'];
314
-				if (!is_array($cloudIds)) {
315
-					$cloudIds = [$cloudIds];
316
-				}
317
-				$lowerSearch = strtolower($search);
318
-				foreach ($cloudIds as $cloudId) {
319
-					list(, $serverUrl) = $this->splitUserRemote($cloudId);
320
-					if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
321
-						if (strtolower($cloudId) === $lowerSearch) {
322
-							$result['exactIdMatch'] = true;
323
-						}
324
-						$result['exact'][] = [
325
-							'label' => $contact['FN'] . " ($cloudId)",
326
-							'value' => [
327
-								'shareType' => Share::SHARE_TYPE_REMOTE,
328
-								'shareWith' => $cloudId,
329
-								'server' => $serverUrl,
330
-							],
331
-						];
332
-					} else {
333
-						$result['results'][] = [
334
-							'label' => $contact['FN'] . " ($cloudId)",
335
-							'value' => [
336
-								'shareType' => Share::SHARE_TYPE_REMOTE,
337
-								'shareWith' => $cloudId,
338
-								'server' => $serverUrl,
339
-							],
340
-						];
341
-					}
342
-				}
343
-			}
344
-		}
345
-
346
-		if (!$this->shareeEnumeration) {
347
-			$result['results'] = [];
348
-		}
349
-
350
-		if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
351
-			$result['exact'][] = [
352
-				'label' => $search,
353
-				'value' => [
354
-					'shareType' => Share::SHARE_TYPE_REMOTE,
355
-					'shareWith' => $search,
356
-				],
357
-			];
358
-		}
359
-
360
-		$this->reachedEndFor[] = 'remotes';
361
-
362
-		return $result;
363
-	}
364
-
365
-	/**
366
-	 * split user and remote from federated cloud id
367
-	 *
368
-	 * @param string $address federated share address
369
-	 * @return array [user, remoteURL]
370
-	 * @throws \Exception
371
-	 */
372
-	public function splitUserRemote($address) {
373
-		try {
374
-			$cloudId = $this->cloudIdManager->resolveCloudId($address);
375
-			return [$cloudId->getUser(), $cloudId->getRemote()];
376
-		} catch (\InvalidArgumentException $e) {
377
-			throw new \Exception('Invalid Federated Cloud ID', 0, $e);
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * Strips away a potential file names and trailing slashes:
383
-	 * - http://localhost
384
-	 * - http://localhost/
385
-	 * - http://localhost/index.php
386
-	 * - http://localhost/index.php/s/{shareToken}
387
-	 *
388
-	 * all return: http://localhost
389
-	 *
390
-	 * @param string $remote
391
-	 * @return string
392
-	 */
393
-	protected function fixRemoteURL($remote) {
394
-		$remote = str_replace('\\', '/', $remote);
395
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
396
-			$remote = substr($remote, 0, $fileNamePosition);
397
-		}
398
-		$remote = rtrim($remote, '/');
399
-
400
-		return $remote;
401
-	}
402
-
403
-	/**
404
-	 * @NoAdminRequired
405
-	 *
406
-	 * @param string $search
407
-	 * @param string $itemType
408
-	 * @param int $page
409
-	 * @param int $perPage
410
-	 * @param int|int[] $shareType
411
-	 * @param bool $lookup
412
-	 * @return Http\DataResponse
413
-	 * @throws OCSBadRequestException
414
-	 */
415
-	public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
416
-
417
-		// only search for string larger than a given threshold
418
-		$threshold = $this->config->getSystemValue('sharing.minSearchStringLength', 0);
419
-		if (strlen($search) < $threshold) {
420
-			return new Http\DataResponse($this->result);
421
-		}
422
-
423
-		// never return more than the max. number of results configured in the config.php
424
-		$maxResults = $this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
425
-		if ($maxResults > 0) {
426
-			$perPage = min($perPage, $maxResults);
427
-		}
428
-		if ($perPage <= 0) {
429
-			throw new OCSBadRequestException('Invalid perPage argument');
430
-		}
431
-		if ($page <= 0) {
432
-			throw new OCSBadRequestException('Invalid page');
433
-		}
434
-
435
-		$shareTypes = [
436
-			Share::SHARE_TYPE_USER,
437
-		];
438
-
439
-		if ($itemType === 'file' || $itemType === 'folder') {
440
-			if ($this->shareManager->allowGroupSharing()) {
441
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
442
-			}
443
-
444
-			if ($this->isRemoteSharingAllowed($itemType)) {
445
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
446
-			}
447
-
448
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
449
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
450
-			}
451
-		} else {
452
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
453
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
454
-		}
455
-
456
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
457
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
458
-			sort($shareTypes);
459
-		} else if (is_numeric($shareType)) {
460
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
461
-			sort($shareTypes);
462
-		}
463
-
464
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
465
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
466
-		$this->limit = (int) $perPage;
467
-		$this->offset = $perPage * ($page - 1);
468
-
469
-		return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
470
-	}
471
-
472
-	/**
473
-	 * Method to get out the static call for better testing
474
-	 *
475
-	 * @param string $itemType
476
-	 * @return bool
477
-	 */
478
-	protected function isRemoteSharingAllowed($itemType) {
479
-		try {
480
-			$backend = Share::getBackend($itemType);
481
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
482
-		} catch (\Exception $e) {
483
-			return false;
484
-		}
485
-	}
486
-
487
-	/**
488
-	 * Testable search function that does not need globals
489
-	 *
490
-	 * @param string $search
491
-	 * @param string $itemType
492
-	 * @param array $shareTypes
493
-	 * @param int $page
494
-	 * @param int $perPage
495
-	 * @param bool $lookup
496
-	 * @return Http\DataResponse
497
-	 * @throws OCSBadRequestException
498
-	 */
499
-	protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
500
-		// Verify arguments
501
-		if ($itemType === null) {
502
-			throw new OCSBadRequestException('Missing itemType');
503
-		}
504
-
505
-		// Get users
506
-		if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
507
-			$this->getUsers($search);
508
-		}
509
-
510
-		// Get groups
511
-		if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
512
-			$this->getGroups($search);
513
-		}
514
-
515
-		// Get remote
516
-		$remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
517
-		if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
518
-			$remoteResults = $this->getRemote($search);
519
-		}
520
-
521
-		// Get emails
522
-		$mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
523
-		if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
524
-			$mailResults = $this->getEmail($search);
525
-		}
526
-
527
-		// Get from lookup server
528
-		if ($lookup) {
529
-			$this->getLookup($search);
530
-		}
531
-
532
-		// if we have a exact match, either for the federated cloud id or for the
533
-		// email address we only return the exact match. It is highly unlikely
534
-		// that the exact same email address and federated cloud id exists
535
-		if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
536
-			$this->result['emails'] = $mailResults['results'];
537
-			$this->result['exact']['emails'] = $mailResults['exact'];
538
-		} else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
539
-			$this->result['remotes'] = $remoteResults['results'];
540
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
541
-		} else {
542
-			$this->result['remotes'] = $remoteResults['results'];
543
-			$this->result['exact']['remotes'] = $remoteResults['exact'];
544
-			$this->result['emails'] = $mailResults['results'];
545
-			$this->result['exact']['emails'] = $mailResults['exact'];
546
-		}
547
-
548
-		$response = new Http\DataResponse($this->result);
549
-
550
-		if (sizeof($this->reachedEndFor) < 3) {
551
-			$response->addHeader('Link', $this->getPaginationLink($page, [
552
-				'search' => $search,
553
-				'itemType' => $itemType,
554
-				'shareType' => $shareTypes,
555
-				'perPage' => $perPage,
556
-			]));
557
-		}
558
-
559
-		return $response;
560
-	}
561
-
562
-	/**
563
-	 * @param string $search
564
-	 * @return array
565
-	 */
566
-	protected function getEmail($search) {
567
-		$result = ['results' => [], 'exact' => []];
568
-
569
-		// Search in contacts
570
-		//@todo Pagination missing
571
-		$addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
572
-		$result['exactIdMatch'] = false;
573
-		foreach ($addressBookContacts as $contact) {
574
-			if (isset($contact['isLocalSystemBook'])) {
575
-				continue;
576
-			}
577
-			if (isset($contact['EMAIL'])) {
578
-				$emailAddresses = $contact['EMAIL'];
579
-				if (!is_array($emailAddresses)) {
580
-					$emailAddresses = [$emailAddresses];
581
-				}
582
-				foreach ($emailAddresses as $emailAddress) {
583
-					if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
584
-						if (strtolower($emailAddress) === strtolower($search)) {
585
-							$result['exactIdMatch'] = true;
586
-						}
587
-						$result['exact'][] = [
588
-							'label' => $contact['FN'] . " ($emailAddress)",
589
-							'value' => [
590
-								'shareType' => Share::SHARE_TYPE_EMAIL,
591
-								'shareWith' => $emailAddress,
592
-							],
593
-						];
594
-					} else {
595
-						$result['results'][] = [
596
-							'label' => $contact['FN'] . " ($emailAddress)",
597
-							'value' => [
598
-								'shareType' => Share::SHARE_TYPE_EMAIL,
599
-								'shareWith' => $emailAddress,
600
-							],
601
-						];
602
-					}
603
-				}
604
-			}
605
-		}
606
-
607
-		if (!$this->shareeEnumeration) {
608
-			$result['results'] = [];
609
-		}
610
-
611
-		if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
612
-			$result['exact'][] = [
613
-				'label' => $search,
614
-				'value' => [
615
-					'shareType' => Share::SHARE_TYPE_EMAIL,
616
-					'shareWith' => $search,
617
-				],
618
-			];
619
-		}
620
-
621
-		$this->reachedEndFor[] = 'emails';
622
-
623
-		return $result;
624
-	}
625
-
626
-	protected function getLookup($search) {
627
-		$isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
628
-		$result = [];
629
-
630
-		if($isEnabled === 'yes') {
631
-			try {
632
-				$client = $this->clientService->newClient();
633
-				$response = $client->get(
634
-					'https://lookup.nextcloud.com/users?search=' . urlencode($search),
635
-					[
636
-						'timeout' => 10,
637
-						'connect_timeout' => 3,
638
-					]
639
-				);
640
-
641
-				$body = json_decode($response->getBody(), true);
642
-
643
-				$result = [];
644
-				foreach ($body as $lookup) {
645
-					$result[] = [
646
-						'label' => $lookup['federationId'],
647
-						'value' => [
648
-							'shareType' => Share::SHARE_TYPE_REMOTE,
649
-							'shareWith' => $lookup['federationId'],
650
-						],
651
-						'extra' => $lookup,
652
-					];
653
-				}
654
-			} catch (\Exception $e) {}
655
-		}
656
-
657
-		$this->result['lookup'] = $result;
658
-	}
659
-
660
-	/**
661
-	 * Generates a bunch of pagination links for the current page
662
-	 *
663
-	 * @param int $page Current page
664
-	 * @param array $params Parameters for the URL
665
-	 * @return string
666
-	 */
667
-	protected function getPaginationLink($page, array $params) {
668
-		if ($this->isV2()) {
669
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
670
-		} else {
671
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
672
-		}
673
-		$params['page'] = $page + 1;
674
-		$link = '<' . $url . http_build_query($params) . '>; rel="next"';
675
-
676
-		return $link;
677
-	}
678
-
679
-	/**
680
-	 * @return bool
681
-	 */
682
-	protected function isV2() {
683
-		return $this->request->getScriptName() === '/ocs/v2.php';
684
-	}
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
+        ],
96
+        'users' => [],
97
+        'groups' => [],
98
+        'remotes' => [],
99
+        'emails' => [],
100
+        'lookup' => [],
101
+    ];
102
+
103
+    protected $reachedEndFor = [];
104
+
105
+    /**
106
+     * @param string $appName
107
+     * @param IRequest $request
108
+     * @param IGroupManager $groupManager
109
+     * @param IUserManager $userManager
110
+     * @param IManager $contactsManager
111
+     * @param IConfig $config
112
+     * @param IUserSession $userSession
113
+     * @param IURLGenerator $urlGenerator
114
+     * @param ILogger $logger
115
+     * @param \OCP\Share\IManager $shareManager
116
+     * @param IClientService $clientService
117
+     * @param ICloudIdManager $cloudIdManager
118
+     */
119
+    public function __construct($appName,
120
+                                IRequest $request,
121
+                                IGroupManager $groupManager,
122
+                                IUserManager $userManager,
123
+                                IManager $contactsManager,
124
+                                IConfig $config,
125
+                                IUserSession $userSession,
126
+                                IURLGenerator $urlGenerator,
127
+                                ILogger $logger,
128
+                                \OCP\Share\IManager $shareManager,
129
+                                IClientService $clientService,
130
+                                ICloudIdManager $cloudIdManager
131
+    ) {
132
+        parent::__construct($appName, $request);
133
+
134
+        $this->groupManager = $groupManager;
135
+        $this->userManager = $userManager;
136
+        $this->contactsManager = $contactsManager;
137
+        $this->config = $config;
138
+        $this->userSession = $userSession;
139
+        $this->urlGenerator = $urlGenerator;
140
+        $this->logger = $logger;
141
+        $this->shareManager = $shareManager;
142
+        $this->clientService = $clientService;
143
+        $this->cloudIdManager = $cloudIdManager;
144
+    }
145
+
146
+    /**
147
+     * @param string $search
148
+     */
149
+    protected function getUsers($search) {
150
+        $this->result['users'] = $this->result['exact']['users'] = $users = [];
151
+
152
+        $userGroups = [];
153
+        if ($this->shareWithGroupOnly) {
154
+            // Search in all the groups this user is part of
155
+            $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser());
156
+            foreach ($userGroups as $userGroup) {
157
+                $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset);
158
+                foreach ($usersTmp as $uid => $userDisplayName) {
159
+                    $users[$uid] = $userDisplayName;
160
+                }
161
+            }
162
+        } else {
163
+            // Search in all users
164
+            $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset);
165
+
166
+            foreach ($usersTmp as $user) {
167
+                $users[$user->getUID()] = $user->getDisplayName();
168
+            }
169
+        }
170
+
171
+        if (!$this->shareeEnumeration || sizeof($users) < $this->limit) {
172
+            $this->reachedEndFor[] = 'users';
173
+        }
174
+
175
+        $foundUserById = false;
176
+        $lowerSearch = strtolower($search);
177
+        foreach ($users as $uid => $userDisplayName) {
178
+            if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) {
179
+                if (strtolower($uid) === $lowerSearch) {
180
+                    $foundUserById = true;
181
+                }
182
+                $this->result['exact']['users'][] = [
183
+                    'label' => $userDisplayName,
184
+                    'value' => [
185
+                        'shareType' => Share::SHARE_TYPE_USER,
186
+                        'shareWith' => $uid,
187
+                    ],
188
+                ];
189
+            } else {
190
+                $this->result['users'][] = [
191
+                    'label' => $userDisplayName,
192
+                    'value' => [
193
+                        'shareType' => Share::SHARE_TYPE_USER,
194
+                        'shareWith' => $uid,
195
+                    ],
196
+                ];
197
+            }
198
+        }
199
+
200
+        if ($this->offset === 0 && !$foundUserById) {
201
+            // On page one we try if the search result has a direct hit on the
202
+            // user id and if so, we add that to the exact match list
203
+            $user = $this->userManager->get($search);
204
+            if ($user instanceof IUser) {
205
+                $addUser = true;
206
+
207
+                if ($this->shareWithGroupOnly) {
208
+                    // Only add, if we have a common group
209
+                    $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user));
210
+                    $addUser = !empty($commonGroups);
211
+                }
212
+
213
+                if ($addUser) {
214
+                    array_push($this->result['exact']['users'], [
215
+                        'label' => $user->getDisplayName(),
216
+                        'value' => [
217
+                            'shareType' => Share::SHARE_TYPE_USER,
218
+                            'shareWith' => $user->getUID(),
219
+                        ],
220
+                    ]);
221
+                }
222
+            }
223
+        }
224
+
225
+        if (!$this->shareeEnumeration) {
226
+            $this->result['users'] = [];
227
+        }
228
+    }
229
+
230
+    /**
231
+     * @param string $search
232
+     */
233
+    protected function getGroups($search) {
234
+        $this->result['groups'] = $this->result['exact']['groups'] = [];
235
+
236
+        $groups = $this->groupManager->search($search, $this->limit, $this->offset);
237
+        $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups);
238
+
239
+        if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) {
240
+            $this->reachedEndFor[] = 'groups';
241
+        }
242
+
243
+        $userGroups =  [];
244
+        if (!empty($groups) && $this->shareWithGroupOnly) {
245
+            // Intersect all the groups that match with the groups this user is a member of
246
+            $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
247
+            $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups);
248
+            $groupIds = array_intersect($groupIds, $userGroups);
249
+        }
250
+
251
+        $lowerSearch = strtolower($search);
252
+        foreach ($groups as $group) {
253
+            // FIXME: use a more efficient approach
254
+            $gid = $group->getGID();
255
+            if (!in_array($gid, $groupIds)) {
256
+                continue;
257
+            }
258
+            if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) {
259
+                $this->result['exact']['groups'][] = [
260
+                    'label' => $group->getDisplayName(),
261
+                    'value' => [
262
+                        'shareType' => Share::SHARE_TYPE_GROUP,
263
+                        'shareWith' => $gid,
264
+                    ],
265
+                ];
266
+            } else {
267
+                $this->result['groups'][] = [
268
+                    'label' => $group->getDisplayName(),
269
+                    'value' => [
270
+                        'shareType' => Share::SHARE_TYPE_GROUP,
271
+                        'shareWith' => $gid,
272
+                    ],
273
+                ];
274
+            }
275
+        }
276
+
277
+        if ($this->offset === 0 && empty($this->result['exact']['groups'])) {
278
+            // On page one we try if the search result has a direct hit on the
279
+            // user id and if so, we add that to the exact match list
280
+            $group = $this->groupManager->get($search);
281
+            if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) {
282
+                array_push($this->result['exact']['groups'], [
283
+                    'label' => $group->getDisplayName(),
284
+                    'value' => [
285
+                        'shareType' => Share::SHARE_TYPE_GROUP,
286
+                        'shareWith' => $group->getGID(),
287
+                    ],
288
+                ]);
289
+            }
290
+        }
291
+
292
+        if (!$this->shareeEnumeration) {
293
+            $this->result['groups'] = [];
294
+        }
295
+    }
296
+
297
+    /**
298
+     * @param string $search
299
+     * @return array
300
+     */
301
+    protected function getRemote($search) {
302
+        $result = ['results' => [], 'exact' => []];
303
+
304
+        // Search in contacts
305
+        //@todo Pagination missing
306
+        $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']);
307
+        $result['exactIdMatch'] = false;
308
+        foreach ($addressBookContacts as $contact) {
309
+            if (isset($contact['isLocalSystemBook'])) {
310
+                continue;
311
+            }
312
+            if (isset($contact['CLOUD'])) {
313
+                $cloudIds = $contact['CLOUD'];
314
+                if (!is_array($cloudIds)) {
315
+                    $cloudIds = [$cloudIds];
316
+                }
317
+                $lowerSearch = strtolower($search);
318
+                foreach ($cloudIds as $cloudId) {
319
+                    list(, $serverUrl) = $this->splitUserRemote($cloudId);
320
+                    if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) {
321
+                        if (strtolower($cloudId) === $lowerSearch) {
322
+                            $result['exactIdMatch'] = true;
323
+                        }
324
+                        $result['exact'][] = [
325
+                            'label' => $contact['FN'] . " ($cloudId)",
326
+                            'value' => [
327
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
328
+                                'shareWith' => $cloudId,
329
+                                'server' => $serverUrl,
330
+                            ],
331
+                        ];
332
+                    } else {
333
+                        $result['results'][] = [
334
+                            'label' => $contact['FN'] . " ($cloudId)",
335
+                            'value' => [
336
+                                'shareType' => Share::SHARE_TYPE_REMOTE,
337
+                                'shareWith' => $cloudId,
338
+                                'server' => $serverUrl,
339
+                            ],
340
+                        ];
341
+                    }
342
+                }
343
+            }
344
+        }
345
+
346
+        if (!$this->shareeEnumeration) {
347
+            $result['results'] = [];
348
+        }
349
+
350
+        if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) {
351
+            $result['exact'][] = [
352
+                'label' => $search,
353
+                'value' => [
354
+                    'shareType' => Share::SHARE_TYPE_REMOTE,
355
+                    'shareWith' => $search,
356
+                ],
357
+            ];
358
+        }
359
+
360
+        $this->reachedEndFor[] = 'remotes';
361
+
362
+        return $result;
363
+    }
364
+
365
+    /**
366
+     * split user and remote from federated cloud id
367
+     *
368
+     * @param string $address federated share address
369
+     * @return array [user, remoteURL]
370
+     * @throws \Exception
371
+     */
372
+    public function splitUserRemote($address) {
373
+        try {
374
+            $cloudId = $this->cloudIdManager->resolveCloudId($address);
375
+            return [$cloudId->getUser(), $cloudId->getRemote()];
376
+        } catch (\InvalidArgumentException $e) {
377
+            throw new \Exception('Invalid Federated Cloud ID', 0, $e);
378
+        }
379
+    }
380
+
381
+    /**
382
+     * Strips away a potential file names and trailing slashes:
383
+     * - http://localhost
384
+     * - http://localhost/
385
+     * - http://localhost/index.php
386
+     * - http://localhost/index.php/s/{shareToken}
387
+     *
388
+     * all return: http://localhost
389
+     *
390
+     * @param string $remote
391
+     * @return string
392
+     */
393
+    protected function fixRemoteURL($remote) {
394
+        $remote = str_replace('\\', '/', $remote);
395
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
396
+            $remote = substr($remote, 0, $fileNamePosition);
397
+        }
398
+        $remote = rtrim($remote, '/');
399
+
400
+        return $remote;
401
+    }
402
+
403
+    /**
404
+     * @NoAdminRequired
405
+     *
406
+     * @param string $search
407
+     * @param string $itemType
408
+     * @param int $page
409
+     * @param int $perPage
410
+     * @param int|int[] $shareType
411
+     * @param bool $lookup
412
+     * @return Http\DataResponse
413
+     * @throws OCSBadRequestException
414
+     */
415
+    public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) {
416
+
417
+        // only search for string larger than a given threshold
418
+        $threshold = $this->config->getSystemValue('sharing.minSearchStringLength', 0);
419
+        if (strlen($search) < $threshold) {
420
+            return new Http\DataResponse($this->result);
421
+        }
422
+
423
+        // never return more than the max. number of results configured in the config.php
424
+        $maxResults = $this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
425
+        if ($maxResults > 0) {
426
+            $perPage = min($perPage, $maxResults);
427
+        }
428
+        if ($perPage <= 0) {
429
+            throw new OCSBadRequestException('Invalid perPage argument');
430
+        }
431
+        if ($page <= 0) {
432
+            throw new OCSBadRequestException('Invalid page');
433
+        }
434
+
435
+        $shareTypes = [
436
+            Share::SHARE_TYPE_USER,
437
+        ];
438
+
439
+        if ($itemType === 'file' || $itemType === 'folder') {
440
+            if ($this->shareManager->allowGroupSharing()) {
441
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
442
+            }
443
+
444
+            if ($this->isRemoteSharingAllowed($itemType)) {
445
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
446
+            }
447
+
448
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
449
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
450
+            }
451
+        } else {
452
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
453
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
454
+        }
455
+
456
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
457
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
458
+            sort($shareTypes);
459
+        } else if (is_numeric($shareType)) {
460
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
461
+            sort($shareTypes);
462
+        }
463
+
464
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
465
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
466
+        $this->limit = (int) $perPage;
467
+        $this->offset = $perPage * ($page - 1);
468
+
469
+        return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup);
470
+    }
471
+
472
+    /**
473
+     * Method to get out the static call for better testing
474
+     *
475
+     * @param string $itemType
476
+     * @return bool
477
+     */
478
+    protected function isRemoteSharingAllowed($itemType) {
479
+        try {
480
+            $backend = Share::getBackend($itemType);
481
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
482
+        } catch (\Exception $e) {
483
+            return false;
484
+        }
485
+    }
486
+
487
+    /**
488
+     * Testable search function that does not need globals
489
+     *
490
+     * @param string $search
491
+     * @param string $itemType
492
+     * @param array $shareTypes
493
+     * @param int $page
494
+     * @param int $perPage
495
+     * @param bool $lookup
496
+     * @return Http\DataResponse
497
+     * @throws OCSBadRequestException
498
+     */
499
+    protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) {
500
+        // Verify arguments
501
+        if ($itemType === null) {
502
+            throw new OCSBadRequestException('Missing itemType');
503
+        }
504
+
505
+        // Get users
506
+        if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) {
507
+            $this->getUsers($search);
508
+        }
509
+
510
+        // Get groups
511
+        if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) {
512
+            $this->getGroups($search);
513
+        }
514
+
515
+        // Get remote
516
+        $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
517
+        if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) {
518
+            $remoteResults = $this->getRemote($search);
519
+        }
520
+
521
+        // Get emails
522
+        $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false];
523
+        if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) {
524
+            $mailResults = $this->getEmail($search);
525
+        }
526
+
527
+        // Get from lookup server
528
+        if ($lookup) {
529
+            $this->getLookup($search);
530
+        }
531
+
532
+        // if we have a exact match, either for the federated cloud id or for the
533
+        // email address we only return the exact match. It is highly unlikely
534
+        // that the exact same email address and federated cloud id exists
535
+        if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) {
536
+            $this->result['emails'] = $mailResults['results'];
537
+            $this->result['exact']['emails'] = $mailResults['exact'];
538
+        } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) {
539
+            $this->result['remotes'] = $remoteResults['results'];
540
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
541
+        } else {
542
+            $this->result['remotes'] = $remoteResults['results'];
543
+            $this->result['exact']['remotes'] = $remoteResults['exact'];
544
+            $this->result['emails'] = $mailResults['results'];
545
+            $this->result['exact']['emails'] = $mailResults['exact'];
546
+        }
547
+
548
+        $response = new Http\DataResponse($this->result);
549
+
550
+        if (sizeof($this->reachedEndFor) < 3) {
551
+            $response->addHeader('Link', $this->getPaginationLink($page, [
552
+                'search' => $search,
553
+                'itemType' => $itemType,
554
+                'shareType' => $shareTypes,
555
+                'perPage' => $perPage,
556
+            ]));
557
+        }
558
+
559
+        return $response;
560
+    }
561
+
562
+    /**
563
+     * @param string $search
564
+     * @return array
565
+     */
566
+    protected function getEmail($search) {
567
+        $result = ['results' => [], 'exact' => []];
568
+
569
+        // Search in contacts
570
+        //@todo Pagination missing
571
+        $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']);
572
+        $result['exactIdMatch'] = false;
573
+        foreach ($addressBookContacts as $contact) {
574
+            if (isset($contact['isLocalSystemBook'])) {
575
+                continue;
576
+            }
577
+            if (isset($contact['EMAIL'])) {
578
+                $emailAddresses = $contact['EMAIL'];
579
+                if (!is_array($emailAddresses)) {
580
+                    $emailAddresses = [$emailAddresses];
581
+                }
582
+                foreach ($emailAddresses as $emailAddress) {
583
+                    if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) {
584
+                        if (strtolower($emailAddress) === strtolower($search)) {
585
+                            $result['exactIdMatch'] = true;
586
+                        }
587
+                        $result['exact'][] = [
588
+                            'label' => $contact['FN'] . " ($emailAddress)",
589
+                            'value' => [
590
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
591
+                                'shareWith' => $emailAddress,
592
+                            ],
593
+                        ];
594
+                    } else {
595
+                        $result['results'][] = [
596
+                            'label' => $contact['FN'] . " ($emailAddress)",
597
+                            'value' => [
598
+                                'shareType' => Share::SHARE_TYPE_EMAIL,
599
+                                'shareWith' => $emailAddress,
600
+                            ],
601
+                        ];
602
+                    }
603
+                }
604
+            }
605
+        }
606
+
607
+        if (!$this->shareeEnumeration) {
608
+            $result['results'] = [];
609
+        }
610
+
611
+        if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) {
612
+            $result['exact'][] = [
613
+                'label' => $search,
614
+                'value' => [
615
+                    'shareType' => Share::SHARE_TYPE_EMAIL,
616
+                    'shareWith' => $search,
617
+                ],
618
+            ];
619
+        }
620
+
621
+        $this->reachedEndFor[] = 'emails';
622
+
623
+        return $result;
624
+    }
625
+
626
+    protected function getLookup($search) {
627
+        $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
628
+        $result = [];
629
+
630
+        if($isEnabled === 'yes') {
631
+            try {
632
+                $client = $this->clientService->newClient();
633
+                $response = $client->get(
634
+                    'https://lookup.nextcloud.com/users?search=' . urlencode($search),
635
+                    [
636
+                        'timeout' => 10,
637
+                        'connect_timeout' => 3,
638
+                    ]
639
+                );
640
+
641
+                $body = json_decode($response->getBody(), true);
642
+
643
+                $result = [];
644
+                foreach ($body as $lookup) {
645
+                    $result[] = [
646
+                        'label' => $lookup['federationId'],
647
+                        'value' => [
648
+                            'shareType' => Share::SHARE_TYPE_REMOTE,
649
+                            'shareWith' => $lookup['federationId'],
650
+                        ],
651
+                        'extra' => $lookup,
652
+                    ];
653
+                }
654
+            } catch (\Exception $e) {}
655
+        }
656
+
657
+        $this->result['lookup'] = $result;
658
+    }
659
+
660
+    /**
661
+     * Generates a bunch of pagination links for the current page
662
+     *
663
+     * @param int $page Current page
664
+     * @param array $params Parameters for the URL
665
+     * @return string
666
+     */
667
+    protected function getPaginationLink($page, array $params) {
668
+        if ($this->isV2()) {
669
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
670
+        } else {
671
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
672
+        }
673
+        $params['page'] = $page + 1;
674
+        $link = '<' . $url . http_build_query($params) . '>; rel="next"';
675
+
676
+        return $link;
677
+    }
678
+
679
+    /**
680
+     * @return bool
681
+     */
682
+    protected function isV2() {
683
+        return $this->request->getScriptName() === '/ocs/v2.php';
684
+    }
685 685
 }
Please login to merge, or discard this patch.