[!!!][TASK] Extbase: Remove preparsing of queries
[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 Doctrine\DBAL\DBALException;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
21 use TYPO3\CMS\Core\SingletonInterface;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\MathUtility;
24 use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
25 use TYPO3\CMS\Extbase\DomainObject\AbstractValueObject;
26 use TYPO3\CMS\Extbase\Persistence\Generic\Qom;
27 use TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException;
28 use TYPO3\CMS\Extbase\Persistence\QueryInterface;
29
30 /**
31 * A Storage backend
32 */
33 class Typo3DbBackend implements BackendInterface, SingletonInterface
34 {
35 /**
36 * The TYPO3 database object
37 *
38 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
39 */
40 protected $databaseHandle;
41
42 /**
43 * @var ConnectionPool
44 */
45 protected $connectionPool;
46
47 /**
48 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
49 */
50 protected $dataMapper;
51
52 /**
53 * The TYPO3 page repository. Used for language and workspace overlay
54 *
55 * @var \TYPO3\CMS\Frontend\Page\PageRepository
56 */
57 protected $pageRepository;
58
59 /**
60 * A first-level TypoScript configuration cache
61 *
62 * @var array
63 */
64 protected $pageTSConfigCache = array();
65
66 /**
67 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
68 */
69 protected $configurationManager;
70
71 /**
72 * @var \TYPO3\CMS\Extbase\Service\CacheService
73 */
74 protected $cacheService;
75
76 /**
77 * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
78 */
79 protected $environmentService;
80
81 /**
82 * @var \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser
83 */
84 protected $queryParser;
85
86 /**
87 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper
88 */
89 public function injectDataMapper(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper)
90 {
91 $this->dataMapper = $dataMapper;
92 }
93
94 /**
95 * @param \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager
96 */
97 public function injectConfigurationManager(ConfigurationManagerInterface $configurationManager)
98 {
99 $this->configurationManager = $configurationManager;
100 }
101
102 /**
103 * @param \TYPO3\CMS\Extbase\Service\CacheService $cacheService
104 */
105 public function injectCacheService(\TYPO3\CMS\Extbase\Service\CacheService $cacheService)
106 {
107 $this->cacheService = $cacheService;
108 }
109
110 /**
111 * @param \TYPO3\CMS\Extbase\Service\EnvironmentService $environmentService
112 */
113 public function injectEnvironmentService(\TYPO3\CMS\Extbase\Service\EnvironmentService $environmentService)
114 {
115 $this->environmentService = $environmentService;
116 }
117
118 /**
119 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser $queryParser
120 */
121 public function injectQueryParser(\TYPO3\CMS\Extbase\Persistence\Generic\Storage\Typo3DbQueryParser $queryParser)
122 {
123 $this->queryParser = $queryParser;
124 }
125
126 /**
127 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
128 */
129 public function __construct()
130 {
131 $this->databaseHandle = $GLOBALS['TYPO3_DB'];
132 $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
133 }
134
135 /**
136 * Adds a row to the storage
137 *
138 * @param string $tableName The database table name
139 * @param array $fieldValues The row to be inserted
140 * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
141 * @return int The uid of the inserted row
142 * @throws SqlErrorException
143 */
144 public function addRow($tableName, array $fieldValues, $isRelation = false)
145 {
146 if (isset($fieldValues['uid'])) {
147 unset($fieldValues['uid']);
148 }
149 try {
150 $connection = $this->connectionPool->getConnectionForTable($tableName);
151 $connection->insert($tableName, $fieldValues);
152 } catch (DBALException $e) {
153 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470230766);
154 }
155
156 $uid = $connection->lastInsertId();
157
158 if (!$isRelation) {
159 $this->clearPageCache($tableName, $uid);
160 }
161 return (int)$uid;
162 }
163
164 /**
165 * Updates a row in the storage
166 *
167 * @param string $tableName The database table name
168 * @param array $fieldValues The row to be updated
169 * @param bool $isRelation TRUE if we are currently inserting into a relation table, FALSE by default
170 * @throws \InvalidArgumentException
171 * @throws SqlErrorException
172 * @return bool
173 */
174 public function updateRow($tableName, array $fieldValues, $isRelation = false)
175 {
176 if (!isset($fieldValues['uid'])) {
177 throw new \InvalidArgumentException('The given row must contain a value for "uid".');
178 }
179
180 $uid = (int)$fieldValues['uid'];
181 unset($fieldValues['uid']);
182
183 try {
184 $this->connectionPool->getConnectionForTable($tableName)
185 ->update($tableName, $fieldValues, ['uid' => $uid]);
186 } catch (DBALException $e) {
187 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470230767);
188 }
189
190 if (!$isRelation) {
191 $this->clearPageCache($tableName, $uid);
192 }
193
194 // always returns true
195 return true;
196 }
197
198 /**
199 * Updates a relation row in the storage.
200 *
201 * @param string $tableName The database relation table name
202 * @param array $fieldValues The row to be updated
203 * @throws \InvalidArgumentException
204 * @return bool
205 * @throws SqlErrorException
206 */
207 public function updateRelationTableRow($tableName, array $fieldValues)
208 {
209 if (!isset($fieldValues['uid_local']) && !isset($fieldValues['uid_foreign'])) {
210 throw new \InvalidArgumentException(
211 'The given fieldValues must contain a value for "uid_local" and "uid_foreign".', 1360500126
212 );
213 }
214
215 $where['uid_local'] = (int)$fieldValues['uid_local'];
216 $where['uid_foreign'] = (int)$fieldValues['uid_foreign'];
217 unset($fieldValues['uid_local']);
218 unset($fieldValues['uid_foreign']);
219
220 if (!empty($fieldValues['tablenames'])) {
221 $where['tablenames'] = $fieldValues['tablenames'];
222 unset($fieldValues['tablenames']);
223 }
224 if (!empty($fieldValues['fieldname'])) {
225 $where['fieldname'] = $fieldValues['fieldname'];
226 unset($fieldValues['fieldname']);
227 }
228
229 try {
230 $this->connectionPool->getConnectionForTable($tableName)
231 ->update($tableName, $fieldValues, $where);
232 } catch (DBALException $e) {
233 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470230768);
234 }
235
236 // always returns true
237 return true;
238 }
239
240 /**
241 * Deletes a row in the storage
242 *
243 * @param string $tableName The database table name
244 * @param array $where An array of where array('fieldname' => value).
245 * @param bool $isRelation TRUE if we are currently manipulating a relation table, FALSE by default
246 * @return bool
247 * @throws SqlErrorException
248 */
249 public function removeRow($tableName, array $where, $isRelation = false)
250 {
251 try {
252 $this->connectionPool->getConnectionForTable($tableName)->delete($tableName, $where);
253 } catch (DBALException $e) {
254 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470230769);
255 }
256
257 if (!$isRelation && isset($where['uid'])) {
258 $this->clearPageCache($tableName, $where['uid']);
259 }
260
261 // always returns true
262 return true;
263 }
264
265 /**
266 * Fetches maximal value for given table column from database.
267 *
268 * @param string $tableName The database table name
269 * @param array $where An array of where array('fieldname' => value).
270 * @param string $columnName column name to get the max value from
271 * @return mixed the max value
272 * @throws SqlErrorException
273 */
274 public function getMaxValueFromTable($tableName, array $where, $columnName)
275 {
276 try {
277 $queryBuilder = $this->connectionPool->getQueryBuilderForTable($tableName);
278 $queryBuilder->getRestrictions()->removeAll();
279 $queryBuilder
280 ->select($columnName)
281 ->from($tableName)
282 ->orderBy($columnName, 'DESC')
283 ->setMaxResults(1);
284
285 foreach ($where as $fieldName => $value) {
286 $queryBuilder->andWhere(
287 $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($value))
288 );
289 }
290
291 $result = $queryBuilder->execute()->fetchColumn(0);
292 } catch (DBALException $e) {
293 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470230770);
294 }
295 return $result;
296 }
297
298 /**
299 * Fetches row data from the database
300 *
301 * @param string $tableName
302 * @param array $where An array of where array('fieldname' => value).
303 * @return array|bool
304 * @throws SqlErrorException
305 */
306 public function getRowByIdentifier($tableName, array $where)
307 {
308 try {
309 $queryBuilder = $this->connectionPool->getQueryBuilderForTable($tableName);
310 $queryBuilder->getRestrictions()->removeAll();
311 $queryBuilder
312 ->select('*')
313 ->from($tableName);
314
315 foreach ($where as $fieldName => $value) {
316 $queryBuilder->andWhere(
317 $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($value))
318 );
319 }
320
321 $row = $queryBuilder->execute()->fetch();
322 } catch (DBALException $e) {
323 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470230771);
324 }
325 return $row ?: false;
326 }
327
328 /**
329 * Returns the object data matching the $query.
330 *
331 * @param QueryInterface $query
332 * @return array
333 */
334 public function getObjectDataByQuery(QueryInterface $query)
335 {
336 $statement = $query->getStatement();
337 if ($statement instanceof Qom\Statement) {
338 $rows = $this->getObjectDataByRawQuery($statement);
339 } else {
340 $statementParts = $this->queryParser->parseQuery($query);
341 $rows = $this->getRowsFromDatabase($statementParts);
342 }
343
344 $rows = $this->doLanguageAndWorkspaceOverlay($query->getSource(), $rows, $query->getQuerySettings());
345 return $rows;
346 }
347
348 /**
349 * Creates the parameters for the query methods of the database methods in the TYPO3 core, from an array
350 * that came from a parsed query.
351 *
352 * @param array $statementParts
353 * @throws \InvalidArgumentException
354 * @return array
355 */
356 protected function createQueryCommandParametersFromStatementParts(array $statementParts)
357 {
358 if (isset($statementParts['offset']) && !isset($statementParts['limit'])) {
359 throw new \InvalidArgumentException(
360 'Trying to make query with offset and no limit, the offset would become a limit. You have to set a limit to use offset. To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the limit.',
361 1465223252
362 );
363 }
364 return array(
365 'selectFields' => implode(' ', $statementParts['keywords']) . ' ' . implode(',', $statementParts['fields']),
366 'fromTable' => implode(' ', $statementParts['tables']) . ' ' . implode(' ', $statementParts['unions']),
367 'whereClause' => (!empty($statementParts['where']) ? implode('', $statementParts['where']) : '1=1')
368 . (!empty($statementParts['additionalWhereClause'])
369 ? ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'])
370 : ''
371 ),
372 'orderBy' => (!empty($statementParts['orderings']) ? implode(', ', $statementParts['orderings']) : ''),
373 'limit' => ($statementParts['offset'] ? $statementParts['offset'] . ', ' : '')
374 . ($statementParts['limit'] ? $statementParts['limit'] : '')
375 );
376 }
377
378 /**
379 * Fetches the rows directly from the database, not using prepared statement
380 *
381 * @param array $statementParts
382 * @return array the result
383 */
384 protected function getRowsFromDatabase(array $statementParts)
385 {
386 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
387 $rows = $this->databaseHandle->exec_SELECTgetRows(
388 $queryCommandParameters['selectFields'],
389 $queryCommandParameters['fromTable'],
390 $queryCommandParameters['whereClause'],
391 '',
392 $queryCommandParameters['orderBy'],
393 $queryCommandParameters['limit']
394 );
395 $this->checkSqlErrors();
396
397 return $rows;
398 }
399
400 /**
401 * Returns the object data using a custom statement
402 *
403 * @param Qom\Statement $statement
404 * @return array
405 */
406 protected function getObjectDataByRawQuery(Qom\Statement $statement)
407 {
408 $realStatement = $statement->getStatement();
409 $parameters = $statement->getBoundVariables();
410
411 if ($realStatement instanceof \TYPO3\CMS\Core\Database\PreparedStatement) {
412 $realStatement->execute($parameters);
413 $rows = $realStatement->fetchAll();
414
415 $realStatement->free();
416 } else {
417 $result = $this->databaseHandle->sql_query($realStatement);
418 $this->checkSqlErrors();
419
420 $rows = array();
421 while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
422 if (is_array($row)) {
423 $rows[] = $row;
424 }
425 }
426 $this->databaseHandle->sql_free_result($result);
427 }
428
429 return $rows;
430 }
431
432 /**
433 * Returns the number of tuples matching the query.
434 *
435 * @param QueryInterface $query
436 * @throws Exception\BadConstraintException
437 * @return int The number of matching tuples
438 */
439 public function getObjectCountByQuery(QueryInterface $query)
440 {
441 if ($query->getConstraint() instanceof Qom\Statement) {
442 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);
443 }
444
445 $statementParts = $this->queryParser->parseQuery($query);
446
447 $fields = '*';
448 if (isset($statementParts['keywords']['distinct'])) {
449 $fields = 'DISTINCT ' . reset($statementParts['tables']) . '.uid';
450 }
451
452 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
453 $count = $this->databaseHandle->exec_SELECTcountRows(
454 $fields,
455 $queryCommandParameters['fromTable'],
456 $queryCommandParameters['whereClause']
457 );
458 $this->checkSqlErrors();
459
460 if ($statementParts['offset']) {
461 $count -= $statementParts['offset'];
462 }
463
464 if ($statementParts['limit']) {
465 $count = min($count, $statementParts['limit']);
466 }
467
468 return (int)max(0, $count);
469 }
470
471 /**
472 * Checks if a Value Object equal to the given Object exists in the database
473 *
474 * @param AbstractValueObject $object The Value Object
475 * @return mixed The matching uid if an object was found, else FALSE
476 * @throws SqlErrorException
477 */
478 public function getUidOfAlreadyPersistedValueObject(AbstractValueObject $object)
479 {
480 $dataMap = $this->dataMapper->getDataMap(get_class($object));
481 $tableName = $dataMap->getTableName();
482 $queryBuilder = $this->connectionPool->getQueryBuilderForTable($tableName);
483 if ($this->environmentService->isEnvironmentInFrontendMode()) {
484 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
485 }
486 $whereClause = [];
487 // loop over all properties of the object to exactly set the values of each database field
488 $properties = $object->_getProperties();
489 foreach ($properties as $propertyName => $propertyValue) {
490 // @todo We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
491 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
492 $fieldName = $dataMap->getColumnMap($propertyName)->getColumnName();
493 if ($propertyValue === null) {
494 $whereClause[] = $queryBuilder->expr()->isNull($fieldName);
495 } else {
496 $whereClause[] = $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($this->dataMapper->getPlainValue($propertyValue)));
497 }
498 }
499 }
500 $queryBuilder
501 ->select('uid')
502 ->from($tableName)
503 ->where(...$whereClause);
504
505 try {
506 $uid = (int)$queryBuilder
507 ->execute()
508 ->fetchColumn(0);
509 if ($uid > 0) {
510 return $uid;
511 } else {
512 return false;
513 }
514 } catch (DBALException $e) {
515 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470231748);
516 }
517 }
518
519 /**
520 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
521 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
522 *
523 * @param Qom\SourceInterface $source The source (selector od join)
524 * @param array $rows
525 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
526 * @param null|int $workspaceUid
527 * @return array
528 */
529 protected function doLanguageAndWorkspaceOverlay(Qom\SourceInterface $source, array $rows, \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $workspaceUid = null)
530 {
531 if ($source instanceof Qom\SelectorInterface) {
532 $tableName = $source->getSelectorName();
533 } elseif ($source instanceof Qom\JoinInterface) {
534 $tableName = $source->getRight()->getSelectorName();
535 } else {
536 // No proper source, so we do not have a table name here
537 // we cannot do an overlay and return the original rows instead.
538 return $rows;
539 }
540
541 $pageRepository = $this->getPageRepository();
542 if (is_object($GLOBALS['TSFE'])) {
543 if ($workspaceUid !== null) {
544 $pageRepository->versioningWorkspaceId = $workspaceUid;
545 }
546 } else {
547 if ($workspaceUid === null) {
548 $workspaceUid = $GLOBALS['BE_USER']->workspace;
549 }
550 $pageRepository->versioningWorkspaceId = $workspaceUid;
551 }
552
553 // Fetches the move-placeholder in case it is supported
554 // by the table and if there's only one row in the result set
555 // (applying this to all rows does not work, since the sorting
556 // order would be destroyed and possible limits not met anymore)
557 if (!empty($pageRepository->versioningWorkspaceId)
558 && BackendUtility::isTableWorkspaceEnabled($tableName)
559 && count($rows) === 1
560 ) {
561 $movePlaceholder = $this->databaseHandle->exec_SELECTgetSingleRow(
562 $tableName . '.*',
563 $tableName,
564 't3ver_state=3 AND t3ver_wsid=' . $pageRepository->versioningWorkspaceId
565 . ' AND t3ver_move_id=' . $rows[0]['uid']
566 );
567 if (!empty($movePlaceholder)) {
568 $rows = array($movePlaceholder);
569 }
570 }
571
572 $overlaidRows = array();
573 foreach ($rows as $row) {
574 // If current row is a translation select its parent
575 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
576 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
577 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
578 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
579 ) {
580 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
581 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
582 ) {
583 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
584 $tableName . '.*',
585 $tableName,
586 $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
587 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
588 );
589 }
590 }
591 $pageRepository->versionOL($tableName, $row, true);
592 if ($tableName == 'pages') {
593 $row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
594 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
595 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
596 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
597 ) {
598 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
599 $overlayMode = $querySettings->getLanguageMode() === 'strict' ? 'hideNonTranslated' : '';
600 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
601 }
602 }
603 if ($row !== null && is_array($row)) {
604 $overlaidRows[] = $row;
605 }
606 }
607 return $overlaidRows;
608 }
609
610 /**
611 * @return \TYPO3\CMS\Frontend\Page\PageRepository
612 */
613 protected function getPageRepository()
614 {
615 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
616 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
617 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
618 } else {
619 $this->pageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class);
620 }
621 }
622
623 return $this->pageRepository;
624 }
625
626 /**
627 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
628 *
629 * @return void
630 * @param string $sql The SQL statement
631 * @throws SqlErrorException
632 */
633 protected function checkSqlErrors($sql = '')
634 {
635 $error = $this->databaseHandle->sql_error();
636 if ($error !== '') {
637 $error .= $sql ? ': ' . $sql : '';
638 throw new SqlErrorException($error, 1247602160);
639 }
640 }
641
642 /**
643 * Clear the TYPO3 page cache for the given record.
644 * If the record lies on a page, then we clear the cache of this page.
645 * If the record has no PID column, we clear the cache of the current page as best-effort.
646 *
647 * Much of this functionality is taken from DataHandler::clear_cache() which unfortunately only works with logged-in BE user.
648 *
649 * @param string $tableName Table name of the record
650 * @param int $uid UID of the record
651 * @return void
652 */
653 protected function clearPageCache($tableName, $uid)
654 {
655 $frameworkConfiguration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
656 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
657 } else {
658 // if disabled, return
659 return;
660 }
661 $pageIdsToClear = array();
662 $storagePage = null;
663 $columns = $this->databaseHandle->admin_get_fields($tableName);
664 if (array_key_exists('pid', $columns)) {
665 $queryBuilder = $this->connectionPool->getQueryBuilderForTable($tableName);
666 $queryBuilder->getRestrictions()->removeAll();
667 $result = $queryBuilder
668 ->select('pid')
669 ->from($tableName)
670 ->where($queryBuilder->expr()->eq('uid', (int)$uid))
671 ->execute();
672 if ($row = $result->fetch()) {
673 $storagePage = $row['pid'];
674 $pageIdsToClear[] = $storagePage;
675 }
676 } elseif (isset($GLOBALS['TSFE'])) {
677 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
678 $storagePage = $GLOBALS['TSFE']->id;
679 $pageIdsToClear[] = $storagePage;
680 }
681 if ($storagePage === null) {
682 return;
683 }
684 if (!isset($this->pageTSConfigCache[$storagePage])) {
685 $this->pageTSConfigCache[$storagePage] = BackendUtility::getPagesTSconfig($storagePage);
686 }
687 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
688 $clearCacheCommands = GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), true);
689 $clearCacheCommands = array_unique($clearCacheCommands);
690 foreach ($clearCacheCommands as $clearCacheCommand) {
691 if (MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
692 $pageIdsToClear[] = $clearCacheCommand;
693 }
694 }
695 }
696
697 foreach ($pageIdsToClear as $pageIdToClear) {
698 $this->cacheService->getPageIdStack()->push($pageIdToClear);
699 }
700 }
701 }