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