This repository has been archived by the owner on May 7, 2022. It is now read-only.
forked from fbrnc/Realurl
-
Notifications
You must be signed in to change notification settings - Fork 3
/
class.tx_realurl_advanced.php
executable file
·1316 lines (1202 loc) · 45 KB
/
class.tx_realurl_advanced.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) 2004 Martin Poelstra ([email protected])
* (c) 2005-2010 Dmitry Dulepov ([email protected])
* All rights reserved
*
* 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!
***************************************************************/
/**
* Class for translating page ids to/from path strings (Speaking URLs)
*
* $Id$
*
* @author Martin Poelstra <[email protected]>
* @author Kasper Skaarhoj <[email protected]>
* @author Dmitry Dulepov <[email protected]>
*/
/**
* Class for translating page ids to/from path strings (Speaking URLs)
*
* @author Martin Poelstra <[email protected]>
* @author Kasper Skaarhoj <[email protected]>
* @author Dmitry Dulepov <[email protected]>
* @package realurl
* @subpackage tx_realurl
*/
class tx_realurl_advanced {
/** @var tx_realurl_apiwrapper */
protected $apiWrapper;
/**
* t3lib_page object for finding rootline on the fly
*
* @var t3lib_pageSelect|\TYPO3\CMS\Frontend\Page\PageRepository
*/
protected $sysPage;
/**
* Reference to parent object
*
* @var tx_realurl
*/
protected $pObj;
/**
* Class configuration
*
* @var array $conf
*/
protected $conf;
/**
* Configuration for the current domain
*
* @var array
*/
protected $extConf;
public function __construct() {
$this->apiWrapper = tx_realurl_apiwrapper::getInstance();
}
/**
* Main function, called for both encoding and deconding of URLs.
* Based on the "mode" key in the $params array it branches out to either decode or encode functions.
*
* @param array $params Parameters passed from parent object, "tx_realurl". Some values are passed by reference! (paramKeyValues, pathParts and pObj)
* @param tx_realurl $parent Copy of parent object. Not used.
* @return mixed Depends on branching.
*/
public function main(array $params, tx_realurl $parent) {
// Setting internal variables
$this->pObj = $parent;
$this->conf = $params['conf'];
$this->extConf = $this->pObj->getConfiguration();
// Branching out based on type
$result = false;
switch ((string)$params['mode']) {
case 'encode':
$this->IDtoPagePath($params['paramKeyValues'], $params['pathParts']);
$result = NULL;
break;
case 'decode':
$result = $this->pagePathtoID($params['pathParts']);
break;
}
return $result;
}
/*******************************
*
* "path" ID-to-URL methods
*
******************************/
/**
* Retrieve the page path for the given page-id.
* If the page is a shortcut to another page, it returns the page path to the shortcutted page.
* MP get variables are also encoded with the page id.
*
* @param array $paramKeyValues GETvar parameters containing eg. "id" key with the page id/alias (passed by reference)
* @param array $pathParts Path parts array (passed by reference)
* @return void
* @see encodeSpURL_pathFromId()
*/
protected function IDtoPagePath(array &$paramKeyValues, &$pathParts) {
$pageId = $paramKeyValues['id'];
unset($paramKeyValues['id']);
$mpvar = (string)$paramKeyValues['MP'];
unset($paramKeyValues['MP']);
// Convert a page-alias to a page-id if needed
$pageId = $this->resolveAlias($pageId);
$pageId = $this->resolveShortcuts($pageId, $mpvar);
if ($pageId) {
// Set error if applicable.
if ($this->isExcludedPage($pageId)) {
$this->pObj->setEncodeError();
}
else {
$lang = $this->getLanguageVar($paramKeyValues);
$cachedPagePath = $this->getPagePathFromCache($pageId, $lang, $mpvar);
if ($cachedPagePath !== false) {
$pagePath = $cachedPagePath;
}
else {
$pagePath = $this->createPagePathAndUpdateURLCache($pageId,
$mpvar, $lang, $cachedPagePath);
}
// Set error if applicable.
if ($pagePath === '__ERROR') {
$this->pObj->setEncodeError();
}
else {
$this->mergeWithPathParts($pathParts, $pagePath);
}
}
}
}
/**
* If page id is not numeric, try to resolve it from alias.
*
* @param int|string $pageId
* @return mixed
*/
private function resolveAlias($pageId) {
if (!is_numeric($pageId)) {
$pageId = $GLOBALS['TSFE']->sys_page->getPageIdFromAlias($pageId);
}
return $pageId;
}
/**
* Checks if the page should be excluded from processing.
*
* @param int $pageId
* @return boolean
*/
protected function isExcludedPage($pageId) {
return $this->conf['excludePageIds'] && $this->apiWrapper->inList($this->conf['excludePageIds'], $pageId);
}
/**
* Merges the path with existing path parts and creates an array of path
* segments.
*
* @param array $pathParts
* @param string $pagePath
* @return void
*/
protected function mergeWithPathParts(array &$pathParts, $pagePath) {
if (strlen($pagePath)) {
$pagePathParts = explode('/', $pagePath);
$pathParts = array_merge($pathParts, $pagePathParts);
}
}
/**
* Resolves shortcuts if necessary and returns the final destination page id.
*
* @param int $pageId
* @param array $mpvar
* @return mixed false if not found or int
*/
protected function resolveShortcuts($pageId, &$mpvar) {
$disableGroupAccessCheck = true;
$loopCount = 20; // Max 20 shortcuts, to prevent an endless loop
while ($pageId > 0 && $loopCount > 0) {
$loopCount--;
$page = $GLOBALS['TSFE']->sys_page->getPage($pageId, $disableGroupAccessCheck);
if (!$page) {
$pageId = false;
break;
}
if (!$this->conf['dontResolveShortcuts'] && $page['doktype'] == 4) {
// Shortcut
$pageId = $this->resolveShortcut($page, $disableGroupAccessCheck, array(), $mpvar);
}
else {
$pageId = $page['uid'];
break;
}
$disableGroupAccessCheck = ($GLOBALS['TSFE']->config['config']['typolinkLinkAccessRestrictedPages'] ? true : false);
}
return $pageId;
}
/**
* Retireves page path from cache.
*
* @param int $pageid
* @param int $lang
* @param string $mpvar
* @return mixed Page path (string) or false if not found
*/
private function getPagePathFromCache($pageid, $lang, $mpvar) {
$result = false;
if (!$this->conf['disablePathCache']) {
/** @noinspection PhpUndefinedMethodInspection */
list($cachedPagePath) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('pagepath', 'tx_realurl_pathcache',
'page_id=' . intval($pageid) .
' AND language_id=' . intval($lang) .
' AND rootpage_id=' . intval($this->conf['rootpage_id']) .
' AND mpvar=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($mpvar, 'tx_realurl_pathcache') .
' AND expire=0', '', '', 1);
if (is_array($cachedPagePath)) {
$result = $cachedPagePath['pagepath'];
}
}
return $result;
}
/**
* Creates the path and inserts into the path cache (if enabled).
*
* @param int $id Page id
* @param string $mpvar MP variable string
* @param int $lang Language uid
* @param string $cachedPagePath If set, then a new entry will be inserted ONLY if it is different from $cachedPagePath
* @return string The page path
*/
protected function createPagePathAndUpdateURLCache($id, $mpvar, $lang, $cachedPagePath = '') {
$pagePathRec = $this->getPagePathRec($id, $mpvar, $lang);
if (!$pagePathRec) {
return '__ERROR';
}
$this->updateURLCache($id, $cachedPagePath, $pagePathRec['pagepath'],
$pagePathRec['langID'], $pagePathRec['rootpage_id'], $mpvar);
return $pagePathRec['pagepath'];
}
/**
* Adds a new entry to the path cache.
*
* @param int $pageId
* @param int $cachedPagePath
* @param int $pagePath
* @param int $langId
* @param int $rootPageId
* @param string $mpvar
* @return void
*/
private function updateURLCache($pageId, $cachedPagePath, $pagePath, $langId, $rootPageId, $mpvar) {
$canCachePaths = !$this->conf['disablePathCache'] && !$this->pObj->isBEUserLoggedIn();
$newPathDiffers = ((string)$pagePath !== (string)$cachedPagePath);
if ($canCachePaths && $newPathDiffers) {
/** @noinspection PhpUndefinedMethodInspection */
$cacheCondition = 'page_id=' . intval($pageId) .
' AND language_id=' . intval($langId) .
' AND rootpage_id=' . intval($rootPageId) .
' AND mpvar=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($mpvar, 'tx_realurl_pathcache');
/** @noinspection PhpUndefinedMethodInspection */
$GLOBALS['TYPO3_DB']->sql_query('START TRANSACTION');
$this->removeExpiredPathCacheEntries();
$this->setExpirationOnOldPathCacheEntries($pagePath, $cacheCondition);
$this->addNewPagePathEntry($pagePath, $cacheCondition, $pageId, $mpvar, $langId, $rootPageId);
/** @noinspection PhpUndefinedMethodInspection */
$GLOBALS['TYPO3_DB']->sql_query('COMMIT');
}
}
/**
* Obtains a page path record.
*
* @param int $id
* @param string $mpvar
* @param int $lang
* @return mixed array(pagepath,langID,rootpage_id) if successful, false otherwise
*/
protected function getPagePathRec($id, $mpvar, $lang) {
static $IDtoPagePathCache = array();
$cacheKey = $id . '.' . $mpvar . '.' . $lang;
if (isset($IDtoPagePathCache[$cacheKey])) {
$pagePathRec = $IDtoPagePathCache[$cacheKey];
}
else {
$pagePathRec = $this->IDtoPagePathThroughOverride($id, $mpvar, $lang);
if (!$pagePathRec) {
// Build the new page path, in the correct language
$pagePathRec = $this->IDtoPagePathSegments($id, $mpvar, $lang);
}
$IDtoPagePathCache[$cacheKey] = $pagePathRec;
}
return $pagePathRec;
}
/**
* Checks if the page has a path to override.
*
* @param int $id
* @param string $mpvar
* @param int $lang
* @return array
*/
protected function IDtoPagePathThroughOverride($id, /** @noinspection PhpUnusedParameterInspection */ $mpvar, $lang) {
$result = false;
$page = $this->getPage($id, $lang);
if ($page['tx_realurl_pathoverride']) {
if ($page['tx_realurl_pathsegment']) {
$result = array(
'pagepath' => trim($page['tx_realurl_pathsegment'], '/'),
'langID' => intval($lang),
// TODO Might be better to fetch root line here to process mount
// points and inner subdomains correctly.
'rootpage_id' => intval($this->conf['rootpage_id'])
);
}
else {
$message = sprintf('Path override is set for page=%d (language=%d) but no segment defined!',
$id, $lang);
$this->apiWrapper->sysLog($message, 'realurl', 3);
$this->pObj->devLog($message, false, 2);
}
}
return $result;
}
/**
* Obtains a page and its translation (if necessary). The reason to use this
* function instead of $GLOBALS['TSFE']->sys_page->getPage() is that
* $GLOBALS['TSFE']->sys_page->getPage() always applies a language overlay
* (even if we have a different language id).
*
* @param int $pageId
* @param int $languageId
* @return mixed Page row or false if not found
*/
protected function getPage($pageId, $languageId) {
$condition = 'uid=' . intval($pageId) . $GLOBALS['TSFE']->sys_page->where_hid_del;
// Note: we do not use $GLOBALS['TSFE']->sys_page->where_groupAccess here
// because we will not come here unless typolinkLinkAccessRestrictedPages
// was active in 'config' or 'typolink'
/** @noinspection PhpUndefinedMethodInspection */
list($row) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'pages',
$condition);
if (is_array($row) && $languageId > 0) {
$row = $GLOBALS['TSFE']->sys_page->getPageOverlay($row, $languageId);
}
return $row;
}
/**
* Adds a new entry to the path cache or revitalizes existing ones
*
* @param string $currentPagePath
* @param string $pathCacheCondition
* @param int $pageId
* @param string $mpvar
* @param int $langId
* @param int $rootPageId
* @return void
*/
protected function addNewPagePathEntry($currentPagePath, $pathCacheCondition, $pageId, $mpvar, $langId, $rootPageId) {
/** @noinspection PhpUndefinedMethodInspection */
$condition = $pathCacheCondition . ' AND pagepath=' .
$GLOBALS['TYPO3_DB']->fullQuoteStr($currentPagePath, 'tx_realurl_pathcache');
$revitalizationCondition = $condition . ' AND expire<>0';
/** @noinspection PhpUndefinedMethodInspection */
list($revitalizationCount) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('COUNT(*) AS t',
'tx_realurl_pathcache', $revitalizationCondition);
if ($revitalizationCount['t'] > 0) {
/** @noinspection PhpUndefinedMethodInspection */
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_realurl_pathcache', $revitalizationCondition, array('expire' => 0));
}
else {
$createCondition = $condition . ' AND expire=0';
/** @noinspection PhpUndefinedMethodInspection */
list($createCount) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('COUNT(*) AS t',
'tx_realurl_pathcache', $createCondition);
if ($createCount['t'] == 0) {
$insertArray = array(
'page_id' => $pageId,
'language_id' => $langId,
'pagepath' => $currentPagePath,
'expire' => 0,
'rootpage_id' => $rootPageId,
'mpvar' => $mpvar
);
/** @noinspection PhpUndefinedMethodInspection */
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_realurl_pathcache', $insertArray);
}
}
}
/**
* Sets expiration time for the old path cache entries
*
* @param string $currentPagePath
* @param string $pathCacheCondition
* @return void
*/
protected function setExpirationOnOldPathCacheEntries($currentPagePath, $pathCacheCondition) {
$expireDays = (isset($this->conf['expireDays']) ? $this->conf['expireDays'] : 60) * 24 * 3600;
/** @noinspection PhpUndefinedMethodInspection */
$condition = $pathCacheCondition . ' AND expire=0 AND pagepath<>' .
$GLOBALS['TYPO3_DB']->fullQuoteStr($currentPagePath, 'tx_realurl_pathcache');
/** @noinspection PhpUndefinedMethodInspection */
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_realurl_pathcache', $condition,
array(
'expire' => $this->makeExpirationTime($expireDays)
),
'expire'
);
}
/**
* Removes all expired path cache entries
*
* @return void
*/
protected function removeExpiredPathCacheEntries() {
$lastCleanUpFileName = PATH_site . 'typo3temp/realurl_last_clean_up';
$lastCleanUpTime = @filemtime($lastCleanUpFileName);
if ($lastCleanUpTime === false || (time() - $lastCleanUpTime >= 6*60*60)) {
touch($lastCleanUpFileName);
/** @noinspection PhpUndefinedMethodInspection */
$GLOBALS['TYPO3_DB']->exec_DELETEquery('tx_realurl_pathcache',
'expire>0 AND expire<' . $this->makeExpirationTime());
}
}
/**
* Fetch the page path (in the correct language)
* Return it in an array like:
* array(
* 'pagepath' => 'product_omschrijving/another_page_title/',
* 'langID' => '2',
* );
*
* @param int $id Page ID
* @param string $mpvar MP variable string
* @param int $langID Language id
* @return array The page path etc.
*/
protected function IDtoPagePathSegments($id, $mpvar, $langID) {
$result = false;
// Get rootLine for current site (overlaid with any language overlay records).
$this->createSysPageIfNecessary();
$this->sysPage->sys_language_uid = $langID;
$rootLine = $this->sysPage->getRootLine($id, $mpvar);
$numberOfRootlineEntries = count($rootLine);
$newRootLine = array();
$rootFound = FALSE;
if (!$GLOBALS['TSFE']->tmpl->rootLine) {
$GLOBALS['TSFE']->tmpl->start($GLOBALS['TSFE']->rootLine);
}
// Pass #1 -- check if linking a page in subdomain inside main domain
$innerSubDomain = false;
for ($i = $numberOfRootlineEntries - 1; $i >= 0; $i--) {
if ($rootLine[$i]['is_siteroot']) {
$this->pObj->devLog('Found siteroot in the rootline for id=' . $id);
$rootFound = true;
$innerSubDomain = true;
for ( ; $i < $numberOfRootlineEntries; $i++) {
$newRootLine[] = $rootLine[$i];
}
break;
}
}
if (!$rootFound) {
// Pass #2 -- check normal page
$this->pObj->devLog('Starting to walk rootline for id=' . $id . ' from index=' . $i, $rootLine);
for ($i = 0; $i < $numberOfRootlineEntries; $i++) {
if ($GLOBALS['TSFE']->tmpl->rootLine[0]['uid'] == $rootLine[$i]['uid']) {
$this->pObj->devLog('Found rootline', array('uid' => $id, 'rootline start pid' => $rootLine[$i]['uid']));
$rootFound = true;
for ( ; $i < $numberOfRootlineEntries; $i++) {
$newRootLine[] = $rootLine[$i];
}
break;
}
}
}
if ($rootFound) {
// Translate the rootline to a valid path (rootline contains localized titles at this point!)
$pagePath = $this->rootLineToPath($newRootLine, $langID);
$this->pObj->devLog('Got page path', array('uid' => $id, 'pagepath' => $pagePath));
$rootPageId = $this->conf['rootpage_id'];
if ($innerSubDomain) {
$parts = parse_url($pagePath);
$this->pObj->devLog('$innerSubDomain=true, showing page path parts', $parts);
if ($parts['host'] == '') {
foreach ($newRootLine as $rl) {
/** @noinspection PhpUndefinedMethodInspection */
$rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('domainName', 'sys_domain', 'pid=' . $rl['uid'] . ' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
if (count($rows)) {
$domain = $rows[0]['domainName'];
$this->pObj->devLog('Found domain', $domain);
$rootPageId = $rl['uid'];
}
}
}
}
$result = array(
'pagepath' => $pagePath,
'langID' => intval($langID),
'rootpage_id' => intval($rootPageId),
);
}
return $result;
}
/**
* Build a virtual path for a page, like "products/product_1/features/"
* The path is language dependant.
* There is also a function $TSFE->sysPage->getPathFromRootline, but that one can only be used for a visual
* indication of the path in the backend, not for a real page path.
* Note also that the for-loop starts with 1 so the first page is stripped off. This is (in most cases) the
* root of the website (which is 'handled' by the domainname).
*
* @param array $rl Rootline array for the current website (rootLine from TSFE->tmpl->rootLine but with modified localization according to language of the URL)
* @param int $lang Language identifier (as in sys_languages)
* @return string Path for the page, eg.
* @see IDtoPagePathSegments()
*/
protected function rootLineToPath($rl, $lang) {
$paths = array();
array_shift($rl); // Ignore the first path, as this is the root of the website
$c = count($rl);
$stopUsingCache = false;
$this->pObj->devLog('rootLineToPath starts searching', array('rootline size' => count($rl)));
for ($i = 1; $i <= $c; $i++) {
$page = array_shift($rl);
// First, check for cached path of this page
$cachedPagePath = false;
if (!$page['tx_realurl_exclude'] && !$stopUsingCache && !$this->conf['disablePathCache']) {
// Using pathq2 index!
/** @noinspection PhpUndefinedMethodInspection */
list($cachedPagePath) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('pagepath', 'tx_realurl_pathcache',
'page_id=' . intval($page['uid']) .
' AND language_id=' . intval($lang) .
' AND rootpage_id=' . intval($this->conf['rootpage_id']) .
' AND mpvar=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($page['_MP_PARAM'], 'tx_realurl_pathcache') .
' AND expire=0', '', '', 1);
if (is_array($cachedPagePath)) {
$lastPath = implode('/', $paths);
$this->pObj->devLog('rootLineToPath found path', $lastPath);
if ($cachedPagePath != false && substr($cachedPagePath['pagepath'], 0, strlen($lastPath)) != $lastPath) {
// Oops. Cached path does not start from already generated path.
// It means that path was mapped from a parallel mount point.
// We cannot not rely on cache any more. Stop using it.
$cachedPagePath = false;
$stopUsingCache = true;
$this->pObj->devLog('rootLineToPath stops searching');
}
}
}
// If a cached path was found for the page it will be inserted as the base of the new path, overriding anything build prior to this
if ($cachedPagePath) {
$paths = array();
$paths[$i] = $cachedPagePath['pagepath'];
}
else {
// Building up the path from page title etc.
if (!$page['tx_realurl_exclude'] || count($rl) == 0) {
// List of "pages" fields to traverse for a "directory title" in the speaking URL (only from RootLine!!)
$segTitleFieldArray = $this->apiWrapper->trimExplode(',', $this->conf['segTitleFieldList'] ? $this->conf['segTitleFieldList'] : TX_REALURL_SEGTITLEFIELDLIST_DEFAULT, 1);
$theTitle = '';
foreach ($segTitleFieldArray as $fieldName) {
if ($page[$fieldName]) {
$theTitle = $page[$fieldName];
break;
}
}
$paths[$i] = $this->encodeTitle($theTitle);
}
}
}
return implode('/', $paths);
}
/*******************************
*
* URL-to-ID methods
*
******************************/
/**
* Convert a page path to an ID.
*
* @param array $pathParts Array of segments from virtual path
* @return integer Page ID
* @see decodeSpURL_idFromPath()
*/
protected function pagePathtoID(&$pathParts) {
$row = $postVar = false;
$copy_pathParts = array();
// If pagePath cache is not disabled, look for entry
if (!$this->conf['disablePathCache']) {
// Work from outside-in to look up path in cache
$postVar = false;
$copy_pathParts = $pathParts;
$charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : $GLOBALS['TSFE']->defaultCharSet;
foreach ($copy_pathParts as $key => $value) {
$copy_pathParts[$key] = $GLOBALS['TSFE']->csConvObj->conv_case($charset, $value, 'toLower');
}
while (count($copy_pathParts)) {
// Using pathq1 index!
/** @noinspection PhpUndefinedMethodInspection */
list($row) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
'tx_realurl_pathcache.*', 'tx_realurl_pathcache,pages',
'tx_realurl_pathcache.page_id=pages.uid AND pages.deleted=0' .
' AND rootpage_id=' . intval($this->conf['rootpage_id']) .
' AND pagepath=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(implode('/', $copy_pathParts), 'tx_realurl_pathcache'),
'', 'expire', '1');
// This lookup does not include language and MP var since those are supposed to be fully reflected in the built url!
if (is_array($row)) {
break;
}
// If no row was found, we simply pop off one element of the path and try again until there are no more elements in the array - which means we didn't find a match!
$postVar = array_pop($copy_pathParts);
}
}
// It could be that entry point to a page but it is not in the cache. If we popped
// any items from path parts, we need to check if they are defined as postSetVars or
// fixedPostVars on this page. This does not guarantie 100% success. For example,
// if path to page is /hello/world/how/are/you and hello/world found in cache and
// there is a postVar 'how' on this page, the check below will not work. But it is still
// better than nothing.
if ($row && $postVar) {
$postVars = $this->pObj->getPostVarSetConfig($row['page_id'], 'postVarSets');
if (!is_array($postVars) || !isset($postVars[$postVar])) {
// Check fixed
$postVars = $this->pObj->getPostVarSetConfig($row['page_id'], 'fixedPostVars');
if (!is_array($postVars) || !isset($postVars[$postVar])) {
// Not a postVar, so page most likely in not in cache. Clear row.
// TODO It would be great to update cache in this case but usually TYPO3 is not
// complitely initialized at this place. So we do not do it...
$row = false;
}
}
}
// Process row if found
if ($row) { // We found it in the cache
// Check for expiration. We can get one of three
// 1. expire = 0
// 2. expire <= time()
// 3. expire > time()
// 1 is permanent, we do not process it. 2 is expired, we look for permanent or non-expired
// (in this order!) entry for the same page od and redirect to corresponding path. 3 - same as
// 1 but means that entry is going to expire eventually, nothing to do for us yet.
if ($row['expire'] > 0) {
$this->pObj->devLog('pagePathToId found row', $row);
// 'expire' in the query is only for logging
// Using pathq2 index!
/** @noinspection PhpUndefinedMethodInspection */
list($newEntry) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('pagepath,expire', 'tx_realurl_pathcache',
'page_id=' . intval($row['page_id']) . '
AND language_id=' . intval($row['language_id']) . '
AND (expire=0 OR expire>' . $row['expire'] . ')', '', 'expire', '1');
$this->pObj->devLog('pagePathToId searched for new entry', $newEntry);
// Redirect to new path immediately if it is found
if ($newEntry) {
// Replace path-segments with new ones
$originalDirs = $this->pObj->dirParts; // All original
$cp_pathParts = $pathParts;
// Popping of pages of original dirs (as many as are remaining in $pathParts)
for ($a = 0; $a < count($pathParts); $a++) {
array_pop($originalDirs); // Finding all preVars here
}
for ($a = 0; $a < count($copy_pathParts); $a++) {
array_shift($cp_pathParts); // Finding all postVars here
}
$newPathSegments = explode('/', $newEntry['pagepath']); // Split new pagepath into segments.
$newUrlSegments = array_merge($originalDirs, $newPathSegments, $cp_pathParts); // Merge those segments.
$this->pObj->appendFilePart($newUrlSegments);
$redirectUrl = implode('/', $newUrlSegments);
header('HTTP/1.1 301 TYPO3 RealURL Redirect A' . __LINE__);
header('Location: ' . $this->apiWrapper->locationHeaderUrl($redirectUrl));
exit();
}
$this->pObj->disableDecodeCache = true; // Do not cache this!
}
// Unshift the number of segments that must have defined the page
$cc = count($copy_pathParts);
for ($a = 0; $a < $cc; $a++) {
array_shift($pathParts);
}
// Assume we can use this info at first
$id = $row['page_id'];
$GET_VARS = $row['mpvar'] ? array('MP' => $row['mpvar']) : '';
}
else {
// Find it
list($id, $GET_VARS) = $this->findIDByURL($pathParts);
}
// Return found ID
return array($id, $GET_VARS);
}
/**
* Search recursively for the URL in the page tree and return the ID of the path ("manual" id resolve)
*
* @param array $urlParts Path parts, passed by reference.
* @return array Info array, currently with "id" set to the ID.
*/
protected function findIDByURL(array &$urlParts) {
$id = 0;
$GET_VARS = '';
$startPid = $this->getRootPid();
if ($startPid && count($urlParts)) {
list($id) = $this->findIDByPathOverride($startPid, $urlParts);
if ($id != 0) {
$startPid = $id;
}
list($id, $mpvar) = $this->findIDBySegment($startPid, '', $urlParts);
if ($mpvar) {
$GET_VARS = array('MP' => $mpvar);
}
}
return array(intval($id), $GET_VARS);
}
/**
* Obtains root page id for the current request.
*
* @return int
*/
protected function getRootPid() {
if ($this->conf['rootpage_id']) { // Take PID from rootpage_id if any:
$startPid = intval($this->conf['rootpage_id']);
}
else {
$startPid = $this->pObj->findRootPageId();
}
return intval($startPid);
}
/**
* Attempts to find the page inside the root page that has a path override
* that fits into the passed segments.
*
* @param int $rootPid
* @param array $urlParts
* @return array Key 0 is pid (or 0), key 2 is empty string
*/
protected function findIDByPathOverride($rootPid, array &$urlParts) {
$pageInfo = array(0, '');
$extraUrlSegments = array();
while (count($urlParts) > 0) {
// Search for the path inside the root page
$url = implode('/', $urlParts);
$pageInfo = $this->findPageByPath($rootPid, $url);
if ($pageInfo[0]) {
break;
}
// Not found, try smaller segment
array_unshift($extraUrlSegments, array_pop($urlParts));
}
$urlParts = $extraUrlSegments;
return $pageInfo;
}
/**
* Attempts to find the page inside the root page that has the given path.
*
* @param int $rootPid
* @param string $url
* @return array Key 0 is pid (or 0), key 2 is empty string
*/
protected function findPageByPath($rootPid, $url) {
$pages = $this->fetchPagesForPath($url);
foreach ($pages as $key => $page) {
if (!$this->isAnyChildOf($page['pid'], $rootPid)) {
unset($pages[$key]);
}
}
if (count($pages) > 1) {
$idList = array();
foreach ($pages as $page) {
$idList[] = $page['uid'];
}
// No need for hsc() because TSFE does that
$this->pObj->decodeSpURL_throw404(sprintf(
'Multiple pages exist for path "%s": %s',
$url, implode(', ', $idList)));
}
reset($pages);
$page = current($pages);
return array($page['uid'], '');
}
/**
* Checks if the the page is any child of the root page.
*
* @param int $pid
* @param int $rootPid
* @return boolean
*/
protected function isAnyChildOf($pid, $rootPid) {
$this->createSysPageIfNecessary();
$rootLine = $this->sysPage->getRootLine($pid);
foreach ($rootLine as $page) {
if ($page['uid'] == $rootPid) {
return true;
}
}
return false;
}
/**
* Fetches a list of pages (uid,pid) for path. The priority of search is:
* - pages
* - pages_language_overlay
*
* @param string $url
* @return array
*/
protected function fetchPagesForPath($url) {
$pages = array();
$language = intval($this->pObj->getDetectedLanguage());
if ($language > 0) {
/** @noinspection PhpUndefinedMethodInspection */
$pagesOverlay = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('t1.pid',
'pages_language_overlay t1, pages t2',
't1.hidden=0 AND t1.deleted=0 AND ' .
't2.hidden=0 AND t2.deleted=0 AND ' .
't1.pid=t2.uid AND ' .
't2.tx_realurl_pathoverride=1 AND ' .
't1.sys_language_uid=' . $language . ' AND ' .
't1.tx_realurl_pathsegment=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($url, 'pages_language_overlay'),
'', '', '', 'pid'
);
if (count($pagesOverlay) > 0) {
/** @noinspection PhpUndefinedMethodInspection */
$pages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,pid', 'pages',
'hidden=0 AND deleted=0 AND uid IN (' . implode(',', array_keys($pagesOverlay)) . ')',
'', '', '', 'uid');
}
}
// $pages has strings as keys. Therefore array_merge will ensure uniqueness.
// Selection from 'pages' table will override selection from
// pages_language_overlay.
/** @noinspection PhpUndefinedMethodInspection */
$pages2 = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,pid', 'pages',
'hidden=0 AND deleted=0 AND tx_realurl_pathoverride=1 AND tx_realurl_pathsegment=' .
$GLOBALS['TYPO3_DB']->fullQuoteStr($url, 'pages'),
'', '', '', 'uid');
if (count($pages2)) {
$pages = $pages + $pages2;
}
return $pages;
}
/**
* Recursively search the subpages of $pid for the first part of $urlParts
*
* @param int $startPid Page id in which to search subpages matching first part of urlParts
* @param string $mpvar MP variable string
* @param array $urlParts Segments of the virtual path (passed by reference; items removed)
* @param array|string $currentIdMp Array with the current pid/mpvar to return if no processing is done.
* @param bool $foundUID
* @return array With resolved id and $mpvar
*/
protected function findIDBySegment($startPid, $mpvar, array &$urlParts, $currentIdMp = '', $foundUID = false) {
// Creating currentIdMp variable if not set
if (!is_array($currentIdMp)) {
$currentIdMp = array($startPid, $mpvar, $foundUID);
}
// No more urlparts? Return what we have.
if (count($urlParts) == 0) {
return $currentIdMp;
}
// Get the title we need to find now
$segment = array_shift($urlParts);
// Perform search
list($uid, $row, $exclude, $possibleMatch) = $this->findPageBySegmentAndPid($startPid, $segment);
// If a title was found...
if ($uid) {
return $this->processFoundPage($row, $mpvar, $urlParts, true);
}
elseif (count($exclude)) {
// There were excluded pages, we have to process those!
foreach ($exclude as $row) {
$urlPartsCopy = $urlParts;
array_unshift($urlPartsCopy, $segment);
$result = $this->processFoundPage($row, $mpvar, $urlPartsCopy, false);
if ($result[2]) {
$urlParts = $urlPartsCopy;
return $result;
}
}
}
// the possible "exclude in URL segment" match must be checked if no other results in
// deeper tree branches were found, because we want to access this page also
// + Books <-- excluded in URL (= possibleMatch)
// - TYPO3
// - ExtJS
if (count($possibleMatch) > 0) {
return $this->processFoundPage($possibleMatch, $mpvar, $urlParts, true);
}
// No title, so we reached the end of the id identifying part of the path and now put back the current non-matched title segment before we return the PID
array_unshift($urlParts, $segment);
return $currentIdMp;
}
/**
* Process title search result. This is executed both when title is found and
* when excluded segment is found
*
* @param array $row Row to process
* @param array $mpvar MP var
* @param array $urlParts URL segments
* @param bool $foundUID
* @return array Resolved id and mpvar
* @see findPageBySegment()
*/
protected function processFoundPage($row, $mpvar, array &$urlParts, $foundUID) {
$uid = $row['uid'];