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