[BUGFIX] Add missing icon overlay for pages in page tree
[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\BackendWorkspaceRestriction;
20 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
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 'alias',
52 'php_tree_stop',
53 'doktype',
54 'is_siteroot',
55 'module',
56 'extendToSubpages',
57 'content_from_pid',
58 't3ver_oid',
59 't3ver_id',
60 't3ver_wsid',
61 't3ver_label',
62 't3ver_state',
63 't3ver_stage',
64 't3ver_tstamp',
65 't3ver_move_id',
66 'perms_userid',
67 'perms_user',
68 'perms_groupid',
69 'perms_group',
70 'perms_everybody',
71 ];
72
73 /**
74 * The workspace ID to operate on
75 *
76 * @var int
77 */
78 protected $currentWorkspace = 0;
79
80 /**
81 * Full page tree when selected without permissions applied.
82 *
83 * @var array
84 */
85 protected $fullPageTree = [];
86
87 /**
88 * @param int $workspaceId the workspace ID to be checked for.
89 * @param array $additionalFieldsToQuery an array with more fields that should be accessed.
90 */
91 public function __construct(int $workspaceId = 0, array $additionalFieldsToQuery = [])
92 {
93 $this->currentWorkspace = $workspaceId;
94 if (!empty($additionalFieldsToQuery)) {
95 $this->fields = array_merge($this->fields, $additionalFieldsToQuery);
96 }
97 }
98
99 /**
100 * Main entry point for this repository, to fetch the tree data for a page.
101 * Basically the page record, plus all child pages and their child pages recursively, stored within "_children" item.
102 *
103 * @param int $entryPoint the page ID to fetch the tree for
104 * @param callable $callback a callback to be used to check for permissions and filter out pages not to be included.
105 * @return array
106 */
107 public function getTree(int $entryPoint, callable $callback = null): array
108 {
109 $this->fetchAllPages();
110 if ($entryPoint === 0) {
111 $tree = $this->fullPageTree;
112 } else {
113 $tree = $this->findInPageTree($entryPoint, $this->fullPageTree);
114 }
115 if (!empty($tree) && $callback !== null) {
116 $this->applyCallbackToChildren($tree, $callback);
117 }
118 return $tree;
119 }
120
121 /**
122 * Removes items from a tree based on a callback, usually used for permission checks
123 *
124 * @param array $tree
125 * @param callable $callback
126 */
127 protected function applyCallbackToChildren(array &$tree, callable $callback)
128 {
129 if (!isset($tree['_children'])) {
130 return;
131 }
132 foreach ($tree['_children'] as $k => $childPage) {
133 if (!call_user_func_array($callback, [$childPage])) {
134 unset($tree['_children'][$k]);
135 continue;
136 }
137 $this->applyCallbackToChildren($childPage, $callback);
138 }
139 }
140
141 /**
142 * Fetch all non-deleted pages, regardless of permissions. That's why it's internal.
143 *
144 * @return array the full page tree of the whole installation
145 */
146 protected function fetchAllPages(): array
147 {
148 if (!empty($this->fullPageTree)) {
149 return $this->fullPageTree;
150 }
151 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
152 ->getQueryBuilderForTable('pages');
153 $queryBuilder->getRestrictions()
154 ->removeAll()
155 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
156 ->add(GeneralUtility::makeInstance(
157 BackendWorkspaceRestriction::class,
158 $this->currentWorkspace,
159 // set this flag to "true" when inside a workspace
160 $this->currentWorkspace !== 0
161 ));
162
163 $pageRecords = $queryBuilder
164 ->select(...$this->fields)
165 ->from('pages')
166 ->where(
167 // Only show records in default language
168 $queryBuilder->expr()->eq('sys_language_uid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
169 )
170 ->execute()
171 ->fetchAll();
172
173 $livePagePids = [];
174 $movePlaceholderData = [];
175 // This is necessary to resolve all IDs in a workspace
176 if ($this->currentWorkspace !== 0 && !empty($pageRecords)) {
177 $livePageIds = [];
178 foreach ($pageRecords as $pageRecord) {
179 // BackendWorkspaceRestriction includes drafts from ALL workspaces, we need to ensure
180 // that only the live records and the drafts from the current workspace are used
181 if (!in_array((int)$pageRecord['t3ver_wsid'], [0, $this->currentWorkspace], true)) {
182 continue;
183 }
184 $livePageIds[] = (int)$pageRecord['uid'];
185 $livePagePids[(int)$pageRecord['uid']] = (int)$pageRecord['pid'];
186 if ((int)$pageRecord['t3ver_state'] === VersionState::MOVE_PLACEHOLDER) {
187 $movePlaceholderData[$pageRecord['t3ver_move_id']] = [
188 'pid' => (int)$pageRecord['pid'],
189 'sorting' => (int)$pageRecord['sorting']
190 ];
191 }
192 }
193 // Resolve placeholders of workspace versions
194 $resolver = GeneralUtility::makeInstance(
195 PlainDataResolver::class,
196 'pages',
197 $livePageIds
198 );
199 $resolver->setWorkspaceId($this->currentWorkspace);
200 $resolver->setKeepDeletePlaceholder(false);
201 $resolver->setKeepMovePlaceholder(false);
202 $resolver->setKeepLiveIds(false);
203 $recordIds = $resolver->get();
204
205 $queryBuilder->getRestrictions()->removeAll();
206 $pageRecords = $queryBuilder
207 ->select(...$this->fields)
208 ->from('pages')
209 ->where(
210 $queryBuilder->expr()->in('uid', $recordIds)
211 )
212 ->execute()
213 ->fetchAll();
214 }
215
216 // Now set up sorting, nesting (tree-structure) for all pages based on pid+sorting fields
217 $groupedAndSortedPagesByPid = [];
218 foreach ($pageRecords as $pageRecord) {
219 $parentPageId = (int)$pageRecord['pid'];
220 // In case this is a record from a workspace
221 // The uid+pid of the live-version record is fetched
222 // This is done in order to avoid fetching records again (e.g. via BackendUtility::workspaceOL()
223 if ($parentPageId === -1) {
224 // When a move pointer is found, the pid+sorting of the MOVE_PLACEHOLDER should be used (this is the
225 // workspace record holding this information), also the t3ver_state is set to the MOVE_PLACEHOLDER
226 // because the record is then added
227 if ((int)$pageRecord['t3ver_state'] === VersionState::MOVE_POINTER && !empty($movePlaceholderData[$pageRecord['t3ver_oid']])) {
228 $parentPageId = (int)$movePlaceholderData[$pageRecord['t3ver_oid']]['pid'];
229 $pageRecord['sorting'] = (int)$movePlaceholderData[$pageRecord['t3ver_oid']]['sorting'];
230 $pageRecord['t3ver_state'] = VersionState::MOVE_PLACEHOLDER;
231 } else {
232 // Just a record in a workspace (not moved etc)
233 $parentPageId = (int)$livePagePids[$pageRecord['t3ver_oid']];
234 }
235 // this is necessary so the links to the modules are still pointing to the live IDs
236 $pageRecord['uid'] = (int)$pageRecord['t3ver_oid'];
237 $pageRecord['pid'] = $parentPageId;
238 }
239
240 $sorting = (int)$pageRecord['sorting'];
241 while (isset($groupedAndSortedPagesByPid[$parentPageId][$sorting])) {
242 $sorting++;
243 }
244 $groupedAndSortedPagesByPid[$parentPageId][$sorting] = $pageRecord;
245 }
246
247 $this->fullPageTree = [
248 'uid' => 0,
249 'title' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] ?: 'TYPO3'
250 ];
251 $this->addChildrenToPage($this->fullPageTree, $groupedAndSortedPagesByPid);
252 return $this->fullPageTree;
253 }
254
255 /**
256 * Adds the property "_children" to a page record with the child pages
257 *
258 * @param array $page
259 * @param array[] $groupedAndSortedPagesByPid
260 */
261 protected function addChildrenToPage(array &$page, array &$groupedAndSortedPagesByPid)
262 {
263 $page['_children'] = $groupedAndSortedPagesByPid[(int)$page['uid']] ?? [];
264 ksort($page['_children']);
265 foreach ($page['_children'] as &$child) {
266 $this->addChildrenToPage($child, $groupedAndSortedPagesByPid);
267 }
268 }
269
270 /**
271 * Looking for a page by traversing the tree
272 *
273 * @param int $pageId the page ID to search for
274 * @param array $pages the page tree to look for the page
275 * @return array Array of the tree data, empty array if nothing was found
276 */
277 protected function findInPageTree(int $pageId, array $pages): array
278 {
279 foreach ($pages['_children'] as $childPage) {
280 if ((int)$childPage['uid'] === $pageId) {
281 return $childPage;
282 }
283 $result = $this->findInPageTree($pageId, $childPage);
284 if (!empty($result)) {
285 return $result;
286 }
287 }
288 return [];
289 }
290 }