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
|
<?php
namespace Handler;
use AuthRequired;
use ORM;
use Request;
use RequestHandlerInterface;
use Response;
class PaginationHandler implements RequestHandlerInterface, AuthRequired
{
/** Upper bound for stored location payloads (epub.js location arrays can be large). */
private const MAX_PAYLOAD_SIZE = 2 * 1024 * 1024;
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) {
$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."])),
};
}
}
|