[!!!][TASK] Remove Pseudo-Site Handling
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / Page / TreeController.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Backend\Controller\Page;
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 Psr\Http\Message\ResponseInterface;
19 use Psr\Http\Message\ServerRequestInterface;
20 use TYPO3\CMS\Backend\Configuration\BackendUserConfiguration;
21 use TYPO3\CMS\Backend\Tree\Repository\PageTreeRepository;
22 use TYPO3\CMS\Backend\Utility\BackendUtility;
23 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
24 use TYPO3\CMS\Core\Database\Query\Restriction\DocumentTypeExclusionRestriction;
25 use TYPO3\CMS\Core\Exception\Page\RootLineException;
26 use TYPO3\CMS\Core\Exception\SiteNotFoundException;
27 use TYPO3\CMS\Core\Http\JsonResponse;
28 use TYPO3\CMS\Core\Imaging\Icon;
29 use TYPO3\CMS\Core\Imaging\IconFactory;
30 use TYPO3\CMS\Core\Localization\LanguageService;
31 use TYPO3\CMS\Core\Site\SiteFinder;
32 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
33 use TYPO3\CMS\Core\Type\Bitmask\Permission;
34 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
35 use TYPO3\CMS\Core\Utility\GeneralUtility;
36 use TYPO3\CMS\Core\Utility\RootlineUtility;
37 use TYPO3\CMS\Workspaces\Service\WorkspaceService;
38
39 /**
40 * Controller providing data to the page tree
41 * @internal This class is a specific Backend controller implementation and is not considered part of the Public TYPO3 API.
42 */
43 class TreeController
44 {
45 /**
46 * Option to use the nav_title field for outputting in the tree items, set via userTS.
47 *
48 * @var bool
49 */
50 protected $useNavTitle = false;
51
52 /**
53 * Option to prefix the page ID when outputting the tree items, set via userTS.
54 *
55 * @var bool
56 */
57 protected $addIdAsPrefix = false;
58
59 /**
60 * Option to prefix the domain name of sys_domains when outputting the tree items, set via userTS.
61 *
62 * @var bool
63 */
64 protected $addDomainName = false;
65
66 /**
67 * Option to add the rootline path above each mount point, set via userTS.
68 *
69 * @var bool
70 */
71 protected $showMountPathAboveMounts = false;
72
73 /**
74 * An array of background colors for a branch in the tree, set via userTS.
75 *
76 * @var array
77 */
78 protected $backgroundColors = [];
79
80 /**
81 * A list of pages not to be shown.
82 *
83 * @var array
84 */
85 protected $hiddenRecords = [];
86
87 /**
88 * Contains the state of all items that are expanded.
89 *
90 * @var array
91 */
92 protected $expandedState = [];
93
94 /**
95 * Instance of the icon factory, to be used for generating the items.
96 *
97 * @var IconFactory
98 */
99 protected $iconFactory;
100
101 /**
102 * Constructor to set up common objects needed in various places.
103 */
104 public function __construct()
105 {
106 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
107 $this->useNavTitle = (bool)($this->getBackendUser()->getTSConfig()['options.']['pageTree.']['showNavTitle'] ?? false);
108 }
109
110 /**
111 * Returns page tree configuration in JSON
112 *
113 * @return ResponseInterface
114 */
115 public function fetchConfigurationAction(): ResponseInterface
116 {
117 $configuration = [
118 'allowRecursiveDelete' => !empty($this->getBackendUser()->uc['recursiveDelete']),
119 'doktypes' => $this->getDokTypes(),
120 'displayDeleteConfirmation' => $this->getBackendUser()->jsConfirmation(JsConfirmation::DELETE),
121 'temporaryMountPoint' => $this->getMountPointPath((int)($this->getBackendUser()->uc['pageTree_temporaryMountPoint'] ?? 0)),
122 ];
123
124 return new JsonResponse($configuration);
125 }
126
127 /**
128 * Returns the list of doktypes to display in page tree toolbar drag area
129 *
130 * Note: The list can be filtered by the user TypoScript
131 * option "options.pageTree.doktypesToShowInNewPageDragArea".
132 *
133 * @return array
134 */
135 protected function getDokTypes(): array
136 {
137 $backendUser = $this->getBackendUser();
138 $doktypeLabelMap = [];
139 foreach ($GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'] as $doktypeItemConfig) {
140 if ($doktypeItemConfig[1] === '--div--') {
141 continue;
142 }
143 $doktypeLabelMap[$doktypeItemConfig[1]] = $doktypeItemConfig[0];
144 }
145 $doktypes = GeneralUtility::intExplode(',', $backendUser->getTSConfig()['options.']['pageTree.']['doktypesToShowInNewPageDragArea'] ?? '', true);
146 $output = [];
147 $allowedDoktypes = GeneralUtility::intExplode(',', $backendUser->groupData['pagetypes_select'], true);
148 $isAdmin = $backendUser->isAdmin();
149 // Early return if backend user may not create any doktype
150 if (!$isAdmin && empty($allowedDoktypes)) {
151 return $output;
152 }
153 foreach ($doktypes as $doktype) {
154 if (!$isAdmin && !in_array($doktype, $allowedDoktypes, true)) {
155 continue;
156 }
157 $label = htmlspecialchars($this->getLanguageService()->sL($doktypeLabelMap[$doktype]));
158 $output[] = [
159 'nodeType' => $doktype,
160 'icon' => $GLOBALS['TCA']['pages']['ctrl']['typeicon_classes'][$doktype] ?? '',
161 'title' => $label,
162 'tooltip' => $label
163 ];
164 }
165 return $output;
166 }
167
168 /**
169 * Returns JSON representing page tree
170 *
171 * @param ServerRequestInterface $request
172 * @return ResponseInterface
173 */
174 public function fetchDataAction(ServerRequestInterface $request): ResponseInterface
175 {
176 $userTsConfig = $this->getBackendUser()->getTSConfig();
177 $this->hiddenRecords = GeneralUtility::intExplode(',', $userTsConfig['options.']['hideRecords.']['pages'] ?? '', true);
178 $this->backgroundColors = $userTsConfig['options.']['pageTree.']['backgroundColor.'] ?? [];
179 $this->addIdAsPrefix = (bool)($userTsConfig['options.']['pageTree.']['showPageIdWithTitle'] ?? false);
180 $this->addDomainName = (bool)($userTsConfig['options.']['pageTree.']['showDomainNameWithTitle'] ?? false);
181 $this->showMountPathAboveMounts = (bool)($userTsConfig['options.']['pageTree.']['showPathAboveMounts'] ?? false);
182 $backendUserConfiguration = GeneralUtility::makeInstance(BackendUserConfiguration::class);
183 $this->expandedState = $backendUserConfiguration->get('BackendComponents.States.Pagetree');
184 if (is_object($this->expandedState) && is_object($this->expandedState->stateHash)) {
185 $this->expandedState = (array)$this->expandedState->stateHash;
186 } else {
187 $this->expandedState = $this->expandedState['stateHash'] ?: [];
188 }
189
190 // Fetching a part of a pagetree
191 if (!empty($request->getQueryParams()['pid'])) {
192 $entryPoints = [(int)$request->getQueryParams()['pid']];
193 } else {
194 $entryPoints = $this->getAllEntryPointPageTrees();
195 }
196 $items = [];
197 foreach ($entryPoints as $page) {
198 $items = array_merge($items, $this->pagesToFlatArray($page, (int)$page['uid']));
199 }
200
201 return new JsonResponse($items);
202 }
203
204 /**
205 * Sets a temporary mount point
206 *
207 * @param ServerRequestInterface $request
208 * @return ResponseInterface
209 * @throws \RuntimeException
210 */
211 public function setTemporaryMountPointAction(ServerRequestInterface $request): ResponseInterface
212 {
213 if (empty($request->getParsedBody()['pid'])) {
214 throw new \RuntimeException(
215 'Required "pid" parameter is missing.',
216 1511792197
217 );
218 }
219 $pid = (int)$request->getParsedBody()['pid'];
220
221 $this->getBackendUser()->uc['pageTree_temporaryMountPoint'] = $pid;
222 $this->getBackendUser()->writeUC();
223 $response = [
224 'mountPointPath' => $this->getMountPointPath($pid)
225 ];
226 return new JsonResponse($response);
227 }
228
229 /**
230 * Converts nested tree structure produced by PageTreeRepository to a flat, one level array
231 * and also adds visual representation information to the data.
232 *
233 * @param array $page
234 * @param int $entryPoint
235 * @param int $depth
236 * @param array $inheritedData
237 * @return array
238 */
239 protected function pagesToFlatArray(array $page, int $entryPoint, int $depth = 0, array $inheritedData = []): array
240 {
241 $pageId = (int)$page['uid'];
242 if (in_array($pageId, $this->hiddenRecords, true)) {
243 return [];
244 }
245
246 $stopPageTree = !empty($page['php_tree_stop']) && $depth > 0;
247 $identifier = $entryPoint . '_' . $pageId;
248 $expanded = !empty($page['expanded']) || (isset($this->expandedState[$identifier]) && $this->expandedState[$identifier]);
249 $backgroundColor = !empty($this->backgroundColors[$pageId]) ? $this->backgroundColors[$pageId] : ($inheritedData['backgroundColor'] ?? '');
250
251 $suffix = '';
252 $prefix = '';
253 $nameSourceField = 'title';
254 $visibleText = $page['title'];
255 $tooltip = BackendUtility::titleAttribForPages($page, '', false);
256 if ($pageId !== 0) {
257 $icon = $this->iconFactory->getIconForRecord('pages', $page, Icon::SIZE_SMALL);
258 } else {
259 $icon = $this->iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL);
260 }
261
262 if ($this->useNavTitle && trim($page['nav_title'] ?? '') !== '') {
263 $nameSourceField = 'nav_title';
264 $visibleText = $page['nav_title'];
265 }
266 if (trim($visibleText) === '') {
267 $visibleText = htmlspecialchars('[' . $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.no_title') . ']');
268 }
269 $visibleText = GeneralUtility::fixed_lgd_cs($visibleText, (int)$this->getBackendUser()->uc['titleLen'] ?: 40);
270
271 if ($this->addDomainName && $page['is_siteroot']) {
272 $domain = $this->getDomainNameForPage($pageId);
273 $suffix = $domain !== '' ? ' [' . $domain . ']' : '';
274 }
275
276 $lockInfo = BackendUtility::isRecordLocked('pages', $pageId);
277 if (is_array($lockInfo)) {
278 $tooltip .= ' - ' . $lockInfo['msg'];
279 }
280 if ($this->addIdAsPrefix) {
281 $prefix = htmlspecialchars('[' . $pageId . '] ');
282 }
283
284 $items = [];
285 $items[] = [
286 // Used to track if the tree item is collapsed or not
287 'stateIdentifier' => $identifier,
288 'identifier' => $pageId,
289 'depth' => $depth,
290 'tip' => htmlspecialchars($tooltip),
291 'hasChildren' => !empty($page['_children']),
292 'icon' => $icon->getIdentifier(),
293 'name' => $visibleText,
294 'nameSourceField' => $nameSourceField,
295 'prefix' => htmlspecialchars($prefix),
296 'suffix' => htmlspecialchars($suffix),
297 'locked' => is_array($lockInfo),
298 'overlayIcon' => $icon->getOverlayIcon() ? $icon->getOverlayIcon()->getIdentifier() : '',
299 'selectable' => true,
300 'expanded' => (bool)$expanded,
301 'checked' => false,
302 'backgroundColor' => htmlspecialchars($backgroundColor),
303 'stopPageTree' => $stopPageTree,
304 'class' => $this->resolvePageCssClassNames($page),
305 'readableRootline' => $depth === 0 && $this->showMountPathAboveMounts ? $this->getMountPointPath($pageId) : '',
306 'isMountPoint' => $depth === 0,
307 'mountPoint' => $entryPoint,
308 'workspaceId' => !empty($page['t3ver_oid']) ? $page['t3ver_oid'] : $pageId,
309 ];
310 if (!$stopPageTree) {
311 foreach ($page['_children'] as $child) {
312 $items = array_merge($items, $this->pagesToFlatArray($child, $entryPoint, $depth + 1, ['backgroundColor' => $backgroundColor]));
313 }
314 }
315 return $items;
316 }
317
318 /**
319 * Fetches all entry points for the page tree that the user is allowed to see
320 *
321 * @return array
322 */
323 protected function getAllEntryPointPageTrees(): array
324 {
325 $backendUser = $this->getBackendUser();
326
327 $userTsConfig = $this->getBackendUser()->getTSConfig();
328 $excludedDocumentTypes = GeneralUtility::intExplode(',', $userTsConfig['options.']['pageTree.']['excludeDoktypes'] ?? '', true);
329
330 $additionalPageTreeQueryRestrictions = [];
331 if (!empty($excludedDocumentTypes)) {
332 foreach ($excludedDocumentTypes as $excludedDocumentType) {
333 $additionalPageTreeQueryRestrictions[] = new DocumentTypeExclusionRestriction((int)$excludedDocumentType);
334 }
335 }
336
337 $repository = GeneralUtility::makeInstance(PageTreeRepository::class, (int)$backendUser->workspace, [], $additionalPageTreeQueryRestrictions);
338
339 $entryPoints = (int)($backendUser->uc['pageTree_temporaryMountPoint'] ?? 0);
340 if ($entryPoints > 0) {
341 $entryPoints = [$entryPoints];
342 } else {
343 $entryPoints = array_map('intval', $backendUser->returnWebmounts());
344 $entryPoints = array_unique($entryPoints);
345 if (empty($entryPoints)) {
346 // use a virtual root
347 // the real mount points will be fetched in getNodes() then
348 // since those will be the "sub pages" of the virtual root
349 $entryPoints = [0];
350 }
351 }
352 if (empty($entryPoints)) {
353 return [];
354 }
355
356 foreach ($entryPoints as $k => &$entryPoint) {
357 if (in_array($entryPoint, $this->hiddenRecords, true)) {
358 unset($entryPoints[$k]);
359 continue;
360 }
361
362 if (!empty($this->backgroundColors) && is_array($this->backgroundColors)) {
363 try {
364 $entryPointRootLine = GeneralUtility::makeInstance(RootlineUtility::class, $entryPoint)->get();
365 } catch (RootLineException $e) {
366 $entryPointRootLine = [];
367 }
368 foreach ($entryPointRootLine as $rootLineEntry) {
369 $parentUid = $rootLineEntry['uid'];
370 if (!empty($this->backgroundColors[$parentUid]) && empty($this->backgroundColors[$entryPoint])) {
371 $this->backgroundColors[$entryPoint] = $this->backgroundColors[$parentUid];
372 }
373 }
374 }
375
376 $entryPoint = $repository->getTree($entryPoint, function ($page) use ($backendUser) {
377 // check each page if the user has permission to access it
378 return $backendUser->doesUserHaveAccess($page, Permission::PAGE_SHOW);
379 });
380 if (!is_array($entryPoint)) {
381 unset($entryPoints[$k]);
382 }
383 }
384
385 return $entryPoints;
386 }
387
388 /**
389 * Returns the first configured domain name for a page
390 *
391 * @param int $pageId
392 * @return string
393 */
394 protected function getDomainNameForPage(int $pageId): string
395 {
396 $domain = '';
397 $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
398 try {
399 $site = $siteFinder->getSiteByRootPageId($pageId);
400 $domain = (string)$site->getBase();
401 } catch (SiteNotFoundException $e) {
402 // No site found
403 }
404
405 return $domain;
406 }
407
408 /**
409 * Returns the mount point path for a temporary mount or the given id
410 *
411 * @param int $uid
412 * @return string
413 */
414 protected function getMountPointPath(int $uid): string
415 {
416 if ($uid <= 0) {
417 return '';
418 }
419 $rootline = array_reverse(BackendUtility::BEgetRootLine($uid));
420 array_shift($rootline);
421 $path = [];
422 foreach ($rootline as $rootlineElement) {
423 $record = BackendUtility::getRecordWSOL('pages', $rootlineElement['uid'], 'title, nav_title', '', true, true);
424 $text = $record['title'];
425 if ($this->useNavTitle && trim($record['nav_title'] ?? '') !== '') {
426 $text = $record['nav_title'];
427 }
428 $path[] = htmlspecialchars($text);
429 }
430 return '/' . implode('/', $path);
431 }
432
433 /**
434 * Fetches possible css class names to be used when a record was modified in a workspace
435 *
436 * @param array $page Page record (workspace overlaid)
437 * @return string CSS class names to be applied
438 */
439 protected function resolvePageCssClassNames(array $page): string
440 {
441 $classes = [];
442
443 if ($page['uid'] === 0) {
444 return '';
445 }
446 $workspaceId = (int)$this->getBackendUser()->workspace;
447 if ($workspaceId > 0 && ExtensionManagementUtility::isLoaded('workspaces')) {
448 if ($page['t3ver_oid'] > 0 && (int)$page['t3ver_wsid'] === $workspaceId) {
449 $classes[] = 'ver-element';
450 $classes[] = 'ver-versions';
451 } elseif (
452 $this->getWorkspaceService()->hasPageRecordVersions(
453 $workspaceId,
454 $page['t3ver_oid'] ?: $page['uid']
455 )
456 ) {
457 $classes[] = 'ver-versions';
458 }
459 }
460
461 return implode(' ', $classes);
462 }
463
464 /**
465 * @return WorkspaceService
466 */
467 protected function getWorkspaceService(): WorkspaceService
468 {
469 return GeneralUtility::makeInstance(WorkspaceService::class);
470 }
471
472 /**
473 * @return BackendUserAuthentication
474 */
475 protected function getBackendUser(): BackendUserAuthentication
476 {
477 return $GLOBALS['BE_USER'];
478 }
479
480 /**
481 * @return LanguageService|null
482 */
483 protected function getLanguageService(): ?LanguageService
484 {
485 return $GLOBALS['LANG'] ?? null;
486 }
487 }