/
UrlEncoder.php
1666 lines (1508 loc) · 52.9 KB
/
UrlEncoder.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
/***************************************************************
* Copyright notice
*
* (c) 2015 Dmitry Dulepov (dmitry.dulepov@gmail.com)
* All rights reserved
*
* You may not remove or change the name of the author above. See:
* http://www.gnu.org/licenses/gpl-faq.html#IWantCredit
*
* This script is part of the Typo3 project. The Typo3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
namespace DmitryDulepov\Realurl\Encoder;
use DmitryDulepov\Realurl\Cache\UrlCacheEntry;
use DmitryDulepov\Realurl\Configuration\ConfigurationReader;
use DmitryDulepov\Realurl\EncodeDecoderBase;
use DmitryDulepov\Realurl\Exceptions\InvalidLanguageParameterException;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
use TYPO3\CMS\Frontend\Page\PageRepository;
/**
* This class contains encoder for the RealURL.
*
* @package DmitryDulepov\Realurl\Encoder
* @author Dmitry Dulepov <dmitry.dulepov@gmail.com>
*/
class UrlEncoder extends EncodeDecoderBase {
const MAX_ALIAS_LENGTH = 100;
/** @var string */
protected $encodedUrl = '';
/** @var array */
protected $encoderParameters;
/**
* This is the URL with sorted GET parameters. It is used for cache
* manipulation.
*
* @var string
*/
protected $originalUrl;
/** @var array */
protected $originalUrlParameters = array();
/** @var int */
protected $sysLanguageUid;
/** @var string */
protected $urlToEncode;
/** @var array */
protected $urlParameters = array();
/** @var string */
static protected $urlPrepend = '';
/** @var array */
protected $usedAliases = array();
/**
* Initializes the class.
*/
public function __construct() {
parent::__construct();
}
/**
* Returns a coipy of original url parameters. This can be used in hooks.
*
* @return array
*/
public function getOriginalUrlParameters() {
return $this->originalUrlParameters;
}
/**
* Returns $this->utility. This can be used in hooks.
*
* @return \DmitryDulepov\Realurl\Utility
*/
public function getUtility() {
return $this->utility;
}
/**
* Entry point for the URL encoder.
*
* @param array $encoderParameters
* @return void
*/
public function encodeUrl(array &$encoderParameters) {
$this->callEarlyHook($encoderParameters);
$this->encoderParameters = $encoderParameters;
$this->urlToEncode = $encoderParameters['LD']['totalURL'];
if ($this->canEncoderExecute()) {
try {
$this->executeEncoder();
$encoderParameters['LD']['totalURL'] = $this->encodedUrl .
(isset($encoderParameters['LD']['sectionIndex']) ? $encoderParameters['LD']['sectionIndex'] : '');
$this->logger->debug(
sprintf(
'Created speaking url "%s" from "%s"',
$encoderParameters['LD']['totalURL'],
$this->originalUrl
),
$encoderParameters
);
}
catch (InvalidLanguageParameterException $exception) {
// Pass through. We just return unencoded URL in such case.
}
}
else {
$this->logger->debug(
sprintf(
'URL "%s" cannot be encoded by realurl',
$this->urlToEncode
)
);
}
}
/**
* Post-processes the URL. If necessary prepends another domain to the URL.
*
* @param array $parameters
* @param ContentObjectRenderer $pObj
* @return void
*/
public function postProcessEncodedUrl(array &$parameters, ContentObjectRenderer $pObj) {
if (self::$urlPrepend !== '' && isset($parameters['finalTagParts']['url'])) {
// We must check for absolute URLs here because typolink can force
// absolute URLs for pages with restricted access. It prepends
// current host always. See http://bugs.typo3.org/view.php?id=18200
$url = $parameters['finalTagParts']['url'];
if (preg_match('/^https?:\/\/[^\/]+\//', $url)) {
$url = preg_replace('/^https?:\/\/[^\/]+(\/.*)$/', '\1', $url);
}
if (self::$urlPrepend{strlen(self::$urlPrepend) - 1} === '/' && $url && $url{0} === '/') {
$url = substr($url, 1);
}
if (self::$urlPrepend{strlen(self::$urlPrepend) - 1} !== '/' && ($url === '' || $url{0} !== '/')) {
$url = '/' . $url;
}
$url = self::$urlPrepend . $url;
// Adjust the URL
$parameters['finalTag'] = str_replace(
'"' . htmlspecialchars($parameters['finalTagParts']['url']) . '"',
'"' . htmlspecialchars($url) . '"',
$parameters['finalTag']
);
$parameters['finalTagParts']['url'] = $url;
$pObj->lastTypoLinkUrl = $url;
$this->logger->debug(
sprintf(
'Post-processed encoded url "%s" to "%s"',
$url,
$url
)
);
self::$urlPrepend = '';
}
}
/**
* Adds remaining parameters to the generated URL. Note: parameters that
* are ignored by the 'cache/ignoredGetParametersRegExp' configuration option
* are not considered here!
*
* @return void
*/
protected function addRemainingUrlParameters() {
$urlParameters = $this->urlParameters;
unset($urlParameters['id']);
if (count($urlParameters) == 1 && isset($urlParameters['cHash'])) {
unset($urlParameters['cHash']);
} elseif (count($urlParameters) > 0) {
$this->encodedUrl .= '?' . trim(GeneralUtility::implodeArrayForUrl('', $urlParameters, '', false, true), '&');
}
}
/**
* Adds an entry to the path cache.
*
* @param string $pagePath
* @return void
*/
protected function addToPathCache($pagePath) {
$cacheEntry = GeneralUtility::makeInstance('DmitryDulepov\\Realurl\\Cache\\PathCacheEntry');
/** @var \DmitryDulepov\Realurl\Cache\PathCacheEntry $cacheEntry */
$cacheEntry->setExpiration(0);
$cacheEntry->setLanguageId($this->sysLanguageUid);
$cacheEntry->setRootPageId($this->rootPageId);
$cacheEntry->setMountPoint(isset($this->originalUrlParameters['MP']) ? $this->originalUrlParameters['MP'] : '');
$cacheEntry->setPageId($this->urlParameters['id']);
$cacheEntry->setPagePath($pagePath);
$this->cache->putPathToCache($cacheEntry);
}
/**
* Appends value from 'config.defaultGetVars' to url parameters.
*/
protected function appendFromDefaultGetVars() {
$config = $this->tsfe->config['config'];
if (isset($config['defaultGetVars.']) && !empty($config['linkVars'])) {
preg_match_all('/(.+?)(\([^)]+\))?(?:,|$)/i', $config['linkVars'], $matches);
for ($i = 0; $i < count($matches[0]); $i++) {
$linkVar = $matches[1][$i];
if (isset($config['defaultGetVars.'][$linkVar]) && !isset($this->urlParameters[$linkVar])) {
$value = $config['defaultGetVars.'][$linkVar];
$this->urlParameters[$linkVar] = $value;
}
}
}
}
/**
* Appends a string to $this->encodedUrl properly handling slashes in between.
*
* @param string $stringToAppend
* @param bool $addSlash
* @return void
*/
protected function appendToEncodedUrl($stringToAppend, $addSlash = TRUE) {
if ($stringToAppend !== '') {
$this->encodedUrl = ($this->encodedUrl ? rtrim($this->encodedUrl, '/') . '/' : '') . $stringToAppend;
if ($addSlash) {
$this->encodedUrl .= '/';
}
}
}
/**
* Early hook for the encoder.
*
* @param array $encoderParameters
*/
protected function callEarlyHook(&$encoderParameters) {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['encodeSpURL_earlyHook'])) {
foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['encodeSpURL_earlyHook'] as $userFunc) {
$hookParams = array(
'pObj' => $this,
'params' => &$encoderParameters,
);
GeneralUtility::callUserFunction($userFunc, $hookParams, $this);
}
}
}
/**
* Calls user-defined hooks after encoding
*/
protected function callPostEncodeHooks() {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['encodeSpURL_postProc'])) {
foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['encodeSpURL_postProc'] as $userFunc) {
$hookParams = array(
'pObj' => $this,
'params' => $this->encoderParameters,
'URL' => &$this->encodedUrl,
);
GeneralUtility::callUserFunction($userFunc, $hookParams, $this);
}
}
}
/**
* Checks if the URL can be cached. This function may prevent RealURL cache
* pollution with Solr or Indexed search URLs. Also some doktypes are ignored
* for the cache.
*
* @param string $url
* @return bool
*/
protected function canCacheUrl($url) {
$result = $this->canCacheUrlFast($url);
if ($result) {
// Check page type: do not cache separators
$pageRecord = $this->pageRepository->getPage($this->urlParameters['id']);
if (is_array($pageRecord) && ($pageRecord['doktype'] == PageRepository::DOKTYPE_SPACER || $pageRecord['doktype'] == PageRepository::DOKTYPE_RECYCLER)) {
$result = false;
}
}
else {
$this->logger->debug(
sprintf(
'URL "%s" will not be cached',
$url
)
);
}
return $result;
}
/**
* Makes a faster check for url caching than canCacheUrl().
*
* @param string $url
* @return bool
*/
protected function canCacheUrlFast($url)
{
$bannedUrlsRegExp = $this->configuration->get('cache/banUrlsRegExp');
return (!$bannedUrlsRegExp || !preg_match($bannedUrlsRegExp, $url));
}
/**
* Checks if RealURL can encode URLs.
*
* @return bool
*/
protected function canEncoderExecute() {
return $this->isRealURLEnabled() &&
!$this->isSimulateStaticEnabled() &&
!$this->isInWorkspace() &&
$this->isTypo3Url() &&
$this->isProperTsfe()
;
}
/**
* Checks if all segments are empty and makes the empty array in such case.
*
* @param array $segments
* @return void
*/
protected function checkForAllEmptySegments(&$segments) {
// If all segments are empty, do not set them. No, array_filter() is not a better solution!
if (count($segments) > 0) {
$allSegmentsAreEmpty = TRUE;
foreach ($segments as $segment) {
if ($segment) {
$allSegmentsAreEmpty = FALSE;
break;
}
}
if ($allSegmentsAreEmpty) {
$segments = array();
}
}
}
/**
* Cleans up the alias
*
* @param array $configuration Configuration array
* @param string $newAliasValue Alias value to clean up
* @return string
*/
public function cleanUpAlias(array $configuration, $newAliasValue) {
$processedTitle = $this->utility->convertToSafeString($newAliasValue, $this->separatorCharacter);
if ($configuration['useUniqueCache_conf']['encodeTitle_userProc']) {
$encodingConfiguration = array('strtolower' => $configuration['useUniqueCache_conf']['strtolower'], 'spaceCharacter' => $configuration['useUniqueCache_conf']['spaceCharacter']);
$parameters = array(
'pObj' => $this,
'title' => $newAliasValue,
'processedTitle' => $processedTitle,
'encodingConfiguration' => $encodingConfiguration
);
$processedTitle = GeneralUtility::callUserFunction($configuration['useUniqueCache_conf']['encodeTitle_userProc'], $parameters, $this);
}
return $processedTitle;
}
/**
* Converts value to the alias
*
* @param string $getVarValue
* @param array $configuration 'lookUpTable' configuration
* @return string
*/
protected function createAliasForValue($getVarValue, array $configuration) {
$result = $getVarValue;
// Define the language for the alias
$languageUrlParameter = $configuration['languageGetVar'] ?: 'L';
$languageUid = isset($this->originalUrlParameters[$languageUrlParameter]) ? (int)$this->originalUrlParameters[$languageUrlParameter] : 0;
if (GeneralUtility::inList($configuration['languageExceptionUids'], $languageUid)) {
$languageUid = 0;
}
// First, test if there is an entry in cache for the id
if (!$configuration['useUniqueCache'] || !($result = $this->getFromAliasCache($configuration, $getVarValue, $languageUid))) {
$languageEnabled = FALSE;
$fieldList = array();
if ($configuration['table'] === 'pages') {
$fieldList[] = 'uid';
$languageEnabled = TRUE;
}
elseif ($configuration['transOrigPointerField'] && $configuration['languageField']) {
$fieldList[] = 'uid';
$fieldList[] = $configuration['transOrigPointerField'];
$fieldList[] = $configuration['languageField'];
$languageEnabled = TRUE;
}
$fieldList[] = $configuration['alias_field'];
$row = $this->databaseConnection->exec_SELECTgetSingleRow(implode(',', $fieldList), $configuration['table'],
$configuration['id_field'] . '=' . $this->databaseConnection->fullQuoteStr($getVarValue, $configuration['table']) .
' ' . $configuration['addWhereClause']);
if (is_array($row)) {
// Looking for localized version
if ($languageEnabled && $languageUid !== 0) {
if ($configuration['table'] === 'pages') {
// Note: can't use $this->pageRepository->getPageOverlay() here because 'alias_field' can be an expression
$localizedRow = $this->databaseConnection->exec_SELECTgetSingleRow($configuration['alias_field'], 'pages_language_overlay',
'pid=' . (int)$row['uid'] . ' AND sys_language_uid=' . $languageUid .
(isset($configuration['addWhereClause']) ? $configuration['addWhereClause'] : '')
);
}
else {
// Note: can't use $this->pageRepository->getRecordOverlay() here because 'alias_field' can be an expression
$localizedRow = $this->databaseConnection->exec_SELECTgetSingleRow($configuration['alias_field'], $configuration['table'],
$configuration['transOrigPointerField'] . '=' . (int)$row['uid'] .
' AND ' . $configuration['languageField'] . '=' . $languageUid .
(isset($configuration['addWhereClause']) ? $configuration['addWhereClause'] : '')
);
}
if (is_array($localizedRow)) {
$row = $localizedRow;
}
}
$maxAliasLengthLength = isset($configuration['maxLength']) ? (int)$configuration['maxLength'] : self::MAX_ALIAS_LENGTH;
$aliasValue = $this->tsfe->csConvObj->substr('utf-8', $row[$configuration['alias_field']], 0, $maxAliasLengthLength);
# Do not allow aliases to be empty (see issue #1)
if (empty($aliasValue)) {
$aliasValue = md5($configuration['table'] . '-' . $row[$configuration['id_field']] . '-' . $languageUid);
}
if ($configuration['useUniqueCache']) { // If cache is to be used, store the alias in the cache:
$result = $this->storeInAliasCache($configuration, $aliasValue, $getVarValue, $languageUid);
} else { // If no cache for alias, then just return whatever value is appropriate:
$result = $aliasValue;
}
}
}
return is_null($result) ? $getVarValue : $result;
}
/**
* Creates a unique alias.
*
* @param array $configuration
* @param $newAliasValue
* @param $idValue
* @return string
*/
protected function createUniqueAlias(array $configuration, $newAliasValue, $idValue) {
$uniqueAlias = '';
$counter = 0;
$maxTry = 100;
$testNewAliasValue = $newAliasValue;
while ($counter < $maxTry) {
// If the test-alias did NOT exist, it must be unique and we break out
$foundId = $this->getFromAliasCacheByAliasValue($configuration, $testNewAliasValue);
if (!$foundId || $foundId == $idValue) {
$uniqueAlias = $testNewAliasValue;
break;
}
$counter++;
$testNewAliasValue = $newAliasValue . '-' . $counter;
}
return $uniqueAlias;
}
/**
* Creates a path part of the URL.
*
* @return void
*/
protected function createPathComponent() {
if (!$this->createPathComponentThroughOverride()) {
$this->createPathComponentUsingRootline();
}
}
/**
* Checks if tx_realurl_pathoverride is set and goes the easy way.
*
* @return bool
*/
protected function createPathComponentThroughOverride() {
$result = false;
// Can't use $this->pageRepository->getPage() here because it does
// language overlay to TSFE's sys_language_uid automatically.
// We do not want this because we may need to encode to a different language
$page = $this->databaseConnection->exec_SELECTgetSingleRow('*', 'pages',
'uid=' . (int)$this->urlParameters['id']
);
$languageExceptionUids = (string)$this->configuration->get('pagePath/languageExceptionUids');
if ($this->sysLanguageUid > 0 && (empty($languageExceptionUids) || !GeneralUtility::inList($languageExceptionUids, $this->sysLanguageUid))) {
$overlay = $this->pageRepository->getPageOverlay($page, $this->sysLanguageUid);
if (is_array($overlay)) {
$page = $overlay;
unset($overlay);
}
}
if ($page['tx_realurl_pathoverride'] && $page['tx_realurl_pathsegment'] !== '') {
$path = trim($page['tx_realurl_pathsegment'], '/');
$pathSegments = explode('/', $path);
array_walk($pathSegments, function(&$segment) {
$segment = rawurlencode($this->utility->convertToSafeString($segment, $this->separatorCharacter));
});
$path = implode('/', $pathSegments);
unset($pathSegments);
$this->appendToEncodedUrl($path);
// Mount points do not work with path override. Having them will
// create duplicate path entries but we have to live with this to
// avoid further cache management complications. If we ignore
// mount point information here, we will have to do something
// about it in encodePathComponents() when we fetch from the cache.
// It is easier to have duplicate entries here (one with MP and
// another without it). It does not really matter.
if ($page['doktype'] != PageRepository::DOKTYPE_SPACER && $page['doktype'] != PageRepository::DOKTYPE_RECYCLER) {
$this->addToPathCache($path);
}
$result = true;
$this->logger->debug(
sprintf(
'Created page path "%s" through override for page %d',
$path,
(int)$this->urlParameters['id']
)
);
}
return $result;
}
/**
* Creates a path part of the URL.
*
* @return void
*/
protected function createPathComponentUsingRootline() {
$this->logger->debug('Starting path generation');
$mountPointParameter = '';
if (isset($this->urlParameters['MP'])) {
$mountPointParameter = $this->urlParameters['MP'];
unset($this->urlParameters['MP']);
}
$rootLineUtility = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\RootlineUtility',
$this->urlParameters['id'], $mountPointParameter, $this->pageRepository
);
/** @var \TYPO3\CMS\Core\Utility\RootlineUtility $rootLineUtility */
$rootLine = $rootLineUtility->get();
// Skip from the root of the tree to the first level of pages
$rootLineIsOk = false;
while (count($rootLine) !== 0) {
$page = array_pop($rootLine);
if ($page['uid'] == $this->rootPageId) {
// This works only if correct root page id is found for the page.
$rootLineIsOk = true;
break;
}
}
if (!$rootLineIsOk) {
// User error: domain is not configured in realurl & linking across domains. Attempt a workaround.
$domainData = $this->tsfe->getDomainDataForPid($this->urlParameters['id']);
if (is_array($domainData)) {
$rootLine = $rootLineUtility->get();
while (count($rootLine) !== 0) {
$page = array_pop($rootLine);
if ($page['uid'] == $domainData['pid']) {
$rootLineIsOk = true;
// Hotfix root page id. Note: this will put cache entries
// to correct pages but will still use pre/postVars from the
// current domain! On the other hand, this is incorrect config
// we are trying to fix here, so it is user's fault!
$this->rootPageId = $domainData['pid'];
break;
}
}
}
if (!$rootLineIsOk) {
$message = sprintf(
'URL cannot be generated because we were unable to find root page for pid=%d. ' .
'Usually this means that domain is not configured in realurl configuration ' .
'and you try to link across domains. Fix your configuration by configuring ' .
'ALL domains there!',
$this->urlParameters['id']
);
$this->logger->warning($message);
/** @noinspection PhpUnhandledExceptionInspection */
throw new \Exception($message, 1530116654);
}
}
unset($rootLineIsOk);
$languageExceptionUids = (string)$this->configuration->get('pagePath/languageExceptionUids');
$enableLanguageOverlay = ((int)$this->originalUrlParameters['L'] > 0) && (empty($languageExceptionUids) || !GeneralUtility::inList($languageExceptionUids, $this->sysLanguageUid));
$components = array();
$reversedRootLine = array_reverse($rootLine);
$rootLineMax = count($reversedRootLine) - 1;
for ($current = 0; $current <= $rootLineMax; $current++) {
$page = $reversedRootLine[$current];
// Skip if this page is excluded
if ($page['tx_realurl_exclude'] && $current !== $rootLineMax) {
$this->logger->debug(
sprintf(
'Page %d is excluded from realurl',
(int)$page['uid']
)
);
continue;
}
if ($enableLanguageOverlay) {
$overlay = $this->pageRepository->getPageOverlay($page, (int)$this->originalUrlParameters['L']);
if (is_array($overlay)) {
$page = $overlay;
unset($overlay);
}
}
// if path override is set, use path segment also for all subpages to shorten the url and throw away all segments found so far
if ($page['tx_realurl_pathoverride'] && $page['tx_realurl_pathsegment'] !== '') {
$this->logger->debug(
sprintf(
'Path override detected for page %d',
(int)$page['uid']
)
);
$segment = trim($page['tx_realurl_pathsegment'], '/');
$segments = explode('/', $segment);
array_walk($segments, function(&$segment) {
$segment = rawurlencode($this->utility->convertToSafeString($segment, $this->separatorCharacter));
});
// Technically we could do with `$components = $segments` but it fills better to have overriden string here
$segment = implode('/', $segments);
unset($segments);
$components = array($segment);
continue;
}
foreach (self::$pageTitleFields as $field) {
if (isset($page[$field]) && $page[$field] !== '') {
$segment = $this->utility->convertToSafeString($page[$field], $this->separatorCharacter);
if ($segment === '') {
$segment = $this->emptySegmentValue;
}
$segment = rawurlencode($segment);
$components[] = $segment;
$this->logger->debug(
sprintf(
'Found path segment "%s" using field "%s"',
$segment,
$field
)
);
continue 2;
}
}
}
if (count($components) > 0) {
$generatedPath = implode('/', $components);
foreach ($components as $segment) {
$this->appendToEncodedUrl($segment);
}
if ($reversedRootLine[$rootLineMax]['doktype'] != PageRepository::DOKTYPE_SPACER && $reversedRootLine[$rootLineMax]['doktype'] != PageRepository::DOKTYPE_RECYCLER) {
$this->addToPathCache($generatedPath);
}
$this->logger->debug(
sprintf(
'Generated path: "%s"',
$generatedPath
)
);
}
$this->logger->debug('Finished path generation');
}
/**
* Encodes fixed postVars.
*
* @return void
*/
protected function encodeFixedPostVars() {
$configuration = (array)$this->configuration->get('fixedPostVars');
$postVarSetConfiguration = $this->getConfigurationForPostVars($configuration, $this->urlParameters['id']);
if (count($postVarSetConfiguration) > 0) {
$segments = $this->encodeUrlParameterBlock($postVarSetConfiguration);
if (count($segments) > 0) {
$this->appendToEncodedUrl(implode('/', $segments));
}
}
}
/**
* Encodes the path to the page.
*
* @return void
*/
protected function encodePathComponents() {
$this->fixPageId();
$cacheEntry = $this->cache->getPathFromCacheByPageId($this->rootPageId,
$this->sysLanguageUid,
$this->urlParameters['id'],
isset($this->urlParameters['MP']) ? $this->urlParameters['MP'] : ''
);
if ($cacheEntry) {
$this->appendToEncodedUrl($cacheEntry->getPagePath());
if (isset($this->urlParameters['MP']) && $cacheEntry->getMountPoint() === $this->urlParameters['MP']) {
unset($this->urlParameters['MP']);
}
} else {
$this->createPathComponent();
}
}
/**
* Encodes 'preVars' into URL segments.
*
* @return void
*/
protected function encodePreVars() {
$preVars = (array)$this->configuration->get('preVars');
if (count($preVars) > 0) {
$segments = $this->encodeUrlParameterBlock($preVars);
if (count($segments) > 0) {
$this->appendToEncodedUrl(implode('/', $segments));
}
}
}
/**
* Encodes 'postVarSets' into URL segments.
*
* @return void
*/
protected function encodePostVarSets() {
// There is at least an 'id' parameter
if (count($this->urlParameters) > 1) {
$configuration = (array)$this->configuration->get('postVarSets');
$postVarSetConfigurations = $this->getConfigurationForPostVars($configuration, $this->urlParameters['id']);
foreach ($postVarSetConfigurations as $postVar => $postVarSetConfiguration) {
if (is_array($postVarSetConfiguration)) {
// Technically it can be a string (for decoding purposes) but makes no sense for encoding
// And decoder does not support it too (see UrlDecoder::decodePostVarSets)
$segments = $this->encodeUrlParameterBlock($postVarSetConfiguration);
if (count($segments) > 0) {
array_unshift($segments, $postVar);
$this->appendToEncodedUrl(implode('/', $segments));
}
}
}
}
}
/**
* Encodes a single variable for xxxVars.
*
* @param array $configuration
* @param string $previousValue
* @param array $segments
*/
protected function encodeSingleVariable(array $configuration, &$previousValue, array &$segments) {
static $varProcessingFunctions = array(
'encodeUrlParameterBlockUsingValueMap',
'encodeUrlParameterBlockUsingNoMatch',
'encodeUrlParameterBlockUsingUserFunc',
'encodeUrlParameterBlockUsingLookupTable',
'encodeUrlParameterBlockUsingValueDefault',
// Always the last one!
'encodeUrlParameterBlockUseAsIs',
);
if (isset($configuration['GETvar'])) {
$getVarName = $configuration['GETvar'];
$getVarValue = isset($this->urlParameters[$getVarName]) ? $this->urlParameters[$getVarName] : '';
if (!isset($configuration['cond']) || $this->checkLegacyCondition($configuration['cond'], $previousValue)) {
// TODO Possible hook here before any other function? Pass name, value, segments and config
foreach ($varProcessingFunctions as $varProcessingFunction) {
if ($this->$varProcessingFunction($getVarName, $getVarValue, $configuration, $segments, $previousValue)) {
// Unset to prevent further processing
unset($this->urlParameters[$getVarName]);
break;
}
}
}
}
else {
// TODO Log an error here: configuration is bad!
}
}
/**
* Encodes pre- or postVars according to the given configuration.
*
* @param array $configurationArray
* @return array
*/
protected function encodeUrlParameterBlock(array $configurationArray) {
$segments = array();
if ($this->hasUrlParameters($configurationArray)) {
$previousValue = '';
foreach ($configurationArray as $configuration) {
if (is_array($configuration)) {
$this->encodeSingleVariable($configuration, $previousValue, $segments);
}
}
}
$this->checkForAllEmptySegments($segments);
$this->fixEmptySegments($segments);
return $segments;
}
/**
* Just sets the value to the segment as is.
*
* @param string $getVarName
* @param string $getVarValue
* @param array $configuration
* @param array $segments
* @param string $previousValue
* @return bool
*/
protected function encodeUrlParameterBlockUseAsIs(/** @noinspection PhpUnusedParameterInspection */ $getVarName, $getVarValue, array $configuration, array &$segments, &$previousValue) {
$previousValue = $getVarValue;
$segments[] = rawurlencode($getVarValue);
return TRUE;
}
/**
* Uses lookUpMap to set the segment.
*
* @param string $getVarName
* @param string $getVarValue
* @param array $configuration
* @param array $segments
* @param string $previousValue
* @return bool
*/
protected function encodeUrlParameterBlockUsingLookupTable(/** @noinspection PhpUnusedParameterInspection */ $getVarName, $getVarValue, array $configuration, array &$segments, &$previousValue) {
$result = FALSE;
if (isset($configuration['lookUpTable'])) {
$previousValue = $getVarValue;
$segments[] = rawurlencode($this->createAliasForValue($getVarValue, $configuration['lookUpTable']));
$result = TRUE;
}
return $result;
}
/**
* Uses 'noMatch' options to set the segment.
*
* @param string $getVarName
* @param string $getVarValue
* @param array $configuration
* @param array $segments
* @param string $previousValue
* @return bool
*/
protected function encodeUrlParameterBlockUsingNoMatch(/** @noinspection PhpUnusedParameterInspection */ $getVarName, $getVarValue, array $configuration, array &$segments, &$previousValue) {
$result = FALSE;
if (isset($configuration['noMatch'])) {
if ($configuration['noMatch'] === 'bypass') {
$result = TRUE;
} elseif ($configuration['noMatch'] === 'null') {
$previousValue = '';
$segments[] = '';
$result = TRUE;
}
}
return $result;
}
/**
* Calls the userFunc for the value to get the segment.
*
* @param string $getVarName
* @param string $getVarValue
* @param array $configuration
* @param array $segments
* @param string $previousValue
* @return bool
*/
protected function encodeUrlParameterBlockUsingUserFunc(/** @noinspection PhpUnusedParameterInspection */ $getVarName, $getVarValue, array $configuration, array &$segments, &$previousValue) {
$result = FALSE;
if (isset($configuration['userFunc'])) {
$previousValue = $getVarValue;
$userFuncParameters = array(
'pObj' => $this,
'value' => $getVarValue,
'decodeAlias' => false,
'pathParts' => &$segments,
'setup' => $configuration,
'sysLanguageUid' => $this->sysLanguageUid,
);
$getVarValue = GeneralUtility::callUserFunction($configuration['userFunc'], $userFuncParameters, $this);
if (is_numeric($getVarValue) || is_string($getVarValue)) {
$segments[] = rawurlencode($getVarValue);
$result = TRUE;
}
}
return $result;
}
/**
* Just sets the default value to the segment.
*
* @param string $getVarName
* @param string $getVarValue
* @param array $configuration
* @param array $segments
* @param string $previousValue
* @return bool
*/
protected function encodeUrlParameterBlockUsingValueDefault(/** @noinspection PhpUnusedParameterInspection */ $getVarName, $getVarValue, array $configuration, array &$segments, &$previousValue) {
$result = FALSE;
if (isset($configuration['valueDefault'])) {
$previousValue = (string)$configuration['valueDefault'];
$segments[] = rawurlencode((string)$configuration['valueDefault']);
$result = TRUE;
}
return $result;
}
/**
* Uses the value map to determine the segment value.
*
* @param string $getVarName
* @param string $getVarValue
* @param array $configuration
* @param array $segments
* @param string $previousValue
* @return bool
*/
protected function encodeUrlParameterBlockUsingValueMap(/** @noinspection PhpUnusedParameterInspection */ $getVarName, $getVarValue, array $configuration, array &$segments, &$previousValue) {
$result = FALSE;
if (isset($configuration['valueMap']) && is_array($configuration['valueMap'])) {
$segmentValue = array_search($getVarValue, $configuration['valueMap']);
if ($segmentValue !== FALSE) {
$previousValue = $getVarValue;
$segments[] = rawurlencode((string)$segmentValue);
$result = TRUE;
}
}
return $result;