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