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