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