FilesReportPlugin.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\DAV\Connector\Sabre;
  8. use OC\Files\View;
  9. use OCA\Circles\Api\v1\Circles;
  10. use OCP\App\IAppManager;
  11. use OCP\Files\Folder;
  12. use OCP\Files\Node as INode;
  13. use OCP\IGroupManager;
  14. use OCP\ITagManager;
  15. use OCP\IUserSession;
  16. use OCP\SystemTag\ISystemTagManager;
  17. use OCP\SystemTag\ISystemTagObjectMapper;
  18. use OCP\SystemTag\TagNotFoundException;
  19. use Sabre\DAV\Exception\BadRequest;
  20. use Sabre\DAV\Exception\PreconditionFailed;
  21. use Sabre\DAV\PropFind;
  22. use Sabre\DAV\ServerPlugin;
  23. use Sabre\DAV\Tree;
  24. use Sabre\DAV\Xml\Element\Response;
  25. use Sabre\DAV\Xml\Response\MultiStatus;
  26. class FilesReportPlugin extends ServerPlugin {
  27. // namespace
  28. public const NS_OWNCLOUD = 'http://owncloud.org/ns';
  29. public const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
  30. public const REPORT_NAME = '{http://owncloud.org/ns}filter-files';
  31. public const SYSTEMTAG_PROPERTYNAME = '{http://owncloud.org/ns}systemtag';
  32. public const CIRCLE_PROPERTYNAME = '{http://owncloud.org/ns}circle';
  33. /**
  34. * Reference to main server object
  35. *
  36. * @var \Sabre\DAV\Server
  37. */
  38. private $server;
  39. /**
  40. * @param Tree $tree
  41. * @param View $fileView
  42. * @param ISystemTagManager $tagManager
  43. * @param ISystemTagObjectMapper $tagMapper
  44. * @param ITagManager $fileTagger manager for private tags
  45. * @param IUserSession $userSession
  46. * @param IGroupManager $groupManager
  47. * @param Folder $userFolder
  48. * @param IAppManager $appManager
  49. */
  50. public function __construct(
  51. private Tree $tree,
  52. private View $fileView,
  53. private ISystemTagManager $tagManager,
  54. private ISystemTagObjectMapper $tagMapper,
  55. /**
  56. * Manager for private tags
  57. */
  58. private ITagManager $fileTagger,
  59. private IUserSession $userSession,
  60. private IGroupManager $groupManager,
  61. private Folder $userFolder,
  62. private IAppManager $appManager,
  63. ) {
  64. }
  65. /**
  66. * This initializes the plugin.
  67. *
  68. * This function is called by \Sabre\DAV\Server, after
  69. * addPlugin is called.
  70. *
  71. * This method should set up the required event subscriptions.
  72. *
  73. * @param \Sabre\DAV\Server $server
  74. * @return void
  75. */
  76. public function initialize(\Sabre\DAV\Server $server) {
  77. $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
  78. $this->server = $server;
  79. $this->server->on('report', [$this, 'onReport']);
  80. }
  81. /**
  82. * Returns a list of reports this plugin supports.
  83. *
  84. * This will be used in the {DAV:}supported-report-set property.
  85. *
  86. * @param string $uri
  87. * @return array
  88. */
  89. public function getSupportedReportSet($uri) {
  90. return [self::REPORT_NAME];
  91. }
  92. /**
  93. * REPORT operations to look for files
  94. *
  95. * @param string $reportName
  96. * @param $report
  97. * @param string $uri
  98. * @return bool
  99. * @throws BadRequest
  100. * @throws PreconditionFailed
  101. * @internal param $ [] $report
  102. */
  103. public function onReport($reportName, $report, $uri) {
  104. $reportTargetNode = $this->server->tree->getNodeForPath($uri);
  105. if (!$reportTargetNode instanceof Directory || $reportName !== self::REPORT_NAME) {
  106. return;
  107. }
  108. $ns = '{' . $this::NS_OWNCLOUD . '}';
  109. $ncns = '{' . $this::NS_NEXTCLOUD . '}';
  110. $requestedProps = [];
  111. $filterRules = [];
  112. // parse report properties and gather filter info
  113. foreach ($report as $reportProps) {
  114. $name = $reportProps['name'];
  115. if ($name === $ns . 'filter-rules') {
  116. $filterRules = $reportProps['value'];
  117. } elseif ($name === '{DAV:}prop') {
  118. // propfind properties
  119. foreach ($reportProps['value'] as $propVal) {
  120. $requestedProps[] = $propVal['name'];
  121. }
  122. } elseif ($name === '{DAV:}limit') {
  123. foreach ($reportProps['value'] as $propVal) {
  124. if ($propVal['name'] === '{DAV:}nresults') {
  125. $limit = (int)$propVal['value'];
  126. } elseif ($propVal['name'] === $ncns . 'firstresult') {
  127. $offset = (int)$propVal['value'];
  128. }
  129. }
  130. }
  131. }
  132. if (empty($filterRules)) {
  133. // an empty filter would return all existing files which would be slow
  134. throw new BadRequest('Missing filter-rule block in request');
  135. }
  136. // gather all file ids matching filter
  137. try {
  138. $resultFileIds = $this->processFilterRulesForFileIDs($filterRules);
  139. // no logic in circles and favorites for paging, we always have all results, and slice later on
  140. $resultFileIds = array_slice($resultFileIds, $offset ?? 0, $limit ?? null);
  141. // fetching nodes has paging on DB level – therefore we cannot mix and slice the results, similar
  142. // to user backends. I.e. the final result may return more results than requested.
  143. $resultNodes = $this->processFilterRulesForFileNodes($filterRules, $limit ?? null, $offset ?? null);
  144. } catch (TagNotFoundException $e) {
  145. throw new PreconditionFailed('Cannot filter by non-existing tag', 0, $e);
  146. }
  147. $results = [];
  148. foreach ($resultNodes as $entry) {
  149. if ($entry) {
  150. $results[] = $this->wrapNode($entry);
  151. }
  152. }
  153. // find sabre nodes by file id, restricted to the root node path
  154. $additionalNodes = $this->findNodesByFileIds($reportTargetNode, $resultFileIds);
  155. if ($additionalNodes && $results) {
  156. $results = array_uintersect($results, $additionalNodes, function (Node $a, Node $b): int {
  157. return $a->getId() - $b->getId();
  158. });
  159. } elseif (!$results && $additionalNodes) {
  160. $results = $additionalNodes;
  161. }
  162. $filesUri = $this->getFilesBaseUri($uri, $reportTargetNode->getPath());
  163. $responses = $this->prepareResponses($filesUri, $requestedProps, $results);
  164. $xml = $this->server->xml->write(
  165. '{DAV:}multistatus',
  166. new MultiStatus($responses)
  167. );
  168. $this->server->httpResponse->setStatus(207);
  169. $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8');
  170. $this->server->httpResponse->setBody($xml);
  171. return false;
  172. }
  173. /**
  174. * Returns the base uri of the files root by removing
  175. * the subpath from the URI
  176. *
  177. * @param string $uri URI from this request
  178. * @param string $subPath subpath to remove from the URI
  179. *
  180. * @return string files base uri
  181. */
  182. private function getFilesBaseUri(string $uri, string $subPath): string {
  183. $uri = trim($uri, '/');
  184. $subPath = trim($subPath, '/');
  185. if (empty($subPath)) {
  186. $filesUri = $uri;
  187. } else {
  188. $filesUri = substr($uri, 0, strlen($uri) - strlen($subPath));
  189. }
  190. $filesUri = trim($filesUri, '/');
  191. if (empty($filesUri)) {
  192. return '';
  193. }
  194. return '/' . $filesUri;
  195. }
  196. /**
  197. * Find file ids matching the given filter rules
  198. *
  199. * @param array $filterRules
  200. * @return array array of unique file id results
  201. */
  202. protected function processFilterRulesForFileIDs(array $filterRules): array {
  203. $ns = '{' . $this::NS_OWNCLOUD . '}';
  204. $resultFileIds = [];
  205. $circlesIds = [];
  206. $favoriteFilter = null;
  207. foreach ($filterRules as $filterRule) {
  208. if ($filterRule['name'] === self::CIRCLE_PROPERTYNAME) {
  209. $circlesIds[] = $filterRule['value'];
  210. }
  211. if ($filterRule['name'] === $ns . 'favorite') {
  212. $favoriteFilter = true;
  213. }
  214. }
  215. if ($favoriteFilter !== null) {
  216. $resultFileIds = $this->fileTagger->load('files')->getFavorites();
  217. if (empty($resultFileIds)) {
  218. return [];
  219. }
  220. }
  221. if (!empty($circlesIds)) {
  222. $fileIds = $this->getCirclesFileIds($circlesIds);
  223. if (empty($resultFileIds)) {
  224. $resultFileIds = $fileIds;
  225. } else {
  226. $resultFileIds = array_intersect($fileIds, $resultFileIds);
  227. }
  228. }
  229. return $resultFileIds;
  230. }
  231. protected function processFilterRulesForFileNodes(array $filterRules, ?int $limit, ?int $offset): array {
  232. $systemTagIds = [];
  233. foreach ($filterRules as $filterRule) {
  234. if ($filterRule['name'] === self::SYSTEMTAG_PROPERTYNAME) {
  235. $systemTagIds[] = $filterRule['value'];
  236. }
  237. }
  238. $nodes = [];
  239. if (!empty($systemTagIds)) {
  240. $tags = $this->tagManager->getTagsByIds($systemTagIds, $this->userSession->getUser());
  241. // For we run DB queries per tag and require intersection, we cannot apply limit and offset for DB queries on multi tag search.
  242. $oneTagSearch = count($tags) === 1;
  243. $dbLimit = $oneTagSearch ? $limit ?? 0 : 0;
  244. $dbOffset = $oneTagSearch ? $offset ?? 0 : 0;
  245. foreach ($tags as $tag) {
  246. $tagName = $tag->getName();
  247. $tmpNodes = $this->userFolder->searchBySystemTag($tagName, $this->userSession->getUser()->getUID(), $dbLimit, $dbOffset);
  248. if (count($nodes) === 0) {
  249. $nodes = $tmpNodes;
  250. } else {
  251. $nodes = array_uintersect($nodes, $tmpNodes, function (INode $a, INode $b): int {
  252. return $a->getId() - $b->getId();
  253. });
  254. }
  255. if ($nodes === []) {
  256. // there cannot be a common match when nodes are empty early.
  257. return $nodes;
  258. }
  259. }
  260. if (!$oneTagSearch && ($limit !== null || $offset !== null)) {
  261. $nodes = array_slice($nodes, $offset, $limit);
  262. }
  263. }
  264. return $nodes;
  265. }
  266. /**
  267. * @suppress PhanUndeclaredClassMethod
  268. * @param array $circlesIds
  269. * @return array
  270. */
  271. private function getCirclesFileIds(array $circlesIds) {
  272. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  273. return [];
  274. }
  275. return Circles::getFilesForCircles($circlesIds);
  276. }
  277. /**
  278. * Prepare propfind response for the given nodes
  279. *
  280. * @param string $filesUri $filesUri URI leading to root of the files URI,
  281. * with a leading slash but no trailing slash
  282. * @param string[] $requestedProps requested properties
  283. * @param Node[] nodes nodes for which to fetch and prepare responses
  284. * @return Response[]
  285. */
  286. public function prepareResponses($filesUri, $requestedProps, $nodes) {
  287. $responses = [];
  288. foreach ($nodes as $node) {
  289. $propFind = new PropFind($filesUri . $node->getPath(), $requestedProps);
  290. $this->server->getPropertiesByNode($propFind, $node);
  291. // copied from Sabre Server's getPropertiesForPath
  292. $result = $propFind->getResultForMultiStatus();
  293. $result['href'] = $propFind->getPath();
  294. $resourceType = $this->server->getResourceTypeForNode($node);
  295. if (in_array('{DAV:}collection', $resourceType) || in_array('{DAV:}principal', $resourceType)) {
  296. $result['href'] .= '/';
  297. }
  298. $responses[] = new Response(
  299. rtrim($this->server->getBaseUri(), '/') . $filesUri . $node->getPath(),
  300. $result,
  301. );
  302. }
  303. return $responses;
  304. }
  305. /**
  306. * Find Sabre nodes by file ids
  307. *
  308. * @param Node $rootNode root node for search
  309. * @param array $fileIds file ids
  310. * @return Node[] array of Sabre nodes
  311. */
  312. public function findNodesByFileIds(Node $rootNode, array $fileIds): array {
  313. if (empty($fileIds)) {
  314. return [];
  315. }
  316. $folder = $this->userFolder;
  317. if (trim($rootNode->getPath(), '/') !== '') {
  318. /** @var Folder $folder */
  319. $folder = $folder->get($rootNode->getPath());
  320. }
  321. $results = [];
  322. foreach ($fileIds as $fileId) {
  323. $entry = $folder->getFirstNodeById((int)$fileId);
  324. if ($entry) {
  325. $results[] = $this->wrapNode($entry);
  326. }
  327. }
  328. return $results;
  329. }
  330. protected function wrapNode(INode $node): File|Directory {
  331. if ($node instanceof \OCP\Files\File) {
  332. return new File($this->fileView, $node);
  333. } else {
  334. return new Directory($this->fileView, $node);
  335. }
  336. }
  337. /**
  338. * Returns whether the currently logged in user is an administrator
  339. */
  340. private function isAdmin() {
  341. $user = $this->userSession->getUser();
  342. if ($user !== null) {
  343. return $this->groupManager->isAdmin($user->getUID());
  344. }
  345. return false;
  346. }
  347. }