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