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.

FileSearchBackend.php 14KB

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