aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Files/Cache/SearchBuilder.php
blob: 41f942cab039f7bcdb3f86b85b38820535df4fa7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
/**
 * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC\Files\Cache;

use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Files\IMimeTypeLoader;
use OCP\Files\Search\ISearchBinaryOperator;
use OCP\Files\Search\ISearchComparison;
use OCP\Files\Search\ISearchOperator;
use OCP\Files\Search\ISearchOrder;
use OCP\FilesMetadata\IMetadataQuery;

/**
 * Tools for transforming search queries into database queries
 *
 * @psalm-import-type ParamSingleValue from ISearchComparison
 * @psalm-import-type ParamValue from ISearchComparison
 */
class SearchBuilder {
	/** @var array<string, string> */
	protected static $searchOperatorMap = [
		ISearchComparison::COMPARE_LIKE => 'iLike',
		ISearchComparison::COMPARE_LIKE_CASE_SENSITIVE => 'like',
		ISearchComparison::COMPARE_EQUAL => 'eq',
		ISearchComparison::COMPARE_GREATER_THAN => 'gt',
		ISearchComparison::COMPARE_GREATER_THAN_EQUAL => 'gte',
		ISearchComparison::COMPARE_LESS_THAN => 'lt',
		ISearchComparison::COMPARE_LESS_THAN_EQUAL => 'lte',
		ISearchComparison::COMPARE_DEFINED => 'isNotNull',
		ISearchComparison::COMPARE_IN => 'in',
	];

	/** @var array<string, string> */
	protected static $searchOperatorNegativeMap = [
		ISearchComparison::COMPARE_LIKE => 'notLike',
		ISearchComparison::COMPARE_LIKE_CASE_SENSITIVE => 'notLike',
		ISearchComparison::COMPARE_EQUAL => 'neq',
		ISearchComparison::COMPARE_GREATER_THAN => 'lte',
		ISearchComparison::COMPARE_GREATER_THAN_EQUAL => 'lt',
		ISearchComparison::COMPARE_LESS_THAN => 'gte',
		ISearchComparison::COMPARE_LESS_THAN_EQUAL => 'gt',
		ISearchComparison::COMPARE_DEFINED => 'isNull',
		ISearchComparison::COMPARE_IN => 'notIn',
	];

	/** @var array<string, string> */
	protected static $fieldTypes = [
		'mimetype' => 'string',
		'mtime' => 'integer',
		'name' => 'string',
		'path' => 'string',
		'size' => 'integer',
		'tagname' => 'string',
		'systemtag' => 'string',
		'favorite' => 'boolean',
		'fileid' => 'integer',
		'storage' => 'integer',
		'share_with' => 'string',
		'share_type' => 'integer',
		'owner' => 'string',
	];

	/** @var array<string, int|string> */
	protected static $paramTypeMap = [
		'string' => IQueryBuilder::PARAM_STR,
		'integer' => IQueryBuilder::PARAM_INT,
		'boolean' => IQueryBuilder::PARAM_BOOL,
	];

	/** @var array<string, int> */
	protected static $paramArrayTypeMap = [
		'string' => IQueryBuilder::PARAM_STR_ARRAY,
		'integer' => IQueryBuilder::PARAM_INT_ARRAY,
		'boolean' => IQueryBuilder::PARAM_INT_ARRAY,
	];

	public const TAG_FAVORITE = '_$!<Favorite>!$_';

	/** @var IMimeTypeLoader */
	private $mimetypeLoader;

	public function __construct(
		IMimeTypeLoader $mimetypeLoader
	) {
		$this->mimetypeLoader = $mimetypeLoader;
	}

	/**
	 * @return string[]
	 */
	public function extractRequestedFields(ISearchOperator $operator): array {
		if ($operator instanceof ISearchBinaryOperator) {
			return array_reduce($operator->getArguments(), function (array $fields, ISearchOperator $operator) {
				return array_unique(array_merge($fields, $this->extractRequestedFields($operator)));
			}, []);
		} elseif ($operator instanceof ISearchComparison && !$operator->getExtra()) {
			return [$operator->getField()];
		}
		return [];
	}

	/**
	 * @param IQueryBuilder $builder
	 * @param ISearchOperator[] $operators
	 */
	public function searchOperatorArrayToDBExprArray(
		IQueryBuilder $builder,
		array $operators,
		?IMetadataQuery $metadataQuery = null
	) {
		return array_filter(array_map(function ($operator) use ($builder, $metadataQuery) {
			return $this->searchOperatorToDBExpr($builder, $operator, $metadataQuery);
		}, $operators));
	}

