[BUGFIX] Show correct page title in new page tree
[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\Controller\UserSettingsController;
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\ConnectionPool;
25 use TYPO3\CMS\Core\Http\JsonResponse;
26 use TYPO3\CMS\Core\Imaging\Icon;
27 use TYPO3\CMS\Core\Imaging\IconFactory;
28 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
29 use TYPO3\CMS\Core\Type\Bitmask\Permission;
30 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
31 use TYPO3\CMS\Core\Utility\GeneralUtility;
32 use TYPO3\CMS\Workspaces\Service\WorkspaceService;
33
34 /**
35 * Controller providing data to the page tree
36 */
37 class TreeController
38 {
39 /**
40 * Option to use the nav_title field for outputting in the tree items, set via userTS.
41 *
42 * @var bool
43 */
44 protected $useNavTitle = false;
45
46 /**
47 * Option to prefix the page ID when outputting the tree items, set via userTS.
48 *
49 * @var bool
50 */
51 protected $addIdAsPrefix = false;
52
53 /**
54 * Option to prefix the domain name of sys_domains when outputting the tree items, set via userTS.
55 *
56 * @var bool
57 */
58 protected $addDomainName = false;
59
60 /**
61 * Option to add the rootline path above each mount point, set via userTS.
62 *
63 * @var bool
64 */
65 protected $showMountPathAboveMounts = false;
66
67 /**
68 * An array of background colors for a branch in the tree, set via userTS.
69 *
70 * @var array
71 */
72 protected $backgroundColors = [];
73
74 /**
75 * A list of pages not to be shown.
76 *
77 * @var array
78 */
79 protected $hiddenRecords = [];
80
81 /**
82 * Contains the state of all items that are expanded.
83 *
84 * @var array
85 */
86 protected $expandedState = [];
87
88 /**
89 * Associative array containing all pageIds as key, and domain names as values.
90 *
91 * @var array|null
92 */
93 protected $domains = null;
94
95 /**
96 * Instance of the icon factory, to be used for generating the items.
97 *
98 * @var IconFactory
99 */
100 protected $iconFactory;
101
102 /**
103 * Constructor to set up common objects needed in various places.
104 */
105 public function __construct()
106 {
107 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
108 $this->useNavTitle = (bool)$this->getBackendUser()->getTSConfigVal('options.pageTree.showNavTitle');
109 }
110
111 /**
112 * Returns page tree configuration in JSON
113 *
114 * @return ResponseInterface
115 */
116 public function fetchConfigurationAction(): ResponseInterface
117 {
118 $configuration = [
119 'allowRecursiveDelete' => !empty($this->getBackendUser()->uc['recursiveDelete']),
120 'doktypes' => $this->getDokTypes(),
121 'displayDeleteConfirmation' => $this->getBackendUser()->jsConfirmation(JsConfirmation::DELETE),
122 'temporaryMountPoint' => $this->getMountPointPath((int)($this->getBackendUser()->uc['pageTree_temporaryMountPoint'] ?? 0)),
123 ];
124
125 return GeneralUtility::makeInstance(JsonResponse::class, $configuration);
126 }
127
128 /**
129 * Returns the list of doktypes to display in page tree toolbar drag area
130 *
131 * Note: The list can be filtered by the user TypoScript
132 * option "options.pageTree.doktypesToShowInNewPageDragArea".
133 *
134 * @return array
135 */
136 protected function getDokTypes(): array
137 {
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(',', $this->getBackendUser()->getTSConfigVal('options.pageTree.doktypesToShowInNewPageDragArea'));
146 $output = [];
147 $allowedDoktypes = GeneralUtility::intExplode(',', $this->getBackendUser()->groupData['pagetypes_select'], true);
148 $isAdmin = $this->getBackendUser()->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($GLOBALS['LANG']->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 $this->hiddenRecords = GeneralUtility::intExplode(',', $this->getBackendUser()->getTSConfigVal('options.hideRecords.pages'), true);
177 $this->backgroundColors = $this->getBackendUser()->getTSConfigProp('options.pageTree.backgroundColor');
178 $this->addIdAsPrefix = (bool)$this->getBackendUser()->getTSConfigVal('options.pageTree.showPageIdWithTitle');
179 $this->addDomainName = (bool)$this->getBackendUser()->getTSConfigVal('options.pageTree.showDomainNameWithTitle');
180 $this->showMountPathAboveMounts = (bool)$this->getBackendUser()->getTSConfigVal('options.pageTree.showPathAboveMounts');
181 $userSettingsController = GeneralUtility::makeInstance(UserSettingsController::class);
182 $this->expandedState = $userSettingsController->process('get', 'BackendComponents.States.Pagetree');
183 if (is_object($this->expandedState->stateHash)) {
184 $this->expandedState = (array)$this->expandedState->stateHash;
185 } else {
186 $this->expandedState = $this->expandedState['stateHash'] ?: [];
187 }
188
189 // Fetching a part of a pagetree
190 if (!empty($request->getQueryParams()['pid'])) {
191 $entryPoints = [(int)$request->getQueryParams()['pid']];
192 } else {
193 $entryPoints = $this->getAllEntryPointPageTrees();
194 }
195 $items = [];
196 foreach ($entryPoints as $page) {
197 $items = array_merge($items, $this->pagesToFlatArray($page, (int)$page['uid']));
198 }
199
200 return GeneralUtility::makeInstance(JsonResponse::class, $items);
201 }
202
203 /**
204 * Sets a temporary mount point
205 *
206 * @param ServerRequestInterface $request
207 * @return ResponseInterface
208 * @throws \RuntimeException
209 */
210 public function setTemporaryMountPointAction(ServerRequestInterface $request): ResponseInterface
211 {
212 if (empty($request->getParsedBody()['pid'])) {
213 throw new \RuntimeException(
214 'Required "pid" parameter is missing.',
215 1511792197
216 );
217 }
218 $pid = (int)$request->getParsedBody()['pid'];
219
220 $this->getBackendUser()->uc['pageTree_temporaryMountPoint'] = $pid;
221 $this->getBackendUser()->writeUC();
222 $response = [
223 'mountPointPath' => $this->getMountPointPath($pid)
224 ];
225 return GeneralUtility::makeInstance(JsonResponse::class, $response);
226 }
227
228 /**
229 * Converts nested tree structure produced by PageTreeRepository to a flat, one level array
230 * and also adds visual representation information to the data.
231 *
232 * @param array $page
233 * @param int $entryPoint
234 * @param int $depth
235 * @param array $inheritedData
236 * @return array
237 */
238 protected function pagesToFlatArray(array $page, int $entryPoint, int $depth = 0, array $inheritedData = []): array
239 {
240 $pageId = (int)$page['uid'];
241 if (in_array($pageId, $this->hiddenRecords, true)) {
242 return [];
243 }
244
245 $stopPageTree = $page['php_tree_stop'] && $depth > 0;
246 $identifier = $entryPoint . '_' . $pageId;
247 $expanded = $page['expanded'] || (isset($this->expandedState[$identifier]) && $this->expandedState[$identifier]);
248 $backgroundColor = $this->backgroundColors[$pageId] ?: ($inheritedData['backgroundColor'] ?? '');
249
250 $suffix = '';
251 $prefix = '';
252 $nameSourceField = 'title';
253 $visibleText = $page['title'];
254 $tooltip = BackendUtility::titleAttribForPages($page, '', false);
255 if ($pageId !== 0) {
256 $icon = $this->iconFactory->getIconForRecord('pages', $page, Icon::SIZE_SMALL);
257 } else {
258 $icon = $this->iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL);
259 }
260
261 if ($this->useNavTitle && trim($page['nav_title'] ?? '') !== '') {
262 $nameSourceField = 'nav_title';
263 $visibleText = $page['nav_title'];
264 }
265 if (trim($visibleText) === '') {
266 $visibleText = htmlspecialchars('[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.no_title') . ']');
267 }
268 $visibleText = GeneralUtility::fixed_lgd_cs($visibleText, (int)$this->getBackendUser()->uc['titleLen'] ?: 40);
269
270 if ($this->addDomainName) {
271 $domain = $this->getDomainNameForPage($pageId);
272 $suffix = $domain !== '' ? ' [' . $domain . ']' : '';
273 }
274
275 $lockInfo = BackendUtility::isRecordLocked('pages', $pageId);
276 if (is_array($lockInfo)) {
277 $tooltip .= ' - ' . $lockInfo['msg'];
278 $prefix = '<span class="typo3-pagetree-status">' . $this->iconFactory->getIcon('warning-in-use', Icon::SIZE_SMALL)->render() . '</span>';
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 'alias' => htmlspecialchars($page['alias'] ?: ''),
296 'prefix' => htmlspecialchars($prefix),
297 'suffix' => htmlspecialchars($suffix),
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' => $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 $repository = GeneralUtility::makeInstance(PageTreeRepository::class, (int)$backendUser->workspace);
327 $entryPoints = (int)($backendUser->uc['pageTree_temporaryMountPoint'] ?? 0);
328 if ($entryPoints > 0) {
329 $entryPoints = [$entryPoints];
330 } else {
331 $entryPoints = array_map('intval', $backendUser->returnWebmounts());
332 $entryPoints = array_unique($entryPoints);
333 if (empty($entryPoints)) {
334 // use a virtual root
335 // the real mount points will be fetched in getNodes() then
336 // since those will be the "sub pages" of the virtual root
337 $entryPoints = [0];
338 }
339 }
340 if (empty($entryPoints)) {
341 return [];
342 }
343 foreach ($entryPoints as $k => &$entryPoint) {
344 if (in_array($entryPoint, $this->hiddenRecords, true)) {
345 unset($entryPoints[$k]);
346 continue;
347 }
348 $entryPoint = $repository->getTree($entryPoint, function ($page) use ($backendUser) {
349 // check each page if the user has permission to access it
350 return $backendUser->doesUserHaveAccess($page, Permission::PAGE_SHOW);
351 });
352 if (!is_array($entryPoint)) {
353 unset($entryPoints[$k]);
354 }
355 }
356
357 return $entryPoints;
358 }
359
360 /**
361 * Returns the first configured domain name for a page
362 *
363 * @param int $pageId
364 * @return string
365 */
366 protected function getDomainNameForPage(int $pageId): string
367 {
368 if (!is_array($this->domains)) {
369 $this->domains = [];
370 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
371 ->getQueryBuilderForTable('sys_domain');
372 $result = $queryBuilder
373 ->select('domainName', 'pid')
374 ->from('sys_domain')
375 ->where(
376 $queryBuilder->expr()->neq('redirectTo', $queryBuilder->createNamedParameter('""'))
377 )
378 ->orderBy('sorting')
379 ->execute()
380 ->fetchAll();
381 foreach ($result as $domain) {
382 $domainPid = (int)$domain['pid'];
383 if (!isset($this->domains[$domainPid])) {
384 $this->domains[$domainPid] = $domain['domainName'];
385 }
386 }
387 }
388 return $this->domains[$pageId] ?? '';
389 }
390
391 /**
392 * Returns the mount point path for a temporary mount or the given id
393 *
394 * @param int $uid
395 * @return string
396 */
397 protected function getMountPointPath(int $uid): string
398 {
399 if ($uid <= 0) {
400 return '';
401 }
402 $rootline = array_reverse(BackendUtility::BEgetRootLine($uid));
403 array_shift($rootline);
404 $path = [];
405 foreach ($rootline as $rootlineElement) {
406 $record = BackendUtility::getRecordWSOL('pages', $rootlineElement['uid'], 'title, nav_title', '', true, true);
407 $text = $record['title'];
408 if ($this->useNavTitle && trim($record['nav_title'] ?? '') !== '') {
409 $text = $record['nav_title'];
410 }
411 $path[] = htmlspecialchars($text);
412 }
413 return '/' . implode('/', $path);
414 }
415
416 /**
417 * Fetches possible css class names to be used when a record was modified in a workspace
418 *
419 * @param array $page Page record (workspace overlaid)
420 * @return string CSS class names to be applied
421 */
422 protected function resolvePageCssClassNames(array $page): string
423 {
424 $classes = [];
425
426 $workspaceId = (int)$this->getBackendUser()->workspace;
427 if ($workspaceId > 0 && ExtensionManagementUtility::isLoaded('workspaces')) {
428 if ($page['t3ver_oid'] > 0 && (int)$page['t3ver_wsid'] === $workspaceId) {
429 $classes[] = 'ver-element';
430 $classes[] = 'ver-versions';
431 } elseif (
432 $this->getWorkspaceService()->hasPageRecordVersions(
433 $workspaceId,
434 $page['t3ver_oid'] ?: $page['uid']
435 )
436 ) {
437 $classes[] = 'ver-versions';
438 }
439 }
440
441 return implode(' ', $classes);
442 }
443
444 /**
445 * @return WorkspaceService
446 */
447 protected function getWorkspaceService(): WorkspaceService
448 {
449 return GeneralUtility::makeInstance(WorkspaceService::class);
450 }
451
452 /**
453 * @return BackendUserAuthentication
454 */
455 protected function getBackendUser(): BackendUserAuthentication
456 {
457 return $GLOBALS['BE_USER'];
458 }
459 }