diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-05-26 11:06:30 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-05-26 11:06:30 +0300 |
| commit | fa1bccd968647f6ab5cce0ec4293b39c6fde7633 (patch) | |
| tree | a51b489a43bdfcc2688bd0855cf3e32382ad958c /classes | |
| parent | ab7702f0e3dd63bdeaea3cb6db138878774c3b47 (diff) | |
| download | the-epube-fa1bccd968647f6ab5cce0ec4293b39c6fde7633.tar.gz the-epube-fa1bccd968647f6ab5cce0ec4293b39c6fde7633.tar.xz | |
spaces to tabs
Diffstat (limited to 'classes')
| -rw-r--r-- | classes/CsrfMiddleware.php | 40 | ||||
| -rw-r--r-- | classes/Debug.php | 126 | ||||
| -rw-r--r-- | classes/Handler/CoverHandler.php | 50 | ||||
| -rw-r--r-- | classes/Handler/DefineHandler.php | 88 | ||||
| -rw-r--r-- | classes/Handler/DownloadHandler.php | 38 | ||||
| -rw-r--r-- | classes/Handler/GetinfoHandler.php | 36 | ||||
| -rw-r--r-- | classes/Handler/GetlastreadHandler.php | 44 | ||||
| -rw-r--r-- | classes/Handler/HealthzHandler.php | 70 | ||||
| -rw-r--r-- | classes/Handler/ListHandler.php | 300 | ||||
| -rw-r--r-- | classes/Handler/LoginHandler.php | 314 | ||||
| -rw-r--r-- | classes/Handler/LogoutHandler.php | 10 | ||||
| -rw-r--r-- | classes/Handler/PaginationHandler.php | 112 | ||||
| -rw-r--r-- | classes/Handler/StorelastreadHandler.php | 68 | ||||
| -rw-r--r-- | classes/Handler/TogglefavHandler.php | 40 | ||||
| -rw-r--r-- | classes/MiddlewareInterface.php | 2 | ||||
| -rw-r--r-- | classes/Request.php | 104 | ||||
| -rw-r--r-- | classes/RequestHandlerInterface.php | 2 | ||||
| -rw-r--r-- | classes/Response.php | 72 | ||||
| -rw-r--r-- | classes/Router.php | 104 |
19 files changed, 810 insertions, 810 deletions
diff --git a/classes/CsrfMiddleware.php b/classes/CsrfMiddleware.php index 9693f99..3977241 100644 --- a/classes/CsrfMiddleware.php +++ b/classes/CsrfMiddleware.php @@ -2,29 +2,29 @@ class CsrfMiddleware implements MiddlewareInterface { - /** @var array<string> */ - private array $csrfIgnore = [ - "cover", "download", "getpagination", "getlastread", "getinfo", "list" - ]; + /** @var array<string> */ + private array $csrfIgnore = [ + "cover", "download", "getpagination", "getlastread", "getinfo", "list" + ]; - public function process(Request $request, callable $next): Response - { - if (empty($_SESSION['owner'])) { - return $next($request); - } + public function process(Request $request, callable $next): Response + { + if (empty($_SESSION['owner'])) { + return $next($request); + } - $op = $request->getAttribute('op'); + $op = $request->getAttribute('op'); - $csrfToken = $request->getAttribute('csrf_token', ''); + $csrfToken = $request->getAttribute('csrf_token', ''); - if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) { - $response = (new Response()) - ->withStatus(401) - ->withBody("Unauthorized (CSRF)"); - $response->send(); - exit; - } + if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) { + $response = (new Response()) + ->withStatus(401) + ->withBody("Unauthorized (CSRF)"); + $response->send(); + exit; + } - return $next($request); - } + return $next($request); + } } diff --git a/classes/Debug.php b/classes/Debug.php index 79116cd..7e7cc29 100644 --- a/classes/Debug.php +++ b/classes/Debug.php @@ -1,91 +1,91 @@ <?php class Debug { const LOG_DISABLED = -1; - const LOG_NORMAL = 0; - const LOG_VERBOSE = 1; - const LOG_EXTENDED = 2; + const LOG_NORMAL = 0; + const LOG_VERBOSE = 1; + const LOG_EXTENDED = 2; public static int $LOG_DISABLED = -1; - public static int $LOG_NORMAL = 0; - public static int $LOG_VERBOSE = 1; - public static int $LOG_EXTENDED = 2; + public static int $LOG_NORMAL = 0; + public static int $LOG_VERBOSE = 1; + public static int $LOG_EXTENDED = 2; - private static bool $enabled = false; - private static bool $quiet = false; - private static string $logfile = ""; - private static int $loglevel = 0; + private static bool $enabled = false; + private static bool $quiet = false; + private static string $logfile = ""; + private static int $loglevel = 0; public static function set_logfile(string $logfile) : void { - self::$logfile = $logfile; - } + self::$logfile = $logfile; + } - public static function enabled() : bool { - return self::$enabled; - } + public static function enabled() : bool { + return self::$enabled; + } - public static function set_enabled(bool $enable) : void { - self::$enabled = $enable; - } + public static function set_enabled(bool $enable) : void { + self::$enabled = $enable; + } - public static function set_quiet(bool $quiet) : void { - self::$quiet = $quiet; - } + public static function set_quiet(bool $quiet) : void { + self::$quiet = $quiet; + } - public static function set_loglevel(int $level) : void { - self::$loglevel = $level; - } + public static function set_loglevel(int $level) : void { + self::$loglevel = $level; + } - public static function get_loglevel() : int { - return self::$loglevel; - } + public static function get_loglevel() : int { + return self::$loglevel; + } - public static function log(string $message, int $level = 0) : void { + public static function log(string $message, int $level = 0) : void { - if (!self::$enabled || self::$loglevel < $level) return; + if (!self::$enabled || self::$loglevel < $level) return; - $ts = strftime("%H:%M:%S", time()); - if (function_exists('posix_getpid')) { - $ts = "$ts/" . posix_getpid(); - } + $ts = strftime("%H:%M:%S", time()); + if (function_exists('posix_getpid')) { + $ts = "$ts/" . posix_getpid(); + } - if (self::$logfile) { - $fp = fopen(self::$logfile, 'a+'); + if (self::$logfile) { + $fp = fopen(self::$logfile, 'a+'); - if ($fp) { - $locked = false; + if ($fp) { + $locked = false; - if (function_exists("flock")) { - $tries = 0; + if (function_exists("flock")) { + $tries = 0; - // try to lock logfile for writing - while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) { - sleep(1); - ++$tries; - } + // try to lock logfile for writing + while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) { + sleep(1); + ++$tries; + } - if (!$locked) { - fclose($fp); - user_error("Unable to lock debugging log file: " . self::$logfile, E_USER_WARNING); - return; - } - } + if (!$locked) { + fclose($fp); + user_error("Unable to lock debugging log file: " . self::$logfile, E_USER_WARNING); + return; + } + } - fputs($fp, "[$ts] $message\n"); + fputs($fp, "[$ts] $message\n"); - if (function_exists("flock")) { - flock($fp, LOCK_UN); - } + if (function_exists("flock")) { + flock($fp, LOCK_UN); + } - fclose($fp); + fclose($fp); - if (self::$quiet) - return; + if (self::$quiet) + return; - } else { - user_error("Unable to open debugging log file: " . self::$logfile, E_USER_WARNING); - } - } + } else { + user_error("Unable to open debugging log file: " . self::$logfile, E_USER_WARNING); + } + } - print "[$ts] $message\n"; - } + print "[$ts] $message\n"; + } } diff --git a/classes/Handler/CoverHandler.php b/classes/Handler/CoverHandler.php index d219f84..d4c0a2c 100644 --- a/classes/Handler/CoverHandler.php +++ b/classes/Handler/CoverHandler.php @@ -11,32 +11,32 @@ use PDO; class CoverHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $id = (int) $request->getAttribute('id'); - $db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); - $sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?"); - $sth->execute([$id]); + public function handle(Request $request): Response + { + $id = (int) $request->getAttribute('id'); + $db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); + $sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?"); + $sth->execute([$id]); - while ($line = $sth->fetch()) { - $filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg"; + while ($line = $sth->fetch()) { + $filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg"; - if (file_exists($filename)) { - return (new Response()) - ->withHeader("Content-type", mime_content_type($filename)) - ->withHeader('Cache-control', "max-age=" . STATIC_EXPIRES) - ->withHeader("Expires", gmdate("D, d M Y H:i:s \G\M\T", time()+STATIC_EXPIRES)) - ->withHeader("Last-Modified", gmdate("D, d M Y H:i:s \G\M\T", filemtime($filename))) - ->withBody(readfile($filename) ?: ''); - } else { - return (new Response()) - ->withStatus(404) - ->withBody("File not found."); - } - } + if (file_exists($filename)) { + return (new Response()) + ->withHeader("Content-type", mime_content_type($filename)) + ->withHeader('Cache-control', "max-age=" . STATIC_EXPIRES) + ->withHeader("Expires", gmdate("D, d M Y H:i:s \G\M\T", time()+STATIC_EXPIRES)) + ->withHeader("Last-Modified", gmdate("D, d M Y H:i:s \G\M\T", filemtime($filename))) + ->withBody(readfile($filename) ?: ''); + } else { + return (new Response()) + ->withStatus(404) + ->withBody("File not found."); + } + } - return (new Response()) - ->withStatus(404) - ->withBody("File not found."); - } + return (new Response()) + ->withStatus(404) + ->withBody("File not found."); + } } diff --git a/classes/Handler/DefineHandler.php b/classes/Handler/DefineHandler.php index 60d5b11..87fd3f9 100644 --- a/classes/Handler/DefineHandler.php +++ b/classes/Handler/DefineHandler.php @@ -10,59 +10,59 @@ use Response; class DefineHandler implements RequestHandlerInterface, AuthRequired { - /** @return array<string> */ - private function parseDictReply(string $reply): array - { - $tmp = []; + /** @return array<string> */ + private function parseDictReply(string $reply): array + { + $tmp = []; - foreach (explode("\n", $reply) as $line) { - list($code, $message) = explode(" ", $line, 2); + foreach (explode("\n", $reply) as $line) { + list($code, $message) = explode(" ", $line, 2); - if (!$code && $message) { - array_push($tmp, $message); - } - } + if (!$code && $message) { + array_push($tmp, $message); + } + } - return $tmp; - } + return $tmp; + } - public function handle(Request $request): Response - { - if (!Config::get(Config::DICT_SERVER)) { - return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]])); - } + public function handle(Request $request): Response + { + if (!Config::get(Config::DICT_SERVER)) { + return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]])); + } - $word = strip_tags(str_replace("", "", $request->getAttribute('word'))); - $origWord = $word; - $result = []; + $word = strip_tags(str_replace("", "", $request->getAttribute('word'))); + $origWord = $word; + $result = []; - for ($i = 0; $i < 3; $i++) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", Config::get(Config::DICT_SERVER), $word)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - $dictReply = curl_exec($ch); + for ($i = 0; $i < 3; $i++) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", Config::get(Config::DICT_SERVER), $word)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $dictReply = curl_exec($ch); - if ($dictReply) { - $retParsed = $this->parseDictReply($dictReply); + if ($dictReply) { + $retParsed = $this->parseDictReply($dictReply); - if (count($retParsed) > 0) { - array_push($result, "<strong>$word</strong>"); - $result = array_merge($result, $retParsed); - break; - } else { - $word = mb_substr($word, 0, mb_strlen($word) - 1); - } - } else { - array_push($result, curl_error($ch)); - } + if (count($retParsed) > 0) { + array_push($result, "<strong>$word</strong>"); + $result = array_merge($result, $retParsed); + break; + } else { + $word = mb_substr($word, 0, mb_strlen($word) - 1); + } + } else { + array_push($result, curl_error($ch)); + } - curl_close($ch); - } + curl_close($ch); + } - if (count($result) == 0) { - array_push($result, "No results for: <b>$origWord</b>"); - } + if (count($result) == 0) { + array_push($result, "No results for: <b>$origWord</b>"); + } - return (new Response())->withBody(json_encode(["result" => $result])); - } + return (new Response())->withBody(json_encode(["result" => $result])); + } } diff --git a/classes/Handler/DownloadHandler.php b/classes/Handler/DownloadHandler.php index e8ff9e7..6eaca11 100644 --- a/classes/Handler/DownloadHandler.php +++ b/classes/Handler/DownloadHandler.php @@ -11,26 +11,26 @@ use PDO; class DownloadHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $bookid = (int) $request->getAttribute('id'); - $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); - $sth = $caldb->prepare("SELECT path, name, format FROM data LEFT JOIN books ON (data.book = books.id) WHERE data.id = ?"); - $sth->execute([$bookid]); + public function handle(Request $request): Response + { + $bookid = (int) $request->getAttribute('id'); + $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); + $sth = $caldb->prepare("SELECT path, name, format FROM data LEFT JOIN books ON (data.book = books.id) WHERE data.id = ?"); + $sth->execute([$bookid]); - while ($row = $sth->fetch()) { - $filename = Config::get(Config::BOOKS_DIR) . "/" . $row["path"] . "/" . $row["name"] . "." . strtolower($row["format"]); + while ($row = $sth->fetch()) { + $filename = Config::get(Config::BOOKS_DIR) . "/" . $row["path"] . "/" . $row["name"] . "." . strtolower($row["format"]); - if (file_exists($filename)) { - return (new Response()) - ->withHeader("Content-type", mime_content_type($filename)) - ->withHeader("Content-Disposition", 'attachment; filename="' . basename($filename) . '"') - ->withBody(readfile($filename) ?: ''); - } - } + if (file_exists($filename)) { + return (new Response()) + ->withHeader("Content-type", mime_content_type($filename)) + ->withHeader("Content-Disposition", 'attachment; filename="' . basename($filename) . '"') + ->withBody(readfile($filename) ?: ''); + } + } - return (new Response()) - ->withStatus(404) - ->withBody("File not found."); - } + return (new Response()) + ->withStatus(404) + ->withBody("File not found."); + } } diff --git a/classes/Handler/GetinfoHandler.php b/classes/Handler/GetinfoHandler.php index 2235ef5..0c51cf5 100644 --- a/classes/Handler/GetinfoHandler.php +++ b/classes/Handler/GetinfoHandler.php @@ -12,27 +12,27 @@ use Sanitizer; class GetinfoHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $id = (int) $request->getAttribute('id'); - $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); + public function handle(Request $request): Response + { + $id = (int) $request->getAttribute('id'); + $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); - $sth = $caldb->prepare("SELECT books.*, s.name AS series_name, - (SELECT text FROM comments WHERE book = books.id) AS comment, - (SELECT id FROM data WHERE book = books.id AND format = 'EPUB' LIMIT 1) AS epub_id FROM books - LEFT JOIN books_series_link AS bsl ON (bsl.book = books.id) - LEFT JOIN series AS s ON (bsl.series = s.id) - WHERE books.id = ?"); - $sth->execute([$id]); + $sth = $caldb->prepare("SELECT books.*, s.name AS series_name, + (SELECT text FROM comments WHERE book = books.id) AS comment, + (SELECT id FROM data WHERE book = books.id AND format = 'EPUB' LIMIT 1) AS epub_id FROM books + LEFT JOIN books_series_link AS bsl ON (bsl.book = books.id) + LEFT JOIN series AS s ON (bsl.series = s.id) + WHERE books.id = ?"); + $sth->execute([$id]); - if ($row = $sth->fetch()) { + if ($row = $sth->fetch()) { $row['comment'] = Sanitizer::sanitize($row['comment'] ?? ""); - return (new Response())->withBody(json_encode($row)); - } + return (new Response())->withBody(json_encode($row)); + } - return (new Response()) - ->withStatus(404) - ->withBody("Not found."); - } + return (new Response()) + ->withStatus(404) + ->withBody("Not found."); + } } diff --git a/classes/Handler/GetlastreadHandler.php b/classes/Handler/GetlastreadHandler.php index 8d0a1f2..d6b82e7 100644 --- a/classes/Handler/GetlastreadHandler.php +++ b/classes/Handler/GetlastreadHandler.php @@ -10,29 +10,29 @@ use Response; class GetlastreadHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $bookid = (int) $request->getAttribute('id'); - $owner = $_SESSION["owner"] ?? ""; + public function handle(Request $request): Response + { + $bookid = (int) $request->getAttribute('id'); + $owner = $_SESSION["owner"] ?? ""; - if ($bookid) { - $book = ORM::for_table('epube_books') - ->where('bookid', $bookid) - ->where('owner', $owner) - ->find_one(); + if ($bookid) { + $book = ORM::for_table('epube_books') + ->where('bookid', $bookid) + ->where('owner', $owner) + ->find_one(); - if ($book) { - return (new Response())->withBody(json_encode([ - "page" => (int)$book->lastread, - "cfi" => $book->lastcfi, - "total" => 100, - "timestamp" => (int)$book->lastts - ])); - } - } + if ($book) { + return (new Response())->withBody(json_encode([ + "page" => (int)$book->lastread, + "cfi" => $book->lastcfi, + "total" => 100, + "timestamp" => (int)$book->lastts + ])); + } + } - return (new Response()) - ->withStatus(404) - ->withBody("Not found."); - } + return (new Response()) + ->withStatus(404) + ->withBody("Not found."); + } } diff --git a/classes/Handler/HealthzHandler.php b/classes/Handler/HealthzHandler.php index 722422c..a243b9f 100644 --- a/classes/Handler/HealthzHandler.php +++ b/classes/Handler/HealthzHandler.php @@ -11,39 +11,39 @@ use Response; class HealthzHandler implements RequestHandlerInterface { - public function handle(Request $request): Response - { - $status = "ok"; - $errors = []; - - // Test Calibre SQLite database - try { - $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); - $caldb->query("SELECT 1 FROM books LIMIT 1"); - } catch (\PDOException $e) { - $status = "degraded"; - $errors["calibre_db"] = "Connection failed: " . $e->getMessage(); - } - - // Test main database (via ORM/Db) - try { - Db::pdo()->query("SELECT 1"); - } catch (\PDOException $e) { - $status = "degraded"; - $errors["main_db"] = "Connection failed: " . $e->getMessage(); - } - - $response = (new Response()) - ->withHeader("Content-Type", "application/json") - ->withBody(json_encode([ - "status" => $status, - "errors" => $errors, - ])); - - if ($status === "degraded") { - $response = $response->withStatus(503); - } - - return $response; - } + public function handle(Request $request): Response + { + $status = "ok"; + $errors = []; + + // Test Calibre SQLite database + try { + $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); + $caldb->query("SELECT 1 FROM books LIMIT 1"); + } catch (\PDOException $e) { + $status = "degraded"; + $errors["calibre_db"] = "Connection failed: " . $e->getMessage(); + } + + // Test main database (via ORM/Db) + try { + Db::pdo()->query("SELECT 1"); + } catch (\PDOException $e) { + $status = "degraded"; + $errors["main_db"] = "Connection failed: " . $e->getMessage(); + } + + $response = (new Response()) + ->withHeader("Content-Type", "application/json") + ->withBody(json_encode([ + "status" => $status, + "errors" => $errors, + ])); + + if ($status === "degraded") { + $response = $response->withStatus(503); + } + + return $response; + } } diff --git a/classes/Handler/ListHandler.php b/classes/Handler/ListHandler.php index e4f6455..fbfb2b3 100644 --- a/classes/Handler/ListHandler.php +++ b/classes/Handler/ListHandler.php @@ -11,154 +11,154 @@ use PDO; class ListHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $owner = $_SESSION["owner"] ?? ""; - $mode = $request->getAttribute('mode', ''); - $query = $request->getAttribute('query', ''); - $limit = (int) $request->getAttribute('limit', 60); - $offset = (int) $request->getAttribute('offset', 0); - - $ldb = \Db::pdo(); - $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); - - $ids_qpart = "1"; - - if ($mode == "favorites") { - $fav_sth = $ldb->prepare("SELECT bookid FROM epube_favorites WHERE owner = ?"); - $fav_sth->execute([$owner]); - - $fav_ids = []; - while ($line = $fav_sth->fetch()) { - array_push($fav_ids, $line["bookid"]); - } - - if (empty($fav_ids)) { - return (new Response())->withBody(json_encode(["books" => [], "total" => 0])); - } - - $ids_qpart = "books.id IN (" . implode(",", $fav_ids) . ")"; - } - - $order_by = $query ? "author_sort, series_name, series_index, title, books.id" : "books.id DESC"; - - $sth = $caldb->prepare("SELECT books.*, s.name AS series_name, - (SELECT id FROM data WHERE book = books.id AND format = 'EPUB' LIMIT 1) AS epub_id FROM books - LEFT JOIN books_series_link AS bsl ON (bsl.book = books.id) - LEFT JOIN series AS s ON (bsl.series = s.id) - WHERE - ((:query = '') OR - ( - LOWER(books.author_sort) LIKE LOWER(:query) OR - LOWER(books.title) LIKE LOWER(:query) OR - LOWER(series_name) LIKE LOWER(:query) - )) - AND $ids_qpart - ORDER BY $order_by LIMIT :limit OFFSET :offset"); - - $sth->execute([':limit' => $limit, ':offset' => $offset, ':query' => '%' . $query . '%']); - - $books = []; - $total = 0; - - while ($line = $sth->fetch()) { - $cover_link = ""; - if ($line['has_cover']) { - $cover_filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg"; - if (file_exists($cover_filename)) { - $cover_mtime = filemtime($cover_filename); - $cover_link = "backend.php?" . http_build_query(["op" => "cover", "id" => $line["id"], "ts" => $cover_mtime]); - } - } - - $read_link = ""; - $in_progress = false; - $is_read = false; - - if ($line["epub_id"]) { - $read_link = "read.html?" . http_build_query(["id" => $line["epub_id"], "rt" => $mode, "b" => $line["id"], "ts" => time()]); - - $lastread_sth = $ldb->prepare("SELECT lastread, total_pages FROM epube_books, epube_pagination - WHERE epube_pagination.bookid = epube_books.bookid AND - epube_books.bookid = ? AND owner = ?"); - $lastread_sth->execute([$line['epub_id'], $owner]); - - if ($lastread_line = $lastread_sth->fetch()) { - $lastread = $lastread_line["lastread"]; - $total_pages = $lastread_line["total_pages"]; - - $is_read = $total_pages - $lastread < 5; - $in_progress = $lastread > 1; - } - } - - $series_link = ""; - $series_full = ""; - - if ($line["series_name"]) { - $series_link = "?" . http_build_query(["query" => $line["series_name"]]); - $series_full = $line["series_name"] . " [" . $line["series_index"] . "]"; - } - - $data_sth = $caldb->prepare("SELECT * FROM data WHERE book = ? LIMIT 3"); - $data_sth->execute([$line['id']]); - - $download_formats = []; - while ($data_line = $data_sth->fetch()) { - if ($data_line["format"] != "ORIGINAL_EPUB") { - $download_formats[] = [ - "format" => $data_line["format"], - "id" => $data_line["id"], - ]; - } - } - - $is_fav = false; - $fav_sth = $ldb->prepare("SELECT id FROM epube_favorites - WHERE bookid = ? AND owner = ? LIMIT 1"); - $fav_sth->execute([$line['id'], $owner]); - if ($fav_sth->fetch()) { - $is_fav = true; - } - - $books[] = [ - "id" => $line["id"], - "title" => $line["title"], - "author_sort" => $line["author_sort"], - "series_name" => $line["series_name"] ?? "", - "series_index" => $line["series_index"] ?? 0, - "series_link" => $series_link, - "series_full" => $series_full, - "cover_link" => $cover_link, - "read_link" => $read_link, - "in_progress" => $in_progress, - "is_read" => $is_read, - "is_fav" => $is_fav, - "epub_id" => $line["epub_id"] ?? 0, - "download_formats" => $download_formats, - ]; - } - - // count total for pagination - $count_sth = $caldb->prepare("SELECT COUNT(*) FROM books - LEFT JOIN books_series_link AS bsl ON (bsl.book = books.id) - LEFT JOIN series AS s ON (bsl.series = s.id) - WHERE - ((:query = '%%') OR - ( - LOWER(books.author_sort) LIKE LOWER(:query) OR - LOWER(books.title) LIKE LOWER(:query) OR - LOWER(s.name) LIKE LOWER(:query) - )) - AND $ids_qpart"); - $count_sth->execute([':query' => '%' . $query . '%']); - $total = (int) $count_sth->fetchColumn(); - - return (new Response())->withBody(json_encode([ - "books" => $books, - "total" => $total, - "offset" => $offset, - "limit" => $limit, - ])); - } + public function handle(Request $request): Response + { + $owner = $_SESSION["owner"] ?? ""; + $mode = $request->getAttribute('mode', ''); + $query = $request->getAttribute('query', ''); + $limit = (int) $request->getAttribute('limit', 60); + $offset = (int) $request->getAttribute('offset', 0); + + $ldb = \Db::pdo(); + $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); + + $ids_qpart = "1"; + + if ($mode == "favorites") { + $fav_sth = $ldb->prepare("SELECT bookid FROM epube_favorites WHERE owner = ?"); + $fav_sth->execute([$owner]); + + $fav_ids = []; + while ($line = $fav_sth->fetch()) { + array_push($fav_ids, $line["bookid"]); + } + + if (empty($fav_ids)) { + return (new Response())->withBody(json_encode(["books" => [], "total" => 0])); + } + + $ids_qpart = "books.id IN (" . implode(",", $fav_ids) . ")"; + } + + $order_by = $query ? "author_sort, series_name, series_index, title, books.id" : "books.id DESC"; + + $sth = $caldb->prepare("SELECT books.*, s.name AS series_name, + (SELECT id FROM data WHERE book = books.id AND format = 'EPUB' LIMIT 1) AS epub_id FROM books + LEFT JOIN books_series_link AS bsl ON (bsl.book = books.id) + LEFT JOIN series AS s ON (bsl.series = s.id) + WHERE + ((:query = '') OR + ( + LOWER(books.author_sort) LIKE LOWER(:query) OR + LOWER(books.title) LIKE LOWER(:query) OR + LOWER(series_name) LIKE LOWER(:query) + )) + AND $ids_qpart + ORDER BY $order_by LIMIT :limit OFFSET :offset"); + + $sth->execute([':limit' => $limit, ':offset' => $offset, ':query' => '%' . $query . '%']); + + $books = []; + $total = 0; + + while ($line = $sth->fetch()) { + $cover_link = ""; + if ($line['has_cover']) { + $cover_filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg"; + if (file_exists($cover_filename)) { + $cover_mtime = filemtime($cover_filename); + $cover_link = "backend.php?" . http_build_query(["op" => "cover", "id" => $line["id"], "ts" => $cover_mtime]); + } + } + + $read_link = ""; + $in_progress = false; + $is_read = false; + + if ($line["epub_id"]) { + $read_link = "read.html?" . http_build_query(["id" => $line["epub_id"], "rt" => $mode, "b" => $line["id"], "ts" => time()]); + + $lastread_sth = $ldb->prepare("SELECT lastread, total_pages FROM epube_books, epube_pagination + WHERE epube_pagination.bookid = epube_books.bookid AND + epube_books.bookid = ? AND owner = ?"); + $lastread_sth->execute([$line['epub_id'], $owner]); + + if ($lastread_line = $lastread_sth->fetch()) { + $lastread = $lastread_line["lastread"]; + $total_pages = $lastread_line["total_pages"]; + + $is_read = $total_pages - $lastread < 5; + $in_progress = $lastread > 1; + } + } + + $series_link = ""; + $series_full = ""; + + if ($line["series_name"]) { + $series_link = "?" . http_build_query(["query" => $line["series_name"]]); + $series_full = $line["series_name"] . " [" . $line["series_index"] . "]"; + } + + $data_sth = $caldb->prepare("SELECT * FROM data WHERE book = ? LIMIT 3"); + $data_sth->execute([$line['id']]); + + $download_formats = []; + while ($data_line = $data_sth->fetch()) { + if ($data_line["format"] != "ORIGINAL_EPUB") { + $download_formats[] = [ + "format" => $data_line["format"], + "id" => $data_line["id"], + ]; + } + } + + $is_fav = false; + $fav_sth = $ldb->prepare("SELECT id FROM epube_favorites + WHERE bookid = ? AND owner = ? LIMIT 1"); + $fav_sth->execute([$line['id'], $owner]); + if ($fav_sth->fetch()) { + $is_fav = true; + } + + $books[] = [ + "id" => $line["id"], + "title" => $line["title"], + "author_sort" => $line["author_sort"], + "series_name" => $line["series_name"] ?? "", + "series_index" => $line["series_index"] ?? 0, + "series_link" => $series_link, + "series_full" => $series_full, + "cover_link" => $cover_link, + "read_link" => $read_link, + "in_progress" => $in_progress, + "is_read" => $is_read, + "is_fav" => $is_fav, + "epub_id" => $line["epub_id"] ?? 0, + "download_formats" => $download_formats, + ]; + } + + // count total for pagination + $count_sth = $caldb->prepare("SELECT COUNT(*) FROM books + LEFT JOIN books_series_link AS bsl ON (bsl.book = books.id) + LEFT JOIN series AS s ON (bsl.series = s.id) + WHERE + ((:query = '%%') OR + ( + LOWER(books.author_sort) LIKE LOWER(:query) OR + LOWER(books.title) LIKE LOWER(:query) OR + LOWER(s.name) LIKE LOWER(:query) + )) + AND $ids_qpart"); + $count_sth->execute([':query' => '%' . $query . '%']); + $total = (int) $count_sth->fetchColumn(); + + return (new Response())->withBody(json_encode([ + "books" => $books, + "total" => $total, + "offset" => $offset, + "limit" => $limit, + ])); + } } diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php index ded6e8c..c97a93e 100644 --- a/classes/Handler/LoginHandler.php +++ b/classes/Handler/LoginHandler.php @@ -11,162 +11,162 @@ use Response; class LoginHandler implements RequestHandlerInterface { - /** @return array<string, string>|null */ - private function doLocalLogin(string $username, string $password): ?array - { - $pass_hash = 'SHA256:' . hash('sha256', "$username:" . $password); - - $user = ORM::for_table('epube_users') - ->where('username', $username) - ->where('pass', $pass_hash) - ->find_one(); - - if (!$user) { - return null; - } - - if (session_status() != PHP_SESSION_ACTIVE) { - session_start(); - } - - session_regenerate_id(true); - - $_SESSION["owner"] = $username; - $_SESSION["pass_hash"] = sha1($user->pass); - $_SESSION["csrf_token"] = bin2hex(random_bytes(16)); - - return ["owner" => $username]; - } - - private function doOidcLogin(): void - { - $oidc = new OpenIDConnectClient( - Config::get(Config::OIDC_URL), - Config::get(Config::OIDC_CLIENT_ID), - Config::get(Config::OIDC_CLIENT_SECRET) - ); - - $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback"); - $oidc->addScope(['openid', 'profile', 'email']); - $oidc->authenticate(); - } - - /** @return array<string, string> */ - private function handleOidcCallback(): array - { - $oidc = new OpenIDConnectClient( - Config::get(Config::OIDC_URL), - Config::get(Config::OIDC_CLIENT_ID), - Config::get(Config::OIDC_CLIENT_SECRET) - ); - - $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback"); - $oidc->addScope(['openid', 'profile', 'email']); - - try { - $oidc->authenticate(); - - $username = trim(mb_strtolower($oidc->requestUserInfo("preferred_username"))); - - if (!$username) { - return ["error" => "No username received from OIDC provider."]; - } - - $user = ORM::for_table('epube_users') - ->where('username', $username) - ->find_one(); - - if (!$user) { - return ["error" => "User not found: $username"]; - } - - if (session_status() != PHP_SESSION_ACTIVE) { - session_start(); - } - - session_regenerate_id(true); - - $_SESSION["access_token"] = $oidc->getAccessToken(); - $_SESSION["access_token_last_check"] = time(); - $_SESSION["owner"] = $username; - $_SESSION["pass_hash"] = sha1($user->pass); - $_SESSION["csrf_token"] = bin2hex(random_bytes(16)); - - return ["owner" => $username]; - - } catch (\Exception $e) { - return ["error" => "OIDC Error: " . $e->getMessage()]; - } - } - - public function handle(Request $request): Response - { - $op = $request->getAttribute('op', ''); - - // Redirect to OIDC provider - if ($op === "perform-oidc-login") { - if (empty(Config::get(Config::OIDC_URL))) { - return (new Response()) - ->withStatus(400) - ->withBody(json_encode(["error" => "OIDC is not configured."])); - } - - $this->doOidcLogin(); - - // unreachable - authenticate() redirects - return new Response(); - } - - // OIDC callback - if ($op === "oidc-login-callback") { - if (empty(Config::get(Config::OIDC_URL))) { - return (new Response()) - ->withStatus(400) - ->withBody(json_encode(["error" => "OIDC is not configured."])); - } - - $result = $this->handleOidcCallback(); - - if (isset($result["error"])) { - // Logout any partial session state - if (function_exists('logout_user')) { - logout_user(); - } - return (new Response()) - ->withStatus(401) - ->withBody(json_encode($result)); - } - - return (new Response()) + /** @return array<string, string>|null */ + private function doLocalLogin(string $username, string $password): ?array + { + $pass_hash = 'SHA256:' . hash('sha256', "$username:" . $password); + + $user = ORM::for_table('epube_users') + ->where('username', $username) + ->where('pass', $pass_hash) + ->find_one(); + + if (!$user) { + return null; + } + + if (session_status() != PHP_SESSION_ACTIVE) { + session_start(); + } + + session_regenerate_id(true); + + $_SESSION["owner"] = $username; + $_SESSION["pass_hash"] = sha1($user->pass); + $_SESSION["csrf_token"] = bin2hex(random_bytes(16)); + + return ["owner" => $username]; + } + + private function doOidcLogin(): void + { + $oidc = new OpenIDConnectClient( + Config::get(Config::OIDC_URL), + Config::get(Config::OIDC_CLIENT_ID), + Config::get(Config::OIDC_CLIENT_SECRET) + ); + + $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback"); + $oidc->addScope(['openid', 'profile', 'email']); + $oidc->authenticate(); + } + + /** @return array<string, string> */ + private function handleOidcCallback(): array + { + $oidc = new OpenIDConnectClient( + Config::get(Config::OIDC_URL), + Config::get(Config::OIDC_CLIENT_ID), + Config::get(Config::OIDC_CLIENT_SECRET) + ); + + $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback"); + $oidc->addScope(['openid', 'profile', 'email']); + + try { + $oidc->authenticate(); + + $username = trim(mb_strtolower($oidc->requestUserInfo("preferred_username"))); + + if (!$username) { + return ["error" => "No username received from OIDC provider."]; + } + + $user = ORM::for_table('epube_users') + ->where('username', $username) + ->find_one(); + + if (!$user) { + return ["error" => "User not found: $username"]; + } + + if (session_status() != PHP_SESSION_ACTIVE) { + session_start(); + } + + session_regenerate_id(true); + + $_SESSION["access_token"] = $oidc->getAccessToken(); + $_SESSION["access_token_last_check"] = time(); + $_SESSION["owner"] = $username; + $_SESSION["pass_hash"] = sha1($user->pass); + $_SESSION["csrf_token"] = bin2hex(random_bytes(16)); + + return ["owner" => $username]; + + } catch (\Exception $e) { + return ["error" => "OIDC Error: " . $e->getMessage()]; + } + } + + public function handle(Request $request): Response + { + $op = $request->getAttribute('op', ''); + + // Redirect to OIDC provider + if ($op === "perform-oidc-login") { + if (empty(Config::get(Config::OIDC_URL))) { + return (new Response()) + ->withStatus(400) + ->withBody(json_encode(["error" => "OIDC is not configured."])); + } + + $this->doOidcLogin(); + + // unreachable - authenticate() redirects + return new Response(); + } + + // OIDC callback + if ($op === "oidc-login-callback") { + if (empty(Config::get(Config::OIDC_URL))) { + return (new Response()) + ->withStatus(400) + ->withBody(json_encode(["error" => "OIDC is not configured."])); + } + + $result = $this->handleOidcCallback(); + + if (isset($result["error"])) { + // Logout any partial session state + if (function_exists('logout_user')) { + logout_user(); + } + return (new Response()) + ->withStatus(401) + ->withBody(json_encode($result)); + } + + return (new Response()) ->withHeader("Location", Config::get_self_url() . "/index.php") - ->withBody(json_encode(["result" => "ok", "user" => $result["owner"]])); - } - - // Local username/password login - if ($op === "perform-login") { - $username = trim(mb_strtolower($request->getAttribute('user', ''))); - $password = $request->getAttribute('password', ''); - - if (!$username || !$password) { - return (new Response()) - ->withStatus(400) - ->withBody(json_encode(["error" => "Username and password are required."])); - } - - $result = $this->doLocalLogin($username, $password); - - if (!$result) { - return (new Response()) - ->withStatus(401) - ->withBody(json_encode(["error" => "Incorrect username or password."])); - } - - return (new Response()) - ->withBody(json_encode(["result" => "ok", "user" => $result["owner"]])); - } - - return (new Response()) - ->withStatus(404) - ->withBody("Not found."); - } + ->withBody(json_encode(["result" => "ok", "user" => $result["owner"]])); + } + + // Local username/password login + if ($op === "perform-login") { + $username = trim(mb_strtolower($request->getAttribute('user', ''))); + $password = $request->getAttribute('password', ''); + + if (!$username || !$password) { + return (new Response()) + ->withStatus(400) + ->withBody(json_encode(["error" => "Username and password are required."])); + } + + $result = $this->doLocalLogin($username, $password); + + if (!$result) { + return (new Response()) + ->withStatus(401) + ->withBody(json_encode(["error" => "Incorrect username or password."])); + } + + return (new Response()) + ->withBody(json_encode(["result" => "ok", "user" => $result["owner"]])); + } + + return (new Response()) + ->withStatus(404) + ->withBody("Not found."); + } } diff --git a/classes/Handler/LogoutHandler.php b/classes/Handler/LogoutHandler.php index 79bc74d..26ae6b6 100644 --- a/classes/Handler/LogoutHandler.php +++ b/classes/Handler/LogoutHandler.php @@ -10,9 +10,9 @@ use Response; class LogoutHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - logout_user(); - return (new Response())->withBody(json_encode(["result" => "OK"])); - } + public function handle(Request $request): Response + { + logout_user(); + return (new Response())->withBody(json_encode(["result" => "OK"])); + } } diff --git a/classes/Handler/PaginationHandler.php b/classes/Handler/PaginationHandler.php index c126762..7015dfc 100644 --- a/classes/Handler/PaginationHandler.php +++ b/classes/Handler/PaginationHandler.php @@ -10,71 +10,71 @@ use Response; class PaginationHandler implements RequestHandlerInterface, AuthRequired { - private function handleGet(int $bookid): Response - { - if ($bookid) { - $pag = ORM::for_table('epube_pagination') - ->where('bookid', $bookid) - ->find_one(); + private function handleGet(int $bookid): Response + { + if ($bookid) { + $pag = ORM::for_table('epube_pagination') + ->where('bookid', $bookid) + ->find_one(); - if ($pag) { - return (new Response())->withBody($pag->pagination); - } - } + if ($pag) { + return (new Response())->withBody($pag->pagination); + } + } - return (new Response()) - ->withStatus(404) - ->withBody("File not found."); - } + return (new Response()) + ->withStatus(404) + ->withBody("File not found."); + } - private function handleStore(int $bookid, ?string $payload): Response - { - if ($bookid && $payload) { - $pag = ORM::for_table('epube_pagination') - ->where('bookid', $bookid) - ->find_one(); + private function handleStore(int $bookid, ?string $payload): Response + { + if ($bookid && $payload) { + $pag = ORM::for_table('epube_pagination') + ->where('bookid', $bookid) + ->find_one(); - if (!$pag) { - $pag = ORM::for_table('epube_pagination')->create(); - $pag->bookid = $bookid; - } + if (!$pag) { + $pag = ORM::for_table('epube_pagination')->create(); + $pag->bookid = $bookid; + } - $pag->pagination = $payload; - $pag->total_pages = 100; - $pag->save(); - } + $pag->pagination = $payload; + $pag->total_pages = 100; + $pag->save(); + } - return new Response(); - } + return new Response(); + } - private function handleDelete(int $bookid): Response - { - if ($bookid) { - $pag = ORM::for_table('epube_pagination') - ->where('bookid', $bookid) - ->find_one(); + private function handleDelete(int $bookid): Response + { + if ($bookid) { + $pag = ORM::for_table('epube_pagination') + ->where('bookid', $bookid) + ->find_one(); - if ($pag) { - $pag->delete(); - return new Response(); - } - } + if ($pag) { + $pag->delete(); + return new Response(); + } + } - return (new Response()) - ->withStatus(404) - ->withBody("Not found."); - } + return (new Response()) + ->withStatus(404) + ->withBody("Not found."); + } - public function handle(Request $request): Response - { - $subOp = $request->getAttribute('op', ''); - $bookid = (int) $request->getAttribute('id'); + public function handle(Request $request): Response + { + $subOp = $request->getAttribute('op', ''); + $bookid = (int) $request->getAttribute('id'); - return match ($subOp) { - 'getpagination' => $this->handleGet($bookid), - 'storepagination' => $this->handleStore($bookid, $request->getAttribute('payload')), - 'deletepagination' => $this->handleDelete($bookid), - default => (new Response())->withStatus(404)->withBody("Not found."), - }; - } + return match ($subOp) { + 'getpagination' => $this->handleGet($bookid), + 'storepagination' => $this->handleStore($bookid, $request->getAttribute('payload')), + 'deletepagination' => $this->handleDelete($bookid), + default => (new Response())->withStatus(404)->withBody("Not found."), + }; + } } diff --git a/classes/Handler/StorelastreadHandler.php b/classes/Handler/StorelastreadHandler.php index 2c2d58b..fa06769 100644 --- a/classes/Handler/StorelastreadHandler.php +++ b/classes/Handler/StorelastreadHandler.php @@ -10,42 +10,42 @@ use Response; class StorelastreadHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $page = (int) $request->getAttribute('page'); - $bookid = (int) $request->getAttribute('id'); - $timestamp = (int) $request->getAttribute('timestamp'); - $cfi = $request->getAttribute('cfi', ''); - $owner = $_SESSION["owner"] ?? ""; + public function handle(Request $request): Response + { + $page = (int) $request->getAttribute('page'); + $bookid = (int) $request->getAttribute('id'); + $timestamp = (int) $request->getAttribute('timestamp'); + $cfi = $request->getAttribute('cfi', ''); + $owner = $_SESSION["owner"] ?? ""; - if ($bookid) { - $book = ORM::for_table('epube_books') - ->where('bookid', $bookid) - ->where('owner', $owner) - ->find_one(); + if ($bookid) { + $book = ORM::for_table('epube_books') + ->where('bookid', $bookid) + ->where('owner', $owner) + ->find_one(); - if ($book) { - if (($timestamp >= $book->lastts) && ($page >= $book->lastread || $page == PAGE_RESET_PROGRESS)) { - $book->set([ - 'lastread' => $page, - 'lastcfi' => $cfi, - 'lastts' => $timestamp, - ]); - } - } else { - $book = ORM::for_table('epube_books')->create(); - $book->set([ - 'bookid' => $bookid, - 'owner' => $owner, - 'lastread' => $page, - 'lastcfi' => $cfi, - 'lastts' => $timestamp, - ]); - } + if ($book) { + if (($timestamp >= $book->lastts) && ($page >= $book->lastread || $page == PAGE_RESET_PROGRESS)) { + $book->set([ + 'lastread' => $page, + 'lastcfi' => $cfi, + 'lastts' => $timestamp, + ]); + } + } else { + $book = ORM::for_table('epube_books')->create(); + $book->set([ + 'bookid' => $bookid, + 'owner' => $owner, + 'lastread' => $page, + 'lastcfi' => $cfi, + 'lastts' => $timestamp, + ]); + } - $book->save(); - } + $book->save(); + } - return (new Response())->withBody(json_encode(["page" => $page, "cfi" => $cfi])); - } + return (new Response())->withBody(json_encode(["page" => $page, "cfi" => $cfi])); + } } diff --git a/classes/Handler/TogglefavHandler.php b/classes/Handler/TogglefavHandler.php index 3b203ad..543b7a4 100644 --- a/classes/Handler/TogglefavHandler.php +++ b/classes/Handler/TogglefavHandler.php @@ -10,27 +10,27 @@ use Response; class TogglefavHandler implements RequestHandlerInterface, AuthRequired { - public function handle(Request $request): Response - { - $bookid = (int) $request->getAttribute('id'); - $owner = $_SESSION["owner"] ?? ""; + public function handle(Request $request): Response + { + $bookid = (int) $request->getAttribute('id'); + $owner = $_SESSION["owner"] ?? ""; - $fav = ORM::for_table('epube_favorites') - ->where('bookid', $bookid) - ->where('owner', $owner) - ->find_one(); + $fav = ORM::for_table('epube_favorites') + ->where('bookid', $bookid) + ->where('owner', $owner) + ->find_one(); - if ($fav) { - $fav->delete(); - $status = 0; - } else { - $fav = ORM::for_table('epube_favorites')->create(); - $fav->bookid = $bookid; - $fav->owner = $owner; - $fav->save(); - $status = 1; - } + if ($fav) { + $fav->delete(); + $status = 0; + } else { + $fav = ORM::for_table('epube_favorites')->create(); + $fav->bookid = $bookid; + $fav->owner = $owner; + $fav->save(); + $status = 1; + } - return (new Response())->withBody(json_encode(["id" => $bookid, "status" => $status])); - } + return (new Response())->withBody(json_encode(["id" => $bookid, "status" => $status])); + } } diff --git a/classes/MiddlewareInterface.php b/classes/MiddlewareInterface.php index ae1949e..ac43ef2 100644 --- a/classes/MiddlewareInterface.php +++ b/classes/MiddlewareInterface.php @@ -2,5 +2,5 @@ interface MiddlewareInterface { - public function process(Request $request, callable $next): Response; + public function process(Request $request, callable $next): Response; } diff --git a/classes/Request.php b/classes/Request.php index b3d2b62..d337740 100644 --- a/classes/Request.php +++ b/classes/Request.php @@ -2,56 +2,56 @@ class Request { - /** @var array<string, mixed> */ - private array $serverParams; - /** @var array<string, mixed> */ - private array $queryParams; - /** @var array<string, mixed> */ - private array $bodyParams; - /** @var array<string, mixed> */ - private array $cookies; - - public function __construct() - { - $this->serverParams = $_SERVER; - $this->queryParams = $_GET; - $this->bodyParams = $_POST; - $this->cookies = $_COOKIE; - } - - /** @return array<string, mixed> */ - public function getServerParams(): array - { - return $this->serverParams; - } - - /** @return array<string, mixed> */ - public function getQueryParams(): array - { - return $this->queryParams; - } - - /** @return array<string, mixed> */ - public function getParsedBody(): array - { - return array_merge($this->queryParams, $this->bodyParams); - } - - /** @return array<string, mixed> */ - public function getCookieParams(): array - { - return $this->cookies; - } - - public function getAttribute(string $name, mixed $default = null): mixed - { - return $this->getParsedBody()[$name] ?? $default; - } - - public function withAttribute(string $name, mixed $value): self - { - $clone = clone $this; - $clone->bodyParams[$name] = $value; - return $clone; - } + /** @var array<string, mixed> */ + private array $serverParams; + /** @var array<string, mixed> */ + private array $queryParams; + /** @var array<string, mixed> */ + private array $bodyParams; + /** @var array<string, mixed> */ + private array $cookies; + + public function __construct() + { + $this->serverParams = $_SERVER; + $this->queryParams = $_GET; + $this->bodyParams = $_POST; + $this->cookies = $_COOKIE; + } + + /** @return array<string, mixed> */ + public function getServerParams(): array + { + return $this->serverParams; + } + + /** @return array<string, mixed> */ + public function getQueryParams(): array + { + return $this->queryParams; + } + + /** @return array<string, mixed> */ + public function getParsedBody(): array + { + return array_merge($this->queryParams, $this->bodyParams); + } + + /** @return array<string, mixed> */ + public function getCookieParams(): array + { + return $this->cookies; + } + + public function getAttribute(string $name, mixed $default = null): mixed + { + return $this->getParsedBody()[$name] ?? $default; + } + + public function withAttribute(string $name, mixed $value): self + { + $clone = clone $this; + $clone->bodyParams[$name] = $value; + return $clone; + } } diff --git a/classes/RequestHandlerInterface.php b/classes/RequestHandlerInterface.php index fefe816..364ed3a 100644 --- a/classes/RequestHandlerInterface.php +++ b/classes/RequestHandlerInterface.php @@ -2,5 +2,5 @@ interface RequestHandlerInterface { - public function handle(Request $request): Response; + public function handle(Request $request): Response; } diff --git a/classes/Response.php b/classes/Response.php index dcbbc5b..a0620ae 100644 --- a/classes/Response.php +++ b/classes/Response.php @@ -2,45 +2,45 @@ class Response { - private int $status = 200; - /** @var array<string, string> */ - private array $headers = []; - private string $body = ''; + private int $status = 200; + /** @var array<string, string> */ + private array $headers = []; + private string $body = ''; - public function withStatus(int $code, string $reasonPhrase = ''): self - { - $clone = clone $this; - $clone->status = $code; - return $clone; - } + public function withStatus(int $code, string $reasonPhrase = ''): self + { + $clone = clone $this; + $clone->status = $code; + return $clone; + } - public function withHeader(string $name, string $value): self - { - $clone = clone $this; - $clone->headers[$name] = $value; - return $clone; - } + public function withHeader(string $name, string $value): self + { + $clone = clone $this; + $clone->headers[$name] = $value; + return $clone; + } - public function getBody(): string - { - return $this->body; - } + public function getBody(): string + { + return $this->body; + } - public function withBody(string $body): self - { - $clone = clone $this; - $clone->body = $body; - return $clone; - } + public function withBody(string $body): self + { + $clone = clone $this; + $clone->body = $body; + return $clone; + } - public function send(): void - { - if ($this->headers) { - foreach ($this->headers as $name => $value) { - header("$name: $value"); - } - } - http_response_code($this->status); - echo $this->body; - } + public function send(): void + { + if ($this->headers) { + foreach ($this->headers as $name => $value) { + header("$name: $value"); + } + } + http_response_code($this->status); + echo $this->body; + } } diff --git a/classes/Router.php b/classes/Router.php index 6d46cfd..6afec1e 100644 --- a/classes/Router.php +++ b/classes/Router.php @@ -2,56 +2,56 @@ class Router { - /** @var array<string, RequestHandlerInterface> */ - private array $routes = []; - - /** @var MiddlewareInterface[] */ - private array $middleware = []; - - public function addRoute(string $op, RequestHandlerInterface $handler): void - { - $this->routes[$op] = $handler; - } - - public function addMiddleware(MiddlewareInterface $middleware): void - { - $this->middleware[] = $middleware; - } - - public function dispatch(string $op): Response - { - $handler = $this->routes[$op] ?? null; - - if (!$handler) { - $response = (new Response()) - ->withStatus(404) - ->withBody("Method not found."); - $response->send(); - exit; - } - - // Check auth for handlers that require it - if ($handler instanceof AuthRequired && empty($_SESSION["owner"])) { - $response = (new Response()) - ->withStatus(401) - ->withBody("Unauthorized"); - $response->send(); - exit; - } - - $pipe = $handler->handle(...); - - // wrap middleware in reverse order (last added = outermost) - foreach (array_reverse($this->middleware) as $mw) { - $previous = $pipe; - $pipe = fn(Request $r) => $mw->process($r, $previous); - } - - $request = new Request(); - $request = $request->withAttribute('op', $op); - - $response = $pipe($request); - $response->send(); - exit; - } + /** @var array<string, RequestHandlerInterface> */ + private array $routes = []; + + /** @var MiddlewareInterface[] */ + private array $middleware = []; + + public function addRoute(string $op, RequestHandlerInterface $handler): void + { + $this->routes[$op] = $handler; + } + + public function addMiddleware(MiddlewareInterface $middleware): void + { + $this->middleware[] = $middleware; + } + + public function dispatch(string $op): Response + { + $handler = $this->routes[$op] ?? null; + + if (!$handler) { + $response = (new Response()) + ->withStatus(404) + ->withBody("Method not found."); + $response->send(); + exit; + } + + // Check auth for handlers that require it + if ($handler instanceof AuthRequired && empty($_SESSION["owner"])) { + $response = (new Response()) + ->withStatus(401) + ->withBody("Unauthorized"); + $response->send(); + exit; + } + + $pipe = $handler->handle(...); + + // wrap middleware in reverse order (last added = outermost) + foreach (array_reverse($this->middleware) as $mw) { + $previous = $pipe; + $pipe = fn(Request $r) => $mw->process($r, $previous); + } + + $request = new Request(); + $request = $request->withAttribute('op', $op); + + $response = $pipe($request); + $response->send(); + exit; + } } |
