about summary refs log tree commit diff stats
path: root/classes/Handler/DownloadHandler.php
blob: 6eaca115b305f323c4b1da88683063c0a56bed78 (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
<?php

namespace Handler;

use AuthRequired;
use Config;
use Request;
use RequestHandlerInterface;
use Response;
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]);

		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) ?: '');
			}
		}

		return (new Response())
			->withStatus(404)
			->withBody("File not found.");
	}
}