ShareesAPIController.php 12 KB

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