-
Notifications
You must be signed in to change notification settings - Fork 8
/
PageTreeRepository.php
786 lines (713 loc) · 31.6 KB
/
PageTreeRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Backend\Tree\Repository;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
use TYPO3\CMS\Core\DataHandling\PlainDataResolver;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Versioning\VersionState;
/**
* Fetches ALL pages in the page tree, possibly overlaid with the workspace
* in a sorted way.
*
* This works agnostic of the Backend User, allows to be used in FE as well in the future.
*
* @internal this class is not public API yet, as it needs to be proven stable enough first.
*/
class PageTreeRepository
{
/**
* Fields to be queried from the database
*
* @var string[]
*/
protected readonly array $fields;
/**
* The fields array, quoted for repeated use in recursive pages queries, to avoid the need to newly
* quote the fields for each single query (which can get really expensive for a large amount of fields)
* @var string[]
*/
protected readonly array $quotedFields;
/**
* The workspace ID to operate on
*/
protected readonly int $currentWorkspace;
/**
* Full page tree when selected without permissions applied.
*/
protected array $fullPageTree = [];
protected readonly array $additionalQueryRestrictions;
protected ?string $additionalWhereClause = null;
/**
* @param int $workspaceId the workspace ID to be checked for.
* @param array $additionalFieldsToQuery an array with more fields that should be accessed.
* @param array $additionalQueryRestrictions an array with more restrictions to add
*/
public function __construct(int $workspaceId = 0, array $additionalFieldsToQuery = [], array $additionalQueryRestrictions = [])
{
$this->currentWorkspace = $workspaceId;
$this->fields = array_merge([
'uid',
'pid',
'sorting',
'starttime',
'endtime',
'hidden',
'fe_group',
'title',
'nav_title',
'nav_hide',
'php_tree_stop',
'doktype',
'is_siteroot',
'module',
'extendToSubpages',
'content_from_pid',
't3ver_oid',
't3ver_wsid',
't3ver_state',
't3ver_stage',
'perms_userid',
'perms_user',
'perms_groupid',
'perms_group',
'perms_everybody',
'mount_pid',
'shortcut',
'shortcut_mode',
'mount_pid_ol',
'url',
'sys_language_uid',
'l10n_parent',
], $additionalFieldsToQuery);
$this->additionalQueryRestrictions = $additionalQueryRestrictions;
$this->quotedFields = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages')
->quoteIdentifiersForSelect($this->fields);
}
public function setAdditionalWhereClause(string $additionalWhereClause): void
{
$this->additionalWhereClause = $additionalWhereClause;
}
/**
* Main entry point for this repository, to fetch the tree data for a page.
* Basically the page record, plus all child pages and their child pages recursively, stored within "_children" item.
*
* @param int $entryPoint the page ID to fetch the tree for
* @param callable|null $callback a callback to be used to check for permissions and filter out pages not to be included.
*/
public function getTree(
int $entryPoint,
?callable $callback = null,
array $dbMounts = []
): array {
$this->fetchAllPages($dbMounts);
if ($entryPoint === 0) {
$tree = $this->fullPageTree;
} else {
$tree = $this->findInPageTree($entryPoint, $this->fullPageTree);
}
if (!empty($tree) && $callback !== null) {
$this->applyCallbackToChildren($tree, $callback);
}
return $tree;
}
/**
* Removes items from a tree based on a callback, usually used for permission checks
*/
protected function applyCallbackToChildren(array &$tree, callable $callback): void
{
if (!isset($tree['_children'])) {
return;
}
foreach ($tree['_children'] as $k => &$childPage) {
if (!$callback($childPage)) {
unset($tree['_children'][$k]);
continue;
}
$this->applyCallbackToChildren($childPage, $callback);
}
}
/**
* Get the page tree based on a given page record and a given depth
*
* @param array $pageTree The page record of the top level page you want to get the page tree of
* @param int $depth Number of levels to fetch
* @param array $entryPointIds entryPointIds to include
* @return array An array with page records and their children
*/
public function getTreeLevels(array $pageTree, int $depth, array $entryPointIds = []): array
{
$groupedAndSortedPagesByPid = [];
if (count($entryPointIds) > 0) {
$pageRecords = $this->getPageRecords($entryPointIds);
$groupedAndSortedPagesByPid[$pageTree['uid']] = $pageRecords;
$parentPageIds = $entryPointIds;
} else {
$parentPageIds = [$pageTree['uid']];
}
for ($i = 0; $i < $depth; $i++) {
if (empty($parentPageIds)) {
break;
}
$pageRecords = $this->getChildPageRecords($parentPageIds);
$groupedAndSortedPagesByPid = $this->groupAndSortPages($pageRecords, $groupedAndSortedPagesByPid);
$parentPageIds = array_column($pageRecords, 'uid');
}
$this->addChildrenToPage($pageTree, $groupedAndSortedPagesByPid);
return $pageTree;
}
/**
* Useful to get a list of pages, with a specific depth, e.g. to limit
* a query to another table to a list of page IDs.
*
* @param int[] $entryPointIds
*/
public function getFlattenedPages(array $entryPointIds, int $depth): array
{
$allPageRecords = $this->getPageRecords($entryPointIds);
$parentPageIds = $entryPointIds;
for ($i = 0; $i < $depth; $i++) {
if (empty($parentPageIds)) {
break;
}
$pageRecords = $this->getChildPageRecords($parentPageIds);
$parentPageIds = array_column($pageRecords, 'uid');
$allPageRecords = array_merge($allPageRecords, $pageRecords);
}
return $allPageRecords;
}
protected function getChildPageRecords(array $parentPageIds): array
{
return $this->getPageRecords([], $parentPageIds);
}
/**
* Retrieve the page records based on the given page or parent page ids
*/
protected function getPageRecords(array $pageIds = [], array $parentPageIds = []): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class))
->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->currentWorkspace));
if (!empty($this->additionalQueryRestrictions)) {
foreach ($this->additionalQueryRestrictions as $additionalQueryRestriction) {
$queryBuilder->getRestrictions()->add($additionalQueryRestriction);
}
}
$queryBuilder->getConcreteQueryBuilder()->select(...$this->quotedFields);
$queryBuilder
->from('pages')
->where(
$queryBuilder->expr()->eq('sys_language_uid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT))
)
// ensure deterministic sorting
->orderBy('sorting', 'ASC')
->addOrderBy('uid', 'ASC');
if (!empty($this->additionalWhereClause)) {
$queryBuilder->andWhere(
QueryHelper::stripLogicalOperatorPrefix($this->additionalWhereClause)
);
}
if (count($pageIds) > 0) {
$queryBuilder->andWhere(
$queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY))
);
}
if (count($parentPageIds) > 0) {
$queryBuilder->andWhere(
$queryBuilder->expr()->in('pid', $queryBuilder->createNamedParameter($parentPageIds, Connection::PARAM_INT_ARRAY))
);
}
$pageRecords = $queryBuilder
->executeQuery()
->fetchAllAssociative();
// This is necessary to resolve all IDs in a workspace
if ($this->currentWorkspace !== 0 && !empty($pageRecords)) {
$livePageIds = [];
$movedPages = [];
foreach ($pageRecords as $pageRecord) {
$livePageIds[] = (int)$pageRecord['uid'];
if (VersionState::tryFrom($pageRecord['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER) {
$movedPages[$pageRecord['t3ver_oid']] = [
'pid' => (int)$pageRecord['pid'],
'sorting' => (int)$pageRecord['sorting'],
];
}
}
// Resolve placeholders of workspace versions
$resolver = GeneralUtility::makeInstance(
PlainDataResolver::class,
'pages',
$livePageIds
);
$resolver->setWorkspaceId($this->currentWorkspace);
$resolver->setKeepDeletePlaceholder(false);
$resolver->setKeepMovePlaceholder(false);
$resolver->setKeepLiveIds(false);
$recordIds = $resolver->get();
if (!empty($recordIds)) {
$queryBuilder->getRestrictions()->removeAll();
$queryBuilder->getConcreteQueryBuilder()->select(...$this->quotedFields);
$pageRecords = $queryBuilder
->from('pages')
->where(
$queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter($recordIds, Connection::PARAM_INT_ARRAY))
)
// ensure deterministic sorting
->orderBy('sorting', 'ASC')
->addOrderBy('uid', 'ASC')
->executeQuery()
->fetchAllAssociative();
foreach ($pageRecords as &$pageRecord) {
if (VersionState::tryFrom($pageRecord['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER && !empty($movedPages[$pageRecord['t3ver_oid']])) {
$pageRecord['uid'] = $pageRecord['t3ver_oid'];
$pageRecord['sorting'] = (int)$movedPages[$pageRecord['t3ver_oid']]['sorting'];
$pageRecord['pid'] = (int)$movedPages[$pageRecord['t3ver_oid']]['pid'];
} elseif ((int)$pageRecord['t3ver_oid'] > 0) {
$liveRecord = BackendUtility::getRecord('pages', $pageRecord['t3ver_oid']);
$pageRecord['sorting'] = (int)$liveRecord['sorting'];
$pageRecord['uid'] = (int)$liveRecord['uid'];
$pageRecord['pid'] = (int)$liveRecord['pid'];
}
}
unset($pageRecord);
} else {
$pageRecords = [];
}
}
foreach ($pageRecords as &$pageRecord) {
$pageRecord['uid'] = (int)$pageRecord['uid'];
}
return $pageRecords;
}
public function hasChildren(int $pid): bool
{
$pageRecords = $this->getChildPageRecords([$pid]);
return !empty($pageRecords);
}
/**
* Fetch all non-deleted pages, regardless of permissions (however, considers additionalQueryRestrictions and additionalWhereClause).
* That's why it's internal.
*
* @return array the full page tree of the whole installation
*/
protected function fetchAllPages(array $dbMounts): array
{
if (!empty($this->fullPageTree)) {
return $this->fullPageTree;
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class))
->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->currentWorkspace));
if (!empty($this->additionalQueryRestrictions)) {
foreach ($this->additionalQueryRestrictions as $additionalQueryRestriction) {
$queryBuilder->getRestrictions()->add($additionalQueryRestriction);
}
}
$queryBuilder->getConcreteQueryBuilder()->select(...$this->quotedFields);
$query = $queryBuilder
->from('pages')
->where(
// Only show records in default language
$queryBuilder->expr()->eq('sys_language_uid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT))
);
if (!empty($this->additionalWhereClause)) {
$queryBuilder->andWhere(
QueryHelper::stripLogicalOperatorPrefix($this->additionalWhereClause)
);
}
$pageRecords = $query->executeQuery()->fetchAllAssociative();
$ids = array_column($pageRecords, 'uid');
foreach ($dbMounts as $mount) {
$entryPointRootLine = BackendUtility::BEgetRootLine($mount, '', false, $this->fields);
foreach ($entryPointRootLine as $page) {
$pageId = (int)$page['uid'];
if (in_array($pageId, $ids) || $pageId === 0) {
continue;
}
$pageRecords[] = $page;
$ids[] = $pageId;
}
}
$livePagePids = [];
$movedPages = [];
// This is necessary to resolve all IDs in a workspace
if ($this->currentWorkspace !== 0 && !empty($pageRecords)) {
$livePageIds = [];
foreach ($pageRecords as $pageRecord) {
$livePageIds[] = (int)$pageRecord['uid'];
$livePagePids[(int)$pageRecord['uid']] = (int)$pageRecord['pid'];
if (VersionState::tryFrom($pageRecord['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER) {
$movedPages[$pageRecord['t3ver_oid']] = [
'pid' => (int)$pageRecord['pid'],
'sorting' => (int)$pageRecord['sorting'],
];
}
}
// Resolve placeholders of workspace versions
$resolver = GeneralUtility::makeInstance(
PlainDataResolver::class,
'pages',
$livePageIds
);
$resolver->setWorkspaceId($this->currentWorkspace);
$resolver->setKeepDeletePlaceholder(false);
$resolver->setKeepMovePlaceholder(false);
$resolver->setKeepLiveIds(false);
$recordIds = $resolver->get();
$queryBuilder->getRestrictions()->removeAll();
$queryBuilder->getConcreteQueryBuilder()->select(...$this->quotedFields);
$pageRecords = $queryBuilder
->from('pages')
->where(
$queryBuilder->expr()->in('uid', $recordIds)
)
->executeQuery()
->fetchAllAssociative();
}
// Now set up sorting, nesting (tree-structure) for all pages based on pid+sorting fields
$groupedAndSortedPagesByPid = [];
foreach ($pageRecords as $pageRecord) {
$parentPageId = (int)$pageRecord['pid'];
// In case this is a record from a workspace
// The uid+pid of the live-version record is fetched
// This is done in order to avoid fetching records again (e.g. via BackendUtility::workspaceOL()
if ((int)$pageRecord['t3ver_oid'] > 0) {
// When a move pointer is found, the pid+sorting of the versioned record should be used
if (VersionState::tryFrom($pageRecord['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER && !empty($movedPages[$pageRecord['t3ver_oid']])) {
$parentPageId = (int)$movedPages[$pageRecord['t3ver_oid']]['pid'];
$pageRecord['sorting'] = (int)$movedPages[$pageRecord['t3ver_oid']]['sorting'];
} else {
// Just a record in a workspace (not moved etc)
$parentPageId = (int)($livePagePids[$pageRecord['t3ver_oid']] ?? $pageRecord['pid']);
}
// this is necessary so the links to the modules are still pointing to the live IDs
$pageRecord['uid'] = (int)$pageRecord['t3ver_oid'];
$pageRecord['pid'] = $parentPageId;
}
$sorting = (int)$pageRecord['sorting'];
while (isset($groupedAndSortedPagesByPid[$parentPageId][$sorting])) {
$sorting++;
}
$groupedAndSortedPagesByPid[$parentPageId][$sorting] = $pageRecord;
}
$this->fullPageTree = [
'uid' => 0,
'title' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] ?: 'TYPO3',
];
$this->addChildrenToPage($this->fullPageTree, $groupedAndSortedPagesByPid);
return $this->fullPageTree;
}
/**
* Adds the property "_children" to a page record with the child pages
*
* @param array[] $groupedAndSortedPagesByPid
*/
protected function addChildrenToPage(array &$page, array &$groupedAndSortedPagesByPid): void
{
$page['_children'] = $groupedAndSortedPagesByPid[(int)$page['uid']] ?? [];
ksort($page['_children']);
foreach ($page['_children'] as &$child) {
$this->addChildrenToPage($child, $groupedAndSortedPagesByPid);
}
}
/**
* Looking for a page by traversing the tree
*
* @param int $pageId the page ID to search for
* @param array $pages the page tree to look for the page
* @return array Array of the tree data, empty array if nothing was found
*/
protected function findInPageTree(int $pageId, array $pages): array
{
foreach ($pages['_children'] as $childPage) {
if ((int)$childPage['uid'] === $pageId) {
return $childPage;
}
$result = $this->findInPageTree($pageId, $childPage);
if (!empty($result)) {
return $result;
}
}
return [];
}
/**
* Retrieve the page tree based on the given search filter
*/
public function fetchFilteredTree(string $searchFilter, array $allowedMountPointPageIds, string $additionalWhereClause): array
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class));
if (!empty($this->additionalQueryRestrictions)) {
foreach ($this->additionalQueryRestrictions as $additionalQueryRestriction) {
$queryBuilder->getRestrictions()->add($additionalQueryRestriction);
}
}
$expressionBuilder = $queryBuilder->expr();
if ($this->currentWorkspace === 0) {
// Only include records from live workspace
$workspaceIdExpression = $expressionBuilder->eq('t3ver_wsid', 0);
} else {
// Include live records PLUS records from the given workspace
$workspaceIdExpression = $expressionBuilder->in(
't3ver_wsid',
[0, $this->currentWorkspace]
);
}
$queryBuilder->getConcreteQueryBuilder()->select(...$this->quotedFields);
$queryBuilder = $queryBuilder
->from('pages')
->where(
// Only show records in default language
$expressionBuilder->eq('sys_language_uid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT)),
$workspaceIdExpression,
QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
);
$searchParts = $expressionBuilder->or();
// Extract true integers from search string
$searchUids = [];
$searchPhrases = GeneralUtility::trimExplode(',', $searchFilter, true);
foreach ($searchPhrases as $searchPhrase) {
if (MathUtility::canBeInterpretedAsInteger($searchPhrase) && $searchPhrase > 0) {
$searchUids[] = (int)$searchPhrase;
}
}
$searchUids = array_unique($searchUids);
if (!empty($searchUids)) {
// Ensure that the LIVE id is also found
if ($this->currentWorkspace > 0) {
$uidFilter = $expressionBuilder->or(
// Check for UID of live record
$expressionBuilder->and(
$expressionBuilder->in('uid', $queryBuilder->createNamedParameter($searchUids, Connection::PARAM_INT_ARRAY)),
$expressionBuilder->eq('t3ver_wsid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT)),
),
// Check for UID of live record in versioned record
$expressionBuilder->and(
$expressionBuilder->in('t3ver_oid', $queryBuilder->createNamedParameter($searchUids, Connection::PARAM_INT_ARRAY)),
$expressionBuilder->eq('t3ver_wsid', $queryBuilder->createNamedParameter($this->currentWorkspace, Connection::PARAM_INT)),
),
// Check for UID for new or moved versioned record
$expressionBuilder->and(
$expressionBuilder->eq('uid', $queryBuilder->createNamedParameter($searchFilter, Connection::PARAM_INT)),
$expressionBuilder->eq('t3ver_oid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT)),
$expressionBuilder->eq('t3ver_wsid', $queryBuilder->createNamedParameter($this->currentWorkspace, Connection::PARAM_INT)),
)
);
} else {
$uidFilter = $expressionBuilder->in('uid', $queryBuilder->createNamedParameter($searchUids, Connection::PARAM_INT_ARRAY));
}
$searchParts = $searchParts->with($uidFilter);
}
$searchFilter = '%' . $queryBuilder->escapeLikeWildcards($searchFilter) . '%';
$searchWhereAlias = $expressionBuilder->or(
$expressionBuilder->like(
'nav_title',
$queryBuilder->createNamedParameter($searchFilter)
),
$expressionBuilder->like(
'title',
$queryBuilder->createNamedParameter($searchFilter)
)
);
$searchParts = $searchParts->with($searchWhereAlias);
$queryBuilder->andWhere($searchParts);
$pageRecords = $queryBuilder
->executeQuery()
->fetchAllAssociative();
$livePagePids = [];
if ($this->currentWorkspace !== 0 && !empty($pageRecords)) {
$livePageIds = [];
foreach ($pageRecords as $pageRecord) {
$livePageIds[] = (int)$pageRecord['uid'];
$livePagePids[(int)$pageRecord['uid']] = (int)$pageRecord['pid'];
if ((int)$pageRecord['t3ver_oid'] > 0) {
$livePagePids[(int)$pageRecord['t3ver_oid']] = (int)$pageRecord['pid'];
}
if (VersionState::tryFrom($pageRecord['t3ver_state'] ?? 0) === VersionState::MOVE_POINTER) {
$movedPages[$pageRecord['t3ver_oid']] = [
'pid' => (int)$pageRecord['pid'],
'sorting' => (int)$pageRecord['sorting'],
];
}
}
// Resolve placeholders of workspace versions
$resolver = GeneralUtility::makeInstance(
PlainDataResolver::class,
'pages',
$livePageIds
);
$resolver->setWorkspaceId($this->currentWorkspace);
$resolver->setKeepDeletePlaceholder(false);
$resolver->setKeepMovePlaceholder(false);
$resolver->setKeepLiveIds(false);
$recordIds = $resolver->get();
$pageRecords = [];
if (!empty($recordIds)) {
$queryBuilder->getRestrictions()->removeAll();
$queryBuilder->getConcreteQueryBuilder()->select(...$this->quotedFields);
$queryBuilder
->from('pages')
->where(
$queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter($recordIds, Connection::PARAM_INT_ARRAY))
);
$queryBuilder->andWhere($searchParts);
$pageRecords = $queryBuilder
->executeQuery()
->fetchAllAssociative();
}
}
$pages = [];
foreach ($pageRecords as $pageRecord) {
// In case this is a record from a workspace
// The uid+pid of the live-version record is fetched
// This is done in order to avoid fetching records again (e.g. via BackendUtility::workspaceOL()
if ((int)$pageRecord['t3ver_oid'] > 0) {
// This probably should also remove the live version
$versionState = VersionState::tryFrom($pageRecord['t3ver_state'] ?? 0);
if ($versionState === VersionState::DELETE_PLACEHOLDER) {
continue;
}
// When a move pointer is found, the pid+sorting of the versioned record be used
if ($versionState === VersionState::MOVE_POINTER && !empty($movedPages[$pageRecord['t3ver_oid']])) {
$parentPageId = (int)$movedPages[$pageRecord['t3ver_oid']]['pid'];
$pageRecord['sorting'] = (int)$movedPages[$pageRecord['t3ver_oid']]['sorting'];
} else {
// Just a record in a workspace (not moved etc)
$parentPageId = (int)$livePagePids[$pageRecord['t3ver_oid']];
}
// this is necessary so the links to the modules are still pointing to the live IDs
$pageRecord['uid'] = (int)$pageRecord['t3ver_oid'];
$pageRecord['pid'] = $parentPageId;
}
$pages[(int)$pageRecord['uid']] = $pageRecord;
}
unset($pageRecords);
$pages = $this->filterPagesOnMountPoints($pages, $allowedMountPointPageIds);
$groupedAndSortedPagesByPid = $this->groupAndSortPages($pages);
$this->fullPageTree = [
'uid' => 0,
'title' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] ?: 'TYPO3',
];
$this->addChildrenToPage($this->fullPageTree, $groupedAndSortedPagesByPid);
return $this->fullPageTree;
}
/**
* Filter all records outside of the allowed mount points
*/
protected function filterPagesOnMountPoints(array $pages, array $mountPoints): array
{
foreach ($pages as $key => $pageRecord) {
$rootline = BackendUtility::BEgetRootLine(
$pageRecord['uid'],
'',
$this->currentWorkspace !== 0,
$this->fields
);
$rootline = array_reverse($rootline);
if (!in_array(0, $mountPoints, true)) {
$isInsideMountPoints = false;
foreach ($rootline as $rootlineElement) {
if (in_array((int)$rootlineElement['uid'], $mountPoints, true)) {
$isInsideMountPoints = true;
break;
}
}
if (!$isInsideMountPoints) {
unset($pages[$key]);
//skip records outside of the allowed mount points
continue;
}
}
$inFilteredRootline = false;
$amountOfRootlineElements = count($rootline);
for ($i = 0; $i < $amountOfRootlineElements; ++$i) {
$rootlineElement = $rootline[$i];
$rootlineElement['uid'] = (int)$rootlineElement['uid'];
$isInWebMount = false;
if ($rootlineElement['uid'] > 0) {
$isInWebMount = (int)$this->getBackendUser()->isInWebMount($rootlineElement);
}
if (!$isInWebMount
|| ($rootlineElement['uid'] === (int)$mountPoints[0]
&& $rootlineElement['uid'] !== $isInWebMount)
) {
continue;
}
if ($this->getBackendUser()->isAdmin() || ($rootlineElement['uid'] === $isInWebMount && in_array($rootlineElement['uid'], $mountPoints, true))) {
$inFilteredRootline = true;
}
if (!$inFilteredRootline) {
continue;
}
if (!isset($pages[$rootlineElement['uid']])) {
$pages[$rootlineElement['uid']] = $rootlineElement;
}
}
}
// Make sure the mountpoints show up in page tree even when parent pages are not accessible pages
foreach ($mountPoints as $mountPoint) {
if ($mountPoint !== 0) {
if (!array_key_exists($mountPoint, $pages)) {
$pages[$mountPoint] = BackendUtility::getRecordWSOL('pages', $mountPoint);
$pages[$mountPoint]['uid'] = (int)$pages[$mountPoint]['uid'];
}
$pages[$mountPoint]['pid'] = 0;
}
}
return $pages;
}
/**
* Group pages by parent page and sort pages based on sorting property
*
* @param array $groupedAndSortedPagesByPid
*/
protected function groupAndSortPages(array $pages, array $groupedAndSortedPagesByPid = []): array
{
foreach ($pages as $pageRecord) {
$parentPageId = (int)$pageRecord['pid'];
$sorting = (int)$pageRecord['sorting'];
// If the page record was already added in another depth level, don't add it another time.
// This may happen, if entry points are intersecting each other (Entry point B is inside entry point A).
if (($groupedAndSortedPagesByPid[$parentPageId][$sorting]['uid'] ?? 0) === $pageRecord['uid']) {
continue;
}
while (isset($groupedAndSortedPagesByPid[$parentPageId][$sorting])) {
$sorting++;
}
$groupedAndSortedPagesByPid[$parentPageId][$sorting] = $pageRecord;
}
return $groupedAndSortedPagesByPid;
}
protected function getBackendUser(): BackendUserAuthentication
{
return $GLOBALS['BE_USER'];
}
}