a2e1908d8d10e8b743c4361953f9007152d837ec
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / RootlineUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
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\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
20 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
21 use TYPO3\CMS\Frontend\Page\PageRepository;
22
23 /**
24 * A utility resolving and Caching the Rootline generation
25 */
26 class RootlineUtility
27 {
28 /**
29 * @var int
30 */
31 protected $pageUid;
32
33 /**
34 * @var string
35 */
36 protected $mountPointParameter;
37
38 /**
39 * @var array
40 */
41 protected $parsedMountPointParameters = [];
42
43 /**
44 * @var int
45 */
46 protected $languageUid = 0;
47
48 /**
49 * @var int
50 */
51 protected $workspaceUid = 0;
52
53 /**
54 * @var bool
55 */
56 protected $versionPreview = false;
57
58 /**
59 * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
60 */
61 protected static $cache = null;
62
63 /**
64 * @var array
65 */
66 protected static $localCache = [];
67
68 /**
69 * Fields to fetch when populating rootline data
70 *
71 * @var array
72 */
73 protected static $rootlineFields = [
74 'pid',
75 'uid',
76 't3ver_oid',
77 't3ver_wsid',
78 't3ver_state',
79 'title',
80 'alias',
81 'nav_title',
82 'media',
83 'layout',
84 'hidden',
85 'starttime',
86 'endtime',
87 'fe_group',
88 'extendToSubpages',
89 'doktype',
90 'TSconfig',
91 'tsconfig_includes',
92 'is_siteroot',
93 'mount_pid',
94 'mount_pid_ol',
95 'fe_login_mode',
96 'backend_layout_next_level'
97 ];
98
99 /**
100 * Rootline Context
101 *
102 * @var \TYPO3\CMS\Frontend\Page\PageRepository
103 */
104 protected $pageContext;
105
106 /**
107 * @var string
108 */
109 protected $cacheIdentifier;
110
111 /**
112 * @var array
113 */
114 protected static $pageRecordCache = [];
115
116 /**
117 * @param int $uid
118 * @param string $mountPointParameter
119 * @param \TYPO3\CMS\Frontend\Page\PageRepository $context
120 * @throws \RuntimeException
121 */
122 public function __construct($uid, $mountPointParameter = '', PageRepository $context = null)
123 {
124 $this->pageUid = (int)$uid;
125 $this->mountPointParameter = trim($mountPointParameter);
126 if ($context === null) {
127 if (isset($GLOBALS['TSFE']) && is_object($GLOBALS['TSFE']) && is_object($GLOBALS['TSFE']->sys_page)) {
128 $this->pageContext = $GLOBALS['TSFE']->sys_page;
129 } else {
130 $this->pageContext = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Page\PageRepository::class);
131 }
132 } else {
133 $this->pageContext = $context;
134 }
135 $this->initializeObject();
136 }
137
138 /**
139 * Initialize a state to work with
140 *
141 * @throws \RuntimeException
142 */
143 protected function initializeObject()
144 {
145 $this->languageUid = (int)$this->pageContext->sys_language_uid;
146 $this->workspaceUid = (int)$this->pageContext->versioningWorkspaceId;
147 $this->versionPreview = $this->pageContext->versioningPreview;
148 if ($this->mountPointParameter !== '') {
149 if (!$GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
150 throw new \RuntimeException('Mount-Point Pages are disabled for this installation. Cannot resolve a Rootline for a page with Mount-Points', 1343462896);
151 }
152 $this->parseMountPointParameter();
153 }
154 if (self::$cache === null) {
155 self::$cache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_rootline');
156 }
157 self::$rootlineFields = array_merge(self::$rootlineFields, GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields'], true));
158 self::$rootlineFields = array_unique(self::$rootlineFields);
159
160 $this->cacheIdentifier = $this->getCacheIdentifier();
161 }
162
163 /**
164 * Purges all rootline caches.
165 *
166 * Note: This function is intended to be used in unit tests only.
167 */
168 public static function purgeCaches()
169 {
170 self::$localCache = [];
171 self::$pageRecordCache = [];
172 }
173
174 /**
175 * Constructs the cache Identifier
176 *
177 * @param int $otherUid
178 * @return string
179 */
180 public function getCacheIdentifier($otherUid = null)
181 {
182 $mountPointParameter = (string)$this->mountPointParameter;
183 if ($mountPointParameter !== '' && strpos($mountPointParameter, ',') !== false) {
184 $mountPointParameter = str_replace(',', '__', $mountPointParameter);
185 }
186
187 return implode('_', [
188 $otherUid !== null ? (int)$otherUid : $this->pageUid,
189 $mountPointParameter,
190 $this->languageUid,
191 $this->workspaceUid,
192 $this->versionPreview ? 1 : 0
193 ]);
194 }
195
196 /**
197 * Returns the actual rootline
198 *
199 * @return array
200 */
201 public function get()
202 {
203 if (!isset(static::$localCache[$this->cacheIdentifier])) {
204 $entry = static::$cache->get($this->cacheIdentifier);
205 if (!$entry) {
206 $this->generateRootlineCache();
207 } else {
208 static::$localCache[$this->cacheIdentifier] = $entry;
209 $depth = count($entry);
210 // Populate the root-lines for parent pages as well
211 // since they are part of the current root-line
212 while ($depth > 1) {
213 --$depth;
214 $parentCacheIdentifier = $this->getCacheIdentifier($entry[$depth - 1]['uid']);
215 // Abort if the root-line of the parent page is
216 // already in the local cache data
217 if (isset(static::$localCache[$parentCacheIdentifier])) {
218 break;
219 }
220 // Behaves similar to array_shift(), but preserves
221 // the array keys - which contain the page ids here
222 $entry = array_slice($entry, 1, null, true);
223 static::$localCache[$parentCacheIdentifier] = $entry;
224 }
225 }
226 }
227 return static::$localCache[$this->cacheIdentifier];
228 }
229
230 /**
231 * Queries the database for the page record and returns it.
232 *
233 * @param int $uid Page id
234 * @throws \RuntimeException
235 * @return array
236 */
237 protected function getRecordArray($uid)
238 {
239 $currentCacheIdentifier = $this->getCacheIdentifier($uid);
240 if (!isset(self::$pageRecordCache[$currentCacheIdentifier])) {
241 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
242 $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
243 $row = $queryBuilder->select(...self::$rootlineFields)
244 ->from('pages')
245 ->where(
246 $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
247 $queryBuilder->expr()->neq(
248 'doktype',
249 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
250 )
251 )
252 ->execute()
253 ->fetch();
254 if (empty($row)) {
255 throw new \RuntimeException('Could not fetch page data for uid ' . $uid . '.', 1343589451);
256 }
257 $this->pageContext->versionOL('pages', $row, false, true);
258 $this->pageContext->fixVersioningPid('pages', $row);
259 if (is_array($row)) {
260 if ($this->languageUid > 0) {
261 $row = $this->pageContext->getPageOverlay($row, $this->languageUid);
262 }
263 $row = $this->enrichWithRelationFields($row['_PAGES_OVERLAY_UID'] ?? $uid, $row);
264 self::$pageRecordCache[$currentCacheIdentifier] = $row;
265 }
266 }
267 if (!is_array(self::$pageRecordCache[$currentCacheIdentifier])) {
268 throw new \RuntimeException('Broken rootline. Could not resolve page with uid ' . $uid . '.', 1343464101);
269 }
270 return self::$pageRecordCache[$currentCacheIdentifier];
271 }
272
273 /**
274 * Resolve relations as defined in TCA and add them to the provided $pageRecord array.
275 *
276 * @param int $uid page ID
277 * @param array $pageRecord Page record (possibly overlaid) to be extended with relations
278 * @throws \RuntimeException
279 * @return array $pageRecord with additional relations
280 */
281 protected function enrichWithRelationFields($uid, array $pageRecord)
282 {
283 $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
284
285 // @todo Remove this special interpretation of relations by consequently using RelationHandler
286 foreach ($GLOBALS['TCA']['pages']['columns'] as $column => $configuration) {
287 if ($this->columnHasRelationToResolve($configuration)) {
288 $configuration = $configuration['config'];
289 if ($configuration['MM']) {
290 /** @var $loadDBGroup \TYPO3\CMS\Core\Database\RelationHandler */
291 $loadDBGroup = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\RelationHandler::class);
292 $loadDBGroup->start(
293 $pageRecord[$column],
294 // @todo That depends on the type (group, select, inline)
295 isset($configuration['allowed']) ? $configuration['allowed'] : $configuration['foreign_table'],
296 $configuration['MM'],
297 $uid,
298 'pages',
299 $configuration
300 );
301 $relatedUids = isset($loadDBGroup->tableArray[$configuration['foreign_table']])
302 ? $loadDBGroup->tableArray[$configuration['foreign_table']]
303 : [];
304 } else {
305 // @todo The assumption is wrong, since group can be used without "MM", but having "allowed"
306 $table = $configuration['foreign_table'];
307
308 $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
309 $queryBuilder->getRestrictions()->removeAll()
310 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
311 ->add(GeneralUtility::makeInstance(HiddenRestriction::class));
312 $queryBuilder->select('uid')
313 ->from($table)
314 ->where(
315 $queryBuilder->expr()->eq(
316 $configuration['foreign_field'],
317 $queryBuilder->createNamedParameter(
318 $uid,
319 \PDO::PARAM_INT
320 )
321 )
322 );
323
324 if (isset($configuration['foreign_match_fields']) && is_array($configuration['foreign_match_fields'])) {
325 foreach ($configuration['foreign_match_fields'] as $field => $value) {
326 $queryBuilder->andWhere(
327 $queryBuilder->expr()->eq(
328 $field,
329 $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR)
330 )
331 );
332 }
333 }
334 if (isset($configuration['foreign_table_field'])) {
335 $queryBuilder->andWhere(
336 $queryBuilder->expr()->eq(
337 trim($configuration['foreign_table_field']),
338 $queryBuilder->createNamedParameter(
339 'pages',
340 \PDO::PARAM_STR
341 )
342 )
343 );
344 }
345 if (isset($configuration['foreign_sortby'])) {
346 $queryBuilder->orderBy($configuration['foreign_sortby']);
347 }
348 try {
349 $statement = $queryBuilder->execute();
350 } catch (DBALException $e) {
351 throw new \RuntimeException('Could to resolve related records for page ' . $uid . ' and foreign_table ' . htmlspecialchars($table), 1343589452);
352 }
353 $relatedUids = [];
354 while ($row = $statement->fetch()) {
355 $relatedUids[] = $row['uid'];
356 }
357 }
358 $pageRecord[$column] = implode(',', $relatedUids);
359 }
360 }
361 return $pageRecord;
362 }
363
364 /**
365 * Checks whether the TCA Configuration array of a column
366 * describes a relation which is not stored as CSV in the record
367 *
368 * @param array $configuration TCA configuration to check
369 * @return bool TRUE, if it describes a non-CSV relation
370 */
371 protected function columnHasRelationToResolve(array $configuration)
372 {
373 $configuration = $configuration['config'];
374 if (!empty($configuration['MM']) && !empty($configuration['type']) && in_array($configuration['type'], ['select', 'inline', 'group'])) {
375 return true;
376 }
377 if (!empty($configuration['foreign_field']) && !empty($configuration['type']) && in_array($configuration['type'], ['select', 'inline'])) {
378 return true;
379 }
380 return false;
381 }
382
383 /**
384 * Actual function to generate the rootline and cache it
385 *
386 * @throws \RuntimeException
387 */
388 protected function generateRootlineCache()
389 {
390 $page = $this->getRecordArray($this->pageUid);
391 // If the current page is a mounted (according to the MP parameter) handle the mount-point
392 if ($this->isMountedPage()) {
393 $mountPoint = $this->getRecordArray($this->parsedMountPointParameters[$this->pageUid]);
394 $page = $this->processMountedPage($page, $mountPoint);
395 $parentUid = $mountPoint['pid'];
396 // Anyhow after reaching the mount-point, we have to go up that rootline
397 unset($this->parsedMountPointParameters[$this->pageUid]);
398 } else {
399 $parentUid = $page['pid'];
400 }
401 $cacheTags = ['pageId_' . $page['uid']];
402 if ($parentUid > 0) {
403 // Get rootline of (and including) parent page
404 $mountPointParameter = !empty($this->parsedMountPointParameters) ? $this->mountPointParameter : '';
405 /** @var $rootline \TYPO3\CMS\Core\Utility\RootlineUtility */
406 $rootline = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Utility\RootlineUtility::class, $parentUid, $mountPointParameter, $this->pageContext);
407 $rootline = $rootline->get();
408 // retrieve cache tags of parent rootline
409 foreach ($rootline as $entry) {
410 $cacheTags[] = 'pageId_' . $entry['uid'];
411 if ($entry['uid'] == $this->pageUid) {
412 throw new \RuntimeException('Circular connection in rootline for page with uid ' . $this->pageUid . ' found. Check your mountpoint configuration.', 1343464103);
413 }
414 }
415 } else {
416 $rootline = [];
417 }
418 $rootline[] = $page;
419 krsort($rootline);
420 static::$cache->set($this->cacheIdentifier, $rootline, $cacheTags);
421 static::$localCache[$this->cacheIdentifier] = $rootline;
422 }
423
424 /**
425 * Checks whether the current Page is a Mounted Page
426 * (according to the MP-URL-Parameter)
427 *
428 * @return bool
429 */
430 public function isMountedPage()
431 {
432 return in_array($this->pageUid, array_keys($this->parsedMountPointParameters));
433 }
434
435 /**
436 * Enhances with mount point information or replaces the node if needed
437 *
438 * @param array $mountedPageData page record array of mounted page
439 * @param array $mountPointPageData page record array of mount point page
440 * @throws \RuntimeException
441 * @return array
442 */
443 protected function processMountedPage(array $mountedPageData, array $mountPointPageData)
444 {
445 if ($mountPointPageData['mount_pid'] != $mountedPageData['uid']) {
446 throw new \RuntimeException('Broken rootline. Mountpoint parameter does not match the actual rootline. mount_pid (' . $mountPointPageData['mount_pid'] . ') does not match page uid (' . $mountedPageData['uid'] . ').', 1343464100);
447 }
448 // Current page replaces the original mount-page
449 if ($mountPointPageData['mount_pid_ol']) {
450 $mountedPageData['_MOUNT_OL'] = true;
451 $mountedPageData['_MOUNT_PAGE'] = [
452 'uid' => $mountPointPageData['uid'],
453 'pid' => $mountPointPageData['pid'],
454 'title' => $mountPointPageData['title']
455 ];
456 } else {
457 // The mount-page is not replaced, the mount-page itself has to be used
458 $mountedPageData = $mountPointPageData;
459 }
460 $mountedPageData['_MOUNTED_FROM'] = $this->pageUid;
461 $mountedPageData['_MP_PARAM'] = $this->pageUid . '-' . $mountPointPageData['uid'];
462 return $mountedPageData;
463 }
464
465 /**
466 * Parse the MountPoint Parameters
467 * Splits the MP-Param via "," for several nested mountpoints
468 * and afterwords registers the mountpoint configurations
469 */
470 protected function parseMountPointParameter()
471 {
472 $mountPoints = GeneralUtility::trimExplode(',', $this->mountPointParameter);
473 foreach ($mountPoints as $mP) {
474 list($mountedPageUid, $mountPageUid) = GeneralUtility::intExplode('-', $mP);
475 $this->parsedMountPointParameters[$mountedPageUid] = $mountPageUid;
476 }
477 }
478 }