prepare("SELECT 1 FROM data WHERE id = ? UNION SELECT 1 FROM books WHERE id = ? LIMIT 1"); $sth->execute([$bookid, $bookid]); return (bool)$sth->fetch(); } 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); } } return (new Response()) ->withStatus(404) ->withBody(json_encode(["error" => "File not found."])); } private function handleStore(int $bookid, ?string $payload): Response { // Payload is later served back verbatim with a JSON content type, // so only accept well-formed JSON arrays (epub.js location format) // instead of storing arbitrary attacker-controlled bytes. if ($payload !== null && strlen($payload) <= self::MAX_PAYLOAD_SIZE) { $decoded = json_decode($payload, true); if (is_array($decoded)) { // Normalize (strips surrounding whitespace etc.) while keeping // the round-trip as byte-faithful as possible. $payload = json_encode($decoded, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } else { $payload = null; } } else { $payload = null; } if ($bookid && $payload && $this->bookExists($bookid)) { $pag = ORM::for_table('epube_pagination') ->where('bookid', $bookid) ->find_one(); if (!$pag) { $pag = ORM::for_table('epube_pagination')->create(); $pag->bookid = $bookid; } $pag->pagination = $payload; $pag->total_pages = 100; $pag->save(); } return new Response(); } 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(); } } return (new Response()) ->withStatus(404) ->withBody(json_encode(["error" => "Not found."])); } public function handle(Request $request): Response { $subOp = $request->getString('op', ''); $bookid = $request->getInt('id'); return match ($subOp) { 'getpagination' => $this->handleGet($bookid), 'storepagination' => $this->handleStore($bookid, $request->getString('payload')), 'deletepagination' => $this->handleDelete($bookid), default => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])), }; } }