[TASK] Update php-cs-fixer to 2.5.0
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Generic / Storage / Typo3DbQueryParser.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Persistence\Generic\Storage;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Database\Connection;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\Database\Query\Expression\CompositeExpression;
21 use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
22 use TYPO3\CMS\Core\Database\Query\QueryBuilder;
23 use TYPO3\CMS\Core\Utility\GeneralUtility;
24 use TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException;
25 use TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException;
26 use TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException;
27 use TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException;
28 use TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException;
29 use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap;
30 use TYPO3\CMS\Extbase\Persistence\Generic\Qom;
31 use TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface;
32 use TYPO3\CMS\Extbase\Persistence\QueryInterface;
33 use TYPO3\CMS\Frontend\Page\PageRepository;
34
35 /**
36 * QueryParser, converting the qom to string representation
37 */
38 class Typo3DbQueryParser
39 {
40 /**
41 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
42 */
43 protected $dataMapper;
44
45 /**
46 * The TYPO3 page repository. Used for language and workspace overlay
47 *
48 * @var PageRepository
49 */
50 protected $pageRepository;
51
52 /**
53 * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
54 */
55 protected $environmentService;
56
57 /**
58 * Instance of the Doctrine query builder
59 *
60 * @var QueryBuilder
61 */
62 protected $queryBuilder;
63
64 /**
65 * Maps domain model properties to their corresponding table aliases that are used in the query, e.g.:
66 *
67 * 'property1' => 'tableName',
68 * 'property1.property2' => 'tableName1',
69 *
70 * @var array
71 */
72 protected $tablePropertyMap = [];
73
74 /**
75 * Maps tablenames to their aliases to be used in where clauses etc.
76 * Mainly used for joins on the same table etc.
77 *
78 * @var array
79 */
80 protected $tableAliasMap = [];
81
82 /**
83 * Stores all tables used in for SQL joins
84 *
85 * @var array
86 */
87 protected $unionTableAliasCache = [];
88
89 /**
90 * @var string
91 */
92 protected $tableName = '';
93
94 /**
95 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper
96 */
97 public function injectDataMapper(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper)
98 {
99 $this->dataMapper = $dataMapper;
100 }
101
102 /**
103 * @param \TYPO3\CMS\Extbase\Service\EnvironmentService $environmentService
104 */
105 public function injectEnvironmentService(\TYPO3\CMS\Extbase\Service\EnvironmentService $environmentService)
106 {
107 $this->environmentService = $environmentService;
108 }
109
110 /**
111 * Returns a ready to be executed QueryBuilder object, based on the query
112 *
113 * @param QueryInterface $query
114 * @return QueryBuilder
115 */
116 public function convertQueryToDoctrineQueryBuilder(QueryInterface $query)
117 {
118 // Reset all properties
119 $this->tablePropertyMap = [];
120 $this->tableAliasMap = [];
121 $this->unionTableAliasCache = [];
122 $this->tableName = '';
123 // Find the right table name
124 $source = $query->getSource();
125 $this->initializeQueryBuilder($source);
126
127 $constraint = $query->getConstraint();
128 if ($constraint instanceof Qom\ConstraintInterface) {
129 $wherePredicates = $this->parseConstraint($constraint, $source);
130 if (!empty($wherePredicates)) {
131 $this->queryBuilder->andWhere($wherePredicates);
132 }
133 }
134
135 $this->parseOrderings($query->getOrderings(), $source);
136 $this->addTypo3Constraints($query);
137
138 return $this->queryBuilder;
139 }
140
141 /**
142 * Creates the queryBuilder object whether it is a regular select or a JOIN
143 *
144 * @param Qom\SourceInterface $source The source
145 */
146 protected function initializeQueryBuilder(Qom\SourceInterface $source)
147 {
148 if ($source instanceof Qom\SelectorInterface) {
149 $className = $source->getNodeTypeName();
150 $tableName = $this->dataMapper->getDataMap($className)->getTableName();
151 $this->tableName = $tableName;
152
153 $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
154 ->getQueryBuilderForTable($tableName);
155
156 $this->queryBuilder
157 ->getRestrictions()
158 ->removeAll();
159
160 $tableAlias = $this->getUniqueAlias($tableName);
161
162 $this->queryBuilder
163 ->select($tableAlias . '.*')
164 ->from($tableName, $tableAlias);
165
166 $this->addRecordTypeConstraint($className);
167 } elseif ($source instanceof Qom\JoinInterface) {
168 $leftSource = $source->getLeft();
169 $leftTableName = $leftSource->getSelectorName();
170
171 $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
172 ->getQueryBuilderForTable($leftTableName);
173 $leftTableAlias = $this->getUniqueAlias($leftTableName);
174 $this->queryBuilder
175 ->select($leftTableAlias . '.*')
176 ->from($leftTableName, $leftTableAlias);
177 $this->parseJoin($source, $leftTableAlias);
178 }
179 }
180
181 /**
182 * Transforms a constraint into SQL and parameter arrays
183 *
184 * @param Qom\ConstraintInterface $constraint The constraint
185 * @param Qom\SourceInterface $source The source
186 * @return CompositeExpression|string
187 * @throws \RuntimeException
188 */
189 protected function parseConstraint(Qom\ConstraintInterface $constraint, Qom\SourceInterface $source)
190 {
191 if ($constraint instanceof Qom\AndInterface) {
192 $constraint1 = $constraint->getConstraint1();
193 $constraint2 = $constraint->getConstraint2();
194 if (($constraint1 instanceof Qom\ConstraintInterface)
195 && ($constraint2 instanceof Qom\ConstraintInterface)
196 ) {
197 return $this->queryBuilder->expr()->andX(
198 $this->parseConstraint($constraint1, $source),
199 $this->parseConstraint($constraint2, $source)
200 );
201 }
202 return '';
203 }
204 if ($constraint instanceof Qom\OrInterface) {
205 $constraint1 = $constraint->getConstraint1();
206 $constraint2 = $constraint->getConstraint2();
207 if (($constraint1 instanceof Qom\ConstraintInterface)
208 && ($constraint2 instanceof Qom\ConstraintInterface)
209 ) {
210 return $this->queryBuilder->expr()->orX(
211 $this->parseConstraint($constraint->getConstraint1(), $source),
212 $this->parseConstraint($constraint->getConstraint2(), $source)
213 );
214 }
215 return '';
216 }
217 if ($constraint instanceof Qom\NotInterface) {
218 return ' NOT(' . $this->parseConstraint($constraint->getConstraint(), $source) . ')';
219 }
220 if ($constraint instanceof Qom\ComparisonInterface) {
221 return $this->parseComparison($constraint, $source);
222 }
223 throw new \RuntimeException('not implemented', 1476199898);
224 }
225
226 /**
227 * Transforms orderings into SQL.
228 *
229 * @param array $orderings An array of orderings (Qom\Ordering)
230 * @param Qom\SourceInterface $source The source
231 * @throws UnsupportedOrderException
232 */
233 protected function parseOrderings(array $orderings, Qom\SourceInterface $source)
234 {
235 foreach ($orderings as $propertyName => $order) {
236 if ($order !== QueryInterface::ORDER_ASCENDING && $order !== QueryInterface::ORDER_DESCENDING) {
237 throw new UnsupportedOrderException('Unsupported order encountered.', 1242816074);
238 }
239 $className = null;
240 $tableName = '';
241 if ($source instanceof Qom\SelectorInterface) {
242 $className = $source->getNodeTypeName();
243 $tableName = $this->dataMapper->convertClassNameToTableName($className);
244 $fullPropertyPath = '';
245 while (strpos($propertyName, '.') !== false) {
246 $this->addUnionStatement($className, $tableName, $propertyName, $fullPropertyPath);
247 }
248 } elseif ($source instanceof Qom\JoinInterface) {
249 $tableName = $source->getLeft()->getSelectorName();
250 }
251 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
252 if ($tableName !== '') {
253 $this->queryBuilder->addOrderBy($tableName . '.' . $columnName, $order);
254 } else {
255 $this->queryBuilder->addOrderBy($columnName, $order);
256 }
257 }
258 }
259
260 /**
261 * add TYPO3 Constraints for all tables to the queryBuilder
262 *
263 * @param QueryInterface $query
264 */
265 protected function addTypo3Constraints(QueryInterface $query)
266 {
267 foreach ($this->tableAliasMap as $tableAlias => $tableName) {
268 $additionalWhereClauses = $this->getAdditionalWhereClause($query->getQuerySettings(), $tableName, $tableAlias);
269 $statement = $this->getVisibilityConstraintStatement($query->getQuerySettings(), $tableName, $tableAlias);
270 if ($statement !== '') {
271 $additionalWhereClauses[] = $statement;
272 }
273 if (!empty($additionalWhereClauses)) {
274 if (in_array($tableAlias, $this->unionTableAliasCache, true)) {
275 $this->queryBuilder->andWhere(
276 $this->queryBuilder->expr()->orX(
277 $this->queryBuilder->expr()->andX(...$additionalWhereClauses),
278 $this->queryBuilder->expr()->isNull($tableAlias . '.uid')
279 )
280 );
281 } else {
282 $this->queryBuilder->andWhere(...$additionalWhereClauses);
283 }
284 }
285 }
286 }
287
288 /**
289 * Parse a Comparison into SQL and parameter arrays.
290 *
291 * @param Qom\ComparisonInterface $comparison The comparison to parse
292 * @param Qom\SourceInterface $source The source
293 * @return string
294 * @throws \RuntimeException
295 * @throws RepositoryException
296 * @throws Exception\BadConstraintException
297 */
298 protected function parseComparison(Qom\ComparisonInterface $comparison, Qom\SourceInterface $source)
299 {
300 if ($comparison->getOperator() === QueryInterface::OPERATOR_CONTAINS) {
301 if ($comparison->getOperand2() === null) {
302 throw new Exception\BadConstraintException('The value for the CONTAINS operator must not be null.', 1484828468);
303 }
304 $value = $this->dataMapper->getPlainValue($comparison->getOperand2());
305 if (!$source instanceof Qom\SelectorInterface) {
306 throw new \RuntimeException('Source is not of type "SelectorInterface"', 1395362539);
307 }
308 $className = $source->getNodeTypeName();
309 $tableName = $this->dataMapper->convertClassNameToTableName($className);
310 $operand1 = $comparison->getOperand1();
311 $propertyName = $operand1->getPropertyName();
312 $fullPropertyPath = '';
313 while (strpos($propertyName, '.') !== false) {
314 $this->addUnionStatement($className, $tableName, $propertyName, $fullPropertyPath);
315 }
316 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
317 $dataMap = $this->dataMapper->getDataMap($className);
318 $columnMap = $dataMap->getColumnMap($propertyName);
319 $typeOfRelation = $columnMap instanceof ColumnMap ? $columnMap->getTypeOfRelation() : null;
320 if ($typeOfRelation === ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
321 $relationTableName = $columnMap->getRelationTableName();
322 $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
323 $queryBuilderForSubselect
324 ->select($columnMap->getParentKeyFieldName())
325 ->from($relationTableName)
326 ->where(
327 $queryBuilderForSubselect->expr()->eq(
328 $columnMap->getChildKeyFieldName(),
329 $this->queryBuilder->createNamedParameter($value)
330 )
331 );
332 $additionalWhereForMatchFields = $this->getAdditionalMatchFieldsStatement($queryBuilderForSubselect->expr(), $columnMap, $relationTableName, $relationTableName);
333 if ($additionalWhereForMatchFields) {
334 $queryBuilderForSubselect->andWhere($additionalWhereForMatchFields);
335 }
336
337 return $this->queryBuilder->expr()->comparison(
338 $this->queryBuilder->quoteIdentifier($tableName . '.uid'),
339 'IN',
340 '(' . $queryBuilderForSubselect->getSQL() . ')'
341 );
342 }
343 if ($typeOfRelation === ColumnMap::RELATION_HAS_MANY) {
344 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
345 if (isset($parentKeyFieldName)) {
346 $childTableName = $columnMap->getChildTableName();
347
348 // Build the SQL statement of the subselect
349 $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
350 $queryBuilderForSubselect
351 ->select($parentKeyFieldName)
352 ->from($childTableName)
353 ->where(
354 $queryBuilderForSubselect->expr()->eq(
355 'uid',
356 (int)$value
357 )
358 );
359
360 // Add it to the main query
361 return $this->queryBuilder->expr()->eq(
362 $tableName . '.uid',
363 '(' . $queryBuilderForSubselect->getSQL() . ')'
364 );
365 }
366 return $this->queryBuilder->expr()->inSet(
367 $tableName . '.' . $columnName,
368 $this->queryBuilder->quote($value)
369 );
370 }
371 throw new RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
372 }
373 return $this->parseDynamicOperand($comparison, $source);
374 }
375
376 /**
377 * Parse a DynamicOperand into SQL and parameter arrays.
378 *
379 * @param Qom\ComparisonInterface $comparison
380 * @param Qom\SourceInterface $source The source
381 * @return string
382 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
383 * @throws Exception\BadConstraintException
384 */
385 protected function parseDynamicOperand(Qom\ComparisonInterface $comparison, Qom\SourceInterface $source)
386 {
387 $value = $comparison->getOperand2();
388 $fieldName = $this->parseOperand($comparison->getOperand1(), $source);
389 $expr = null;
390 $exprBuilder = $this->queryBuilder->expr();
391 switch ($comparison->getOperator()) {
392 case QueryInterface::OPERATOR_IN:
393 $hasValue = false;
394 $plainValues = [];
395 foreach ($value as $singleValue) {
396 $plainValue = $this->dataMapper->getPlainValue($singleValue);
397 if ($plainValue !== null) {
398 $hasValue = true;
399 $plainValues[] = $this->createTypedNamedParameter($singleValue);
400 }
401 }
402 if (!$hasValue) {
403 throw new Exception\BadConstraintException(
404 'The IN operator needs a non-empty value list to compare against. ' .
405 'The given value list is empty.',
406 1484828466
407 );
408 }
409 $expr = $exprBuilder->comparison($fieldName, 'IN', '(' . implode(', ', $plainValues) . ')');
410 break;
411 case QueryInterface::OPERATOR_EQUAL_TO:
412 if ($value === null) {
413 $expr = $fieldName . ' IS NULL';
414 } else {
415 $placeHolder = $this->createTypedNamedParameter($value);
416 $expr = $exprBuilder->comparison($fieldName, $exprBuilder::EQ, $placeHolder);
417 }
418 break;
419 case QueryInterface::OPERATOR_EQUAL_TO_NULL:
420 $expr = $fieldName . ' IS NULL';
421 break;
422 case QueryInterface::OPERATOR_NOT_EQUAL_TO:
423 if ($value === null) {
424 $expr = $fieldName . ' IS NOT NULL';
425 } else {
426 $placeHolder = $this->createTypedNamedParameter($value);
427 $expr = $exprBuilder->comparison($fieldName, $exprBuilder::NEQ, $placeHolder);
428 }
429 break;
430 case QueryInterface::OPERATOR_NOT_EQUAL_TO_NULL:
431 $expr = $fieldName . ' IS NOT NULL';
432 break;
433 case QueryInterface::OPERATOR_LESS_THAN:
434 $placeHolder = $this->createTypedNamedParameter($value);
435 $expr = $exprBuilder->comparison($fieldName, $exprBuilder::LT, $placeHolder);
436 break;
437 case QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
438 $placeHolder = $this->createTypedNamedParameter($value);
439 $expr = $exprBuilder->comparison($fieldName, $exprBuilder::LTE, $placeHolder);
440 break;
441 case QueryInterface::OPERATOR_GREATER_THAN:
442 $placeHolder = $this->createTypedNamedParameter($value);
443 $expr = $exprBuilder->comparison($fieldName, $exprBuilder::GT, $placeHolder);
444 break;
445 case QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
446 $placeHolder = $this->createTypedNamedParameter($value);
447 $expr = $exprBuilder->comparison($fieldName, $exprBuilder::GTE, $placeHolder);
448 break;
449 case QueryInterface::OPERATOR_LIKE:
450 $placeHolder = $this->createTypedNamedParameter($value, \PDO::PARAM_STR);
451 $expr = $exprBuilder->comparison($fieldName, 'LIKE', $placeHolder);
452 break;
453 default:
454 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception(
455 'Unsupported operator encountered.',
456 1242816073
457 );
458 }
459 return $expr;
460 }
461
462 /**
463 * Maps plain value of operand to PDO types to help Doctrine and/or the database driver process the value
464 * correctly when building the query.
465 *
466 * @param mixed $value The parameter value
467 * @return int
468 * @throws \InvalidArgumentException
469 */
470 protected function getParameterType($value): int
471 {
472 $parameterType = gettype($value);
473 switch ($parameterType) {
474 case 'integer':
475 return \PDO::PARAM_INT;
476 case 'string':
477 return \PDO::PARAM_STR;
478 default:
479 throw new \InvalidArgumentException(
480 'Unsupported parameter type encountered. Expected integer or string, ' . $parameterType . ' given.',
481 1494878863
482 );
483 }
484 }
485
486 /**
487 * Create a named parameter for the QueryBuilder and guess the parameter type based on the
488 * output of DataMapper::getPlainValue(). The type of the named parameter can be forced to
489 * one of the \PDO::PARAM_* types by specifying the $forceType argument.
490 *
491 * @param mixed $value The input value that should be sent to the database
492 * @param int|null $forceType The \PDO::PARAM_* type that should be forced
493 * @return string The placeholder string to be used in the query
494 * @see \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::getPlainValue()
495 */
496 protected function createTypedNamedParameter($value, int $forceType = null): string
497 {
498 $plainValue = $this->dataMapper->getPlainValue($value);
499 $parameterType = $forceType ?? $this->getParameterType($plainValue);
500 $placeholder = $this->queryBuilder->createNamedParameter($plainValue, $parameterType);
501
502 return $placeholder;
503 }
504
505 /**
506 * @param Qom\DynamicOperandInterface $operand
507 * @param Qom\SourceInterface $source The source
508 * @return string
509 * @throws \InvalidArgumentException
510 */
511 protected function parseOperand(Qom\DynamicOperandInterface $operand, Qom\SourceInterface $source)
512 {
513 if ($operand instanceof Qom\LowerCaseInterface) {
514 $constraintSQL = 'LOWER(' . $this->parseOperand($operand->getOperand(), $source) . ')';
515 } elseif ($operand instanceof Qom\UpperCaseInterface) {
516 $constraintSQL = 'UPPER(' . $this->parseOperand($operand->getOperand(), $source) . ')';
517 } elseif ($operand instanceof Qom\PropertyValueInterface) {
518 $propertyName = $operand->getPropertyName();
519 $className = '';
520 if ($source instanceof Qom\SelectorInterface) {
521 $className = $source->getNodeTypeName();
522 $tableName = $this->dataMapper->convertClassNameToTableName($className);
523 $fullPropertyPath = '';
524 while (strpos($propertyName, '.') !== false) {
525 $this->addUnionStatement($className, $tableName, $propertyName, $fullPropertyPath);
526 }
527 } elseif ($source instanceof Qom\JoinInterface) {
528 $tableName = $source->getJoinCondition()->getSelector1Name();
529 }
530 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
531 $constraintSQL = (!empty($tableName) ? $tableName . '.' : '') . $columnName;
532 $constraintSQL = $this->queryBuilder->getConnection()->quoteIdentifier($constraintSQL);
533 } else {
534 throw new \InvalidArgumentException('Given operand has invalid type "' . get_class($operand) . '".', 1395710211);
535 }
536 return $constraintSQL;
537 }
538
539 /**
540 * Add a constraint to ensure that the record type of the returned tuples is matching the data type of the repository.
541 *
542 * @param string $className The class name
543 */
544 protected function addRecordTypeConstraint($className)
545 {
546 if ($className !== null) {
547 $dataMap = $this->dataMapper->getDataMap($className);
548 if ($dataMap->getRecordTypeColumnName() !== null) {
549 $recordTypes = [];
550 if ($dataMap->getRecordType() !== null) {
551 $recordTypes[] = $dataMap->getRecordType();
552 }
553 foreach ($dataMap->getSubclasses() as $subclassName) {
554 $subclassDataMap = $this->dataMapper->getDataMap($subclassName);
555 if ($subclassDataMap->getRecordType() !== null) {
556 $recordTypes[] = $subclassDataMap->getRecordType();
557 }
558 }
559 if (!empty($recordTypes)) {
560 $recordTypeStatements = [];
561 foreach ($recordTypes as $recordType) {
562 $tableName = $dataMap->getTableName();
563 $recordTypeStatements[] = $this->queryBuilder->expr()->eq(
564 $tableName . '.' . $dataMap->getRecordTypeColumnName(),
565 $this->queryBuilder->createNamedParameter($recordType)
566 );
567 }
568 $this->queryBuilder->andWhere(
569 $this->queryBuilder->expr()->orX(...$recordTypeStatements)
570 );
571 }
572 }
573 }
574 }
575
576 /**
577 * Builds a condition for filtering records by the configured match field,
578 * e.g. MM_match_fields, foreign_match_fields or foreign_table_field.
579 *
580 * @param ExpressionBuilder $exprBuilder
581 * @param ColumnMap $columnMap The column man for which the condition should be build.
582 * @param string $childTableAlias The alias of the child record table used in the query.
583 * @param string $parentTable The real name of the parent table (used for building the foreign_table_field condition).
584 * @return string The match field conditions or an empty string.
585 */
586 protected function getAdditionalMatchFieldsStatement($exprBuilder, $columnMap, $childTableAlias, $parentTable = null)
587 {
588 $additionalWhereForMatchFields = [];
589 $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
590 if (is_array($relationTableMatchFields) && !empty($relationTableMatchFields)) {
591 foreach ($relationTableMatchFields as $fieldName => $value) {
592 $additionalWhereForMatchFields[] = $exprBuilder->eq($childTableAlias . '.' . $fieldName, $this->queryBuilder->createNamedParameter($value));
593 }
594 }
595
596 if (isset($parentTable)) {
597 $parentTableFieldName = $columnMap->getParentTableFieldName();
598 if (!empty($parentTableFieldName)) {
599 $additionalWhereForMatchFields[] = $exprBuilder->eq($childTableAlias . '.' . $parentTableFieldName, $this->queryBuilder->createNamedParameter($parentTable));
600 }
601 }
602
603 if (!empty($additionalWhereForMatchFields)) {
604 return $exprBuilder->andX(...$additionalWhereForMatchFields);
605 }
606 return '';
607 }
608
609 /**
610 * Adds additional WHERE statements according to the query settings.
611 *
612 * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
613 * @param string $tableName The table name to add the additional where clause for
614 * @param string $tableAlias The table alias used in the query.
615 * @return array
616 */
617 protected function getAdditionalWhereClause(QuerySettingsInterface $querySettings, $tableName, $tableAlias = null)
618 {
619 $whereClause = [];
620 if ($querySettings->getRespectSysLanguage()) {
621 $systemLanguageStatement = $this->getSysLanguageStatement($tableName, $tableAlias, $querySettings);
622 if (!empty($systemLanguageStatement)) {
623 $whereClause[] = $systemLanguageStatement;
624 }
625 }
626
627 if ($querySettings->getRespectStoragePage()) {
628 $pageIdStatement = $this->getPageIdStatement($tableName, $tableAlias, $querySettings->getStoragePageIds());
629 if (!empty($pageIdStatement)) {
630 $whereClause[] = $pageIdStatement;
631 }
632 }
633
634 return $whereClause;
635 }
636
637 /**
638 * Adds enableFields and deletedClause to the query if necessary
639 *
640 * @param QuerySettingsInterface $querySettings
641 * @param string $tableName The database table name
642 * @param string $tableAlias
643 * @return string
644 */
645 protected function getVisibilityConstraintStatement(QuerySettingsInterface $querySettings, $tableName, $tableAlias)
646 {
647 $statement = '';
648 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
649 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
650 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
651 $includeDeleted = $querySettings->getIncludeDeleted();
652 if ($this->environmentService->isEnvironmentInFrontendMode()) {
653 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
654 } else {
655 // TYPO3_MODE === 'BE'
656 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
657 }
658 if (!empty($statement)) {
659 $statement = $this->replaceTableNameWithAlias($statement, $tableName, $tableAlias);
660 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
661 }
662 }
663 return $statement;
664 }
665
666 /**
667 * Returns constraint statement for frontend context
668 *
669 * @param string $tableName
670 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
671 * @param array $enableFieldsToBeIgnored If $ignoreEnableFields is true, this array specifies enable fields to be ignored. If it is NULL or an empty array (default) all enable fields are ignored.
672 * @param bool $includeDeleted A flag indicating whether deleted records should be included
673 * @return string
674 * @throws InconsistentQuerySettingsException
675 */
676 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored = [], $includeDeleted)
677 {
678 $statement = '';
679 if ($ignoreEnableFields && !$includeDeleted) {
680 if (!empty($enableFieldsToBeIgnored)) {
681 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
682 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
683 } else {
684 $statement .= $this->getPageRepository()->deleteClause($tableName);
685 }
686 } elseif (!$ignoreEnableFields && !$includeDeleted) {
687 $statement .= $this->getPageRepository()->enableFields($tableName);
688 } elseif (!$ignoreEnableFields && $includeDeleted) {
689 throw new InconsistentQuerySettingsException('Query setting "ignoreEnableFields=FALSE" can not be used together with "includeDeleted=TRUE" in frontend context.', 1460975922);
690 }
691 return $statement;
692 }
693
694 /**
695 * Returns constraint statement for backend context
696 *
697 * @param string $tableName
698 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
699 * @param bool $includeDeleted A flag indicating whether deleted records should be included
700 * @return string
701 */
702 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted)
703 {
704 $statement = '';
705 if (!$ignoreEnableFields) {
706 $statement .= BackendUtility::BEenableFields($tableName);
707 }
708 if (!$includeDeleted) {
709 $statement .= BackendUtility::deleteClause($tableName);
710 }
711 return $statement;
712 }
713
714 /**
715 * Builds the language field statement
716 *
717 * @param string $tableName The database table name
718 * @param string $tableAlias The table alias used in the query.
719 * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
720 * @return string
721 */
722 protected function getSysLanguageStatement($tableName, $tableAlias, $querySettings)
723 {
724 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
725 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
726 // Select all entries for the current language
727 // If any language is set -> get those entries which are not translated yet
728 // They will be removed by \TYPO3\CMS\Frontend\Page\PageRepository::getRecordOverlay if not matching overlay mode
729 $languageField = $GLOBALS['TCA'][$tableName]['ctrl']['languageField'];
730
731 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
732 && $querySettings->getLanguageUid() > 0
733 ) {
734 $mode = $querySettings->getLanguageMode();
735
736 if ($mode === 'strict') {
737 $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
738 $queryBuilderForSubselect
739 ->select($tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
740 ->from($tableName)
741 ->where(
742 $queryBuilderForSubselect->expr()->andX(
743 $queryBuilderForSubselect->expr()->gt($tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'], 0),
744 $queryBuilderForSubselect->expr()->eq($tableName . '.' . $languageField, (int)$querySettings->getLanguageUid())
745 )
746 );
747 return $this->queryBuilder->expr()->orX(
748 $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, -1),
749 $this->queryBuilder->expr()->andX(
750 $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, (int)$querySettings->getLanguageUid()),
751 $this->queryBuilder->expr()->eq($tableAlias . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'], 0)
752 ),
753 $this->queryBuilder->expr()->andX(
754 $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, 0),
755 $this->queryBuilder->expr()->in(
756 $tableAlias . '.uid',
757 $queryBuilderForSubselect->getSQL()
758
759 )
760 )
761 );
762 }
763 $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
764 $queryBuilderForSubselect
765 ->select($tableAlias . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
766 ->from($tableName)
767 ->where(
768 $queryBuilderForSubselect->expr()->andX(
769 $queryBuilderForSubselect->expr()->gt($tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'], 0),
770 $queryBuilderForSubselect->expr()->eq($tableName . '.' . $languageField, (int)$querySettings->getLanguageUid())
771 )
772 );
773 return $this->queryBuilder->expr()->orX(
774 $this->queryBuilder->expr()->in($tableAlias . '.' . $languageField, [(int)$querySettings->getLanguageUid(), -1]),
775 $this->queryBuilder->expr()->andX(
776 $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, 0),
777 $this->queryBuilder->expr()->notIn(
778 $tableAlias . '.uid',
779 $queryBuilderForSubselect->getSQL()
780
781 )
782 )
783 );
784 }
785 return $this->queryBuilder->expr()->in(
786 $tableAlias . '.' . $languageField,
787 [(int)$querySettings->getLanguageUid(), -1]
788 );
789 }
790 }
791 return '';
792 }
793
794 /**
795 * Builds the page ID checking statement
796 *
797 * @param string $tableName The database table name
798 * @param string $tableAlias The table alias used in the query.
799 * @param array $storagePageIds list of storage page ids
800 * @throws InconsistentQuerySettingsException
801 * @return string
802 */
803 protected function getPageIdStatement($tableName, $tableAlias, array $storagePageIds)
804 {
805 if (!is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
806 return '';
807 }
808
809 $rootLevel = (int)$GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'];
810 switch ($rootLevel) {
811 // Only in pid 0
812 case 1:
813 $storagePageIds = [0];
814 break;
815 // Pid 0 and pagetree
816 case -1:
817 if (empty($storagePageIds)) {
818 $storagePageIds = [0];
819 } else {
820 $storagePageIds[] = 0;
821 }
822 break;
823 // Only pagetree or not set
824 case 0:
825 if (empty($storagePageIds)) {
826 throw new InconsistentQuerySettingsException('Missing storage page ids.', 1365779762);
827 }
828 break;
829 // Invalid configuration
830 default:
831 return '';
832 }
833 $storagePageIds = array_map('intval', $storagePageIds);
834 if (count($storagePageIds) === 1) {
835 return $this->queryBuilder->expr()->eq($tableAlias . '.pid', reset($storagePageIds));
836 }
837 return $this->queryBuilder->expr()->in($tableAlias . '.pid', $storagePageIds);
838 }
839
840 /**
841 * Transforms a Join into SQL and parameter arrays
842 *
843 * @param Qom\JoinInterface $join The join
844 * @param string $leftTableAlias The alias from the table to main
845 */
846 protected function parseJoin(Qom\JoinInterface $join, $leftTableAlias)
847 {
848 $leftSource = $join->getLeft();
849 $leftClassName = $leftSource->getNodeTypeName();
850 $this->addRecordTypeConstraint($leftClassName);
851 $rightSource = $join->getRight();
852 if ($rightSource instanceof Qom\JoinInterface) {
853 $left = $rightSource->getLeft();
854 $rightClassName = $left->getNodeTypeName();
855 $rightTableName = $left->getSelectorName();
856 } else {
857 $rightClassName = $rightSource->getNodeTypeName();
858 $rightTableName = $rightSource->getSelectorName();
859 $this->queryBuilder->addSelect($rightTableName . '.*');
860 }
861 $this->addRecordTypeConstraint($rightClassName);
862 $rightTableAlias = $this->getUniqueAlias($rightTableName);
863 $joinCondition = $join->getJoinCondition();
864 $joinConditionExpression = null;
865 $this->unionTableAliasCache[] = $rightTableAlias;
866 if ($joinCondition instanceof Qom\EquiJoinCondition) {
867 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
868 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
869
870 $joinConditionExpression = $this->queryBuilder->expr()->eq(
871 $leftTableAlias . '.' . $column1Name,
872 $this->queryBuilder->quoteIdentifier($rightTableAlias . '.' . $column2Name)
873 );
874 }
875 $this->queryBuilder->leftJoin($leftTableAlias, $rightTableName, $rightTableAlias, $joinConditionExpression);
876 if ($rightSource instanceof Qom\JoinInterface) {
877 $this->parseJoin($rightSource, $rightTableAlias);
878 }
879 }
880
881 /**
882 * Generates a unique alias for the given table and the given property path.
883 * The property path will be mapped to the generated alias in the tablePropertyMap.
884 *
885 * @param string $tableName The name of the table for which the alias should be generated.
886 * @param string $fullPropertyPath The full property path that is related to the given table.
887 * @return string The generated table alias.
888 */
889 protected function getUniqueAlias($tableName, $fullPropertyPath = null)
890 {
891 if (isset($fullPropertyPath) && isset($this->tablePropertyMap[$fullPropertyPath])) {
892 return $this->tablePropertyMap[$fullPropertyPath];
893 }
894
895 $alias = $tableName;
896 $i = 0;
897 while (isset($this->tableAliasMap[$alias])) {
898 $alias = $tableName . $i;
899 $i++;
900 }
901
902 $this->tableAliasMap[$alias] = $tableName;
903
904 if (isset($fullPropertyPath)) {
905 $this->tablePropertyMap[$fullPropertyPath] = $alias;
906 }
907
908 return $alias;
909 }
910
911 /**
912 * adds a union statement to the query, mostly for tables referenced in the where condition.
913 * The property for which the union statement is generated will be appended.
914 *
915 * @param string &$className The name of the parent class, will be set to the child class after processing.
916 * @param string &$tableName The name of the parent table, will be set to the table alias that is used in the union statement.
917 * @param string &$propertyPath The remaining property path, will be cut of by one part during the process.
918 * @param string $fullPropertyPath The full path the the current property, will be used to make table names unique.
919 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
920 * @throws InvalidRelationConfigurationException
921 * @throws MissingColumnMapException
922 */
923 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, &$fullPropertyPath)
924 {
925 $explodedPropertyPath = explode('.', $propertyPath, 2);
926 $propertyName = $explodedPropertyPath[0];
927 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
928 $realTableName = $this->dataMapper->convertClassNameToTableName($className);
929 $tableName = isset($this->tablePropertyMap[$fullPropertyPath]) ? $this->tablePropertyMap[$fullPropertyPath] : $realTableName;
930 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
931
932 if ($columnMap === null) {
933 throw new MissingColumnMapException('The ColumnMap for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1355142232);
934 }
935
936 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
937 $childTableName = $columnMap->getChildTableName();
938
939 if ($childTableName === null) {
940 throw new InvalidRelationConfigurationException('The relation information for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1353170925);
941 }
942
943 $fullPropertyPath .= ($fullPropertyPath === '') ? $propertyName : '.' . $propertyName;
944 $childTableAlias = $this->getUniqueAlias($childTableName, $fullPropertyPath);
945
946 // If there is already a union with the current identifier we do not need to build it again and exit early.
947 if (in_array($childTableAlias, $this->unionTableAliasCache, true)) {
948 $propertyPath = $explodedPropertyPath[1];
949 $tableName = $childTableAlias;
950 $className = $this->dataMapper->getType($className, $propertyName);
951 return;
952 }
953
954 if ($columnMap->getTypeOfRelation() === ColumnMap::RELATION_HAS_ONE) {
955 if (isset($parentKeyFieldName)) {
956 // @todo: no test for this part yet
957 $joinConditionExpression = $this->queryBuilder->expr()->eq(
958 $tableName . '.uid',
959 $this->queryBuilder->quoteIdentifier($childTableAlias . '.' . $parentKeyFieldName)
960 );
961 } else {
962 $joinConditionExpression = $this->queryBuilder->expr()->eq(
963 $tableName . '.' . $columnName,
964 $this->queryBuilder->quoteIdentifier($childTableAlias . '.uid')
965 );
966 }
967 $this->queryBuilder->leftJoin($tableName, $childTableName, $childTableAlias, $joinConditionExpression);
968 $this->unionTableAliasCache[] = $childTableAlias;
969 $this->queryBuilder->andWhere(
970 $this->getAdditionalMatchFieldsStatement($this->queryBuilder->expr(), $columnMap, $childTableAlias, $realTableName)
971 );
972 } elseif ($columnMap->getTypeOfRelation() === ColumnMap::RELATION_HAS_MANY) {
973 // @todo: no tests for this part yet
974 if (isset($parentKeyFieldName)) {
975 $joinConditionExpression = $this->queryBuilder->expr()->eq(
976 $tableName . '.uid',
977 $this->queryBuilder->quoteIdentifier($childTableAlias . '.' . $parentKeyFieldName)
978 );
979 } else {
980 $joinConditionExpression = $this->queryBuilder->expr()->inSet(
981 $tableName . '.' . $columnName,
982 $this->queryBuilder->quoteIdentifier($childTableAlias . '.uid'),
983 true
984 );
985 }
986 $this->queryBuilder->leftJoin($tableName, $childTableName, $childTableAlias, $joinConditionExpression);
987 $this->unionTableAliasCache[] = $childTableAlias;
988 $this->queryBuilder->andWhere(
989 $this->getAdditionalMatchFieldsStatement($this->queryBuilder->expr(), $columnMap, $childTableAlias, $realTableName)
990 );
991 } elseif ($columnMap->getTypeOfRelation() === ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
992 $relationTableName = $columnMap->getRelationTableName();
993 $relationTableAlias = $relationTableAlias = $this->getUniqueAlias($relationTableName, $fullPropertyPath . '_mm');
994
995 $joinConditionExpression = $this->queryBuilder->expr()->andX(
996 $this->queryBuilder->expr()->eq(
997 $tableName . '.uid',
998 $this->queryBuilder->quoteIdentifier(
999 $relationTableAlias . '.' . $columnMap->getParentKeyFieldName()
1000 )
1001 ),
1002 $this->getAdditionalMatchFieldsStatement($this->queryBuilder->expr(), $columnMap, $relationTableAlias, $realTableName)
1003 );
1004 $this->queryBuilder->leftJoin($tableName, $relationTableName, $relationTableAlias, $joinConditionExpression);
1005 $joinConditionExpression = $this->queryBuilder->expr()->eq(
1006 $relationTableAlias . '.' . $columnMap->getChildKeyFieldName(),
1007 $this->queryBuilder->quoteIdentifier($childTableAlias . '.uid')
1008 );
1009 $this->queryBuilder->leftJoin($relationTableAlias, $childTableName, $childTableAlias, $joinConditionExpression);
1010 $this->unionTableAliasCache[] = $childTableAlias;
1011 $this->queryBuilder->addGroupBy($this->tableName . '.uid');
1012 } else {
1013 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Could not determine type of relation.', 1252502725);
1014 }
1015 $propertyPath = $explodedPropertyPath[1];
1016 $tableName = $childTableAlias;
1017 $className = $this->dataMapper->getType($className, $propertyName);
1018 }
1019
1020 /**
1021 * If the table name does not match the table alias all occurrences of
1022 * "tableName." are replaced with "tableAlias." in the given SQL statement.
1023 *
1024 * @param string $statement The SQL statement in which the values are replaced.
1025 * @param string $tableName The table name that is replaced.
1026 * @param string $tableAlias The table alias that replaced the table name.
1027 * @return string The modified SQL statement.
1028 */
1029 protected function replaceTableNameWithAlias($statement, $tableName, $tableAlias)
1030 {
1031 if ($tableAlias !== $tableName) {
1032 /** @var Connection $connection */
1033 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($tableName);
1034 $quotedTableName = $connection->quoteIdentifier($tableName);
1035 $quotedTableAlias = $connection->quoteIdentifier($tableAlias);
1036 $statement = str_replace(
1037 [$tableName . '.', $quotedTableName . '.'],
1038 [$tableAlias . '.', $quotedTableAlias . '.'],
1039 $statement
1040 );
1041 }
1042
1043 return $statement;
1044 }
1045
1046 /**
1047 * @return PageRepository
1048 */
1049 protected function getPageRepository()
1050 {
1051 if (!$this->pageRepository instanceof PageRepository) {
1052 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
1053 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
1054 } else {
1055 $this->pageRepository = GeneralUtility::makeInstance(PageRepository::class);
1056 }
1057 }
1058
1059 return $this->pageRepository;
1060 }
1061 }