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