diff options
| author | fox <fox@fakecake.org> | 2026-06-15 22:12:27 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-06-15 22:12:27 +0300 |
| commit | 789758a094d4885432f165c0c8a419adeb55906c (patch) | |
| tree | b5e4229ed2119bcfc0b59cf3f634fd8fa503cf0c | |
| parent | 3a87066a7cf645eb8f8ddbc5d031afe753516de9 (diff) | |
| parent | 7d5e7b0f95992650189b73c6160264db6b658bde (diff) | |
| download | the-epube-789758a094d4885432f165c0c8a419adeb55906c.tar.gz the-epube-789758a094d4885432f165c0c8a419adeb55906c.tar.xz | |
Merge branch 'dev' into 'master'
remove dedicated getinfo handler because list may operate on IDs; add some... See merge request git/the-epube!56
| -rw-r--r-- | .docker/web-nginx/nginx.conf | 3 | ||||
| -rw-r--r-- | backend.php | 1 | ||||
| -rw-r--r-- | classes/CsrfMiddleware.php | 4 | ||||
| -rw-r--r-- | classes/Handler/CoverHandler.php | 2 | ||||
| -rw-r--r-- | classes/Handler/DefineHandler.php | 2 | ||||
| -rw-r--r-- | classes/Handler/DownloadHandler.php | 2 | ||||
| -rw-r--r-- | classes/Handler/GetinfoHandler.php | 38 | ||||
| -rw-r--r-- | classes/Handler/LastreadHandler.php | 10 | ||||
| -rw-r--r-- | classes/Handler/ListHandler.php | 21 | ||||
| -rw-r--r-- | classes/Handler/LoginHandler.php | 6 | ||||
| -rw-r--r-- | classes/Handler/PaginationHandler.php | 6 | ||||
| -rw-r--r-- | classes/Handler/TogglefavHandler.php | 2 | ||||
| -rw-r--r-- | classes/Request.php | 392 | ||||
| -rw-r--r-- | include/common.php | 13 | ||||
| -rw-r--r-- | phpstan.neon | 2 | ||||
| -rw-r--r-- | src/app.js | 12 | ||||
| -rw-r--r-- | src/index.d.ts | 9 | ||||
| -rw-r--r-- | src/reader.js | 10 | ||||
| -rw-r--r-- | src/worker.js | 4 | ||||
| -rw-r--r-- | tests/RequestTest.php | 513 | ||||
| -rw-r--r-- | tests_integration/CsrfMiddlewareTest.php | 21 | ||||
| -rw-r--r-- | tests_integration/GetinfoHandlerTest.php | 167 |
22 files changed, 945 insertions, 295 deletions
diff --git a/.docker/web-nginx/nginx.conf b/.docker/web-nginx/nginx.conf index 8ee0d91..8fb8ce2 100644 --- a/.docker/web-nginx/nginx.conf +++ b/.docker/web-nginx/nginx.conf @@ -39,6 +39,9 @@ http { return 301 $base_path/index.html; } + # pagination may be quite large + client_max_body_size 0; + location ~ \.php$ { # regex to split $uri to $fastcgi_script_name and $fastcgi_path fastcgi_split_path_info ^(.+?\.php)(/.*)$; diff --git a/backend.php b/backend.php index 135943c..028f4d1 100644 --- a/backend.php +++ b/backend.php @@ -17,7 +17,6 @@ $router->addRoute("oidc-login-callback", new \Handler\LoginHandler()); $router->addRoute("healthz", new \Handler\HealthzHandler()); $router->addRoute("cover", new \Handler\CoverHandler()); - $router->addRoute("getinfo", new \Handler\GetinfoHandler()); $router->addRoute("list", new \Handler\ListHandler()); $router->addRoute("togglefav", new \Handler\TogglefavHandler()); $router->addRoute("download", new \Handler\DownloadHandler()); diff --git a/classes/CsrfMiddleware.php b/classes/CsrfMiddleware.php index 0a03925..c9374b0 100644 --- a/classes/CsrfMiddleware.php +++ b/classes/CsrfMiddleware.php @@ -13,9 +13,9 @@ class CsrfMiddleware implements MiddlewareInterface return $next($request); } - $op = $request->getAttribute('op'); + $op = $request->getString('op'); - $csrfToken = $request->getAttribute('csrf_token', ''); + $csrfToken = $request->getString('csrf_token', ''); if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) { $response = (new Response()) diff --git a/classes/Handler/CoverHandler.php b/classes/Handler/CoverHandler.php index 4e95e54..cd26308 100644 --- a/classes/Handler/CoverHandler.php +++ b/classes/Handler/CoverHandler.php @@ -13,7 +13,7 @@ class CoverHandler implements RequestHandlerInterface, AuthRequired { public function handle(Request $request): Response { - $id = (int) $request->getAttribute('id'); + $id = $request->getInt('id'); $db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); $sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?"); $sth->execute([$id]); diff --git a/classes/Handler/DefineHandler.php b/classes/Handler/DefineHandler.php index 60d5b11..7906adc 100644 --- a/classes/Handler/DefineHandler.php +++ b/classes/Handler/DefineHandler.php @@ -32,7 +32,7 @@ class DefineHandler implements RequestHandlerInterface, AuthRequired return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]])); } - $word = strip_tags(str_replace("", "", $request->getAttribute('word'))); + $word = strip_tags(str_replace("", "", $request->getString('word'))); $origWord = $word; $result = []; diff --git a/classes/Handler/DownloadHandler.php b/classes/Handler/DownloadHandler.php index 330c04f..da50c90 100644 --- a/classes/Handler/DownloadHandler.php +++ b/classes/Handler/DownloadHandler.php @@ -13,7 +13,7 @@ class DownloadHandler implements RequestHandlerInterface, AuthRequired { public function handle(Request $request): Response { - $bookid = (int) $request->getAttribute('id'); + $bookid = $request->getInt('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]); diff --git a/classes/Handler/GetinfoHandler.php b/classes/Handler/GetinfoHandler.php deleted file mode 100644 index ee4a69a..0000000 --- a/classes/Handler/GetinfoHandler.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php - -namespace Handler; - -use AuthRequired; -use Config; -use Request; -use RequestHandlerInterface; -use Response; -use PDO; -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)); - - $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()) { - $row['comment'] = Sanitizer::sanitize($row['comment'] ?? ""); - - return (new Response())->withBody(json_encode($row)); - } - - return (new Response()) - ->withStatus(404) - ->withBody(json_encode(["error" => "Not found."])); - } -} diff --git a/classes/Handler/LastreadHandler.php b/classes/Handler/LastreadHandler.php index ab177ed..638db25 100644 --- a/classes/Handler/LastreadHandler.php +++ b/classes/Handler/LastreadHandler.php @@ -68,16 +68,16 @@ class LastreadHandler implements RequestHandlerInterface, AuthRequired public function handle(Request $request): Response { - $subOp = $request->getAttribute('op', ''); - $bookid = (int) $request->getAttribute('id'); + $subOp = $request->getString('op', ''); + $bookid = $request->getInt('id'); return match ($subOp) { 'getlastread' => $this->handleGet($bookid), 'storelastread' => $this->handleStore( $bookid, - (int) $request->getAttribute('page'), - (string) $request->getAttribute('cfi', ''), - (int) $request->getAttribute('timestamp'), + $request->getInt('page'), + $request->getString('cfi', ''), + $request->getInt('timestamp'), ), default => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])), }; diff --git a/classes/Handler/ListHandler.php b/classes/Handler/ListHandler.php index 9c65176..e8a5916 100644 --- a/classes/Handler/ListHandler.php +++ b/classes/Handler/ListHandler.php @@ -14,15 +14,17 @@ 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); + $mode = $request->getString('mode', ''); + $query = $request->getString('query', ''); + $limit = $request->getInt('limit', 60); + $offset = $request->getInt('offset', 0); $ldb = \Db::pdo(); $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB)); - $ids_qpart = "1"; + $ids = array_filter( + explode(",", $request->getString('ids', '')), 'intval'); + if ($mode == "favorites") { $fav_sth = $ldb->prepare("SELECT bookid FROM epube_favorites WHERE owner = ?"); @@ -38,14 +40,19 @@ class ListHandler implements RequestHandlerInterface, AuthRequired } $ids_qpart = "books.id IN (" . implode(",", $fav_ids) . ")"; + } else if (count($ids) > 0) { + $ids_qpart = "books.id IN (" . implode(",", $ids) . ")"; + } else { + $ids_qpart = "1"; } $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, + $sth = $caldb->prepare("SELECT books.*, s.name AS series_name, c.text 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) + LEFT JOIN comments AS c ON (c.book = books.id) WHERE ((:query = '') OR ( @@ -117,11 +124,13 @@ class ListHandler implements RequestHandlerInterface, AuthRequired "series_name" => $line["series_name"] ?? "", "series_index" => $line["series_index"] ?? 0, "cover_link" => $cover_link, + "has_cover" => $line["has_cover"] == 1, "in_progress" => $in_progress, "is_read" => $is_read, "is_fav" => $is_fav, "epub_id" => $line["epub_id"] ?? 0, "download_formats" => $download_formats, + "comment" => \Sanitizer::sanitize($line["comment"] ?? "") ]; } diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php index f8a2b41..7fb1449 100644 --- a/classes/Handler/LoginHandler.php +++ b/classes/Handler/LoginHandler.php @@ -107,7 +107,7 @@ class LoginHandler implements RequestHandlerInterface public function handle(Request $request): Response { - $op = $request->getAttribute('op', ''); + $op = $request->getString('op', ''); // Redirect to OIDC provider if ($op === "perform-oidc-login") { @@ -150,8 +150,8 @@ class LoginHandler implements RequestHandlerInterface // Local username/password login if ($op === "perform-login") { - $username = trim(mb_strtolower($request->getAttribute('user', ''))); - $password = $request->getAttribute('password', ''); + $username = trim(mb_strtolower($request->getString('user', ''))); + $password = $request->getString('password', ''); if (!$username || !$password) { return (new Response()) diff --git a/classes/Handler/PaginationHandler.php b/classes/Handler/PaginationHandler.php index a027c58..3c0555b 100644 --- a/classes/Handler/PaginationHandler.php +++ b/classes/Handler/PaginationHandler.php @@ -67,12 +67,12 @@ class PaginationHandler implements RequestHandlerInterface, AuthRequired public function handle(Request $request): Response { - $subOp = $request->getAttribute('op', ''); - $bookid = (int) $request->getAttribute('id'); + $subOp = $request->getString('op', ''); + $bookid = $request->getInt('id'); return match ($subOp) { 'getpagination' => $this->handleGet($bookid), - 'storepagination' => $this->handleStore($bookid, $request->getAttribute('payload')), + 'storepagination' => $this->handleStore($bookid, $request->getString('payload')), 'deletepagination' => $this->handleDelete($bookid), default => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])), }; diff --git a/classes/Handler/TogglefavHandler.php b/classes/Handler/TogglefavHandler.php index 3b203ad..d6a3913 100644 --- a/classes/Handler/TogglefavHandler.php +++ b/classes/Handler/TogglefavHandler.php @@ -12,7 +12,7 @@ class TogglefavHandler implements RequestHandlerInterface, AuthRequired { public function handle(Request $request): Response { - $bookid = (int) $request->getAttribute('id'); + $bookid = $request->getInt('id'); $owner = $_SESSION["owner"] ?? ""; $fav = ORM::for_table('epube_favorites') diff --git a/classes/Request.php b/classes/Request.php index b3d2b62..3a8e696 100644 --- a/classes/Request.php +++ b/classes/Request.php @@ -1,57 +1,373 @@ <?php +/** + * Typed parameter extraction wrapper around PHP superglobals. + * + * Provides clean, type-safe access to request parameters, replacing the + * repetitive clean($_REQUEST['key'] ?? default) pattern throughout handlers. + * + * Usage: + * $request = new Request(); + * $id = $request->getInt('id', 0); + * $name = $request->getString('name', ''); + * $flag = $request->getBool('flag', false); + * $ids = $request->getArray('ids', []); + * + * Can also extract from specific superglobals: + * $request->fromPost()->getString('login'); + * $request->fromGet()->getInt('limit', 20); + */ +class Request { -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 const SOURCE_REQUEST = 'request'; + public const SOURCE_GET = 'get'; + public const SOURCE_POST = 'post'; + public const SOURCE_BODY = 'body'; - public function __construct() - { - $this->serverParams = $_SERVER; - $this->queryParams = $_GET; - $this->bodyParams = $_POST; - $this->cookies = $_COOKIE; + /** @var array<int|string, mixed>|null */ + private ?array $data = null; + + /** @var array<int|string, mixed>|null */ + private ?array $body = null; + + /** @var array<int|string, mixed> */ + private array $attributes = []; + + /** @var self::SOURCE_* */ + private string $source = self::SOURCE_REQUEST; + + /** + * @param array<int|string, mixed>|null $data Optional explicit data source (e.g. from constructor arg) + */ + public function __construct(?array $data = null) { + $this->data = $data; + } + + /** + * Extract from the given superglobal. + * + * @param self::SOURCE_* $source + * @return $this + */ + public function from(string $source): self { + $this->source = $source; + return $this; + } + + /** + * Extract from $_POST. + * @return $this + */ + public function fromPost(): self { + return $this->from(self::SOURCE_POST); + } + + /** + * Extract from $_GET. + * @return $this + */ + public function fromGet(): self { + return $this->from(self::SOURCE_GET); + } + + /** + * Extract from $_REQUEST (default). + * @return $this + */ + public function fromRequest(): self { + return $this->from(self::SOURCE_REQUEST); } - /** @return array<string, mixed> */ - public function getServerParams(): array - { - return $this->serverParams; + /** + * Extract from the raw request body (php://input). + * + * Inspects Content-Type to determine parsing strategy: + * - application/json / text/json → JSON decode + * - application/x-www-form-urlencoded → parse_str (like $_POST) + * - anything else / missing → empty array + * + * If JSON decoding fails, an empty array is returned so downstream + * getters fall back to defaults. + * + * Useful for PATCH/PUT requests where $_POST is not populated. + * + * @return $this + */ + public function fromBody(): self { + if ($this->body !== null) { + return $this; + } + + $raw = file_get_contents('php://input'); + if ($raw === '') { + $this->body = []; + return $this; + } + + // Determine content type, stripping charset etc. + $contentType = strtolower(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0]); + + if (in_array($contentType, ['application/json', 'text/json'], true)) { + $decoded = json_decode($raw, true); + $this->body = is_array($decoded) ? $decoded : []; + } elseif ($contentType === 'application/x-www-form-urlencoded') { + parse_str($raw, $parsed); + $this->body = $parsed; + } else { + $this->body = []; + } + + return $this->from(self::SOURCE_BODY); + } + + /** + * Get a sanitized string value. + * + * @param string $key + * @param string $default + * @return string + */ + public function getString(string $key, string $default = ''): string { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return clean((string)$value); } - /** @return array<string, mixed> */ - public function getQueryParams(): array - { - return $this->queryParams; + /** + * Get a sanitized integer value. + * + * @param string $key + * @param int $default + * @return int + */ + public function getInt(string $key, int $default = 0): int { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return (int) clean((string)$value); } - /** @return array<string, mixed> */ - public function getParsedBody(): array - { - return array_merge($this->queryParams, $this->bodyParams); + /** + * Get a sanitized float value. + * + * @param string $key + * @param float $default + * @return float + */ + public function getFloat(string $key, float $default = 0.0): float { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return (float) clean((string)$value); } - /** @return array<string, mixed> */ - public function getCookieParams(): array - { - return $this->cookies; + /** + * Get a sanitized boolean value. + * + * Treats the following as true: "1", "true", "t", "on", non-zero integers, + * non-empty strings. All other values are treated as false. + * + * @param string $key + * @param bool $default + * @return bool + */ + public function getBool(string $key, bool $default = false): bool { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + return self::_to_bool($value); } - public function getAttribute(string $name, mixed $default = null): mixed - { - return $this->getParsedBody()[$name] ?? $default; + /** + * Get a sanitized array value. + * + * If the value is a comma-separated string, it will be split into an array. + * Each element is trimmed and HTML tags are stripped. + * + * @param string $key + * @param array<int|string, mixed> $default + * @return array<int|string, mixed> + */ + public function getArray(string $key, array $default = []): array { + $value = $this->getRaw($key); + if ($value === null) { + return $default; + } + + if (is_array($value)) { + return clean($value); + } + + // Handle comma-separated string values + $cleaned = clean((string)$value); + if ($cleaned === '') { + return []; + } + + return array_map('trim', explode(',', $cleaned)); } - public function withAttribute(string $name, mixed $value): self - { + /** + * Get the raw (unsanitized) value. + * + * @param string $key + * @return mixed|null + */ + public function getRaw(string $key): mixed { + return match ($this->source) { + self::SOURCE_POST => $_POST[$key] ?? null, + self::SOURCE_GET => $_GET[$key] ?? null, + self::SOURCE_BODY => $this->body[$key] ?? null, + default => $this->data !== null ? ($this->data[$key] ?? null) : ($_REQUEST[$key] ?? null), + }; + } + + /** + * Check if a key exists in the current source. + * + * @param string $key + * @return bool + */ + public function has(string $key): bool { + return match ($this->source) { + self::SOURCE_POST => array_key_exists($key, $_POST), + self::SOURCE_GET => array_key_exists($key, $_GET), + self::SOURCE_BODY => array_key_exists($key, $this->body), + default => $this->data !== null + ? array_key_exists($key, $this->data) + : array_key_exists($key, $_REQUEST), + }; + } + + /** + * Get all parameters from the current source. + * + * @return array<int|string, mixed> + */ + public function all(): array { + return match ($this->source) { + self::SOURCE_POST => $_POST, + self::SOURCE_GET => $_GET, + self::SOURCE_BODY => $this->body ?? [], + default => $this->data !== null ? $this->data : $_REQUEST, + }; + } + + /** + * Get all query parameters (\$_GET). + * + * @return array<int|string, mixed> + */ + public function getQueryParams(): array { + return $_GET; + } + + /** + * Get all server parameters (\$_SERVER). + * + * @return array<int|string, mixed> + */ + public function getServerParams(): array { + return $_SERVER; + } + + /** + * Get all cookie parameters (\$_COOKIE). + * + * @return array<int|string, mixed> + */ + public function getCookieParams(): array { + return $_COOKIE; + } + + /** + * Get a merged body from \$_GET and \$_POST, with \$_POST values + * overriding \$_GET on key collision. + * + * @return array<int|string, mixed> + */ + public function getParsedBody(): array { + return array_merge($_GET, $_POST); + } + + /** + * Get an attribute or request parameter by key. + * + * Looks first in attributes set via withAttribute(), then in the + * parsed body (\$_GET + \$_POST merged). + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function getAttribute(string $key, mixed $default = null): mixed { + // Check attributes first + if (array_key_exists($key, $this->attributes)) { + return $this->attributes[$key]; + } + + // Fall back to parsed body + $body = $this->getParsedBody(); + return $body[$key] ?? $default; + } + + /** + * Return a clone of this request with a new attribute added. + * + * @param string $key + * @param mixed $value + * @return self + */ + public function withAttribute(string $key, mixed $value): self { $clone = clone $this; - $clone->bodyParams[$name] = $value; + $clone->attributes[$key] = $value; return $clone; } + + /** + * Get a subset of parameters by key names. + * + * @param array<int, string> $keys + * @return array<int|string, mixed> + */ + public function only(array $keys): array { + $result = []; + foreach ($keys as $key) { + $result[$key] = $this->getRaw($key); + } + return $result; + } + + /** + * Convert a value to boolean using the same logic as Handler::_param_to_bool(). + * + * @param mixed $value + * @return bool + */ + public static function _to_bool(mixed $value): bool { + $value = clean($value); + + if (is_bool($value)) { + return $value; + } + + if (is_int($value)) { + return $value !== 0; + } + + if (is_float($value)) { + return $value != 0.0; + } + + if (is_string($value)) { + $lower = strtolower($value); + return in_array($lower, ['1', 'true', 't', 'on'], true); + } + + return (bool) $value; + } } diff --git a/include/common.php b/include/common.php index 12753c8..684d9c6 100644 --- a/include/common.php +++ b/include/common.php @@ -32,3 +32,16 @@ return ""; } + + /** + * This is used for user http parameters unless HTML code is actually needed. + */ + function clean(mixed $param): mixed { + if (is_array($param)) { + return array_map("trim", array_map("strip_tags", $param)); + } else if (is_string($param)) { + return trim(strip_tags($param)); + } else { + return $param; + } + } diff --git a/phpstan.neon b/phpstan.neon index 678dbbd..7542412 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -9,6 +9,8 @@ parameters: # set_include_path detection issue - message: '#"(autoload|common)\.php"#' identifier: requireOnce.fileNotFound + # allow passing a 'strlen' string, etc. as the array_filter callback + - "/Parameter #2 \\$callback of function array_filter expects .+ '.+' given/" excludePaths: - node_modules/* - vendor/**/* diff --git a/src/app.js b/src/app.js index 5cbf7ec..82a0013 100644 --- a/src/app.js +++ b/src/app.js @@ -232,7 +232,12 @@ class AppClass extends AppCommon { if (this.isOnline()) { - const data = await $.post("backend.php", {op: 'getinfo', id: bookId}); + /** @type{BookList} */ + const reply = await $.post("backend.php", {op: 'list', ids: bookId}); + + /** @type{BookInfo} */ + const data = reply['books'][0]; + const comment = data.comment ? data.comment : 'No description available'; $("#summary-modal .modal-title").text(data.title); @@ -383,7 +388,10 @@ class AppClass extends AppCommon { get(bookId, callback) { console.log("offline cache: " + bookId); - $.post("backend.php", {op: "getinfo", id: bookId}, (data) => { + $.post("backend.php", {op: "list", ids: bookId}, (/** @type{BookList} */ reply) => { + + /** @type{BookInfo} */ + const data = reply['books'][0]; if (data) { const cacheId = 'epube-book.' + bookId; diff --git a/src/index.d.ts b/src/index.d.ts index d7a8861..60ffba3 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -27,6 +27,15 @@ declare interface BookInfo { is_fav: boolean; epub_id: number; download_formats: DownloadFormat[]; + comment: string; + has_cover: boolean; +} + +declare interface BookList { + books: BookInfo[]; + total: number; + offset: number; + limit: number; } declare var EpubeApp: EpubeApp; diff --git a/src/reader.js b/src/reader.js index 7bcac76..0c61a0c 100644 --- a/src/reader.js +++ b/src/reader.js @@ -222,16 +222,20 @@ class ReaderClass extends AppCommon { console.log('requesting bookinfo for book', bookId) try { - const resp = await $.post("backend.php", {op: "getinfo", id: bookId }); + /** @type{BookList} */ + const resp = await $.post("backend.php", {op: "list", ids: bookId }); - if (resp.has_cover) { + /** @type{BookInfo} */ + const info = resp['books'][0]; + + if (info.has_cover) { const cover = await fetch("backend.php?op=cover&id=" + bookId); if (cover.ok) await localforage.setItem(this.cacheId('cover'), cover.blob()); } - await localforage.setItem(this.cacheId(), resp); + await localforage.setItem(this.cacheId(), info); console.log('bookinfo saved'); diff --git a/src/worker.js b/src/worker.js index 414c328..94da8db 100644 --- a/src/worker.js +++ b/src/worker.js @@ -80,8 +80,8 @@ sw.addEventListener('fetch', (event) => { // /assets/ belong to android app if (url.pathname.startsWith('/assets/')) return; - // request specific API endpoints from the network if possible and cache them locally - if (url.pathname.match('backend.php\\?op=(cover|getinfo)')) { + // request API endpoints from the network if possible and cache them locally + if (url.pathname.match('backend.php')) { event.respondWith( // @ts-ignore-next-line (async () => { diff --git a/tests/RequestTest.php b/tests/RequestTest.php index 1f45505..fc7ff97 100644 --- a/tests/RequestTest.php +++ b/tests/RequestTest.php @@ -3,6 +3,15 @@ use PHPUnit\Framework\TestCase; final class RequestTest extends TestCase { + protected function setUp(): void + { + $_GET = $_POST = $_REQUEST = $_COOKIE = $_SERVER = []; + } + + protected function tearDown(): void + { + $_GET = $_POST = $_REQUEST = $_COOKIE = $_SERVER = []; + } // ── getQueryParams() ───────────────────────────────────────────────────── public function test_get_query_params_returns_get(): void @@ -140,4 +149,508 @@ final class RequestTest extends TestCase $newRequest = $request->withAttribute('op', 'getinfo'); $this->assertEquals('getinfo', $newRequest->getAttribute('op')); } + + // ── __construct() ──────────────────────────────────────────────────────── + + public function test_construct_with_explicit_data(): void + { + $request = new Request(['op' => 'list', 'limit' => '20']); + $this->assertEquals('list', $request->getString('op')); + $this->assertEquals(20, $request->getInt('limit')); + } + + public function test_construct_with_null_data(): void + { + $request = new Request(null); + $this->assertEquals('', $request->getString('missing')); + } + + // ── from() / fromPost() / fromGet() / fromRequest() ───────────────────── + + public function test_from_set_source_to_post(): void + { + $_GET = ['op' => 'list']; + $_POST = ['op' => 'post-op']; + $request = new Request(); + $request->from(Request::SOURCE_POST); + $this->assertEquals('post-op', $request->getString('op')); + } + + public function test_from_set_source_to_get(): void + { + $_GET = ['op' => 'get-op']; + $_POST = ['op' => 'post-op']; + $request = new Request(); + $request->from(Request::SOURCE_GET); + $this->assertEquals('get-op', $request->getString('op')); + } + + public function test_from_set_source_to_request(): void + { + $_REQUEST = ['op' => 'request-op']; + $request = new Request(); + $request->from(Request::SOURCE_REQUEST); + $this->assertEquals('request-op', $request->getString('op')); + } + + public function test_from_returns_self_for_chaining(): void + { + $request = new Request(); + $this->assertSame($request, $request->from(Request::SOURCE_POST)); + } + + public function test_from_post_returns_self(): void + { + $_POST = ['op' => 'post-op']; + $request = new Request(); + $this->assertSame($request, $request->fromPost()); + } + + public function test_from_get_returns_self(): void + { + $_GET = ['op' => 'get-op']; + $request = new Request(); + $this->assertSame($request, $request->fromGet()); + } + + public function test_from_request_returns_self(): void + { + $_REQUEST = ['op' => 'request-op']; + $request = new Request(); + $this->assertSame($request, $request->fromRequest()); + } + + // ── fromBody() ────────────────────────────────────────────────────────── + + public function test_from_body_json_decodes(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + // Use constructor data so getRaw works without php://input + $request = new Request(['name' => 'json-value']); + $request->from(Request::SOURCE_BODY); + // Body is empty since php://input is not available, but + // the method should not throw and returns $this. + $this->assertEquals([], $request->all()); + } + + public function test_from_body_returns_self(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $request = new Request(); + $this->assertSame($request, $request->fromBody()); + } + + public function test_from_body_is_idempotent(): void + { + $_SERVER['CONTENT_TYPE'] = 'application/json'; + $request = new Request(); + $request->fromBody(); + $request->fromBody(); + // Should not double-read php://input; no exception = success + $this->expectNotToPerformAssertions(); + } + + // ── getString() ────────────────────────────────────────────────────────── + + public function test_get_string_returns_value(): void + { + $_REQUEST = ['name' => 'hello']; + $request = new Request(); + $this->assertEquals('hello', $request->getString('name')); + } + + public function test_get_string_returns_default_when_missing(): void + { + $_REQUEST = []; + $request = new Request(); + $this->assertEquals('default', $request->getString('missing', 'default')); + } + + public function test_get_string_sanitizes_input(): void + { + $_REQUEST = ['html' => '<script>alert(1)</script>']; + $request = new Request(); + $this->assertEquals('alert(1)', $request->getString('html')); + } + + public function test_get_string_handles_numeric_value(): void + { + $_REQUEST = ['count' => '42']; + $request = new Request(); + $this->assertEquals('42', $request->getString('count')); + } + + public function test_get_string_with_explicit_data(): void + { + $request = new Request(['name' => 'from-data']); + $this->assertEquals('from-data', $request->getString('name')); + } + + // ── getInt() ───────────────────────────────────────────────────────────── + + public function test_get_int_returns_value(): void + { + $_REQUEST = ['page' => '3']; + $request = new Request(); + $this->assertEquals(3, $request->getInt('page')); + } + + public function test_get_int_returns_default_when_missing(): void + { + $_REQUEST = []; + $request = new Request(); + $this->assertEquals(10, $request->getInt('page', 10)); + } + + public function test_get_int_handles_non_numeric_string(): void + { + $_REQUEST = ['page' => 'abc']; + $request = new Request(); + $this->assertEquals(0, $request->getInt('page')); + } + + public function test_get_int_with_explicit_data(): void + { + $request = new Request(['count' => '7']); + $this->assertEquals(7, $request->getInt('count')); + } + + // ── getFloat() ─────────────────────────────────────────────────────────── + + public function test_get_float_returns_value(): void + { + $_REQUEST = ['price' => '19.99']; + $request = new Request(); + $this->assertEquals(19.99, $request->getFloat('price')); + } + + public function test_get_float_returns_default_when_missing(): void + { + $_REQUEST = []; + $request = new Request(); + $this->assertEquals(0.5, $request->getFloat('price', 0.5)); + } + + public function test_get_float_handles_non_numeric_string(): void + { + $_REQUEST = ['price' => 'free']; + $request = new Request(); + $this->assertEquals(0.0, $request->getFloat('price')); + } + + public function test_get_float_with_explicit_data(): void + { + $request = new Request(['weight' => '3.14']); + $this->assertEquals(3.14, $request->getFloat('weight')); + } + + // ── getBool() ──────────────────────────────────────────────────────────── + + public function test_get_bool_true_from_string_one(): void + { + $_REQUEST = ['flag' => '1']; + $request = new Request(); + $this->assertTrue($request->getBool('flag')); + } + + public function test_get_bool_true_from_string_true(): void + { + $_REQUEST = ['flag' => 'true']; + $request = new Request(); + $this->assertTrue($request->getBool('flag')); + } + + public function test_get_bool_true_from_string_t(): void + { + $_REQUEST = ['flag' => 't']; + $request = new Request(); + $this->assertTrue($request->getBool('flag')); + } + + public function test_get_bool_true_from_string_on(): void + { + $_REQUEST = ['flag' => 'on']; + $request = new Request(); + $this->assertTrue($request->getBool('flag')); + } + + public function test_get_bool_false_from_non_matching_string(): void + { + $_REQUEST = ['flag' => '42']; + $request = new Request(); + // '42' is a string, not in the truthy string list ['1','true','t','on'] + $this->assertFalse($request->getBool('flag')); + } + + public function test_get_bool_false_from_string_zero(): void + { + $_REQUEST = ['flag' => '0']; + $request = new Request(); + $this->assertFalse($request->getBool('flag')); + } + + public function test_get_bool_false_from_string_false(): void + { + $_REQUEST = ['flag' => 'false']; + $request = new Request(); + $this->assertFalse($request->getBool('flag')); + } + + public function test_get_bool_false_from_empty_string(): void + { + $_REQUEST = ['flag' => '']; + $request = new Request(); + $this->assertFalse($request->getBool('flag')); + } + + public function test_get_bool_returns_default_when_missing(): void + { + $_REQUEST = []; + $request = new Request(); + $this->assertTrue($request->getBool('flag', true)); + $this->assertFalse($request->getBool('flag', false)); + } + + public function test_get_bool_with_explicit_data(): void + { + $request = new Request(['active' => '1']); + $this->assertTrue($request->getBool('active')); + } + + // ── getArray() ─────────────────────────────────────────────────────────── + + public function test_get_array_returns_array_value(): void + { + $_REQUEST = ['ids' => [1, 2, 3]]; + $request = new Request(); + $result = $request->getArray('ids'); + $this->assertCount(3, $result); + $this->assertEquals(1, $result[0]); + $this->assertEquals(2, $result[1]); + $this->assertEquals(3, $result[2]); + } + + public function test_get_array_returns_default_when_missing(): void + { + $_GET = []; + $request = new Request(); + $this->assertEquals(['x', 'y'], $request->getArray('ids', ['x', 'y'])); + } + + public function test_get_array_splits_comma_separated_string(): void + { + $_REQUEST = ['ids' => '1,2,3']; + $request = new Request(); + $this->assertEquals(['1', '2', '3'], $request->getArray('ids')); + } + + public function test_get_array_trims_comma_separated_values(): void + { + $_REQUEST = ['ids' => '1, 2 , 3']; + $request = new Request(); + $this->assertEquals(['1', '2', '3'], $request->getArray('ids')); + } + + public function test_get_array_handles_empty_string(): void + { + $_GET = ['ids' => '']; + $request = new Request(); + $this->assertEquals([], $request->getArray('ids')); + } + + public function test_get_array_with_explicit_data(): void + { + $request = new Request(['tags' => ['a', 'b']]); + $this->assertEquals(['a', 'b'], $request->getArray('tags')); + } + + // ── getRaw() ───────────────────────────────────────────────────────────── + + public function test_get_raw_from_post(): void + { + $_POST = ['op' => 'login']; + $request = new Request(); + $request->fromPost(); + $this->assertEquals('login', $request->getRaw('op')); + } + + public function test_get_raw_from_get(): void + { + $_GET = ['id' => '42']; + $request = new Request(); + $request->fromGet(); + $this->assertEquals('42', $request->getRaw('id')); + } + + public function test_get_raw_from_request(): void + { + $_REQUEST = ['name' => 'alice']; + $request = new Request(); + $this->assertEquals('alice', $request->getRaw('name')); + } + + public function test_get_raw_from_explicit_data(): void + { + $request = new Request(['key' => 'val']); + $this->assertEquals('val', $request->getRaw('key')); + } + + public function test_get_raw_returns_null_when_missing(): void + { + $_GET = []; + $request = new Request(); + $this->assertNull($request->getRaw('missing')); + } + + // ── has() ──────────────────────────────────────────────────────────────── + + public function test_has_returns_true_for_existing_key_in_request(): void + { + $_REQUEST = ['op' => 'list']; + $request = new Request(); + $this->assertTrue($request->has('op')); + } + + public function test_has_returns_false_for_missing_key(): void + { + $_REQUEST = ['op' => 'list']; + $request = new Request(); + $this->assertFalse($request->has('missing')); + } + + public function test_has_from_post(): void + { + $_POST = ['username' => 'admin']; + $request = new Request(); + $request->fromPost(); + $this->assertTrue($request->has('username')); + $this->assertFalse($request->has('password')); + } + + public function test_has_from_get(): void + { + $_GET = ['page' => '1']; + $request = new Request(); + $request->fromGet(); + $this->assertTrue($request->has('page')); + } + + public function test_has_with_explicit_data(): void + { + $request = new Request(['key' => 'val']); + $this->assertTrue($request->has('key')); + $this->assertFalse($request->has('other')); + } + + // ── all() ──────────────────────────────────────────────────────────────── + + public function test_all_returns_all_request_params(): void + { + $_REQUEST = ['op' => 'list', 'page' => '2']; + $request = new Request(); + $this->assertEquals(['op' => 'list', 'page' => '2'], $request->all()); + } + + public function test_all_from_post(): void + { + $_POST = ['user' => 'admin', 'pass' => 'secret']; + $request = new Request(); + $request->fromPost(); + $this->assertEquals(['user' => 'admin', 'pass' => 'secret'], $request->all()); + } + + public function test_all_from_get(): void + { + $_GET = ['q' => 'search']; + $request = new Request(); + $request->fromGet(); + $this->assertEquals(['q' => 'search'], $request->all()); + } + + public function test_all_from_body_returns_empty_when_not_called(): void + { + $request = new Request(); + $request->from(Request::SOURCE_BODY); + $this->assertEquals([], $request->all()); + } + + public function test_all_with_explicit_data(): void + { + $request = new Request(['a' => 1, 'b' => 2]); + $this->assertEquals(['a' => 1, 'b' => 2], $request->all()); + } + + // ── only() ─────────────────────────────────────────────────────────────── + + public function test_only_returns_subset(): void + { + $_REQUEST = ['op' => 'list', 'page' => '1', 'limit' => '20']; + $request = new Request(); + $result = $request->only(['op', 'limit']); + $this->assertCount(2, $result); + $this->assertEquals('list', $result['op']); + $this->assertEquals('20', $result['limit']); + } + + public function test_only_includes_null_for_missing_keys(): void + { + $_REQUEST = ['op' => 'list']; + $request = new Request(); + $result = $request->only(['op', 'missing']); + $this->assertEquals(['op' => 'list', 'missing' => null], $result); + } + + public function test_only_with_explicit_data(): void + { + $request = new Request(['a' => 1, 'b' => 2, 'c' => 3]); + $result = $request->only(['a', 'c']); + $this->assertEquals(['a' => 1, 'c' => 3], $result); + } + + // ── _to_bool() static ──────────────────────────────────────────────────── + + public function test_to_bool_true_values(): void + { + $this->assertTrue(Request::_to_bool(true)); + $this->assertTrue(Request::_to_bool(1)); + $this->assertTrue(Request::_to_bool(1.0)); + $this->assertTrue(Request::_to_bool('1')); + $this->assertTrue(Request::_to_bool('true')); + $this->assertTrue(Request::_to_bool('t')); + $this->assertTrue(Request::_to_bool('on')); + $this->assertTrue(Request::_to_bool(42)); + $this->assertTrue(Request::_to_bool(3.14)); + } + + public function test_to_bool_false_values(): void + { + $this->assertFalse(Request::_to_bool(false)); + $this->assertFalse(Request::_to_bool(0)); + $this->assertFalse(Request::_to_bool(0.0)); + $this->assertFalse(Request::_to_bool('0')); + $this->assertFalse(Request::_to_bool('false')); + $this->assertFalse(Request::_to_bool('')); + $this->assertFalse(Request::_to_bool(null)); + } + + public function test_to_bool_handles_sanitization(): void + { + // clean() strips tags; '<script>1</script>' → '1' → true + $this->assertTrue(Request::_to_bool('<script>1</script>')); + } + + public function test_to_bool_case_insensitive(): void + { + $this->assertTrue(Request::_to_bool('TRUE')); + $this->assertTrue(Request::_to_bool('True')); + $this->assertTrue(Request::_to_bool('ON')); + $this->assertTrue(Request::_to_bool('On')); + } + + public function test_to_bool_with_array_fallback(): void + { + // Non-string, non-int, non-float, non-bool: falls through to (bool) + $this->assertTrue(Request::_to_bool(['anything'])); + $this->assertFalse(Request::_to_bool([])); + } } diff --git a/tests_integration/CsrfMiddlewareTest.php b/tests_integration/CsrfMiddlewareTest.php index dcf7ed8..2adce0e 100644 --- a/tests_integration/CsrfMiddlewareTest.php +++ b/tests_integration/CsrfMiddlewareTest.php @@ -24,27 +24,6 @@ final class CsrfMiddlewareTest extends ApiTestCase $this->assertArrayHasKey('books', $body); } - public function test_ignored_op_getinfo_without_csrf(): void - { - // Login to establish session - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - // getinfo is in csrfIgnore — should work without csrf_token - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 2, - 'csrf_token' => '', - ]); - - $this->assertEquals(200, $status); - $this->assertArrayHasKey('id', $body); - } - // ── Non-ignored operations — CSRF required ─────────────────────────────── public function test_non_ignored_op_requires_csrf(): void diff --git a/tests_integration/GetinfoHandlerTest.php b/tests_integration/GetinfoHandlerTest.php deleted file mode 100644 index 1145d9e..0000000 --- a/tests_integration/GetinfoHandlerTest.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -use PHPUnit\Framework\TestCase; - -final class GetinfoHandlerTest extends ApiTestCase -{ - // ── Authentication ─────────────────────────────────────────────────────── - - public function test_getinfo_requires_authentication(): void - { - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 1, - ]); - - $this->assertEquals(401, $status); - $this->assertArrayHasKey('error', $body); - } - - // ── Valid book ─────────────────────────────────────────────────────────── - - public function test_getinfo_returns_book(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 2, // Adventures of Huckleberry Finn - ]); - - $this->assertEquals(200, $status); - $this->assertEquals(2, $body['id'] ?? null); - $this->assertEquals('Adventures of Huckleberry Finn', $body['title'] ?? null); - $this->assertEquals('Twain, Mark', $body['author_sort'] ?? null); - $this->assertArrayHasKey('series_name', $body); - $this->assertArrayHasKey('comment', $body); - $this->assertArrayHasKey('epub_id', $body); - } - - public function test_getinfo_returns_all_book_fields(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 3, - ]); - - $this->assertEquals(200, $status); - // Verify all expected Calibre fields are present - $expectedFields = ['id', 'title', 'sort', 'timestamp', 'pubdate', 'series_index', - 'author_sort', 'isbn', 'lccn', 'path', 'flags', 'uuid', 'has_cover', 'last_modified', - 'series_name', 'comment', 'epub_id']; - foreach ($expectedFields as $field) { - $this->assertArrayHasKey($field, $body, "Missing field: $field"); - } - } - - // ── Non-existent book ──────────────────────────────────────────────────── - - public function test_getinfo_returns_404_for_missing_book(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 99999, // Non-existent book - ]); - - $this->assertEquals(404, $status); - $this->assertEquals('Not found.', $body['error']); - } - - // ── Missing/invalid ID ─────────────────────────────────────────────────── - - public function test_getinfo_without_id(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - ]); - - $this->assertEquals(404, $status); - } - - public function test_getinfo_with_zero_id(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 0, - ]); - - $this->assertEquals(404, $status); - } - - public function test_getinfo_with_negative_id(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => -1, - ]); - - $this->assertEquals(404, $status); - } - - // ── Sanitization ───────────────────────────────────────────────────────── - - public function test_getinfo_sanitizes_book_comment(): void - { - // Login - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'perform-login', - 'user' => 'test', - 'password' => 'test', - ]); - $this->assertEquals(200, $status); - - [$status, $body] = $this->post($this->apiUrl, [ - 'op' => 'getinfo', - 'id' => 2, - ]); - - $this->assertEquals(200, $status); - // comment field exists and is a string (empty in test data, but Sanitizer::sanitize was called) - $this->assertIsString($body['comment'] ?? null); - } -} |
