d20f11e5dee54cec769b6565fa0d1bdd0cdd4046
[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 = [];
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($tableName);
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 [
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 * @throws SqlErrorException when the raw SQL statement fails in the database
406 */
407 protected function getObjectDataByRawQuery(Qom\Statement $statement)
408 {
409 $realStatement = $statement->getStatement();
410 $parameters = $statement->getBoundVariables();
411
412 if ($realStatement instanceof \TYPO3\CMS\Core\Database\PreparedStatement) {
413 $realStatement->execute($parameters);
414 $rows = $realStatement->fetchAll();
415
416 $realStatement->free();
417 } else {
418 // Do a real raw query. This is very stupid, as it does not allow to use DBAL's real power if
419 // several tables are on different databases, so this is used with caution and could be removed
420 // in the future
421 try {
422 $connection = $this->connectionPool->getConnectionByName(ConnectionPool::DEFAULT_CONNECTION_NAME);
423 $statement = $connection->executeQuery($realStatement);
424 } catch (DBALException $e) {
425 throw new SqlErrorException($e->getPrevious()->getMessage(), 1472064775);
426 }
427
428 $rows = [];
429 while ($row = $statement->fetch()) {
430 if (is_array($row)) {
431 $rows[] = $row;
432 }
433 }
434 }
435
436 return $rows;
437 }
438
439 /**
440 * Returns the number of tuples matching the query.
441 *
442 * @param QueryInterface $query
443 * @throws Exception\BadConstraintException
444 * @return int The number of matching tuples
445 */
446 public function getObjectCountByQuery(QueryInterface $query)
447 {
448 if ($query->getConstraint() instanceof Qom\Statement) {
449 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);
450 }
451
452 $statementParts = $this->queryParser->parseQuery($query);
453
454 $fields = '*';
455 if (isset($statementParts['keywords']['distinct'])) {
456 $fields = 'DISTINCT ' . reset($statementParts['tables']) . '.uid';
457 }
458
459 $queryCommandParameters = $this->createQueryCommandParametersFromStatementParts($statementParts);
460 $count = $this->databaseHandle->exec_SELECTcountRows(
461 $fields,
462 $queryCommandParameters['fromTable'],
463 $queryCommandParameters['whereClause']
464 );
465 $this->checkSqlErrors();
466
467 if ($statementParts['offset']) {
468 $count -= $statementParts['offset'];
469 }
470
471 if ($statementParts['limit']) {
472 $count = min($count, $statementParts['limit']);
473 }
474
475 return (int)max(0, $count);
476 }
477
478 /**
479 * Checks if a Value Object equal to the given Object exists in the database
480 *
481 * @param AbstractValueObject $object The Value Object
482 * @return mixed The matching uid if an object was found, else FALSE
483 * @throws SqlErrorException
484 */
485 public function getUidOfAlreadyPersistedValueObject(AbstractValueObject $object)
486 {
487 $dataMap = $this->dataMapper->getDataMap(get_class($object));
488 $tableName = $dataMap->getTableName();
489 $queryBuilder = $this->connectionPool->getQueryBuilderForTable($tableName);
490 if ($this->environmentService->isEnvironmentInFrontendMode()) {
491 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
492 }
493 $whereClause = [];
494 // loop over all properties of the object to exactly set the values of each database field
495 $properties = $object->_getProperties();
496 foreach ($properties as $propertyName => $propertyValue) {
497 // @todo We couple the Backend to the Entity implementation (uid, isClone); changes there breaks this method
498 if ($dataMap->isPersistableProperty($propertyName) && $propertyName !== 'uid' && $propertyName !== 'pid' && $propertyName !== 'isClone') {
499 $fieldName = $dataMap->getColumnMap($propertyName)->getColumnName();
500 if ($propertyValue === null) {
501 $whereClause[] = $queryBuilder->expr()->isNull($fieldName);
502 } else {
503 $whereClause[] = $queryBuilder->expr()->eq($fieldName, $queryBuilder->createNamedParameter($this->dataMapper->getPlainValue($propertyValue)));
504 }
505 }
506 }
507 $queryBuilder
508 ->select('uid')
509 ->from($tableName)
510 ->where(...$whereClause);
511
512 try {
513 $uid = (int)$queryBuilder
514 ->execute()
515 ->fetchColumn(0);
516 if ($uid > 0) {
517 return $uid;
518 } else {
519 return false;
520 }
521 } catch (DBALException $e) {
522 throw new SqlErrorException($e->getPrevious()->getMessage(), 1470231748);
523 }
524 }
525
526 /**
527 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
528 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
529 *
530 * @param Qom\SourceInterface $source The source (selector od join)
531 * @param array $rows
532 * @param \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
533 * @param null|int $workspaceUid
534 * @return array
535 */
536 protected function doLanguageAndWorkspaceOverlay(Qom\SourceInterface $source, array $rows, \TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface $querySettings, $workspaceUid = null)
537 {
538 if ($source instanceof Qom\SelectorInterface) {
539 $tableName = $source->getSelectorName();
540 } elseif ($source instanceof Qom\JoinInterface) {
541 $tableName = $source->getRight()->getSelectorName();
542 } else {
543 // No proper source, so we do not have a table name here
544 // we cannot do an overlay and return the original rows instead.
545 return $rows;
546 }
547
548 $pageRepository = $this->getPageRepository();
549 if (is_object($GLOBALS['TSFE'])) {
550 if ($workspaceUid !== null) {
551 $pageRepository->versioningWorkspaceId = $workspaceUid;
552 }
553 } else {
554 if ($workspaceUid === null) {
555 $workspaceUid = $GLOBALS['BE_USER']->workspace;
556 }
557 $pageRepository->versioningWorkspaceId = $workspaceUid;
558 }
559
560 // Fetches the move-placeholder in case it is supported
561 // by the table and if there's only one row in the result set
562 // (applying this to all rows does not work, since the sorting
563 // order would be destroyed and possible limits not met anymore)
564 if (!empty($pageRepository->versioningWorkspaceId)
565 && BackendUtility::isTableWorkspaceEnabled($tableName)
566 && count($rows) === 1
567 ) {
568 $movePlaceholder = $this->databaseHandle->exec_SELECTgetSingleRow(
569 $tableName . '.*',
570 $tableName,
571 't3ver_state=3 AND t3ver_wsid=' . $pageRepository->versioningWorkspaceId
572 . ' AND t3ver_move_id=' . $rows[0]['uid']
573 );
574 if (!empty($movePlaceholder)) {
575 $rows = [$movePlaceholder];
576 }
577 }
578
579 $overlaidRows = [];
580 foreach ($rows as $row) {
581 // If current row is a translation select its parent
582 if (isset($tableName) && isset($GLOBALS['TCA'][$tableName])
583 && isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
584 && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
585 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
586 ) {
587 if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
588 && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
589 ) {
590 $row = $this->databaseHandle->exec_SELECTgetSingleRow(
591 $tableName . '.*',
592 $tableName,
593 $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
594 ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
595 );
596 }
597 }
598 $pageRepository->versionOL($tableName, $row, true);
599 if ($tableName == 'pages') {
600 $row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
601 } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
602 && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
603 && !isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerTable'])
604 ) {
605 if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], [-1, 0])) {
606 $overlayMode = $querySettings->getLanguageMode() === 'strict' ? 'hideNonTranslated' : '';
607 $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
608 }
609 }
610 if ($row !== null && is_array($row)) {
611 $overlaidRows[] = $row;
612 }
613 }
614 return $overlaidRows;
615 }
616
617 /**
618 * @return \TYPO3\CMS\Frontend\Page\PageRepository
619 */
620 protected function getPageRepository()
621 {
622 if (!$this->pageRepository instanceof \TYPO3\CMS\Frontend\Page\PageRepository) {
623 if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
624 $this->pageRepository = $GLOBALS['TSFE']->sys_page;
625 } else {
626 $this->pageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class);
627 }
628 }
629
630 return $this->pageRepository;
631 }
632
633 /**
634 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
635 *
636 * @return void
637 * @param string $sql The SQL statement
638 * @throws SqlErrorException
639 */
640 protected function checkSqlErrors($sql = '')
641 {
642 $error = $this->databaseHandle->sql_error();
643 if ($error !== '') {
644 $error .= $sql ? ': ' . $sql : '';
645 throw new SqlErrorException($error, 1247602160);
646 }
647 }
648
649 /**
650 * Clear the TYPO3 page cache for the given record.
651 * If the record lies on a page, then we clear the cache of this page.
652 * If the record has no PID column, we clear the cache of the current page as best-effort.
653 *
654 * Much of this functionality is taken from DataHandler::clear_cache() which unfortunately only works with logged-in BE user.
655 *
656 * @param string $tableName Table name of the record
657 * @param int $uid UID of the record
658 * @return void
659 */
660 protected function clearPageCache($tableName, $uid)
661 {
662 $frameworkConfiguration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
663 if (isset($frameworkConfiguration['persistence']['enableAutomaticCacheClearing']) && $frameworkConfiguration['persistence']['enableAutomaticCacheClearing'] === '1') {
664 } else {
665 // if disabled, return
666 return;
667 }
668 $pageIdsToClear = [];
669 $storagePage = null;
670 $columns = GeneralUtility::makeInstance(ConnectionPool::class)
671 ->getConnectionForTable($tableName)
672 ->getSchemaManager()
673 ->listTableColumns($tableName);
674 if (array_key_exists('pid', $columns)) {
675 $queryBuilder = $this->connectionPool->getQueryBuilderForTable($tableName);
676 $queryBuilder->getRestrictions()->removeAll();
677 $result = $queryBuilder
678 ->select('pid')
679 ->from($tableName)
680 ->where($queryBuilder->expr()->eq('uid', (int)$uid))
681 ->execute();
682 if ($row = $result->fetch()) {
683 $storagePage = $row['pid'];
684 $pageIdsToClear[] = $storagePage;
685 }
686 } elseif (isset($GLOBALS['TSFE'])) {
687 // No PID column - we can do a best-effort to clear the cache of the current page if in FE
688 $storagePage = $GLOBALS['TSFE']->id;
689 $pageIdsToClear[] = $storagePage;
690 }
691 if ($storagePage === null) {
692 return;
693 }
694 if (!isset($this->pageTSConfigCache[$storagePage])) {
695 $this->pageTSConfigCache[$storagePage] = BackendUtility::getPagesTSconfig($storagePage);
696 }
697 if (isset($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd'])) {
698 $clearCacheCommands = GeneralUtility::trimExplode(',', strtolower($this->pageTSConfigCache[$storagePage]['TCEMAIN.']['clearCacheCmd']), true);
699 $clearCacheCommands = array_unique($clearCacheCommands);
700 foreach ($clearCacheCommands as $clearCacheCommand) {
701 if (MathUtility::canBeInterpretedAsInteger($clearCacheCommand)) {
702 $pageIdsToClear[] = $clearCacheCommand;
703 }
704 }
705 }
706
707 foreach ($pageIdsToClear as $pageIdToClear) {
708 $this->cacheService->getPageIdStack()->push($pageIdToClear);
709 }
710 }
711 }