FilesReportPlugin.php 13 KB

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