3bd359451be039567737e3f99c9a67a45e2085b9
[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 * Copyright notice
6 *
7 * (c) 2014 Extbase Team (http://forge.typo3.org/projects/typo3v4-mvc)
8 * Extbase is a backport of TYPO3 Flow. All credits go to the TYPO3 Flow team.
9 * All rights reserved
10 *
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 * A copy is found in the text file GPL.txt and important notices to the license
20 * from the author is found in LICENSE.txt distributed with these scripts.
21 *
22 *
23 * This script is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * This copyright notice MUST APPEAR in all copies of the script!
29 ***************************************************************/
30
31 use TYPO3\CMS\Backend\Utility\BackendUtility;
32 use TYPO3\CMS\Extbase\Utility\TypeHandlingUtility;
33
34 /**
35 * QueryParser, converting the qom to string representation
36 */
37 class Typo3DbQueryParser {
38
39 const OPERATOR_EQUAL_TO_NULL = 'operatorEqualToNull';
40 const OPERATOR_NOT_EQUAL_TO_NULL = 'operatorNotEqualToNull';
41
42 /**
43 * The TYPO3 database object
44 *
45 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
46 */
47 protected $databaseHandle;
48
49 /**
50 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
51 * @inject
52 */
53 protected $dataMapper;
54
55 /**
56 * The TYPO3 page repository. Used for language and workspace overlay
57 *
58 * @var \TYPO3\CMS\Frontend\Page\PageRepository
59 */
60 protected $pageRepository;
61
62 /**
63 * @var \TYPO3\CMS\Core\Cache\CacheManager
64 * @inject
65 */
66 protected $cacheManager;
67
68 /**
69 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
70 */
71 protected $tableColumnCache;
72
73 /**
74 * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
75 * @inject
76 */
77 protected $environmentService;
78
79 /**
80 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
81 */
82 public function __construct() {
83 $this->databaseHandle = $GLOBALS['TYPO3_DB'];
84 }
85
86 /**
87 * Lifecycle method
88 *
89 * @return void
90 */
91 public function initializeObject() {
92 $this->tableColumnCache = $this->cacheManager->getCache('extbase_typo3dbbackend_tablecolumns');
93 }
94
95 /**
96 * Preparses the query and returns the query's hash and the parameters
97 *
98 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query The query
99 * @return array the hash and the parameters
100 */
101 public function preparseQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
102 $parameters = $this->preparseComparison($query->getConstraint());
103 $hashPartials = array(
104 $query->getQuerySettings(),
105 $query->getSource(),
106 array_keys($parameters),
107 $query->getOrderings(),
108 );
109 $hash = md5(serialize($hashPartials));
110
111 return array($hash, $parameters);
112 }
113
114 /**
115 * Walks through the qom's constraints and extracts the properties and values.
116 *
117 * In the qom the query structure and values are glued together. This walks through the
118 * qom and only extracts the parts necessary for generating the hash and filling the
119 * statement. It leaves out the actual statement generation, as it is the most time
120 * consuming.
121 *
122 * @param object $comparison The constraint. Could be And-, Or-, Not- or ComparisonInterface
123 * @param string $qomPath current position of the child in the qom
124 * @return array string representation of constraint and array of parameters
125 * @throws \Exception
126 */
127 protected function preparseComparison($comparison, $qomPath = '') {
128 $parameters = array();
129 $objectsToParse = array();
130
131 if ($comparison instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface) {
132 $delimiter = 'AND';
133 $objectsToParse = array($comparison->getConstraint1(), $comparison->getConstraint2());
134 } elseif ($comparison instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface) {
135 $delimiter = 'OR';
136 $objectsToParse = array($comparison->getConstraint1(), $comparison->getConstraint2());
137 } elseif ($comparison instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface) {
138 $delimiter = 'NOT';
139 $objectsToParse = array($comparison->getConstraint());
140 } elseif ($comparison instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface) {
141 $parameterIdentifier = $this->normalizeParameterIdentifier($qomPath . $comparison->getOperand1()->getPropertyName());
142 $comparison->setParameterIdentifier($parameterIdentifier);
143 $parameters[$parameterIdentifier] = $comparison->getOperand2();
144 } elseif (!is_object($comparison)) {
145 return array(array(), $comparison);
146 } else {
147 throw new \Exception('Can not hash Query Component "' . get_class($comparison) . '".', 1392840462);
148 }
149
150 $childObjectIterator = 0;
151 foreach ($objectsToParse as $objectToParse) {
152 $preparsedParameters = $this->preparseComparison($objectToParse, $qomPath . $delimiter . $childObjectIterator++);
153 if (!empty($preparsedParameters)) {
154 $parameters = array_merge($parameters, $preparsedParameters);
155 }
156 }
157
158 return $parameters;
159 }
160
161 /**
162 * normalizes the parameter's identifier
163 *
164 * @param string $identifier
165 * @return string
166 * @todo come on, clean up that method!
167 */
168 public function normalizeParameterIdentifier($identifier) {
169 return ':' . preg_replace('/[^A-Za-z0-9]/', '', $identifier);
170 }
171
172 /**
173 * Parses the query and returns the SQL statement parts.
174 *
175 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query The query
176 * @return array The SQL statement parts
177 */
178 public function parseQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
179 $sql = array();
180 $sql['keywords'] = array();
181 $sql['tables'] = array();
182 $sql['unions'] = array();
183 $sql['fields'] = array();
184 $sql['where'] = array();
185 $sql['additionalWhereClause'] = array();
186 $sql['orderings'] = array();
187 $sql['limit'] = ((int)$query->getLimit() ?: NULL);
188 $sql['offset'] = ((int)$query->getOffset() ?: NULL);
189 $source = $query->getSource();
190 $this->parseSource($source, $sql);
191 $this->parseConstraint($query->getConstraint(), $source, $sql);
192 $this->parseOrderings($query->getOrderings(), $source, $sql);
193
194 $tableNames = array_unique(array_keys($sql['tables'] + $sql['unions']));
195 foreach ($tableNames as $tableName) {
196 if (is_string($tableName) && !empty($tableName)) {
197 $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql);
198 }
199 }
200
201 return $sql;
202 }
203
204 /**
205 * Transforms a Query Source into SQL and parameter arrays
206 *
207 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
208 * @param array &$sql
209 * @return void
210 */
211 protected function parseSource(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
212 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
213 $className = $source->getNodeTypeName();
214 $tableName = $this->dataMapper->getDataMap($className)->getTableName();
215 $this->addRecordTypeConstraint($className, $sql);
216 $sql['fields'][$tableName] = $tableName . '.*';
217 $sql['tables'][$tableName] = $tableName;
218 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
219 $this->parseJoin($source, $sql);
220 }
221 }
222
223 /**
224 * Transforms a constraint into SQL and parameter arrays
225 *
226 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint The constraint
227 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
228 * @param array &$sql The query parts
229 * @return void
230 */
231 protected function parseConstraint(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint = NULL, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
232 if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface) {
233 $sql['where'][] = '(';
234 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
235 $sql['where'][] = ' AND ';
236 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
237 $sql['where'][] = ')';
238 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface) {
239 $sql['where'][] = '(';
240 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
241 $sql['where'][] = ' OR ';
242 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
243 $sql['where'][] = ')';
244 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface) {
245 $sql['where'][] = 'NOT (';
246 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
247 $sql['where'][] = ')';
248 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface) {
249 $this->parseComparison($constraint, $source, $sql);
250 }
251 }
252
253 /**
254 * Transforms orderings into SQL.
255 *
256 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
257 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
258 * @param array &$sql The query parts
259 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException
260 * @return void
261 */
262 protected function parseOrderings(array $orderings, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
263 foreach ($orderings as $propertyName => $order) {
264 switch ($order) {
265 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
266
267 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING:
268 $order = 'ASC';
269 break;
270 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
271
272 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING:
273 $order = 'DESC';
274 break;
275 default:
276 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException('Unsupported order encountered.', 1242816074);
277 }
278 $className = '';
279 $tableName = '';
280 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
281 $className = $source->getNodeTypeName();
282 $tableName = $this->dataMapper->convertClassNameToTableName($className);
283 while (strpos($propertyName, '.') !== FALSE) {
284 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
285 }
286 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
287 $tableName = $source->getLeft()->getSelectorName();
288 }
289 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
290 if ($tableName !== '') {
291 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
292 } else {
293 $sql['orderings'][] = $columnName . ' ' . $order;
294 }
295 }
296 }
297
298 /**
299 * Parse a Comparison into SQL and parameter arrays.
300 *
301 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison The comparison to parse
302 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
303 * @param array &$sql SQL query parts to add to
304 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException
305 * @return void
306 */
307 protected function parseComparison(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
308 $operand1 = $comparison->getOperand1();
309 $operator = $comparison->getOperator();
310 $operand2 = $comparison->getOperand2();
311 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_IN) {
312 $items = array();
313 $hasValue = FALSE;
314 foreach ($operand2 as $value) {
315 $value = $this->getPlainValue($value);
316 if ($value !== NULL) {
317 $parameters[] = $value;
318 $hasValue = TRUE;
319 }
320 }
321 if ($hasValue === FALSE) {
322 $sql['where'][] = '1<>1';
323 } else {
324 $this->parseDynamicOperand($comparison, $source, $sql, NULL);
325 }
326 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_CONTAINS) {
327 if ($operand2 === NULL) {
328 $sql['where'][] = '1<>1';
329 } else {
330 $className = $source->getNodeTypeName();
331 $tableName = $this->dataMapper->convertClassNameToTableName($className);
332 $propertyName = $operand1->getPropertyName();
333 while (strpos($propertyName, '.') !== FALSE) {
334 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
335 }
336 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
337 $dataMap = $this->dataMapper->getDataMap($className);
338 $columnMap = $dataMap->getColumnMap($propertyName);
339 $typeOfRelation = $columnMap instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap ? $columnMap->getTypeOfRelation() : NULL;
340 if ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
341 $relationTableName = $columnMap->getRelationTableName();
342 $sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=?)';
343 } elseif ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
344 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
345 if (isset($parentKeyFieldName)) {
346 $childTableName = $columnMap->getChildTableName();
347 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=?)';
348 } else {
349 $sql['where'][] = 'FIND_IN_SET(?,' . $tableName . '.' . $columnName . ')';
350 }
351 } else {
352 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
353 }
354 }
355 } else {
356 if ($operand2 === NULL) {
357 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_EQUAL_TO) {
358 $operator = self::OPERATOR_EQUAL_TO_NULL;
359 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_NOT_EQUAL_TO) {
360 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
361 }
362 }
363 $this->parseDynamicOperand($comparison, $source, $sql, $parameters);
364 }
365 }
366
367 /**
368 * Parse a DynamicOperand into SQL and parameter arrays.
369 *
370 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\DynamicOperandInterface $operand
371 * @param string $operator One of the JCR_OPERATOR_* constants
372 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
373 * @param array &$sql The query parts
374 * @param string $valueFunction an optional SQL function to apply to the operand value
375 * @return void
376 */
377 protected function parseDynamicOperand(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql, $valueFunction = NULL) {
378 $operand = $comparison->getOperand1();
379 $operator = $comparison->getOperator();
380 $operand2 = $comparison->getOperand2();
381
382 if ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\LowerCaseInterface) {
383 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
384 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\UpperCaseInterface) {
385 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
386 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\PropertyValueInterface) {
387 $propertyName = $operand->getPropertyName();
388 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
389 // FIXME Only necessary to differ from Join
390 $className = $source->getNodeTypeName();
391 $tableName = $this->dataMapper->convertClassNameToTableName($className);
392 while (strpos($propertyName, '.') !== FALSE) {
393 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
394 }
395 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
396 $tableName = $source->getJoinCondition()->getSelector1Name();
397 }
398 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
399 $operator = $this->resolveOperator($operator);
400 $constraintSQL = '';
401 if ($valueFunction === NULL) {
402 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ';
403 } else {
404 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ') ' . $operator . ' ';
405 }
406
407 if ($operator === 'LIKE' || $operator === 'IN') {
408 $constraintSQL .= '(' . $this->normalizeParameterIdentifier($comparison->getParameterIdentifier()) . ')';
409 } else {
410 $constraintSQL .= $this->normalizeParameterIdentifier($comparison->getParameterIdentifier());
411 }
412
413 $sql['where'][] = $constraintSQL;
414 }
415 }
416
417 /**
418 * Add a constraint to ensure that the record type of the returned tuples is matching the data type of the repository.
419 *
420 * @param string $className The class name
421 * @param array &$sql The query parts
422 * @return void
423 */
424 protected function addRecordTypeConstraint($className, &$sql) {
425 if ($className !== NULL) {
426 $dataMap = $this->dataMapper->getDataMap($className);
427 if ($dataMap->getRecordTypeColumnName() !== NULL) {
428 $recordTypes = array();
429 if ($dataMap->getRecordType() !== NULL) {
430 $recordTypes[] = $dataMap->getRecordType();
431 }
432 foreach ($dataMap->getSubclasses() as $subclassName) {
433 $subclassDataMap = $this->dataMapper->getDataMap($subclassName);
434 if ($subclassDataMap->getRecordType() !== NULL) {
435 $recordTypes[] = $subclassDataMap->getRecordType();
436 }
437 }
438 if (!empty($recordTypes)) {
439 $recordTypeStatements = array();
440 foreach ($recordTypes as $recordType) {
441 $tableName = $dataMap->getTableName();
442 $recordTypeStatements[] = $tableName . '.' . $dataMap->getRecordTypeColumnName() . '=' . $this->databaseHandle->fullQuoteStr($recordType, $tableName);
443 }
444 $sql['additionalWhereClause'][] = '(' . implode(' OR ', $recordTypeStatements) . ')';
445 }
446 }
447 }
448 }
449
450 /**
451 * Adds additional WHERE statements according to the query settings.
452 *
453 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
454 * @param string $tableName The table name to add the additional where clause for
455 * @param string &$sql
456 * @return void
457 */
458 protected function addAdditionalWhereClause(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, &$sql) {
459 $this->addVisibilityConstraintStatement($querySettings, $tableName, $sql);
460 if ($querySettings->getRespectSysLanguage()) {
461 $this->addSysLanguageStatement($tableName, $sql, $querySettings);
462 }
463 if ($querySettings->getRespectStoragePage()) {
464 $this->addPageIdStatement($tableName, $sql, $querySettings->getStoragePageIds());
465 }
466 }
467
468 /**
469 * Adds enableFields and deletedClause to the query if necessary
470 *
471 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
472 * @param string $tableName The database table name
473 * @param array &$sql The query parts
474 * @return void
475 */
476 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, array &$sql) {
477 $statement = '';
478 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
479 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
480 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
481 $includeDeleted = $querySettings->getIncludeDeleted();
482 if ($this->environmentService->isEnvironmentInFrontendMode()) {
483 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
484 } else {
485 // TYPO3_MODE === 'BE'
486 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
487 }
488 if (!empty($statement)) {
489 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
490 $sql['additionalWhereClause'][] = $statement;
491 }
492 }
493 }
494
495 /**
496 * Returns constraint statement for frontend context
497 *
498 * @param string $tableName
499 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
500 * @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.
501 * @param bool $includeDeleted A flag indicating whether deleted records should be included
502 * @return string
503 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
504 */
505 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored = array(), $includeDeleted) {
506 $statement = '';
507 if ($ignoreEnableFields && !$includeDeleted) {
508 if (count($enableFieldsToBeIgnored)) {
509 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
510 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
511 } else {
512 $statement .= $this->getPageRepository()->deleteClause($tableName);
513 }
514 } elseif (!$ignoreEnableFields && !$includeDeleted) {
515 $statement .= $this->getPageRepository()->enableFields($tableName);
516 } elseif (!$ignoreEnableFields && $includeDeleted) {
517 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException('Query setting "ignoreEnableFields=FALSE" can not be used together with "includeDeleted=TRUE" in frontend context.', 1327678173);
518 }
519 return $statement;
520 }
521
522 /**
523 * Returns constraint statement for backend context
524 *
525 * @param string $tableName
526 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
527 * @param bool $includeDeleted A flag indicating whether deleted records should be included
528 * @return string
529 */
530 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
531 $statement = '';
532 if (!$ignoreEnableFields) {
533 $statement .= BackendUtility::BEenableFields($tableName);
534 }
535 if (!$includeDeleted) {
536 $statement .= BackendUtility::deleteClause($tableName);
537 }
538 return $statement;
539 }
540
541 /**
542 * Builds the language field statement
543 *
544 * @param string $tableName The database table name
545 * @param array &$sql The query parts
546 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
547 * @return void
548 */
549 protected function addSysLanguageStatement($tableName, array &$sql, $querySettings) {
550 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
551 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
552 // Select all entries for the current language
553 $additionalWhereClause = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (' . (int)$querySettings->getLanguageUid() . ',-1)';
554 // If any language is set -> get those entries which are not translated yet
555 // They will be removed by t3lib_page::getRecordOverlay if not matching overlay mode
556 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
557 && $querySettings->getLanguageUid() > 0
558 ) {
559 $additionalWhereClause .= ' OR (' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0' .
560 ' AND ' . $tableName . '.uid NOT IN (SELECT ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] .
561 ' FROM ' . $tableName .
562 ' WHERE ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] . '>0' .
563 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '>0';
564
565 // Add delete clause to ensure all entries are loaded
566 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
567 $additionalWhereClause .= ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
568 }
569 $additionalWhereClause .= '))';
570 }
571 $sql['additionalWhereClause'][] = '(' . $additionalWhereClause . ')';
572 }
573 }
574 }
575
576 /**
577 * Builds the page ID checking statement
578 *
579 * @param string $tableName The database table name
580 * @param array &$sql The query parts
581 * @param array $storagePageIds list of storage page ids
582 * @return void
583 */
584 protected function addPageIdStatement($tableName, array &$sql, array $storagePageIds) {
585 $tableColumns = $this->tableColumnCache->get($tableName);
586 if ($tableColumns === FALSE) {
587 $tableColumns = $this->databaseHandle->admin_get_fields($tableName);
588 $this->tableColumnCache->set($tableName, $tableColumns);
589 }
590 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $tableColumns)) {
591 $rootLevel = (int)$GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'];
592 if ($rootLevel) {
593 if ($rootLevel === 1) {
594 $sql['additionalWhereClause'][] = $tableName . '.pid = 0';
595 }
596 } else {
597 if (empty($storagePageIds)) {
598 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException('Missing storage page ids.', 1365779762);
599 }
600 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', $storagePageIds) . ')';
601 }
602 }
603 }
604
605 /**
606 * Transforms a Join into SQL and parameter arrays
607 *
608 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join The join
609 * @param array &$sql The query parts
610 * @return void
611 */
612 protected function parseJoin(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join, array &$sql) {
613 $leftSource = $join->getLeft();
614 $leftClassName = $leftSource->getNodeTypeName();
615 $this->addRecordTypeConstraint($leftClassName, $sql);
616 $leftTableName = $leftSource->getSelectorName();
617 $rightSource = $join->getRight();
618 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
619 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
620 $rightTableName = $rightSource->getLeft()->getSelectorName();
621 } else {
622 $rightClassName = $rightSource->getNodeTypeName();
623 $rightTableName = $rightSource->getSelectorName();
624 $sql['fields'][$leftTableName] = $rightTableName . '.*';
625 }
626 $this->addRecordTypeConstraint($rightClassName, $sql);
627 $sql['tables'][$leftTableName] = $leftTableName;
628 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
629 $joinCondition = $join->getJoinCondition();
630 if ($joinCondition instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition) {
631 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
632 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
633 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
634 }
635 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
636 $this->parseJoin($rightSource, $sql);
637 }
638 }
639
640 /**
641 * Returns a plain value, i.e. objects are flattened out if possible.
642 *
643 * @param mixed $input
644 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
645 * @return mixed
646 */
647 protected function getPlainValue($input) {
648 if (is_array($input)) {
649 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
650 }
651 if ($input instanceof \DateTime) {
652 return $input->format('U');
653 } elseif (TypeHandlingUtility::isCoreType($input)) {
654 return (string) $input;
655 } elseif (is_object($input)) {
656 if ($input instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
657 $realInput = $input->_loadRealInstance();
658 } else {
659 $realInput = $input;
660 }
661 if ($realInput instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
662 return $realInput->getUid();
663 } else {
664 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An object of class "' . get_class($realInput) . '" could not be converted to a plain value.', 1274799934);
665 }
666 } elseif (is_bool($input)) {
667 return $input === TRUE ? 1 : 0;
668 } else {
669 return $input;
670 }
671 }
672
673
674 /**
675 * adds a union statement to the query, mostly for tables referenced in the where condition.
676 *
677 * @param string &$className
678 * @param string &$tableName
679 * @param array &$propertyPath
680 * @param array &$sql
681 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
682 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException
683 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException
684 */
685 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
686 $explodedPropertyPath = explode('.', $propertyPath, 2);
687 $propertyName = $explodedPropertyPath[0];
688 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
689 $tableName = $this->dataMapper->convertClassNameToTableName($className);
690 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
691
692 if ($columnMap === NULL) {
693 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException('The ColumnMap for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1355142232);
694 }
695
696 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
697 $childTableName = $columnMap->getChildTableName();
698
699 if ($childTableName === NULL) {
700 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException('The relation information for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1353170925);
701 }
702
703 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_ONE) {
704 if (isset($parentKeyFieldName)) {
705 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
706 } else {
707 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
708 }
709 $className = $this->dataMapper->getType($className, $propertyName);
710 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
711 if (isset($parentKeyFieldName)) {
712 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
713 } else {
714 $onStatement = '(FIND_IN_SET(' . $childTableName . '.uid, ' . $tableName . '.' . $columnName . '))';
715 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $onStatement;
716 }
717 $className = $this->dataMapper->getType($className, $propertyName);
718 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
719 $relationTableName = $columnMap->getRelationTableName();
720 $sql['unions'][$relationTableName] = 'LEFT JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.' . $columnMap->getParentKeyFieldName();
721 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $relationTableName . '.' . $columnMap->getChildKeyFieldName() . '=' . $childTableName . '.uid';
722 $className = $this->dataMapper->getType($className, $propertyName);
723 } else {
724 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Could not determine type of relation.', 1252502725);
725 }
726 // TODO check if there is another solution for this
727 $sql['keywords']['distinct'] = 'DISTINCT';
728 $propertyPath = $explodedPropertyPath[1];
729 $tableName = $childTableName;
730 }
731
732 /**
733 * Returns the SQL operator for the given JCR operator type.
734 *
735 * @param string $operator One of the JCR_OPERATOR_* constants
736 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
737 * @return string an SQL operator
738 */
739 protected function resolveOperator($operator) {
740 switch ($operator) {
741 case self::OPERATOR_EQUAL_TO_NULL:
742 $operator = 'IS';
743 break;
744 case self::OPERATOR_NOT_EQUAL_TO_NULL:
745 $operator = 'IS NOT';
746 break;
747 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_IN:
748 $operator = 'IN';
749 break;
750 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_EQUAL_TO:
751 $operator = '=';
752 break;
753 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_NOT_EQUAL_TO:
754 $operator = '!=';
755 break;
756 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LESS_THAN:
757 $operator = '<';
758 break;
759 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
760 $operator = '<=';
761 break;
762 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_GREATER_THAN:
763 $operator = '>';
764 break;
765 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
766 $operator = '>=';
767 break;
768 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LIKE:
769 $operator = 'LIKE';
770 break;
771 default:
772 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Unsupported operator encountered.', 1242816073);
773 }
774 return $operator;
775 }
776
777 /**
778 * @return \TYPO3\CMS\Frontend\Page\PageRepository
779 */
780 protected function getPageRepository() {
781 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
782 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
783 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
784 } else {
785 $this->pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
786 }
787 }
788
789 return $this->pageRepository;
790 }
791 }