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