2518698f925c379592cdc34c73ca738ecc55266a
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Persistence / Generic / Storage / Typo3DbBackend.php
1 <?php
2 namespace TYPO3\CMS\Extbase\Persistence\Generic\Storage;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * This class is a backport of the corresponding class of TYPO3 Flow.
8 * 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 textfile 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 * A Storage backend
32 */
33 class Typo3DbBackend implements \TYPO3\CMS\Extbase\Persistence\Generic\Storage\BackendInterface, \TYPO3\CMS\Core\SingletonInterface {
34
35 const OPERATOR_EQUAL_TO_NULL = 'operatorEqualToNull';
36 const OPERATOR_NOT_EQUAL_TO_NULL = 'operatorNotEqualToNull';
37 /**
38 * The TYPO3 database object
39 *
40 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
41 */
42 protected $databaseHandle;
43
44 /**
45 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
46 */
47 protected $dataMapper;
48
49 /**
50 * The TYPO3 page repository. Used for language and workspace overlay
51 *
52 * @var \TYPO3\CMS\Frontend\Page\PageRepository
53 */
54 protected $pageRepository;
55
56 /**
57 * A first-level TypoScript configuration cache
58 *
59 * @var array
60 */
61 protected $pageTSConfigCache = array();
62
63 /**
64 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
65 */
66 protected $configurationManager;
67
68 /**
69 * @var \TYPO3\CMS\Extbase\Service\CacheService
70 */
71 protected $cacheService;
72
73 /**
74 * @var \TYPO3\CMS\Core\Cache\CacheManager
75 */
76 protected $cacheManager;
77
78 /**
79 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
80 */
81 protected $tableColumnCache;
82
83 /**
84 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
85 */
86 public function __construct() {
87 $this->databaseHandle = $GLOBALS['TYPO3_DB'];
88 }
89
90 /**
91 * @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
92 * @return void
93 */
94 public function injectConfigurationManager(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager) {
95 $this->configurationManager = $configurationManager;
96 }
97
98 /**
99 * @param \TYPO3\CMS\Core\Cache\CacheManager $cacheManager
100 */
101 public function injectCacheManager(\TYPO3\CMS\Core\Cache\CacheManager $cacheManager) {
102 $this->cacheManager = $cacheManager;
103 }
104
105 /**
106 * Lifecycle method
107 *
108 * @return void
109 */
110 public function initializeObject() {
111 $this->tableColumnCache = $this->cacheManager->getCache('extbase_typo3dbbackend_tablecolumns');
112 }
113
114 /**
115 * Injects the DataMapper to map nodes to objects
116 *
117 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper
118 * @return void
119 */
120 public function injectDataMapper(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper) {
121 $this->dataMapper = $dataMapper;
122 }
123
124 /**
125 * @param \TYPO3\CMS\Extbase\Service\CacheService $cacheService
126 * @return void
127 */
128 public function injectCacheService(\TYPO3\CMS\Extbase\Service\CacheService $cacheService) {
129 $this->cacheService = $cacheService;
130 }
131
132 /**
133 * Adds a row to the storage
134 *
135 * @param string $tableName The database table name
136 * @param array $row The row to be inserted
137 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
138 * @return int The uid of the inserted row
139 */
140 public function addRow($tableName, array $row, $isRelation = FALSE) {
141 $fields = array();
142 $values = array();
143 $parameters = array();
144 if (isset($row['uid'])) {
145 unset($row['uid']);
146 }
147 foreach ($row as $columnName => $value) {
148 $fields[] = $columnName;
149 $values[] = '?';
150 $parameters[] = $value;
151 }
152 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
153 $this->replacePlaceholders($sqlString, $parameters);
154 // debug($sqlString,-2);
155 $this->databaseHandle->sql_query($sqlString);
156 $this->checkSqlErrors($sqlString);
157 $uid = $this->databaseHandle->sql_insert_id();
158 if (!$isRelation) {
159 $this->clearPageCache($tableName, $uid);
160 }
161 return (int) $uid;
162 }
163
164 /**
165 * Updates a row in the storage
166 *
167 * @param string $tableName The database table name
168 * @param array $row The row to be updated
169 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
170 * @throws \InvalidArgumentException
171 * @return bool
172 */
173 public function updateRow($tableName, array $row, $isRelation = FALSE) {
174 if (!isset($row['uid'])) {
175 throw new \InvalidArgumentException('The given row must contain a value for "uid".');
176 }
177 $uid = (int) $row['uid'];
178 unset($row['uid']);
179 $fields = array();
180 $parameters = array();
181 foreach ($row as $columnName => $value) {
182 $fields[] = $columnName . '=?';
183 $parameters[] = $value;
184 }
185 $parameters[] = $uid;
186 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
187 $this->replacePlaceholders($sqlString, $parameters);
188 // debug($sqlString,-2);
189 $returnValue = $this->databaseHandle->sql_query($sqlString);
190 $this->checkSqlErrors($sqlString);
191 if (!$isRelation) {
192 $this->clearPageCache($tableName, $uid);
193 }
194 return $returnValue;
195 }
196
197 /**
198 * Deletes a row in the storage
199 *
200 * @param string $tableName The database table name
201 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
202 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
203 * @return bool
204 */
205 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
206 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
207 $this->replacePlaceholders($statement, $identifier);
208 if (!$isRelation && isset($identifier['uid'])) {
209 $this->clearPageCache($tableName, $identifier['uid'], $isRelation);
210 }
211 // debug($statement, -2);
212 $returnValue = $this->databaseHandle->sql_query($statement);
213 $this->checkSqlErrors($statement);
214 return $returnValue;
215 }
216
217 /**
218 * Fetches row data from the database
219 *
220 * @param string $tableName
221 * @param array $identifier The Identifier of the row to fetch
222 * @return array|boolean
223 */
224 public function getRowByIdentifier($tableName, array $identifier) {
225 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
226 $this->replacePlaceholders($statement, $identifier);
227 // debug($statement,-2);
228 $res = $this->databaseHandle->sql_query($statement);
229 $this->checkSqlErrors($statement);
230 $row = $this->databaseHandle->sql_fetch_assoc($res);
231 if ($row !== FALSE) {
232 return $row;
233 } else {
234 return FALSE;
235 }
236 }
237
238 /**
239 * @param array $identifier
240 * @return string
241 */
242 protected function parseIdentifier(array $identifier) {
243 $fieldNames = array_keys($identifier);
244 $suffixedFieldNames = array();
245 foreach ($fieldNames as $fieldName) {
246 $suffixedFieldNames[] = $fieldName . '=?';
247 }
248 return implode(' AND ', $suffixedFieldNames);
249 }
250
251 /**
252 * Returns the object data matching the $query.
253 *
254 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
255 * @return array
256 * @author Karsten Dambekalns <karsten@typo3.org>
257 */
258 public function getObjectDataByQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
259 $statement = $query->getStatement();
260 if ($statement instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement) {
261 $sql = $statement->getStatement();
262 $parameters = $statement->getBoundVariables();
263 } else {
264 $parameters = array();
265 $statementParts = $this->parseQuery($query, $parameters);
266 $sql = $this->buildQuery($statementParts, $parameters);
267 }
268 $this->replacePlaceholders($sql, $parameters);
269 // debug($sql,-2);
270 $result = $this->databaseHandle->sql_query($sql);
271 $this->checkSqlErrors($sql);
272 $rows = $this->getRowsFromResult($query->getSource(), $result);
273 $this->databaseHandle->sql_free_result($result);
274 // Get language uid from querySettings.
275 // Ensure the backend handling is not broken (fallback to Get parameter 'L' if needed)
276 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows, $query->getQuerySettings());
277 // TODO: implement $objectData = $this->processObjectRecords($statementHandle);
278 return $rows;
279 }
280
281 /**
282 * Returns the number of tuples matching the query.
283 *
284 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
285 * @throws Exception\BadConstraintException
286 * @return integer The number of matching tuples
287 */
288 public function getObjectCountByQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query) {
289 $constraint = $query->getConstraint();
290 if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement) {
291 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException('Could not execute count on queries with a constraint of type TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\StatementInterface', 1256661045);
292 }
293 $parameters = array();
294 $statementParts = $this->parseQuery($query, $parameters);
295 // if limit is set, we need to count the rows "manually" as COUNT(*) ignores LIMIT constraints
296 if (!empty($statementParts['limit'])) {
297 $statement = $this->buildQuery($statementParts, $parameters);
298 $this->replacePlaceholders($statement, $parameters);
299 $result = $this->databaseHandle->sql_query($statement);
300 $this->checkSqlErrors($statement);
301 $count = $this->databaseHandle->sql_num_rows($result);
302 } else {
303 $statementParts['fields'] = array('COUNT(*)');
304 if (isset($statementParts['keywords']['distinct'])) {
305 unset($statementParts['keywords']['distinct']);
306 $statementParts['fields'] = array('COUNT(DISTINCT ' . reset($statementParts['tables']) . '.uid)');
307 }
308 $statement = $this->buildQuery($statementParts, $parameters);
309 $this->replacePlaceholders($statement, $parameters);
310 $result = $this->databaseHandle->sql_query($statement);
311 $this->checkSqlErrors($statement);
312 $rows = $this->getRowsFromResult($query->getSource(), $result);
313 $count = current(current($rows));
314 }
315 $this->databaseHandle->sql_free_result($result);
316 return (int) $count;
317 }
318
319 /**
320 * Parses the query and returns the SQL statement parts.
321 *
322 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query The query
323 * @param array $parameters
324 * @return array The SQL statement parts
325 */
326 public function parseQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface $query, array &$parameters) {
327 $sql = array();
328 $sql['keywords'] = array();
329 $sql['tables'] = array();
330 $sql['unions'] = array();
331 $sql['fields'] = array();
332 $sql['where'] = array();
333 $sql['additionalWhereClause'] = array();
334 $sql['orderings'] = array();
335 $sql['limit'] = array();
336 $source = $query->getSource();
337 $this->parseSource($source, $sql);
338 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters);
339 $this->parseOrderings($query->getOrderings(), $source, $sql);
340 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
341 $tableNames = array_unique(array_keys($sql['tables'] + $sql['unions']));
342 foreach ($tableNames as $tableName) {
343 if (is_string($tableName) && strlen($tableName) > 0) {
344 $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql);
345 }
346 }
347 return $sql;
348 }
349
350 /**
351 * Returns the statement, ready to be executed.
352 *
353 * @param array $sql The SQL statement parts
354 * @return string The SQL statement
355 */
356 public function buildQuery(array $sql) {
357 $statement = 'SELECT ' . implode(' ', $sql['keywords']) . ' ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']) . ' ' . implode(' ', $sql['unions']);
358 if (!empty($sql['where'])) {
359 $statement .= ' WHERE ' . implode('', $sql['where']);
360 if (!empty($sql['additionalWhereClause'])) {
361 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
362 }
363 } elseif (!empty($sql['additionalWhereClause'])) {
364 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
365 }
366 if (!empty($sql['orderings'])) {
367 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
368 }
369 if (!empty($sql['limit'])) {
370 $statement .= ' LIMIT ' . $sql['limit'];
371 }
372 return $statement;
373 }
374
375 /**
376 * Checks if a Value Object equal to the given Object exists in the data base
377 *
378 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The Value Object
379 * @return mixed The matching uid if an object was found, else FALSE
380 */
381 public function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object) {
382 $fields = array();
383 $parameters = array();
384 $dataMap = $this->dataMapper->getDataMap(get_class($object));
385 $properties = $object->_getProperties();
386 foreach ($properties as $propertyName => $propertyValue) {
387 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
388 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
389 if ($propertyValue === NULL) {
390 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
391 } else {
392 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
393 $parameters[] = $this->getPlainValue($propertyValue);
394 }
395 }
396 }
397 $sql = array();
398 $sql['additionalWhereClause'] = array();
399 $tableName = $dataMap->getTableName();
400 $this->addVisibilityConstraintStatement(new \TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings(), $tableName, $sql);
401 $statement = 'SELECT * FROM ' . $tableName;
402 $statement .= ' WHERE ' . implode(' AND ', $fields);
403 if (!empty($sql['additionalWhereClause'])) {
404 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
405 }
406 $this->replacePlaceholders($statement, $parameters);
407 // debug($statement,-2);
408 $res = $this->databaseHandle->sql_query($statement);
409 $this->checkSqlErrors($statement);
410 $row = $this->databaseHandle->sql_fetch_assoc($res);
411 if ($row !== FALSE) {
412 return (int) $row['uid'];
413 } else {
414 return FALSE;
415 }
416 }
417
418 /**
419 * Transforms a Query Source into SQL and parameter arrays
420 *
421 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
422 * @param array &$sql
423 * @return void
424 */
425 protected function parseSource(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
426 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
427 $className = $source->getNodeTypeName();
428 $tableName = $this->dataMapper->getDataMap($className)->getTableName();
429 $this->addRecordTypeConstraint($className, $sql);
430 $sql['fields'][$tableName] = $tableName . '.*';
431 $sql['tables'][$tableName] = $tableName;
432 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
433 $this->parseJoin($source, $sql);
434 }
435 }
436
437 /**
438 * Adda a constrint to ensure that the record type of the returned tuples is matching the data type of the repository.
439 *
440 * @param string $className The class name
441 * @param array &$sql The query parts
442 * @return void
443 */
444 protected function addRecordTypeConstraint($className, &$sql) {
445 if ($className !== NULL) {
446 $dataMap = $this->dataMapper->getDataMap($className);
447 if ($dataMap->getRecordTypeColumnName() !== NULL) {
448 $recordTypes = array();
449 if ($dataMap->getRecordType() !== NULL) {
450 $recordTypes[] = $dataMap->getRecordType();
451 }
452 foreach ($dataMap->getSubclasses() as $subclassName) {
453 $subclassDataMap = $this->dataMapper->getDataMap($subclassName);
454 if ($subclassDataMap->getRecordType() !== NULL) {
455 $recordTypes[] = $subclassDataMap->getRecordType();
456 }
457 }
458 if (count($recordTypes) > 0) {
459 $recordTypeStatements = array();
460 foreach ($recordTypes as $recordType) {
461 $recordTypeStatements[] = $dataMap->getTableName() . '.' . $dataMap->getRecordTypeColumnName() . '=' . $this->databaseHandle->fullQuoteStr($recordType, 'foo');
462 }
463 $sql['additionalWhereClause'][] = '(' . implode(' OR ', $recordTypeStatements) . ')';
464 }
465 }
466 }
467 }
468
469 /**
470 * Transforms a Join into SQL and parameter arrays
471 *
472 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join The join
473 * @param array &$sql The query parts
474 * @return void
475 */
476 protected function parseJoin(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join, array &$sql) {
477 $leftSource = $join->getLeft();
478 $leftClassName = $leftSource->getNodeTypeName();
479 $this->addRecordTypeConstraint($leftClassName, $sql);
480 $leftTableName = $leftSource->getSelectorName();
481 // $sql['fields'][$leftTableName] = $leftTableName . '.*';
482 $rightSource = $join->getRight();
483 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
484 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
485 $rightTableName = $rightSource->getLeft()->getSelectorName();
486 } else {
487 $rightClassName = $rightSource->getNodeTypeName();
488 $rightTableName = $rightSource->getSelectorName();
489 $sql['fields'][$leftTableName] = $rightTableName . '.*';
490 }
491 $this->addRecordTypeConstraint($rightClassName, $sql);
492 $sql['tables'][$leftTableName] = $leftTableName;
493 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
494 $joinCondition = $join->getJoinCondition();
495 if ($joinCondition instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition) {
496 $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
497 $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
498 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
499 }
500 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
501 $this->parseJoin($rightSource, $sql);
502 }
503 }
504
505 /**
506 * Transforms a constraint into SQL and parameter arrays
507 *
508 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint The constraint
509 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
510 * @param array &$sql The query parts
511 * @param array &$parameters The parameters that will replace the markers
512 * @return void
513 */
514 protected function parseConstraint(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint = NULL, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql, array &$parameters) {
515 if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface) {
516 $sql['where'][] = '(';
517 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
518 $sql['where'][] = ' AND ';
519 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
520 $sql['where'][] = ')';
521 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface) {
522 $sql['where'][] = '(';
523 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
524 $sql['where'][] = ' OR ';
525 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
526 $sql['where'][] = ')';
527 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface) {
528 $sql['where'][] = 'NOT (';
529 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
530 $sql['where'][] = ')';
531 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface) {
532 $this->parseComparison($constraint, $source, $sql, $parameters);
533 }
534 }
535
536 /**
537 * Parse a Comparison into SQL and parameter arrays.
538 *
539 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison The comparison to parse
540 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
541 * @param array &$sql SQL query parts to add to
542 * @param array &$parameters Parameters to bind to the SQL
543 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException
544 * @return void
545 */
546 protected function parseComparison(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql, array &$parameters) {
547 $operand1 = $comparison->getOperand1();
548 $operator = $comparison->getOperator();
549 $operand2 = $comparison->getOperand2();
550 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_IN) {
551 $items = array();
552 $hasValue = FALSE;
553 foreach ($operand2 as $value) {
554 $value = $this->getPlainValue($value);
555 if ($value !== NULL) {
556 $items[] = $value;
557 $hasValue = TRUE;
558 }
559 }
560 if ($hasValue === FALSE) {
561 $sql['where'][] = '1<>1';
562 } else {
563 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
564 $parameters[] = $items;
565 }
566 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_CONTAINS) {
567 if ($operand2 === NULL) {
568 $sql['where'][] = '1<>1';
569 } else {
570 $className = $source->getNodeTypeName();
571 $tableName = $this->dataMapper->convertClassNameToTableName($className);
572 $propertyName = $operand1->getPropertyName();
573 while (strpos($propertyName, '.') !== FALSE) {
574 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
575 }
576 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
577 $dataMap = $this->dataMapper->getDataMap($className);
578 $columnMap = $dataMap->getColumnMap($propertyName);
579 $typeOfRelation = $columnMap instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap ? $columnMap->getTypeOfRelation() : NULL;
580 if ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
581 $relationTableName = $columnMap->getRelationTableName();
582 $sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=' . $this->getPlainValue($operand2) . ')';
583 } elseif ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
584 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
585 if (isset($parentKeyFieldName)) {
586 $childTableName = $columnMap->getChildTableName();
587 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
588 } else {
589 $statement = 'FIND_IN_SET(' . $this->getPlainValue($operand2) . ',' . $tableName . '.' . $columnName . ')';
590 $sql['where'][] = $statement;
591 }
592 } else {
593 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
594 }
595 }
596 } else {
597 if ($operand2 === NULL) {
598 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_EQUAL_TO) {
599 $operator = self::OPERATOR_EQUAL_TO_NULL;
600 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_NOT_EQUAL_TO) {
601 $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
602 }
603 }
604 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
605 $parameters[] = $this->getPlainValue($operand2);
606 }
607 }
608
609 /**
610 * Returns a plain value, i.e. objects are flattened out if possible.
611 *
612 * @param mixed $input
613 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
614 * @return mixed
615 */
616 protected function getPlainValue($input) {
617 if (is_array($input)) {
618 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
619 }
620 if ($input instanceof \DateTime) {
621 return $input->format('U');
622 } elseif (is_object($input)) {
623 if ($input instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
624 return $input->getUid();
625 } else {
626 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An object of class "' . get_class($input) . '" could not be converted to a plain value.', 1274799934);
627 }
628 } elseif (is_bool($input)) {
629 return $input === TRUE ? 1 : 0;
630 } else {
631 return $input;
632 }
633 }
634
635 /**
636 * Parse a DynamicOperand into SQL and parameter arrays.
637 *
638 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\DynamicOperandInterface $operand
639 * @param string $operator One of the JCR_OPERATOR_* constants
640 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
641 * @param array &$sql The query parts
642 * @param array &$parameters The parameters that will replace the markers
643 * @param string $valueFunction an optional SQL function to apply to the operand value
644 * @param null $operand2
645 * @return void
646 */
647 protected function parseDynamicOperand(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\DynamicOperandInterface $operand, $operator, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL, $operand2 = NULL) {
648 if ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\LowerCaseInterface) {
649 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
650 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\UpperCaseInterface) {
651 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
652 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\PropertyValueInterface) {
653 $propertyName = $operand->getPropertyName();
654 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
655 // FIXME Only necessary to differ from Join
656 $className = $source->getNodeTypeName();
657 $tableName = $this->dataMapper->convertClassNameToTableName($className);
658 while (strpos($propertyName, '.') !== FALSE) {
659 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
660 }
661 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
662 $tableName = $source->getJoinCondition()->getSelector1Name();
663 }
664 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
665 $operator = $this->resolveOperator($operator);
666 $constraintSQL = '';
667 if ($valueFunction === NULL) {
668 $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
669 } else {
670 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ') ' . $operator . ' ?';
671 }
672 $sql['where'][] = $constraintSQL;
673 }
674 }
675
676 /**
677 * @param $className
678 * @param $tableName
679 * @param $propertyPath
680 * @param array $sql
681 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
682 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException
683 */
684 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
685 $explodedPropertyPath = explode('.', $propertyPath, 2);
686 $propertyName = $explodedPropertyPath[0];
687 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
688 $tableName = $this->dataMapper->convertClassNameToTableName($className);
689 $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
690 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
691 $childTableName = $columnMap->getChildTableName();
692
693 if ($childTableName === NULL) {
694 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException('The relation information for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1353170925);
695 }
696
697 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_ONE) {
698 if (isset($parentKeyFieldName)) {
699 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
700 } else {
701 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
702 }
703 $className = $this->dataMapper->getType($className, $propertyName);
704 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY) {
705 if (isset($parentKeyFieldName)) {
706 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
707 } else {
708 $onStatement = '(FIND_IN_SET(' . $childTableName . '.uid, ' . $tableName . '.' . $columnName . '))';
709 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $onStatement;
710 }
711 $className = $this->dataMapper->getType($className, $propertyName);
712 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
713 $relationTableName = $columnMap->getRelationTableName();
714 $sql['unions'][$relationTableName] = 'LEFT JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.' . $columnMap->getParentKeyFieldName();
715 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $relationTableName . '.' . $columnMap->getChildKeyFieldName() . '=' . $childTableName . '.uid';
716 $className = $this->dataMapper->getType($className, $propertyName);
717 } else {
718 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Could not determine type of relation.', 1252502725);
719 }
720 // TODO check if there is another solution for this
721 $sql['keywords']['distinct'] = 'DISTINCT';
722 $propertyPath = $explodedPropertyPath[1];
723 $tableName = $childTableName;
724 }
725
726 /**
727 * Returns the SQL operator for the given JCR operator type.
728 *
729 * @param string $operator One of the JCR_OPERATOR_* constants
730 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
731 * @return string an SQL operator
732 */
733 protected function resolveOperator($operator) {
734 switch ($operator) {
735 case self::OPERATOR_EQUAL_TO_NULL:
736 $operator = 'IS';
737 break;
738 case self::OPERATOR_NOT_EQUAL_TO_NULL:
739 $operator = 'IS NOT';
740 break;
741 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_IN:
742 $operator = 'IN';
743 break;
744 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_EQUAL_TO:
745 $operator = '=';
746 break;
747 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_NOT_EQUAL_TO:
748 $operator = '!=';
749 break;
750 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LESS_THAN:
751 $operator = '<';
752 break;
753 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
754 $operator = '<=';
755 break;
756 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_GREATER_THAN:
757 $operator = '>';
758 break;
759 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
760 $operator = '>=';
761 break;
762 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::OPERATOR_LIKE:
763 $operator = 'LIKE';
764 break;
765 default:
766 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Unsupported operator encountered.', 1242816073);
767 }
768 return $operator;
769 }
770
771 /**
772 * Replace query placeholders in a query part by the given
773 * parameters.
774 *
775 * @param string $sqlString The query part with placeholders
776 * @param array $parameters The parameters
777 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
778 * @return string The query part with replaced placeholders
779 */
780 protected function replacePlaceholders(&$sqlString, array $parameters) {
781 // TODO profile this method again
782 if (substr_count($sqlString, '?') !== count($parameters)) {
783 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
784 }
785 $offset = 0;
786 foreach ($parameters as $parameter) {
787 $markPosition = strpos($sqlString, '?', $offset);
788 if ($markPosition !== FALSE) {
789 if ($parameter === NULL) {
790 $parameter = 'NULL';
791 } elseif (is_array($parameter) || $parameter instanceof \ArrayAccess || $parameter instanceof \Traversable) {
792 $items = array();
793 foreach ($parameter as $item) {
794 $items[] = $this->databaseHandle->fullQuoteStr($item, 'foo');
795 }
796 $parameter = '(' . implode(',', $items) . ')';
797 } else {
798 $parameter = $this->databaseHandle->fullQuoteStr($parameter, 'foo');
799 }
800 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition + 1));
801 }
802 $offset = $markPosition + strlen($parameter);
803 }
804 }
805
806 /**
807 * Adds additional WHERE statements according to the query settings.
808 *
809 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
810 * @param string $tableName The table name to add the additional where clause for
811 * @param string $sql
812 * @return void
813 */
814 protected function addAdditionalWhereClause(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, &$sql) {
815 $this->addVisibilityConstraintStatement($querySettings, $tableName, $sql);
816 if ($querySettings->getRespectSysLanguage()) {
817 $this->addSysLanguageStatement($tableName, $sql, $querySettings);
818 }
819 if ($querySettings->getRespectStoragePage()) {
820 $this->addPageIdStatement($tableName, $sql, $querySettings->getStoragePageIds());
821 }
822 }
823
824 /**
825 * Builds the enable fields statement
826 *
827 * @param string $tableName The database table name
828 * @param array &$sql The query parts
829 * @return void
830 * @deprecated since Extbase 6.0, will be removed in Extbase 6.2.
831 */
832 protected function addEnableFieldsStatement($tableName, array &$sql) {
833 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
834 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
835 if ($this->getTypo3Mode() === 'FE') {
836 $statement = $this->getPageRepository()->enableFields($tableName);
837 } else {
838 // TYPO3_MODE === 'BE'
839 $statement = \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($tableName);
840 $statement .= \TYPO3\CMS\Backend\Utility\BackendUtility::BEenableFields($tableName);
841 }
842 if (!empty($statement)) {
843 $statement = substr($statement, 5);
844 $sql['additionalWhereClause'][] = $statement;
845 }
846 }
847 }
848
849 /**
850 * Adds enableFields and deletedClause to the query if necessary
851 *
852 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
853 * @param string $tableName The database table name
854 * @param array &$sql The query parts
855 * @return void
856 */
857 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, array &$sql) {
858 $statement = '';
859 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
860 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
861 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
862 $includeDeleted = $querySettings->getIncludeDeleted();
863 if ($this->getTypo3Mode() === 'FE') {
864 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
865 } else {
866 // TYPO3_MODE === 'BE'
867 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
868 }
869 if (!empty($statement)) {
870 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
871 $sql['additionalWhereClause'][] = $statement;
872 }
873 }
874 }
875
876 /**
877 * Returns constraint statement for frontend context
878 *
879 * @param string $tableName
880 * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
881 * @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.
882 * @param boolean $includeDeleted A flag indicating whether deleted records should be included
883 * @return string
884 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
885 */
886 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored = array(), $includeDeleted) {
887 $statement = '';
888 if ($ignoreEnableFields && !$includeDeleted) {
889 if (count($enableFieldsToBeIgnored)) {
890 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
891 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
892 } else {
893 $statement .= $this->getPageRepository()->deleteClause($tableName);
894 }
895 } elseif (!$ignoreEnableFields && !$includeDeleted) {
896 $statement .= $this->getPageRepository()->enableFields($tableName);
897 } elseif (!$ignoreEnableFields && $includeDeleted) {
898 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);
899 }
900 return $statement;
901 }
902
903 /**
904 * Returns constraint statement for backend context
905 *
906 * @param string $tableName
907 * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
908 * @param boolean $includeDeleted A flag indicating whether deleted records should be included
909 * @return string
910 */
911 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
912 $statement = '';
913 if (!$ignoreEnableFields) {
914 $statement .= \TYPO3\CMS\Backend\Utility\BackendUtility::BEenableFields($tableName);
915 }
916 if (!$includeDeleted) {
917 $statement .= \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($tableName);
918 }
919 return $statement;
920 }
921
922 /**
923 * Builds the language field statement
924 *
925 * @param string $tableName The database table name
926 * @param array &$sql The query parts
927 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
928 * @return void
929 */
930 protected function addSysLanguageStatement($tableName, array &$sql, $querySettings) {
931 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
932 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
933 // Select all entries for the current language
934 $additionalWhereClause = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (' . intval($querySettings->getSysLanguageUid()) . ',-1)';
935 // If any language is set -> get those entries which are not translated yet
936 // They will be removed by t3lib_page::getRecordOverlay if not matching overlay mode
937 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
938 && $querySettings->getSysLanguageUid() > 0
939 ) {
940 $additionalWhereClause .= ' OR (' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0' .
941 ' AND ' . $tableName . '.uid NOT IN (' . 'SELECT ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] .
942 ' FROM ' . $tableName .
943 ' WHERE ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] . '>0' .
944 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '>0';
945
946 // Add delete clause to ensure all entries are loaded
947 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
948 $additionalWhereClause .= ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
949 }
950 $additionalWhereClause .= '))';
951 }
952 $sql['additionalWhereClause'][] = '(' . $additionalWhereClause . ')';
953 }
954 }
955 }
956
957 /**
958 * Builds the page ID checking statement
959 *
960 * @param string $tableName The database table name
961 * @param array &$sql The query parts
962 * @param array $storagePageIds list of storage page ids
963 * @return void
964 */
965 protected function addPageIdStatement($tableName, array &$sql, array $storagePageIds) {
966 $tableColumns = $this->tableColumnCache->get($tableName);
967 if ($tableColumns === FALSE) {
968 $tableColumns = $this->databaseHandle->admin_get_fields($tableName);
969 $this->tableColumnCache->set($tableName, $tableColumns);
970 }
971 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $tableColumns)) {
972 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', $storagePageIds) . ')';
973 }
974 }
975
976 /**
977 * Transforms orderings into SQL.
978 *
979 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
980 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
981 * @param array &$sql The query parts
982 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException
983 * @return void
984 */
985 protected function parseOrderings(array $orderings, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array &$sql) {
986 foreach ($orderings as $propertyName => $order) {
987 switch ($order) {
988 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface::JCR_ORDER_ASCENDING:
989
990 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING:
991 $order = 'ASC';
992 break;
993 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface::JCR_ORDER_DESCENDING:
994
995 case \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING:
996 $order = 'DESC';
997 break;
998 default:
999 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException('Unsupported order encountered.', 1242816074);
1000 }
1001 $className = '';
1002 $tableName = '';
1003 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
1004 $className = $source->getNodeTypeName();
1005 $tableName = $this->dataMapper->convertClassNameToTableName($className);
1006 while (strpos($propertyName, '.') !== FALSE) {
1007 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
1008 }
1009 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
1010 $tableName = $source->getLeft()->getSelectorName();
1011 }
1012 $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
1013 if (strlen($tableName) > 0) {
1014 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
1015 } else {
1016 $sql['orderings'][] = $columnName . ' ' . $order;
1017 }
1018 }
1019 }
1020
1021 /**
1022 * Transforms limit and offset into SQL
1023 *
1024 * @param int $limit
1025 * @param int $offset
1026 * @param array &$sql
1027 * @return void
1028 */
1029 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
1030 if ($limit !== NULL && $offset !== NULL) {
1031 $sql['limit'] = $offset . ', ' . $limit;
1032 } elseif ($limit !== NULL) {
1033 $sql['limit'] = $limit;
1034 }
1035 }
1036
1037 /**
1038 * Transforms a Resource from a database query to an array of rows.
1039 *
1040 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source (selector od join)
1041 * @param resource $result The result
1042 * @return array The result as an array of rows (tuples)
1043 */
1044 protected function getRowsFromResult(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, $result) {
1045 $rows = array();
1046 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
1047 if (is_array($row)) {
1048 // TODO Check if this is necessary, maybe the last line is enough
1049 $arrayKeys = range(0, count($row));
1050 array_fill_keys($arrayKeys, $row);
1051 $rows[] = $row;
1052 }
1053 }
1054 return $rows;
1055 }
1056
1057 /**
1058 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
1059 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
1060 *
1061 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source (selector od join)
1062 * @param array $rows
1063 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
1064 * @param null|integer $workspaceUid
1065 * @return array
1066 */
1067 protected function doLanguageAndWorkspaceOverlay(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source, array $rows, $querySettings, $workspaceUid = NULL) {
1068 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
1069 $tableName = $source->getSelectorName();
1070 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface) {
1071 $tableName = $source->getRight()->getSelectorName();
1072 }
1073 // If we do not have a table name here, we cannot do an overlay and return the original rows instead.
1074 if (isset($tableName)) {
1075 $pageRepository = $this->getPageRepository();
1076 if (is_object($GLOBALS['TSFE'])) {
1077 $languageMode = $GLOBALS['TSFE']->sys_language_mode;
1078 if ($workspaceUid !== NULL) {
1079 $pageRepository->versioningWorkspaceId = $workspaceUid;
1080 }
1081 } else {
1082 $languageMode = '';
1083 if ($workspaceUid === NULL) {
1084 $workspaceUid = $GLOBALS['BE_USER']->workspace;
1085 }
1086 $pageRepository->versioningWorkspaceId = $workspaceUid;
1087 }
1088
1089 $overlayedRows = array();
1090 foreach ($rows as $row) {
1091 // If current row is a translation select its parent
1092 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
1093 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1094 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1095 ) {
1096 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
1097 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
1098 ) {
1099 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
1100 $tableName . '.*',
1101 $tableName,
1102 $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
1103 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
1104 );
1105 }
1106 }
1107 $pageRepository->versionOL($tableName, $row, TRUE);
1108 if ($pageRepository->versioningPreview && isset($row['_ORIG_uid'])) {
1109 $row['uid'] = $row['_ORIG_uid'];
1110 }
1111 if ($tableName == 'pages') {
1112 $row = $pageRepository->getPageOverlay($row, $querySettings->getSysLanguageUid());
1113 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1114 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
1115 ) {
1116 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
1117 $overlayMode = $languageMode === 'strict' ? 'hideNonTranslated' : '';
1118 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getSysLanguageUid(), $overlayMode);
1119 }
1120 }
1121 if ($row !== NULL && is_array($row)) {
1122 $overlayedRows[] = $row;
1123 }
1124 }
1125 } else {
1126 $overlayedRows = $rows;
1127 }
1128 return $overlayedRows;
1129 }
1130
1131 /**
1132 * @return \TYPO3\CMS\Frontend\Page\PageRepository
1133 */
1134 protected function getPageRepository() {
1135 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
1136 if ($this->getTypo3Mode() === 'FE' && is_object($GLOBALS['TSFE'])) {
1137 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
1138 } else {
1139 $this->pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
1140 }
1141 }
1142
1143 return $this->pageRepository;
1144 }
1145
1146 /**
1147 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
1148 *
1149 * @return void
1150 * @param string $sql The SQL statement
1151 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
1152 */
1153 protected function checkSqlErrors($sql = '') {
1154 $error = $this->databaseHandle->sql_error();
1155 if ($error !== '') {
1156 $error .= $sql ? ': ' . $sql : '';
1157 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException($error, 1247602160);
1158 }
1159 }
1160
1161 /**
1162 * Clear the TYPO3 page cache for the given record.
1163 * If the record lies on a page, then we clear the cache of this page.
1164 * If the record has no PID column, we clear the cache of the current page as best-effort.
1165 *
1166 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
1167 *
1168 * @param string $tableName Table name of the record
1169 * @param integer $uid UID of the record
1170 * @return void
1171 */
1172 protected function clearPageCache($tableName, $uid) {
1173 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
1174 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
1175
1176 } else {
1177 // if disabled, return
1178 return;
1179 }
1180 $pageIdsToClear = array();
1181 $storagePage = NULL;
1182 $columns = $this->databaseHandle->admin_get_fields($tableName);
1183 if (array_key_exists('pid', $columns)) {
1184 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid=' . intval($uid));
1185 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
1186 $storagePage = $row['pid'];
1187 $pageIdsToClear[] = $storagePage;
1188 }
1189 } elseif (isset($GLOBALS['TSFE'])) {
1190 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
1191 $storagePage = $GLOBALS['TSFE']->id;
1192 $pageIdsToClear[] = $storagePage;
1193 }
1194 if ($storagePage === NULL) {
1195 return;
1196 }
1197 if (!isset($this->pageTSConfigCache[$storagePage])) {
1198 $this->pageTSConfigCache[$storagePage] = \TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig($storagePage);
1199 }
1200 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
1201 $clearCacheCommands = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), 1);
1202 $clearCacheCommands = array_unique($clearCacheCommands);
1203 foreach ($clearCacheCommands as $clearCacheCommand) {
1204 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
1205 $pageIdsToClear[] = $clearCacheCommand;
1206 }
1207 }
1208 }
1209 // TODO check if we can hand this over to the Dispatcher to clear the page only once, this will save around 10% time while inserting and updating
1210 $this->cacheService->clearPageCache($pageIdsToClear);
1211 }
1212
1213 /**
1214 * Returns the TYPO3 Mode ("FE" for front-end or "BE" for back-end). This method is necessary to enable unit tests to
1215 * mock this constant.
1216 *
1217 * @return string
1218 */
1219 protected function getTypo3Mode() {
1220 return TYPO3_MODE;
1221 }
1222
1223 }
1224
1225
1226 ?>