ShareesAPIController.php 12 KB

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