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