/
PageRepository.php
2139 lines (2016 loc) · 103 KB
/
PageRepository.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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* 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\Core\Domain\Repository;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
use TYPO3\CMS\Core\Compatibility\PublicMethodDeprecationTrait;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
use TYPO3\CMS\Core\Context\LanguageAspect;
use TYPO3\CMS\Core\Context\UserAspect;
use TYPO3\CMS\Core\Context\VisibilityAspect;
use TYPO3\CMS\Core\Context\WorkspaceAspect;
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\EndTimeRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\FrontendGroupRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
use TYPO3\CMS\Core\Domain\Access\RecordAccessVoter;
use TYPO3\CMS\Core\Domain\Event\AfterRecordLanguageOverlayEvent;
use TYPO3\CMS\Core\Domain\Event\BeforePageLanguageOverlayEvent;
use TYPO3\CMS\Core\Domain\Event\BeforeRecordLanguageOverlayEvent;
use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
use TYPO3\CMS\Core\Type\Bitmask\PageTranslationVisibility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Versioning\VersionState;
/**
* Page functions, a lot of sql/pages-related functions
*
* Mainly used in the frontend but also in some cases in the backend. It's
* important to set the right $where_hid_del in the object so that the
* functions operate properly
* @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::determineId()
*/
class PageRepository implements LoggerAwareInterface
{
use LoggerAwareTrait;
use PublicMethodDeprecationTrait;
private array $deprecatedPublicMethods = [
'getRecordOverlay' => 'Using PageRepository::getRecordOverlay() is deprecated and will not be possible anymore in TYPO3 v13.0. Use PageRepository:getLanguageOverlay() instead.',
];
/**
* This is not the final clauses. There will normally be conditions for the
* hidden, starttime and endtime fields as well. You MUST initialize the object
* by the init() function
*
* @var string
*/
public $where_hid_del = ' AND pages.deleted=0';
/**
* Clause for fe_group access
*
* @var string
*/
public $where_groupAccess = '';
/**
* Can be migrated away later to use context API directly.
*
* @var int
*/
protected $sys_language_uid = 0;
/**
* Can be migrated away later to use context API directly.
* Workspace ID for preview
* If > 0, versioning preview of other record versions is allowed. THIS MUST
* ONLY BE SET IF the page is not cached and truly previewed by a backend
* user!
*
* @var int
*/
protected $versioningWorkspaceId = 0;
/**
* Computed properties that are added to database rows.
*
* @var array
*/
protected $computedPropertyNames = [
'_LOCALIZED_UID',
'_MP_PARAM',
'_ORIG_uid',
'_ORIG_pid',
'_SHORTCUT_ORIGINAL_PAGE_UID',
'_PAGES_OVERLAY',
'_PAGES_OVERLAY_UID',
'_PAGES_OVERLAY_LANGUAGE',
'_PAGES_OVERLAY_REQUESTEDLANGUAGE',
];
/**
* Named constants for "magic numbers" of the field doktype
*/
public const DOKTYPE_DEFAULT = 1;
public const DOKTYPE_LINK = 3;
public const DOKTYPE_SHORTCUT = 4;
public const DOKTYPE_BE_USER_SECTION = 6;
public const DOKTYPE_MOUNTPOINT = 7;
public const DOKTYPE_SPACER = 199;
public const DOKTYPE_SYSFOLDER = 254;
public const DOKTYPE_RECYCLER = 255;
/**
* Named constants for "magic numbers" of the field shortcut_mode
*/
public const SHORTCUT_MODE_NONE = 0;
public const SHORTCUT_MODE_FIRST_SUBPAGE = 1;
public const SHORTCUT_MODE_RANDOM_SUBPAGE = 2;
public const SHORTCUT_MODE_PARENT_PAGE = 3;
/**
* @var Context
*/
protected $context;
/**
* PageRepository constructor to set the base context, this will effectively remove the necessity for
* setting properties from the outside.
*/
public function __construct(Context $context = null)
{
$this->context = $context ?? GeneralUtility::makeInstance(Context::class);
$this->versioningWorkspaceId = $this->context->getPropertyFromAspect('workspace', 'id');
// Only set up the where clauses for pages when TCA is set. This usually happens only in tests.
// Once all tests are written very well, this can be removed again
if (isset($GLOBALS['TCA']['pages'])) {
$this->init($this->context->getPropertyFromAspect('visibility', 'includeHiddenPages'));
$this->where_groupAccess = $this->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
$this->sys_language_uid = (int)$this->context->getPropertyFromAspect('language', 'id', 0);
}
}
/**
* init() MUST be run directly after creating a new template-object
* This sets the internal variable $this->where_hid_del to the correct where
* clause for page records taking deleted/hidden/starttime/endtime/t3ver_state
* into account
*
* @param bool $show_hidden If $show_hidden is TRUE, the hidden-field is ignored!! Normally this should be FALSE. Is used for previewing.
* @internal
*/
protected function init($show_hidden)
{
$this->where_groupAccess = '';
// As PageRepository may be used multiple times during the frontend request, and may
// actually be used before the usergroups have been resolved, self::getMultipleGroupsWhereClause()
// and the hook in ->enableFields() need to be reconsidered when the usergroup state changes.
// When something changes in the context, a second runtime cache entry is built.
// However, the PageRepository is generally in use for generating e.g. hundreds of links, so they would all use
// the same cache identifier.
$userAspect = $this->context->getAspect('frontend.user');
$frontendUserIdentifier = 'user_' . (int)$userAspect->get('id') . '_groups_' . md5(implode(',', $userAspect->getGroupIds()));
// We need to respect the date aspect as we might have subrequests with a different time (e.g. backend preview links)
$dateTimeIdentifier = $this->context->getAspect('date')->get('timestamp');
$cache = $this->getRuntimeCache();
$cacheIdentifier = 'PageRepository_hidDelWhere' . ($show_hidden ? 'ShowHidden' : '') . '_' . (int)$this->versioningWorkspaceId . '_' . $frontendUserIdentifier . '_' . $dateTimeIdentifier;
$cacheEntry = $cache->get($cacheIdentifier);
if ($cacheEntry) {
$this->where_hid_del = $cacheEntry;
} else {
$expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages')
->expr();
if ($this->versioningWorkspaceId > 0) {
// For version previewing, make sure that enable-fields are not
// de-selecting hidden pages - we need versionOL() to unset them only
// if the overlay record instructs us to.
// Clear where_hid_del and restrict to live and current workspaces
$this->where_hid_del = ' AND ' . $expressionBuilder->and(
$expressionBuilder->eq('pages.deleted', 0),
$expressionBuilder->or(
$expressionBuilder->eq('pages.t3ver_wsid', 0),
$expressionBuilder->eq('pages.t3ver_wsid', (int)$this->versioningWorkspaceId)
),
$expressionBuilder->neq('pages.doktype', self::DOKTYPE_RECYCLER)
);
} else {
// add starttime / endtime, and check for hidden/deleted
// Filter out new/deleted place-holder pages in case we are NOT in a
// versioning preview (that means we are online!)
$this->where_hid_del = ' AND ' . (string)$expressionBuilder->and(
QueryHelper::stripLogicalOperatorPrefix(
$this->enableFields('pages', (int)$show_hidden, ['fe_group' => true])
),
$expressionBuilder->neq('pages.doktype', self::DOKTYPE_RECYCLER)
);
}
$cache->set($cacheIdentifier, $this->where_hid_del);
}
if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] ?? false)) {
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['init'] as $classRef) {
$hookObject = GeneralUtility::makeInstance($classRef);
if (!$hookObject instanceof PageRepositoryInitHookInterface) {
throw new \UnexpectedValueException($classRef . ' must implement interface ' . PageRepositoryInitHookInterface::class, 1379579812);
}
$hookObject->init_postProcess($this);
}
}
}
/**************************
*
* Selecting page records
*
**************************/
/**
* Loads the full page record for the given page ID.
*
* The page record is either served from a first-level cache or loaded from the
* database. If no page can be found, an empty array is returned.
*
* Language overlay and versioning overlay are applied. Mount Point
* handling is not done, an overlaid Mount Point is not replaced.
*
* The result is conditioned by the public properties where_groupAccess
* and where_hid_del that are preset by the init() method.
*
* @see PageRepository::where_groupAccess
* @see PageRepository::where_hid_del
*
* By default the usergroup access check is enabled. Use the second method argument
* to disable the usergroup access check.
*
* The given UID can be preprocessed by registering a hook class that is
* implementing the PageRepositoryGetPageHookInterface into the configuration array
* $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'].
*
* @param int $uid The page id to look up
* @param bool $disableGroupAccessCheck set to true to disable group access check
* @return array The resulting page record with overlays or empty array
* @throws \UnexpectedValueException
* @see PageRepository::getPage_noCheck()
*/
public function getPage($uid, $disableGroupAccessCheck = false)
{
// Hook to manipulate the page uid for special overlay handling
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_page.php']['getPage'] ?? [] as $className) {
$hookObject = GeneralUtility::makeInstance($className);
if (!$hookObject instanceof PageRepositoryGetPageHookInterface) {
throw new \UnexpectedValueException($className . ' must implement interface ' . PageRepositoryGetPageHookInterface::class, 1251476766);
}
$hookObject->getPage_preProcess($uid, $disableGroupAccessCheck, $this);
}
$cacheIdentifier = 'PageRepository_getPage_' . md5(
implode(
'-',
[
$uid,
$disableGroupAccessCheck ? '' : $this->where_groupAccess,
$this->where_hid_del,
$this->sys_language_uid,
]
)
);
$cache = $this->getRuntimeCache();
$cacheEntry = $cache->get($cacheIdentifier);
if (is_array($cacheEntry)) {
return $cacheEntry;
}
$result = [];
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll();
$queryBuilder->select('*')
->from('pages')
->where(
$queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$uid, Connection::PARAM_INT)),
QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del)
);
$originalWhereGroupAccess = '';
if (!$disableGroupAccessCheck) {
$queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess));
} else {
$originalWhereGroupAccess = $this->where_groupAccess;
$this->where_groupAccess = '';
}
$row = $queryBuilder->executeQuery()->fetchAssociative();
if ($row) {
$this->versionOL('pages', $row);
if (is_array($row)) {
$result = $this->getLanguageOverlay('pages', $row);
}
}
if ($disableGroupAccessCheck) {
$this->where_groupAccess = $originalWhereGroupAccess;
}
$cache->set($cacheIdentifier, $result);
return $result;
}
/**
* Return the $row for the page with uid = $uid WITHOUT checking for
* ->where_hid_del (start- and endtime or hidden). Only "deleted" is checked!
*
* @param int $uid The page id to look up
* @return array The page row with overlaid localized fields. Empty array if no page.
* @see getPage()
*/
public function getPage_noCheck($uid)
{
$cache = $this->getRuntimeCache();
$cacheIdentifier = 'PageRepository_getPage_noCheck_' . $uid . '_' . $this->sys_language_uid . '_' . $this->versioningWorkspaceId;
$cacheEntry = $cache->get($cacheIdentifier);
if ($cacheEntry !== false) {
return $cacheEntry;
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$row = $queryBuilder->select('*')
->from('pages')
->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter((int)$uid, Connection::PARAM_INT)))
->executeQuery()
->fetchAssociative();
$result = [];
if ($row) {
$this->versionOL('pages', $row);
if (is_array($row)) {
$result = $this->getLanguageOverlay('pages', $row);
}
}
$cache->set($cacheIdentifier, $result);
return $result;
}
/**
* Master helper method to overlay a record to a language.
*
* Be aware that for pages the languageId is taken, and for all other records the contentId.
* This might change through a feature switch in the future.
*
* @param string $table the name of the table, should be a TCA table with localization enabled
* @param array $originalRow the current (full-fletched) record.
* @param LanguageAspect|null $languageAspect an alternative language aspect if needed (optional)
* @return array|null NULL If overlays were activated but no overlay was found and LanguageAspect was NOT set to MIXED
*/
public function getLanguageOverlay(string $table, array $originalRow, LanguageAspect $languageAspect = null): ?array
{
// table is not localizable, so return directly
if (!isset($GLOBALS['TCA'][$table]['ctrl']['languageField'])) {
return $originalRow;
}
try {
/** @var LanguageAspect $languageAspect */
$languageAspect = $languageAspect ?? $this->context->getAspect('language');
} catch (AspectNotFoundException $e) {
// no overlays
return $originalRow;
}
$eventDispatcher = GeneralUtility::makeInstance(EventDispatcherInterface::class);
$event = $eventDispatcher->dispatch(new BeforeRecordLanguageOverlayEvent($table, $originalRow, $languageAspect));
$languageAspect = $event->getLanguageAspect();
$originalRow = $event->getRecord();
$attempted = false;
$localizedRecord = null;
if ($languageAspect->doOverlays()) {
$attempted = true;
if ($table === 'pages') {
$localizedRecord = $this->getPageOverlay($originalRow, $languageAspect);
} else {
$localizedRecord = $this->getRecordOverlay($table, $originalRow, $languageAspect);
}
}
$event = new AfterRecordLanguageOverlayEvent($table, $originalRow, $localizedRecord, $attempted, $languageAspect);
/** @var AfterRecordLanguageOverlayEvent $event */
$event = $eventDispatcher->dispatch($event);
// Return localized record or the original row, if no overlays were done
return $event->overlayingWasAttempted() ? $event->getLocalizedRecord() : $originalRow;
}
/**
* Returns the relevant page overlay record fields
*
* @param mixed $pageInput If $pageInput is an integer, it's the pid of the pageOverlay record and thus the page overlay record is returned. If $pageInput is an array, it's a page-record and based on this page record the language record is found and OVERLAID before the page record is returned.
* @param int|LanguageAspect|null $language language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
* @throws \UnexpectedValueException
* @return array Page row which is overlaid with language_overlay record (or the overlay record alone)
*/
public function getPageOverlay($pageInput, $language = null)
{
$rows = $this->getPagesOverlay([$pageInput], $language);
// Always an array in return
return $rows[0] ?? [];
}
/**
* Returns the relevant page overlay record fields
*
* @param array $pagesInput Array of integers or array of arrays. If each value is an integer, it's the pids of the pageOverlay records and thus the page overlay records are returned. If each value is an array, it's page-records and based on this page records the language records are found and OVERLAID before the page records are returned.
* @param int|LanguageAspect|null $language Language UID if you want to set an alternative value to $this->sys_language_uid which is default. Should be >=0
* @throws \UnexpectedValueException
* @return array Page rows which are overlaid with language_overlay record.
* If the input was an array of integers, missing records are not
* included. If the input were page rows, untranslated pages
* are returned.
*/
public function getPagesOverlay(array $pagesInput, int|LanguageAspect $language = null)
{
if (empty($pagesInput)) {
return [];
}
if (is_int($language)) {
$languageAspect = new LanguageAspect($language, $language);
} else {
$languageAspect = $language ?? $this->context->getAspect('language');
}
$overlays = [];
// If language UID is different from zero, do overlay:
if ($languageAspect->getId() > 0) {
$pageIds = [];
foreach ($pagesInput as $origPage) {
if (is_array($origPage)) {
// Was the whole record
$pageIds[] = (int)($origPage['uid'] ?? 0);
} else {
// Was the id
$pageIds[] = (int)$origPage;
}
}
$event = GeneralUtility::makeInstance(EventDispatcherInterface::class)->dispatch(
new BeforePageLanguageOverlayEvent($pagesInput, $pageIds, $languageAspect)
);
$pagesInput = $event->getPageInput();
$overlays = $this->getPageOverlaysForLanguage($event->getPageIds(), $event->getLanguageAspect());
}
// Create output:
$pagesOutput = [];
foreach ($pagesInput as $key => $origPage) {
if (is_array($origPage)) {
$pagesOutput[$key] = $origPage;
if (isset($origPage['uid'], $overlays[$origPage['uid']])) {
// Overwrite the original field with the overlay
foreach ($overlays[$origPage['uid']] as $fieldName => $fieldValue) {
if ($fieldName !== 'uid' && $fieldName !== 'pid') {
$pagesOutput[$key][$fieldName] = $fieldValue;
}
}
}
} elseif (isset($overlays[$origPage])) {
$pagesOutput[$key] = $overlays[$origPage];
}
}
return $pagesOutput;
}
/**
* Checks whether the passed (translated or default language) page is accessible with the given language settings.
*
* @param array $page the page translation record or the page in the default language
* @return bool true if the given page translation record is suited for the given language ID
* @internal
*/
public function isPageSuitableForLanguage(array $page, LanguageAspect $languageAspect): bool
{
$languageUid = $languageAspect->getId();
// Checks if the default language version can be shown
// Block page is set, if l18n_cfg allows plus: 1) Either default language or 2) another language but NO overlay record set for page!
$pageTranslationVisibility = new PageTranslationVisibility((int)($page['l18n_cfg'] ?? 0));
if ((!$languageUid || !($page['_PAGES_OVERLAY'] ?? false))
&& $pageTranslationVisibility->shouldBeHiddenInDefaultLanguage()
) {
return false;
}
if ($languageUid > 0 && $pageTranslationVisibility->shouldHideTranslationIfNoTranslatedRecordExists()) {
if (!($page['_PAGES_OVERLAY'] ?? false) || (int)($page['_PAGES_OVERLAY_LANGUAGE'] ?? 0) !== $languageUid) {
return false;
}
} elseif ($languageUid > 0) {
$languageUids = array_merge([$languageUid], $this->getLanguageFallbackChain($languageAspect));
return in_array((int)($page['sys_language_uid'] ?? 0), $languageUids, true);
}
return true;
}
/**
* Returns the cleaned fallback chain from the current language aspect, if there is one.
*
* @return int[]
*/
protected function getLanguageFallbackChain(?LanguageAspect $languageAspect): array
{
$languageAspect = $languageAspect ?? $this->context->getAspect('language');
return array_filter($languageAspect->getFallbackChain(), static function ($item) {
return MathUtility::canBeInterpretedAsInteger($item);
});
}
/**
* Returns the first match of overlays for pages in the passed languages.
*
* NOTE regarding the query restrictions:
* Currently the visibility aspect within the FrontendRestrictionContainer will allow
* page translation records to be selected as they are child-records of a page.
* However you may argue that the visibility flag should determine this.
* But that's not how it's done right now.
*
* @param array $pageUids
* @param LanguageAspect $languageAspect Used for the fallback chain
*/
protected function getPageOverlaysForLanguage(array $pageUids, LanguageAspect $languageAspect): array
{
$languageUids = array_merge([$languageAspect->getId()], $this->getLanguageFallbackChain($languageAspect));
// Remove default language ("0")
$languageUids = array_filter($languageUids);
$languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'];
$overlays = [];
foreach ($pageUids as $pageId) {
// Create a map based on the order of values in $languageUids. Those entries reflect the order of the language + fallback chain.
// We can't work with database ordering since there is no common SQL clause to order by e.g. [7, 1, 2].
$orderedListByLanguages = array_flip($languageUids);
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context));
// Because "fe_group" is an exclude field, so it is synced between overlays, the group restriction is removed for language overlays of pages
$queryBuilder->getRestrictions()->removeByType(FrontendGroupRestriction::class);
$result = $queryBuilder->select('*')
->from('pages')
->where(
$queryBuilder->expr()->eq(
$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
$queryBuilder->createNamedParameter($pageId, Connection::PARAM_INT)
),
$queryBuilder->expr()->in(
$GLOBALS['TCA']['pages']['ctrl']['languageField'],
$queryBuilder->createNamedParameter($languageUids, Connection::PARAM_INT_ARRAY)
)
)
->executeQuery();
// Create a list of rows ordered by values in $languageUids
while ($row = $result->fetchAssociative()) {
$orderedListByLanguages[$row[$languageField]] = $row;
}
foreach ($orderedListByLanguages as $languageUid => $row) {
if (!is_array($row)) {
continue;
}
// Found a result for the current language id
$this->versionOL('pages', $row);
if (is_array($row)) {
$row['_PAGES_OVERLAY'] = true;
$row['_PAGES_OVERLAY_UID'] = $row['uid'];
$row['_PAGES_OVERLAY_LANGUAGE'] = $languageUid;
$row['_PAGES_OVERLAY_REQUESTEDLANGUAGE'] = $languageUids[0];
// Unset vital fields that are NOT allowed to be overlaid:
unset($row['uid'], $row['pid']);
$overlays[$pageId] = $row;
// Language fallback found, stop querying further languages
break;
}
}
}
return $overlays;
}
/**
* Creates language-overlay for records in general (where translation is found
* in records from the same table)
*
* @param string $table Table name
* @param array $row Record to overlay. Must contain uid, pid and $table]['ctrl']['languageField']
* @param LanguageAspect|int|null $languageAspect Pointer to the site language id for content on the site.
* @param string $OLmode Overlay mode. If "hideNonTranslated" then records without translation will not be returned un-translated but unset (and return value is NULL) - will be removed in TYPOO3 v13.0.
* @throws \UnexpectedValueException
* @return array|null Returns the input record, possibly overlaid with a translation. But if overlays are not mixed ("fallback to default language") then it will return NULL if no translation is found.
*/
protected function getRecordOverlay(string $table, array $row, $languageAspect = null, $OLmode = '')
{
// Kept for backwards-compatibility, can be removed in TYPO3 v13.0.
if (is_int($languageAspect)) {
$OLmode = func_get_args()[3] ?? '';
$languageAspect = new LanguageAspect(
$languageAspect,
$languageAspect,
($OLmode === 'hideNonTranslated' ? LanguageAspect::OVERLAYS_ON_WITH_FLOATING : ($OLmode ? LanguageAspect::OVERLAYS_MIXED : LanguageAspect::OVERLAYS_OFF))
);
}
$languageAspect ??= $this->context->getAspect('language');
// Early return when no overlays are needed
if ($languageAspect->getOverlayType() === $languageAspect::OVERLAYS_OFF) {
return $row;
}
$tableControl = $GLOBALS['TCA'][$table]['ctrl'] ?? [];
if (!empty($tableControl['languageField'])
// Return record for ALL languages untouched
// @todo: Fix call stack to prevent this situation in the first place
&& (int)($row[$tableControl['languageField']] ?? 0) !== -1
&& !empty($tableControl['transOrigPointerField'])
&& $row['uid'] > 0
&& ($row['pid'] > 0 || in_array($tableControl['rootLevel'] ?? false, [true, 1, -1], true))
) {
// Will try to overlay a record only if the sys_language_content value is larger than zero.
if ($languageAspect->getContentId() > 0) {
// Must be default language, otherwise no overlaying
if ((int)($row[$tableControl['languageField']] ?? 0) === 0) {
// Select overlay record:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable($table);
$queryBuilder->setRestrictions(
GeneralUtility::makeInstance(FrontendRestrictionContainer::class, $this->context)
);
if ($this->versioningWorkspaceId > 0) {
// If not in live workspace, remove query based "enable fields" checks, it will be done in versionOL()
// @see functional workspace test createLocalizedNotHiddenWorkspaceContentHiddenInLive()
$queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
$queryBuilder->getRestrictions()->removeByType(StartTimeRestriction::class);
$queryBuilder->getRestrictions()->removeByType(EndTimeRestriction::class);
// We keep the WorkspaceRestriction in this case, because we need to get the LIVE record
// of the language record before doing the version overlay of the language again. WorkspaceRestriction
// does this for us, PLUS we need to ensure to get a possible LIVE record first (that's why
// the "orderBy" query is there, so the LIVE record is found first), as there might only be a
// versioned record (e.g. new version) or both (common for modifying, moving etc).
if ($this->hasTableWorkspaceSupport($table)) {
$queryBuilder->orderBy('t3ver_wsid', 'ASC');
}
}
$pid = $row['pid'];
// When inside a workspace, the already versioned $row of the default language is coming in
// For moved versioned records, the PID MIGHT be different. However, the idea of this function is
// to get the language overlay of the LIVE default record, and afterwards get the versioned record
// the found (live) language record again, see the versionOL() call a few lines below.
// This means, we need to modify the $pid value for moved records, as they might be on a different
// page and use the PID of the LIVE version.
if (isset($row['_ORIG_pid']) && $this->hasTableWorkspaceSupport($table) && VersionState::cast($row['t3ver_state'] ?? 0)->equals(VersionState::MOVE_POINTER)) {
$pid = $row['_ORIG_pid'];
}
$olrow = $queryBuilder->select('*')
->from($table)
->where(
$queryBuilder->expr()->eq(
'pid',
$queryBuilder->createNamedParameter($pid, Connection::PARAM_INT)
),
$queryBuilder->expr()->eq(
$tableControl['languageField'],
$queryBuilder->createNamedParameter($languageAspect->getContentId(), Connection::PARAM_INT)
),
$queryBuilder->expr()->eq(
$tableControl['transOrigPointerField'],
$queryBuilder->createNamedParameter($row['uid'], Connection::PARAM_INT)
)
)
->setMaxResults(1)
->executeQuery()
->fetchAssociative();
$this->versionOL($table, $olrow);
// Merge record content by traversing all fields:
if (is_array($olrow)) {
if (isset($olrow['_ORIG_uid'])) {
$row['_ORIG_uid'] = $olrow['_ORIG_uid'];
}
if (isset($olrow['_ORIG_pid'])) {
$row['_ORIG_pid'] = $olrow['_ORIG_pid'];
}
foreach ($row as $fN => $fV) {
if ($fN !== 'uid' && $fN !== 'pid' && array_key_exists($fN, $olrow)) {
$row[$fN] = $olrow[$fN];
} elseif ($fN === 'uid') {
$row['_LOCALIZED_UID'] = $olrow['uid'];
}
}
} elseif (in_array($languageAspect->getOverlayType(), [LanguageAspect::OVERLAYS_ON_WITH_FLOATING, LanguageAspect::OVERLAYS_ON])
&& (int)($row[$tableControl['languageField']] ?? 0) === 0
) {
// Unset, if non-translated records should be hidden. ONLY done if the source
// record really is default language and not [All] in which case it is allowed.
$row = null;
}
} elseif ($languageAspect->getContentId() != ($row[$tableControl['languageField']] ?? null)) {
$row = null;
}
} else {
// When default language is displayed, we never want to return a record carrying
// another language!
if ((int)($row[$tableControl['languageField']] ?? 0) > 0) {
$row = null;
}
}
}
return $row;
}
/************************************************
*
* Page related: Menu, Domain record, Root line
*
************************************************/
/**
* Returns an array with page rows for subpages of a certain page ID. This is used for menus in the frontend.
* If there are mount points in overlay mode the _MP_PARAM field is set to the correct MPvar.
*
* If the $pageId being input does in itself require MPvars to define a correct
* rootline these must be handled externally to this function.
*
* @param int|int[] $pageId The page id (or array of page ids) for which to fetch subpages (PID)
* @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
* contains the `uid` field. It's mandatory for further processing of the result row.
* @param string $sortField The field to sort by. Default is "sorting
* @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
* @param bool $checkShortcuts Check if shortcuts exist, checks by default
* @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
* @see getPageShortcut()
* @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
*/
public function getMenu($pageId, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
{
// @todo: Restricting $fields to a list like 'uid, title' here, leads to issues from methods like
// getSubpagesForPages() which access keys like 'doktype'. This is odd, select field list
// should be handled better here, probably at least containing fields that are used in the
// sub methods. In the end, it might be easier to drop argument $fields altogether and
// always select * ?
return $this->getSubpagesForPages((array)$pageId, $fields, $sortField, $additionalWhereClause, $checkShortcuts);
}
/**
* Returns an array with page-rows for pages with uid in $pageIds.
*
* This is used for menus. If there are mount points in overlay mode
* the _MP_PARAM field is set to the correct MPvar.
*
* @param int[] $pageIds Array of page ids to fetch
* @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
* contains the `uid` field. It's mandatory for further processing of the result row.
* @param string $sortField The field to sort by. Default is "sorting"
* @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
* @param bool $checkShortcuts Check if shortcuts exist, checks by default
* @return array Array with key/value pairs; keys are page-uid numbers. values are the corresponding page records (with overlaid localized fields, if any)
*/
public function getMenuForPages(array $pageIds, $fields = '*', $sortField = 'sorting', $additionalWhereClause = '', $checkShortcuts = true)
{
return $this->getSubpagesForPages($pageIds, $fields, $sortField, $additionalWhereClause, $checkShortcuts, false);
}
/**
* Loads page records either by PIDs or by UIDs.
*
* By default the subpages of the given page IDs are loaded (as the method name suggests). If $parentPages is set
* to FALSE, the page records for the given page IDs are loaded directly.
*
* Concerning the rationale, please see these two other methods:
*
* @see PageRepository::getMenu()
* @see PageRepository::getMenuForPages()
*
* Version and language overlay are applied to the loaded records.
*
* If a record is a mount point in overlay mode, the the overlaying page record is returned in place of the
* record. The record is enriched by the field _MP_PARAM containing the mount point mapping for the mount
* point.
*
* The query can be customized by setting fields, sorting and additional WHERE clauses. If additional WHERE
* clauses are given, the clause must start with an operator, i.e: "AND title like '%some text%'".
*
* The keys of the returned page records are the page UIDs.
*
* CAUTION: In case of an overlaid mount point, it is the original UID.
*
* @param int[] $pageIds PIDs or UIDs to load records for
* @param string $fields Fields to select, `*` is the default - If a custom list is set, make sure the list
* contains the `uid` field. It's mandatory for further processing of the result row.
* @param string $sortField the field to sort by
* @param string $additionalWhereClause optional additional WHERE clause
* @param bool $checkShortcuts whether to check if shortcuts exist
* @param bool $parentPages Switch to load pages (false) or child pages (true).
* @return array page records
*
* @see self::getPageShortcut()
* @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::makeMenu()
*/
protected function getSubpagesForPages(
array $pageIds,
string $fields = '*',
string $sortField = 'sorting',
string $additionalWhereClause = '',
bool $checkShortcuts = true,
bool $parentPages = true
): array {
$relationField = $parentPages ? 'pid' : 'uid';
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->versioningWorkspaceId));
$res = $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true))
->from('pages')
->where(
$queryBuilder->expr()->in(
$relationField,
$queryBuilder->createNamedParameter($pageIds, Connection::PARAM_INT_ARRAY)
),
$queryBuilder->expr()->eq(
$GLOBALS['TCA']['pages']['ctrl']['languageField'],
$queryBuilder->createNamedParameter(0, Connection::PARAM_INT)
),
QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
);
if (!empty($sortField)) {
$orderBy = QueryHelper::parseOrderBy($sortField);
foreach ($orderBy as $order) {
$res->addOrderBy($order[0], $order[1] ?? 'ASC');
}
}
$result = $res->executeQuery();
$pages = [];
while ($page = $result->fetchAssociative()) {
$originalUid = $page['uid'];
// Versioning Preview Overlay
$this->versionOL('pages', $page, true);
// Skip if page got disabled due to version overlay (might be delete placeholder)
if (empty($page)) {
continue;
}
// Add a mount point parameter if needed
$page = $this->addMountPointParameterToPage((array)$page);
// If shortcut, look up if the target exists and is currently visible
if ($checkShortcuts) {
$page = $this->checkValidShortcutOfPage((array)$page, $additionalWhereClause);
}
// If the page still is there, we add it to the output
if (!empty($page)) {
$pages[$originalUid] = $page;
}
}
// Finally load language overlays
return $this->getPagesOverlay($pages);
}
/**
* Replaces the given page record with mounted page if required
*
* If the given page record is a mount point in overlay mode, the page
* record is replaced by the record of the overlaying page. The overlay
* record is enriched by setting the mount point mapping into the field
* _MP_PARAM as string for example '23-14'.
*
* In all other cases the given page record is returned as is.
*
* @todo Find a better name. The current doesn't hit the point.
*
* @param array $page The page record to handle.
* @return array The given page record or it's replacement.
*/
protected function addMountPointParameterToPage(array $page): array
{
if (empty($page)) {
return [];
}
// $page MUST have "uid", "pid", "doktype", "mount_pid", "mount_pid_ol" fields in it
$mountPointInfo = $this->getMountPointInfo($page['uid'], $page);
// There is a valid mount point in overlay mode.
if (is_array($mountPointInfo) && $mountPointInfo['overlay']) {
// Using "getPage" is OK since we need the check for enableFields AND for type 2
// of mount pids we DO require a doktype < 200!
$mountPointPage = $this->getPage($mountPointInfo['mount_pid']);
if (!empty($mountPointPage)) {
$page = $mountPointPage;
$page['_MP_PARAM'] = $mountPointInfo['MPvar'];
} else {
$page = [];
}
}
return $page;
}
/**
* If shortcut, look up if the target exists and is currently visible
*
* @param array $page The page to check
* @param string $additionalWhereClause Optional additional where clauses. Like "AND title like '%some text%'" for instance.
* @return array
*/
protected function checkValidShortcutOfPage(array $page, $additionalWhereClause)
{
if (empty($page)) {
return [];
}
$dokType = (int)$page['doktype'];
$shortcutMode = (int)$page['shortcut_mode'];
if ($dokType === self::DOKTYPE_SHORTCUT && ($page['shortcut'] || $shortcutMode)) {
if ($shortcutMode === self::SHORTCUT_MODE_NONE) {
// No shortcut_mode set, so target is directly set in $page['shortcut']
$searchField = 'uid';
$searchUid = (int)$page['shortcut'];
} elseif ($shortcutMode === self::SHORTCUT_MODE_FIRST_SUBPAGE || $shortcutMode === self::SHORTCUT_MODE_RANDOM_SUBPAGE) {
// Check subpages - first subpage or random subpage
$searchField = 'pid';
// If a shortcut mode is set and no valid page is given to select subpages
// from use the actual page.
$searchUid = (int)$page['shortcut'] ?: $page['uid'];
} elseif ($shortcutMode === self::SHORTCUT_MODE_PARENT_PAGE) {
// Shortcut to parent page
$searchField = 'uid';
$searchUid = $page['pid'];
} else {
$searchField = '';
$searchUid = 0;
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll();
$count = $queryBuilder->count('uid')
->from('pages')
->where(
$queryBuilder->expr()->eq(
$searchField,
$queryBuilder->createNamedParameter($searchUid, Connection::PARAM_INT)
),
QueryHelper::stripLogicalOperatorPrefix($this->where_hid_del),
QueryHelper::stripLogicalOperatorPrefix($this->where_groupAccess),
QueryHelper::stripLogicalOperatorPrefix($additionalWhereClause)
)
->executeQuery()
->fetchOne();
if (!$count) {
$page = [];
}
} elseif ($dokType === self::DOKTYPE_SHORTCUT) {
// Neither shortcut target nor mode is set. Remove the page from the menu.
$page = [];
}
return $page;
}
/**
* Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
*
* @param string $shortcutFieldValue The value of the "shortcut" field from the pages record
* @param int $shortcutMode The shortcut mode: 1 will select first subpage, 2 a random subpage, 3 the parent page; default is the page pointed to by $SC