FileSearchBackend.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Christian <16852529+cviereck@users.noreply.github.com>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OCA\DAV\Files;
  26. use OC\Files\Search\SearchBinaryOperator;
  27. use OC\Files\Search\SearchComparison;
  28. use OC\Files\Search\SearchOrder;
  29. use OC\Files\Search\SearchQuery;
  30. use OC\Files\View;
  31. use OCA\DAV\Connector\Sabre\CachingTree;
  32. use OCA\DAV\Connector\Sabre\Directory;
  33. use OCA\DAV\Connector\Sabre\FilesPlugin;
  34. use OCA\DAV\Connector\Sabre\TagsPlugin;
  35. use OCP\Files\Cache\ICacheEntry;
  36. use OCP\Files\Folder;
  37. use OCP\Files\IRootFolder;
  38. use OCP\Files\Node;
  39. use OCP\Files\Search\ISearchOperator;
  40. use OCP\Files\Search\ISearchOrder;
  41. use OCP\Files\Search\ISearchQuery;
  42. use OCP\IUser;
  43. use OCP\Share\IManager;
  44. use Sabre\DAV\Exception\NotFound;
  45. use SearchDAV\Backend\ISearchBackend;
  46. use SearchDAV\Backend\SearchPropertyDefinition;
  47. use SearchDAV\Backend\SearchResult;
  48. use SearchDAV\Query\Literal;
  49. use SearchDAV\Query\Operator;
  50. use SearchDAV\Query\Order;
  51. use SearchDAV\Query\Query;
  52. class FileSearchBackend implements ISearchBackend {
  53. /** @var CachingTree */
  54. private $tree;
  55. /** @var IUser */
  56. private $user;
  57. /** @var IRootFolder */
  58. private $rootFolder;
  59. /** @var IManager */
  60. private $shareManager;
  61. /** @var View */
  62. private $view;
  63. /**
  64. * FileSearchBackend constructor.
  65. *
  66. * @param CachingTree $tree
  67. * @param IUser $user
  68. * @param IRootFolder $rootFolder
  69. * @param IManager $shareManager
  70. * @param View $view
  71. * @internal param IRootFolder $rootFolder
  72. */
  73. public function __construct(CachingTree $tree, IUser $user, IRootFolder $rootFolder, IManager $shareManager, View $view) {
  74. $this->tree = $tree;
  75. $this->user = $user;
  76. $this->rootFolder = $rootFolder;
  77. $this->shareManager = $shareManager;
  78. $this->view = $view;
  79. }
  80. /**
  81. * Search endpoint will be remote.php/dav
  82. *
  83. * @return string
  84. */
  85. public function getArbiterPath() {
  86. return '';
  87. }
  88. public function isValidScope($href, $depth, $path) {
  89. // only allow scopes inside the dav server
  90. if (is_null($path)) {
  91. return false;
  92. }
  93. try {
  94. $node = $this->tree->getNodeForPath($path);
  95. return $node instanceof Directory;
  96. } catch (NotFound $e) {
  97. return false;
  98. }
  99. }
  100. public function getPropertyDefinitionsForScope($href, $path) {
  101. // all valid scopes support the same schema
  102. //todo dynamically load all propfind properties that are supported
  103. return [
  104. // queryable properties
  105. new SearchPropertyDefinition('{DAV:}displayname', true, true, true),
  106. new SearchPropertyDefinition('{DAV:}getcontenttype', true, true, true),
  107. new SearchPropertyDefinition('{DAV:}getlastmodified', true, true, true, SearchPropertyDefinition::DATATYPE_DATETIME),
  108. new SearchPropertyDefinition(FilesPlugin::SIZE_PROPERTYNAME, true, true, true, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
  109. new SearchPropertyDefinition(TagsPlugin::FAVORITE_PROPERTYNAME, true, true, true, SearchPropertyDefinition::DATATYPE_BOOLEAN),
  110. new SearchPropertyDefinition(FilesPlugin::INTERNAL_FILEID_PROPERTYNAME, true, true, false, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
  111. new SearchPropertyDefinition(FilesPlugin::OWNER_ID_PROPERTYNAME, true, true, false),
  112. // select only properties
  113. new SearchPropertyDefinition('{DAV:}resourcetype', false, true, false),
  114. new SearchPropertyDefinition('{DAV:}getcontentlength', false, true, false),
  115. new SearchPropertyDefinition(FilesPlugin::CHECKSUMS_PROPERTYNAME, false, true, false),
  116. new SearchPropertyDefinition(FilesPlugin::PERMISSIONS_PROPERTYNAME, false, true, false),
  117. new SearchPropertyDefinition(FilesPlugin::GETETAG_PROPERTYNAME, false, true, false),
  118. new SearchPropertyDefinition(FilesPlugin::OWNER_DISPLAY_NAME_PROPERTYNAME, false, true, false),
  119. new SearchPropertyDefinition(FilesPlugin::DATA_FINGERPRINT_PROPERTYNAME, false, true, false),
  120. new SearchPropertyDefinition(FilesPlugin::HAS_PREVIEW_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_BOOLEAN),
  121. new SearchPropertyDefinition(FilesPlugin::FILEID_PROPERTYNAME, false, true, false, SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER),
  122. ];
  123. }
  124. /**
  125. * @param Query $search
  126. * @return SearchResult[]
  127. */
  128. public function search(Query $search) {
  129. if (count($search->from) !== 1) {
  130. throw new \InvalidArgumentException('Searching more than one folder is not supported');
  131. }
  132. $query = $this->transformQuery($search);
  133. $scope = $search->from[0];
  134. if ($scope->path === null) {
  135. throw new \InvalidArgumentException('Using uri\'s as scope is not supported, please use a path relative to the search arbiter instead');
  136. }
  137. $node = $this->tree->getNodeForPath($scope->path);
  138. if (!$node instanceof Directory) {
  139. throw new \InvalidArgumentException('Search is only supported on directories');
  140. }
  141. $fileInfo = $node->getFileInfo();
  142. $folder = $this->rootFolder->get($fileInfo->getPath());
  143. /** @var Folder $folder $results */
  144. $results = $folder->search($query);
  145. /** @var SearchResult[] $nodes */
  146. $nodes = array_map(function (Node $node) {
  147. if ($node instanceof Folder) {
  148. $davNode = new \OCA\DAV\Connector\Sabre\Directory($this->view, $node, $this->tree, $this->shareManager);
  149. } else {
  150. $davNode = new \OCA\DAV\Connector\Sabre\File($this->view, $node, $this->shareManager);
  151. }
  152. $path = $this->getHrefForNode($node);
  153. $this->tree->cacheNode($davNode, $path);
  154. return new SearchResult($davNode, $path);
  155. }, $results);
  156. if (!$query->limitToHome()) {
  157. // Sort again, since the result from multiple storages is appended and not sorted
  158. usort($nodes, function (SearchResult $a, SearchResult $b) use ($search) {
  159. return $this->sort($a, $b, $search->orderBy);
  160. });
  161. }
  162. // If a limit is provided use only return that number of files
  163. if ($search->limit->maxResults !== 0) {
  164. $nodes = \array_slice($nodes, 0, $search->limit->maxResults);
  165. }
  166. return $nodes;
  167. }
  168. private function sort(SearchResult $a, SearchResult $b, array $orders) {
  169. /** @var Order $order */
  170. foreach ($orders as $order) {
  171. $v1 = $this->getSearchResultProperty($a, $order->property);
  172. $v2 = $this->getSearchResultProperty($b, $order->property);
  173. if ($v1 === null && $v2 === null) {
  174. continue;
  175. }
  176. if ($v1 === null) {
  177. return $order->order === Order::ASC ? 1 : -1;
  178. }
  179. if ($v2 === null) {
  180. return $order->order === Order::ASC ? -1 : 1;
  181. }
  182. $s = $this->compareProperties($v1, $v2, $order);
  183. if ($s === 0) {
  184. continue;
  185. }
  186. if ($order->order === Order::DESC) {
  187. $s = -$s;
  188. }
  189. return $s;
  190. }
  191. return 0;
  192. }
  193. private function compareProperties($a, $b, Order $order) {
  194. switch ($order->property->dataType) {
  195. case SearchPropertyDefinition::DATATYPE_STRING:
  196. return strcmp($a, $b);
  197. case SearchPropertyDefinition::DATATYPE_BOOLEAN:
  198. if ($a === $b) {
  199. return 0;
  200. }
  201. if ($a === false) {
  202. return -1;
  203. }
  204. return 1;
  205. default:
  206. if ($a === $b) {
  207. return 0;
  208. }
  209. if ($a < $b) {
  210. return -1;
  211. }
  212. return 1;
  213. }
  214. }
  215. private function getSearchResultProperty(SearchResult $result, SearchPropertyDefinition $property) {
  216. /** @var \OCA\DAV\Connector\Sabre\Node $node */
  217. $node = $result->node;
  218. switch ($property->name) {
  219. case '{DAV:}displayname':
  220. return $node->getName();
  221. case '{DAV:}getlastmodified':
  222. return $node->getLastModified();
  223. case FilesPlugin::SIZE_PROPERTYNAME:
  224. return $node->getSize();
  225. case FilesPlugin::INTERNAL_FILEID_PROPERTYNAME:
  226. return $node->getInternalFileId();
  227. default:
  228. return null;
  229. }
  230. }
  231. /**
  232. * @param Node $node
  233. * @return string
  234. */
  235. private function getHrefForNode(Node $node) {
  236. $base = '/files/' . $this->user->getUID();
  237. return $base . $this->view->getRelativePath($node->getPath());
  238. }
  239. /**
  240. * @param Query $query
  241. * @return ISearchQuery
  242. */
  243. private function transformQuery(Query $query): ISearchQuery {
  244. // TODO offset
  245. $limit = $query->limit;
  246. $orders = array_map([$this, 'mapSearchOrder'], $query->orderBy);
  247. $offset = 0;
  248. $limitHome = false;
  249. $ownerProp = $this->extractWhereValue($query->where, FilesPlugin::OWNER_ID_PROPERTYNAME, Operator::OPERATION_EQUAL);
  250. if ($ownerProp !== null) {
  251. if ($ownerProp === $this->user->getUID()) {
  252. $limitHome = true;
  253. } else {
  254. throw new \InvalidArgumentException("Invalid search value for '{http://owncloud.org/ns}owner-id', only the current user id is allowed");
  255. }
  256. $offset = $limit->firstResult;
  257. }
  258. return new SearchQuery(
  259. $this->transformSearchOperation($query->where),
  260. (int)$limit->maxResults,
  261. $offset,
  262. $orders,
  263. $this->user,
  264. $limitHome
  265. );
  266. }
  267. /**
  268. * @param Order $order
  269. * @return ISearchOrder
  270. */
  271. private function mapSearchOrder(Order $order) {
  272. return new SearchOrder($order->order === Order::ASC ? ISearchOrder::DIRECTION_ASCENDING : ISearchOrder::DIRECTION_DESCENDING, $this->mapPropertyNameToColumn($order->property));
  273. }
  274. /**
  275. * @param Operator $operator
  276. * @return ISearchOperator
  277. */
  278. private function transformSearchOperation(Operator $operator) {
  279. list(, $trimmedType) = explode('}', $operator->type);
  280. switch ($operator->type) {
  281. case Operator::OPERATION_AND:
  282. case Operator::OPERATION_OR:
  283. case Operator::OPERATION_NOT:
  284. $arguments = array_map([$this, 'transformSearchOperation'], $operator->arguments);
  285. return new SearchBinaryOperator($trimmedType, $arguments);
  286. case Operator::OPERATION_EQUAL:
  287. case Operator::OPERATION_GREATER_OR_EQUAL_THAN:
  288. case Operator::OPERATION_GREATER_THAN:
  289. case Operator::OPERATION_LESS_OR_EQUAL_THAN:
  290. case Operator::OPERATION_LESS_THAN:
  291. case Operator::OPERATION_IS_LIKE:
  292. if (count($operator->arguments) !== 2) {
  293. throw new \InvalidArgumentException('Invalid number of arguments for ' . $trimmedType . ' operation');
  294. }
  295. if (!($operator->arguments[0] instanceof SearchPropertyDefinition)) {
  296. throw new \InvalidArgumentException('Invalid argument 1 for ' . $trimmedType . ' operation, expected property');
  297. }
  298. if (!($operator->arguments[1] instanceof Literal)) {
  299. throw new \InvalidArgumentException('Invalid argument 2 for ' . $trimmedType . ' operation, expected literal');
  300. }
  301. return new SearchComparison($trimmedType, $this->mapPropertyNameToColumn($operator->arguments[0]), $this->castValue($operator->arguments[0], $operator->arguments[1]->value));
  302. case Operator::OPERATION_IS_COLLECTION:
  303. return new SearchComparison('eq', 'mimetype', ICacheEntry::DIRECTORY_MIMETYPE);
  304. default:
  305. throw new \InvalidArgumentException('Unsupported operation ' . $trimmedType . ' (' . $operator->type . ')');
  306. }
  307. }
  308. /**
  309. * @param SearchPropertyDefinition $property
  310. * @return string
  311. */
  312. private function mapPropertyNameToColumn(SearchPropertyDefinition $property) {
  313. switch ($property->name) {
  314. case '{DAV:}displayname':
  315. return 'name';
  316. case '{DAV:}getcontenttype':
  317. return 'mimetype';
  318. case '{DAV:}getlastmodified':
  319. return 'mtime';
  320. case FilesPlugin::SIZE_PROPERTYNAME:
  321. return 'size';
  322. case TagsPlugin::FAVORITE_PROPERTYNAME:
  323. return 'favorite';
  324. case TagsPlugin::TAGS_PROPERTYNAME:
  325. return 'tagname';
  326. case FilesPlugin::INTERNAL_FILEID_PROPERTYNAME:
  327. return 'fileid';
  328. default:
  329. throw new \InvalidArgumentException('Unsupported property for search or order: ' . $property->name);
  330. }
  331. }
  332. private function castValue(SearchPropertyDefinition $property, $value) {
  333. switch ($property->dataType) {
  334. case SearchPropertyDefinition::DATATYPE_BOOLEAN:
  335. return $value === 'yes';
  336. case SearchPropertyDefinition::DATATYPE_DECIMAL:
  337. case SearchPropertyDefinition::DATATYPE_INTEGER:
  338. case SearchPropertyDefinition::DATATYPE_NONNEGATIVE_INTEGER:
  339. return 0 + $value;
  340. case SearchPropertyDefinition::DATATYPE_DATETIME:
  341. if (is_numeric($value)) {
  342. return max(0, 0 + $value);
  343. }
  344. $date = \DateTime::createFromFormat(\DateTime::ATOM, $value);
  345. return ($date instanceof \DateTime && $date->getTimestamp() !== false) ? $date->getTimestamp() : 0;
  346. default:
  347. return $value;
  348. }
  349. }
  350. /**
  351. * Get a specific property from the were clause
  352. */
  353. private function extractWhereValue(Operator &$operator, string $propertyName, string $comparison, bool $acceptableLocation = true): ?string {
  354. switch ($operator->type) {
  355. case Operator::OPERATION_AND:
  356. case Operator::OPERATION_OR:
  357. case Operator::OPERATION_NOT:
  358. foreach ($operator->arguments as &$argument) {
  359. $value = $this->extractWhereValue($argument, $propertyName, $comparison, $acceptableLocation && $operator->type === Operator::OPERATION_AND);
  360. if ($value !== null) {
  361. return $value;
  362. }
  363. }
  364. return null;
  365. case Operator::OPERATION_EQUAL:
  366. case Operator::OPERATION_GREATER_OR_EQUAL_THAN:
  367. case Operator::OPERATION_GREATER_THAN:
  368. case Operator::OPERATION_LESS_OR_EQUAL_THAN:
  369. case Operator::OPERATION_LESS_THAN:
  370. case Operator::OPERATION_IS_LIKE:
  371. if ($operator->arguments[0]->name === $propertyName) {
  372. if ($operator->type === $comparison) {
  373. if ($acceptableLocation) {
  374. if ($operator->arguments[1] instanceof Literal) {
  375. $value = $operator->arguments[1]->value;
  376. // to remove the comparison from the query, we replace it with an empty AND
  377. $operator = new Operator(Operator::OPERATION_AND);
  378. return $value;
  379. } else {
  380. throw new \InvalidArgumentException("searching by '$propertyName' is only allowed with a literal value");
  381. }
  382. } else{
  383. throw new \InvalidArgumentException("searching by '$propertyName' is not allowed inside a '{DAV:}or' or '{DAV:}not'");
  384. }
  385. } else {
  386. throw new \InvalidArgumentException("searching by '$propertyName' is only allowed inside a '$comparison'");
  387. }
  388. } else {
  389. return null;
  390. }
  391. default:
  392. return null;
  393. }
  394. }
  395. }