	public function searchOperatorToDBExpr(
		IQueryBuilder $builder,
		ISearchOperator $operator,
		?IMetadataQuery $metadataQuery = null
	) {
		$expr = $builder->expr();

		if ($operator instanceof ISearchBinaryOperator) {
			if (count($operator->getArguments()) === 0) {
				return null;
			}

			switch ($operator->getType()) {
				case ISearchBinaryOperator::OPERATOR_NOT:
					$negativeOperator = $operator->getArguments()[0];
					if ($negativeOperator instanceof ISearchComparison) {
						return $this->searchComparisonToDBExpr($builder, $negativeOperator, self::$searchOperatorNegativeMap, $metadataQuery);
					} else {
						throw new \InvalidArgumentException('Binary operators inside "not" is not supported');
					}
					// no break
				case ISearchBinaryOperator::OPERATOR_AND:
					return call_user_func_array([$expr, 'andX'], $this->searchOperatorArrayToDBExprArray($builder, $operator->getArguments(), $metadataQuery));
				case ISearchBinaryOperator::OPERATOR_OR:
					return call_user_func_array([$expr, 'orX'], $this->searchOperatorArrayToDBExprArray($builder, $operator->getArguments(), $metadataQuery));
				default:
					throw new \InvalidArgumentException('Invalid operator type: ' . $operator->getType());
			}
		} elseif ($operator instanceof ISearchComparison) {
			return $this->searchComparisonToDBExpr($builder, $operator, self::$searchOperatorMap, $metadataQuery);
		} else {
			throw new \InvalidArgumentException('Invalid operator type: ' . get_class($operator));
		}
	}

	private function searchComparisonToDBExpr(
		IQueryBuilder $builder,
		ISearchComparison $comparison,
		array $operatorMap,
		?IMetadataQuery $metadataQuery = null
	) {
		if ($comparison->getExtra()) {
			[$field, $value, $type, $paramType] = $this->getExtraOperatorField($comparison, $metadataQuery);
		} else {
			[$field, $value, $type, $paramType] = $this->getOperatorFieldAndValue($comparison);
		}

		if (isset($operatorMap[$type])) {
			$queryOperator = $operatorMap[$type];
			return $builder->expr()->$queryOperator($field, $this->getParameterForValue($builder, $value, $paramType));
		} else {
			throw new \InvalidArgumentException('Invalid operator type: ' . $comparison->getType());
		}
	}

	/**
	 * @param ISearchComparison $operator
	 * @return list{string, ParamValue, string, string}
	 */
	private function getOperatorFieldAndValue(ISearchComparison $operator): array {
		$this->validateComparison($operator);
		$field = $operator->getField();
		$value = $operator->getValue();
		$type = $operator->getType();
		$pathEqHash = $operator->getQueryHint(ISearchComparison::HINT_PATH_EQ_HASH, true);
		return $this->getOperatorFieldAndValueInner($field, $value, $type, $pathEqHash);
	}

	/**
	 * @param string $field
	 * @param ParamValue $value
	 * @param string $type
	 * @return list{string, ParamValue, string, string}
	 */
	private function getOperatorFieldAndValueInner(string $field, mixed $value, string $type, bool $pathEqHash): array {
		$paramType = self::$fieldTypes[$field];
		if ($type === ISearchComparison::COMPARE_IN) {
			$resultField = $field;
			$values = [];
			foreach ($value as $arrayValue) {
				/** @var ParamSingleValue $arrayValue */
				[$arrayField, $arrayValue] = $this->getOperatorFieldAndValueInner($field, $arrayValue, ISearchComparison::COMPARE_EQUAL, $pathEqHash);
				$resultField = $arrayField;
				$values[] = $arrayValue;
			}
			return [$resultField, $values, ISearchComparison::COMPARE_IN, $paramType];
		}
		if ($field === 'mimetype') {
			$value = (string)$value;
			if ($type === ISearchComparison::COMPARE_EQUAL) {
				$value = $this->mimetypeLoader->getId($value);
			} elseif ($type === ISearchComparison::COMPARE_LIKE) {
				// transform "mimetype='foo/%'" to "mimepart='foo'"
				if (preg_match('|(.+)/%|', $value, $matches)) {
					$field = 'mimepart';
					$value = $this->mimetypeLoader->getId($matches[1]);
					$type = ISearchComparison::COMPARE_EQUAL;
				} elseif (str_contains($value, '%')) {
					throw new \InvalidArgumentException('Unsupported query value for mimetype: ' . $value . ', only values in the format "mime/type" or "mime/%" are supported');
				} else {
					$field = 'mimetype';
					$value = $this->mimetypeLoader->getId($value);
					$type = ISearchComparison::COMPARE_EQUAL;
				}
			}
		} elseif ($field === 'favorite') {
			$field = 'tag.category';
			$value = self::TAG_FAVORITE;
			$paramType = 'string';
		} elseif ($field === 'name') {
			$field = 'file.name';
		} elseif ($field === 'tagname') {
			$field = 'tag.category';
		} elseif ($field === 'systemtag') {
			$field = 'systemtag.name';
		} elseif ($field === 'fileid') {
			$field = 'file.fileid';
		} elseif ($field === 'path' && $type === ISearchComparison::COMPARE_EQUAL && $pathEqHash) {
			$field = 'path_hash';
			$value = md5((string)$value);
		} elseif ($field === 'owner') {
			$field = 'uid_owner';
		}
		return [$field, $value, $type, $paramType];
	}

