[BUGFIX] Queries with NULL don't work anymore
[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 \RuntimeException
267 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException
268 * @return void
269 */
270 protected function parseOrderings(array $orderings, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
271 foreach ($orderings as $propertyName => $order) {
272 switch ($order) {
273 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
274
275 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING:
276 $order = 'ASC';
277 break;
278 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
279
280 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING:
281 $order = 'DESC';
282 break;
283 default:
284 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException('Unsupported order encountered.', 1242816074);
285 }
286 $className = '';
287 $tableName = '';
288 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
289 $className = $source->getNodeTypeName();
290 $tableName = $this->dataMapper->convertClassNameToTableName($className);
291 while (strpos($propertyName, '.') !== FALSE) {
292 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
293 }
294 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
295 $tableName = $source->getLeft()->getSelectorName();
296 }
297 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
298 if ($tableName !== '') {
299 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
300 } else {
301 $sql['orderings'][] = $columnName . ' ' . $order;
302 }
303 }
304 }
305
306 /**
307 * Parse a Comparison into SQL and parameter arrays.
308 *
309 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison The comparison to parse
310 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
311 * @param array &$sql SQL query parts to add to
312 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException
313 * @return void
314 */
315 protected function parseComparison(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
316 $parameterIdentifier = $this->normalizeParameterIdentifier($comparison->getParameterIdentifier());
317 $operand1 = $comparison->getOperand1();
318 $operator = $comparison->getOperator();
319 $operand2 = $comparison->getOperand2();
320 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_IN) {
321 $items = array();
322 $hasValue = FALSE;
323 foreach ($operand2 as $value) {
324 $value = $this->getPlainValue($value);
325 if ($value !== NULL) {
326 $parameters[] = $value;
327 $hasValue = TRUE;
328 }
329 }
330 if ($hasValue === FALSE) {
331 $sql['where'][] = '1<>1';
332 } else {
333 $this->parseDynamicOperand($comparison, $operator, $source, $sql, NULL);
334 }
335 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_CONTAINS) {
336 if ($operand2 === NULL) {
337 $sql['where'][] = '1<>1';
338 } else {
339 $className = $source->getNodeTypeName();
340 $tableName = $this->dataMapper->convertClassNameToTableName($className);
341 $propertyName = $operand1->getPropertyName();
342 while (strpos($propertyName, '.') !== FALSE) {
343 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
344 }
345 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
346 $dataMap = $this->dataMapper->getDataMap($className);
347 $columnMap = $dataMap->getColumnMap($propertyName);
348 $typeOfRelation = $columnMap instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap ? $columnMap->getTypeOfRelation() : NULL;
349 if ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
350 $relationTableName = $columnMap->getRelationTableName();
351 $sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=' . $parameterIdentifier . ')';
352 } elseif ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
353 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
354 if (isset($parentKeyFieldName)) {
355 $childTableName = $columnMap->getChildTableName();
356 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $parameterIdentifier . ')';
357 } else {
358 $sql['where'][] = 'FIND_IN_SET(' . $parameterIdentifier . ', ' . $tableName . '.' . $columnName . ')';
359 }
360 } else {
361 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
362 }
363 }
364 } else {
365 if ($operand2 === NULL) {
366 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_EQUAL_TO) {
367 $operator = self::OPERATOR_EQUAL_TO_NULL;
368 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_NOT_EQUAL_TO) {
369 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
370 }
371 }
372 $this->parseDynamicOperand($comparison, $operator, $source, $sql);
373 }
374 }
375
376 /**
377 * Parse a DynamicOperand into SQL and parameter arrays.
378 *
379 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison
380 * @param string $operator One of the JCR_OPERATOR_* constants
381 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
382 * @param array &$sql The query parts
383 * @param string $valueFunction an optional SQL function to apply to the operand value
384 * @return void
385 */
386 protected function parseDynamicOperand(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison, $operator, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql, $valueFunction = NULL) {
387 $operand = $comparison->getOperand1();
388 if ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\LowerCaseInterface) {
389 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, 'LOWER');
390 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\UpperCaseInterface) {
391 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, 'UPPER');
392 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\PropertyValueInterface) {
393 $propertyName = $operand->getPropertyName();
394 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
395 // FIXME Only necessary to differ from Join
396 $className = $source->getNodeTypeName();
397 $tableName = $this->dataMapper->convertClassNameToTableName($className);
398 while (strpos($propertyName, '.') !== FALSE) {
399 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
400 }
401 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
402 $tableName = $source->getJoinCondition()->getSelector1Name();
403 }
404 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
405 $operator = $this->resolveOperator($operator);
406 $constraintSQL = '';
407 if ($valueFunction === NULL) {
408 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ';
409 } else {
410 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ') ' . $operator . ' ';
411 }
412
413 if ($operator === 'LIKE' || $operator === 'IN') {
414 $constraintSQL .= '(' . $this->normalizeParameterIdentifier($comparison->getParameterIdentifier()) . ')';
415 } else {
416 $constraintSQL .= $this->normalizeParameterIdentifier($comparison->getParameterIdentifier());
417 }
418
419 $sql['where'][] = $constraintSQL;
420 }
421 }
422
423 /**
424 * Add a constraint to ensure that the record type of the returned tuples is matching the data type of the repository.
425 *
426 * @param string $className The class name
427 * @param array &$sql The query parts
428 * @return void
429 */
430 protected function addRecordTypeConstraint($className, &$sql) {
431 if ($className !== NULL) {
432 $dataMap = $this->dataMapper->getDataMap($className);
433 if ($dataMap->getRecordTypeColumnName() !== NULL) {
434 $recordTypes = array();
435 if ($dataMap->getRecordType() !== NULL) {
436 $recordTypes[] = $dataMap->getRecordType();
437 }
438 foreach ($dataMap->getSubclasses() as $subclassName) {
439 $subclassDataMap = $this->dataMapper->getDataMap($subclassName);
440 if ($subclassDataMap->getRecordType() !== NULL) {
441 $recordTypes[] = $subclassDataMap->getRecordType();
442 }
443 }
444 if (!empty($recordTypes)) {
445 $recordTypeStatements = array();
446 foreach ($recordTypes as $recordType) {
447 $tableName = $dataMap->getTableName();
448 $recordTypeStatements[] = $tableName . '.' . $dataMap->getRecordTypeColumnName() . '=' . $this->databaseHandle->fullQuoteStr($recordType, $tableName);
449 }
450 $sql['additionalWhereClause'][] = '(' . implode(' OR ', $recordTypeStatements) . ')';
451 }
452 }
453 }
454 }
455
456 /**
457 * Adds additional WHERE statements according to the query settings.
458 *
459 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
460 * @param string $tableName The table name to add the additional where clause for
461 * @param string &$sql
462 * @return void
463 */
464 protected function addAdditionalWhereClause(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, &$sql) {
465 $this->addVisibilityConstraintStatement($querySettings, $tableName, $sql);
466 if ($querySettings->getRespectSysLanguage()) {
467 $this->addSysLanguageStatement($tableName, $sql, $querySettings);
468 }
469 if ($querySettings->getRespectStoragePage()) {
470 $this->addPageIdStatement($tableName, $sql, $querySettings->getStoragePageIds());
471 }
472 }
473
474 /**
475 * Adds enableFields and deletedClause to the query if necessary
476 *
477 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
478 * @param string $tableName The database table name
479 * @param array &$sql The query parts
480 * @return void
481 */
482 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, array &$sql) {
483 $statement = '';
484 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
485 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
486 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
487 $includeDeleted = $querySettings->getIncludeDeleted();
488 if ($this->environmentService->isEnvironmentInFrontendMode()) {
489 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
490 } else {
491 // TYPO3_MODE === 'BE'
492 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
493 }
494 if (!empty($statement)) {
495 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
496 $sql['additionalWhereClause'][] = $statement;
497 }
498 }
499 }
500
501 /**
502 * Returns constraint statement for frontend context
503 *
504 * @param string $tableName
505 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
506 * @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.
507 * @param bool $includeDeleted A flag indicating whether deleted records should be included
508 * @return string
509 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
510 */
511 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored = array(), $includeDeleted) {
512 $statement = '';
513 if ($ignoreEnableFields && !$includeDeleted) {
514 if (count($enableFieldsToBeIgnored)) {
515 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
516 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
517 } else {
518 $statement .= $this->getPageRepository()->deleteClause($tableName);
519 }
520 } elseif (!$ignoreEnableFields && !$includeDeleted) {
521 $statement .= $this->getPageRepository()->enableFields($tableName);
522 } elseif (!$ignoreEnableFields && $includeDeleted) {
523 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);
524 }
525 return $statement;
526 }
527
528 /**
529 * Returns constraint statement for backend context
530 *
531 * @param string $tableName
532 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
533 * @param bool $includeDeleted A flag indicating whether deleted records should be included
534 * @return string
535 */
536 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
537 $statement = '';
538 if (!$ignoreEnableFields) {
539 $statement .= BackendUtility::BEenableFields($tableName);
540 }
541 if (!$includeDeleted) {
542 $statement .= BackendUtility::deleteClause($tableName);
543 }
544 return $statement;
545 }
546
547 /**
548 * Builds the language field statement
549 *
550 * @param string $tableName The database table name
551 * @param array &$sql The query parts
552 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
553 * @return void
554 */
555 protected function addSysLanguageStatement($tableName, array &$sql, $querySettings) {
556 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
557 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
558 // Select all entries for the current language
559 $additionalWhereClause = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (' . (int)$querySettings->getLanguageUid() . ',-1)';
560 // If any language is set -> get those entries which are not translated yet
561 // They will be removed by t3lib_page::getRecordOverlay if not matching overlay mode
562 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
563 && $querySettings->getLanguageUid() > 0
564 ) {
565 $additionalWhereClause .= ' OR (' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0' .
566 ' AND ' . $tableName . '.uid NOT IN (SELECT ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] .
567 ' FROM ' . $tableName .
568 ' WHERE ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] . '>0' .
569 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '>0';
570
571 // Add delete clause to ensure all entries are loaded
572 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
573 $additionalWhereClause .= ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
574 }
575 $additionalWhereClause .= '))';
576 }
577 $sql['additionalWhereClause'][] = '(' . $additionalWhereClause . ')';
578 }
579 }
580 }
581
582 /**
583 * Builds the page ID checking statement
584 *
585 * @param string $tableName The database table name
586 * @param array &$sql The query parts
587 * @param array $storagePageIds list of storage page ids
588 * @return void
589 */
590 protected function addPageIdStatement($tableName, array &$sql, array $storagePageIds) {
591 $tableColumns = $this->tableColumnCache->get($tableName);
592 if ($tableColumns === FALSE) {
593 $tableColumns = $this->databaseHandle->admin_get_fields($tableName);
594 $this->tableColumnCache->set($tableName, $tableColumns);
595 }
596 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $tableColumns)) {
597 $rootLevel = (int)$GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'];
598 if ($rootLevel) {
599 if ($rootLevel === 1) {
600 $sql['additionalWhereClause'][] = $tableName . '.pid = 0';
601 }
602 } else {
603 if (empty($storagePageIds)) {
604 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException('Missing storage page ids.', 1365779762);
605 }
606 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', $storagePageIds) . ')';
607 }
608 }
609 }
610
611 /**
612 * Transforms a Join into SQL and parameter arrays
613 *
614 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join The join
615 * @param array &$sql The query parts
616 * @return void
617 */
618 protected function parseJoin(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join, array &$sql) {
619 $leftSource = $join->getLeft();
620 $leftClassName = $leftSource->getNodeTypeName();
621 $this->addRecordTypeConstraint($leftClassName, $sql);
622 $leftTableName = $leftSource->getSelectorName();
623 $rightSource = $join->getRight();
624 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
625 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
626 $rightTableName = $rightSource->getLeft()->getSelectorName();
627 } else {
628 $rightClassName = $rightSource->getNodeTypeName();
629 $rightTableName = $rightSource->getSelectorName();
630 $sql['fields'][$leftTableName] = $rightTableName . '.*';
631 }
632 $this->addRecordTypeConstraint($rightClassName, $sql);
633 $sql['tables'][$leftTableName] = $leftTableName;
634 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
635 $joinCondition = $join->getJoinCondition();
636 if ($joinCondition instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition) {
637 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
638 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
639 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
640 }
641 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
642 $this->parseJoin($rightSource, $sql);
643 }
644 }
645
646 /**
647 * Returns a plain value, i.e. objects are flattened out if possible.
648 *
649 * @param mixed $input
650 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
651 * @return mixed
652 */
653 protected function getPlainValue($input) {
654 if (is_array($input)) {
655 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
656 }
657 if ($input instanceof \DateTime) {
658 return $input->format('U');
659 } elseif (TypeHandlingUtility::isCoreType($input)) {
660 return (string) $input;
661 } elseif (is_object($input)) {
662 if ($input instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
663 $realInput = $input->_loadRealInstance();
664 } else {
665 $realInput = $input;
666 }
667 if ($realInput instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
668 return $realInput->getUid();
669 } else {
670 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);
671 }
672 } elseif (is_bool($input)) {
673 return $input === TRUE ? 1 : 0;
674 } else {
675 return $input;
676 }
677 }
678
679
680 /**
681 * adds a union statement to the query, mostly for tables referenced in the where condition.
682 *
683 * @param string &$className
684 * @param string &$tableName
685 * @param array &$propertyPath
686 * @param array &$sql
687 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
688 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException
689 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException
690 */
691 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
692 $explodedPropertyPath = explode('.', $propertyPath, 2);
693 $propertyName = $explodedPropertyPath[0];
694 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
695 $tableName = $this->dataMapper->convertClassNameToTableName($className);
696 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
697
698 if ($columnMap === NULL) {
699 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException('The ColumnMap for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1355142232);
700 }
701
702 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
703 $childTableName = $columnMap->getChildTableName();
704
705 if ($childTableName === NULL) {
706 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException('The relation information for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1353170925);
707 }
708
709 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_ONE) {
710 if (isset($parentKeyFieldName)) {
711 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
712 } else {
713 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
714 }
715 $className = $this->dataMapper->getType($className, $propertyName);
716 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
717 if (isset($parentKeyFieldName)) {
718 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
719 } else {
720 $onStatement = '(FIND_IN_SET(' . $childTableName . '.uid, ' . $tableName . '.' . $columnName . '))';
721 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $onStatement;
722 }
723 $className = $this->dataMapper->getType($className, $propertyName);
724 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
725 $relationTableName = $columnMap->getRelationTableName();
726 $sql['unions'][$relationTableName] = 'LEFT JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.' . $columnMap->getParentKeyFieldName();
727 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $relationTableName . '.' . $columnMap->getChildKeyFieldName() . '=' . $childTableName . '.uid';
728 $className = $this->dataMapper->getType($className, $propertyName);
729 } else {
730 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Could not determine type of relation.', 1252502725);
731 }
732 // TODO check if there is another solution for this
733 $sql['keywords']['distinct'] = 'DISTINCT';
734 $propertyPath = $explodedPropertyPath[1];
735 $tableName = $childTableName;
736 }
737
738 /**
739 * Returns the SQL operator for the given JCR operator type.
740 *
741 * @param string $operator One of the JCR_OPERATOR_* constants
742 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
743 * @return string an SQL operator
744 */
745 protected function resolveOperator($operator) {
746 switch ($operator) {
747 case self::OPERATOR_EQUAL_TO_NULL:
748 $operator = 'IS';
749 break;
750 case self::OPERATOR_NOT_EQUAL_TO_NULL:
751 $operator = 'IS NOT';
752 break;
753 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_IN:
754 $operator = 'IN';
755 break;
756 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_EQUAL_TO:
757 $operator = '=';
758 break;
759 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_NOT_EQUAL_TO:
760 $operator = '!=';
761 break;
762 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LESS_THAN:
763 $operator = '<';
764 break;
765 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
766 $operator = '<=';
767 break;
768 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_GREATER_THAN:
769 $operator = '>';
770 break;
771 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
772 $operator = '>=';
773 break;
774 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LIKE:
775 $operator = 'LIKE';
776 break;
777 default:
778 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Unsupported operator encountered.', 1242816073);
779 }
780 return $operator;
781 }
782
783 /**
784 * @return \TYPO3\CMS\Frontend\Page\PageRepository
785 */
786 protected function getPageRepository() {
787 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
788 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
789 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
790 } else {
791 $this->pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
792 }
793 }
794
795 return $this->pageRepository;
796 }
797 }