ShareesAPIController.php 12 KB

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