2 namespace TYPO3\CMS\Extbase\Persistence\Generic\Storage
;
4 /***************************************************************
7 * (c) 2010-2012 Extbase Team (http://forge.typo3.org/projects/typo3v4-mvc)
8 * Extbase is a backport of TYPO3 Flow. All credits go to the TYPO3 Flow team.
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.
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.
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.
28 * This copyright notice MUST APPEAR in all copies of the script!
29 ***************************************************************/
33 class Typo3DbBackend
implements \TYPO3\CMS\Extbase\Persistence\Generic\Storage\BackendInterface
, \TYPO3\CMS\Core\SingletonInterface
{
35 const OPERATOR_EQUAL_TO_NULL
= 'operatorEqualToNull';
36 const OPERATOR_NOT_EQUAL_TO_NULL
= 'operatorNotEqualToNull';
39 * The TYPO3 database object
41 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
43 protected $databaseHandle;
46 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
48 protected $dataMapper;
51 * The TYPO3 page repository. Used for language and workspace overlay
53 * @var \TYPO3\CMS\Frontend\Page\PageRepository
55 protected $pageRepository;
58 * A first-level TypoScript configuration cache
62 protected $pageTSConfigCache = array();
65 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
67 protected $configurationManager;
70 * @var \TYPO3\CMS\Extbase\Service\CacheService
72 protected $cacheService;
75 * @var \TYPO3\CMS\Core\Cache\CacheManager
77 protected $cacheManager;
80 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
82 protected $tableColumnCache;
85 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
87 public function __construct() {
88 $this->databaseHandle
= $GLOBALS['TYPO3_DB'];
92 * @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
95 public function injectConfigurationManager(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
$configurationManager) {
96 $this->configurationManager
= $configurationManager;
100 * @param \TYPO3\CMS\Core\Cache\CacheManager $cacheManager
102 public function injectCacheManager(\TYPO3\CMS\Core\Cache\CacheManager
$cacheManager) {
103 $this->cacheManager
= $cacheManager;
111 public function initializeObject() {
112 $this->tableColumnCache
= $this->cacheManager
->getCache('extbase_typo3dbbackend_tablecolumns');
116 * Injects the DataMapper to map nodes to objects
118 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper
121 public function injectDataMapper(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
$dataMapper) {
122 $this->dataMapper
= $dataMapper;
126 * @param \TYPO3\CMS\Extbase\Service\CacheService $cacheService
129 public function injectCacheService(\TYPO3\CMS\Extbase\Service\CacheService
$cacheService) {
130 $this->cacheService
= $cacheService;
134 * Adds a row to the storage
136 * @param string $tableName The database table name
137 * @param array $row The row to be inserted
138 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
139 * @return int The uid of the inserted row
141 public function addRow($tableName, array $row, $isRelation = FALSE) {
144 $parameters = array();
145 if (isset($row['uid'])) {
148 foreach ($row as $columnName => $value) {
149 $fields[] = $columnName;
151 $parameters[] = $value;
153 $sqlString = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
154 $this->replacePlaceholders($sqlString, $parameters, $tableName);
155 // debug($sqlString,-2);
156 $this->databaseHandle
->sql_query($sqlString);
157 $this->checkSqlErrors($sqlString);
158 $uid = $this->databaseHandle
->sql_insert_id();
160 $this->clearPageCache($tableName, $uid);
162 return (integer) $uid;
166 * Updates a row in the storage
168 * @param string $tableName The database table name
169 * @param array $row The row to be updated
170 * @param boolean $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
171 * @throws \InvalidArgumentException
174 public function updateRow($tableName, array $row, $isRelation = FALSE) {
175 if (!isset($row['uid'])) {
176 throw new \
InvalidArgumentException('The given row must contain a value for "uid".');
178 $uid = (integer) $row['uid'];
181 $parameters = array();
182 foreach ($row as $columnName => $value) {
183 $fields[] = $columnName . '=?';
184 $parameters[] = $value;
186 $parameters[] = $uid;
187 $sqlString = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $fields) . ' WHERE uid=?';
188 $this->replacePlaceholders($sqlString, $parameters, $tableName);
189 // debug($sqlString,-2);
190 $returnValue = $this->databaseHandle
->sql_query($sqlString);
191 $this->checkSqlErrors($sqlString);
193 $this->clearPageCache($tableName, $uid);
199 * Deletes a row in the storage
201 * @param string $tableName The database table name
202 * @param array $identifier An array of identifier array('fieldname' => value). This array will be transformed to a WHERE clause
203 * @param boolean $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
206 public function removeRow($tableName, array $identifier, $isRelation = FALSE) {
207 $statement = 'DELETE FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
208 $this->replacePlaceholders($statement, $identifier, $tableName);
209 if (!$isRelation && isset($identifier['uid'])) {
210 $this->clearPageCache($tableName, $identifier['uid'], $isRelation);
212 // debug($statement, -2);
213 $returnValue = $this->databaseHandle
->sql_query($statement);
214 $this->checkSqlErrors($statement);
219 * Fetches row data from the database
221 * @param string $tableName
222 * @param array $identifier The Identifier of the row to fetch
223 * @return array|boolean
225 public function getRowByIdentifier($tableName, array $identifier) {
226 $statement = 'SELECT * FROM ' . $tableName . ' WHERE ' . $this->parseIdentifier($identifier);
227 $this->replacePlaceholders($statement, $identifier, $tableName);
228 // debug($statement,-2);
229 $res = $this->databaseHandle
->sql_query($statement);
230 $this->checkSqlErrors($statement);
231 $row = $this->databaseHandle
->sql_fetch_assoc($res);
232 if ($row !== FALSE) {
240 * @param array $identifier
243 protected function parseIdentifier(array $identifier) {
244 $fieldNames = array_keys($identifier);
245 $suffixedFieldNames = array();
246 foreach ($fieldNames as $fieldName) {
247 $suffixedFieldNames[] = $fieldName . '=?';
249 return implode(' AND ', $suffixedFieldNames);
253 * Returns the object data matching the $query.
255 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
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();
264 $parameters = array();
265 $statementParts = $this->parseQuery($query, $parameters);
266 $sql = $this->buildQuery($statementParts, $parameters);
269 if (is_array($statementParts && !empty($statementParts['tables'][0]))) {
270 $tableName = $statementParts['tables'][0];
272 $this->replacePlaceholders($sql, $parameters, $tableName);
274 $result = $this->databaseHandle
->sql_query($sql);
275 $this->checkSqlErrors($sql);
276 $rows = $this->getRowsFromResult($query->getSource(), $result);
277 $this->databaseHandle
->sql_free_result($result);
278 // Get language uid from querySettings.
279 // Ensure the backend handling is not broken (fallback to Get parameter 'L' if needed)
280 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows, $query->getQuerySettings());
281 // TODO: implement $objectData = $this->processObjectRecords($statementHandle);
286 * Returns the number of tuples matching the query.
288 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
289 * @throws Exception\BadConstraintException
290 * @return integer The number of matching tuples
292 public function getObjectCountByQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface
$query) {
293 $constraint = $query->getConstraint();
294 if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
) {
295 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);
297 $parameters = array();
298 $statementParts = $this->parseQuery($query, $parameters);
299 // Reset $statementParts for valid table return
300 reset($statementParts);
301 // if limit is set, we need to count the rows "manually" as COUNT(*) ignores LIMIT constraints
302 if (!empty($statementParts['limit'])) {
303 $statement = $this->buildQuery($statementParts, $parameters);
304 $this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
305 $result = $this->databaseHandle
->sql_query($statement);
306 $this->checkSqlErrors($statement);
307 $count = $this->databaseHandle
->sql_num_rows($result);
309 $statementParts['fields'] = array('COUNT(*)');
310 // having orderings without grouping is not compatible with non-MySQL DBMS
311 $statementParts['orderings'] = array();
312 if (isset($statementParts['keywords']['distinct'])) {
313 unset($statementParts['keywords']['distinct']);
314 $statementParts['fields'] = array('COUNT(DISTINCT ' . reset($statementParts['tables']) . '.uid)');
316 $statement = $this->buildQuery($statementParts, $parameters);
317 $this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
318 $result = $this->databaseHandle
->sql_query($statement);
319 $this->checkSqlErrors($statement);
320 $rows = $this->getRowsFromResult($query->getSource(), $result);
321 $count = current(current($rows));
323 $this->databaseHandle
->sql_free_result($result);
324 return (integer) $count;
328 * Parses the query and returns the SQL statement parts.
330 * @param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query The query
331 * @param array $parameters
332 * @return array The SQL statement parts
334 public function parseQuery(\TYPO3\CMS\Extbase\Persistence\QueryInterface
$query, array &$parameters) {
336 $sql['keywords'] = array();
337 $sql['tables'] = array();
338 $sql['unions'] = array();
339 $sql['fields'] = array();
340 $sql['where'] = array();
341 $sql['additionalWhereClause'] = array();
342 $sql['orderings'] = array();
343 $sql['limit'] = array();
344 $source = $query->getSource();
345 $this->parseSource($source, $sql);
346 $this->parseConstraint($query->getConstraint(), $source, $sql, $parameters);
347 $this->parseOrderings($query->getOrderings(), $source, $sql);
348 $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $sql);
349 $tableNames = array_unique(array_keys($sql['tables'] +
$sql['unions']));
350 foreach ($tableNames as $tableName) {
351 if (is_string($tableName) && strlen($tableName) > 0) {
352 $this->addAdditionalWhereClause($query->getQuerySettings(), $tableName, $sql);
359 * Returns the statement, ready to be executed.
361 * @param array $sql The SQL statement parts
362 * @return string The SQL statement
364 public function buildQuery(array $sql) {
365 $statement = 'SELECT ' . implode(' ', $sql['keywords']) . ' ' . implode(',', $sql['fields']) . ' FROM ' . implode(' ', $sql['tables']) . ' ' . implode(' ', $sql['unions']);
366 if (!empty($sql['where'])) {
367 $statement .= ' WHERE ' . implode('', $sql['where']);
368 if (!empty($sql['additionalWhereClause'])) {
369 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
371 } elseif (!empty($sql['additionalWhereClause'])) {
372 $statement .= ' WHERE ' . implode(' AND ', $sql['additionalWhereClause']);
374 if (!empty($sql['orderings'])) {
375 $statement .= ' ORDER BY ' . implode(', ', $sql['orderings']);
377 if (!empty($sql['limit'])) {
378 $statement .= ' LIMIT ' . $sql['limit'];
384 * Checks if a Value Object equal to the given Object exists in the data base
386 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The Value Object
387 * @return mixed The matching uid if an object was found, else FALSE
389 public function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject
$object) {
391 $parameters = array();
392 $dataMap = $this->dataMapper
->getDataMap(get_class($object));
393 $properties = $object->_getProperties();
394 foreach ($properties as $propertyName => $propertyValue) {
395 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
396 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
397 if ($propertyValue === NULL) {
398 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
400 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
401 $parameters[] = $this->getPlainValue($propertyValue);
406 $sql['additionalWhereClause'] = array();
407 $tableName = $dataMap->getTableName();
408 $this->addVisibilityConstraintStatement(new \TYPO3\CMS\Extbase\Persistence\Generic\
Typo3QuerySettings(), $tableName, $sql);
409 $statement = 'SELECT * FROM ' . $tableName;
410 $statement .= ' WHERE ' . implode(' AND ', $fields);
411 if (!empty($sql['additionalWhereClause'])) {
412 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
414 $this->replacePlaceholders($statement, $parameters, $tableName);
415 // debug($statement,-2);
416 $res = $this->databaseHandle
->sql_query($statement);
417 $this->checkSqlErrors($statement);
418 $row = $this->databaseHandle
->sql_fetch_assoc($res);
419 if ($row !== FALSE) {
420 return (integer) $row['uid'];
427 * Transforms a Query Source into SQL and parameter arrays
429 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
433 protected function parseSource(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
$source, array &$sql) {
434 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface
) {
435 $className = $source->getNodeTypeName();
436 $tableName = $this->dataMapper
->getDataMap($className)->getTableName();
437 $this->addRecordTypeConstraint($className, $sql);
438 $sql['fields'][$tableName] = $tableName . '.*';
439 $sql['tables'][$tableName] = $tableName;
440 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
) {
441 $this->parseJoin($source, $sql);
446 * Add a constraint to ensure that the record type of the returned tuples is matching the data type of the repository.
448 * @param string $className The class name
449 * @param array &$sql The query parts
452 protected function addRecordTypeConstraint($className, &$sql) {
453 if ($className !== NULL) {
454 $dataMap = $this->dataMapper
->getDataMap($className);
455 if ($dataMap->getRecordTypeColumnName() !== NULL) {
456 $recordTypes = array();
457 if ($dataMap->getRecordType() !== NULL) {
458 $recordTypes[] = $dataMap->getRecordType();
460 foreach ($dataMap->getSubclasses() as $subclassName) {
461 $subclassDataMap = $this->dataMapper
->getDataMap($subclassName);
462 if ($subclassDataMap->getRecordType() !== NULL) {
463 $recordTypes[] = $subclassDataMap->getRecordType();
466 if (count($recordTypes) > 0) {
467 $recordTypeStatements = array();
468 foreach ($recordTypes as $recordType) {
469 $tableName = $dataMap->getTableName();
470 $recordTypeStatements[] = $tableName . '.' . $dataMap->getRecordTypeColumnName() . '=' . $this->databaseHandle
->fullQuoteStr($recordType, $tableName);
472 $sql['additionalWhereClause'][] = '(' . implode(' OR ', $recordTypeStatements) . ')';
479 * Transforms a Join into SQL and parameter arrays
481 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface $join The join
482 * @param array &$sql The query parts
485 protected function parseJoin(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
$join, array &$sql) {
486 $leftSource = $join->getLeft();
487 $leftClassName = $leftSource->getNodeTypeName();
488 $this->addRecordTypeConstraint($leftClassName, $sql);
489 $leftTableName = $leftSource->getSelectorName();
490 // $sql['fields'][$leftTableName] = $leftTableName . '.*';
491 $rightSource = $join->getRight();
492 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
) {
493 $rightClassName = $rightSource->getLeft()->getNodeTypeName();
494 $rightTableName = $rightSource->getLeft()->getSelectorName();
496 $rightClassName = $rightSource->getNodeTypeName();
497 $rightTableName = $rightSource->getSelectorName();
498 $sql['fields'][$leftTableName] = $rightTableName . '.*';
500 $this->addRecordTypeConstraint($rightClassName, $sql);
501 $sql['tables'][$leftTableName] = $leftTableName;
502 $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
503 $joinCondition = $join->getJoinCondition();
504 if ($joinCondition instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition
) {
505 $column1Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
506 $column2Name = $this->dataMapper
->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
507 $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
509 if ($rightSource instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
) {
510 $this->parseJoin($rightSource, $sql);
515 * Transforms a constraint into SQL and parameter arrays
517 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint The constraint
518 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
519 * @param array &$sql The query parts
520 * @param array &$parameters The parameters that will replace the markers
523 protected function parseConstraint(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface
$constraint = NULL, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
$source, array &$sql, array &$parameters) {
524 if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface
) {
525 $sql['where'][] = '(';
526 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
527 $sql['where'][] = ' AND ';
528 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
529 $sql['where'][] = ')';
530 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface
) {
531 $sql['where'][] = '(';
532 $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
533 $sql['where'][] = ' OR ';
534 $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
535 $sql['where'][] = ')';
536 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface
) {
537 $sql['where'][] = 'NOT (';
538 $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
539 $sql['where'][] = ')';
540 } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
) {
541 $this->parseComparison($constraint, $source, $sql, $parameters);
546 * Parse a Comparison into SQL and parameter arrays.
548 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface $comparison The comparison to parse
549 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
550 * @param array &$sql SQL query parts to add to
551 * @param array &$parameters Parameters to bind to the SQL
552 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException
555 protected function parseComparison(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
$comparison, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
$source, array &$sql, array &$parameters) {
556 $operand1 = $comparison->getOperand1();
557 $operator = $comparison->getOperator();
558 $operand2 = $comparison->getOperand2();
559 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_IN
) {
562 foreach ($operand2 as $value) {
563 $value = $this->getPlainValue($value);
564 if ($value !== NULL) {
569 if ($hasValue === FALSE) {
570 $sql['where'][] = '1<>1';
572 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL, $operand2);
573 $parameters[] = $items;
575 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_CONTAINS
) {
576 if ($operand2 === NULL) {
577 $sql['where'][] = '1<>1';
579 $className = $source->getNodeTypeName();
580 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
581 $propertyName = $operand1->getPropertyName();
582 while (strpos($propertyName, '.') !== FALSE) {
583 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
585 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
586 $dataMap = $this->dataMapper
->getDataMap($className);
587 $columnMap = $dataMap->getColumnMap($propertyName);
588 $typeOfRelation = $columnMap instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap ?
$columnMap->getTypeOfRelation() : NULL;
589 if ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
590 $relationTableName = $columnMap->getRelationTableName();
591 $sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=' . $this->getPlainValue($operand2) . ')';
592 } elseif ($typeOfRelation === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap
::RELATION_HAS_MANY
) {
593 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
594 if (isset($parentKeyFieldName)) {
595 $childTableName = $columnMap->getChildTableName();
596 $sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=' . $this->getPlainValue($operand2) . ')';
598 $statement = 'FIND_IN_SET(' . $this->getPlainValue($operand2) . ',' . $tableName . '.' . $columnName . ')';
599 $sql['where'][] = $statement;
602 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\
RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
606 if ($operand2 === NULL) {
607 if ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_EQUAL_TO
) {
608 $operator = self
::OPERATOR_EQUAL_TO_NULL
;
609 } elseif ($operator === \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_NOT_EQUAL_TO
) {
610 $operator = self
::OPERATOR_NOT_EQUAL_TO_NULL
;
613 $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
614 $parameters[] = $this->getPlainValue($operand2);
619 * Returns a plain value, i.e. objects are flattened out if possible.
621 * @param mixed $input
622 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
625 protected function getPlainValue($input) {
626 if (is_array($input)) {
627 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\
UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
629 if ($input instanceof \DateTime
) {
630 return $input->format('U');
631 } elseif (is_object($input)) {
632 if ($input instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface
) {
633 return $input->getUid();
635 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);
637 } elseif (is_bool($input)) {
638 return $input === TRUE ?
1 : 0;
645 * Parse a DynamicOperand into SQL and parameter arrays.
647 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\DynamicOperandInterface $operand
648 * @param string $operator One of the JCR_OPERATOR_* constants
649 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
650 * @param array &$sql The query parts
651 * @param array &$parameters The parameters that will replace the markers
652 * @param string $valueFunction an optional SQL function to apply to the operand value
653 * @param null $operand2
656 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) {
657 if ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\LowerCaseInterface
) {
658 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
659 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\UpperCaseInterface
) {
660 $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
661 } elseif ($operand instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\PropertyValueInterface
) {
662 $propertyName = $operand->getPropertyName();
663 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface
) {
664 // FIXME Only necessary to differ from Join
665 $className = $source->getNodeTypeName();
666 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
667 while (strpos($propertyName, '.') !== FALSE) {
668 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
670 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
) {
671 $tableName = $source->getJoinCondition()->getSelector1Name();
673 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
674 $operator = $this->resolveOperator($operator);
676 if ($valueFunction === NULL) {
677 $constraintSQL .= (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
679 $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ?
$tableName . '.' : '') . $columnName . ') ' . $operator . ' ?';
681 $sql['where'][] = $constraintSQL;
688 * @param $propertyPath
690 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
691 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException
693 protected function addUnionStatement(&$className, &$tableName, &$propertyPath, array &$sql) {
694 $explodedPropertyPath = explode('.', $propertyPath, 2);
695 $propertyName = $explodedPropertyPath[0];
696 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
697 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
698 $columnMap = $this->dataMapper
->getDataMap($className)->getColumnMap($propertyName);
699 $parentKeyFieldName = $columnMap->getParentKeyFieldName();
700 $childTableName = $columnMap->getChildTableName();
702 if ($childTableName === NULL) {
703 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\
InvalidRelationConfigurationException('The relation information for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1353170925);
706 if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap
::RELATION_HAS_ONE
) {
707 if (isset($parentKeyFieldName)) {
708 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
710 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $columnName . '=' . $childTableName . '.uid';
712 $className = $this->dataMapper
->getType($className, $propertyName);
713 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap
::RELATION_HAS_MANY
) {
714 if (isset($parentKeyFieldName)) {
715 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
717 $onStatement = '(FIND_IN_SET(' . $childTableName . '.uid, ' . $tableName . '.' . $columnName . '))';
718 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $onStatement;
720 $className = $this->dataMapper
->getType($className, $propertyName);
721 } elseif ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap
::RELATION_HAS_AND_BELONGS_TO_MANY
) {
722 $relationTableName = $columnMap->getRelationTableName();
723 $sql['unions'][$relationTableName] = 'LEFT JOIN ' . $relationTableName . ' ON ' . $tableName . '.uid=' . $relationTableName . '.' . $columnMap->getParentKeyFieldName();
724 $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $relationTableName . '.' . $columnMap->getChildKeyFieldName() . '=' . $childTableName . '.uid';
725 $className = $this->dataMapper
->getType($className, $propertyName);
727 throw new \TYPO3\CMS\Extbase\Persistence\Generic\
Exception('Could not determine type of relation.', 1252502725);
729 // TODO check if there is another solution for this
730 $sql['keywords']['distinct'] = 'DISTINCT';
731 $propertyPath = $explodedPropertyPath[1];
732 $tableName = $childTableName;
736 * Returns the SQL operator for the given JCR operator type.
738 * @param string $operator One of the JCR_OPERATOR_* constants
739 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
740 * @return string an SQL operator
742 protected function resolveOperator($operator) {
744 case self
::OPERATOR_EQUAL_TO_NULL
:
747 case self
::OPERATOR_NOT_EQUAL_TO_NULL
:
748 $operator = 'IS NOT';
750 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_IN
:
753 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_EQUAL_TO
:
756 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_NOT_EQUAL_TO
:
759 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_LESS_THAN
:
762 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_LESS_THAN_OR_EQUAL_TO
:
765 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_GREATER_THAN
:
768 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_GREATER_THAN_OR_EQUAL_TO
:
771 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::OPERATOR_LIKE
:
775 throw new \TYPO3\CMS\Extbase\Persistence\Generic\
Exception('Unsupported operator encountered.', 1242816073);
781 * Replace query placeholders in a query part by the given
784 * @param string $sqlString The query part with placeholders
785 * @param array $parameters The parameters
786 * @param string $tableName
788 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
789 * @return string The query part with replaced placeholders
791 protected function replacePlaceholders(&$sqlString, array $parameters, $tableName = 'foo') {
792 // TODO profile this method again
793 if (substr_count($sqlString, '?') !== count($parameters)) {
794 throw new \TYPO3\CMS\Extbase\Persistence\Generic\
Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
797 foreach ($parameters as $parameter) {
798 $markPosition = strpos($sqlString, '?', $offset);
799 if ($markPosition !== FALSE) {
800 if ($parameter === NULL) {
802 } elseif (is_array($parameter) ||
$parameter instanceof \ArrayAccess ||
$parameter instanceof \Traversable
) {
804 foreach ($parameter as $item) {
805 $items[] = $this->databaseHandle
->fullQuoteStr($item, $tableName);
807 $parameter = '(' . implode(',', $items) . ')';
809 $parameter = $this->databaseHandle
->fullQuoteStr($parameter, $tableName);
811 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition +
1));
813 $offset = $markPosition +
strlen($parameter);
818 * Adds additional WHERE statements according to the query settings.
820 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
821 * @param string $tableName The table name to add the additional where clause for
825 protected function addAdditionalWhereClause(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface
$querySettings, $tableName, &$sql) {
826 $this->addVisibilityConstraintStatement($querySettings, $tableName, $sql);
827 if ($querySettings->getRespectSysLanguage()) {
828 $this->addSysLanguageStatement($tableName, $sql, $querySettings);
830 if ($querySettings->getRespectStoragePage()) {
831 $this->addPageIdStatement($tableName, $sql, $querySettings->getStoragePageIds());
836 * Builds the enable fields statement
838 * @param string $tableName The database table name
839 * @param array &$sql The query parts
841 * @deprecated since Extbase 6.0, will be removed in Extbase 6.2.
843 protected function addEnableFieldsStatement($tableName, array &$sql) {
844 \TYPO3\CMS\Core\Utility\GeneralUtility
::logDeprecatedFunction();
845 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
846 if ($this->getTypo3Mode() === 'FE') {
847 $statement = $this->getPageRepository()->enableFields($tableName);
849 // TYPO3_MODE === 'BE'
850 $statement = \TYPO3\CMS\Backend\Utility\BackendUtility
::deleteClause($tableName);
851 $statement .= \TYPO3\CMS\Backend\Utility\BackendUtility
::BEenableFields($tableName);
853 if (!empty($statement)) {
854 $statement = substr($statement, 5);
855 $sql['additionalWhereClause'][] = $statement;
861 * Adds enableFields and deletedClause to the query if necessary
863 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
864 * @param string $tableName The database table name
865 * @param array &$sql The query parts
868 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface
$querySettings, $tableName, array &$sql) {
870 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
871 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
872 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
873 $includeDeleted = $querySettings->getIncludeDeleted();
874 if ($this->getTypo3Mode() === 'FE') {
875 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
877 // TYPO3_MODE === 'BE'
878 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
880 if (!empty($statement)) {
881 $statement = strtolower(substr($statement, 1, 3)) === 'and' ?
substr($statement, 5) : $statement;
882 $sql['additionalWhereClause'][] = $statement;
888 * Returns constraint statement for frontend context
890 * @param string $tableName
891 * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
892 * @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.
893 * @param boolean $includeDeleted A flag indicating whether deleted records should be included
895 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
897 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored = array(), $includeDeleted) {
899 if ($ignoreEnableFields && !$includeDeleted) {
900 if (count($enableFieldsToBeIgnored)) {
901 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
902 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
904 $statement .= $this->getPageRepository()->deleteClause($tableName);
906 } elseif (!$ignoreEnableFields && !$includeDeleted) {
907 $statement .= $this->getPageRepository()->enableFields($tableName);
908 } elseif (!$ignoreEnableFields && $includeDeleted) {
909 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);
915 * Returns constraint statement for backend context
917 * @param string $tableName
918 * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
919 * @param boolean $includeDeleted A flag indicating whether deleted records should be included
922 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
924 if (!$ignoreEnableFields) {
925 $statement .= \TYPO3\CMS\Backend\Utility\BackendUtility
::BEenableFields($tableName);
927 if (!$includeDeleted) {
928 $statement .= \TYPO3\CMS\Backend\Utility\BackendUtility
::deleteClause($tableName);
934 * Builds the language field statement
936 * @param string $tableName The database table name
937 * @param array &$sql The query parts
938 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
941 protected function addSysLanguageStatement($tableName, array &$sql, $querySettings) {
942 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
943 if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
944 // Select all entries for the current language
945 $additionalWhereClause = $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (' . intval($querySettings->getSysLanguageUid()) . ',-1)';
946 // If any language is set -> get those entries which are not translated yet
947 // They will be removed by t3lib_page::getRecordOverlay if not matching overlay mode
948 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
949 && $querySettings->getSysLanguageUid() > 0
951 $additionalWhereClause .= ' OR (' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0' .
952 ' AND ' . $tableName . '.uid NOT IN (' . 'SELECT ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] .
953 ' FROM ' . $tableName .
954 ' WHERE ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] . '>0' .
955 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '>0';
957 // Add delete clause to ensure all entries are loaded
958 if (isset($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
959 $additionalWhereClause .= ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
961 $additionalWhereClause .= '))';
963 $sql['additionalWhereClause'][] = '(' . $additionalWhereClause . ')';
969 * Builds the page ID checking statement
971 * @param string $tableName The database table name
972 * @param array &$sql The query parts
973 * @param array $storagePageIds list of storage page ids
976 protected function addPageIdStatement($tableName, array &$sql, array $storagePageIds) {
977 $tableColumns = $this->tableColumnCache
->get($tableName);
978 if ($tableColumns === FALSE) {
979 $tableColumns = $this->databaseHandle
->admin_get_fields($tableName);
980 $this->tableColumnCache
->set($tableName, $tableColumns);
982 if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $tableColumns)) {
983 $sql['additionalWhereClause'][] = $tableName . '.pid IN (' . implode(', ', $storagePageIds) . ')';
988 * Transforms orderings into SQL.
990 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
991 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source
992 * @param array &$sql The query parts
993 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException
996 protected function parseOrderings(array $orderings, \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
$source, array &$sql) {
997 foreach ($orderings as $propertyName => $order) {
999 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface
::JCR_ORDER_ASCENDING
:
1001 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::ORDER_ASCENDING
:
1004 case \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelConstantsInterface
::JCR_ORDER_DESCENDING
:
1006 case \TYPO3\CMS\Extbase\Persistence\QueryInterface
::ORDER_DESCENDING
:
1010 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\
UnsupportedOrderException('Unsupported order encountered.', 1242816074);
1014 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface
) {
1015 $className = $source->getNodeTypeName();
1016 $tableName = $this->dataMapper
->convertClassNameToTableName($className);
1017 while (strpos($propertyName, '.') !== FALSE) {
1018 $this->addUnionStatement($className, $tableName, $propertyName, $sql);
1020 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
) {
1021 $tableName = $source->getLeft()->getSelectorName();
1023 $columnName = $this->dataMapper
->convertPropertyNameToColumnName($propertyName, $className);
1024 if (strlen($tableName) > 0) {
1025 $sql['orderings'][] = $tableName . '.' . $columnName . ' ' . $order;
1027 $sql['orderings'][] = $columnName . ' ' . $order;
1033 * Transforms limit and offset into SQL
1035 * @param integer $limit
1036 * @param integer $offset
1037 * @param array &$sql
1040 protected function parseLimitAndOffset($limit, $offset, array &$sql) {
1041 if ($limit !== NULL && $offset !== NULL) {
1042 $sql['limit'] = $offset . ', ' . $limit;
1043 } elseif ($limit !== NULL) {
1044 $sql['limit'] = $limit;
1049 * Transforms a Resource from a database query to an array of rows.
1051 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source (selector od join)
1052 * @param resource $result The result
1053 * @return array The result as an array of rows (tuples)
1055 protected function getRowsFromResult(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
$source, $result) {
1057 while ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
1058 if (is_array($row)) {
1059 // TODO Check if this is necessary, maybe the last line is enough
1060 $arrayKeys = range(0, count($row));
1061 array_fill_keys($arrayKeys, $row);
1069 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
1070 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
1072 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source The source (selector od join)
1073 * @param array $rows
1074 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
1075 * @param null|integer $workspaceUid
1078 protected function doLanguageAndWorkspaceOverlay(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
$source, array $rows, $querySettings, $workspaceUid = NULL) {
1079 if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface
) {
1080 $tableName = $source->getSelectorName();
1081 } elseif ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface
) {
1082 $tableName = $source->getRight()->getSelectorName();
1084 // If we do not have a table name here, we cannot do an overlay and return the original rows instead.
1085 if (isset($tableName)) {
1086 $pageRepository = $this->getPageRepository();
1087 if (is_object($GLOBALS['TSFE'])) {
1088 $languageMode = $GLOBALS['TSFE']->sys_language_mode
;
1089 if ($workspaceUid !== NULL) {
1090 $pageRepository->versioningWorkspaceId
= $workspaceUid;
1094 if ($workspaceUid === NULL) {
1095 $workspaceUid = $GLOBALS['BE_USER']->workspace
;
1097 $pageRepository->versioningWorkspaceId
= $workspaceUid;
1100 $overlayedRows = array();
1101 foreach ($rows as $row) {
1102 // If current row is a translation select its parent
1103 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
1104 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1105 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1107 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
1108 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
1110 $row = $this->databaseHandle
->exec_SELECTgetSingleRow(
1113 $tableName . '.uid=' . (integer) $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
1114 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
1118 $pageRepository->versionOL($tableName, $row, TRUE);
1119 if ($pageRepository->versioningPreview
&& isset($row['_ORIG_uid'])) {
1120 $row['uid'] = $row['_ORIG_uid'];
1122 if ($tableName == 'pages') {
1123 $row = $pageRepository->getPageOverlay($row, $querySettings->getSysLanguageUid());
1124 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1125 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
1127 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
1128 $overlayMode = $languageMode === 'strict' ?
'hideNonTranslated' : '';
1129 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getSysLanguageUid(), $overlayMode);
1132 if ($row !== NULL && is_array($row)) {
1133 $overlayedRows[] = $row;
1137 $overlayedRows = $rows;
1139 return $overlayedRows;
1143 * @return \TYPO3\CMS\Frontend\Page\PageRepository
1145 protected function getPageRepository() {
1146 if (!$this->pageRepository
instanceof \TYPO3\CMS\Frontend\Page\PageRepository
) {
1147 if ($this->getTypo3Mode() === 'FE' && is_object($GLOBALS['TSFE'])) {
1148 $this->pageRepository
= $GLOBALS['TSFE']->sys_page
;
1150 $this->pageRepository
= \TYPO3\CMS\Core\Utility\GeneralUtility
::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
1154 return $this->pageRepository
;
1158 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
1161 * @param string $sql The SQL statement
1162 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
1164 protected function checkSqlErrors($sql = '') {
1165 $error = $this->databaseHandle
->sql_error();
1166 if ($error !== '') {
1167 $error .= $sql ?
': ' . $sql : '';
1168 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\
SqlErrorException($error, 1247602160);
1173 * Clear the TYPO3 page cache for the given record.
1174 * If the record lies on a page, then we clear the cache of this page.
1175 * If the record has no PID column, we clear the cache of the current page as best-effort.
1177 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
1179 * @param string $tableName Table name of the record
1180 * @param integer $uid UID of the record
1183 protected function clearPageCache($tableName, $uid) {
1184 $frameworkConfiguration = $this->configurationManager
->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
::CONFIGURATION_TYPE_FRAMEWORK
);
1185 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
1187 // if disabled, return
1190 $pageIdsToClear = array();
1191 $storagePage = NULL;
1192 $columns = $this->databaseHandle
->admin_get_fields($tableName);
1193 if (array_key_exists('pid', $columns)) {
1194 $result = $this->databaseHandle
->exec_SELECTquery('pid', $tableName, 'uid=' . intval($uid));
1195 if ($row = $this->databaseHandle
->sql_fetch_assoc($result)) {
1196 $storagePage = $row['pid'];
1197 $pageIdsToClear[] = $storagePage;
1199 } elseif (isset($GLOBALS['TSFE'])) {
1200 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
1201 $storagePage = $GLOBALS['TSFE']->id
;
1202 $pageIdsToClear[] = $storagePage;
1204 if ($storagePage === NULL) {
1207 if (!isset($this->pageTSConfigCache
[$storagePage])) {
1208 $this->pageTSConfigCache
[$storagePage] = \TYPO3\CMS\Backend\Utility\BackendUtility
::getPagesTSconfig($storagePage);
1210 if (isset($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
1211 $clearCacheCommands = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', strtolower($this->pageTSConfigCache
[$storagePage]['TCEMAIN.']['clearCacheCmd']), 1);
1212 $clearCacheCommands = array_unique($clearCacheCommands);
1213 foreach ($clearCacheCommands as $clearCacheCommand) {
1214 if (\TYPO3\CMS\Core\Utility\MathUtility
::canBeInterpretedAsInteger($clearCacheCommand)) {
1215 $pageIdsToClear[] = $clearCacheCommand;
1220 foreach ($pageIdsToClear as $pageIdToClear) {
1221 $this->cacheService
->getPageIdStack()->push($pageIdToClear);
1226 * Returns the TYPO3 Mode ("FE" for front-end or "BE" for back-end). This method is necessary to enable unit tests to
1227 * mock this constant.
1231 protected function getTypo3Mode() {