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