stylehub/lib/routing.php
2024-01-16 20:57:51 +01:00

91 lines
2.9 KiB
PHP

<?php
function getProtocol(){
if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
return "https://";
} else {
/** @noinspection HttpUrlsUsage */
return "http://";
}
}
function initRouter(){
global $routerRequest;
global $routerConfig;
$routerRequest["protocol"] = getProtocol();
$routerRequest["requestAddress"] = array_slice(explode('.', $_SERVER['HTTP_HOST']), -3, 3); //get the last 3 elements
$needsRedirect = false;
if(count($routerRequest["requestAddress"]) < 3){
// Root domain accessed directly
$needsRedirect = true;
} else {
$routerRequest["subdomain"] = basename($routerRequest["requestAddress"][0]);
$routerRequest["domain"] = basename($routerRequest["requestAddress"][1]);
$routerRequest["tld"] = basename($routerRequest["requestAddress"][2]);
$routerRequest["page_name"] = basename($_SERVER["QUERY_STRING"]);
if (empty($routerRequest["page_name"])){
$needsRedirect = true;
}
}
if ($needsRedirect) {
$redirectAddress = implode('.', $routerRequest["requestAddress"]);
header("Location: " . $routerRequest["protocol"] . $redirectAddress . "/" . $routerConfig["default_page"]);
}
return !$needsRedirect;
}
function renderDynamicPage($page_file)
{
require_once $page_file;
return render();
}
function getPage($page_name = null){
global $routerConfig;
global $routerRequest;
if(!$page_name){
$page_name = $routerRequest["page_name"];
}
$dynamic_page_file = $routerConfig["page_dir"] . $routerRequest["subdomain"] . "/" . $page_name . ".php";
$page_file = $routerConfig["page_dir"] . $routerRequest["subdomain"] . "/" . $page_name . ".html";
$dynamic_page_file_global = $routerConfig["page_dir"] . "global/" . $page_name . ".php";
$page_file_global = $routerConfig["page_dir"] . "global/" . $page_name . ".html";
$skeleton = file_get_contents($routerConfig["template_dir"] . "skeleton.html");
$nav = file_get_contents($routerConfig["template_dir"] . "nav.html");
if (file_exists($dynamic_page_file_global)){
$page = renderDynamicPage($dynamic_page_file_global);
}
elseif (file_exists($page_file_global)){
$page = file_get_contents($page_file_global);
}
elseif (file_exists($dynamic_page_file)){
$page = renderDynamicPage($dynamic_page_file);
}
elseif (file_exists($page_file)){
$page = file_get_contents($page_file);
}
else{
$page = file_get_contents($routerConfig["template_dir"] . "404.html");
}
$navpages = generateNavigation();
$nav = str_replace("__NAV_PAGES__", $navpages, $nav);
$out = $skeleton;
$out = str_replace("__TEMPLATE__NAV__", $nav, $out);
$out = str_replace("__TEMPLATE__PAGE__", $page, $out);
return str_replace("__TEMPLATE_PAGE_NAME__", $page_name, $out);
}