	private function validateComparison(ISearchComparison $operator) {
		$comparisons = [
			'mimetype' => ['eq', 'like', 'in'],
			'mtime' => ['eq', 'gt', 'lt', 'gte', 'lte'],
			'name' => ['eq', 'like', 'clike', 'in'],
			'path' => ['eq', 'like', 'clike', 'in'],
			'size' => ['eq', 'gt', 'lt', 'gte', 'lte'],
			'tagname' => ['eq', 'like'],
			'systemtag' => ['eq', 'like'],
			'favorite' => ['eq'],
			'fileid' => ['eq', 'in'],
			'storage' => ['eq', 'in'],
			'share_with' => ['eq'],
			'share_type' => ['eq'],
			'owner' => ['eq'],
		];

		if (!isset(self::$fieldTypes[$operator->getField()])) {
			throw new \InvalidArgumentException('Unsupported comparison field ' . $operator->getField());
		}
		$type = self::$fieldTypes[$operator->getField()];
		if ($operator->getType() === ISearchComparison::COMPARE_IN) {
			if (!is_array($operator->getValue())) {
				throw new \InvalidArgumentException('Invalid type for field ' . $operator->getField());
			}
			foreach ($operator->getValue() as $arrayValue) {
				if (gettype($arrayValue) !== $type) {
					throw new \InvalidArgumentException('Invalid type in array for field ' . $operator->getField());
				}
			}
		} else {
			if (gettype($operator->getValue()) !== $type) {
				throw new \InvalidArgumentException('Invalid type for field ' . $operator->getField());
			}
		}
		if (!in_array($operator->getType(), $comparisons[$operator->getField()])) {
			throw new \InvalidArgumentException('Unsupported comparison for field  ' . $operator->getField() . ': ' . $operator->getType());
		}
	}


	private function getExtraOperatorField(ISearchComparison $operator, IMetadataQuery $metadataQuery): array {
		$paramType = self::$fieldTypes[$operator->getField()];
		$field = $operator->getField();
		$value = $operator->getValue();
		$type = $operator->getType();

		switch ($operator->getExtra()) {
			case IMetadataQuery::EXTRA:
				$metadataQuery->joinIndex($field); // join index table if not joined yet
				$field = $metadataQuery->getMetadataValueField($field);
				break;
			default:
				throw new \InvalidArgumentException('Invalid extra type: ' . $operator->getExtra());
		}

		return [$field, $value, $type, $paramType];
	}

	private function getParameterForValue(IQueryBuilder $builder, $value, string $paramType) {
		if ($value instanceof \DateTime) {
			$value = $value->getTimestamp();
		}
		if (is_array($value)) {
			$type = self::$paramArrayTypeMap[$paramType];
		} else {
			$type = self::$paramTypeMap[$paramType];
		}
		return $builder->createNamedParameter($value, $type);
	}

	/**
	 * @param IQueryBuilder $query
	 * @param ISearchOrder[] $orders
	 * @param IMetadataQuery|null $metadataQuery
	 */
	public function addSearchOrdersToQuery(IQueryBuilder $query, array $orders, ?IMetadataQuery $metadataQuery = null): void {
		foreach ($orders as $order) {
			$field = $order->getField();
			switch ($order->getExtra()) {
				case IMetadataQuery::EXTRA:
					$metadataQuery->joinIndex($field); // join index table if not joined yet
					$field = $metadataQuery->getMetadataValueField($order->getField());
					break;

				default:
					if ($field === 'fileid') {
						$field = 'file.fileid';
					}

					// Mysql really likes to pick an index for sorting if it can't fully satisfy the where
					// filter with an index, since search queries pretty much never are fully filtered by index
					// mysql often picks an index for sorting instead of the much more useful index for filtering.
					//
					// By changing the order by to an expression, mysql isn't smart enough to see that it could still
					// use the index, so it instead picks an index for the filtering
					if ($field === 'mtime') {
						$field = $query->func()->add($field, $query->createNamedParameter(0));
					}
			}
			$query->addOrderBy($field, $order->getDirection());
		}
	}
}