You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShareesAPIController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  11. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  12. * @author J0WI <J0WI@users.noreply.github.com>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author John Molakvoæ <skjnldsv@protonmail.com>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Maxence Lange <maxence@nextcloud.com>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Robin Appelman <robin@icewind.nl>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author Kate Döen <kate.doeen@nextcloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OCA\Files_Sharing\Controller;
  38. use OCP\Constants;
  39. use function array_slice;
  40. use function array_values;
  41. use Generator;
  42. use OC\Collaboration\Collaborators\SearchResult;
  43. use OCA\Files_Sharing\ResponseDefinitions;
  44. use OCP\AppFramework\Http;
  45. use OCP\AppFramework\Http\DataResponse;
  46. use OCP\AppFramework\OCS\OCSBadRequestException;
  47. use OCP\AppFramework\OCSController;
  48. use OCP\Collaboration\Collaborators\ISearch;
  49. use OCP\Collaboration\Collaborators\ISearchResult;
  50. use OCP\Collaboration\Collaborators\SearchResultType;
  51. use OCP\IConfig;
  52. use OCP\IRequest;
  53. use OCP\IURLGenerator;
  54. use OCP\Share\IShare;
  55. use OCP\Share\IManager;
  56. use function usort;
  57. /**
  58. * @psalm-import-type FilesSharingShareesSearchResult from ResponseDefinitions
  59. * @psalm-import-type FilesSharingShareesRecommendedResult from ResponseDefinitions
  60. */
  61. class ShareesAPIController extends OCSController {
  62. /** @var string */
  63. protected $userId;
  64. /** @var IConfig */
  65. protected $config;
  66. /** @var IURLGenerator */
  67. protected $urlGenerator;
  68. /** @var IManager */
  69. protected $shareManager;
  70. /** @var int */
  71. protected $offset = 0;
  72. /** @var int */
  73. protected $limit = 10;
  74. /** @var FilesSharingShareesSearchResult */
  75. protected $result = [
  76. 'exact' => [
  77. 'users' => [],
  78. 'groups' => [],
  79. 'remotes' => [],
  80. 'remote_groups' => [],
  81. 'emails' => [],
  82. 'circles' => [],
  83. 'rooms' => [],
  84. ],
  85. 'users' => [],
  86. 'groups' => [],
  87. 'remotes' => [],
  88. 'remote_groups' => [],
  89. 'emails' => [],
  90. 'lookup' => [],
  91. 'circles' => [],
  92. 'rooms' => [],
  93. 'lookupEnabled' => false,
  94. ];
  95. protected $reachedEndFor = [];
  96. /** @var ISearch */
  97. private $collaboratorSearch;
  98. /**
  99. * @param string $UserId
  100. * @param string $appName
  101. * @param IRequest $request
  102. * @param IConfig $config
  103. * @param IURLGenerator $urlGenerator
  104. * @param IManager $shareManager
  105. * @param ISearch $collaboratorSearch
  106. */
  107. public function __construct(
  108. $UserId,
  109. string $appName,
  110. IRequest $request,
  111. IConfig $config,
  112. IURLGenerator $urlGenerator,
  113. IManager $shareManager,
  114. ISearch $collaboratorSearch
  115. ) {
  116. parent::__construct($appName, $request);
  117. $this->userId = $UserId;
  118. $this->config = $config;
  119. $this->urlGenerator = $urlGenerator;
  120. $this->shareManager = $shareManager;
  121. $this->collaboratorSearch = $collaboratorSearch;
  122. }
  123. /**
  124. * @NoAdminRequired
  125. *
  126. * Search for sharees
  127. *
  128. * @param string $search Text to search for
  129. * @param string|null $itemType Limit to specific item types
  130. * @param int $page Page offset for searching
  131. * @param int $perPage Limit amount of search results per page
  132. * @param int|int[]|null $shareType Limit to specific share types
  133. * @param bool $lookup If a global lookup should be performed too
  134. * @return DataResponse<Http::STATUS_OK, FilesSharingShareesSearchResult, array{Link?: string}>
  135. * @throws OCSBadRequestException Invalid search parameters
  136. *
  137. * 200: Sharees search result returned
  138. */
  139. public function search(string $search = '', string $itemType = null, int $page = 1, int $perPage = 200, $shareType = null, bool $lookup = false): DataResponse {
  140. // only search for string larger than a given threshold
  141. $threshold = $this->config->getSystemValueInt('sharing.minSearchStringLength', 0);
  142. if (strlen($search) < $threshold) {
  143. return new DataResponse($this->result);
  144. }
  145. // never return more than the max. number of results configured in the config.php
  146. $maxResults = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
  147. if ($maxResults > 0) {
  148. $perPage = min($perPage, $maxResults);
  149. }
  150. if ($perPage <= 0) {
  151. throw new OCSBadRequestException('Invalid perPage argument');
  152. }
  153. if ($page <= 0) {
  154. throw new OCSBadRequestException('Invalid page');
  155. }
  156. $shareTypes = [
  157. IShare::TYPE_USER,
  158. ];
  159. if ($itemType === null) {
  160. throw new OCSBadRequestException('Missing itemType');
  161. } elseif ($itemType === 'file' || $itemType === 'folder') {
  162. if ($this->shareManager->allowGroupSharing()) {
  163. $shareTypes[] = IShare::TYPE_GROUP;
  164. }
  165. if ($this->isRemoteSharingAllowed($itemType)) {
  166. $shareTypes[] = IShare::TYPE_REMOTE;
  167. }
  168. if ($this->isRemoteGroupSharingAllowed($itemType)) {
  169. $shareTypes[] = IShare::TYPE_REMOTE_GROUP;
  170. }
  171. if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
  172. $shareTypes[] = IShare::TYPE_EMAIL;
  173. }
  174. if ($this->shareManager->shareProviderExists(IShare::TYPE_ROOM)) {
  175. $shareTypes[] = IShare::TYPE_ROOM;
  176. }
  177. if ($this->shareManager->shareProviderExists(IShare::TYPE_SCIENCEMESH)) {
  178. $shareTypes[] = IShare::TYPE_SCIENCEMESH;
  179. }
  180. } else {
  181. if ($this->shareManager->allowGroupSharing()) {
  182. $shareTypes[] = IShare::TYPE_GROUP;
  183. }
  184. $shareTypes[] = IShare::TYPE_EMAIL;
  185. }
  186. // FIXME: DI
  187. if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
  188. $shareTypes[] = IShare::TYPE_CIRCLE;
  189. }
  190. if ($this->shareManager->shareProviderExists(IShare::TYPE_SCIENCEMESH)) {
  191. $shareTypes[] = IShare::TYPE_SCIENCEMESH;
  192. }
  193. if ($shareType !== null && is_array($shareType)) {
  194. $shareTypes = array_intersect($shareTypes, $shareType);
  195. } elseif (is_numeric($shareType)) {
  196. $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
  197. }
  198. sort($shareTypes);
  199. $this->limit = $perPage;
  200. $this->offset = $perPage * ($page - 1);
  201. // In global scale mode we always search the loogup server
  202. if ($this->config->getSystemValueBool('gs.enabled', false)) {
  203. $lookup = true;
  204. $this->result['lookupEnabled'] = true;
  205. } else {
  206. $this->result['lookupEnabled'] = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'yes') === 'yes';
  207. }
  208. [$result, $hasMoreResults] = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset);
  209. // extra treatment for 'exact' subarray, with a single merge expected keys might be lost
  210. if (isset($result['exact'])) {
  211. $result['exact'] = array_merge($this->result['exact'], $result['exact']);
  212. }
  213. $this->result = array_merge($this->result, $result);
  214. $response = new DataResponse($this->result);
  215. if ($hasMoreResults) {
  216. $response->setHeaders(['Link' => $this->getPaginationLink($page, [
  217. 'search' => $search,
  218. 'itemType' => $itemType,
  219. 'shareType' => $shareTypes,
  220. 'perPage' => $perPage,
  221. ])]);
  222. }
  223. return $response;
  224. }
  225. /**
  226. * @param string $user
  227. * @param int $shareType
  228. *
  229. * @return Generator<array<string>>
  230. */
  231. private function getAllShareesByType(string $user, int $shareType): Generator {
  232. $offset = 0;
  233. $pageSize = 50;
  234. while (count($page = $this->shareManager->getSharesBy(
  235. $user,
  236. $shareType,
  237. null,
  238. false,
  239. $pageSize,
  240. $offset
  241. ))) {
  242. foreach ($page as $share) {
  243. yield [$share->getSharedWith(), $share->getSharedWithDisplayName() ?? $share->getSharedWith()];
  244. }
  245. $offset += $pageSize;
  246. }
  247. }
  248. private function sortShareesByFrequency(array $sharees): array {
  249. usort($sharees, function (array $s1, array $s2): int {
  250. return $s2['count'] - $s1['count'];
  251. });
  252. return $sharees;
  253. }
  254. private $searchResultTypeMap = [
  255. IShare::TYPE_USER => 'users',
  256. IShare::TYPE_GROUP => 'groups',
  257. IShare::TYPE_REMOTE => 'remotes',
  258. IShare::TYPE_REMOTE_GROUP => 'remote_groups',
  259. IShare::TYPE_EMAIL => 'emails',
  260. ];
  261. private function getAllSharees(string $user, array $shareTypes): ISearchResult {
  262. $result = [];
  263. foreach ($shareTypes as $shareType) {
  264. $sharees = $this->getAllShareesByType($user, $shareType);
  265. $shareTypeResults = [];
  266. foreach ($sharees as [$sharee, $displayname]) {
  267. if (!isset($this->searchResultTypeMap[$shareType])) {
  268. continue;
  269. }
  270. if (!isset($shareTypeResults[$sharee])) {
  271. $shareTypeResults[$sharee] = [
  272. 'count' => 1,
  273. 'label' => $displayname,
  274. 'value' => [
  275. 'shareType' => $shareType,
  276. 'shareWith' => $sharee,
  277. ],
  278. ];
  279. } else {
  280. $shareTypeResults[$sharee]['count']++;
  281. }
  282. }
  283. $result = array_merge($result, array_values($shareTypeResults));
  284. }
  285. $top5 = array_slice(
  286. $this->sortShareesByFrequency($result),
  287. 0,
  288. 5
  289. );
  290. $searchResult = new SearchResult();
  291. foreach ($this->searchResultTypeMap as $int => $str) {
  292. $searchResult->addResultSet(new SearchResultType($str), [], []);
  293. foreach ($top5 as $x) {
  294. if ($x['value']['shareType'] === $int) {
  295. $searchResult->addResultSet(new SearchResultType($str), [], [$x]);
  296. }
  297. }
  298. }
  299. return $searchResult;
  300. }
  301. /**
  302. * @NoAdminRequired
  303. *
  304. * Find recommended sharees
  305. *
  306. * @param string $itemType Limit to specific item types
  307. * @param int|int[]|null $shareType Limit to specific share types
  308. * @return DataResponse<Http::STATUS_OK, FilesSharingShareesRecommendedResult, array{}>
  309. *
  310. * 200: Recommended sharees returned
  311. */
  312. public function findRecommended(string $itemType, $shareType = null): DataResponse {
  313. $shareTypes = [
  314. IShare::TYPE_USER,
  315. ];
  316. if ($itemType === 'file' || $itemType === 'folder') {
  317. if ($this->shareManager->allowGroupSharing()) {
  318. $shareTypes[] = IShare::TYPE_GROUP;
  319. }
  320. if ($this->isRemoteSharingAllowed($itemType)) {
  321. $shareTypes[] = IShare::TYPE_REMOTE;
  322. }
  323. if ($this->isRemoteGroupSharingAllowed($itemType)) {
  324. $shareTypes[] = IShare::TYPE_REMOTE_GROUP;
  325. }
  326. if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
  327. $shareTypes[] = IShare::TYPE_EMAIL;
  328. }
  329. if ($this->shareManager->shareProviderExists(IShare::TYPE_ROOM)) {
  330. $shareTypes[] = IShare::TYPE_ROOM;
  331. }
  332. } else {
  333. $shareTypes[] = IShare::TYPE_GROUP;
  334. $shareTypes[] = IShare::TYPE_EMAIL;
  335. }
  336. // FIXME: DI
  337. if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
  338. $shareTypes[] = IShare::TYPE_CIRCLE;
  339. }
  340. if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
  341. $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
  342. sort($shareTypes);
  343. } elseif (is_numeric($shareType)) {
  344. $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
  345. sort($shareTypes);
  346. }
  347. return new DataResponse(
  348. $this->getAllSharees($this->userId, $shareTypes)->asArray()
  349. );
  350. }
  351. /**
  352. * Method to get out the static call for better testing
  353. *
  354. * @param string $itemType
  355. * @return bool
  356. */
  357. protected function isRemoteSharingAllowed(string $itemType): bool {
  358. try {
  359. // FIXME: static foo makes unit testing unnecessarily difficult
  360. $backend = \OC\Share\Share::getBackend($itemType);
  361. return $backend->isShareTypeAllowed(IShare::TYPE_REMOTE);
  362. } catch (\Exception $e) {
  363. return false;
  364. }
  365. }
  366. protected function isRemoteGroupSharingAllowed(string $itemType): bool {
  367. try {
  368. // FIXME: static foo makes unit testing unnecessarily difficult
  369. $backend = \OC\Share\Share::getBackend($itemType);
  370. return $backend->isShareTypeAllowed(IShare::TYPE_REMOTE_GROUP);
  371. } catch (\Exception $e) {
  372. return false;
  373. }
  374. }
  375. /**
  376. * Generates a bunch of pagination links for the current page
  377. *
  378. * @param int $page Current page
  379. * @param array $params Parameters for the URL
  380. * @return string
  381. */
  382. protected function getPaginationLink(int $page, array $params): string {
  383. if ($this->isV2()) {
  384. $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
  385. } else {
  386. $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
  387. }
  388. $params['page'] = $page + 1;
  389. return '<' . $url . http_build_query($params) . '>; rel="next"';
  390. }
  391. /**
  392. * @return bool
  393. */
  394. protected function isV2(): bool {
  395. return $this->request->getScriptName() === '/ocs/v2.php';
  396. }
  397. }