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