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