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.

426 lines
12 KiB

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