ShareesAPIController.php 13 KB

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