1c3437056SNickeau<?php 2c3437056SNickeau 3c3437056SNickeau 4c3437056SNickeauuse ComboStrap\DatabasePageRow; 511d09b86Sgerardnicouse ComboStrap\DokuwikiId; 604fd306cSNickeauuse ComboStrap\ExceptionBadArgument; 704fd306cSNickeauuse ComboStrap\ExceptionBadSyntax; 804fd306cSNickeauuse ComboStrap\ExceptionCompile; 904fd306cSNickeauuse ComboStrap\ExceptionSqliteNotAvailable; 1004fd306cSNickeauuse ComboStrap\ExecutionContext; 1104fd306cSNickeauuse ComboStrap\FileSystems; 12c3437056SNickeauuse ComboStrap\HttpResponse; 1304fd306cSNickeauuse ComboStrap\HttpResponseStatus; 14c3437056SNickeauuse ComboStrap\Identity; 15c3437056SNickeauuse ComboStrap\LogUtility; 1604fd306cSNickeauuse ComboStrap\MarkupPath; 1704fd306cSNickeauuse ComboStrap\Meta\Field\AliasType; 18c3437056SNickeauuse ComboStrap\Mime; 19c3437056SNickeauuse ComboStrap\PageId; 20c3437056SNickeauuse ComboStrap\PageRules; 21c3437056SNickeauuse ComboStrap\PageUrlPath; 2282a60d03SNickeauuse ComboStrap\PageUrlType; 2304fd306cSNickeauuse ComboStrap\RouterBestEndPage; 24c3437056SNickeauuse ComboStrap\Site; 2504fd306cSNickeauuse ComboStrap\SiteConfig; 26c3437056SNickeauuse ComboStrap\Sqlite; 2704fd306cSNickeauuse ComboStrap\Web\Url; 2811d09b86Sgerardnicouse ComboStrap\Web\UrlEndpoint; 2954743e42Sgerardnicouse ComboStrap\Web\UrlRewrite; 3004fd306cSNickeauuse ComboStrap\WikiPath; 31c3437056SNickeau 3204fd306cSNickeaurequire_once(__DIR__ . '/../vendor/autoload.php'); 33c3437056SNickeau 34c3437056SNickeau/** 35c3437056SNickeau * Class action_plugin_combo_url 36c3437056SNickeau * 37c3437056SNickeau * The actual URL manager 38c3437056SNickeau * 39c3437056SNickeau * 40c3437056SNickeau */ 41c3437056SNickeauclass action_plugin_combo_router extends DokuWiki_Action_Plugin 42c3437056SNickeau{ 43c3437056SNickeau 44c3437056SNickeau /** 45c3437056SNickeau * @deprecated 46c3437056SNickeau */ 47c3437056SNickeau const URL_MANAGER_ENABLE_CONF = "enableUrlManager"; 48c3437056SNickeau const ROUTER_ENABLE_CONF = "enableRouter"; 49c3437056SNickeau 50c3437056SNickeau // The redirect type 51c3437056SNickeau const REDIRECT_TRANSPARENT_METHOD = 'transparent'; // was (Id) 52c3437056SNickeau // For permanent, see https://developers.google.com/search/docs/advanced/crawling/301-redirects 53c3437056SNickeau const REDIRECT_PERMANENT_METHOD = 'permanent'; // was `Http` (301) 54c3437056SNickeau const REDIRECT_NOTFOUND_METHOD = "notfound"; // 404 (See other) (when best page name is calculated) 55c3437056SNickeau 56c3437056SNickeau public const PERMANENT_REDIRECT_CANONICAL = "permanent:redirect"; 57c3437056SNickeau 58c3437056SNickeau // Where the target id value comes from 59c3437056SNickeau const TARGET_ORIGIN_WELL_KNOWN = 'well-known'; 60c3437056SNickeau const TARGET_ORIGIN_PAGE_RULES = 'pageRules'; 61c3437056SNickeau /** 62c3437056SNickeau * Named Permalink (canonical) 63c3437056SNickeau */ 64c3437056SNickeau const TARGET_ORIGIN_CANONICAL = 'canonical'; 65c3437056SNickeau const TARGET_ORIGIN_ALIAS = 'alias'; 66c3437056SNickeau /** 67c3437056SNickeau * Identifier Permalink (full page id) 68c3437056SNickeau */ 69c3437056SNickeau const TARGET_ORIGIN_PERMALINK = "permalink"; 70c3437056SNickeau /** 71c3437056SNickeau * Extended Permalink (abbreviated page id at the end) 72c3437056SNickeau */ 73c3437056SNickeau const TARGET_ORIGIN_PERMALINK_EXTENDED = "extendedPermalink"; 74c3437056SNickeau const TARGET_ORIGIN_START_PAGE = 'startPage'; 75c3437056SNickeau const TARGET_ORIGIN_BEST_PAGE_NAME = 'bestPageName'; 76c3437056SNickeau const TARGET_ORIGIN_BEST_NAMESPACE = 'bestNamespace'; 77c3437056SNickeau const TARGET_ORIGIN_SEARCH_ENGINE = 'searchEngine'; 78c3437056SNickeau const TARGET_ORIGIN_BEST_END_PAGE_NAME = 'bestEndPageName'; 79c3437056SNickeau const TARGET_ORIGIN_SHADOW_BANNED = "shadowBanned"; 80c3437056SNickeau 81c3437056SNickeau 82c3437056SNickeau // The constant parameters 83c3437056SNickeau const GO_TO_SEARCH_ENGINE = 'GoToSearchEngine'; 84c3437056SNickeau const GO_TO_BEST_NAMESPACE = 'GoToBestNamespace'; 85c3437056SNickeau const GO_TO_BEST_PAGE_NAME = 'GoToBestPageName'; 86c3437056SNickeau const GO_TO_BEST_END_PAGE_NAME = 'GoToBestEndPageName'; 87c3437056SNickeau const GO_TO_NS_START_PAGE = 'GoToNsStartPage'; 88c3437056SNickeau const GO_TO_EDIT_MODE = 'GoToEditMode'; 89c3437056SNickeau const NOTHING = 'Nothing'; 90c3437056SNickeau 91c3437056SNickeau /** @var string - a name used in log and other places */ 92c3437056SNickeau const NAME = 'Url Manager'; 93c3437056SNickeau const CANONICAL = 'router'; 94c3437056SNickeau const PAGE_404 = "<html lang=\"en\"><body></body></html>"; 95c3437056SNickeau const REFRESH_HEADER_NAME = "Refresh"; 96c3437056SNickeau const REFRESH_HEADER_PREFIX = self::REFRESH_HEADER_NAME . ': 0;url='; 9704fd306cSNickeau const LOCATION_HEADER_PREFIX = HttpResponse::LOCATION_HEADER_NAME . ": "; 98c3437056SNickeau public const URL_MANAGER_NAME = "Router"; 99c3437056SNickeau 100c3437056SNickeau 101c3437056SNickeau /** 102c3437056SNickeau * @var PageRules 103c3437056SNickeau */ 104c3437056SNickeau private $pageRules; 105c3437056SNickeau 106c3437056SNickeau 107c3437056SNickeau function __construct() 108c3437056SNickeau { 109c3437056SNickeau // enable direct access to language strings 110c3437056SNickeau // ie $this->lang 111c3437056SNickeau $this->setupLocale(); 112c3437056SNickeau 113c3437056SNickeau } 114c3437056SNickeau 115c3437056SNickeau /** 11604fd306cSNickeau * @param string $refreshHeader 117c3437056SNickeau * @return false|string 118c3437056SNickeau */ 11904fd306cSNickeau public static function getUrlFromRefresh(string $refreshHeader) 120c3437056SNickeau { 121c3437056SNickeau return substr($refreshHeader, strlen(action_plugin_combo_router::REFRESH_HEADER_PREFIX)); 122c3437056SNickeau } 123c3437056SNickeau 124c3437056SNickeau public static function getUrlFromLocation($refreshHeader) 125c3437056SNickeau { 126c3437056SNickeau return substr($refreshHeader, strlen(action_plugin_combo_router::LOCATION_HEADER_PREFIX)); 127c3437056SNickeau } 128c3437056SNickeau 129c3437056SNickeau /** 130ad79af66SNico * @return string|null 131c3437056SNickeau * 13294daa629SNico * Return the original id from the request 13394daa629SNico * ie `howto:how-to-get-started-with-combostrap-m3i8vga8` 13494daa629SNico * if `/howto/how-to-get-started-with-combostrap-m3i8vga8` 13594daa629SNico * 136c3437056SNickeau * Unfortunately, DOKUWIKI_STARTED is not the first event 137c3437056SNickeau * The id may have been changed by 138ad79af66SNico * {@link action_plugin_combo_lang::load_lang()} 139c3437056SNickeau * function, that's why we have this function 140c3437056SNickeau * to get the original requested id 141c3437056SNickeau */ 142ad79af66SNico private static function getOriginalIdFromRequest(): ?string 143c3437056SNickeau { 14494daa629SNico $originalId = $_GET["id"] ?? null; 145f49666c9Sgerardnico if ($originalId === null) { 146f49666c9Sgerardnico return null; 147f49666c9Sgerardnico } 14894daa629SNico // We get a `/` as first character 14994daa629SNico // because we return an id, we need to delete it 15094daa629SNico $originalId = substr($originalId, 1); 15194daa629SNico // transform / to : 15204fd306cSNickeau return str_replace("/", WikiPath::NAMESPACE_SEPARATOR_DOUBLE_POINT, $originalId); 153c3437056SNickeau } 154c3437056SNickeau 155c3437056SNickeau /** 156c3437056SNickeau * Determine if the request should be banned based on the id 157c3437056SNickeau * 158c3437056SNickeau * @param string $id 159c3437056SNickeau * @return bool 160c3437056SNickeau * 161c3437056SNickeau * See also {@link https://perishablepress.com/7g-firewall/#features} 162c3437056SNickeau * for blocking rules on http request data such as: 163c3437056SNickeau * * query_string 164c3437056SNickeau * * user_agent, 165c3437056SNickeau * * remote host 166c3437056SNickeau */ 167c3437056SNickeau public static function isShadowBanned(string $id): bool 168c3437056SNickeau { 169c3437056SNickeau /** 170c3437056SNickeau * ie 171c3437056SNickeau * wp-json:api:flutter_woo:config_file 172c3437056SNickeau * wp-content:plugins:wpdiscuz:themes:default:style-rtl.css 173c3437056SNickeau * wp-admin 174c3437056SNickeau * 2020:wp-includes:wlwmanifest.xml 175c3437056SNickeau * wp-content:start 176c3437056SNickeau * wp-admin:css:start 177c3437056SNickeau * sito:wp-includes:wlwmanifest.xml 178c3437056SNickeau * site:wp-includes:wlwmanifest.xml 179c3437056SNickeau * cms:wp-includes:wlwmanifest.xml 180c3437056SNickeau * test:wp-includes:wlwmanifest.xml 181c3437056SNickeau * media:wp-includes:wlwmanifest.xml 182c3437056SNickeau * wp2:wp-includes:wlwmanifest.xml 183c3437056SNickeau * 2019:wp-includes:wlwmanifest.xml 184c3437056SNickeau * shop:wp-includes:wlwmanifest.xml 185c3437056SNickeau * wp1:wp-includes:wlwmanifest.xml 186c3437056SNickeau * news:wp-includes:wlwmanifest.xml 187c3437056SNickeau * 2018:wp-includes:wlwmanifest.xml 188c3437056SNickeau */ 189c3437056SNickeau if (strpos($id, 'wp-') !== false) { 190c3437056SNickeau return true; 191c3437056SNickeau } 192c3437056SNickeau 193c3437056SNickeau /** 194c3437056SNickeau * 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 195c3437056SNickeau * db:oracle:999999.9:union:all:select_null:from_dual 196c3437056SNickeau * db:oracle:999999.9:union:all:select_null:from_dual_and_0_0 197c3437056SNickeau */ 198c3437056SNickeau if (preg_match('/_chr_|_0_0/', $id) === 1) { 199c3437056SNickeau return true; 200c3437056SNickeau } 201c3437056SNickeau 202c3437056SNickeau 203c3437056SNickeau /** 204c3437056SNickeau * ie 205c3437056SNickeau * git:objects: 206c3437056SNickeau * git:refs:heads:stable 207c3437056SNickeau * git:logs:refs:heads:main 208c3437056SNickeau * git:logs:refs:heads:stable 209c3437056SNickeau * git:hooks:pre-push.sample 210c3437056SNickeau * git:hooks:pre-receive.sample 211c3437056SNickeau */ 212c3437056SNickeau if (strpos($id, "git:") === 0) { 213c3437056SNickeau return true; 214c3437056SNickeau } 215c3437056SNickeau 216c3437056SNickeau return false; 217c3437056SNickeau 218c3437056SNickeau } 219c3437056SNickeau 220c3437056SNickeau /** 221c3437056SNickeau * @param string $id 222c3437056SNickeau * @return bool 223c3437056SNickeau * well-known:traffic-advice = https://github.com/buettner/private-prefetch-proxy/blob/main/traffic-advice.md 224c3437056SNickeau * .well-known/security.txt, id=well-known:security.txt = https://securitytxt.org/ 225c3437056SNickeau * well-known:dnt-policy.txt 226c3437056SNickeau */ 227c3437056SNickeau public static function isWellKnownFile(string $id): bool 228c3437056SNickeau { 229c3437056SNickeau return strpos($id, "well-known") === 0; 230c3437056SNickeau } 231c3437056SNickeau 232c3437056SNickeau 233c3437056SNickeau function register(Doku_Event_Handler $controller) 234c3437056SNickeau { 235c3437056SNickeau 23604fd306cSNickeau if (SiteConfig::getConfValue(self::ROUTER_ENABLE_CONF, 1)) { 23704fd306cSNickeau 238c3437056SNickeau /** 239c3437056SNickeau * This will call the function {@link action_plugin_combo_router::_router()} 240c3437056SNickeau * The event is not DOKUWIKI_STARTED because this is not the first one 241c3437056SNickeau * 242c3437056SNickeau * https://www.dokuwiki.org/devel:event:init_lang_load 243c3437056SNickeau */ 244c3437056SNickeau $controller->register_hook('DOKUWIKI_STARTED', 24504fd306cSNickeau 'BEFORE', 246c3437056SNickeau $this, 247c3437056SNickeau 'router', 248c3437056SNickeau array()); 249c3437056SNickeau 250c3437056SNickeau /** 251*5187326aSNico * Bot Ban functionality 252c3437056SNickeau * 253*5187326aSNico * Because we make a redirection to the home page, we need to check 254*5187326aSNico * if the home is readable, for that, the AUTH plugin needs to be initialized 255*5187326aSNico * That's why we wait 256*5187326aSNico * https://www.dokuwiki.org/devel:event:dokuwiki_init_done 257*5187326aSNico * 258*5187326aSNico * and we can't use 259c3437056SNickeau * https://www.dokuwiki.org/devel:event:init_lang_load 260*5187326aSNico * because there is no auth setup in {@link auth_aclcheck_cb()} 261*5187326aSNico * and the the line `if (!$auth instanceof AuthPlugin) return AUTH_NONE;` return none; 262c3437056SNickeau */ 263*5187326aSNico $controller->register_hook('DOKUWIKI_INIT_DONE', 'BEFORE', $this, 'ban', array()); 264c3437056SNickeau 265c3437056SNickeau } 266c3437056SNickeau 267c3437056SNickeau 268c3437056SNickeau } 269c3437056SNickeau 270c3437056SNickeau /** 271c3437056SNickeau * 272c3437056SNickeau * We have created a spacial ban function that is 273c3437056SNickeau * called before the first function 274c3437056SNickeau * {@link action_plugin_combo_metalang::load_lang()} 275c3437056SNickeau * to spare CPU. 276c3437056SNickeau * 277c3437056SNickeau * @param $event 278c3437056SNickeau * @throws Exception 279c3437056SNickeau */ 280c3437056SNickeau function ban(&$event) 281c3437056SNickeau { 282c3437056SNickeau 283c3437056SNickeau $id = self::getOriginalIdFromRequest(); 28406ecf9e7Sgerardnico if ($id === null) { 28506ecf9e7Sgerardnico return; 28606ecf9e7Sgerardnico } 28704fd306cSNickeau $page = MarkupPath::createMarkupFromId($id); 288*5187326aSNico if (FileSystems::exists($page)) { 289*5187326aSNico return; 290*5187326aSNico } 291*5187326aSNico 292c3437056SNickeau // Well known 293c3437056SNickeau if (self::isWellKnownFile($id)) { 294c3437056SNickeau $this->logRedirection($id, "", self::TARGET_ORIGIN_WELL_KNOWN, self::REDIRECT_NOTFOUND_METHOD); 29504fd306cSNickeau ExecutionContext::getActualOrCreateFromEnv() 29604fd306cSNickeau ->response() 29704fd306cSNickeau ->setStatus(HttpResponseStatus::NOT_FOUND) 29804fd306cSNickeau ->end(); 299c3437056SNickeau return; 300c3437056SNickeau } 301c3437056SNickeau 302c3437056SNickeau // Shadow banned 303c3437056SNickeau if (self::isShadowBanned($id)) { 30404fd306cSNickeau $webSiteHomePage = Site::getIndexPageName(); 305c3437056SNickeau $this->executeTransparentRedirect($webSiteHomePage, self::TARGET_ORIGIN_SHADOW_BANNED); 306c3437056SNickeau } 307*5187326aSNico 308c3437056SNickeau } 309c3437056SNickeau 310c3437056SNickeau /** 311c3437056SNickeau * @param $event Doku_Event 312c3437056SNickeau * @param $param 313c3437056SNickeau * @return void 314c3437056SNickeau * @throws Exception 315c3437056SNickeau */ 316c3437056SNickeau function router(&$event, $param) 317c3437056SNickeau { 318c3437056SNickeau 31904fd306cSNickeau /** 32004fd306cSNickeau * Just the {@link ExecutionContext::SHOW_ACTION} 32104fd306cSNickeau * may be redirected 32204fd306cSNickeau */ 32304fd306cSNickeau $executionContext = ExecutionContext::getActualOrCreateFromEnv(); 32404fd306cSNickeau if ($executionContext->getExecutingAction() !== ExecutionContext::SHOW_ACTION) { 32504fd306cSNickeau return; 32604fd306cSNickeau } 327c3437056SNickeau 32854743e42Sgerardnico $urlRewrite = Site::getUrlRewrite(); 32954743e42Sgerardnico if ($urlRewrite == UrlRewrite::VALUE_DOKU_REWRITE) { 33054743e42Sgerardnico UrlRewrite::sendErrorMessage(); 33154743e42Sgerardnico return; 33254743e42Sgerardnico } 333c3437056SNickeau 334c3437056SNickeau global $ID; 335c3437056SNickeau 336c3437056SNickeau /** 337c3437056SNickeau * Without SQLite, this module does not work further 338c3437056SNickeau */ 33904fd306cSNickeau try { 34004fd306cSNickeau Sqlite::createOrGetSqlite(); 34104fd306cSNickeau } catch (ExceptionSqliteNotAvailable $e) { 342c3437056SNickeau return; 343c3437056SNickeau } 344c3437056SNickeau 34504fd306cSNickeau $this->pageRules = new PageRules(); 34604fd306cSNickeau 34704fd306cSNickeau 348c3437056SNickeau /** 349c3437056SNickeau * Unfortunately, DOKUWIKI_STARTED is not the first event 350c3437056SNickeau * The id may have been changed by 35104fd306cSNickeau * {@link action_plugin_combo_lang::load_lang()} 352c3437056SNickeau * function, that's why we check against the {@link $_REQUEST} 353c3437056SNickeau * and not the global ID 354c3437056SNickeau */ 355c3437056SNickeau $originalId = self::getOriginalIdFromRequest(); 356c3437056SNickeau 357c3437056SNickeau /** 358c3437056SNickeau * Page is an existing id ? 359c3437056SNickeau */ 36004fd306cSNickeau $requestedMarkupPath = MarkupPath::createMarkupFromId($ID); 36104fd306cSNickeau if (FileSystems::exists($requestedMarkupPath)) { 362c3437056SNickeau 363c3437056SNickeau /** 364c3437056SNickeau * If this is not the root home page 36594daa629SNico * and if the canonical id is the not the same (the id has changed) 366c3437056SNickeau * and if this is not a historical page (revision) 367c3437056SNickeau * redirect 368c3437056SNickeau */ 369c3437056SNickeau if ( 37004fd306cSNickeau $originalId !== $requestedMarkupPath->getUrlId() // The id may have been changed 37104fd306cSNickeau && $ID != Site::getIndexPageName() 372c3437056SNickeau && !isset($_REQUEST["rev"]) 373c3437056SNickeau ) { 3744cadd4f8SNickeau /** 3754cadd4f8SNickeau * TODO: When saving for the first time, the page is not stored in the database 3764cadd4f8SNickeau * but that's not the case actually 3774cadd4f8SNickeau */ 37804fd306cSNickeau $databasePageRow = $requestedMarkupPath->getDatabasePage(); 37904fd306cSNickeau if ($databasePageRow->exists()) { 38004fd306cSNickeau /** 38104fd306cSNickeau * A move may leave the database in a bad state, 38204fd306cSNickeau * unfortunately (ie page is not in index, unable to update, ...) 38304fd306cSNickeau * We test therefore if the database page id exists 38404fd306cSNickeau */ 38504fd306cSNickeau $targetPageId = $databasePageRow->getFromRow("id"); 38604fd306cSNickeau $targetPath = WikiPath::createMarkupPathFromId($targetPageId); 38704fd306cSNickeau if (FileSystems::exists($targetPath)) { 388c3437056SNickeau $this->executePermanentRedirect( 38904fd306cSNickeau $requestedMarkupPath->getCanonicalUrl()->toAbsoluteUrlString(), 390c3437056SNickeau self::TARGET_ORIGIN_PERMALINK_EXTENDED 391c3437056SNickeau ); 392c3437056SNickeau } 3934cadd4f8SNickeau } 39404fd306cSNickeau } 395c3437056SNickeau return; 396c3437056SNickeau } 397c3437056SNickeau 398c3437056SNickeau 399c3437056SNickeau $identifier = $ID; 400c3437056SNickeau 401c3437056SNickeau 402c3437056SNickeau /** 4031089b853Sgerardnico * Page Id in the url 404c3437056SNickeau */ 40504fd306cSNickeau $shortPageId = PageUrlPath::getShortEncodedPageIdFromUrlId($requestedMarkupPath->getPathObject()->getLastNameWithoutExtension()); 4061089b853Sgerardnico if ($shortPageId != null) { 407c3437056SNickeau $pageId = PageUrlPath::decodePageId($shortPageId); 4081089b853Sgerardnico } else { 4091089b853Sgerardnico /** 4101089b853Sgerardnico * Permalink with id 4111089b853Sgerardnico */ 4121089b853Sgerardnico $pageId = PageUrlPath::decodePageId($identifier); 4131089b853Sgerardnico } 4141089b853Sgerardnico if ($pageId !== null) { 4151089b853Sgerardnico 4161089b853Sgerardnico if ($requestedMarkupPath->getParent() === null) { 41704fd306cSNickeau $page = DatabasePageRow::createFromPageId($pageId)->getMarkupPath(); 418c3437056SNickeau if ($page !== null && $page->exists()) { 41982a60d03SNickeau $this->executePermanentRedirect( 42004fd306cSNickeau $page->getCanonicalUrl()->toAbsoluteUrlString(), 42182a60d03SNickeau self::TARGET_ORIGIN_PERMALINK 42282a60d03SNickeau ); 4231089b853Sgerardnico return; 424c3437056SNickeau } 425c3437056SNickeau } 426c3437056SNickeau 427c3437056SNickeau /** 428c3437056SNickeau * Page Id Abbr ? 429c3437056SNickeau * {@link PageUrlType::CONF_CANONICAL_URL_TYPE} 430c3437056SNickeau */ 43104fd306cSNickeau $page = DatabasePageRow::createFromPageIdAbbr($pageId)->getMarkupPath(); 432c3437056SNickeau if ($page === null) { 433c3437056SNickeau // or the length of the abbr has changed 43404fd306cSNickeau $canonicalDatabasePage = new DatabasePageRow(); 43504fd306cSNickeau $row = $canonicalDatabasePage->getDatabaseRowFromAttribute("substr(" . PageId::PROPERTY_NAME . ", 1, " . strlen($pageId) . ")", $pageId); 4364cadd4f8SNickeau if ($row !== null) { 43704fd306cSNickeau $canonicalDatabasePage->setRow($row); 43804fd306cSNickeau $page = $canonicalDatabasePage->getMarkupPath(); 439c3437056SNickeau } 440c3437056SNickeau } 441c3437056SNickeau if ($page !== null && $page->exists()) { 442c3437056SNickeau /** 443c3437056SNickeau * If the url canonical id has changed, we show it 444c3437056SNickeau * to the writer by performing a permanent redirect 445c3437056SNickeau */ 446c3437056SNickeau if ($identifier != $page->getUrlId()) { 447c3437056SNickeau // Google asks for a redirect 448c3437056SNickeau // https://developers.google.com/search/docs/advanced/crawling/301-redirects 449c3437056SNickeau // People access your site through several different URLs. 450c3437056SNickeau // If, for example, your home page can be reached in multiple ways 451c3437056SNickeau // (for instance, http://example.com/home, http://home.example.com, or http://www.example.com), 452c3437056SNickeau // it's a good idea to pick one of those URLs as your preferred (canonical) destination, 453c3437056SNickeau // and use redirects to send traffic from the other URLs to your preferred URL. 454c3437056SNickeau $this->executePermanentRedirect( 45504fd306cSNickeau $page->getCanonicalUrl()->toAbsoluteUrlString(), 456c3437056SNickeau self::TARGET_ORIGIN_PERMALINK_EXTENDED 457c3437056SNickeau ); 458c3437056SNickeau return; 459c3437056SNickeau } 4604cadd4f8SNickeau 46104fd306cSNickeau $this->executeTransparentRedirect($page->getWikiId(), self::TARGET_ORIGIN_PERMALINK_EXTENDED); 462c3437056SNickeau return; 463c3437056SNickeau 464c3437056SNickeau } 465c3437056SNickeau // permanent url not yet in the database 466c3437056SNickeau // Other permanent such as permanent canonical ? 467c3437056SNickeau // We let the process go with the new identifier 468c3437056SNickeau 469c3437056SNickeau } 470c3437056SNickeau 471c3437056SNickeau // Global variable needed in the process 472c3437056SNickeau global $conf; 473c3437056SNickeau 474c3437056SNickeau /** 475c3437056SNickeau * Identifier is a Canonical ? 476c3437056SNickeau */ 47704fd306cSNickeau $canonicalDatabasePage = DatabasePageRow::createFromCanonical($identifier); 47804fd306cSNickeau $canonicalPage = $canonicalDatabasePage->getMarkupPath(); 47904fd306cSNickeau if ($canonicalPage !== null && $canonicalPage->exists()) { 48082a60d03SNickeau /** 48182a60d03SNickeau * Does the canonical url is canonical name based 48282a60d03SNickeau * ie {@link PageUrlType::CONF_VALUE_CANONICAL_PATH} 48382a60d03SNickeau */ 48404fd306cSNickeau if ($canonicalPage->getUrlId() === $identifier) { 48582a60d03SNickeau $res = $this->executeTransparentRedirect( 48604fd306cSNickeau $canonicalPage->getWikiId(), 48782a60d03SNickeau self::TARGET_ORIGIN_CANONICAL 48882a60d03SNickeau ); 48982a60d03SNickeau } else { 49082a60d03SNickeau $res = $this->executePermanentRedirect( 49104fd306cSNickeau $canonicalPage->getWikiId(), // not the url because, it allows to add url query redirection property 49282a60d03SNickeau self::TARGET_ORIGIN_CANONICAL 49382a60d03SNickeau ); 49482a60d03SNickeau } 495c3437056SNickeau if ($res) { 496c3437056SNickeau return; 497c3437056SNickeau } 498c3437056SNickeau } 499c3437056SNickeau 500c3437056SNickeau /** 501c3437056SNickeau * Identifier is an alias 502c3437056SNickeau */ 50304fd306cSNickeau $aliasRequestedPage = DatabasePageRow::createFromAlias($identifier)->getMarkupPath(); 504c3437056SNickeau if ( 50504fd306cSNickeau $aliasRequestedPage !== null 50604fd306cSNickeau && $aliasRequestedPage->exists() 507c3437056SNickeau // The build alias is the file system metadata alias 508c3437056SNickeau // it may be null if the replication in the database was not successful 50904fd306cSNickeau && $aliasRequestedPage->getBuildAlias() !== null 510c3437056SNickeau ) { 51104fd306cSNickeau $buildAlias = $aliasRequestedPage->getBuildAlias(); 512c3437056SNickeau switch ($buildAlias->getType()) { 513c3437056SNickeau case AliasType::REDIRECT: 51404fd306cSNickeau $res = $this->executePermanentRedirect($aliasRequestedPage->getCanonicalUrl()->toAbsoluteUrlString(), self::TARGET_ORIGIN_ALIAS); 515c3437056SNickeau if ($res) { 516c3437056SNickeau return; 517c3437056SNickeau } 518c3437056SNickeau break; 519c3437056SNickeau case AliasType::SYNONYM: 52004fd306cSNickeau $res = $this->executeTransparentRedirect($aliasRequestedPage->getWikiId(), self::TARGET_ORIGIN_ALIAS); 521c3437056SNickeau if ($res) { 522c3437056SNickeau return; 523c3437056SNickeau } 524c3437056SNickeau break; 525c3437056SNickeau default: 526c3437056SNickeau LogUtility::msg("The alias type ({$buildAlias->getType()}) is unknown. A permanent redirect was performed for the alias $identifier"); 52704fd306cSNickeau $res = $this->executePermanentRedirect($aliasRequestedPage->getCanonicalUrl()->toAbsoluteUrlString(), self::TARGET_ORIGIN_ALIAS); 528c3437056SNickeau if ($res) { 529c3437056SNickeau return; 530c3437056SNickeau } 531c3437056SNickeau break; 532c3437056SNickeau } 533c3437056SNickeau } 534c3437056SNickeau 535c3437056SNickeau 536c3437056SNickeau // If there is a redirection defined in the page rules 537c3437056SNickeau $result = $this->processingPageRules(); 538c3437056SNickeau if ($result) { 539c3437056SNickeau // A redirection has occurred 540c3437056SNickeau // finish the process 541c3437056SNickeau return; 542c3437056SNickeau } 543c3437056SNickeau 544c3437056SNickeau /** 545c3437056SNickeau * 546c3437056SNickeau * There was no redirection found, redirect to edit mode if writer 547c3437056SNickeau * 548c3437056SNickeau */ 549c3437056SNickeau if (Identity::isWriter() && $this->getConf(self::GO_TO_EDIT_MODE) == 1) { 550c3437056SNickeau 551c3437056SNickeau $this->gotToEditMode($event); 552c3437056SNickeau // Stop here 553c3437056SNickeau return; 554c3437056SNickeau 555c3437056SNickeau } 556c3437056SNickeau 55704fd306cSNickeau /** 558c3437056SNickeau * We are still a reader, the redirection does not exist the user is not allowed to edit the page (public of other) 559c3437056SNickeau */ 560c3437056SNickeau if ($this->getConf('ActionReaderFirst') == self::NOTHING) { 561c3437056SNickeau return; 562c3437056SNickeau } 563c3437056SNickeau 564c3437056SNickeau // We are reader and their is no redirection set, we apply the algorithm 565c3437056SNickeau $readerAlgorithms = array(); 566c3437056SNickeau $readerAlgorithms[0] = $this->getConf('ActionReaderFirst'); 567c3437056SNickeau $readerAlgorithms[1] = $this->getConf('ActionReaderSecond'); 568c3437056SNickeau $readerAlgorithms[2] = $this->getConf('ActionReaderThird'); 569c3437056SNickeau 570c3437056SNickeau while ( 571c3437056SNickeau ($algorithm = array_shift($readerAlgorithms)) != null 572c3437056SNickeau ) { 573c3437056SNickeau 574c3437056SNickeau switch ($algorithm) { 575c3437056SNickeau 576c3437056SNickeau case self::NOTHING: 577c3437056SNickeau return; 578c3437056SNickeau 579c3437056SNickeau case self::GO_TO_BEST_END_PAGE_NAME: 580c3437056SNickeau 58104fd306cSNickeau /** 58204fd306cSNickeau * @var MarkupPath $bestEndPage 58304fd306cSNickeau */ 58404fd306cSNickeau list($bestEndPage, $method) = RouterBestEndPage::process($requestedMarkupPath); 585ea801fd8Sgerardnico if ($bestEndPage != null && $bestEndPage->getWikiId() !== $requestedMarkupPath->getWikiId()) { 586c3437056SNickeau $res = false; 587c3437056SNickeau switch ($method) { 588c3437056SNickeau case self::REDIRECT_PERMANENT_METHOD: 58904fd306cSNickeau $res = $this->executePermanentRedirect($bestEndPage->getWikiId(), self::TARGET_ORIGIN_BEST_END_PAGE_NAME); 590c3437056SNickeau break; 591c3437056SNickeau case self::REDIRECT_NOTFOUND_METHOD: 59204fd306cSNickeau $res = $this->performNotFoundRedirect($bestEndPage->getWikiId(), self::TARGET_ORIGIN_BEST_END_PAGE_NAME); 593c3437056SNickeau break; 594c3437056SNickeau default: 595c3437056SNickeau LogUtility::msg("This redirection method ($method) was not expected for the redirection algorithm ($algorithm)"); 596c3437056SNickeau } 597c3437056SNickeau if ($res) { 598c3437056SNickeau // Redirection has succeeded 599c3437056SNickeau return; 600c3437056SNickeau } 601c3437056SNickeau } 602c3437056SNickeau break; 603c3437056SNickeau 604c3437056SNickeau case self::GO_TO_NS_START_PAGE: 605c3437056SNickeau 606c3437056SNickeau // Start page with the conf['start'] parameter 607c3437056SNickeau $startPage = getNS($identifier) . ':' . $conf['start']; 608c3437056SNickeau if (page_exists($startPage)) { 609c3437056SNickeau $res = $this->performNotFoundRedirect($startPage, self::TARGET_ORIGIN_START_PAGE); 610c3437056SNickeau if ($res) { 611c3437056SNickeau return; 612c3437056SNickeau } 613c3437056SNickeau } 614c3437056SNickeau 615c3437056SNickeau // Start page with the same name than the namespace 616c3437056SNickeau $startPage = getNS($identifier) . ':' . curNS($identifier); 617c3437056SNickeau if (page_exists($startPage)) { 618c3437056SNickeau $res = $this->performNotFoundRedirect($startPage, self::TARGET_ORIGIN_START_PAGE); 619c3437056SNickeau if ($res) { 620c3437056SNickeau return; 621c3437056SNickeau } 622c3437056SNickeau } 623c3437056SNickeau break; 624c3437056SNickeau 625c3437056SNickeau case self::GO_TO_BEST_PAGE_NAME: 626c3437056SNickeau 627c3437056SNickeau $bestPageId = null; 628c3437056SNickeau 629c3437056SNickeau $bestPage = $this->getBestPage($identifier); 630c3437056SNickeau $bestPageId = $bestPage['id']; 631c3437056SNickeau $scorePageName = $bestPage['score']; 632c3437056SNickeau 633c3437056SNickeau // Get Score from a Namespace 634c3437056SNickeau $bestNamespace = $this->scoreBestNamespace($identifier); 635c3437056SNickeau $bestNamespaceId = $bestNamespace['namespace']; 636c3437056SNickeau $namespaceScore = $bestNamespace['score']; 637c3437056SNickeau 638c3437056SNickeau // Compare the two score 639c3437056SNickeau if ($scorePageName > 0 or $namespaceScore > 0) { 640c3437056SNickeau if ($scorePageName > $namespaceScore) { 641c3437056SNickeau $this->performNotFoundRedirect($bestPageId, self::TARGET_ORIGIN_BEST_PAGE_NAME); 642c3437056SNickeau } else { 643c3437056SNickeau $this->performNotFoundRedirect($bestNamespaceId, self::TARGET_ORIGIN_BEST_PAGE_NAME); 644c3437056SNickeau } 645c3437056SNickeau return; 646c3437056SNickeau } 647c3437056SNickeau break; 648c3437056SNickeau 649c3437056SNickeau case self::GO_TO_BEST_NAMESPACE: 650c3437056SNickeau 651c3437056SNickeau $scoreNamespace = $this->scoreBestNamespace($identifier); 652c3437056SNickeau $bestNamespaceId = $scoreNamespace['namespace']; 653c3437056SNickeau $score = $scoreNamespace['score']; 654c3437056SNickeau 655c3437056SNickeau if ($score > 0) { 656c3437056SNickeau $this->performNotFoundRedirect($bestNamespaceId, self::TARGET_ORIGIN_BEST_NAMESPACE); 657c3437056SNickeau return; 658c3437056SNickeau } 659c3437056SNickeau break; 660c3437056SNickeau 661c3437056SNickeau case self::GO_TO_SEARCH_ENGINE: 662c3437056SNickeau 663c3437056SNickeau $this->redirectToSearchEngine(); 664c3437056SNickeau 665c3437056SNickeau return; 666c3437056SNickeau 667c3437056SNickeau // End Switch Action 668c3437056SNickeau } 669c3437056SNickeau 670c3437056SNickeau // End While Action 671c3437056SNickeau } 672c3437056SNickeau 673c3437056SNickeau 674c3437056SNickeau } 675c3437056SNickeau 676c3437056SNickeau 677c3437056SNickeau /** 678c3437056SNickeau * getBestNamespace 679c3437056SNickeau * Return a list with 'BestNamespaceId Score' 680c3437056SNickeau * @param $id 681c3437056SNickeau * @return array 682c3437056SNickeau */ 683c3437056SNickeau private 684c3437056SNickeau function scoreBestNamespace($id) 685c3437056SNickeau { 686c3437056SNickeau 687c3437056SNickeau global $conf; 688c3437056SNickeau 689c3437056SNickeau // Parameters 690c3437056SNickeau $pageNameSpace = getNS($id); 691c3437056SNickeau 692c3437056SNickeau // If the page has an existing namespace start page take it, other search other namespace 693c3437056SNickeau $startPageNameSpace = $pageNameSpace . ":"; 694c3437056SNickeau $dateAt = ''; 695c3437056SNickeau // $startPageNameSpace will get a full path (ie with start or the namespace 696c3437056SNickeau resolve_pageid($pageNameSpace, $startPageNameSpace, $exists, $dateAt, true); 697c3437056SNickeau if (page_exists($startPageNameSpace)) { 698c3437056SNickeau $nameSpaces = array($startPageNameSpace); 699c3437056SNickeau } else { 700c3437056SNickeau $nameSpaces = ft_pageLookup($conf['start']); 701c3437056SNickeau } 702c3437056SNickeau 703c3437056SNickeau // Parameters and search the best namespace 704c3437056SNickeau $pathNames = explode(':', $pageNameSpace); 705c3437056SNickeau $bestNbWordFound = 0; 706c3437056SNickeau $bestNamespaceId = ''; 707c3437056SNickeau foreach ($nameSpaces as $nameSpace) { 708c3437056SNickeau 709c3437056SNickeau $nbWordFound = 0; 710c3437056SNickeau foreach ($pathNames as $pathName) { 711c3437056SNickeau if (strlen($pathName) > 2) { 712c3437056SNickeau $nbWordFound = $nbWordFound + substr_count($nameSpace, $pathName); 713c3437056SNickeau } 714c3437056SNickeau } 715c3437056SNickeau if ($nbWordFound > $bestNbWordFound) { 716c3437056SNickeau // Take only the smallest namespace 717c3437056SNickeau if (strlen($nameSpace) < strlen($bestNamespaceId) or $nbWordFound > $bestNbWordFound) { 718c3437056SNickeau $bestNbWordFound = $nbWordFound; 719c3437056SNickeau $bestNamespaceId = $nameSpace; 720c3437056SNickeau } 721c3437056SNickeau } 722c3437056SNickeau } 723c3437056SNickeau 724c3437056SNickeau $startPageFactor = $this->getConf('WeightFactorForStartPage'); 725c3437056SNickeau $nameSpaceFactor = $this->getConf('WeightFactorForSameNamespace'); 726c3437056SNickeau if ($bestNbWordFound > 0) { 727c3437056SNickeau $bestNamespaceScore = $bestNbWordFound * $nameSpaceFactor + $startPageFactor; 728c3437056SNickeau } else { 729c3437056SNickeau $bestNamespaceScore = 0; 730c3437056SNickeau } 731c3437056SNickeau 732c3437056SNickeau 733c3437056SNickeau return array( 734c3437056SNickeau 'namespace' => $bestNamespaceId, 735c3437056SNickeau 'score' => $bestNamespaceScore 736c3437056SNickeau ); 737c3437056SNickeau 738c3437056SNickeau } 739c3437056SNickeau 740c3437056SNickeau /** 741c3437056SNickeau * @param $event 742c3437056SNickeau */ 743c3437056SNickeau private 744c3437056SNickeau function gotToEditMode(&$event) 745c3437056SNickeau { 746c3437056SNickeau global $ACT; 747c3437056SNickeau $ACT = 'edit'; 748c3437056SNickeau 749c3437056SNickeau } 750c3437056SNickeau 751c3437056SNickeau 752c3437056SNickeau /** 753c3437056SNickeau * Redirect to an internal page ie: 754c3437056SNickeau * * on the same domain 755c3437056SNickeau * * no HTTP redirect 756c3437056SNickeau * * id rewrite 757c3437056SNickeau * @param string $targetPageId - target page id 758c3437056SNickeau * @param string $targetOriginId - the source of the target (redirect) 759c3437056SNickeau * @return bool - return true if the user has the permission and that the redirect was done 760c3437056SNickeau * @throws Exception 761c3437056SNickeau */ 762c3437056SNickeau private 763c3437056SNickeau function executeTransparentRedirect(string $targetPageId, string $targetOriginId): bool 764c3437056SNickeau { 765c3437056SNickeau /** 766c3437056SNickeau * Because we set the ID globally for the ID redirect 76704fd306cSNickeau * we make sure that this is not a {@link MarkupPath} 768c3437056SNickeau * object otherwise we got an error in the {@link \ComboStrap\AnalyticsMenuItem} 769c3437056SNickeau * because the constructor takes it {@link \dokuwiki\Menu\Item\AbstractItem} 770c3437056SNickeau */ 771c3437056SNickeau if (is_object($targetPageId)) { 772c3437056SNickeau $class = get_class($targetPageId); 773c3437056SNickeau LogUtility::msg("The parameters targetPageId ($targetPageId) is an object of the class ($class) and it should be a page id"); 774c3437056SNickeau } 775c3437056SNickeau 776c3437056SNickeau if (is_object($targetOriginId)) { 777c3437056SNickeau $class = get_class($targetOriginId); 778c3437056SNickeau LogUtility::msg("The parameters targetOriginId ($targetOriginId) is an object of the class ($class) and it should be a page id"); 779c3437056SNickeau } 780c3437056SNickeau 781c3437056SNickeau // If the user does not have the right to see the target page 782c3437056SNickeau // don't do anything 783c3437056SNickeau if (!(Identity::isReader($targetPageId))) { 784c3437056SNickeau return false; 785c3437056SNickeau } 786c3437056SNickeau 787c3437056SNickeau // Change the id 788c3437056SNickeau global $ID; 789c3437056SNickeau global $INFO; 790c3437056SNickeau $sourceId = $ID; 791c3437056SNickeau $ID = $targetPageId; 79204fd306cSNickeau if (isset($_REQUEST["id"])) { 79304fd306cSNickeau $_REQUEST["id"] = $targetPageId; 79404fd306cSNickeau } 79504fd306cSNickeau if (isset($_GET["id"])) { 79604fd306cSNickeau $_GET["id"] = $targetPageId; 79704fd306cSNickeau } 7984cadd4f8SNickeau 799c3437056SNickeau /** 8004cadd4f8SNickeau * Refresh the $INFO data 8014cadd4f8SNickeau * 8024cadd4f8SNickeau * the info attributes are used elsewhere 8034cadd4f8SNickeau * 'id': for the sidebar 8044cadd4f8SNickeau * 'exist' : for the meta robot = noindex,follow, see {@link tpl_metaheaders()} 8054cadd4f8SNickeau * 'rev' : for the edit button to be sure that the page is still the same 806c3437056SNickeau */ 8074cadd4f8SNickeau $INFO = pageinfo(); 808c3437056SNickeau 809c3437056SNickeau /** 810c3437056SNickeau * Not compatible with 811c3437056SNickeau * https://www.dokuwiki.org/config:send404 is enabled 812c3437056SNickeau * 813c3437056SNickeau * This check happens before that dokuwiki is started 814c3437056SNickeau * and send an header in doku.php 815c3437056SNickeau * 816c3437056SNickeau * We send a warning 817c3437056SNickeau */ 818c3437056SNickeau global $conf; 819c3437056SNickeau if ($conf['send404'] == true) { 820c3437056SNickeau 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); 821c3437056SNickeau } 822c3437056SNickeau 823c3437056SNickeau // Redirection 824c3437056SNickeau $this->logRedirection($sourceId, $targetPageId, $targetOriginId, self::REDIRECT_TRANSPARENT_METHOD); 825c3437056SNickeau 826c3437056SNickeau return true; 827c3437056SNickeau 828c3437056SNickeau } 829c3437056SNickeau 83004fd306cSNickeau private function executePermanentRedirect(string $targetIdOrUrl, $targetOrigin): bool 831c3437056SNickeau { 83204fd306cSNickeau return $this->executeHttpRedirect($targetIdOrUrl, $targetOrigin, self::REDIRECT_PERMANENT_METHOD); 833c3437056SNickeau } 834c3437056SNickeau 835c3437056SNickeau /** 836c3437056SNickeau * The general HTTP Redirect method to an internal page 837c3437056SNickeau * where the redirection method decide which type of redirection 83804fd306cSNickeau * @param string $targetIdOrUrl - a dokuwiki id or an url 839c3437056SNickeau * @param string $targetOrigin - the origin of the target (the algorithm used to get the target origin) 840c3437056SNickeau * @param string $method - the redirection method 841c3437056SNickeau */ 842c3437056SNickeau private 84304fd306cSNickeau function executeHttpRedirect(string $targetIdOrUrl, string $targetOrigin, string $method): bool 844c3437056SNickeau { 845c3437056SNickeau 846c3437056SNickeau global $ID; 847c3437056SNickeau 848c3437056SNickeau 849c3437056SNickeau // Log the redirections 85004fd306cSNickeau $this->logRedirection($ID, $targetIdOrUrl, $targetOrigin, $method); 851c3437056SNickeau 852c3437056SNickeau 85304fd306cSNickeau // An http external url ? 85404fd306cSNickeau try { 8555b0932efSgerardnico $isHttpUrl = Url::createFromString($targetIdOrUrl)->isHttpUrl(); 85604fd306cSNickeau } catch (ExceptionBadSyntax|ExceptionBadArgument $e) { 8575b0932efSgerardnico $isHttpUrl = false; 85804fd306cSNickeau } 85904fd306cSNickeau 86082a60d03SNickeau // If there is a bug in the isValid function for an internal url 86182a60d03SNickeau // We get a loop. 86282a60d03SNickeau // The Url becomes the id, the id is unknown and we do a redirect again 86382a60d03SNickeau // 86482a60d03SNickeau // We check then if the target starts with the base url 86582a60d03SNickeau // if this is the case, it's valid 8665b0932efSgerardnico if (!$isHttpUrl && strpos($targetIdOrUrl, DOKU_URL) === 0) { 8675b0932efSgerardnico $isHttpUrl = true; 86882a60d03SNickeau } 8695b0932efSgerardnico if ($isHttpUrl) { 870c3437056SNickeau 871c3437056SNickeau // defend against HTTP Response Splitting 872c3437056SNickeau // https://owasp.org/www-community/attacks/HTTP_Response_Splitting 87304fd306cSNickeau $targetUrl = stripctl($targetIdOrUrl); 874c3437056SNickeau 875c3437056SNickeau } else { 876c3437056SNickeau 877c3437056SNickeau 878c3437056SNickeau // Explode the page ID and the anchor (#) 87904fd306cSNickeau $link = explode('#', $targetIdOrUrl, 2); 880c3437056SNickeau 88111d09b86Sgerardnico $url = UrlEndpoint::createDokuUrl(); 882c3437056SNickeau 8835b0932efSgerardnico $urlParams = []; 884c3437056SNickeau // if this is search engine redirect 885c3437056SNickeau if ($targetOrigin == self::TARGET_ORIGIN_SEARCH_ENGINE) { 886c3437056SNickeau $replacementPart = array(':', '_', '-'); 887c3437056SNickeau $query = str_replace($replacementPart, ' ', $ID); 88811d09b86Sgerardnico $url->setQueryParameter(ExecutionContext::DO_ATTRIBUTE, ExecutionContext::SEARCH_ACTION); 88911d09b86Sgerardnico $url->setQueryParameter("q", $query); 890c3437056SNickeau } 891c3437056SNickeau 8925b0932efSgerardnico /** 8935b0932efSgerardnico * Doing a permanent redirect with a added query string 8945b0932efSgerardnico * create a new page url on the search engine 8955b0932efSgerardnico * 8965b0932efSgerardnico * ie 8975b0932efSgerardnico * http://host/page 8985b0932efSgerardnico * is not the same 8995b0932efSgerardnico * than 9005b0932efSgerardnico * http://host/page?whatever 9015b0932efSgerardnico * 9025b0932efSgerardnico * We can't pass query string otherwise, we get 90349b8fb24Sgerardnico * the SEO warning / error 9045b0932efSgerardnico * `Alternative page with proper canonical tag` 90511d09b86Sgerardnico * 90611d09b86Sgerardnico * Use HTTP X header for debug 9075b0932efSgerardnico */ 9085b0932efSgerardnico if ($method !== self::REDIRECT_PERMANENT_METHOD) { 90911d09b86Sgerardnico $url->setQueryParameter(action_plugin_combo_routermessage::ORIGIN_PAGE, $ID); 91011d09b86Sgerardnico $url->setQueryParameter(action_plugin_combo_routermessage::ORIGIN_TYPE, $targetOrigin); 9115b0932efSgerardnico } 9125b0932efSgerardnico 91311d09b86Sgerardnico $id = $link[0]; 91411d09b86Sgerardnico $url->setQueryParameter(DokuwikiId::DOKUWIKI_ID_ATTRIBUTE, $id); 91570bbd7f1Sgerardnico if (array_key_exists(1, $link)) { 91611d09b86Sgerardnico $url->setFragment($link[1]); 917c3437056SNickeau } 91811d09b86Sgerardnico $targetUrl = $url->toAbsoluteUrlString(); 919c3437056SNickeau 920c3437056SNickeau } 921c3437056SNickeau 922c3437056SNickeau /** 923c3437056SNickeau * The dokuwiki function {@link send_redirect()} 924c3437056SNickeau * set the `Location header` and in php, the header function 925c3437056SNickeau * in this case change the status code to 302 Arghhhh. 926c3437056SNickeau * The code below is adapted from this function {@link send_redirect()} 927c3437056SNickeau */ 928c3437056SNickeau global $MSG; // are there any undisplayed messages? keep them in session for display 929c3437056SNickeau if (isset($MSG) && count($MSG) && !defined('NOSESSION')) { 930c3437056SNickeau //reopen session, store data and close session again 931c3437056SNickeau @session_start(); 932c3437056SNickeau $_SESSION[DOKU_COOKIE]['msg'] = $MSG; 933c3437056SNickeau } 934c3437056SNickeau session_write_close(); // always close the session 935c3437056SNickeau 936c3437056SNickeau switch ($method) { 9375b0932efSgerardnico 938c3437056SNickeau case self::REDIRECT_PERMANENT_METHOD: 93904fd306cSNickeau ExecutionContext::getActualOrCreateFromEnv() 94004fd306cSNickeau ->response() 94104fd306cSNickeau ->setStatus(HttpResponseStatus::PERMANENT_REDIRECT) 942c3437056SNickeau ->addHeader(self::LOCATION_HEADER_PREFIX . $targetUrl) 94304fd306cSNickeau ->end(); 944c3437056SNickeau return true; 9455b0932efSgerardnico 946c3437056SNickeau case self::REDIRECT_NOTFOUND_METHOD: 947c3437056SNickeau 9485b0932efSgerardnico 949c3437056SNickeau // Empty 404 body to not get the standard 404 page of the browser 950c3437056SNickeau // but a blank page to avoid a sort of FOUC. 951c3437056SNickeau // ie the user see a page briefly 95204fd306cSNickeau ExecutionContext::getActualOrCreateFromEnv() 95304fd306cSNickeau ->response() 95404fd306cSNickeau ->setStatus(HttpResponseStatus::NOT_FOUND) 955c3437056SNickeau ->addHeader(self::REFRESH_HEADER_PREFIX . $targetUrl) 95604fd306cSNickeau ->setBody(self::PAGE_404, Mime::getHtml()) 95704fd306cSNickeau ->end(); 958c3437056SNickeau return true; 959c3437056SNickeau 960c3437056SNickeau default: 961c3437056SNickeau LogUtility::msg("The method ($method) is not an http redirection"); 962c3437056SNickeau return false; 963c3437056SNickeau } 964c3437056SNickeau 965c3437056SNickeau 966c3437056SNickeau } 967c3437056SNickeau 968c3437056SNickeau /** 969c3437056SNickeau * @param $id 970c3437056SNickeau * @return array 971c3437056SNickeau */ 972c3437056SNickeau private 973c3437056SNickeau function getBestPage($id): array 974c3437056SNickeau { 975c3437056SNickeau 976c3437056SNickeau // The return parameters 977c3437056SNickeau $bestPageId = null; 978c3437056SNickeau $scorePageName = null; 979c3437056SNickeau 980c3437056SNickeau // Get Score from a page 981c3437056SNickeau $pageName = noNS($id); 982c3437056SNickeau $pagesWithSameName = ft_pageLookup($pageName); 983c3437056SNickeau if (count($pagesWithSameName) > 0) { 984c3437056SNickeau 985c3437056SNickeau // Search same namespace in the page found than in the Id page asked. 986c3437056SNickeau $bestNbWordFound = 0; 987c3437056SNickeau 988c3437056SNickeau 989c3437056SNickeau $wordsInPageSourceId = explode(':', $id); 990c3437056SNickeau foreach ($pagesWithSameName as $targetPageId => $title) { 991c3437056SNickeau 992c3437056SNickeau // Nb of word found in the target page id 993c3437056SNickeau // that are in the source page id 994c3437056SNickeau $nbWordFound = 0; 995c3437056SNickeau foreach ($wordsInPageSourceId as $word) { 996c3437056SNickeau $nbWordFound = $nbWordFound + substr_count($targetPageId, $word); 997c3437056SNickeau } 998c3437056SNickeau 999c3437056SNickeau if ($bestPageId == null) { 1000c3437056SNickeau 1001c3437056SNickeau $bestNbWordFound = $nbWordFound; 1002c3437056SNickeau $bestPageId = $targetPageId; 1003c3437056SNickeau 1004c3437056SNickeau } else { 1005c3437056SNickeau 1006c3437056SNickeau if ($nbWordFound >= $bestNbWordFound && strlen($bestPageId) > strlen($targetPageId)) { 1007c3437056SNickeau 1008c3437056SNickeau $bestNbWordFound = $nbWordFound; 1009c3437056SNickeau $bestPageId = $targetPageId; 1010c3437056SNickeau 1011c3437056SNickeau } 1012c3437056SNickeau 1013c3437056SNickeau } 1014c3437056SNickeau 1015c3437056SNickeau } 1016c3437056SNickeau $scorePageName = $this->getConf('WeightFactorForSamePageName') + ($bestNbWordFound - 1) * $this->getConf('WeightFactorForSameNamespace'); 1017c3437056SNickeau return array( 1018c3437056SNickeau 'id' => $bestPageId, 1019c3437056SNickeau 'score' => $scorePageName); 1020c3437056SNickeau } 1021c3437056SNickeau return array( 1022c3437056SNickeau 'id' => $bestPageId, 1023c3437056SNickeau 'score' => $scorePageName 1024c3437056SNickeau ); 1025c3437056SNickeau 1026c3437056SNickeau } 1027c3437056SNickeau 1028c3437056SNickeau 1029c3437056SNickeau /** 1030c3437056SNickeau * Redirect to the search engine 1031c3437056SNickeau */ 1032c3437056SNickeau private 1033c3437056SNickeau function redirectToSearchEngine() 1034c3437056SNickeau { 1035c3437056SNickeau 1036c3437056SNickeau global $ID; 1037c3437056SNickeau $this->performNotFoundRedirect($ID, self::TARGET_ORIGIN_SEARCH_ENGINE); 1038c3437056SNickeau 1039c3437056SNickeau } 1040c3437056SNickeau 1041c3437056SNickeau 1042c3437056SNickeau /** 1043c3437056SNickeau * 1044c3437056SNickeau * * For a conf file, it will update the Redirection Action Data as Referrer, Count Of Redirection, Redirection Date 1045c3437056SNickeau * * For a SQlite database, it will add a row into the log 1046c3437056SNickeau * 1047c3437056SNickeau * @param string $sourcePageId 1048c3437056SNickeau * @param $targetPageId 1049c3437056SNickeau * @param $algorithmic 1050c3437056SNickeau * @param $method - http or rewrite 1051c3437056SNickeau */ 1052c3437056SNickeau function logRedirection(string $sourcePageId, $targetPageId, $algorithmic, $method) 1053c3437056SNickeau { 1054c3437056SNickeau 1055c3437056SNickeau $row = array( 1056c3437056SNickeau "TIMESTAMP" => date("c"), 1057c3437056SNickeau "SOURCE" => $sourcePageId, 1058c3437056SNickeau "TARGET" => $targetPageId, 105970bbd7f1Sgerardnico "REFERRER" => $_SERVER['HTTP_REFERER'] ?? null, 1060c3437056SNickeau "TYPE" => $algorithmic, 1061c3437056SNickeau "METHOD" => $method 1062c3437056SNickeau ); 1063c3437056SNickeau $request = Sqlite::createOrGetBackendSqlite() 1064c3437056SNickeau ->createRequest() 1065c3437056SNickeau ->setTableRow('redirections_log', $row); 1066c3437056SNickeau try { 1067c3437056SNickeau $request 1068c3437056SNickeau ->execute(); 106904fd306cSNickeau } catch (ExceptionCompile $e) { 1070c3437056SNickeau LogUtility::msg("Redirection Log Insert Error. {$e->getMessage()}"); 1071c3437056SNickeau } finally { 1072c3437056SNickeau $request->close(); 1073c3437056SNickeau } 1074c3437056SNickeau 1075c3437056SNickeau 1076c3437056SNickeau } 1077c3437056SNickeau 1078c3437056SNickeau /** 1079c3437056SNickeau * This function check if there is a redirection declared 1080c3437056SNickeau * in the redirection table 1081c3437056SNickeau * @return bool - true if a rewrite or redirection occurs 1082c3437056SNickeau * @throws Exception 1083c3437056SNickeau */ 1084c3437056SNickeau private function processingPageRules(): bool 1085c3437056SNickeau { 1086c3437056SNickeau global $ID; 1087c3437056SNickeau 1088c3437056SNickeau $calculatedTarget = null; 1089c3437056SNickeau $ruleMatcher = null; // Used in a warning message if the target page does not exist 1090c3437056SNickeau // Known redirection in the table 1091c3437056SNickeau // Get the page from redirection data 1092c3437056SNickeau $rules = $this->pageRules->getRules(); 1093c3437056SNickeau foreach ($rules as $rule) { 1094c3437056SNickeau 1095c3437056SNickeau $ruleMatcher = strtolower($rule[PageRules::MATCHER_NAME]); 1096c3437056SNickeau $ruleTarget = $rule[PageRules::TARGET_NAME]; 1097c3437056SNickeau 1098c3437056SNickeau // Glob to Rexgexp 109904fd306cSNickeau $regexpPattern = '/' . str_replace("*", "(.*)", $ruleMatcher) . '/i'; 1100c3437056SNickeau 1101c3437056SNickeau // Match ? 1102c3437056SNickeau // https://www.php.net/manual/en/function.preg-match.php 110386867397Sgerardnico $pregMatchResult = @preg_match($regexpPattern, $ID, $matches); 110486867397Sgerardnico if ($pregMatchResult === false) { 110586867397Sgerardnico // The `if` to take into account this problem 110686867397Sgerardnico // PHP Warning: preg_match(): Unknown modifier 'd' in /opt/www/datacadamia.com/lib/plugins/combo/action/router.php on line 972 110786867397Sgerardnico LogUtility::log2file("processing Page Rules An error occurred with the pattern ($regexpPattern)", LogUtility::LVL_MSG_WARNING); 110886867397Sgerardnico return false; 110986867397Sgerardnico } 111086867397Sgerardnico if ($pregMatchResult) { 1111c3437056SNickeau $calculatedTarget = $ruleTarget; 1112c3437056SNickeau foreach ($matches as $key => $match) { 1113c3437056SNickeau if ($key == 0) { 1114c3437056SNickeau continue; 1115c3437056SNickeau } else { 1116c3437056SNickeau $calculatedTarget = str_replace('$' . $key, $match, $calculatedTarget); 1117c3437056SNickeau } 1118c3437056SNickeau } 1119c3437056SNickeau break; 1120c3437056SNickeau } 1121c3437056SNickeau } 1122c3437056SNickeau 1123c3437056SNickeau if ($calculatedTarget == null) { 1124c3437056SNickeau return false; 1125c3437056SNickeau } 1126c3437056SNickeau 1127c3437056SNickeau // If this is an external redirect (other domain) 112804fd306cSNickeau try { 112904fd306cSNickeau $isHttpUrl = Url::createFromString($calculatedTarget)->isHttpUrl(); 113004fd306cSNickeau } catch (ExceptionBadSyntax $e) { 113104fd306cSNickeau $isHttpUrl = false; 113204fd306cSNickeau } 113304fd306cSNickeau if ($isHttpUrl) { 1134c3437056SNickeau $this->executeHttpRedirect($calculatedTarget, self::TARGET_ORIGIN_PAGE_RULES, self::REDIRECT_PERMANENT_METHOD); 1135c3437056SNickeau return true; 1136c3437056SNickeau } 1137c3437056SNickeau 1138c3437056SNickeau // If the page exist 1139c3437056SNickeau if (page_exists($calculatedTarget)) { 1140c3437056SNickeau 1141c3437056SNickeau // This is DokuWiki Id and should always be lowercase 1142c3437056SNickeau // The page rule may have change that 1143c3437056SNickeau $calculatedTarget = strtolower($calculatedTarget); 1144d0abe7fcSgerardnico $res = $this->executeHttpRedirect($calculatedTarget, self::TARGET_ORIGIN_PAGE_RULES, self::REDIRECT_PERMANENT_METHOD); 1145c3437056SNickeau if ($res) { 1146c3437056SNickeau return true; 1147c3437056SNickeau } else { 1148c3437056SNickeau return false; 1149c3437056SNickeau } 1150c3437056SNickeau 1151c3437056SNickeau } else { 1152c3437056SNickeau 1153c3437056SNickeau LogUtility::msg("The calculated target page ($calculatedTarget) (for the non-existing page `$ID` with the matcher `$ruleMatcher`) does not exist", LogUtility::LVL_MSG_ERROR); 1154c3437056SNickeau return false; 1155c3437056SNickeau 1156c3437056SNickeau } 1157c3437056SNickeau 1158c3437056SNickeau } 1159c3437056SNickeau 1160c3437056SNickeau private function performNotFoundRedirect(string $targetId, string $origin): bool 1161c3437056SNickeau { 1162c3437056SNickeau return $this->executeHttpRedirect($targetId, $origin, self::REDIRECT_NOTFOUND_METHOD); 1163c3437056SNickeau } 1164c3437056SNickeau 1165c3437056SNickeau 1166c3437056SNickeau} 1167