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