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