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 OCA\Files_Sharing\ResponseDefinitions;
  12. use OCP\AppFramework\Http;
  13. use OCP\AppFramework\Http\DataResponse;
  14. use OCP\AppFramework\OCS\OCSBadRequestException;
  15. use OCP\AppFramework\OCSController;
  16. use OCP\Collaboration\Collaborators\ISearch;
  17. use OCP\Collaboration\Collaborators\ISearchResult;
  18. use OCP\Collaboration\Collaborators\SearchResultType;
  19. use OCP\Constants;
  20. use OCP\IConfig;
  21. use OCP\IRequest;
  22. use OCP\IURLGenerator;
  23. use OCP\Share\IManager;
  24. use OCP\Share\IShare;
  25. use function array_slice;
  26. use function array_values;
  27. use function usort;
  28. /**
  29. * @psalm-import-type Files_SharingShareesSearchResult from ResponseDefinitions
  30. * @psalm-import-type Files_SharingShareesRecommendedResult from ResponseDefinitions
  31. */
  32. class ShareesAPIController extends OCSController {
  33. /** @var int */
  34. protected $offset = 0;
  35. /** @var int */
  36. protected $limit = 10;
  37. /** @var Files_SharingShareesSearchResult */
  38. protected $result = [
  39. 'exact' => [
  40. 'users' => [],
  41. 'groups' => [],
  42. 'remotes' => [],
  43. 'remote_groups' => [],
  44. 'emails' => [],
  45. 'circles' => [],
  46. 'rooms' => [],
  47. ],
  48. 'users' => [],
  49. 'groups' => [],
  50. 'remotes' => [],
  51. 'remote_groups' => [],
  52. 'emails' => [],
  53. 'lookup' => [],
  54. 'circles' => [],
  55. 'rooms' => [],
  56. 'lookupEnabled' => false,
  57. ];
  58. protected $reachedEndFor = [];
  59. /**
  60. * @param string $UserId
  61. * @param string $appName
  62. * @param IRequest $request
  63. * @param IConfig $config
  64. * @param IURLGenerator $urlGenerator
  65. * @param IManager $shareManager
  66. * @param ISearch $collaboratorSearch
  67. */
  68. public function __construct(
  69. string $appName,
  70. IRequest $request,
  71. protected string $userId,
  72. protected IConfig $config,
  73. protected IURLGenerator $urlGenerator,
  74. protected IManager $shareManager,
  75. protected ISearch $collaboratorSearch,
  76. ) {
  77. parent::__construct($appName, $request);
  78. }
  79. /**
  80. * @NoAdminRequired
  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|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. 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])) {
  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. * @NoAdminRequired
  262. *
  263. * Find recommended sharees
  264. *
  265. * @param string $itemType Limit to specific item types
  266. * @param int|int[]|null $shareType Limit to specific share types
  267. * @return DataResponse<Http::STATUS_OK, Files_SharingShareesRecommendedResult, array{}>
  268. *
  269. * 200: Recommended sharees returned
  270. */
  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 = \OC\Share\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 = \OC\Share\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. }