diff --git a/assets/script.js b/assets/script.js index c3d8c8a..e61c1e3 100644 --- a/assets/script.js +++ b/assets/script.js @@ -1,67 +1,52 @@ +async function doAction(url, requestData, successMessage, failureMessage, silent = false) { + try { + const params = new URLSearchParams(); -function doAccountAction(requestData, successMessage, failureMessage, silent=false) { - return fetch('/account', { - method: 'POST', - body: requestData, - }) - .then(response => { - if (!response.ok) { - throw new Error(`HTTP error! Status: ${response.status}`); - } - return response.json(); - }) - .then(data => { - if(!silent) { - handleResponse(data, successMessage, failureMessage); - } - return data; // Returning the response data for further processing - }) - .catch((error) => { - console.error('Error:', error); + for (const key in requestData) { + params.append(key, requestData[key]); + } + + const response = await fetch(url, { + method: 'POST', + body: params, }); -} + if (!response.ok) { + throw new Error(`HTTP error! Status: ${response.status}`); + } + const data = await response.json(); -function handlePageResponse(data){ - if(data.Navigation){ - document.getElementById("navbar").innerHTML = data.Navigation; - } - if(data.Page){ - document.getElementById("pagearea").innerHTML = data.Page; - // if(data.PageLocation){ - // history.pushState({}, "", data.PageLocation); - // } + if (!silent) { + handleResponse(data, successMessage, failureMessage); + } + + return data; + } catch (error) { + console.error('Error:', error); } } -function doPageAction(requestData){ - return fetch('/page', { - method: 'POST', - body: requestData, - }) - .then(response => { - if (!response.ok) { - throw new Error(`HTTP error! Status: ${response.status}`); - } - return response.json(); - }) - .then(data => { - handlePageResponse(data); - }) - .catch((error) => { - console.error('Error:', error); - }); +function handlePageResponse(data) { + const navbar = document.getElementById("navbar"); + const pageArea = document.getElementById("pagearea"); + + if (data.Navigation) { + navbar.innerHTML = data.Navigation; + } + + if (data.Page) { + pageArea.innerHTML = data.Page; + } } -function displayList(data, element_id, delete_function=null) { - const tableContainer = document.getElementById(element_id); +function displayList(data, elementId, deleteFunction) { + const tableContainer = document.getElementById(elementId); tableContainer.innerHTML = ""; // Clear previous content const table = document.createElement("table"); table.classList.add("list-table"); - // Create header row const headerRow = table.insertRow(0); for (const key in data[0]) { const th = document.createElement("th"); @@ -69,13 +54,12 @@ function displayList(data, element_id, delete_function=null) { headerRow.appendChild(th); } - if(typeof delete_function === "function") { + if (typeof deleteFunction === "function") { const th = document.createElement("th"); th.appendChild(document.createTextNode("Delete")); headerRow.appendChild(th); } - // Create data rows for (const line of data) { const dataRow = table.insertRow(); for (const key in line) { @@ -83,14 +67,12 @@ function displayList(data, element_id, delete_function=null) { td.appendChild(document.createTextNode(line[key])); dataRow.appendChild(td); } - if(typeof delete_function === "function") { + if (typeof deleteFunction === "function") { const td = document.createElement("td"); - let delete_button = document.createElement('button'); - delete_button.textContent = "Delete" - delete_button.onclick = function (){ - delete_function(line.ID); - } - td.appendChild(delete_button); + const deleteButton = document.createElement('button'); + deleteButton.textContent = "Delete"; + deleteButton.onclick = () => deleteFunction(line.ID); + td.appendChild(deleteButton); dataRow.appendChild(td); } } @@ -98,85 +80,45 @@ function displayList(data, element_id, delete_function=null) { tableContainer.appendChild(table); } -function handleResponse(data, SuccessMessage, failureMessage) { - const StatusMessageElement = document.getElementById("StatusMessage"); +async function doPageAction(requestData, wantsReturn = false) { + try { + const response = await fetch('/page', { + method: 'POST', + body: new URLSearchParams(requestData), + }); - if (data.Status === 'Success') { - StatusMessageElement.innerText = SuccessMessage; - } else { - StatusMessageElement.innerText = failureMessage; + if (!response.ok) { + throw new Error(`HTTP error! Status: ${response.status}`); + } + + if (wantsReturn) { + return await response.json(); + } else { + const data = await response.json(); + handlePageResponse(data); + } + } catch (error) { + console.error('Error:', error); } - - // Show the status message - StatusMessageElement.style.display = "block"; - setTimeout(() => { - // Hide the status message after 3 seconds - StatusMessageElement.style.opacity = "0"; - setTimeout(() => { - StatusMessageElement.style.display = "none"; - // Reset opacity for future messages - StatusMessageElement.style.opacity = "1"; - }, 500); - }, 3000); -} - -function navigateTo(site, page){ - const data = new URLSearchParams(); - data.append("action", "getPage"); - data.append("site", site); - data.append("page", page); - doPageAction(data).then(() => { - localStorage.setItem("currentSite", site); - localStorage.setItem("currentPage", page); - onPageLoad(); - // Expected output: "Success!" - }); -} - -function softReload(){ - navigateTo(localStorage.getItem("currentSite"), localStorage.getItem("currentPage")); -} - -function refreshNavbar(){ - const data = new URLSearchParams(); - data.append("action", "getNavigation"); - doPageAction(data); -} - -function logout() { - const data = new URLSearchParams(); - data.append("action", "logout"); - - doAccountAction(data, "Logout Successful!", "Logout failed.").then(() => { - refreshNavbar(); - navigateTo("", localStorage.getItem("defaultPage")); - // Expected output: "Success!" - }); } function initAjax() { - let links = document.querySelectorAll('.navsite_link, .navpage_link'); + const links = document.querySelectorAll('.navsite_link, .navpage_link'); -// Add click event listener to each link links.forEach(function (link) { link.addEventListener('click', function (e) { e.preventDefault(); - - // Get page and site information let site = this.dataset.site; let page = this.dataset.page; - if (site && page) { navigateTo(site, page); } - - // You can use this information to update the URL or perform other actions }); }); onPageLoad(); } -document.addEventListener('DOMContentLoaded', initAjax); +document.addEventListener('DOMContentLoaded', initAjax); function onPageLoad(){ let currentSite = localStorage.getItem("currentSite"); @@ -192,7 +134,41 @@ function onPageLoad(){ } } -//Login +function navigateTo(site, page){ + const data = { + action: "getPage", + site: site, + page: page, + }; + let pageActionStatus = doPageAction(data, true); + if(pageActionStatus.Status === "Success") { + localStorage.setItem("currentSite", site); + localStorage.setItem("currentPage", page); + onPageLoad(); + } +} + +function softReload(){ + navigateTo(localStorage.getItem("currentSite"), localStorage.getItem("currentPage")); +} + +function refreshNavbar(){ + const data = { + action: "getNavigation", + }; + doPageAction(data); +} + +function logout() { + const data = { + action: "logout", + }; + + doAction('/account', data, "Logout Successful!", "Logout failed.").then(() => { + refreshNavbar(); + navigateTo("", localStorage.getItem("defaultPage")); + }); +} function login() { const email = document.getElementById("login_email").value; @@ -202,13 +178,14 @@ function login() { softReload(); } -function doLogin(email, password) { - const data = new URLSearchParams(); - data.append("action", "login"); - data.append("email", email); - data.append("password", password); +async function doLogin(email, password) { + const data = { + action: "login", + email: email, + password: password, + }; - doAccountAction(data, "Login Successful!", "Login failed. Please check your credentials."); + await doAction('/account', data, "Login Successful!", "Login failed. Please check your credentials."); } function register() { @@ -218,38 +195,39 @@ function register() { const password = document.getElementById("register_password").value; const activationToken = document.getElementById("register_activationToken").value; - const data = new URLSearchParams(); - data.append("action", "register"); - data.append("firstname", firstName); - data.append("lastname", lastName); - data.append("email", email); - data.append("password", password); - data.append("activation_token", activationToken); + const data = { + action: "register", + firstname: firstName, + lastname: lastName, + email: email, + password: password, + activation_token: activationToken, + }; doRegister(data); } -function doRegister(requestData) { - doAccountAction(requestData, "Registration Successful!", "Registration failed."); +async function doRegister(requestData) { + await doAction('/account', requestData, "Registration Successful!", "Registration failed."); } - //User settings start function changePassword() { const oldPassword = document.getElementById("changeOldPassword").value; const newPassword = document.getElementById("changeNewPassword").value; - const data = new URLSearchParams(); - data.append("action", "change_password"); - data.append("old_password", oldPassword); - data.append("new_password", newPassword); + const data = { + action: "change_password", + old_password: oldPassword, + new_password: newPassword, + }; doChangePassword(data, "Password change Successful!", "Password change failed."); } -function doChangePassword(requestData, successMessage, failureMessage) { - doAccountAction(requestData, successMessage, failureMessage); +async function doChangePassword(requestData, successMessage, failureMessage) { + await doAction('/account', requestData, successMessage, failureMessage); } function updateUserProfile() { @@ -258,24 +236,26 @@ function updateUserProfile() { const nickname = document.getElementById("updateNickname").value; const minecraftNick = document.getElementById("updateMinecraftNick").value; - const data = new URLSearchParams(); - data.append("action", "update_user_profile"); - data.append("first_name", firstName); - data.append("last_name", lastName); - data.append("nickname", nickname); - data.append("minecraft_nick", minecraftNick); + const data = { + action: "update_user_profile", + first_name: firstName, + last_name: lastName, + nickname: nickname, + minecraft_nick: minecraftNick, + }; - doAccountAction(data, "Profile update Successful!", "Profile update failed."); + doAction('/account', data, "Profile update Successful!", "Profile update failed."); } function updateEmail() { const newEmail = document.getElementById("updateNewEmail").value; - const data = new URLSearchParams(); - data.append("action", "update_user_email"); - data.append("email", newEmail); + const data = { + action: "update_user_email", + email: newEmail, + }; - doAccountAction(data, "Email update Successful!", "Email update failed."); + doAction('/account', data, "Email update Successful!", "Email update failed."); } function populateUserInfoFields(userData) { @@ -286,11 +266,12 @@ function populateUserInfoFields(userData) { document.getElementById("updateNewEmail").value = userData.Email || ""; } -async function getUserInfo() { - const data = new URLSearchParams(); - data.append("action", "get_user_info"); +function getUserInfo() { + const data = { + action: "get_user_info", + }; - const result = await doAccountAction(data, "User info retrieved Successfully!", "User info retrieval failed.", true); + const result = doAction('/account', data, "User info retrieved Successfully!", "User info retrieval failed.", true); if (result && result.Status === "Success") { populateUserInfoFields(result.UserInfo); @@ -301,56 +282,58 @@ async function getUserInfo() { //Admin settings start -async function addActivationCodes() { +function addActivationCodes() { const count = document.getElementById("activationCodeCount").value; - const data = new URLSearchParams(); - data.append("action", "add_activation_codes"); - data.append("count", count); + const data = { + action: "add_activation_codes", + count: count, + }; - const result = await doAccountAction(data, "Activation codes added Successfully!", "Activation codes addition failed."); + const result = doAction('/account', data, "Activation codes added Successfully!", "Activation codes addition failed."); displayList(result.ActivationCodes, "codeListTable", deleteActivationCode); } -async function listUsers() { - const data = new URLSearchParams(); - data.append("action", "list_users"); +function listUsers() { + const data = { + action: "list_users", + }; - const result = await doAccountAction(data, "User list retrieved Successfully!", "User list retrieval failed."); + const result = doAction('/account', data, "User list retrieved Successfully!", "User list retrieval failed."); if (result && result.Status === "Success") { displayList(result.Users, "userListTable", deleteUser); } } +function listActivationCodes() { + const data = { + action: "list_activation_codes", + }; -async function listActivationCodes() { - const data = new URLSearchParams(); - data.append("action", "list_activation_codes"); - - const result = await doAccountAction(data, "Activation code list retrieved Successfully!", "Activation code list retrieval failed."); + const result = doAction('/account', data, "Activation code list retrieved Successfully!", "Activation code list retrieval failed."); displayList(result.ActivationCodes, "codeListTable", deleteActivationCode); } function deleteUser(userId) { + const data = { + action: "delete_user", + user_id: userId, + }; - const data = new URLSearchParams(); - data.append("action", "delete_user"); - data.append("user_id", userId); - - doAccountAction(data, "User deleted Successfully!", "User deletion failed."); + doAction('/account', data, "User deleted Successfully!", "User deletion failed."); listUsers(); } function deleteActivationCode(activationCode) { + const data = { + action: "delete_activation_code", + activation_code: activationCode, + }; - const data = new URLSearchParams(); - data.append("action", "delete_activation_code"); - data.append("activation_code", activationCode); - - doAccountAction(data, "Activation code deleted Successfully!", "Activation code deletion failed."); + doAction('/account', data, "Activation code deleted Successfully!", "Activation code deletion failed."); listActivationCodes(); } //Admin settings end diff --git a/endpoints/global/account.php b/endpoints/account.php similarity index 100% rename from endpoints/global/account.php rename to endpoints/account.php diff --git a/endpoints/global/page.php b/endpoints/page.php similarity index 100% rename from endpoints/global/page.php rename to endpoints/page.php diff --git a/index.php b/index.php index bed7315..f02e17a 100644 --- a/index.php +++ b/index.php @@ -1,4 +1,5 @@ 0 && !empty($_SESSION["email"]) && $_SESSION["privilege_level"] >= $routerConfig["logged_in_default_permission_level"]; + return $_SESSION["ID"] > 0 && !empty($_SESSION["email"]) && $_SESSION["privilege_level"] >= $routerConfig["permissions"]["logged_in_default"]; } function isVerified(): bool { global $routerConfig; - return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["verified_permission_level"]; + return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["permissions"]["verified"]; } function isTrustWorthy(): bool { global $routerConfig; - return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["trustworthy_permission_level"]; + return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["permissions"]["trustworthy"]; } function isModerator(): bool { global $routerConfig; - return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["moderator_permission_level"]; + return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["permissions"]["moderator"]; } function isUserAdmin(): bool { global $routerConfig; - return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["user_admin_permission_level"]; + return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["permissions"]["user_admin"]; } function isAdmin(): bool { global $routerConfig; - return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["admin_permission_level"]; + return isLoggedIn() && $_SESSION["privilege_level"] >= $routerConfig["permissions"]["admin"]; } @@ -69,7 +69,7 @@ function setDefaultSessionData(): void $_SESSION["nickname"] = ""; $_SESSION["email"] = ""; $_SESSION["minecraft_nickname"] = ""; - $_SESSION["privilege_level"] = $routerConfig["logged_out_permission_level"]; + $_SESSION["privilege_level"] = $routerConfig["permissions"]["logged_out"]; } function verifyPassword($userID, $password): bool @@ -86,17 +86,16 @@ function verifyPassword($userID, $password): bool return !empty($password_hash) && !empty($password) && password_verify($password, $password_hash); } -function UpdateSession(){ +function UpdateSession(): void +{ global $mysqli; $stmt = $mysqli->prepare("SELECT FirstName, LastName, Nickname, Email, MinecraftNick, PrivilegeLevel, LastLoginAt, LoginCount, ClassID, FavoriteColor FROM Users WHERE ID = ? AND isActivated = 1"); $stmt->bind_param("i", $_SESSION["ID"]); $stmt->execute(); - $uid = 0; $first_name = ""; $last_name = ""; $nickname = ""; - $password_hash = ""; $email = ""; $minecraft_nickname = ""; $privilege_level = 0; @@ -123,7 +122,7 @@ function UpdateSession(){ function doLogin($email, $password): array { - global $mysqli, $routerConfig; + global $mysqli; $found = false; if (!empty($email) && !empty($password)) { $stmt = $mysqli->prepare("SELECT ID, PasswordHash FROM Users WHERE Email = ? AND isActivated = 1"); @@ -171,7 +170,7 @@ function doRegister($firstname, $lastname, $email, $password, $activation_token) $passwordHash = password_hash($password, PASSWORD_DEFAULT); $stmt = $mysqli->prepare("UPDATE Users SET FirstName=?, LastName=?, Email=?, PasswordHash=?, PrivilegeLevel=?, isActivated=1, ActivationToken='', RegisteredAt=NOW() WHERE ActivationToken = ?"); - $privilege_level = $routerConfig["logged_in_default_permission_level"]; + $privilege_level = $routerConfig["permissions"]["logged_in_default"]; /** @noinspection SpellCheckingInspection */ $stmt->bind_param("ssssis", $firstname, $lastname, $email, $passwordHash, $privilege_level, $activation_token); @@ -315,7 +314,7 @@ function getUserInfo(): array function addActivationCodes($count): array { - global $mysqli, $routerConfig; + global $mysqli; $activationCodes = []; $output = ["Status" => "Fail"]; // Default Status is "Fail" @@ -347,7 +346,7 @@ function addActivationCodes($count): array function listUsers(): array { - global $mysqli, $routerConfig; + global $mysqli; $output = ["Status" => "Fail"]; // Default Status is "Fail" if (isUserAdmin()) { @@ -369,7 +368,7 @@ function listUsers(): array function listActivationCodes(): array { - global $mysqli, $routerConfig; + global $mysqli; $output = ["Status" => "Fail"]; // Default Status is "Fail" if (isUserAdmin()) { @@ -414,7 +413,7 @@ function listActivationCodes(): array function deleteUser($userID): array { - global $mysqli, $routerConfig; + global $mysqli; $status = ["Status" => "Fail"]; if (!empty($userID) && isUserAdmin()) { $stmt = $mysqli->prepare("DELETE FROM Users WHERE ID = ?"); @@ -430,7 +429,7 @@ function deleteUser($userID): array function deleteActivationCode($activationCode): array { - global $mysqli, $routerConfig; + global $mysqli; $status = ["Status" => "Fail"]; if (!empty($activationCode) && isUserAdmin()) { $stmt = $mysqli->prepare("DELETE FROM Users WHERE ActivationToken = ?"); diff --git a/lib/config.php b/lib/config.php index 2de72eb..3eeb6b0 100644 --- a/lib/config.php +++ b/lib/config.php @@ -1,35 +1,30 @@ false, + 'domain' => 'adlerka', + 'tld' => 'top', + 'default_page' => 'index', + 'default_site' => 'home', + 'template_dir' => 'templates/', + 'endpoint_dir' => 'endpoints/', + 'page_dir' => 'pages/', + 'protocol' => 'https://', + 'permissions' => [ + 'logged_out' => 1, + 'logged_in_default' => 2, + 'verified' => 3, + 'trustworthy' => 4, + 'moderator' => 5, + 'user_admin' => 254, + 'admin' => 255, + ], + 'page' => [ + 'default_secret' => 1, + 'default_permissions' => 255, - $routerConfig["template_dir"] = "templates/"; - - $routerConfig["endpoint_dir"] = "endpoints/"; - - $routerConfig["page_dir"] = "pages/"; - - $routerConfig["protocol"] = "https://"; - - $routerConfig["logged_out_permission_level"] = 1; - - $routerConfig["logged_in_default_permission_level"] = 2; - - $routerConfig["verified_permission_level"] = 3; - - $routerConfig["trustworthy_permission_level"] = 4; - - $routerConfig["moderator_permission_level"] = 5; - - $routerConfig["user_admin_permission_level"] = 254; - - $routerConfig["admin_permission_level"] = 255; - - $routerConfig["default_page_permission_level"] = 255; - - $routerConfig["default_page_secret"] = 1; + ] + ]; } diff --git a/lib/endpoint.php b/lib/endpoint.php index f81419b..fa52aff 100644 --- a/lib/endpoint.php +++ b/lib/endpoint.php @@ -21,21 +21,9 @@ function getEndpoint($endpoint_name): string $endpoint_name = $routerRequest["page_name"]; } - if($routerRequest["isToApex"]){ - $subdomain_part = ""; - } - else{ - $subdomain_part = $routerRequest["subdomain"] . "/"; - } + $endpoint_file = $routerConfig["endpoint_dir"] . $endpoint_name . ".php"; - $endpoint_file = $routerConfig["endpoint_dir"] . $subdomain_part . $endpoint_name . ".php"; - - $endpoint_file_global = $routerConfig["endpoint_dir"] . "global/" . $endpoint_name . ".php"; - - if (file_exists($endpoint_file_global)){ - $output = runEndpoint($endpoint_file_global); - } - elseif (file_exists($endpoint_file)){ + if (file_exists($endpoint_file)){ $output = runEndpoint($endpoint_file); } else{ diff --git a/lib/inliner.php b/lib/inliner.php index 7342400..4761191 100644 --- a/lib/inliner.php +++ b/lib/inliner.php @@ -1,9 +1,10 @@ ]*?\srel=["\']?stylesheet["\'].*?\shref=["\']?\/(.*?)["\'][^>]*?>/i'; - $outputString = preg_replace_callback($pattern, function($match) { + return preg_replace_callback($pattern, function($match) { $href = $match[1]; $cssFilePath = $_SERVER['DOCUMENT_ROOT'] . '/' . $href; $cssContent = file_get_contents($cssFilePath); @@ -28,14 +29,13 @@ function inlineLocalStylesFromHref($inputString) { return ""; }, $inputString); - - return $outputString; } -function inlineScriptFromSrc($inputString) { +function inlineScriptFromSrc($inputString): string +{ $pattern = '/\s*<\/script>/i'; - $outputString = preg_replace_callback($pattern, function($match) { + return preg_replace_callback($pattern, function($match) { $src = $match[1]; $jsContent = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $src); @@ -43,11 +43,10 @@ function inlineScriptFromSrc($inputString) { $jsContent = minifyJs($jsContent); return ""; }, $inputString); - - return $outputString; } -function minifyCss($css) { +function minifyCss($css): string +{ // Remove comments $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css); @@ -66,7 +65,8 @@ function minifyCss($css) { return trim($css); } -function minifyJs($js) { +function minifyJs($js): string +{ // Remove newlines and tabs $js = str_replace("\t", '', $js); diff --git a/lib/navigation.php b/lib/navigation.php index 82b0ca6..19efeb8 100644 --- a/lib/navigation.php +++ b/lib/navigation.php @@ -7,11 +7,11 @@ function getDynamicPermission($file): int { $permission_level = $page_tmp["parameters"]["minimal_permission_level"]; if (!is_numeric($permission_level) || $permission_level <= 0) { - $permission_level = $routerConfig["default_page_permission_level"]; + $permission_level = $routerConfig["page"]["default_permissions"]; } } catch (Exception){ - $permission_level = $routerConfig["default_page_permission_level"]; + $permission_level = $routerConfig["page"]["default_permissions"]; } finally { return $permission_level; } @@ -32,16 +32,11 @@ function generateNavigation(): string $site_name = str_replace("_", " ", $site_dir); - $site_subdomain = $site_dir . "."; - if ($site_name == $routerConfig["default_site"]) { - $site_subdomain = ""; - } - $site_name = ucfirst($site_name); - $site_location = $routerConfig["protocol"] . $site_subdomain . $routerRequest["domain"] . "." . $routerRequest["tld"] . "/" . $routerConfig["default_page"]; + $site_location = "/" . $site_dir . "/" . $routerConfig["default_page"]; - if ($routerRequest["subdomain"] == $site_dir) { + if ($routerRequest["site_name"] == $site_dir) { //this is the current page $site_class = "class=\"navsite_link active\""; } @@ -49,17 +44,17 @@ function generateNavigation(): string $site_class = "class=\"navsite_link\""; } - $navpages = ""; + $navigation_pages = ""; foreach ($pages_dir as $page_file) { $page_file_tmp = explode(".", $page_file); $page_basename = $page_file_tmp[0]; $page_class = "class=\"navpage_link\""; - if ($routerRequest["subdomain"] == $site_dir && $routerRequest["page_name"] == $page_basename) { + if ($routerRequest["site_name"] == $site_dir && $routerRequest["page_name"] == $page_basename) { $page_class = "class=\"navpage_link active\""; } - $page_location = $routerConfig["protocol"] . $site_subdomain . $routerRequest["domain"] . "." . $routerRequest["tld"] . "/" . $page_basename; + $page_location = "/" . $site_dir . "/" . $page_basename; $page_name = str_replace("_", " ", $page_basename); $page_name = explode(".", $page_name)[0]; @@ -73,23 +68,26 @@ function generateNavigation(): string $page_required_permission = intval($pageMetadata["parameters"]["minimal_permission_level"]); } else{ - $page_required_permission = $routerConfig["default_page_permission_level"]; + $page_required_permission = $routerConfig["page"]["default_permissions"]; } } elseif($page_file_tmp[1] == "php"){ $page_required_permission = getDynamicPermission($page_file_path); } else{ - $page_required_permission = $routerConfig["default_page_permission_level"]; + $page_required_permission = $routerConfig["page"]["default_permissions"]; } + if($page_required_permission <= $_SESSION["privilege_level"]) { - $navpages .= ""; + $navpage_attributes = "data-site='$site_dir' data-page='$page_basename'"; + $navigation_pages .= ""; } } - if(!empty($navpages)){ + if(!empty($navigation_pages)){ $default_page = $routerConfig["default_page"]; - $nav_out .= ""; + $navsite_attributes = "data-page='$default_page' data-site='$site_dir'"; + $nav_out .= ""; } } diff --git a/lib/page.php b/lib/page.php index 6411b75..77c3a75 100644 --- a/lib/page.php +++ b/lib/page.php @@ -1,5 +1,4 @@ $routerConfig["default_page"], ]); - $navpages = generateNavigation(); + $navigation = generateNavigation(); $out = $skeleton; - $out = str_replace("__TEMPLATE__NAV__", $navpages, $out); + $out = str_replace("__TEMPLATE__NAV__", $navigation, $out); $out = str_replace("__TEMPLATE__PAGE__", $page, $out); - $out = str_replace("__TEMPLATE__DYNASCRIPT__", $dynamic_script, $out); - $out = str_replace("__TEMPLATE__DYNASTYLE__", $dynamic_style, $out); - $out = inlineLocalStylesFromHref($out); - $out = inlineScriptFromSrc($out); + $out = str_replace("__TEMPLATE__DYNAMIC__SCRIPT__", $dynamic_script, $out); + $out = str_replace("__TEMPLATE__DYNAMIC__STYLE__", $dynamic_style, $out); + if($routerConfig["inlining"]) { + require_once "lib/inliner.php"; + $out = inlineLocalStylesFromHref($out); + $out = inlineScriptFromSrc($out); + } return str_replace("__TEMPLATE_PAGE_TITLE__", $page_title, $out); } function getPageEndpoint($page_name, $site_name) :array { - global $routerRequest, $routerConfig; - if(!empty($site_name)){ - $subdomain = "$site_name."; - } - else{ - $subdomain = ""; - } - $page_location = $routerConfig["protocol"] . $subdomain . $routerRequest["domain"] . "." . $routerRequest["tld"] . "/" . $page_name; + $page_location = "/" . $site_name . "/" . $page_name; $page_tmp = renderPage($page_name, $site_name); return [ "Status" => "Success", diff --git a/lib/router.php b/lib/router.php index 2ad4038..0b704be 100644 --- a/lib/router.php +++ b/lib/router.php @@ -1,68 +1,36 @@ +

Adlerka Memes

Skoro ako r/adlerka - ale lepšie.

diff --git a/pages/memes/info.html b/pages/memes/info.html index 09f1709..5b2e4c1 100644 --- a/pages/memes/info.html +++ b/pages/memes/info.html @@ -1,2 +1,2 @@ - -

Vitaj na oficiálnej stránke Memeov o AdlerkaSMP

\ No newline at end of file + +

Vitaj na stránke Adlerka memes

\ No newline at end of file diff --git a/pages/News/index.html b/pages/news/index.html similarity index 100% rename from pages/News/index.html rename to pages/news/index.html diff --git a/templates/skeleton.html b/templates/skeleton.html index 7b63c1c..dcdb16f 100644 --- a/templates/skeleton.html +++ b/templates/skeleton.html @@ -5,8 +5,8 @@ - __TEMPLATE__DYNASCRIPT__ - __TEMPLATE__DYNASTYLE__ + __TEMPLATE__DYNAMIC__SCRIPT__ + __TEMPLATE__DYNAMIC__STYLE__ Adlerka __TEMPLATE_PAGE_TITLE__