ShareesAPIController.php 11 KB

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