xref: /plugin/combo/action/router.php (revision 94daa629a8cbc1668b3d4ff7a6baae15b68cf430)
1<?php
2
3
4use ComboStrap\DatabasePageRow;
5use ComboStrap\DokuwikiId;
6use ComboStrap\ExceptionBadArgument;
7use ComboStrap\ExceptionBadSyntax;
8use ComboStrap\ExceptionCompile;
9use ComboStrap\ExceptionSqliteNotAvailable;
10use ComboStrap\ExecutionContext;
11use ComboStrap\FileSystems;
12use ComboStrap\HttpResponse;
13use ComboStrap\HttpResponseStatus;
14use ComboStrap\Identity;
15use ComboStrap\LogUtility;
16use ComboStrap\MarkupPath;
17use ComboStrap\Meta\Field\AliasType;
18use ComboStrap\Mime;
19use ComboStrap\PageId;
20use ComboStrap\PageRules;
21use ComboStrap\PageUrlPath;
22use ComboStrap\PageUrlType;
23use ComboStrap\RouterBestEndPage;
24use ComboStrap\Site;
25use ComboStrap\SiteConfig;
26use ComboStrap\Sqlite;
27use ComboStrap\Web\Url;
28use ComboStrap\Web\UrlEndpoint;
29use ComboStrap\Web\UrlRewrite;
30use ComboStrap\WikiPath;
31
32require_once(__DIR__ . '/../vendor/autoload.php');
33
34/**
35 * Class action_plugin_combo_url
36 *
37 * The actual URL manager
38 *
39 *
40 */
41class action_plugin_combo_router extends DokuWiki_Action_Plugin
42{
43
44    /**
45     * @deprecated
46     */
47    const URL_MANAGER_ENABLE_CONF = "enableUrlManager";
48    const ROUTER_ENABLE_CONF = "enableRouter";
49
50    // The redirect type
51    const REDIRECT_TRANSPARENT_METHOD = 'transparent'; // was (Id)
52    // For permanent, see https://developers.google.com/search/docs/advanced/crawling/301-redirects
53    const REDIRECT_PERMANENT_METHOD = 'permanent'; // was `Http` (301)
54    const REDIRECT_NOTFOUND_METHOD = "notfound"; // 404 (See other) (when best page name is calculated)
55
56    public const PERMANENT_REDIRECT_CANONICAL = "permanent:redirect";
57
58    // Where the target id value comes from
59    const TARGET_ORIGIN_WELL_KNOWN = 'well-known';
60    const TARGET_ORIGIN_PAGE_RULES = 'pageRules';
61    /**
62     * Named Permalink (canonical)
63     */
64    const TARGET_ORIGIN_CANONICAL = 'canonical';
65    const TARGET_ORIGIN_ALIAS = 'alias';
66    /**
67     * Identifier Permalink (full page id)
68     */
69    const TARGET_ORIGIN_PERMALINK = "permalink";
70    /**
71     * Extended Permalink (abbreviated page id at the end)
72     */
73    const TARGET_ORIGIN_PERMALINK_EXTENDED = "extendedPermalink";
74    const TARGET_ORIGIN_START_PAGE = 'startPage';
75    const TARGET_ORIGIN_BEST_PAGE_NAME = 'bestPageName';
76    const TARGET_ORIGIN_BEST_NAMESPACE = 'bestNamespace';
77    const TARGET_ORIGIN_SEARCH_ENGINE = 'searchEngine';
78    const TARGET_ORIGIN_BEST_END_PAGE_NAME = 'bestEndPageName';
79    const TARGET_ORIGIN_SHADOW_BANNED = "shadowBanned";
80
81
82    // The constant parameters
83    const GO_TO_SEARCH_ENGINE = 'GoToSearchEngine';
84    const GO_TO_BEST_NAMESPACE = 'GoToBestNamespace';
85    const GO_TO_BEST_PAGE_NAME = 'GoToBestPageName';
86    const GO_TO_BEST_END_PAGE_NAME = 'GoToBestEndPageName';
87    const GO_TO_NS_START_PAGE = 'GoToNsStartPage';
88    const GO_TO_EDIT_MODE = 'GoToEditMode';
89    const NOTHING = 'Nothing';
90
91    /** @var string - a name used in log and other places */
92    const NAME = 'Url Manager';
93    const CANONICAL = 'router';
94    const PAGE_404 = "<html lang=\"en\"><body></body></html>";
95    const REFRESH_HEADER_NAME = "Refresh";
96    const REFRESH_HEADER_PREFIX = self::REFRESH_HEADER_NAME . ': 0;url=';
97    const LOCATION_HEADER_PREFIX = HttpResponse::LOCATION_HEADER_NAME . ": ";
98    public const URL_MANAGER_NAME = "Router";
99
100
101    /**
102     * @var PageRules
103     */
104    private $pageRules;
105
106
107    function __construct()
108    {
109        // enable direct access to language strings
110        // ie $this->lang
111        $this->setupLocale();
112
113    }
114
115    /**
116     * @param string $refreshHeader
117     * @return false|string
118     */
119    public static function getUrlFromRefresh(string $refreshHeader)
120    {
121        return substr($refreshHeader, strlen(action_plugin_combo_router::REFRESH_HEADER_PREFIX));
122    }
123
124    public static function getUrlFromLocation($refreshHeader)
125    {
126        return substr($refreshHeader, strlen(action_plugin_combo_router::LOCATION_HEADER_PREFIX));
127    }
128
129    /**
130     * @return string|null
131     *
132     * Return the original id from the request
133     * ie `howto:how-to-get-started-with-combostrap-m3i8vga8`
134     * if `/howto/how-to-get-started-with-combostrap-m3i8vga8`
135     *
136     * Unfortunately, DOKUWIKI_STARTED is not the first event
137     * The id may have been changed by
138     * {@link action_plugin_combo_lang::load_lang()}
139     * function, that's why we have this function
140     * to get the original requested id
141     */
142    private static function getOriginalIdFromRequest(): ?string
143    {
144        $originalId = $_GET["id"] ?? null;
145        if ($originalId === null) {
146            return null;
147        }
148        // We get a `/` as first character
149        // because we return an id, we need to delete it
150        $originalId = substr($originalId,1);
151        // transform / to :
152        return str_replace("/", WikiPath::NAMESPACE_SEPARATOR_DOUBLE_POINT, $originalId);
153    }
154
155    /**
156     * Determine if the request should be banned based on the id
157     *
158     * @param string $id
159     * @return bool
160     *
161     * See also {@link https://perishablepress.com/7g-firewall/#features}
162     * for blocking rules on http request data such as:
163     *   * query_string
164     *   * user_agent,
165     *   * remote host
166     */
167    public static function isShadowBanned(string $id): bool
168    {
169        /**
170         * ie
171         * wp-json:api:flutter_woo:config_file
172         * wp-content:plugins:wpdiscuz:themes:default:style-rtl.css
173         * wp-admin
174         * 2020:wp-includes:wlwmanifest.xml
175         * wp-content:start
176         * wp-admin:css:start
177         * sito:wp-includes:wlwmanifest.xml
178         * site:wp-includes:wlwmanifest.xml
179         * cms:wp-includes:wlwmanifest.xml
180         * test:wp-includes:wlwmanifest.xml
181         * media:wp-includes:wlwmanifest.xml
182         * wp2:wp-includes:wlwmanifest.xml
183         * 2019:wp-includes:wlwmanifest.xml
184         * shop:wp-includes:wlwmanifest.xml
185         * wp1:wp-includes:wlwmanifest.xml
186         * news:wp-includes:wlwmanifest.xml
187         * 2018:wp-includes:wlwmanifest.xml
188         */
189        if (strpos($id, 'wp-') !== false) {
190            return true;
191        }
192
193        /**
194         * db:oracle:long_or_1_utl_inaddr.get_host_address_chr_33_chr_126_chr_33_chr_65_chr_66_chr_67_chr_49_chr_52_chr_53_chr_90_chr_81_chr_54_chr_50_chr_68_chr_87_chr_81_chr_65_chr_70_chr_80_chr_79_chr_73_chr_89_chr_67_chr_70_chr_68_chr_33_chr_126_chr_33
195         * db:oracle:999999.9:union:all:select_null:from_dual
196         * db:oracle:999999.9:union:all:select_null:from_dual_and_0_0
197         */
198        if (preg_match('/_chr_|_0_0/', $id) === 1) {
199            return true;
200        }
201
202
203        /**
204         * ie
205         * git:objects:
206         * git:refs:heads:stable
207         * git:logs:refs:heads:main
208         * git:logs:refs:heads:stable
209         * git:hooks:pre-push.sample
210         * git:hooks:pre-receive.sample
211         */
212        if (strpos($id, "git:") === 0) {
213            return true;
214        }
215
216        return false;
217
218    }
219
220    /**
221     * @param string $id
222     * @return bool
223     * well-known:traffic-advice = https://github.com/buettner/private-prefetch-proxy/blob/main/traffic-advice.md
224     * .well-known/security.txt, id=well-known:security.txt = https://securitytxt.org/
225     * well-known:dnt-policy.txt
226     */
227    public static function isWellKnownFile(string $id): bool
228    {
229        return strpos($id, "well-known") === 0;
230    }
231
232
233    function register(Doku_Event_Handler $controller)
234    {
235
236        if (SiteConfig::getConfValue(self::ROUTER_ENABLE_CONF, 1)) {
237
238            /**
239             * This will call the function {@link action_plugin_combo_router::_router()}
240             * The event is not DOKUWIKI_STARTED because this is not the first one
241             *
242             * https://www.dokuwiki.org/devel:event:init_lang_load
243             */
244            $controller->register_hook('DOKUWIKI_STARTED',
245                'BEFORE',
246                $this,
247                'router',
248                array());
249
250            /**
251             * This is the real first call of Dokuwiki
252             * Unfortunately, it does not create the environment
253             * We just ban to spare server resources
254             *
255             * https://www.dokuwiki.org/devel:event:init_lang_load
256             */
257            $controller->register_hook('INIT_LANG_LOAD', 'BEFORE', $this, 'ban', array());
258
259        }
260
261
262    }
263
264    /**
265     *
266     * We have created a spacial ban function that is
267     * called before the first function
268     * {@link action_plugin_combo_metalang::load_lang()}
269     * to spare CPU.
270     *
271     * @param $event
272     * @throws Exception
273     */
274    function ban(&$event)
275    {
276
277        $id = self::getOriginalIdFromRequest();
278        if ($id === null) {
279            return;
280        }
281        $page = MarkupPath::createMarkupFromId($id);
282        if (!FileSystems::exists($page)) {
283            // Well known
284            if (self::isWellKnownFile($id)) {
285                $this->logRedirection($id, "", self::TARGET_ORIGIN_WELL_KNOWN, self::REDIRECT_NOTFOUND_METHOD);
286                ExecutionContext::getActualOrCreateFromEnv()
287                    ->response()
288                    ->setStatus(HttpResponseStatus::NOT_FOUND)
289                    ->end();
290                return;
291            }
292
293            // Shadow banned
294            if (self::isShadowBanned($id)) {
295                $webSiteHomePage = Site::getIndexPageName();
296                $this->executeTransparentRedirect($webSiteHomePage, self::TARGET_ORIGIN_SHADOW_BANNED);
297            }
298        }
299    }
300
301    /**
302     * @param $event Doku_Event
303     * @param $param
304     * @return void
305     * @throws Exception
306     */
307    function router(&$event, $param)
308    {
309
310        /**
311         * Just the {@link ExecutionContext::SHOW_ACTION}
312         * may be redirected
313         */
314        $executionContext = ExecutionContext::getActualOrCreateFromEnv();
315        if ($executionContext->getExecutingAction() !== ExecutionContext::SHOW_ACTION) {
316            return;
317        }
318
319        $urlRewrite = Site::getUrlRewrite();
320        if ($urlRewrite == UrlRewrite::VALUE_DOKU_REWRITE) {
321            UrlRewrite::sendErrorMessage();
322            return;
323        }
324
325        global $ID;
326
327        /**
328         * Without SQLite, this module does not work further
329         */
330        try {
331            Sqlite::createOrGetSqlite();
332        } catch (ExceptionSqliteNotAvailable $e) {
333            return;
334        }
335
336        $this->pageRules = new PageRules();
337
338
339        /**
340         * Unfortunately, DOKUWIKI_STARTED is not the first event
341         * The id may have been changed by
342         * {@link action_plugin_combo_lang::load_lang()}
343         * function, that's why we check against the {@link $_REQUEST}
344         * and not the global ID
345         */
346        $originalId = self::getOriginalIdFromRequest();
347
348        /**
349         * Page is an existing id ?
350         */
351        $requestedMarkupPath = MarkupPath::createMarkupFromId($ID);
352        if (FileSystems::exists($requestedMarkupPath)) {
353
354            /**
355             * If this is not the root home page
356             * and if the canonical id is the not the same (the id has changed)
357             * and if this is not a historical page (revision)
358             * redirect
359             */
360            if (
361                $originalId !== $requestedMarkupPath->getUrlId() // The id may have been changed
362                && $ID != Site::getIndexPageName()
363                && !isset($_REQUEST["rev"])
364            ) {
365                /**
366                 * TODO: When saving for the first time, the page is not stored in the database
367                 *   but that's not the case actually
368                 */
369                $databasePageRow = $requestedMarkupPath->getDatabasePage();
370                if ($databasePageRow->exists()) {
371                    /**
372                     * A move may leave the database in a bad state,
373                     * unfortunately (ie page is not in index, unable to update, ...)
374                     * We test therefore if the database page id exists
375                     */
376                    $targetPageId = $databasePageRow->getFromRow("id");
377                    $targetPath = WikiPath::createMarkupPathFromId($targetPageId);
378                    if (FileSystems::exists($targetPath)) {
379                        $this->executePermanentRedirect(
380                            $requestedMarkupPath->getCanonicalUrl()->toAbsoluteUrlString(),
381                            self::TARGET_ORIGIN_PERMALINK_EXTENDED
382                        );
383                    }
384                }
385            }
386            return;
387        }
388
389
390        $identifier = $ID;
391
392
393        /**
394         * Page Id in the url
395         */
396        $shortPageId = PageUrlPath::getShortEncodedPageIdFromUrlId($requestedMarkupPath->getPathObject()->getLastNameWithoutExtension());
397        if ($shortPageId != null) {
398            $pageId = PageUrlPath::decodePageId($shortPageId);
399        } else {
400            /**
401             * Permalink with id
402             */
403            $pageId = PageUrlPath::decodePageId($identifier);
404        }
405        if ($pageId !== null) {
406
407            if ($requestedMarkupPath->getParent() === null) {
408                $page = DatabasePageRow::createFromPageId($pageId)->getMarkupPath();
409                if ($page !== null && $page->exists()) {
410                    $this->executePermanentRedirect(
411                        $page->getCanonicalUrl()->toAbsoluteUrlString(),
412                        self::TARGET_ORIGIN_PERMALINK
413                    );
414                    return;
415                }
416            }
417
418            /**
419             * Page Id Abbr ?
420             * {@link PageUrlType::CONF_CANONICAL_URL_TYPE}
421             */
422            $page = DatabasePageRow::createFromPageIdAbbr($pageId)->getMarkupPath();
423            if ($page === null) {
424                // or the length of the abbr has changed
425                $canonicalDatabasePage = new DatabasePageRow();
426                $row = $canonicalDatabasePage->getDatabaseRowFromAttribute("substr(" . PageId::PROPERTY_NAME . ", 1, " . strlen($pageId) . ")", $pageId);
427                if ($row !== null) {
428                    $canonicalDatabasePage->setRow($row);
429                    $page = $canonicalDatabasePage->getMarkupPath();
430                }
431            }
432            if ($page !== null && $page->exists()) {
433                /**
434                 * If the url canonical id has changed, we show it
435                 * to the writer by performing a permanent redirect
436                 */
437                if ($identifier != $page->getUrlId()) {
438                    // Google asks for a redirect
439                    // https://developers.google.com/search/docs/advanced/crawling/301-redirects
440                    // People access your site through several different URLs.
441                    // If, for example, your home page can be reached in multiple ways
442                    // (for instance, http://example.com/home, http://home.example.com, or http://www.example.com),
443                    // it's a good idea to pick one of those URLs as your preferred (canonical) destination,
444                    // and use redirects to send traffic from the other URLs to your preferred URL.
445                    $this->executePermanentRedirect(
446                        $page->getCanonicalUrl()->toAbsoluteUrlString(),
447                        self::TARGET_ORIGIN_PERMALINK_EXTENDED
448                    );
449                    return;
450                }
451
452                $this->executeTransparentRedirect($page->getWikiId(), self::TARGET_ORIGIN_PERMALINK_EXTENDED);
453                return;
454
455            }
456            // permanent url not yet in the database
457            // Other permanent such as permanent canonical ?
458            // We let the process go with the new identifier
459
460        }
461
462        // Global variable needed in the process
463        global $conf;
464
465        /**
466         * Identifier is a Canonical ?
467         */
468        $canonicalDatabasePage = DatabasePageRow::createFromCanonical($identifier);
469        $canonicalPage = $canonicalDatabasePage->getMarkupPath();
470        if ($canonicalPage !== null && $canonicalPage->exists()) {
471            /**
472             * Does the canonical url is canonical name based
473             * ie {@link  PageUrlType::CONF_VALUE_CANONICAL_PATH}
474             */
475            if ($canonicalPage->getUrlId() === $identifier) {
476                $res = $this->executeTransparentRedirect(
477                    $canonicalPage->getWikiId(),
478                    self::TARGET_ORIGIN_CANONICAL
479                );
480            } else {
481                $res = $this->executePermanentRedirect(
482                    $canonicalPage->getWikiId(), // not the url because, it allows to add url query redirection property
483                    self::TARGET_ORIGIN_CANONICAL
484                );
485            }
486            if ($res) {
487                return;
488            }
489        }
490
491        /**
492         * Identifier is an alias
493         */
494        $aliasRequestedPage = DatabasePageRow::createFromAlias($identifier)->getMarkupPath();
495        if (
496            $aliasRequestedPage !== null
497            && $aliasRequestedPage->exists()
498            // The build alias is the file system metadata alias
499            // it may be null if the replication in the database was not successful
500            && $aliasRequestedPage->getBuildAlias() !== null
501        ) {
502            $buildAlias = $aliasRequestedPage->getBuildAlias();
503            switch ($buildAlias->getType()) {
504                case AliasType::REDIRECT:
505                    $res = $this->executePermanentRedirect($aliasRequestedPage->getCanonicalUrl()->toAbsoluteUrlString(), self::TARGET_ORIGIN_ALIAS);
506                    if ($res) {
507                        return;
508                    }
509                    break;
510                case AliasType::SYNONYM:
511                    $res = $this->executeTransparentRedirect($aliasRequestedPage->getWikiId(), self::TARGET_ORIGIN_ALIAS);
512                    if ($res) {
513                        return;
514                    }
515                    break;
516                default:
517                    LogUtility::msg("The alias type ({$buildAlias->getType()}) is unknown. A permanent redirect was performed for the alias $identifier");
518                    $res = $this->executePermanentRedirect($aliasRequestedPage->getCanonicalUrl()->toAbsoluteUrlString(), self::TARGET_ORIGIN_ALIAS);
519                    if ($res) {
520                        return;
521                    }
522                    break;
523            }
524        }
525
526
527        // If there is a redirection defined in the page rules
528        $result = $this->processingPageRules();
529        if ($result) {
530            // A redirection has occurred
531            // finish the process
532            return;
533        }
534
535        /**
536         *
537         * There was no redirection found, redirect to edit mode if writer
538         *
539         */
540        if (Identity::isWriter() && $this->getConf(self::GO_TO_EDIT_MODE) == 1) {
541
542            $this->gotToEditMode($event);
543            // Stop here
544            return;
545
546        }
547
548        /**
549         *  We are still a reader, the redirection does not exist the user is not allowed to edit the page (public of other)
550         */
551        if ($this->getConf('ActionReaderFirst') == self::NOTHING) {
552            return;
553        }
554
555        // We are reader and their is no redirection set, we apply the algorithm
556        $readerAlgorithms = array();
557        $readerAlgorithms[0] = $this->getConf('ActionReaderFirst');
558        $readerAlgorithms[1] = $this->getConf('ActionReaderSecond');
559        $readerAlgorithms[2] = $this->getConf('ActionReaderThird');
560
561        while (
562            ($algorithm = array_shift($readerAlgorithms)) != null
563        ) {
564
565            switch ($algorithm) {
566
567                case self::NOTHING:
568                    return;
569
570                case self::GO_TO_BEST_END_PAGE_NAME:
571
572                    /**
573                     * @var MarkupPath $bestEndPage
574                     */
575                    list($bestEndPage, $method) = RouterBestEndPage::process($requestedMarkupPath);
576                    if ($bestEndPage != null && $bestEndPage->getWikiId() !== $requestedMarkupPath->getWikiId()) {
577                        $res = false;
578                        switch ($method) {
579                            case self::REDIRECT_PERMANENT_METHOD:
580                                $res = $this->executePermanentRedirect($bestEndPage->getWikiId(), self::TARGET_ORIGIN_BEST_END_PAGE_NAME);
581                                break;
582                            case self::REDIRECT_NOTFOUND_METHOD:
583                                $res = $this->performNotFoundRedirect($bestEndPage->getWikiId(), self::TARGET_ORIGIN_BEST_END_PAGE_NAME);
584                                break;
585                            default:
586                                LogUtility::msg("This redirection method ($method) was not expected for the redirection algorithm ($algorithm)");
587                        }
588                        if ($res) {
589                            // Redirection has succeeded
590                            return;
591                        }
592                    }
593                    break;
594
595                case self::GO_TO_NS_START_PAGE:
596
597                    // Start page with the conf['start'] parameter
598                    $startPage = getNS($identifier) . ':' . $conf['start'];
599                    if (page_exists($startPage)) {
600                        $res = $this->performNotFoundRedirect($startPage, self::TARGET_ORIGIN_START_PAGE);
601                        if ($res) {
602                            return;
603                        }
604                    }
605
606                    // Start page with the same name than the namespace
607                    $startPage = getNS($identifier) . ':' . curNS($identifier);
608                    if (page_exists($startPage)) {
609                        $res = $this->performNotFoundRedirect($startPage, self::TARGET_ORIGIN_START_PAGE);
610                        if ($res) {
611                            return;
612                        }
613                    }
614                    break;
615
616                case self::GO_TO_BEST_PAGE_NAME:
617
618                    $bestPageId = null;
619
620                    $bestPage = $this->getBestPage($identifier);
621                    $bestPageId = $bestPage['id'];
622                    $scorePageName = $bestPage['score'];
623
624                    // Get Score from a Namespace
625                    $bestNamespace = $this->scoreBestNamespace($identifier);
626                    $bestNamespaceId = $bestNamespace['namespace'];
627                    $namespaceScore = $bestNamespace['score'];
628
629                    // Compare the two score
630                    if ($scorePageName > 0 or $namespaceScore > 0) {
631                        if ($scorePageName > $namespaceScore) {
632                            $this->performNotFoundRedirect($bestPageId, self::TARGET_ORIGIN_BEST_PAGE_NAME);
633                        } else {
634                            $this->performNotFoundRedirect($bestNamespaceId, self::TARGET_ORIGIN_BEST_PAGE_NAME);
635                        }
636                        return;
637                    }
638                    break;
639
640                case self::GO_TO_BEST_NAMESPACE:
641
642                    $scoreNamespace = $this->scoreBestNamespace($identifier);
643                    $bestNamespaceId = $scoreNamespace['namespace'];
644                    $score = $scoreNamespace['score'];
645
646                    if ($score > 0) {
647                        $this->performNotFoundRedirect($bestNamespaceId, self::TARGET_ORIGIN_BEST_NAMESPACE);
648                        return;
649                    }
650                    break;
651
652                case self::GO_TO_SEARCH_ENGINE:
653
654                    $this->redirectToSearchEngine();
655
656                    return;
657
658                // End Switch Action
659            }
660
661            // End While Action
662        }
663
664
665    }
666
667
668    /**
669     * getBestNamespace
670     * Return a list with 'BestNamespaceId Score'
671     * @param $id
672     * @return array
673     */
674    private
675    function scoreBestNamespace($id)
676    {
677
678        global $conf;
679
680        // Parameters
681        $pageNameSpace = getNS($id);
682
683        // If the page has an existing namespace start page take it, other search other namespace
684        $startPageNameSpace = $pageNameSpace . ":";
685        $dateAt = '';
686        // $startPageNameSpace will get a full path (ie with start or the namespace
687        resolve_pageid($pageNameSpace, $startPageNameSpace, $exists, $dateAt, true);
688        if (page_exists($startPageNameSpace)) {
689            $nameSpaces = array($startPageNameSpace);
690        } else {
691            $nameSpaces = ft_pageLookup($conf['start']);
692        }
693
694        // Parameters and search the best namespace
695        $pathNames = explode(':', $pageNameSpace);
696        $bestNbWordFound = 0;
697        $bestNamespaceId = '';
698        foreach ($nameSpaces as $nameSpace) {
699
700            $nbWordFound = 0;
701            foreach ($pathNames as $pathName) {
702                if (strlen($pathName) > 2) {
703                    $nbWordFound = $nbWordFound + substr_count($nameSpace, $pathName);
704                }
705            }
706            if ($nbWordFound > $bestNbWordFound) {
707                // Take only the smallest namespace
708                if (strlen($nameSpace) < strlen($bestNamespaceId) or $nbWordFound > $bestNbWordFound) {
709                    $bestNbWordFound = $nbWordFound;
710                    $bestNamespaceId = $nameSpace;
711                }
712            }
713        }
714
715        $startPageFactor = $this->getConf('WeightFactorForStartPage');
716        $nameSpaceFactor = $this->getConf('WeightFactorForSameNamespace');
717        if ($bestNbWordFound > 0) {
718            $bestNamespaceScore = $bestNbWordFound * $nameSpaceFactor + $startPageFactor;
719        } else {
720            $bestNamespaceScore = 0;
721        }
722
723
724        return array(
725            'namespace' => $bestNamespaceId,
726            'score' => $bestNamespaceScore
727        );
728
729    }
730
731    /**
732     * @param $event
733     */
734    private
735    function gotToEditMode(&$event)
736    {
737        global $ACT;
738        $ACT = 'edit';
739
740    }
741
742
743    /**
744     * Redirect to an internal page ie:
745     *   * on the same domain
746     *   * no HTTP redirect
747     *   * id rewrite
748     * @param string $targetPageId - target page id
749     * @param string $targetOriginId - the source of the target (redirect)
750     * @return bool - return true if the user has the permission and that the redirect was done
751     * @throws Exception
752     */
753    private
754    function executeTransparentRedirect(string $targetPageId, string $targetOriginId): bool
755    {
756        /**
757         * Because we set the ID globally for the ID redirect
758         * we make sure that this is not a {@link MarkupPath}
759         * object otherwise we got an error in the {@link \ComboStrap\AnalyticsMenuItem}
760         * because the constructor takes it {@link \dokuwiki\Menu\Item\AbstractItem}
761         */
762        if (is_object($targetPageId)) {
763            $class = get_class($targetPageId);
764            LogUtility::msg("The parameters targetPageId ($targetPageId) is an object of the class ($class) and it should be a page id");
765        }
766
767        if (is_object($targetOriginId)) {
768            $class = get_class($targetOriginId);
769            LogUtility::msg("The parameters targetOriginId ($targetOriginId) is an object of the class ($class) and it should be a page id");
770        }
771
772        // If the user does not have the right to see the target page
773        // don't do anything
774        if (!(Identity::isReader($targetPageId))) {
775            return false;
776        }
777
778        // Change the id
779        global $ID;
780        global $INFO;
781        $sourceId = $ID;
782        $ID = $targetPageId;
783        if (isset($_REQUEST["id"])) {
784            $_REQUEST["id"] = $targetPageId;
785        }
786        if (isset($_GET["id"])) {
787            $_GET["id"] = $targetPageId;
788        }
789
790        /**
791         * Refresh the $INFO data
792         *
793         * the info attributes are used elsewhere
794         *   'id': for the sidebar
795         *   'exist' : for the meta robot = noindex,follow, see {@link tpl_metaheaders()}
796         *   'rev' : for the edit button to be sure that the page is still the same
797         */
798        $INFO = pageinfo();
799
800        /**
801         * Not compatible with
802         * https://www.dokuwiki.org/config:send404 is enabled
803         *
804         * This check happens before that dokuwiki is started
805         * and send an header in doku.php
806         *
807         * We send a warning
808         */
809        global $conf;
810        if ($conf['send404'] == true) {
811            LogUtility::msg("The <a href=\"https://www.dokuwiki.org/config:send404\">dokuwiki send404 configuration</a> is on and should be disabled when using the url manager", LogUtility::LVL_MSG_ERROR, self::CANONICAL);
812        }
813
814        // Redirection
815        $this->logRedirection($sourceId, $targetPageId, $targetOriginId, self::REDIRECT_TRANSPARENT_METHOD);
816
817        return true;
818
819    }
820
821    private function executePermanentRedirect(string $targetIdOrUrl, $targetOrigin): bool
822    {
823        return $this->executeHttpRedirect($targetIdOrUrl, $targetOrigin, self::REDIRECT_PERMANENT_METHOD);
824    }
825
826    /**
827     * The general HTTP Redirect method to an internal page
828     * where the redirection method decide which type of redirection
829     * @param string $targetIdOrUrl - a dokuwiki id or an url
830     * @param string $targetOrigin - the origin of the target (the algorithm used to get the target origin)
831     * @param string $method - the redirection method
832     */
833    private
834    function executeHttpRedirect(string $targetIdOrUrl, string $targetOrigin, string $method): bool
835    {
836
837        global $ID;
838
839
840        // Log the redirections
841        $this->logRedirection($ID, $targetIdOrUrl, $targetOrigin, $method);
842
843
844        // An http external url ?
845        try {
846            $isHttpUrl = Url::createFromString($targetIdOrUrl)->isHttpUrl();
847        } catch (ExceptionBadSyntax|ExceptionBadArgument $e) {
848            $isHttpUrl = false;
849        }
850
851        // If there is a bug in the isValid function for an internal url
852        // We get a loop.
853        // The Url becomes the id, the id is unknown and we do a redirect again
854        //
855        // We check then if the target starts with the base url
856        // if this is the case, it's valid
857        if (!$isHttpUrl && strpos($targetIdOrUrl, DOKU_URL) === 0) {
858            $isHttpUrl = true;
859        }
860        if ($isHttpUrl) {
861
862            // defend against HTTP Response Splitting
863            // https://owasp.org/www-community/attacks/HTTP_Response_Splitting
864            $targetUrl = stripctl($targetIdOrUrl);
865
866        } else {
867
868
869            // Explode the page ID and the anchor (#)
870            $link = explode('#', $targetIdOrUrl, 2);
871
872            $url = UrlEndpoint::createDokuUrl();
873
874            $urlParams = [];
875            // if this is search engine redirect
876            if ($targetOrigin == self::TARGET_ORIGIN_SEARCH_ENGINE) {
877                $replacementPart = array(':', '_', '-');
878                $query = str_replace($replacementPart, ' ', $ID);
879                $url->setQueryParameter(ExecutionContext::DO_ATTRIBUTE, ExecutionContext::SEARCH_ACTION);
880                $url->setQueryParameter("q", $query);
881            }
882
883            /**
884             * Doing a permanent redirect with a added query string
885             * create a new page url on the search engine
886             *
887             * ie
888             * http://host/page
889             * is not the same
890             * than
891             * http://host/page?whatever
892             *
893             * We can't pass query string otherwise, we get
894             * the SEO warning / error
895             * `Alternative page with proper canonical tag`
896             *
897             * Use HTTP X header for debug
898             */
899            if ($method !== self::REDIRECT_PERMANENT_METHOD) {
900                $url->setQueryParameter(action_plugin_combo_routermessage::ORIGIN_PAGE, $ID);
901                $url->setQueryParameter(action_plugin_combo_routermessage::ORIGIN_TYPE, $targetOrigin);
902            }
903
904            $id = $link[0];
905            $url->setQueryParameter(DokuwikiId::DOKUWIKI_ID_ATTRIBUTE, $id);
906            if (array_key_exists(1, $link)) {
907                $url->setFragment($link[1]);
908            }
909            $targetUrl = $url->toAbsoluteUrlString();
910
911        }
912
913        /**
914         * The dokuwiki function {@link send_redirect()}
915         * set the `Location header` and in php, the header function
916         * in this case change the status code to 302 Arghhhh.
917         * The code below is adapted from this function {@link send_redirect()}
918         */
919        global $MSG; // are there any undisplayed messages? keep them in session for display
920        if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
921            //reopen session, store data and close session again
922            @session_start();
923            $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
924        }
925        session_write_close(); // always close the session
926
927        switch ($method) {
928
929            case self::REDIRECT_PERMANENT_METHOD:
930                ExecutionContext::getActualOrCreateFromEnv()
931                    ->response()
932                    ->setStatus(HttpResponseStatus::PERMANENT_REDIRECT)
933                    ->addHeader(self::LOCATION_HEADER_PREFIX . $targetUrl)
934                    ->end();
935                return true;
936
937            case self::REDIRECT_NOTFOUND_METHOD:
938
939
940                // Empty 404 body to not get the standard 404 page of the browser
941                // but a blank page to avoid a sort of FOUC.
942                // ie the user see a page briefly
943                ExecutionContext::getActualOrCreateFromEnv()
944                    ->response()
945                    ->setStatus(HttpResponseStatus::NOT_FOUND)
946                    ->addHeader(self::REFRESH_HEADER_PREFIX . $targetUrl)
947                    ->setBody(self::PAGE_404, Mime::getHtml())
948                    ->end();
949                return true;
950
951            default:
952                LogUtility::msg("The method ($method) is not an http redirection");
953                return false;
954        }
955
956
957    }
958
959    /**
960     * @param $id
961     * @return array
962     */
963    private
964    function getBestPage($id): array
965    {
966
967        // The return parameters
968        $bestPageId = null;
969        $scorePageName = null;
970
971        // Get Score from a page
972        $pageName = noNS($id);
973        $pagesWithSameName = ft_pageLookup($pageName);
974        if (count($pagesWithSameName) > 0) {
975
976            // Search same namespace in the page found than in the Id page asked.
977            $bestNbWordFound = 0;
978
979
980            $wordsInPageSourceId = explode(':', $id);
981            foreach ($pagesWithSameName as $targetPageId => $title) {
982
983                // Nb of word found in the target page id
984                // that are in the source page id
985                $nbWordFound = 0;
986                foreach ($wordsInPageSourceId as $word) {
987                    $nbWordFound = $nbWordFound + substr_count($targetPageId, $word);
988                }
989
990                if ($bestPageId == null) {
991
992                    $bestNbWordFound = $nbWordFound;
993                    $bestPageId = $targetPageId;
994
995                } else {
996
997                    if ($nbWordFound >= $bestNbWordFound && strlen($bestPageId) > strlen($targetPageId)) {
998
999                        $bestNbWordFound = $nbWordFound;
1000                        $bestPageId = $targetPageId;
1001
1002                    }
1003
1004                }
1005
1006            }
1007            $scorePageName = $this->getConf('WeightFactorForSamePageName') + ($bestNbWordFound - 1) * $this->getConf('WeightFactorForSameNamespace');
1008            return array(
1009                'id' => $bestPageId,
1010                'score' => $scorePageName);
1011        }
1012        return array(
1013            'id' => $bestPageId,
1014            'score' => $scorePageName
1015        );
1016
1017    }
1018
1019
1020    /**
1021     * Redirect to the search engine
1022     */
1023    private
1024    function redirectToSearchEngine()
1025    {
1026
1027        global $ID;
1028        $this->performNotFoundRedirect($ID, self::TARGET_ORIGIN_SEARCH_ENGINE);
1029
1030    }
1031
1032
1033    /**
1034     *
1035     *   * For a conf file, it will update the Redirection Action Data as Referrer, Count Of Redirection, Redirection Date
1036     *   * For a SQlite database, it will add a row into the log
1037     *
1038     * @param string $sourcePageId
1039     * @param $targetPageId
1040     * @param $algorithmic
1041     * @param $method - http or rewrite
1042     */
1043    function logRedirection(string $sourcePageId, $targetPageId, $algorithmic, $method)
1044    {
1045
1046        $row = array(
1047            "TIMESTAMP" => date("c"),
1048            "SOURCE" => $sourcePageId,
1049            "TARGET" => $targetPageId,
1050            "REFERRER" => $_SERVER['HTTP_REFERER'] ?? null,
1051            "TYPE" => $algorithmic,
1052            "METHOD" => $method
1053        );
1054        $request = Sqlite::createOrGetBackendSqlite()
1055            ->createRequest()
1056            ->setTableRow('redirections_log', $row);
1057        try {
1058            $request
1059                ->execute();
1060        } catch (ExceptionCompile $e) {
1061            LogUtility::msg("Redirection Log Insert Error. {$e->getMessage()}");
1062        } finally {
1063            $request->close();
1064        }
1065
1066
1067    }
1068
1069    /**
1070     * This function check if there is a redirection declared
1071     * in the redirection table
1072     * @return bool - true if a rewrite or redirection occurs
1073     * @throws Exception
1074     */
1075    private function processingPageRules(): bool
1076    {
1077        global $ID;
1078
1079        $calculatedTarget = null;
1080        $ruleMatcher = null; // Used in a warning message if the target page does not exist
1081        // Known redirection in the table
1082        // Get the page from redirection data
1083        $rules = $this->pageRules->getRules();
1084        foreach ($rules as $rule) {
1085
1086            $ruleMatcher = strtolower($rule[PageRules::MATCHER_NAME]);
1087            $ruleTarget = $rule[PageRules::TARGET_NAME];
1088
1089            // Glob to Rexgexp
1090            $regexpPattern = '/' . str_replace("*", "(.*)", $ruleMatcher) . '/i';
1091
1092            // Match ?
1093            // https://www.php.net/manual/en/function.preg-match.php
1094            $pregMatchResult = @preg_match($regexpPattern, $ID, $matches);
1095            if ($pregMatchResult === false) {
1096                // The `if` to take into account this problem
1097                // PHP Warning:  preg_match(): Unknown modifier 'd' in /opt/www/datacadamia.com/lib/plugins/combo/action/router.php on line 972
1098                LogUtility::log2file("processing Page Rules An error occurred with the pattern ($regexpPattern)", LogUtility::LVL_MSG_WARNING);
1099                return false;
1100            }
1101            if ($pregMatchResult) {
1102                $calculatedTarget = $ruleTarget;
1103                foreach ($matches as $key => $match) {
1104                    if ($key == 0) {
1105                        continue;
1106                    } else {
1107                        $calculatedTarget = str_replace('$' . $key, $match, $calculatedTarget);
1108                    }
1109                }
1110                break;
1111            }
1112        }
1113
1114        if ($calculatedTarget == null) {
1115            return false;
1116        }
1117
1118        // If this is an external redirect (other domain)
1119        try {
1120            $isHttpUrl = Url::createFromString($calculatedTarget)->isHttpUrl();
1121        } catch (ExceptionBadSyntax $e) {
1122            $isHttpUrl = false;
1123        }
1124        if ($isHttpUrl) {
1125            $this->executeHttpRedirect($calculatedTarget, self::TARGET_ORIGIN_PAGE_RULES, self::REDIRECT_PERMANENT_METHOD);
1126            return true;
1127        }
1128
1129        // If the page exist
1130        if (page_exists($calculatedTarget)) {
1131
1132            // This is DokuWiki Id and should always be lowercase
1133            // The page rule may have change that
1134            $calculatedTarget = strtolower($calculatedTarget);
1135            $res = $this->executeHttpRedirect($calculatedTarget, self::TARGET_ORIGIN_PAGE_RULES, self::REDIRECT_PERMANENT_METHOD);
1136            if ($res) {
1137                return true;
1138            } else {
1139                return false;
1140            }
1141
1142        } else {
1143
1144            LogUtility::msg("The calculated target page ($calculatedTarget) (for the non-existing page `$ID` with the matcher `$ruleMatcher`) does not exist", LogUtility::LVL_MSG_ERROR);
1145            return false;
1146
1147        }
1148
1149    }
1150
1151    private function performNotFoundRedirect(string $targetId, string $origin): bool
1152    {
1153        return $this->executeHttpRedirect($targetId, $origin, self::REDIRECT_NOTFOUND_METHOD);
1154    }
1155
1156
1157}
1158