2c5dc9ff399e159353c6face7f872da2b5e17e0c
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Tree / Repository / PageTreeRepository.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Backend\Tree\Repository;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
20 use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
21 use TYPO3\CMS\Core\DataHandling\PlainDataResolver;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Versioning\VersionState;
24
25 /**
26 * Fetches ALL pages in the page tree, possibly overlaid with the workspace
27 * in a sorted way.
28 *
29 * This works agnostic of the Backend User, allows to be used in FE as well in the future.
30 *
31 * @internal this class is not public API yet, as it needs to be proven stable enough first.
32 */
33 class PageTreeRepository
34 {
35 /**
36 * Fields to be queried from the database
37 *
38 * @var string[]
39 */
40 protected $fields = [
41 'uid',
42 'pid',
43 'sorting',
44 'starttime',
45 'endtime',
46 'hidden',
47 'fe_group',
48 'title',
49 'nav_title',
50 'nav_hide',
51 'php_tree_stop',
52 'doktype',
53 'is_siteroot',
54 'module',
55 'extendToSubpages',
56 'content_from_pid',
57 't3ver_oid',
58 't3ver_id',
59 't3ver_wsid',
60 't3ver_label',
61 't3ver_state',
62 't3ver_stage',
63 't3ver_tstamp',
64 't3ver_move_id',
65 'perms_userid',
66 'perms_user',
67 'perms_groupid',
68 'perms_group',
69 'perms_everybody',
70 'mount_pid',
71 'shortcut',
72 'shortcut_mode',
73 'mount_pid_ol',
74 'url',
75 ];
76
77 /**
78 * The workspace ID to operate on
79 *
80 * @var int
81 */
82 protected $currentWorkspace = 0;
83
84 /**
85 * Full page tree when selected without permissions applied.
86 *
87 * @var array
88 */
89 protected $fullPageTree = [];
90
91 /**
92 * @param int $workspaceId the workspace ID to be checked for.
93 * @param array $additionalFieldsToQuery an array with more fields that should be accessed.
94 */
95 public function __construct(int $workspaceId = 0, array $additionalFieldsToQuery = [])
96 {
97 $this->currentWorkspace = $workspaceId;
98 if (!empty($additionalFieldsToQuery)) {
99 $this->fields = array_merge($this->fields, $additionalFieldsToQuery);
100 }
101 }
102
103 /**
104 * Main entry point for this repository, to fetch the tree data for a page.
105 * Basically the page record, plus all child pages and their child pages recursively, stored within "_children" item.
106 *
107 * @param int $entryPoint the page ID to fetch the tree for
108 * @param callable $callback a callback to be used to check for permissions and filter out pages not to be included.
109 * @return array
110 */
111 public function getTree(int $entryPoint, callable $callback = null): array
112 {
113 $this->fetchAllPages();
114 if ($entryPoint === 0) {
115 $tree = $this->fullPageTree;
116 } else {
117 $tree = $this->findInPageTree($entryPoint, $this->fullPageTree);
118 }
119 if (!empty($tree) && $callback !== null) {
120 $this->applyCallbackToChildren($tree, $callback);
121 }
122 return $tree;
123 }
124
125 /**
126 * Removes items from a tree based on a callback, usually used for permission checks
127 *
128 * @param array $tree
129 * @param callable $callback
130 */
131 protected function applyCallbackToChildren(array &$tree, callable $callback)
132 {
133 if (!isset($tree['_children'])) {
134 return;
135 }
136 foreach ($tree['_children'] as $k => $childPage) {
137 if (!call_user_func_array($callback, [$childPage])) {
138 unset($tree['_children'][$k]);
139 continue;
140 }
141 $this->applyCallbackToChildren($childPage, $callback);
142 }
143 }
144
145 /**
146 * Fetch all non-deleted pages, regardless of permissions. That's why it's internal.
147 *
148 * @return array the full page tree of the whole installation
149 */
150 protected function fetchAllPages(): array
151 {
152 if (!empty($this->fullPageTree)) {
153 return $this->fullPageTree;
154 }
155 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
156 ->getQueryBuilderForTable('pages');
157 $queryBuilder->getRestrictions()
158 ->removeAll()
159 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
160 ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->currentWorkspace));
161
162 $pageRecords = $queryBuilder
163 ->select(...$this->fields)
164 ->from('pages')
165 ->where(
166 // Only show records in default language
167 $queryBuilder->expr()->eq('sys_language_uid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
168 )
169 ->execute()
170 ->fetchAll();
171
172 $livePagePids = [];
173 $movePlaceholderData = [];
174 // This is necessary to resolve all IDs in a workspace
175 if ($this->currentWorkspace !== 0 && !empty($pageRecords)) {
176 $livePageIds = [];
177 foreach ($pageRecords as $pageRecord) {
178 $livePageIds[] = (int)$pageRecord['uid'];
179 $livePagePids[(int)$pageRecord['uid']] = (int)$pageRecord['pid'];
180 if ((int)$pageRecord['t3ver_state'] === VersionState::MOVE_PLACEHOLDER) {
181 $movePlaceholderData[$pageRecord['t3ver_move_id']] = [
182 'pid' => (int)$pageRecord['pid'],
183 'sorting' => (int)$pageRecord['sorting']
184 ];
185 }
186 }
187 // Resolve placeholders of workspace versions
188 $resolver = GeneralUtility::makeInstance(
189 PlainDataResolver::class,
190 'pages',
191 $livePageIds
192 );
193 $resolver->setWorkspaceId($this->currentWorkspace);
194 $resolver->setKeepDeletePlaceholder(false);
195 $resolver->setKeepMovePlaceholder(false);
196 $resolver->setKeepLiveIds(false);
197 $recordIds = $resolver->get();
198
199 $queryBuilder->getRestrictions()->removeAll();
200 $pageRecords = $queryBuilder
201 ->select(...$this->fields)
202 ->from('pages')
203 ->where(
204 $queryBuilder->expr()->in('uid', $recordIds)
205 )
206 ->execute()
207 ->fetchAll();
208 }
209
210 // Now set up sorting, nesting (tree-structure) for all pages based on pid+sorting fields
211 $groupedAndSortedPagesByPid = [];
212 foreach ($pageRecords as $pageRecord) {
213 $parentPageId = (int)$pageRecord['pid'];
214 // In case this is a record from a workspace
215 // The uid+pid of the live-version record is fetched
216 // This is done in order to avoid fetching records again (e.g. via BackendUtility::workspaceOL()
217 if ($parentPageId === -1) {
218 // When a move pointer is found, the pid+sorting of the MOVE_PLACEHOLDER should be used (this is the
219 // workspace record holding this information), also the t3ver_state is set to the MOVE_PLACEHOLDER
220 // because the record is then added
221 if ((int)$pageRecord['t3ver_state'] === VersionState::MOVE_POINTER && !empty($movePlaceholderData[$pageRecord['t3ver_oid']])) {
222 $parentPageId = (int)$movePlaceholderData[$pageRecord['t3ver_oid']]['pid'];
223 $pageRecord['sorting'] = (int)$movePlaceholderData[$pageRecord['t3ver_oid']]['sorting'];
224 $pageRecord['t3ver_state'] = VersionState::MOVE_PLACEHOLDER;
225 } else {
226 // Just a record in a workspace (not moved etc)
227 $parentPageId = (int)$livePagePids[$pageRecord['t3ver_oid']];
228 }
229 // this is necessary so the links to the modules are still pointing to the live IDs
230 $pageRecord['uid'] = (int)$pageRecord['t3ver_oid'];
231 $pageRecord['pid'] = $parentPageId;
232 }
233
234 $sorting = (int)$pageRecord['sorting'];
235 while (isset($groupedAndSortedPagesByPid[$parentPageId][$sorting])) {
236 $sorting++;
237 }
238 $groupedAndSortedPagesByPid[$parentPageId][$sorting] = $pageRecord;
239 }
240
241 $this->fullPageTree = [
242 'uid' => 0,
243 'title' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] ?: 'TYPO3'
244 ];
245 $this->addChildrenToPage($this->fullPageTree, $groupedAndSortedPagesByPid);
246 return $this->fullPageTree;
247 }
248
249 /**
250 * Adds the property "_children" to a page record with the child pages
251 *
252 * @param array $page
253 * @param array[] $groupedAndSortedPagesByPid
254 */
255 protected function addChildrenToPage(array &$page, array &$groupedAndSortedPagesByPid)
256 {
257 $page['_children'] = $groupedAndSortedPagesByPid[(int)$page['uid']] ?? [];
258 ksort($page['_children']);
259 foreach ($page['_children'] as &$child) {
260 $this->addChildrenToPage($child, $groupedAndSortedPagesByPid);
261 }
262 }
263
264 /**
265 * Looking for a page by traversing the tree
266 *
267 * @param int $pageId the page ID to search for
268 * @param array $pages the page tree to look for the page
269 * @return array Array of the tree data, empty array if nothing was found
270 */
271 protected function findInPageTree(int $pageId, array $pages): array
272 {
273 foreach ($pages['_children'] as $childPage) {
274 if ((int)$childPage['uid'] === $pageId) {
275 return $childPage;
276 }
277 $result = $this->findInPageTree($pageId, $childPage);
278 if (!empty($result)) {
279 return $result;
280 }
281 }
282 return [];
283 }
284 }