about summary refs log tree commit diff stats
path: root/classes/Handler/PaginationHandler.php
blob: de22037d066b994afa04ccc4db5518a4f6530d33 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php

namespace Handler;

use AuthRequired;
use Config;
use ORM;
use PDO;
use Request;
use RequestHandlerInterface;
use Response;

class PaginationHandler implements RequestHandlerInterface, AuthRequired
{
    /**
     * Upper bound for stored location payloads. Observed real-world max in
     * production is ~3 MB for large books; 16 MiB keeps generous headroom
     * while still bounding unbounded storage growth.
     */
    private const MAX_PAYLOAD_SIZE = 16 * 1024 * 1024;

    /**
     * Verify the id refers to an actual library entry in the Calibre DB.
     * The frontend keys pagination by the EPUB 'data' row id, but accept
     * a 'books' row id as well for robustness/backwards compatibility.
     */
    private function bookExists(int $bookid): bool
    {
        $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
        $sth = $caldb->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."])),
        };
    }
}