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