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.

226 lines
8.0 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. * @author Tobias Kaminsky <tobias@kaminsky.me>
  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 OC\Files\Cache;
  27. use OCP\DB\QueryBuilder\IQueryBuilder;
  28. use OCP\Files\IMimeTypeLoader;
  29. use OCP\Files\Search\ISearchBinaryOperator;
  30. use OCP\Files\Search\ISearchComparison;
  31. use OCP\Files\Search\ISearchOperator;
  32. use OCP\Files\Search\ISearchOrder;
  33. /**
  34. * Tools for transforming search queries into database queries
  35. */
  36. class QuerySearchHelper {
  37. protected static $searchOperatorMap = [
  38. ISearchComparison::COMPARE_LIKE => 'iLike',
  39. ISearchComparison::COMPARE_EQUAL => 'eq',
  40. ISearchComparison::COMPARE_GREATER_THAN => 'gt',
  41. ISearchComparison::COMPARE_GREATER_THAN_EQUAL => 'gte',
  42. ISearchComparison::COMPARE_LESS_THAN => 'lt',
  43. ISearchComparison::COMPARE_LESS_THAN_EQUAL => 'lte'
  44. ];
  45. protected static $searchOperatorNegativeMap = [
  46. ISearchComparison::COMPARE_LIKE => 'notLike',
  47. ISearchComparison::COMPARE_EQUAL => 'neq',
  48. ISearchComparison::COMPARE_GREATER_THAN => 'lte',
  49. ISearchComparison::COMPARE_GREATER_THAN_EQUAL => 'lt',
  50. ISearchComparison::COMPARE_LESS_THAN => 'gte',
  51. ISearchComparison::COMPARE_LESS_THAN_EQUAL => 'lt'
  52. ];
  53. public const TAG_FAVORITE = '_$!<Favorite>!$_';
  54. /** @var IMimeTypeLoader */
  55. private $mimetypeLoader;
  56. /**
  57. * QuerySearchUtil constructor.
  58. *
  59. * @param IMimeTypeLoader $mimetypeLoader
  60. */
  61. public function __construct(IMimeTypeLoader $mimetypeLoader) {
  62. $this->mimetypeLoader = $mimetypeLoader;
  63. }
  64. /**
  65. * Whether or not the tag tables should be joined to complete the search
  66. *
  67. * @param ISearchOperator $operator
  68. * @return boolean
  69. */
  70. public function shouldJoinTags(ISearchOperator $operator) {
  71. if ($operator instanceof ISearchBinaryOperator) {
  72. return array_reduce($operator->getArguments(), function ($shouldJoin, ISearchOperator $operator) {
  73. return $shouldJoin || $this->shouldJoinTags($operator);
  74. }, false);
  75. } elseif ($operator instanceof ISearchComparison) {
  76. return $operator->getField() === 'tagname' || $operator->getField() === 'favorite';
  77. }
  78. return false;
  79. }
  80. /**
  81. * @param IQueryBuilder $builder
  82. * @param ISearchOperator $operator
  83. */
  84. public function searchOperatorArrayToDBExprArray(IQueryBuilder $builder, array $operators) {
  85. return array_filter(array_map(function ($operator) use ($builder) {
  86. return $this->searchOperatorToDBExpr($builder, $operator);
  87. }, $operators));
  88. }
  89. public function searchOperatorToDBExpr(IQueryBuilder $builder, ISearchOperator $operator) {
  90. $expr = $builder->expr();
  91. if ($operator instanceof ISearchBinaryOperator) {
  92. if (count($operator->getArguments()) === 0) {
  93. return null;
  94. }
  95. switch ($operator->getType()) {
  96. case ISearchBinaryOperator::OPERATOR_NOT:
  97. $negativeOperator = $operator->getArguments()[0];
  98. if ($negativeOperator instanceof ISearchComparison) {
  99. return $this->searchComparisonToDBExpr($builder, $negativeOperator, self::$searchOperatorNegativeMap);
  100. } else {
  101. throw new \InvalidArgumentException('Binary operators inside "not" is not supported');
  102. }
  103. // no break
  104. case ISearchBinaryOperator::OPERATOR_AND:
  105. return call_user_func_array([$expr, 'andX'], $this->searchOperatorArrayToDBExprArray($builder, $operator->getArguments()));
  106. case ISearchBinaryOperator::OPERATOR_OR:
  107. return call_user_func_array([$expr, 'orX'], $this->searchOperatorArrayToDBExprArray($builder, $operator->getArguments()));
  108. default:
  109. throw new \InvalidArgumentException('Invalid operator type: ' . $operator->getType());
  110. }
  111. } elseif ($operator instanceof ISearchComparison) {
  112. return $this->searchComparisonToDBExpr($builder, $operator, self::$searchOperatorMap);
  113. } else {
  114. throw new \InvalidArgumentException('Invalid operator type: ' . get_class($operator));
  115. }
  116. }
  117. private function searchComparisonToDBExpr(IQueryBuilder $builder, ISearchComparison $comparison, array $operatorMap) {
  118. $this->validateComparison($comparison);
  119. list($field, $value, $type) = $this->getOperatorFieldAndValue($comparison);
  120. if (isset($operatorMap[$type])) {
  121. $queryOperator = $operatorMap[$type];
  122. return $builder->expr()->$queryOperator($field, $this->getParameterForValue($builder, $value));
  123. } else {
  124. throw new \InvalidArgumentException('Invalid operator type: ' . $comparison->getType());
  125. }
  126. }
  127. private function getOperatorFieldAndValue(ISearchComparison $operator) {
  128. $field = $operator->getField();
  129. $value = $operator->getValue();
  130. $type = $operator->getType();
  131. if ($field === 'mimetype') {
  132. if ($operator->getType() === ISearchComparison::COMPARE_EQUAL) {
  133. $value = (int)$this->mimetypeLoader->getId($value);
  134. } elseif ($operator->getType() === ISearchComparison::COMPARE_LIKE) {
  135. // transform "mimetype='foo/%'" to "mimepart='foo'"
  136. if (preg_match('|(.+)/%|', $value, $matches)) {
  137. $field = 'mimepart';
  138. $value = (int)$this->mimetypeLoader->getId($matches[1]);
  139. $type = ISearchComparison::COMPARE_EQUAL;
  140. } elseif (strpos($value, '%') !== false) {
  141. throw new \InvalidArgumentException('Unsupported query value for mimetype: ' . $value . ', only values in the format "mime/type" or "mime/%" are supported');
  142. } else {
  143. $field = 'mimetype';
  144. $value = (int)$this->mimetypeLoader->getId($value);
  145. $type = ISearchComparison::COMPARE_EQUAL;
  146. }
  147. }
  148. } elseif ($field === 'favorite') {
  149. $field = 'tag.category';
  150. $value = self::TAG_FAVORITE;
  151. } elseif ($field === 'tagname') {
  152. $field = 'tag.category';
  153. } elseif ($field === 'fileid') {
  154. $field = 'file.fileid';
  155. }
  156. return [$field, $value, $type];
  157. }
  158. private function validateComparison(ISearchComparison $operator) {
  159. $types = [
  160. 'mimetype' => 'string',
  161. 'mtime' => 'integer',
  162. 'name' => 'string',
  163. 'size' => 'integer',
  164. 'tagname' => 'string',
  165. 'favorite' => 'boolean',
  166. 'fileid' => 'integer'
  167. ];
  168. $comparisons = [
  169. 'mimetype' => ['eq', 'like'],
  170. 'mtime' => ['eq', 'gt', 'lt', 'gte', 'lte'],
  171. 'name' => ['eq', 'like'],
  172. 'size' => ['eq', 'gt', 'lt', 'gte', 'lte'],
  173. 'tagname' => ['eq', 'like'],
  174. 'favorite' => ['eq'],
  175. 'fileid' => ['eq']
  176. ];
  177. if (!isset($types[$operator->getField()])) {
  178. throw new \InvalidArgumentException('Unsupported comparison field ' . $operator->getField());
  179. }
  180. $type = $types[$operator->getField()];
  181. if (gettype($operator->getValue()) !== $type) {
  182. throw new \InvalidArgumentException('Invalid type for field ' . $operator->getField());
  183. }
  184. if (!in_array($operator->getType(), $comparisons[$operator->getField()])) {
  185. throw new \InvalidArgumentException('Unsupported comparison for field ' . $operator->getField() . ': ' . $operator->getType());
  186. }
  187. }
  188. private function getParameterForValue(IQueryBuilder $builder, $value) {
  189. if ($value instanceof \DateTime) {
  190. $value = $value->getTimestamp();
  191. }
  192. if (is_numeric($value)) {
  193. $type = IQueryBuilder::PARAM_INT;
  194. } else {
  195. $type = IQueryBuilder::PARAM_STR;
  196. }
  197. return $builder->createNamedParameter($value, $type);
  198. }
  199. /**
  200. * @param IQueryBuilder $query
  201. * @param ISearchOrder[] $orders
  202. */
  203. public function addSearchOrdersToQuery(IQueryBuilder $query, array $orders) {
  204. foreach ($orders as $order) {
  205. $query->addOrderBy($order->getField(), $order->getDirection());
  206. }
  207. }
  208. }