From 51595c13eb96d6aa1e1e11d1f6c13578e0a75e01 Mon Sep 17 00:00:00 2001 From: Greg Sarjeant <1686767+gsarjeant@users.noreply.github.com> Date: Sun, 1 Jun 2025 23:30:24 -0400 Subject: [PATCH] Make the homepage an actual template. --- configs/nginx/folder.conf | 18 ++-- src/bootstrap.php | 12 +-- src/classes/Config.php | 4 +- src/classes/User.php | 4 +- src/lib/mood.php | 8 +- src/lib/session.php | 2 - src/lib/ticks.php | 2 +- src/lib/util.php | 98 +++++++++++++++++++ src/public/index.php | 62 ++++++++++-- src/public/logout.php | 14 --- src/public/save_tick.php | 12 +-- src/{public => templates}/admin.php | 8 +- src/{public => templates}/atom/index.php | 8 +- .../index.php.bak => templates/home.php} | 26 +---- src/{public => templates}/login.php | 8 +- src/templates/logout.php | 14 +++ src/{public => templates}/rss/index.php | 8 +- src/{public => templates}/set_mood.php | 10 +- src/{public => templates}/setup.php | 4 +- src/{public => templates}/tick.php | 6 +- 20 files changed, 229 insertions(+), 99 deletions(-) delete mode 100644 src/public/logout.php rename src/{public => templates}/admin.php (97%) rename src/{public => templates}/atom/index.php (90%) rename src/{public/index.php.bak => templates/home.php} (82%) rename src/{public => templates}/login.php (92%) create mode 100644 src/templates/logout.php rename src/{public => templates}/rss/index.php (89%) rename src/{public => templates}/set_mood.php (83%) rename src/{public => templates}/setup.php (97%) rename src/{public => templates}/tick.php (88%) diff --git a/configs/nginx/folder.conf b/configs/nginx/folder.conf index 550b70f..36694c1 100644 --- a/configs/nginx/folder.conf +++ b/configs/nginx/folder.conf @@ -22,6 +22,15 @@ server { alias /var/www/html/public; index index.php; + # Cache static files + # Note that I don't actually serve most of this (just js and css to start) + # but including them all will let caching work later if I add images or something + location ~* ^/tkr/.+\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + try_files $uri =404; + } + # index.php is the entry point # It needs to be sent to php-fpm # But if someone tries to directly access index.php, that file will throw a 404 @@ -60,15 +69,6 @@ server { fastcgi_param QUERY_STRING $query_string; } - # Cache static files - # Note that I don't actually serve most of this (just js and css to start) - # but including them all will let caching work later if I add images or something - location ~* ^/tkr/.+\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { - expires 1y; - add_header Cache-Control "public, immutable"; - try_files $uri =404; - } - # Deny access to sensitive directories location ~ ^/tkr/(storage|lib|vendor|config) { deny all; diff --git a/src/bootstrap.php b/src/bootstrap.php index 1594fee..605fac1 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -1,11 +1,11 @@ s . ' second' . ($diff->s != 1 ? 's' : '') . ' ago'; } +function verify_data_dir(string $dir, bool $allow_create = false): void { + if (!is_dir($dir)) { + if ($allow_create) { + if (!mkdir($dir, 0770, true)) { + http_response_code(500); + echo "Failed to create required directory: $dir"; + exit; + } + } else { + http_response_code(500); + echo "Required directory does not exist: $dir"; + exit; + } + } + + if (!is_writable($dir)) { + http_response_code(500); + echo "Directory is not writable: $dir"; + exit; + } +} + +// Verify that setup is complete (i.e. the databse is populated). +// Redirect to setup.php if it isn't. +function confirm_setup(): void { + $db = get_db(); + + // Ensure required tables exist + $db->exec("CREATE TABLE IF NOT EXISTS user ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + about TEXT NULL, + website TEXT NULL, + mood TEXT NULL + )"); + + $db->exec("CREATE TABLE IF NOT EXISTS settings ( + id INTEGER PRIMARY KEY, + site_title TEXT NOT NULL, + site_description TEXT NULL, + base_path TEXT NOT NULL, + items_per_page INTEGER NOT NULL + )"); + + // See if there's any data in the tables + $user_count = (int) $db->query("SELECT COUNT(*) FROM user")->fetchColumn(); + $settings_count = (int) $db->query("SELECT COUNT(*) FROM settings")->fetchColumn(); + + // If either table has no records and we aren't on setup.php, redirect to setup.php + if ($user_count === 0 || $settings_count === 0){ + if (basename($_SERVER['PHP_SELF']) !== 'setup.php'){ + header('Location: setup.php'); + exit; + } + } else { + // If setup is complete and we are on setup.php, redirect to index.php. + if (basename($_SERVER['PHP_SELF']) === 'setup.php'){ + header('Location: index.php'); + exit; + } + }; +} + +function get_db(): PDO { + verify_data_dir(DATA_DIR, true); + + try { + $db = new PDO("sqlite:" . DB_FILE); + $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); + } catch (PDOException $e) { + die("Database connection failed: " . $e->getMessage()); + } + + return $db; +} + +function render_template(string $templateFile, array $vars = []): string { + #$templatePath = TEMPLATES_DIR . '/' . ltrim($templateFile, '/'); + + if (!file_exists($templateFile)) { + throw new RuntimeException("Template not found: $templatePath"); + } + + // Extract variables into local scope + extract($vars, EXTR_SKIP); + + // Start output buffering + ob_start(); + + // Include the template (with extracted variables in scope) + include $templateFile; + + // Return rendered output + return ob_get_clean(); +} \ No newline at end of file diff --git a/src/public/index.php b/src/public/index.php index b35c36c..1095f18 100644 --- a/src/public/index.php +++ b/src/public/index.php @@ -1,7 +1,36 @@ 404 Not Found'; + exit; +} + +if (strpos($path, $config->basePath) === 0) { + $path = substr($path, strlen($config->basePath)); } $path = trim($path, '/'); @@ -42,7 +78,21 @@ header('Content-Type: text/html; charset=utf-8'); echo "Path: " . $path; // Define your routes -route('', function() { - echo '
Welcome to the home page!
'; +route('', function() use ($isLoggedIn, $config, $user) { + #include TEMPLATES_DIR . "/home.php"; + #echo render_home_page($isLoggedIn, $config, $user); + $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1; + $limit = $config->itemsPerPage; + $offset = ($page - 1) * $limit; + $ticks = iterator_to_array(stream_ticks($limit, $offset)); + + $vars = [ + 'isLoggedIn' => $isLoggedIn, + 'config' => $config, + 'user' => $user, + 'ticks' => $ticks, + ]; + + echo render_template(TEMPLATES_DIR . "/home.php", $vars); }); +//isset($_SESSION['user_id']) \ No newline at end of file diff --git a/src/public/logout.php b/src/public/logout.php deleted file mode 100644 index a7c1648..0000000 --- a/src/public/logout.php +++ /dev/null @@ -1,14 +0,0 @@ -basePath); -exit; \ No newline at end of file diff --git a/src/public/save_tick.php b/src/public/save_tick.php index 73c92c2..d0b21d4 100644 --- a/src/public/save_tick.php +++ b/src/public/save_tick.php @@ -1,12 +1,12 @@ basePath . 'login.php'); diff --git a/src/public/atom/index.php b/src/templates/atom/index.php similarity index 90% rename from src/public/atom/index.php rename to src/templates/atom/index.php index 34e01c0..e33d7de 100644 --- a/src/public/atom/index.php +++ b/src/templates/atom/index.php @@ -1,10 +1,10 @@ itemsPerPage)); diff --git a/src/public/index.php.bak b/src/templates/home.php similarity index 82% rename from src/public/index.php.bak rename to src/templates/home.php index b0d54f6..341f926 100644 --- a/src/public/index.php.bak +++ b/src/templates/home.php @@ -1,31 +1,15 @@ - + + + -confirm_setup(); - -require_once CLASSES_DIR . '/Config.php'; -require_once CLASSES_DIR . '/User.php'; -require LIB_DIR . '/session.php'; -require LIB_DIR . '/ticks.php'; -require LIB_DIR . '/util.php'; - -$config = Config::load(); -// I can get away with this before login because there's only one user. -$user = User::load(); - -$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1; -$limit = $config->itemsPerPage; -$offset = ($page - 1) * $limit; - -$ticks = iterator_to_array(stream_ticks($limit, $offset)); -?>