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