1
0

ShareesAPIController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\Files_Sharing\Controller;
  9. use Generator;
  10. use OC\Collaboration\Collaborators\SearchResult;
  11. use OC\Share\Share;
  12. use OCA\Files_Sharing\ResponseDefinitions;
  13. use OCP\AppFramework\Http;
  14. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  15. use OCP\AppFramework\Http\DataResponse;
  16. use OCP\AppFramework\OCS\OCSBadRequestException;
  17. use OCP\AppFramework\OCSController;
  18. use OCP\Collaboration\Collaborators\ISearch;
  19. use OCP\Collaboration\Collaborators\ISearchResult;
  20. use OCP\Collaboration\Collaborators\SearchResultType;
  21. use OCP\Constants;
  22. use OCP\IConfig;
  23. use OCP\IRequest;
  24. use OCP\IURLGenerator;
  25. use OCP\Share\IManager;
  26. use OCP\Share\IShare;
  27. use function array_slice;
  28. use function array_values;
  29. use function usort;
  30. /**
  31. * @psalm-import-type Files_SharingShareesSearchResult from ResponseDefinitions
  32. * @psalm-import-type Files_SharingShareesRecommendedResult from ResponseDefinitions
  33. */
  34. class ShareesAPIController extends OCSController {
  35. /** @var int */
  36. protected $offset = 0;
  37. /** @var int */
  38. protected $limit = 10;
  39. /** @var Files_SharingShareesSearchResult */
  40. protected $result = [
  41. 'exact' => [
  42. 'users' => [],
  43. 'groups' => [],
  44. 'remotes' => [],
  45. 'remote_groups' => [],
  46. 'emails' => [],
  47. 'circles' => [],
  48. 'rooms' => [],
  49. ],
  50. 'users' => [],
  51. 'groups' => [],
  52. 'remotes' => [],
  53. 'remote_groups' => [],
  54. 'emails' => [],
  55. 'lookup' => [],
  56. 'circles' => [],
  57. 'rooms' => [],
  58. 'lookupEnabled' => false,
  59. ];
  60. protected $reachedEndFor = [];
  61. /**
  62. * @param string $UserId
  63. * @param string $appName
  64. * @param IRequest $request
  65. * @param IConfig $config
  66. * @param IURLGenerator $urlGenerator
  67. * @param IManager $shareManager
  68. * @param ISearch $collaboratorSearch
  69. */
  70. public function __construct(
  71. string $appName,
  72. IRequest $request,
  73. protected string $userId,
  74. protected IConfig $config,
  75. protected IURLGenerator $urlGenerator,
  76. protected IManager $shareManager,
  77. protected ISearch $collaboratorSearch,
  78. ) {
  79. parent::__construct($appName, $request);
  80. }
  81. /**
  82. * Search for sharees
  83. *
  84. * @param string $search Text to search for
  85. * @param string|null $itemType Limit to specific item types
  86. * @param int $page Page offset for searching
  87. * @param int $perPage Limit amount of search results per page
  88. * @param int|list<int>|null $shareType Limit to specific share types
  89. * @param bool $lookup If a global lookup should be performed too
  90. * @return DataResponse<Http::STATUS_OK, Files_SharingShareesSearchResult, array{Link?: string}>
  91. * @throws OCSBadRequestException Invalid search parameters
  92. *
  93. * 200: Sharees search result returned
  94. */
  95. #[NoAdminRequired]
  96. public function search(string $search = '', ?string $itemType = null, int $page = 1, int $perPage = 200, $shareType = null, bool $lookup = false): DataResponse {
  97. // only search for string larger than a given threshold
  98. $threshold = $this->config->getSystemValueInt('sharing.minSearchStringLength', 0);
  99. if (strlen($search) < $threshold) {
  100. return new DataResponse($this->result);
  101. }
  102. if ($this->shareManager->sharingDisabledForUser($this->userId)) {
  103. return new DataResponse($this->result);
  104. }
  105. // never return more than the max. number of results configured in the config.php
  106. $maxResults = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
  107. if ($maxResults > 0) {
  108. $perPage = min($perPage, $maxResults);
  109. }
  110. if ($perPage <= 0) {
  111. throw new OCSBadRequestException('Invalid perPage argument');
  112. }
  113. if ($page <= 0) {
  114. throw new OCSBadRequestException('Invalid page');
  115. }
  116. $shareTypes = [
  117. IShare::TYPE_USER,
  118. ];
  119. if ($itemType === null) {
  120. throw new OCSBadRequestException('Missing itemType');
  121. } elseif ($itemType === 'file' || $itemType === 'folder') {
  122. if ($this->shareManager->allowGroupSharing()) {
  123. $shareTypes[] = IShare::TYPE_GROUP;
  124. }
  125. if ($this->isRemoteSharingAllowed($itemType)) {
  126. $shareTypes[] = IShare::TYPE_REMOTE;
  127. }
  128. if ($this->isRemoteGroupSharingAllowed($itemType)) {
  129. $shareTypes[] = IShare::TYPE_REMOTE_GROUP;
  130. }
  131. if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
  132. $shareTypes[] = IShare::TYPE_EMAIL;
  133. }
  134. if ($this->shareManager->shareProviderExists(IShare::TYPE_ROOM)) {
  135. $shareTypes[] = IShare::TYPE_ROOM;
  136. }
  137. if ($this->shareManager->shareProviderExists(IShare::TYPE_SCIENCEMESH)) {
  138. $shareTypes[] = IShare::TYPE_SCIENCEMESH;
  139. }
  140. } else {
  141. if ($this->shareManager->allowGroupSharing()) {
  142. $shareTypes[] = IShare::TYPE_GROUP;
  143. }
  144. $shareTypes[] = IShare::TYPE_EMAIL;
  145. }
  146. // FIXME: DI
  147. if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
  148. $shareTypes[] = IShare::TYPE_CIRCLE;
  149. }
  150. if ($this->shareManager->shareProviderExists(IShare::TYPE_SCIENCEMESH)) {
  151. $shareTypes[] = IShare::TYPE_SCIENCEMESH;
  152. }
  153. if ($shareType !== null && is_array($shareType)) {
  154. $shareTypes = array_intersect($shareTypes, $shareType);
  155. } elseif (is_numeric($shareType)) {
  156. $shareTypes = array_intersect($shareTypes, [(int)$shareType]);
  157. }
  158. sort($shareTypes);
  159. $this->limit = $perPage;
  160. $this->offset = $perPage * ($page - 1);
  161. // In global scale mode we always search the loogup server
  162. if ($this->config->getSystemValueBool('gs.enabled', false)) {
  163. $lookup = true;
  164. $this->result['lookupEnabled'] = true;
  165. } else {
  166. $this->result['lookupEnabled'] = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes') === 'yes';
  167. }
  168. [$result, $hasMoreResults] = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset);
  169. // extra treatment for 'exact' subarray, with a single merge expected keys might be lost
  170. if (isset($result['exact'])) {
  171. $result['exact'] = array_merge($this->result['exact'], $result['exact']);
  172. }
  173. $this->result = array_merge($this->result, $result);
  174. $response = new DataResponse($this->result);
  175. if ($hasMoreResults) {
  176. $response->setHeaders(['Link' => $this->getPaginationLink($page, [
  177. 'search' => $search,
  178. 'itemType' => $itemType,
  179. 'shareType' => $shareTypes,
  180. 'perPage' => $perPage,
  181. ])]);
  182. }
  183. return $response;
  184. }
  185. /**
  186. * @param string $user
  187. * @param int $shareType
  188. *
  189. * @return Generator<array<string>>
  190. */
  191. private function getAllShareesByType(string $user, int $shareType): Generator {
  192. $offset = 0;
  193. $pageSize = 50;
  194. while (count($page = $this->shareManager->getSharesBy(
  195. $user,
  196. $shareType,
  197. null,
  198. false,
  199. $pageSize,
  200. $offset
  201. ))) {
  202. foreach ($page as $share) {
  203. yield [$share->getSharedWith(), $share->getSharedWithDisplayName() ?? $share->getSharedWith()];
  204. }
  205. $offset += $pageSize;
  206. }
  207. }
  208. private function sortShareesByFrequency(array $sharees): array {
  209. usort($sharees, function (array $s1, array $s2): int {
  210. return $s2['count'] - $s1['count'];
  211. });
  212. return $sharees;
  213. }
  214. private $searchResultTypeMap = [
  215. IShare::TYPE_USER => 'users',
  216. IShare::TYPE_GROUP => 'groups',
  217. IShare::TYPE_REMOTE => 'remotes',
  218. IShare::TYPE_REMOTE_GROUP => 'remote_groups',
  219. IShare::TYPE_EMAIL => 'emails',
  220. ];
  221. private function getAllSharees(string $user, array $shareTypes): ISearchResult {
  222. $result = [];
  223. foreach ($shareTypes as $shareType) {
  224. $sharees = $this->getAllShareesByType($user, $shareType);
  225. $shareTypeResults = [];
  226. foreach ($sharees as [$sharee, $displayname]) {
  227. if (!isset($this->searchResultTypeMap[$shareType]) || trim($sharee) === '') {
  228. continue;
  229. }
  230. if (!isset($shareTypeResults[$sharee])) {
  231. $shareTypeResults[$sharee] = [
  232. 'count' => 1,
  233. 'label' => $displayname,
  234. 'value' => [
  235. 'shareType' => $shareType,
  236. 'shareWith' => $sharee,
  237. ],
  238. ];
  239. } else {
  240. $shareTypeResults[$sharee]['count']++;
  241. }
  242. }
  243. $result = array_merge($result, array_values($shareTypeResults));
  244. }
  245. $top5 = array_slice(
  246. $this->sortShareesByFrequency($result),
  247. 0,
  248. 5
  249. );
  250. $searchResult = new SearchResult();
  251. foreach ($this->searchResultTypeMap as $int => $str) {
  252. $searchResult->addResultSet(new SearchResultType($str), [], []);
  253. foreach ($top5 as $x) {
  254. if ($x['value']['shareType'] === $int) {
  255. $searchResult->addResultSet(new SearchResultType($str), [], [$x]);
  256. }
  257. }
  258. }
  259. return $searchResult;
  260. }
  261. /**
  262. * Find recommended sharees
  263. *
  264. * @param string $itemType Limit to specific item types
  265. * @param int|list<int>|null $shareType Limit to specific share types
  266. * @return DataResponse<Http::STATUS_OK, Files_SharingShareesRecommendedResult, array{}>
  267. *
  268. * 200: Recommended sharees returned
  269. */
  270. #[NoAdminRequired]
  271. public function findRecommended(string $itemType, $shareType = null): DataResponse {
  272. $shareTypes = [
  273. IShare::TYPE_USER,
  274. ];
  275. if ($itemType === 'file' || $itemType === 'folder') {
  276. if ($this->shareManager->allowGroupSharing()) {
  277. $shareTypes[] = IShare::TYPE_GROUP;
  278. }
  279. if ($this->isRemoteSharingAllowed($itemType)) {
  280. $shareTypes[] = IShare::TYPE_REMOTE;
  281. }
  282. if ($this->isRemoteGroupSharingAllowed($itemType)) {
  283. $shareTypes[] = IShare::TYPE_REMOTE_GROUP;
  284. }
  285. if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
  286. $shareTypes[] = IShare::TYPE_EMAIL;
  287. }
  288. if ($this->shareManager->shareProviderExists(IShare::TYPE_ROOM)) {
  289. $shareTypes[] = IShare::TYPE_ROOM;
  290. }
  291. } else {
  292. $shareTypes[] = IShare::TYPE_GROUP;
  293. $shareTypes[] = IShare::TYPE_EMAIL;
  294. }
  295. // FIXME: DI
  296. if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
  297. $shareTypes[] = IShare::TYPE_CIRCLE;
  298. }
  299. if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
  300. $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
  301. sort($shareTypes);
  302. } elseif (is_numeric($shareType)) {
  303. $shareTypes = array_intersect($shareTypes, [(int)$shareType]);
  304. sort($shareTypes);
  305. }
  306. return new DataResponse(
  307. $this->getAllSharees($this->userId, $shareTypes)->asArray()
  308. );
  309. }
  310. /**
  311. * Method to get out the static call for better testing
  312. *
  313. * @param string $itemType
  314. * @return bool
  315. */
  316. protected function isRemoteSharingAllowed(string $itemType): bool {
  317. try {
  318. // FIXME: static foo makes unit testing unnecessarily difficult
  319. $backend = Share::getBackend($itemType);
  320. return $backend->isShareTypeAllowed(IShare::TYPE_REMOTE);
  321. } catch (\Exception $e) {
  322. return false;
  323. }
  324. }
  325. protected function isRemoteGroupSharingAllowed(string $itemType): bool {
  326. try {
  327. // FIXME: static foo makes unit testing unnecessarily difficult
  328. $backend = Share::getBackend($itemType);
  329. return $backend->isShareTypeAllowed(IShare::TYPE_REMOTE_GROUP);
  330. } catch (\Exception $e) {
  331. return false;
  332. }
  333. }
  334. /**
  335. * Generates a bunch of pagination links for the current page
  336. *
  337. * @param int $page Current page
  338. * @param array $params Parameters for the URL
  339. * @return string
  340. */
  341. protected function getPaginationLink(int $page, array $params): string {
  342. if ($this->isV2()) {
  343. $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
  344. } else {
  345. $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
  346. }
  347. $params['page'] = $page + 1;
  348. return '<' . $url . http_build_query($params) . '>; rel="next"';
  349. }
  350. /**
  351. * @return bool
  352. */
  353. protected function isV2(): bool {
  354. return $this->request->getScriptName() === '/ocs/v2.php';
  355. }
  356. }