-
Notifications
You must be signed in to change notification settings - Fork 126
/
UrlDecoder.php
1579 lines (1422 loc) · 49.7 KB
/
UrlDecoder.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 ([email protected])
* 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\Decoder;
use DmitryDulepov\Realurl\Cache\PathCacheEntry;
use DmitryDulepov\Realurl\Cache\UrlCacheEntry;
use DmitryDulepov\Realurl\Configuration\ConfigurationReader;
use DmitryDulepov\Realurl\EncodeDecoderBase;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
use TYPO3\CMS\Frontend\Page\PageRepository;
/**
* This class contains URL decoder for the RealURL. It is singleton because the
* same instance must run in two different hooks.
*
* @package DmitryDulepov\Realurl\Decoder
* @author Dmitry Dulepov <[email protected]>
*/
class UrlDecoder extends EncodeDecoderBase implements SingletonInterface {
const REDIRECT_STATUS_HEADER = 'HTTP/1.0 301 TYPO3 RealURL Redirect';
const REDIRECT_INFO_HEADER = 'X-TYPO3-RealURL-Info';
/** @var bool */
protected $appendedSlash = FALSE;
/** @var TypoScriptFrontendController */
protected $caller;
/**
* This attribute keeps a detected language id for the speaking URL. Firsts,
* if _DOMAINS configuration has L parameter, it's value will be set to
* $_GET['L']. Than this attribute will be set from $_GET['L'] (if set).
* Finally preVar handling code will check for L after decoding and set
* this attribute either to the decoded value or to zero. This value can
* be null until preVars are decoded. After that it is either zero or
* the decoded language uid.
*
* @var int|null
*/
protected $detectedLanguageId = null;
/** @var string */
protected $disallowedDoktypes;
/**
* Indicates that the path is expired but we could not redirect because
* non-expired path is missing from the path cache. In such case we do not
* cache the entry in the URL cache to force resolving of the path when
* the current URL is fetched.
*
* @var bool
*/
protected $isExpiredPath = FALSE;
/**
* Holds information about expired path for the SEO redirect.
*
* @var string
*/
protected $expiredPath = '';
/** @var string */
protected $mimeType = '';
/**
* Contains a mount point starting pid for the current branch. Zero means
* "no mount point in the path". This variable will direct the decoder to
* continue page look up from this branch of tree.
*
* @var int
*/
protected $mountPointStartPid = 0;
/**
* Contains a generated $_GET['MP'] for the currently decoded branch.
*
* @var string
*/
protected $mountPointVariable = '';
/**
* This variable is set to the speaking path only if he decoding has to run.
*
* @var string
*/
protected $originalPath;
/** @var string */
protected $savedErrorHandler = '';
/** @var string */
protected $siteScript;
/** @var string */
protected $speakingUri;
/**
* Initializes the class.
*/
public function __construct() {
parent::__construct();
$this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
}
/**
* Decodes the URL. This function is called from \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::checkAlternativeIdMethods()
*
* @param array $params
* @return void
*/
public function decodeUrl(array $params) {
if ($this->canDecoderExecute()) {
$this->caller = $params['pObj'];
$this->initialize();
$this->mergeGetVarsFromDomainsConfiguration();
if ($this->isSpeakingUrl()) {
$this->configuration->validate();
$this->setSpeakingUriFromSiteScript();
$this->callPreDecodeHooks($params);
$this->checkMissingSlash();
if ($this->speakingUri) {
$this->setLanguageFromQueryString();
$this->runDecoding();
}
}
}
}
/**
* Calls user-defined hooks.
*
* @param array $params
*/
protected function callPreDecodeHooks(array $params) {
if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['decodeSpURL_preProc'])) {
foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['decodeSpURL_preProc'] as $userFunc) {
$hookParams = array(
'pObj' => &$this,
'params' => $params,
'URL' => &$this->speakingUri,
);
GeneralUtility::callUserFunction($userFunc, $hookParams, $this);
}
}
}
/**
* Checks if the decoder can execute.
*
* @return bool
*/
protected function canDecoderExecute() {
return $this->isProperTsfe() && !$this->isInWorkspace();
}
/**
* Checks if the entry is expired and redirects to a non-expired entry.
*
* @param UrlCacheEntry $cacheEntry
*/
protected function checkExpiration(UrlCacheEntry $cacheEntry) {
if ($cacheEntry->getExpiration() > 0) {
$newerCacheEntry = $this->cache->getUrlFromCacheByOriginalUrl($cacheEntry->getRootPageId(), $cacheEntry->getOriginalUrl());
if ($newerCacheEntry->getExpiration() === 0) {
// Note: the above check will fail the first time the page is visited
// because there will be no cache entry yet. However if the visited
// page has a URL to itself, then the entry will be detected and
// redirection happen starting from the second visit to the
// expired url.
if ($cacheEntry->getSpeakingUrl() !== $newerCacheEntry->getSpeakingUrl()) {
$this->logger->notice(
sprintf(
'RealURL redirects expired URL "%s" to a newer URL "%s"',
$cacheEntry->getSpeakingUrl(),
$newerCacheEntry->getSpeakingUrl()
)
);
@ob_end_clean();
header(self::REDIRECT_STATUS_HEADER);
header(self::REDIRECT_INFO_HEADER . ': redirecting expired URL to a fresh one');
header('Content-length: 0');
header('Connection: close');
header('Location: ' . GeneralUtility::locationHeaderUrl($newerCacheEntry->getSpeakingUrl()));
die;
}
else {
// Got expired and non-expired entry for the same speaking url. Remove expired one.
$this->cache->clearUrlCacheById($cacheEntry->getCacheId());
}
}
}
}
/**
* Checks if the missing slash should be corrected.
*
* @return void
*/
protected function checkMissingSlash() {
$originalUri = $this->speakingUri = rtrim($this->speakingUri, '?');
$regexp = '~^([^\?]*[^/])(\?.*)?$~';
if (preg_match($regexp, $this->speakingUri)) { // Only process if a slash is missing:
$options = GeneralUtility::trimExplode(',', $this->configuration->get('init/appendMissingSlash'), true);
if (in_array('ifNotFile', $options)) {
if (!preg_match('/\/[^\/\?]+\.[^\/]+(\?.*)?$/', '/' . $this->speakingUri)) {
$this->speakingUri = preg_replace($regexp, '\1/\2', $this->speakingUri);
$this->appendedSlash = true;
}
} else {
$this->speakingUri = preg_replace($regexp, '\1/\2', $this->speakingUri);
$this->appendedSlash = true;
}
if ($this->appendedSlash && count($options) > 0) {
foreach ($options as $option) {
$matches = array();
if (preg_match('/^redirect(\[(30[1237])\])?$/', $option, $matches)) {
$code = count($matches) > 1 ? $matches[2] : 301;
$status = 'HTTP/1.1 ' . $code . ' TYPO3 RealURL redirect';
// Check path segment to be relative for the current site.
// parse_url() does not work with relative URLs, so we use it to test
if (!@parse_url($this->speakingUri, PHP_URL_HOST)) {
$this->logger->notice(
sprintf(
'RealURL redirects from "%s" to "%s" due to missing slash',
$originalUri,
$this->speakingUri
)
);
@ob_end_clean();
header($status);
header(self::REDIRECT_INFO_HEADER . ': redirect for missing slash');
header('Content-length: 0');
header('Connection: close');
header('Location: ' . GeneralUtility::locationHeaderUrl($this->speakingUri));
exit;
}
}
}
}
}
}
/**
* Converts alias to id.
*
* @param array $configuration
* @param string $value
* @return int|string
*/
protected function convertAliasToId(array $configuration, $value) {
$result = (string)$value;
// First, test if there is an entry in cache for the alias
if ($configuration['useUniqueCache']) {
$cachedId = $this->getFromAliasCacheByAliasValue($configuration, $value);
if (MathUtility::canBeInterpretedAsInteger($cachedId)) {
$result = (int)$cachedId;
}
}
if (!is_int($result) && $configuration['table'] !== 'pages') {
// If no cached entry, look it up directly in the table. Note: this will
// most likely fail. When encoding we convert alias field to a nice
// looking URL segment, which usually looks differently from the field.
// But this is the only thing we can do without fetching each record and
// re-encoding the field to find the match.
// Assemble list of fields to look up. This includes localization related fields
$translationEnabled = FALSE;
$fieldList = array();
if ($configuration['languageGetVar'] && $configuration['transOrigPointerField'] && $configuration['languageField']) {
$fieldList[] = 'uid';
if ($configuration['table'] !== 'pages') {
$fieldList[] = $configuration['transOrigPointerField'];
$fieldList[] = $configuration['languageField'];
}
$translationEnabled = TRUE;
}
$fieldList[] = $configuration['id_field'];
$row = $this->databaseConnection->exec_SELECTgetSingleRow(implode(',', $fieldList),
$configuration['table'],
$configuration['alias_field'] . '=' . $this->databaseConnection->fullQuoteStr($value, $configuration['table']) .
' ' . $configuration['addWhereClause']);
if (is_array($row)) {
$result = (int)$row[$configuration['id_field']];
// If localization is enabled, check if this record is a localized version and if so, find uid of the original version.
if ($translationEnabled && $row[$configuration['languageField']] > 0) {
$result = (int)$row[$configuration['transOrigPointerField']];
}
}
}
return $result;
}
/**
* Find a page entry for the current segment and returns a PathCacheEntry for it.
*
* @param string $segment
* @param array $pages
* @param array $shortcutPages
* @return \DmitryDulepov\Realurl\Cache\PathCacheEntry | NULL
*/
protected function createPathCacheEntry($segment, array $pages, array &$shortcutPages) {
$result = NULL;
foreach ($pages as $page) {
$originalMountPointPid = 0;
if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
// Value is not relevant, key is!
$shortcutPages[$page['uid']] = true;
}
while ($page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $page['mount_pid_ol'] == 1) {
$originalMountPointPid = $page['uid'];
$page = $this->pageRepository->getPage($page['mount_pid']);
if (!is_array($page)) {
$this->tsfe->pageNotFoundAndExit('[realurl] Broken mount point at page with uid=' . $originalMountPointPid);
}
}
$languageExceptionUids = (string)$this->configuration->get('pagePath/languageExceptionUids');
if ($this->detectedLanguageId > 0 && !isset($page['_PAGES_OVERLAY']) && (empty($languageExceptionUids) || !GeneralUtility::inList($languageExceptionUids, $this->detectedLanguageId))) {
$page = $this->pageRepository->getPageOverlay($page, (int)$this->detectedLanguageId);
}
foreach (self::$pageTitleFields as $field) {
if (isset($page[$field]) && $page[$field] !== '' && $this->utility->convertToSafeString($page[$field], $this->separatorCharacter) === $segment) {
$result = GeneralUtility::makeInstance('DmitryDulepov\\Realurl\\Cache\\PathCacheEntry');
/** @var \DmitryDulepov\Realurl\Cache\PathCacheEntry $result */
$result->setPageId((int)$page['uid']);
if ($this->mountPointVariable !== '') {
$result->setMountPoint($this->mountPointVariable);
}
if ($originalMountPointPid !== 0) {
// Mount point with mount_pid_ol==1
$this->mountPointVariable = $page['uid'] . '-' . $originalMountPointPid;
// No $this->mountPointStartPid here because this is a substituted page
}
elseif ((int)$page['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
$this->mountPointVariable = $page['mount_pid'] . '-' . $page['uid'];
$this->mountPointStartPid = (int)$page['mount_pid'];
}
break 2;
}
}
}
return $result;
}
/**
* Generates a parameter string from an array recursively
*
* @param array $parameters Array to generate strings from
* @param string $prependString path to prepend to every parameter
* @return array
*/
protected function createQueryStringParameter($parameters, $prependString = '') {
if (!is_array($parameters)) {
return array($prependString . '=' . $parameters);
}
if (count($parameters) == 0) {
return array();
}
$paramList = array();
foreach ($parameters as $var => $value) {
$paramList = array_merge($paramList, $this->createQueryStringParameter($value, $prependString . '[' . $var . ']'));
}
return $paramList;
}
/**
* Decodes fixedPostVars into request variables.
*
* @param int $pageId
* @param array $pathSegments
* @return array
*/
protected function decodeFixedPostVars($pageId, array &$pathSegments) {
$requestVariables = array();
if (count($pathSegments) > 0) {
$allPostVars = array_filter((array)$this->configuration->get('fixedPostVars'));
$postVars = $this->getConfigurationForPostVars($allPostVars, $pageId);
$previousValue = '';
foreach ($postVars as $postVarConfiguration) {
if (!is_array($postVarConfiguration)) {
continue;
}
$this->decodeSingleVariable($postVarConfiguration, $pathSegments, $requestVariables, $previousValue);
if (empty($postVars['requireFullEvaluation']) && count($pathSegments) === 0) {
break;
}
}
}
return $requestVariables;
}
/**
* Decodes the path.
*
* @param array $pathSegments
* @return int
*/
protected function decodePath(array &$pathSegments) {
$savedRemainingPathSegments = array();
$currentPid = 0;
$remainingPathSegments = $pathSegments;
$savedResult = NULL;
$result = $this->searchPathInCache($remainingPathSegments);
$allPathsAreExpired = $this->isExpiredPath && $result && !$this->expiredPath;
if ($allPathsAreExpired) {
// Special case: all paths are expired. We will try to unexpire the actual entry.
$savedRemainingPathSegments = $remainingPathSegments;
$remainingPathSegments = $pathSegments;
$savedResult = $result;
$result = NULL;
}
if (is_null($result)) {
$result = $this->decodePathByOverride($remainingPathSegments);
if (!is_null($result)) {
$currentPid = $result->getPageId();
}
}
if (is_null($result) || count($remainingPathSegments) > 0) {
// Here we are if one of the following is true:
// - nothing is in the cache
// - there is an entry in the cache for the partial path
// We see what it is:
// - if a postVar exists for the next segment, it is a full path
// - if no path segments left, we found the path
// - otherwise we have to search
reset($pathSegments);
if (!$this->isPostVar(current($pathSegments))) {
if ($result) {
$processedPathSegments = array_diff($pathSegments, $remainingPathSegments);
$currentPid = $result->getPageId();
} else {
$processedPathSegments = array();
$currentPid = $this->rootPageId;
}
$currentMountPointPid = 0;
while ($currentPid !== 0 && count($remainingPathSegments) > 0) {
$segment = array_shift($remainingPathSegments);
if ($segment === '') {
array_unshift($remainingPathSegments, $segment);
break;
}
$saveToCache = true;
$nextResult = $this->searchPages($currentPid, $segment, $saveToCache);
if ($nextResult) {
$result = $nextResult;
if ($this->mountPointStartPid !== $currentMountPointPid) {
$currentPid = $currentMountPointPid = $this->mountPointStartPid;
}
else {
$currentPid = $result->getPageId();
}
$processedPathSegments[] = $segment;
$result->setPagePath(implode('/', $processedPathSegments));
if ($saveToCache) {
// Path is valid so far, so we cache it
$this->putToPathCache($result);
}
}
elseif ($this->isPostVar($segment, $currentPid)) {
// Not decoded, looks like a postVarSet. Put it back.
array_unshift($remainingPathSegments, $segment);
break;
}
else {
// Not decoded, not a postVarSet, could be a fixedPostVar. Still put back and hope for the best!
array_unshift($remainingPathSegments, $segment);
break;
}
}
}
elseif ($currentPid === 0) {
// Found a postVar on the rootPage
$currentPid = $this->rootPageId;
}
}
if ($allPathsAreExpired && !$result) {
// We could not resolve the new path, use the expired one :(
$result = $savedResult;
$remainingPathSegments = $savedRemainingPathSegments;
}
if ($result && $this->expiredPath) {
$startPosition = (int)strpos($this->speakingUri, $this->expiredPath);
if ($startPosition !== FALSE) {
$newUrl = substr($this->speakingUri, 0, $startPosition) .
$result->getPagePath() .
substr($this->speakingUri, $startPosition + strlen($this->expiredPath));
$this->logger->debug(
sprintf(
'RealURL is redirecting from "%s" to "%s" because the former is expired',
$this->speakingUri,
$newUrl
)
);
@ob_end_clean();
header(self::REDIRECT_STATUS_HEADER);
header(self::REDIRECT_INFO_HEADER . ': redirect for expired page path');
header('Content-length: 0');
header('Connection: close');
header('Location: ' . GeneralUtility::locationHeaderUrl($newUrl));
die;
}
}
if ($result || (int)$currentPid === (int)$this->rootPageId) {
$pathSegments = $remainingPathSegments;
} else {
$this->logger->error(
sprintf(
'Decoder was not able to decode "%s" and will throw a 404 now',
implode('/', $pathSegments)
)
);
$this->throw404('Cannot decode "' . implode('/', $pathSegments) . '"');
}
$pageId = 0;
if ($result) {
if ($result->getMountPoint()) {
$this->mountPointVariable = $result->getMountPoint();
}
$pageId = $result->getPageId();
} elseif ((int)$currentPid === (int)$this->rootPageId) {
$pageId = $currentPid;
}
return $pageId;
}
/**
* Tries to decode the path by path override when the whole path is overriden.
*
* @param array $pathSegments
* @return PathCacheEntry
*/
protected function decodePathByOverride(array &$pathSegments) {
$result = null;
$possibleSegments = array();
foreach ($pathSegments as $segment) {
if ($this->isPostVar($segment)) {
break;
}
$possibleSegments[] = $segment;
}
while (!empty($possibleSegments) && !$result) {
$result = $this->searchPagesByPathOverride($possibleSegments);
if (!$result) {
array_pop($possibleSegments);
}
}
if ($result) {
$pathSegments = array_slice($pathSegments, count($possibleSegments));
}
return $result;
}
/**
* Decodes preVars into request variables.
*
* @param array $pathSegments
* @return array
*/
protected function decodePreVars(array &$pathSegments) {
$requestVariables = array();
if (count($pathSegments) > 0) {
$preVarsList = array_filter((array)$this->configuration->get('preVars'));
$previousValue = '';
foreach ($preVarsList as $preVarConfiguration) {
$this->decodeSingleVariable($preVarConfiguration, $pathSegments, $requestVariables, $previousValue);
if (count($pathSegments) == 0) {
break;
}
}
if (isset($requestVariables['L'])) {
$this->detectedLanguageId = (int)$requestVariables['L'];
}
}
if (is_null($this->detectedLanguageId)) {
$this->detectedLanguageId = (int)$this->configuration->get('init/defaultLanguageUid');
}
return $requestVariables;
}
/**
* Decodes postVarSets into request variables.
*
* @param int $pageId
* @param array $pathSegments
* @return array
*/
protected function decodePostVarSets($pageId, array &$pathSegments) {
$requestVariables = array();
if (count($pathSegments) > 0) {
$allPostVarSets = array_filter((array)$this->configuration->get('postVarSets'));
$postVarSets = $this->getConfigurationForPostVars($allPostVarSets, $pageId);
$previousValue = '';
while (count($pathSegments) > 0) {
$postVarSetKey = array_shift($pathSegments);
if (!isset($postVarSets[$postVarSetKey]) || !is_array($postVarSets[$postVarSetKey])) {
$this->handleNonExistingPostVarSet($pageId, $postVarSetKey, $pathSegments);
} else {
$postVarSetConfiguration = $postVarSets[$postVarSetKey];
// Note: we do not support aliases for postVarSets!
if (is_array($postVarSetConfiguration)) {
foreach ($postVarSetConfiguration as $postVarConfiguration) {
$this->decodeSingleVariable($postVarConfiguration, $pathSegments, $requestVariables, $previousValue);
}
}
}
}
}
return $requestVariables;
}
/**
* Decodes a single variable and adds it to the list of request variables.
*
* @param array $varConfiguration
* @param array $pathSegments
* @param array $requestVariables
* @param $previousValue
* @return void
*/
protected function decodeSingleVariable(array $varConfiguration, array &$pathSegments, array &$requestVariables, &$previousValue) {
static $varProcessingFunctions = array(
'decodeUrlParameterBlockUsingValueMap',
'decodeUrlParameterBlockUsingNoMatch',
'decodeUrlParameterBlockUsingUserFunc',
'decodeUrlParameterBlockUsingLookupTable',
'decodeUrlParameterBlockUsingValueDefault',
// Always the last one!
'decodeUrlParameterBlockUseAsIs',
);
if (count($pathSegments) > 0) {
$getVarValue = count($pathSegments) > 0 ? array_shift($pathSegments) : '';
if ($this->emptySegmentValue !== '' && $getVarValue === $this->emptySegmentValue) {
$getVarValue = '';
}
$isFakeValue = false;
}
else {
$getVarValue = '';
$isFakeValue = true;
}
// TODO Possible hook here before any other function? Pass name, value, segments and config
$handled = FALSE;
if (!isset($varConfiguration['cond']) || $this->checkLegacyCondition($varConfiguration['cond'], $previousValue)) {
foreach ($varProcessingFunctions as $varProcessingFunction) {
if (isset($varConfiguration['GETvar'])) {
if ($this->$varProcessingFunction($varConfiguration, $getVarValue, $requestVariables, $pathSegments, $isFakeValue)) {
$previousValue = (string)end($requestVariables);
$handled = TRUE;
break;
}
}
else {
// TODO Log about bad configuration
}
}
}
if (!$handled && !$isFakeValue) {
array_unshift($pathSegments, $getVarValue);
}
}
/**
* Sets segment value as is to the request variables
*
* @param array $configuration
* @param $getVarValue
* @param array $requestVariables
* @return bool
*/
protected function decodeUrlParameterBlockUseAsIs(array $configuration, $getVarValue, array &$requestVariables) {
// TODO Possible conditions: if int, if notEmpty, etc
$requestVariables[$configuration['GETvar']] = $getVarValue;
return TRUE;
}
/**
* Sets segment value as is to the request variables
*
* @param array $configuration
* @param $getVarValue
* @param array $requestVariables
* @return bool
*/
protected function decodeUrlParameterBlockUsingLookupTable(array $configuration, $getVarValue, array &$requestVariables) {
$result = FALSE;
if (isset($configuration['lookUpTable'])) {
$value = $this->convertAliasToId($configuration['lookUpTable'], $getVarValue);
if (!MathUtility::canBeInterpretedAsInteger($value) && $value === $getVarValue) {
if ($configuration['lookUpTable']['enable404forInvalidAlias']) {
$this->throw404('Could not map alias "' . $value . '" to an id.');
}
} else {
$requestVariables[$configuration['GETvar']] = $value;
$result = TRUE;
}
}
return $result;
}
/**
* Sets segment value as is to the request variables
*
* @param array $configuration
* @param $getVarValue
* @param array $requestVariables
* @param array $pathSegments
* @param bool $isFakeValue
* @return bool
*/
protected function decodeUrlParameterBlockUsingNoMatch(array $configuration, $getVarValue, /** @noinspection PhpUnusedParameterInspection */ array &$requestVariables, array &$pathSegments, $isFakeValue) {
$result = FALSE;
if ($configuration['noMatch'] == 'bypass') {
// If no match and "bypass" is set, then return the value to $pathSegments and break
if (!$isFakeValue) {
array_unshift($pathSegments, $getVarValue);
}
$result = TRUE;
} elseif ($configuration['noMatch'] == 'null') {
// If no match and "null" is set, then break (without setting any value!)
$result = TRUE;
}
return $result;
}
/**
* Sets segment value as is to the request variables
*
* @param array $configuration
* @param $getVarValue
* @param array $requestVariables
* @param array $pathSegments
* @param bool $isFakeValue
* @return bool
*/
protected function decodeUrlParameterBlockUsingUserFunc(array $configuration, $getVarValue, array &$requestVariables, array &$pathSegments, $isFakeValue) {
$result = FALSE;
if (isset($configuration['userFunc'])) {
$parameters = array(
'decodeAlias' => true,
'isFakeValue' => $isFakeValue,
'origValue' => $getVarValue,
'pathParts' => &$pathSegments,
'pObj' => $this,
'sysLanguageUid' => $this->detectedLanguageId,
'value' => $getVarValue,
'setup' => $configuration
);
$value = GeneralUtility::callUserFunction($configuration['userFunc'], $parameters, $this);
if (is_numeric($value) || is_string($value)) {
$requestVariables[$configuration['GETvar']] = $value;
$result = TRUE;
}
}
return $result;
}
/**
* Sets segment value as is to the request variables
*
* @param array $configuration
* @param $getVarValue
* @param array $requestVariables
* @return bool
*/
protected function decodeUrlParameterBlockUsingValueDefault(array $configuration, /** @noinspection PhpUnusedParameterInspection */ $getVarValue, array &$requestVariables) {
$result = FALSE;
if (isset($configuration['valueDefault'])) {
$defaultValue = $configuration['valueDefault'];
$requestVariables[$configuration['GETvar']] = isset($configuration['valueMap'][$defaultValue]) ? $configuration['valueMap'][$defaultValue] : $defaultValue;
$result = TRUE;
}
return $result;
}
/**
* Sets segment value as is to the request variables
*
* @param array $configuration
* @param $getVarValue
* @param array $requestVariables
* @return bool
*/
protected function decodeUrlParameterBlockUsingValueMap(array $configuration, $getVarValue, array &$requestVariables) {
$result = FALSE;
if (isset($configuration['valueMap'][$getVarValue])) {
$requestVariables[$configuration['GETvar']] = $configuration['valueMap'][$getVarValue];
$result = TRUE;
}
return $result;
}
/**
* Decodes the URL. This function is called only if the URL is not in the
* URL cache.
*
* @param string $path
* @return UrlCacheEntry with only pageId and requestVariables filled in
*/
protected function doDecoding($path) {
$path = trim($path, '/');
$pathSegments = $path ? explode('/', $path) : array();
// Remember: urldecode(), not rawurldecode()!
foreach($pathSegments as $id => $value) {
$pathSegments[$id] = urldecode($value);
}
$requestVariables = array();
ArrayUtility::mergeRecursiveWithOverrule($requestVariables, $this->handleFileName($pathSegments));
ArrayUtility::mergeRecursiveWithOverrule($requestVariables, $this->getVarsFromDomainConfiguration());
ArrayUtility::mergeRecursiveWithOverrule($requestVariables, $this->decodePreVars($pathSegments));
$pageId = $this->decodePath($pathSegments);
if ($this->mountPointVariable !== '') {
$requestVariables['MP'] = $this->mountPointVariable;
}
ArrayUtility::mergeRecursiveWithOverrule($requestVariables, $this->decodeFixedPostVars($pageId, $pathSegments));
ArrayUtility::mergeRecursiveWithOverrule($requestVariables, $this->decodePostVarSets($pageId, $pathSegments));
$this->mergeWithExistingGetVars($requestVariables);
$cacheEntry = GeneralUtility::makeInstance('DmitryDulepov\\Realurl\\Cache\\UrlCacheEntry');
/** @var \DmitryDulepov\Realurl\Cache\UrlCacheEntry $cacheEntry */
$cacheEntry->setPageId($pageId);
$cacheEntry->setRequestVariables($requestVariables);
return $cacheEntry;
}
/**
* Fixes a problem with parse_str that returns `a[b[c]` instead of `a[b[c]]` when parsing `a%5Bb%5Bc%5D%5D`
*
* @param array $array
* @return void
*/
protected function fixBracketsAfterParseStr(array &$array) {
$badKeys = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$this->fixBracketsAfterParseStr($array[$key]);
} else {
if (strchr($key, '[') && !strchr($key, ']')) {
$badKeys[] = $key;
}
}
}
if (count($badKeys) > 0) {
foreach ($badKeys as $key) {
$arr[$key . ']'] = $array[$key];
unset($array[$key]);
}
}
}
/**
* Gets the entry from cache.
*
* @param string $speakingUrl
* @return UrlCacheEntry|null
*/
protected function getFromUrlCache($speakingUrl) {
return $this->cache->getUrlFromCacheBySpeakingUrl($this->rootPageId, $speakingUrl, $this->detectedLanguageId);
}
/**
* Searches a page below excluded pages and returns the PathCacheEntry if something was found.
*
* @param string $segment
* @param array $pages
* @param string $pagesEnableFields
* @param array $shortcutPages
* @return \DmitryDulepov\Realurl\Cache\PathCacheEntry | NULL
*/
protected function getPathCacheEntryAfterExcludedPages($segment, array $pages, $pagesEnableFields, array &$shortcutPages) {
$ids = array();
$result = null;
$newPages = $pages;
while ($newPages) {
foreach ($newPages as $page) {
while ($page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $page['mount_pid_ol'] == 1) {
$originalUid = $page['uid'];
$page = $this->pageRepository->getPage($page['mount_pid']);
if (!is_array($page)) {
$this->tsfe->pageNotFoundAndExit('[realurl] Broken mount point at page with uid=' . $originalUid);
}
}
if ($page['tx_realurl_exclude']) {
$ids[] = $page['uid'];
}
}
if ($ids) {
// No sorting here because pages can be on any level
$children = $this->databaseConnection->exec_SELECTgetRows(
'*', 'pages', 'pid IN (' . implode(',', $ids) . ')' .
' AND doktype NOT IN (' . $this->disallowedDoktypes . ')' . $pagesEnableFields
);
$languageExceptionUids = (string)$this->configuration->get('pagePath/languageExceptionUids');
if ($this->detectedLanguageId > 0 && (empty($languageExceptionUids) || !GeneralUtility::inList($languageExceptionUids, $this->detectedLanguageId))) {
foreach ($children as $key => $child) {
$children[$key] = $this->pageRepository->getPageOverlay($child, (int)$this->detectedLanguageId);
}
}
$result = $this->createPathCacheEntry($segment, $children, $shortcutPages);
if ($result) {
break;
}
$newPages = $children;
$ids = array();
} else {
break;
}
}
return $result;
}
/**
* Parses the URL and validates the result. This function will strip possible
* query string from speaking URL (we only need to decode the speaking URL!)
*
* @return array