[CLEANUP] Remove redundant code in Persistence
[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 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Extbase\Persistence\Generic\Qom;
19 use TYPO3\CMS\Extbase\Persistence\QueryInterface;
20
21 /**
22 * A Storage backend
23 */
24 class Typo3DbBackend implements BackendInterface, \TYPO3\CMS\Core\SingletonInterface {
25
26 /**
27 * The TYPO3 database object
28 *
29 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
30 */
31 protected $databaseHandle;
32
33 /**
34 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
35 * @inject
36 */
37 protected $dataMapper;
38
39 /**
40 * The TYPO3 page repository. Used for language and workspace overlay
41 *
42 * @var \TYPO3\CMS\Frontend\Page\PageRepository
43 */
44 protected $pageRepository;
45
46 /**
47 * A first-level TypoScript configuration cache
48 *
49 * @var array
50 */
51 protected $pageTSConfigCache = array();
52
53 /**
54 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
55 * @inject
56 */
57 protected $configurationManager;
58
59 /**
60 * @var \TYPO3\CMS\Extbase\Service\CacheService
61 * @inject
62 */
63 protected $cacheService;
64
65 /**
66 * @var \TYPO3\CMS\Core\Cache\CacheManager
67 * @inject
68 */
69 protected $cacheManager;
70
71 /**
72 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
73 */
74 protected $tableColumnCache;
75
76 /**
77 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
78 */
79 protected $queryCache;
80
81 /**
82 * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
83 * @inject
84 */
85 protected $environmentService;
86
87 /**
88 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser
89 * @inject
90 */
91 protected $queryParser;
92
93 /**
94 * A first level cache for queries during runtime
95 *
96 * @var array
97 */
98 protected $queryRuntimeCache = array();
99
100 /**
101 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
102 */
103 public function __construct() {
104 $this->databaseHandle = $GLOBALS['TYPO3_DB'];
105 }
106
107 /**
108 * Lifecycle method
109 *
110 * @return void
111 */
112 public function initializeObject() {
113 $this->tableColumnCache = $this->cacheManager->getCache('extbase_typo3dbbackend_tablecolumns');
114 $this->queryCache = $this->cacheManager->getCache('extbase_typo3dbbackend_queries');
115 }
116
117 /**
118 * Adds a row to the storage
119 *
120 * @param string $tableName The database table name
121 * @param array $fieldValues The row to be inserted
122 * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
123 * @return integer The uid of the inserted row
124 */
125 public function addRow($tableName, array $fieldValues, $isRelation = FALSE) {
126 if (isset($fieldValues['uid'])) {
127 unset($fieldValues['uid']);
128 }
129
130 $this->databaseHandle->exec_INSERTquery($tableName, $fieldValues);
131 $this->checkSqlErrors();
132 $uid = $this->databaseHandle->sql_insert_id();
133
134 if (!$isRelation) {
135 $this->clearPageCache($tableName, $uid);
136 }
137 return (int)$uid;
138 }
139
140 /**
141 * Updates a row in the storage
142 *
143 * @param string $tableName The database table name
144 * @param array $fieldValues The row to be updated
145 * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
146 * @throws \InvalidArgumentException
147 * @return bool
148 */
149 public function updateRow($tableName, array $fieldValues, $isRelation = FALSE) {
150 if (!isset($fieldValues['uid'])) {
151 throw new \InvalidArgumentException('The given row must contain a value for "uid".');
152 }
153
154 $uid = (int)$fieldValues['uid'];
155 unset($fieldValues['uid']);
156
157 $updateSuccessful = $this->databaseHandle->exec_UPDATEquery($tableName, 'uid = '. $uid, $fieldValues);
158 $this->checkSqlErrors();
159
160 if (!$isRelation) {
161 $this->clearPageCache($tableName, $uid);
162 }
163
164 return $updateSuccessful;
165 }
166
167 /**
168 * Updates a relation row in the storage.
169 *
170 * @param string $tableName The database relation table name
171 * @param array $fieldValues The row to be updated
172 * @throws \InvalidArgumentException
173 * @return bool
174 */
175 public function updateRelationTableRow($tableName, array $fieldValues) {
176 if (!isset($fieldValues['uid_local']) && !isset($fieldValues['uid_foreign'])) {
177 throw new \InvalidArgumentException(
178 'The given fieldValues must contain a value for "uid_local" and "uid_foreign".', 1360500126
179 );
180 }
181
182 $where['uid_local'] = (int)$fieldValues['uid_local'];
183 $where['uid_foreign'] = (int)$fieldValues['uid_foreign'];
184 unset($fieldValues['uid_local']);
185 unset($fieldValues['uid_foreign']);
186
187 $updateSuccessful = $this->databaseHandle->exec_UPDATEquery(
188 $tableName,
189 $this->resolveWhereStatement($where, $tableName),
190 $fieldValues
191 );
192 $this->checkSqlErrors();
193
194 return $updateSuccessful;
195 }
196
197 /**
198 * Deletes a row in the storage
199 *
200 * @param string $tableName The database table name
201 * @param array $where An array of where array('fieldname' => value).
202 * @param bool $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
203 * @return bool
204 */
205 public function removeRow($tableName, array $where, $isRelation = FALSE) {
206 $deleteSuccessful = $this->databaseHandle->exec_DELETEquery(
207 $tableName,
208 $this->resolveWhereStatement($where, $tableName)
209 );
210 $this->checkSqlErrors();
211
212 if (!$isRelation && isset($where['uid'])) {
213 $this->clearPageCache($tableName, $where['uid']);
214 }
215
216 return $deleteSuccessful;
217 }
218
219 /**
220 * Fetches maximal value for given table column from database.
221 *
222 * @param string $tableName The database table name
223 * @param array $where An array of where array('fieldname' => value).
224 * @param string $columnName column name to get the max value from
225 * @return mixed the max value
226 */
227 public function getMaxValueFromTable($tableName, array $where, $columnName) {
228 $result = $this->databaseHandle->exec_SELECTgetSingleRow(
229 $columnName,
230 $tableName,
231 $this->resolveWhereStatement($where, $tableName),
232 '',
233 $columnName . ' DESC',
234 TRUE
235 );
236 $this->checkSqlErrors();
237
238 return $result[0];
239 }
240
241 /**
242 * Fetches row data from the database
243 *
244 * @param string $tableName
245 * @param array $where An array of where array('fieldname' => value).
246 * @return array|bool
247 */
248 public function getRowByIdentifier($tableName, array $where) {
249 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
250 '*',
251 $tableName,
252 $this->resolveWhereStatement($where, $tableName)
253 );
254 $this->checkSqlErrors();
255
256 return $row ?: FALSE;
257 }
258
259 /**
260 * Converts an array to an AND concatenated where statement
261 *
262 * @param array $where array('fieldName' => 'fieldValue')
263 * @param string $tableName table to use for escaping config
264 *
265 * @return string
266 */
267 protected function resolveWhereStatement(array $where, $tableName = 'foo') {
268 $whereStatement = array();
269
270 foreach ($where as $fieldName => $fieldValue) {
271 $whereStatement[] = $fieldName . ' = ' . $this->databaseHandle->fullQuoteStr($fieldValue, $tableName);
272 }
273
274 return implode(' AND ', $whereStatement);
275 }
276
277 /**
278 * Returns the object data matching the $query.
279 *
280 * @param QueryInterface $query
281 * @return array
282 */
283 public function getObjectDataByQuery(QueryInterface $query) {
284 $statement = $query->getStatement();
285 if ($statement instanceof Qom\Statement) {
286 $rows = $this->getObjectDataByRawQuery($statement);
287 } else {
288 $rows = $this->getRowsByStatementParts($query);
289 }
290
291 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows, $query->getQuerySettings());
292 return $rows;
293 }
294
295 /**
296 * Creates the parameters for the query methods of the database methods in the TYPO3 core, from an array
297 * that came from a parsed query.
298 *
299 * @param array $statementParts
300 * @return array
301 */
302 protected function createQueryCommandParametersFromStatementParts(array $statementParts) {
303 return array(
304 'selectFields' => implode(' ', $statementParts['keywords']) . ' ' . implode(',', $statementParts['fields']),
305 'fromTable' => implode(' ', $statementParts['tables']) . ' ' . implode(' ', $statementParts['unions']),
306 'whereClause' => (!empty($statementParts['where']) ? implode('', $statementParts['where']) : '1')
307 . (!empty($statementParts['additionalWhereClause'])
308 ? ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'])
309 : ''
310 ),
311 'orderBy' => (!empty($statementParts['orderings']) ? implode(', ', $statementParts['orderings']) : ''),
312 'limit' => ($statementParts['offset'] ? $statementParts['offset'] . ', ' : '')
313 . ($statementParts['limit'] ? $statementParts['limit'] : '')
314 );
315 }
316
317 /**
318 * Determines whether to use prepared statement or not and returns the rows from the corresponding method
319 *
320 * @param QueryInterface $query
321 * @return array
322 */
323 protected function getRowsByStatementParts(QueryInterface $query) {
324 if ($query->getQuerySettings()->getUsePreparedStatement()) {
325 list($statementParts, $parameters) = $this->getStatementParts($query, FALSE);
326 $rows = $this->getRowsFromPreparedDatabase($statementParts, $parameters);
327 } else {
328 list($statementParts) = $this->getStatementParts($query);
329 $rows = $this->getRowsFromDatabase($statementParts);
330 }
331
332 return $rows;
333 }
334
335 /**
336 * Fetches the rows directly from the database, not using prepared statement
337 *
338 * @param array $statementParts
339 * @return array the result
340 */
341 protected function getRowsFromDatabase(array $statementParts) {
342 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
343 $rows = $this->databaseHandle->exec_SELECTgetRows(
344 $queryCommandParameters['selectFields'],
345 $queryCommandParameters['fromTable'],
346 $queryCommandParameters['whereClause'],
347 '',
348 $queryCommandParameters['orderBy'],
349 $queryCommandParameters['limit']
350 );
351 $this->checkSqlErrors();
352
353 return $rows;
354 }
355
356 /**
357 * Fetches the rows from the database, using prepared statement
358 *
359 * @param array $statementParts
360 * @param array $parameters
361 * @return array the result
362 */
363 protected function getRowsFromPreparedDatabase(array $statementParts, array $parameters) {
364 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
365 $preparedStatement = $this->databaseHandle->prepare_SELECTquery(
366 $queryCommandParameters['selectFields'],
367 $queryCommandParameters['fromTable'],
368 $queryCommandParameters['whereClause'],
369 '',
370 $queryCommandParameters['orderBy'],
371 $queryCommandParameters['limit']
372 );
373
374 $preparedStatement->execute($parameters);
375 $rows = $preparedStatement->fetchAll();
376
377 $preparedStatement->free();
378 return $rows;
379 }
380
381 /**
382 * Returns the object data using a custom statement
383 *
384 * @param Qom\Statement $statement
385 * @return array
386 */
387 protected function getObjectDataByRawQuery(Qom\Statement $statement) {
388 $realStatement = $statement->getStatement();
389 $parameters = $statement->getBoundVariables();
390
391 if ($realStatement instanceof \TYPO3\CMS\Core\Database\PreparedStatement) {
392 $realStatement->execute($parameters);
393 $rows = $realStatement->fetchAll();
394
395 $realStatement->free();
396 } else {
397 /**
398 * @deprecated since 6.2, this block will be removed in two versions
399 * the deprecation log is in Qom\Statement
400 */
401 if (!empty($parameters)) {
402 $this->replacePlaceholders($realStatement, $parameters);
403 }
404
405 $result = $this->databaseHandle->sql_query($realStatement);
406 $this->checkSqlErrors();
407
408 $rows = array();
409 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
410 if (is_array($row)) {
411 $rows[] = $row;
412 }
413 }
414 $this->databaseHandle->sql_free_result($result);
415 }
416
417 return $rows;
418 }
419
420 /**
421 * Returns the number of tuples matching the query.
422 *
423 * @param QueryInterface $query
424 * @throws Exception\BadConstraintException
425 * @return integer The number of matching tuples
426 */
427 public function getObjectCountByQuery(QueryInterface $query) {
428 if ($query->getConstraint() instanceof Qom\Statement) {
429 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\\Statement', 1256661045);
430 }
431
432 list($statementParts) = $this->getStatementParts($query);
433
434 $fields = '*';
435 if (isset($statementParts['keywords']['distinct'])) {
436 $fields = 'DISTINCT ' . reset($statementParts['tables']) . '.uid';
437 }
438
439 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
440 $count = $this->databaseHandle->exec_SELECTcountRows(
441 $fields,
442 $queryCommandParameters['fromTable'],
443 $queryCommandParameters['whereClause']
444 );
445 $this->checkSqlErrors();
446
447 if ($statementParts['offset']) {
448 $count -= $statementParts['offset'];
449 }
450
451 if ($statementParts['limit']) {
452 $count = min($count, $statementParts['limit']);
453 }
454
455 return (int)max(0, $count);
456 }
457
458 /**
459 * Looks for the query in cache or builds it up otherwise
460 *
461 * @param QueryInterface $query
462 * @param bool $resolveParameterPlaceholders whether to resolve the parameters or leave the placeholders
463 * @return array
464 * @throws \RuntimeException
465 */
466 protected function getStatementParts($query, $resolveParameterPlaceholders = TRUE) {
467 /**
468 * The queryParser will preparse the query to get the query's hash and parameters.
469 * If the hash is found in the cache and useQueryCaching is enabled, extbase will
470 * then take the string representation from cache and build a prepared query with
471 * the parameters found.
472 *
473 * Otherwise extbase will parse the complete query, build the string representation
474 * and run a usual query.
475 */
476 list($queryHash, $parameters) = $this->queryParser->preparseQuery($query);
477
478 if ($query->getQuerySettings()->getUseQueryCache()) {
479 $statementParts = $this->getQueryCacheEntry($queryHash);
480 if ($queryHash && !$statementParts) {
481 $statementParts = $this->queryParser->parseQuery($query);
482 $this->setQueryCacheEntry($queryHash, $statementParts);
483 }
484 } else {
485 $statementParts = $this->queryParser->parseQuery($query);
486 }
487
488 if (!$statementParts) {
489 throw new \RuntimeException('Your query could not be built.', 1394453197);
490 }
491
492 $this->queryParser->addDynamicQueryParts($query->getQuerySettings(), $statementParts);
493
494 // Limit and offset are not cached to allow caching of pagebrowser queries.
495 $statementParts['limit'] = ((int)$query->getLimit() ?: NULL);
496 $statementParts['offset'] = ((int)$query->getOffset() ?: NULL);
497
498 if ($resolveParameterPlaceholders === TRUE) {
499 $statementParts = $this->resolveParameterPlaceholders($statementParts, $parameters);
500 }
501
502 return array($statementParts, $parameters);
503 }
504
505 /**
506 * Replaces the parameters in the queryStructure with given values
507 *
508 * @param array $statementParts
509 * @param array $parameters
510 * @return array
511 */
512 protected function resolveParameterPlaceholders(array $statementParts, array $parameters) {
513 $tableName = reset($statementParts['tables']) ?: 'foo';
514
515 foreach ($parameters as $parameterPlaceholder => $parameter) {
516 $parameter = $this->dataMapper->getPlainValue($parameter, NULL, array($this, 'quoteTextValueCallback'), array('tablename' => $tableName));
517 $statementParts['where'] = str_replace($parameterPlaceholder, $parameter, $statementParts['where']);
518 }
519
520 return $statementParts;
521 }
522
523 /**
524 * Will be called by the data mapper to quote string values.
525 *
526 * @param string $value The value to be quoted.
527 * @param array $parameters Additional parameters array currently containing the "tablename" key.
528 * @return string The quoted string.
529 */
530 public function quoteTextValueCallback($value, $parameters) {
531 return $this->databaseHandle->fullQuoteStr($value, $parameters['tablename']);
532 }
533
534 /**
535 * Checks if a Value Object equal to the given Object exists in the data base
536 *
537 * @param \TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object The Value Object
538 * @return mixed The matching uid if an object was found, else FALSE
539 * @todo this is the last monster in this persistence series. refactor!
540 */
541 public function getUidOfAlreadyPersistedValueObject(\TYPO3\CMS\Extbase\DomainObject\AbstractValueObject $object) {
542 $fields = array();
543 $parameters = array();
544 $dataMap = $this->dataMapper->getDataMap(get_class($object));
545 $properties = $object->_getProperties();
546 foreach ($properties as $propertyName => $propertyValue) {
547 // FIXME We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
548 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
549 if ($propertyValue === NULL) {
550 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . ' IS NULL';
551 } else {
552 $fields[] = $dataMap->getColumnMap($propertyName)->getColumnName() . '=?';
553 $parameters[] = $this->dataMapper->getPlainValue($propertyValue);
554 }
555 }
556 }
557 $sql = array();
558 $sql['additionalWhereClause'] = array();
559 $tableName = $dataMap->getTableName();
560 $this->addVisibilityConstraintStatement(new \TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings(), $tableName, $sql);
561 $statement = 'SELECT * FROM ' . $tableName;
562 $statement .= ' WHERE ' . implode(' AND ', $fields);
563 if (!empty($sql['additionalWhereClause'])) {
564 $statement .= ' AND ' . implode(' AND ', $sql['additionalWhereClause']);
565 }
566 $this->replacePlaceholders($statement, $parameters, $tableName);
567 // debug($statement,-2);
568 $res = $this->databaseHandle->sql_query($statement);
569 $this->checkSqlErrors($statement);
570 $row = $this->databaseHandle->sql_fetch_assoc($res);
571 if ($row !== FALSE) {
572 return (int)$row['uid'];
573 } else {
574 return FALSE;
575 }
576 }
577
578 /**
579 * Replace query placeholders in a query part by the given
580 * parameters.
581 *
582 * @param string &$sqlString The query part with placeholders
583 * @param array $parameters The parameters
584 * @param string $tableName
585 *
586 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception
587 * @deprecated since 6.2, will be removed two versions later
588 * @todo add deprecation notice after getUidOfAlreadyPersistedValueObject is adjusted
589 */
590 protected function replacePlaceholders(&$sqlString, array $parameters, $tableName = 'foo') {
591 // TODO profile this method again
592 if (substr_count($sqlString, '?') !== count($parameters)) {
593 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
594 }
595 $offset = 0;
596 foreach ($parameters as $parameter) {
597 $markPosition = strpos($sqlString, '?', $offset);
598 if ($markPosition !== FALSE) {
599 if ($parameter === NULL) {
600 $parameter = 'NULL';
601 } elseif (is_array($parameter) || $parameter instanceof \ArrayAccess || $parameter instanceof \Traversable) {
602 $items = array();
603 foreach ($parameter as $item) {
604 $items[] = $this->databaseHandle->fullQuoteStr($item, $tableName);
605 }
606 $parameter = '(' . implode(',', $items) . ')';
607 } else {
608 $parameter = $this->databaseHandle->fullQuoteStr($parameter, $tableName);
609 }
610 $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition + 1));
611 }
612 $offset = $markPosition + strlen($parameter);
613 }
614 }
615
616 /**
617 * Adds enableFields and deletedClause to the query if necessary
618 *
619 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings
620 * @param string $tableName The database table name
621 * @param array &$sql The query parts
622 * @return void
623 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
624 */
625 protected function addVisibilityConstraintStatement(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $tableName, array &$sql) {
626 $statement = '';
627 if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
628 $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
629 $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
630 $includeDeleted = $querySettings->getIncludeDeleted();
631 if ($this->environmentService->isEnvironmentInFrontendMode()) {
632 $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
633 } else {
634 // TYPO3_MODE === 'BE'
635 $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
636 }
637 if (!empty($statement)) {
638 $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
639 $sql['additionalWhereClause'][] = $statement;
640 }
641 }
642 }
643
644 /**
645 * Returns constraint statement for frontend context
646 *
647 * @param string $tableName
648 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
649 * @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.
650 * @param bool $includeDeleted A flag indicating whether deleted records should be included
651 * @return string
652 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException
653 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
654 */
655 protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored = array(), $includeDeleted) {
656 $statement = '';
657 if ($ignoreEnableFields && !$includeDeleted) {
658 if (count($enableFieldsToBeIgnored)) {
659 // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
660 $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
661 } else {
662 $statement .= $this->getPageRepository()->deleteClause($tableName);
663 }
664 } elseif (!$ignoreEnableFields && !$includeDeleted) {
665 $statement .= $this->getPageRepository()->enableFields($tableName);
666 } elseif (!$ignoreEnableFields && $includeDeleted) {
667 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);
668 }
669 return $statement;
670 }
671
672 /**
673 * Returns constraint statement for backend context
674 *
675 * @param string $tableName
676 * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
677 * @param bool $includeDeleted A flag indicating whether deleted records should be included
678 * @return string
679 * @todo remove after getUidOfAlreadyPersistedValueObject is adjusted, this was moved to queryParser
680 */
681 protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted) {
682 $statement = '';
683 if (!$ignoreEnableFields) {
684 $statement .= BackendUtility::BEenableFields($tableName);
685 }
686 if (!$includeDeleted) {
687 $statement .= BackendUtility::deleteClause($tableName);
688 }
689 return $statement;
690 }
691
692 /**
693 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
694 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
695 *
696 * @param Qom\SourceInterface $source The source (selector od join)
697 * @param array $rows
698 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
699 * @param null|integer $workspaceUid
700 * @return array
701 */
702 protected function doLanguageAndWorkspaceOverlay(Qom\SourceInterface $source, array $rows, \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $workspaceUid = NULL) {
703 if ($source instanceof Qom\SelectorInterface) {
704 $tableName = $source->getSelectorName();
705 } elseif ($source instanceof Qom\JoinInterface) {
706 $tableName = $source->getRight()->getSelectorName();
707 } else {
708 // No proper source, so we do not have a table name here
709 // we cannot do an overlay and return the original rows instead.
710 return $rows;
711 }
712
713 $pageRepository = $this->getPageRepository();
714 if (is_object($GLOBALS['TSFE'])) {
715 if ($workspaceUid !== NULL) {
716 $pageRepository->versioningWorkspaceId = $workspaceUid;
717 }
718 } else {
719 if ($workspaceUid === NULL) {
720 $workspaceUid = $GLOBALS['BE_USER']->workspace;
721 }
722 $pageRepository->versioningWorkspaceId = $workspaceUid;
723 }
724
725 $overlaidRows = array();
726 foreach ($rows as $row) {
727 // If current row is a translation select its parent
728 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
729 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
730 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
731 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
732 ) {
733 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
734 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
735 ) {
736 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
737 $tableName . '.*',
738 $tableName,
739 $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
740 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
741 );
742 }
743 }
744 $pageRepository->versionOL($tableName, $row, TRUE);
745 if ($pageRepository->versioningPreview && isset($row['_ORIG_uid'])) {
746 $row['uid'] = $row['_ORIG_uid'];
747 }
748 if ($tableName == 'pages') {
749 $row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
750 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
751 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
752 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
753 ) {
754 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
755 $overlayMode = $querySettings->getLanguageMode() === 'strict' ? 'hideNonTranslated' : '';
756 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
757 }
758 }
759 if ($row !== NULL && is_array($row)) {
760 $overlaidRows[] = $row;
761 }
762 }
763 return $overlaidRows;
764 }
765
766 /**
767 * @return \TYPO3\CMS\Frontend\Page\PageRepository
768 */
769 protected function getPageRepository() {
770 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
771 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
772 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
773 } else {
774 $this->pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
775 }
776 }
777
778 return $this->pageRepository;
779 }
780
781 /**
782 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
783 *
784 * @return void
785 * @param string $sql The SQL statement
786 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
787 */
788 protected function checkSqlErrors($sql = '') {
789 $error = $this->databaseHandle->sql_error();
790 if ($error !== '') {
791 $error .= $sql ? ': ' . $sql : '';
792 throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException($error, 1247602160);
793 }
794 }
795
796 /**
797 * Clear the TYPO3 page cache for the given record.
798 * If the record lies on a page, then we clear the cache of this page.
799 * If the record has no PID column, we clear the cache of the current page as best-effort.
800 *
801 * Much of this functionality is taken from t3lib_tcemain::clear_cache() which unfortunately only works with logged-in BE user.
802 *
803 * @param string $tableName Table name of the record
804 * @param integer $uid UID of the record
805 * @return void
806 */
807 protected function clearPageCache($tableName, $uid) {
808 $frameworkConfiguration = $this->configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
809 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
810 } else {
811 // if disabled, return
812 return;
813 }
814 $pageIdsToClear = array();
815 $storagePage = NULL;
816 $columns = $this->databaseHandle->admin_get_fields($tableName);
817 if (array_key_exists('pid', $columns)) {
818 $result = $this->databaseHandle->exec_SELECTquery('pid', $tableName, 'uid=' . (int)$uid);
819 if ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
820 $storagePage = $row['pid'];
821 $pageIdsToClear[] = $storagePage;
822 }
823 } elseif (isset($GLOBALS['TSFE'])) {
824 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
825 $storagePage = $GLOBALS['TSFE']->id;
826 $pageIdsToClear[] = $storagePage;
827 }
828 if ($storagePage === NULL) {
829 return;
830 }
831 if (!isset($this->pageTSConfigCache[$storagePage])) {
832 $this->pageTSConfigCache[$storagePage] = BackendUtility::getPagesTSconfig($storagePage);
833 }
834 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
835 $clearCacheCommands = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), TRUE);
836 $clearCacheCommands = array_unique($clearCacheCommands);
837 foreach ($clearCacheCommands as $clearCacheCommand) {
838 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
839 $pageIdsToClear[] = $clearCacheCommand;
840 }
841 }
842 }
843
844 foreach ($pageIdsToClear as $pageIdToClear) {
845 $this->cacheService->getPageIdStack()->push($pageIdToClear);
846 }
847 }
848
849 /**
850 * Finds and returns a variable value from the query cache.
851 *
852 * @param string $entryIdentifier Identifier of the cache entry to fetch
853 * @return mixed The value
854 */
855 protected function getQueryCacheEntry($entryIdentifier) {
856 if (!isset($this->queryRuntimeCache[$entryIdentifier])) {
857 $this->queryRuntimeCache[$entryIdentifier] = $this->queryCache->get($entryIdentifier);
858 }
859 return $this->queryRuntimeCache[$entryIdentifier];
860 }
861
862 /**
863 * Saves the value of a PHP variable in the query cache.
864 *
865 * @param string $entryIdentifier An identifier used for this cache entry
866 * @param mixed $variable The query to cache
867 * @return void
868 */
869 protected function setQueryCacheEntry($entryIdentifier, $variable) {
870 $this->queryRuntimeCache[$entryIdentifier] = $variable;
871 $this->queryCache->set($entryIdentifier, $variable, array(), 0);
872 }
873 }