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 12KB

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