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