about summary refs log tree commit diff stats
path: root/classes
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-05-31 09:11:20 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-05-31 09:11:20 +0300
commitb58f0a8f2431040edf94edb21f9c884f20ba6049 (patch)
treeb70055bf14983a59242ae27cdba75f6d39d391a3 /classes
parentb76af33e9bfb57b46fb8d8292b614bf9ee2e3c2d (diff)
downloadthe-epube-b58f0a8f2431040edf94edb21f9c884f20ba6049.tar.gz
the-epube-b58f0a8f2431040edf94edb21f9c884f20ba6049.tar.xz
tabs to spaces
Diffstat (limited to 'classes')
-rw-r--r--classes/Config.php692
-rw-r--r--classes/CsrfMiddleware.php40
-rw-r--r--classes/Db.php120
-rw-r--r--classes/Db_Migrations.php380
-rw-r--r--classes/Debug.php132
-rw-r--r--classes/Handler/CoverHandler.php50
-rw-r--r--classes/Handler/DefineHandler.php88
-rw-r--r--classes/Handler/DownloadHandler.php38
-rw-r--r--classes/Handler/GetinfoHandler.php38
-rw-r--r--classes/Handler/HealthzHandler.php70
-rw-r--r--classes/Handler/LastreadHandler.php128
-rw-r--r--classes/Handler/ListHandler.php300
-rw-r--r--classes/Handler/LoginHandler.php328
-rw-r--r--classes/Handler/LogoutHandler.php10
-rw-r--r--classes/Handler/PaginationHandler.php112
-rw-r--r--classes/Handler/TogglefavHandler.php40
-rw-r--r--classes/MiddlewareInterface.php2
-rw-r--r--classes/Request.php104
-rw-r--r--classes/RequestHandlerInterface.php2
-rw-r--r--classes/Response.php102
-rw-r--r--classes/Router.php102
-rw-r--r--classes/Sanitizer.php514
22 files changed, 1696 insertions, 1696 deletions
diff --git a/classes/Config.php b/classes/Config.php
index 1129117..b0a6e12 100644
--- a/classes/Config.php
+++ b/classes/Config.php
@@ -1,356 +1,356 @@
 <?php
 class Config {
-	private const _ENVVAR_PREFIX = "EPUBE_";
-
-	const T_BOOL = 1;
-	const T_STRING = 2;
-	const T_INT = 3;
-
-	// override defaults, defined below in _DEFAULTS[], via environment: DB_TYPE becomes EPUBE_DB_TYPE, etc
-
-	const DB_TYPE = "DB_TYPE";
-	const DB_HOST = "DB_HOST";
-	const DB_USER = "DB_USER";
-	const DB_NAME = "DB_NAME";
-	const DB_PASS = "DB_PASS";
-	const DB_PORT = "DB_PORT";
-
-	const SCRATCH_DB = "SCRATCH_DB";
-	const CALIBRE_DB = "CALIBRE_DB";
-	const BOOKS_DIR = "BOOKS_DIR";
-	const DICT_SERVER = "DICT_SERVER";
-	const SESSION_LIFETIME = "SESSION_LIFETIME";
-	const SESSION_NAME = "SESSION_NAME";
-	const OIDC_NAME = "OIDC_NAME";
-	const OIDC_URL = "OIDC_URL";
-	const OIDC_CLIENT_ID = "OIDC_CLIENT_ID";
-	const OIDC_CLIENT_SECRET = "OIDC_CLIENT_SECRET";
-
-	private const _DEFAULTS = [
-		Config::DB_TYPE => [ "sqlite", Config::T_STRING ],
-		Config::DB_HOST => [ "db", Config::T_STRING ],
-		Config::DB_USER => [ "", Config::T_STRING ],
-		Config::DB_NAME => [ "", Config::T_STRING ],
-		Config::DB_PASS => [ "", Config::T_STRING ],
-		Config::DB_PORT => [ "5432", Config::T_STRING ],
-		Config::SCRATCH_DB => [ "db/scratch.db", Config::T_STRING ],
-		Config::CALIBRE_DB => [ "", Config::T_STRING ],
-		Config::BOOKS_DIR => [ "", Config::T_STRING ],
-		Config::DICT_SERVER => [ "", Config::T_STRING ],
-		Config::SESSION_LIFETIME => [ 86400*30, Config::T_INT ],
-		Config::SESSION_NAME => [ "epube_sid", Config::T_STRING ],
-		Config::OIDC_NAME => [ "OIDC", Config::T_STRING ],
-		Config::OIDC_URL => [ "", Config::T_STRING ],
-		Config::OIDC_CLIENT_ID => [ "", Config::T_STRING ],
-		Config::OIDC_CLIENT_SECRET => [ "", Config::T_STRING ],
-	];
-
-	private static ?Config $instance = null;
-
-	/** @var array<string, array<bool|int|string>> */
-	private array $params = [];
-
-	/** @var array<string, mixed> */
-	private array $version = [];
-
-	private Db_Migrations $migrations;
-
-	public static function get_instance() : Config {
-		if (self::$instance == null)
-			self::$instance = new self();
-
-		return self::$instance;
-	}
-
-	private function __clone() {
-		//
-	}
-
-	/** load data from environment variables */
-	function reload(): void {
-		$ref = new ReflectionClass(get_class($this));
-
-		foreach ($ref->getConstants() as $const => $cvalue) {
-			if (isset(self::_DEFAULTS[$const])) {
-				$override = getenv(self::_ENVVAR_PREFIX . $const);
-
-				list ($defval, $deftype) = self::_DEFAULTS[$const];
-
-				$this->params[$cvalue] = [ self::cast_to($override !== false ? $override : $defval, $deftype), $deftype ];
-			}
-		}
-	}
-
-	/** this is primarily needed for tests, normally global config is not changed at runtime */
-	static function set(string $key, mixed $value): bool {
-		if (!getenv('IS_INTEGRATION_TESTING') && !getenv('IS_TESTING')) {
-			user_error("This method is only available for tests.", E_USER_WARNING);
-
-			return false;
-		} if (array_key_exists($key, self::_DEFAULTS)) {
-			list ($defval, $deftype) = self::_DEFAULTS[$key];
-
-			self::get_instance()->params[$key] = [self::cast_to($value, $deftype), $deftype];
-
-			return true;
-		} else {
-			user_error("Requested to set unknown global config variable: {$key}", E_USER_WARNING);
-
-			return false;
-		}
-	}
-
-	function __construct() {
-		$this->reload();
-	}
-
-	/* package maintainers who don't use git: if version_static.txt exists in tt-rss root
-		directory, its contents are displayed instead of git commit-based version, this could be generated
-		based on source git tree commit used when creating the package */
-
-	/** @return string|array<string, mixed> */
-	static function get_version(bool $as_string = true) : mixed {
-		return self::get_instance()->_get_version($as_string);
-	}
-
-	/** @return string|array<string, mixed> */
-	private function _get_version(bool $as_string = true) : mixed {
-		$root_dir = dirname(__DIR__);
-
-		if (empty($this->version)) {
-			$this->version["status"] = -1;
-
-			if (getenv("CI_COMMIT_SHORT_SHA") && getenv("CI_COMMIT_TIMESTAMP")) {
-
-				$this->version["branch"] = getenv("CI_COMMIT_BRANCH");
-				$this->version["timestamp"] = strtotime(getenv("CI_COMMIT_TIMESTAMP"));
-				$this->version["version"] = sprintf("%s-%s", date("y.m", $this->version["timestamp"]), getenv("CI_COMMIT_SHORT_SHA"));
-				$this->version["commit"] = getenv("CI_COMMIT_SHORT_SHA");
-				$this->version["status"] = 0;
-
-			} else if (PHP_OS === "Darwin") {
-				$this->version["version"] = "UNKNOWN (Unsupported, Darwin)";
-			} else if (file_exists("$root_dir/version_static.txt")) {
-				$this->version["version"] = trim(file_get_contents("$root_dir/version_static.txt")) . " (Unsupported)";
-			} else if (is_dir("$root_dir/.git")) {
-				$this->version = self::get_version_from_git($root_dir);
-
-				if ($this->version["status"] != 0) {
-					user_error("Unable to determine version: " . $this->version["version"], E_USER_WARNING);
-
-					$this->version["version"] = "UNKNOWN (Unsupported, Git error)";
-				}
-			} else {
-				$this->version["version"] = "UNKNOWN (Unsupported)";
-			}
-		}
+    private const _ENVVAR_PREFIX = "EPUBE_";
+
+    const T_BOOL = 1;
+    const T_STRING = 2;
+    const T_INT = 3;
+
+    // override defaults, defined below in _DEFAULTS[], via environment: DB_TYPE becomes EPUBE_DB_TYPE, etc
+
+    const DB_TYPE = "DB_TYPE";
+    const DB_HOST = "DB_HOST";
+    const DB_USER = "DB_USER";
+    const DB_NAME = "DB_NAME";
+    const DB_PASS = "DB_PASS";
+    const DB_PORT = "DB_PORT";
+
+    const SCRATCH_DB = "SCRATCH_DB";
+    const CALIBRE_DB = "CALIBRE_DB";
+    const BOOKS_DIR = "BOOKS_DIR";
+    const DICT_SERVER = "DICT_SERVER";
+    const SESSION_LIFETIME = "SESSION_LIFETIME";
+    const SESSION_NAME = "SESSION_NAME";
+    const OIDC_NAME = "OIDC_NAME";
+    const OIDC_URL = "OIDC_URL";
+    const OIDC_CLIENT_ID = "OIDC_CLIENT_ID";
+    const OIDC_CLIENT_SECRET = "OIDC_CLIENT_SECRET";
+
+    private const _DEFAULTS = [
+        Config::DB_TYPE => [ "sqlite", Config::T_STRING ],
+        Config::DB_HOST => [ "db", Config::T_STRING ],
+        Config::DB_USER => [ "", Config::T_STRING ],
+        Config::DB_NAME => [ "", Config::T_STRING ],
+        Config::DB_PASS => [ "", Config::T_STRING ],
+        Config::DB_PORT => [ "5432", Config::T_STRING ],
+        Config::SCRATCH_DB => [ "db/scratch.db", Config::T_STRING ],
+        Config::CALIBRE_DB => [ "", Config::T_STRING ],
+        Config::BOOKS_DIR => [ "", Config::T_STRING ],
+        Config::DICT_SERVER => [ "", Config::T_STRING ],
+        Config::SESSION_LIFETIME => [ 86400*30, Config::T_INT ],
+        Config::SESSION_NAME => [ "epube_sid", Config::T_STRING ],
+        Config::OIDC_NAME => [ "OIDC", Config::T_STRING ],
+        Config::OIDC_URL => [ "", Config::T_STRING ],
+        Config::OIDC_CLIENT_ID => [ "", Config::T_STRING ],
+        Config::OIDC_CLIENT_SECRET => [ "", Config::T_STRING ],
+    ];
+
+    private static ?Config $instance = null;
+
+    /** @var array<string, array<bool|int|string>> */
+    private array $params = [];
+
+    /** @var array<string, mixed> */
+    private array $version = [];
+
+    private Db_Migrations $migrations;
+
+    public static function get_instance() : Config {
+        if (self::$instance == null)
+            self::$instance = new self();
+
+        return self::$instance;
+    }
+
+    private function __clone() {
+        //
+    }
+
+    /** load data from environment variables */
+    function reload(): void {
+        $ref = new ReflectionClass(get_class($this));
+
+        foreach ($ref->getConstants() as $const => $cvalue) {
+            if (isset(self::_DEFAULTS[$const])) {
+                $override = getenv(self::_ENVVAR_PREFIX . $const);
+
+                list ($defval, $deftype) = self::_DEFAULTS[$const];
+
+                $this->params[$cvalue] = [ self::cast_to($override !== false ? $override : $defval, $deftype), $deftype ];
+            }
+        }
+    }
+
+    /** this is primarily needed for tests, normally global config is not changed at runtime */
+    static function set(string $key, mixed $value): bool {
+        if (!getenv('IS_INTEGRATION_TESTING') && !getenv('IS_TESTING')) {
+            user_error("This method is only available for tests.", E_USER_WARNING);
+
+            return false;
+        } if (array_key_exists($key, self::_DEFAULTS)) {
+            list ($defval, $deftype) = self::_DEFAULTS[$key];
+
+            self::get_instance()->params[$key] = [self::cast_to($value, $deftype), $deftype];
+
+            return true;
+        } else {
+            user_error("Requested to set unknown global config variable: {$key}", E_USER_WARNING);
+
+            return false;
+        }
+    }
+
+    function __construct() {
+        $this->reload();
+    }
+
+    /* package maintainers who don't use git: if version_static.txt exists in tt-rss root
+        directory, its contents are displayed instead of git commit-based version, this could be generated
+        based on source git tree commit used when creating the package */
+
+    /** @return string|array<string, mixed> */
+    static function get_version(bool $as_string = true) : mixed {
+        return self::get_instance()->_get_version($as_string);
+    }
+
+    /** @return string|array<string, mixed> */
+    private function _get_version(bool $as_string = true) : mixed {
+        $root_dir = dirname(__DIR__);
+
+        if (empty($this->version)) {
+            $this->version["status"] = -1;
+
+            if (getenv("CI_COMMIT_SHORT_SHA") && getenv("CI_COMMIT_TIMESTAMP")) {
+
+                $this->version["branch"] = getenv("CI_COMMIT_BRANCH");
+                $this->version["timestamp"] = strtotime(getenv("CI_COMMIT_TIMESTAMP"));
+                $this->version["version"] = sprintf("%s-%s", date("y.m", $this->version["timestamp"]), getenv("CI_COMMIT_SHORT_SHA"));
+                $this->version["commit"] = getenv("CI_COMMIT_SHORT_SHA");
+                $this->version["status"] = 0;
+
+            } else if (PHP_OS === "Darwin") {
+                $this->version["version"] = "UNKNOWN (Unsupported, Darwin)";
+            } else if (file_exists("$root_dir/version_static.txt")) {
+                $this->version["version"] = trim(file_get_contents("$root_dir/version_static.txt")) . " (Unsupported)";
+            } else if (is_dir("$root_dir/.git")) {
+                $this->version = self::get_version_from_git($root_dir);
+
+                if ($this->version["status"] != 0) {
+                    user_error("Unable to determine version: " . $this->version["version"], E_USER_WARNING);
+
+                    $this->version["version"] = "UNKNOWN (Unsupported, Git error)";
+                }
+            } else {
+                $this->version["version"] = "UNKNOWN (Unsupported)";
+            }
+        }
 
-		return $as_string ? $this->version["version"] : $this->version;
-	}
+        return $as_string ? $this->version["version"] : $this->version;
+    }
 
-	/** @return array<string, mixed> */
-	static function get_version_from_git(string $dir) : array {
-		$descriptorspec = [
-			1 => ["pipe", "w"], // STDOUT
-			2 => ["pipe", "w"], // STDERR
-		];
+    /** @return array<string, mixed> */
+    static function get_version_from_git(string $dir) : array {
+        $descriptorspec = [
+            1 => ["pipe", "w"], // STDOUT
+            2 => ["pipe", "w"], // STDERR
+        ];
 
-		$rv = [
-			"status" => -1,
-			"version" => "",
-			"commit" => "",
-			"branch" => "",
-			"timestamp" => 0,
-		];
-
-		$proc = proc_open("git --no-pager log --pretty=\"version-%ct-%h\" -n1 HEAD",
-						$descriptorspec, $pipes, $dir);
+        $rv = [
+            "status" => -1,
+            "version" => "",
+            "commit" => "",
+            "branch" => "",
+            "timestamp" => 0,
+        ];
+
+        $proc = proc_open("git --no-pager log --pretty=\"version-%ct-%h\" -n1 HEAD",
+                        $descriptorspec, $pipes, $dir);
 
-		if (is_resource($proc)) {
-			$stdout = trim(stream_get_contents($pipes[1]));
-			$stderr = trim(stream_get_contents($pipes[2]));
-			$status = proc_close($proc);
-
-			$rv["status"] = $status;
-
-			list($check, $timestamp, $commit) = explode("-", $stdout);
-
-			if ($check == "version") {
-
-				$rv["version"] = strftime("%y.%m", (int)$timestamp) . "-$commit";
-				$rv["commit"] = $commit;
-				$rv["timestamp"] = $timestamp;
-
-				// proc_close() may return -1 even if command completed successfully
-				// so if it looks like we got valid data, we ignore it
-
-				if ($rv["status"] == -1)
-					$rv["status"] = 0;
+        if (is_resource($proc)) {
+            $stdout = trim(stream_get_contents($pipes[1]));
+            $stderr = trim(stream_get_contents($pipes[2]));
+            $status = proc_close($proc);
+
+            $rv["status"] = $status;
+
+            list($check, $timestamp, $commit) = explode("-", $stdout);
+
+            if ($check == "version") {
+
+                $rv["version"] = strftime("%y.%m", (int)$timestamp) . "-$commit";
+                $rv["commit"] = $commit;
+                $rv["timestamp"] = $timestamp;
+
+                // proc_close() may return -1 even if command completed successfully
+                // so if it looks like we got valid data, we ignore it
+
+                if ($rv["status"] == -1)
+                    $rv["status"] = 0;
 
-			} else {
-				$rv["version"] = T_sprintf("Git error [RC=%d]: %s", $status, $stderr);
-			}
-		}
+            } else {
+                $rv["version"] = T_sprintf("Git error [RC=%d]: %s", $status, $stderr);
+            }
+        }
 
-		return $rv;
-	}
+        return $rv;
+    }
 
-	static function get_migrations() : Db_Migrations {
-		return self::get_instance()->_get_migrations();
-	}
-
-	private function _get_migrations() : Db_Migrations {
-		if (empty($this->migrations)) {
-			$this->migrations = new Db_Migrations();
-			$this->migrations->initialize(dirname(__DIR__) . "/sql", "epube_migrations", true);
-		}
-
-		return $this->migrations;
-	}
-
-	static function is_migration_needed() : bool {
-		return self::get_migrations()->is_migration_needed();
-	}
-
-	static function get_schema_version() : int {
-		return self::get_migrations()->get_version();
-	}
-
-	/** @return int|bool|string */
-	static function cast_to(string $value, int $type_hint) : mixed {
-		switch ($type_hint) {
-			case self::T_BOOL:
-				return sql_bool_to_bool($value);
-			case self::T_INT:
-				return (int) $value;
-			default:
-				return $value;
-		}
-	}
-
-	/** @return int|bool|string */
-	private function _get(string $param) : mixed {
-		list ($value, $type_hint) = $this->params[$param];
-
-		return $this->cast_to($value, $type_hint);
-	}
-
-	private function _add(string $param, string $default, int $type_hint) : void {
-		$override = getenv($this::_ENVVAR_PREFIX . $param);
-
-		$this->params[$param] = [ self::cast_to(!empty($override) ? $override : $default, $type_hint), $type_hint ];
-	}
-
-	static function add(string $param, string $default, int $type_hint = Config::T_STRING) : void {
-		$instance = self::get_instance();
-
-		$instance->_add($param, $default, $type_hint);
-	}
-
-	/** @return int|bool|string */
-	static function get(string $param) {
-		$instance = self::get_instance();
-
-		return $instance->_get($param);
-	}
-
-	static function is_server_https() : bool {
-		return (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off')) ||
-			(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
-	}
-
-	/** generates reference self_url_path (no trailing slash) */
-	static function get_self_url() : string {
-		$proto = self::is_server_https() ? 'https' : 'http';
-		$self_url_path = $proto . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
-
-		$self_url_path = preg_replace("/\w+\.php(\?.*$)?$/", "", $self_url_path);
-
-		if (substr($self_url_path, -1) === "/") {
-			return substr($self_url_path, 0, -1);
-		} else {
-			return $self_url_path;
-		}
-	}
-
-	/** also initializes Db and ORM */
-	static function sanity_check() : void {
-
-		/*
-			we don't actually need the DB object right now but some checks below might use ORM which won't be initialized
-			because it is set up in the Db constructor, which is why it's a good idea to invoke it as early as possible
-
-			it is a bit of a hack, maybe ORM should be initialized somewhere else (functions.php?)
-		*/
-
-		$pdo = Db::pdo();
-
-		$errors = [];
-
-		if (function_exists('posix_getuid') && posix_getuid() == 0) {
-			array_push($errors, "Please don't run this script as root.");
-		}
-
-		if (version_compare(PHP_VERSION, '7.1.0', '<')) {
-			array_push($errors, "PHP version 7.1.0 or newer required. You're using " . PHP_VERSION . ".");
-		}
-
-		if (php_sapi_name() != "cli") {
-			if (self::get_schema_version() < 0) {
-				array_push($errors, "Base database schema is missing. Either load it manually or perform a migration (<code>update.php --update-schema</code>)");
-			}
-		}
-
-		if (count($errors) > 0 && php_sapi_name() != "cli") { ?>
-			<!DOCTYPE html>
-			<html>
-				<head>
-					<meta name="viewport" content="width=device-width, initial-scale=1.0">
-					<link href="lib/bootstrap/v3/css/bootstrap.min.css" rel="stylesheet" media="screen">
-					<link href="lib/bootstrap/v3/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
-					<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-					<script src="dist/app-libs.min.js"></script>
-					<title>Startup failed</title>
-					<link type="text/css" rel="stylesheet" media="screen" href="dist/app.min.css" />
-					<link rel="shortcut icon" type="image/png" href="img/favicon.png" />
-					<link rel="manifest" href="manifest.json">
-					<meta name="mobile-web-app-capable" content="yes">
-					<script type="text/javascript">
-						$(document).ready(function() {
-								/* global EpubeApp */
-
-								if (typeof EpubeApp != "undefined") {
-									EpubeApp.setPage("PAGE_LOGIN");
-								}
-						});
-					</script>
-				</head>
-				<body class="epube-sanity-failed">
-					<div class="container">
-						<h1>Startup failed</h1>
-
-						<p>Please fix errors indicated by the following messages:</p>
-
-						<?php foreach ($errors as $error) { echo self::format_error($error); } ?>
-
-					</div>
-				</body>
-			</html>
-
-		<?php
-			die;
-		} else if (count($errors) > 0) {
-			echo "Please fix errors indicated by the following messages:\n\n";
-
-			foreach ($errors as $error) {
-				echo " * " . strip_tags($error)."\n";
-			}
-
-			exit(1);
-		}
-	}
-
-	private static function format_error(string $msg) : string {
-		return "<div class=\"alert alert-danger\">$msg</div>";
-	}
+    static function get_migrations() : Db_Migrations {
+        return self::get_instance()->_get_migrations();
+    }
+
+    private function _get_migrations() : Db_Migrations {
+        if (empty($this->migrations)) {
+            $this->migrations = new Db_Migrations();
+            $this->migrations->initialize(dirname(__DIR__) . "/sql", "epube_migrations", true);
+        }
+
+        return $this->migrations;
+    }
+
+    static function is_migration_needed() : bool {
+        return self::get_migrations()->is_migration_needed();
+    }
+
+    static function get_schema_version() : int {
+        return self::get_migrations()->get_version();
+    }
+
+    /** @return int|bool|string */
+    static function cast_to(string $value, int $type_hint) : mixed {
+        switch ($type_hint) {
+            case self::T_BOOL:
+                return sql_bool_to_bool($value);
+            case self::T_INT:
+                return (int) $value;
+            default:
+                return $value;
+        }
+    }
+
+    /** @return int|bool|string */
+    private function _get(string $param) : mixed {
+        list ($value, $type_hint) = $this->params[$param];
+
+        return $this->cast_to($value, $type_hint);
+    }
+
+    private function _add(string $param, string $default, int $type_hint) : void {
+        $override = getenv($this::_ENVVAR_PREFIX . $param);
+
+        $this->params[$param] = [ self::cast_to(!empty($override) ? $override : $default, $type_hint), $type_hint ];
+    }
+
+    static function add(string $param, string $default, int $type_hint = Config::T_STRING) : void {
+        $instance = self::get_instance();
+
+        $instance->_add($param, $default, $type_hint);
+    }
+
+    /** @return int|bool|string */
+    static function get(string $param) {
+        $instance = self::get_instance();
+
+        return $instance->_get($param);
+    }
+
+    static function is_server_https() : bool {
+        return (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off')) ||
+            (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
+    }
+
+    /** generates reference self_url_path (no trailing slash) */
+    static function get_self_url() : string {
+        $proto = self::is_server_https() ? 'https' : 'http';
+        $self_url_path = $proto . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
+
+        $self_url_path = preg_replace("/\w+\.php(\?.*$)?$/", "", $self_url_path);
+
+        if (substr($self_url_path, -1) === "/") {
+            return substr($self_url_path, 0, -1);
+        } else {
+            return $self_url_path;
+        }
+    }
+
+    /** also initializes Db and ORM */
+    static function sanity_check() : void {
+
+        /*
+            we don't actually need the DB object right now but some checks below might use ORM which won't be initialized
+            because it is set up in the Db constructor, which is why it's a good idea to invoke it as early as possible
+
+            it is a bit of a hack, maybe ORM should be initialized somewhere else (functions.php?)
+        */
+
+        $pdo = Db::pdo();
+
+        $errors = [];
+
+        if (function_exists('posix_getuid') && posix_getuid() == 0) {
+            array_push($errors, "Please don't run this script as root.");
+        }
+
+        if (version_compare(PHP_VERSION, '7.1.0', '<')) {
+            array_push($errors, "PHP version 7.1.0 or newer required. You're using " . PHP_VERSION . ".");
+        }
+
+        if (php_sapi_name() != "cli") {
+            if (self::get_schema_version() < 0) {
+                array_push($errors, "Base database schema is missing. Either load it manually or perform a migration (<code>update.php --update-schema</code>)");
+            }
+        }
+
+        if (count($errors) > 0 && php_sapi_name() != "cli") { ?>
+            <!DOCTYPE html>
+            <html>
+                <head>
+                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+                    <link href="lib/bootstrap/v3/css/bootstrap.min.css" rel="stylesheet" media="screen">
+                    <link href="lib/bootstrap/v3/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
+                    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+                    <script src="dist/app-libs.min.js"></script>
+                    <title>Startup failed</title>
+                    <link type="text/css" rel="stylesheet" media="screen" href="dist/app.min.css" />
+                    <link rel="shortcut icon" type="image/png" href="img/favicon.png" />
+                    <link rel="manifest" href="manifest.json">
+                    <meta name="mobile-web-app-capable" content="yes">
+                    <script type="text/javascript">
+                        $(document).ready(function() {
+                                /* global EpubeApp */
+
+                                if (typeof EpubeApp != "undefined") {
+                                    EpubeApp.setPage("PAGE_LOGIN");
+                                }
+                        });
+                    </script>
+                </head>
+                <body class="epube-sanity-failed">
+                    <div class="container">
+                        <h1>Startup failed</h1>
+
+                        <p>Please fix errors indicated by the following messages:</p>
+
+                        <?php foreach ($errors as $error) { echo self::format_error($error); } ?>
+
+                    </div>
+                </body>
+            </html>
+
+        <?php
+            die;
+        } else if (count($errors) > 0) {
+            echo "Please fix errors indicated by the following messages:\n\n";
+
+            foreach ($errors as $error) {
+                echo " * " . strip_tags($error)."\n";
+            }
+
+            exit(1);
+        }
+    }
+
+    private static function format_error(string $msg) : string {
+        return "<div class=\"alert alert-danger\">$msg</div>";
+    }
 }
diff --git a/classes/CsrfMiddleware.php b/classes/CsrfMiddleware.php
index 1a49d48..0a03925 100644
--- a/classes/CsrfMiddleware.php
+++ b/classes/CsrfMiddleware.php
@@ -2,29 +2,29 @@
 
 class CsrfMiddleware implements MiddlewareInterface
 {
-	/** @var array<string> */
-	private array $csrfIgnore = [
-		"cover", "download", "getpagination", "getlastread", "getinfo", "list", "healthz"
-	];
+    /** @var array<string> */
+    private array $csrfIgnore = [
+        "cover", "download", "getpagination", "getlastread", "getinfo", "list", "healthz"
+    ];
 
-	public function process(Request $request, callable $next): Response
-	{
-		if (empty($_SESSION['owner'])) {
-			return $next($request);
-		}
+    public function process(Request $request, callable $next): Response
+    {
+        if (empty($_SESSION['owner'])) {
+            return $next($request);
+        }
 
-		$op = $request->getAttribute('op');
+        $op = $request->getAttribute('op');
 
-		$csrfToken = $request->getAttribute('csrf_token', '');
+        $csrfToken = $request->getAttribute('csrf_token', '');
 
-		if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) {
-			$response = (new Response())
-				->withStatus(401)
-				->withBody(json_encode(["error" => "Unauthorized (CSRF)"]));
-			$response->send();
-			exit;
-		}
+        if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) {
+            $response = (new Response())
+                ->withStatus(401)
+                ->withBody(json_encode(["error" => "Unauthorized (CSRF)"]));
+            $response->send();
+            exit;
+        }
 
-		return $next($request);
-	}
+        return $next($request);
+    }
 }
diff --git a/classes/Db.php b/classes/Db.php
index dcaa482..7f5a9f4 100644
--- a/classes/Db.php
+++ b/classes/Db.php
@@ -1,65 +1,65 @@
 <?php
 
 class Db {
-	private static ?Db $instance = null;
-
-	private PDO $pdo;
-
-	private function __construct() {
-		$db_type = Config::get(Config::DB_TYPE);
-
-		try {
-			$this->pdo = new PDO(self::get_dsn(),
-				Config::get(Config::DB_USER),
-				Config::get(Config::DB_PASS));
-
-			if ($db_type == 'sqlite') {
-				$this->pdo->query('PRAGMA journal_mode = wal');
-			}
-		} catch (Exception $e) {
-			user_error($e, E_USER_WARNING);
-			die("Unable to initialize database driver: " . Config::get(Config::DB_TYPE));
-		}
-
-		$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
-
-		try {
-			ORM::configure(self::get_dsn());
-			ORM::configure('return_result_sets', true);
-
-			if ($db_type == 'pgsql') {
-				ORM::configure('username', Config::get(Config::DB_USER));
-				ORM::configure('password', Config::get(Config::DB_PASS));
-				ORM::configure('return_result_sets', true);
-			} else {
-				ORM::raw_execute('PRAGMA journal_mode = wal');
-			}
-
-		} catch (Exception $e) {
-			user_error($e, E_USER_WARNING);
-			die("Unable to initialize ORM layer.");
-		}
-	}
-
-	public static function get_dsn() : string {
-		$db_type = Config::get(Config::DB_TYPE);
-
-		if ($db_type == 'pgsql') {
-			$db_port = Config::get(Config::DB_PORT) ? ';port=' . Config::get(Config::DB_PORT) : '';
-			$db_host = Config::get(Config::DB_HOST) ? ';host=' . Config::get(Config::DB_HOST) : '';
-
-			return $db_type . ':dbname=' . Config::get(Config::DB_NAME) . $db_host . $db_port;
-
-		} else {
-			return $db_type . ':' . Config::get(Config::SCRATCH_DB);
-		}
-	}
-
-	public static function pdo() : PDO {
-		if (self::$instance == null)
-			self::$instance = new self();
-
-		return self::$instance->pdo;
-	}
+    private static ?Db $instance = null;
+
+    private PDO $pdo;
+
+    private function __construct() {
+        $db_type = Config::get(Config::DB_TYPE);
+
+        try {
+            $this->pdo = new PDO(self::get_dsn(),
+                Config::get(Config::DB_USER),
+                Config::get(Config::DB_PASS));
+
+            if ($db_type == 'sqlite') {
+                $this->pdo->query('PRAGMA journal_mode = wal');
+            }
+        } catch (Exception $e) {
+            user_error($e, E_USER_WARNING);
+            die("Unable to initialize database driver: " . Config::get(Config::DB_TYPE));
+        }
+
+        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+
+        try {
+            ORM::configure(self::get_dsn());
+            ORM::configure('return_result_sets', true);
+
+            if ($db_type == 'pgsql') {
+                ORM::configure('username', Config::get(Config::DB_USER));
+                ORM::configure('password', Config::get(Config::DB_PASS));
+                ORM::configure('return_result_sets', true);
+            } else {
+                ORM::raw_execute('PRAGMA journal_mode = wal');
+            }
+
+        } catch (Exception $e) {
+            user_error($e, E_USER_WARNING);
+            die("Unable to initialize ORM layer.");
+        }
+    }
+
+    public static function get_dsn() : string {
+        $db_type = Config::get(Config::DB_TYPE);
+
+        if ($db_type == 'pgsql') {
+            $db_port = Config::get(Config::DB_PORT) ? ';port=' . Config::get(Config::DB_PORT) : '';
+            $db_host = Config::get(Config::DB_HOST) ? ';host=' . Config::get(Config::DB_HOST) : '';
+
+            return $db_type . ':dbname=' . Config::get(Config::DB_NAME) . $db_host . $db_port;
+
+        } else {
+            return $db_type . ':' . Config::get(Config::SCRATCH_DB);
+        }
+    }
+
+    public static function pdo() : PDO {
+        if (self::$instance == null)
+            self::$instance = new self();
+
+        return self::$instance->pdo;
+    }
 
 };
diff --git a/classes/Db_Migrations.php b/classes/Db_Migrations.php
index 1af798b..27419d0 100644
--- a/classes/Db_Migrations.php
+++ b/classes/Db_Migrations.php
@@ -1,194 +1,194 @@
 <?php
 class Db_Migrations {
 
-	private string $base_filename = "schema.sql";
-	private string $base_path;
-	private string $migrations_path;
-	private string $migrations_table;
-	private bool $base_is_latest;
-	private PDO $pdo;
-
-	private int $cached_version;
-	private int $cached_max_version;
-	private int $max_version_override;
-
-	function __construct() {
-		$this->pdo = Db::pdo();
-	}
-
-	function initialize(string $root_path, string $migrations_table, bool $base_is_latest = true, int $max_version_override = 0) : void {
-		$this->base_path = "$root_path/" . Config::get(Config::DB_TYPE);
-		$this->migrations_path = $this->base_path . "/migrations";
-		$this->migrations_table = $migrations_table;
-		$this->base_is_latest = $base_is_latest;
-		$this->max_version_override =  $max_version_override;
-	}
-
-	private function set_version(int $version) : void {
-		Debug::log("Updating table {$this->migrations_table} with version ${version}...", Debug::LOG_EXTENDED);
-
-		$sth = $this->pdo->query("SELECT * FROM {$this->migrations_table}");
-
-		if ($res = $sth->fetch()) {
-			$sth = $this->pdo->prepare("UPDATE {$this->migrations_table} SET schema_version = ?");
-		} else {
-			$sth = $this->pdo->prepare("INSERT INTO {$this->migrations_table} (schema_version) VALUES (?)");
-		}
-
-		$sth->execute([$version]);
-
-		$this->cached_version = $version;
-	}
-
-	function get_version() : int {
-		if (isset($this->cached_version))
-			return $this->cached_version;
-
-		try {
-			$sth = $this->pdo->query("SELECT * FROM {$this->migrations_table}");
-
-			if ($res = $sth->fetch()) {
-				return (int) $res['schema_version'];
-			} else {
-				return -1;
-			}
-		} catch (PDOException $e) {
-			$this->create_migrations_table();
-
-			return -1;
-		}
-	}
-
-	private function create_migrations_table() : void {
-		$this->pdo->query("CREATE TABLE IF NOT EXISTS {$this->migrations_table} (schema_version integer not null)");
-	}
-
-	private function migrate_to(int $version) : bool {
-		try {
-			if ($version <= $this->get_version()) {
-				Debug::log("Refusing to apply version $version: current version is higher", Debug::LOG_VERBOSE);
-				return false;
-			}
-
-			if ($version == 0)
-				Debug::log("Loading base database schema...", Debug::LOG_VERBOSE);
-			else
-				Debug::log("Starting migration to $version...", Debug::LOG_VERBOSE);
-
-			$lines = $this->get_lines($version);
-
-			if (count($lines) > 0) {
-				// mysql doesn't support transactions for DDL statements
-				if (Config::get(Config::DB_TYPE) != "mysql")
-					$this->pdo->beginTransaction();
-
-				foreach ($lines as $line) {
-					Debug::log($line, Debug::LOG_EXTENDED);
-					try {
-						$this->pdo->query($line);
-					} catch (PDOException $e) {
-						Debug::log("Failed on line: $line", Debug::LOG_VERBOSE);
-						throw $e;
-					}
-				}
-
-				if ($version == 0 && $this->base_is_latest)
-					$this->set_version($this->get_max_version());
-				else
-					$this->set_version($version);
-
-				if (Config::get(Config::DB_TYPE) != "mysql")
-					$this->pdo->commit();
-
-				Debug::log("Migration finished, current version: " . $this->get_version(), Debug::LOG_VERBOSE);
-
-				return true;
-			} else {
-				Debug::log("Migration failed: schema file is empty or missing.", Debug::LOG_VERBOSE);
-			}
-
-		} catch (PDOException $e) {
-			Debug::log("Migration failed: " . $e->getMessage(), Debug::LOG_VERBOSE);
-			try {
-				$this->pdo->rollback();
-			} catch (PDOException $ie) {
-				//
-			}
-			throw $e;
-		}
-
-		return false;
-	}
-
-	function get_max_version() : int {
-		if ($this->max_version_override > 0)
-			return $this->max_version_override;
-
-		if (isset($this->cached_max_version))
-			return $this->cached_max_version;
-
-		$migrations = glob("{$this->migrations_path}/*.sql");
-
-		if (count($migrations) > 0) {
-			natsort($migrations);
-
-			$this->cached_max_version = (int) basename(array_pop($migrations), ".sql");
-
-		} else {
-			$this->cached_max_version = 0;
-		}
-
-		return $this->cached_max_version;
-	}
-
-	function is_migration_needed() : bool {
-		return $this->get_version() != $this->get_max_version();
-	}
-
-	function migrate() : bool {
-
-		if ($this->get_version() == -1) {
-			try {
-				$this->migrate_to(0);
-			} catch (PDOException $e) {
-				user_error("Failed to load base schema for {$this->migrations_table}: " . $e->getMessage(), E_USER_WARNING);
-				return false;
-			}
-		}
-
-		for ($i = $this->get_version() + 1; $i <= $this->get_max_version(); $i++) {
-			try {
-				$this->migrate_to($i);
-			} catch (PDOException $e) {
-				user_error("Failed to apply migration ${i} for {$this->migrations_table}: " . $e->getMessage(), E_USER_WARNING);
-				return false;
-				//throw $e;
-			}
-		}
-
-		return !$this->is_migration_needed();
-	}
-
-	/** @return array<string> */
-	private function get_lines(int $version) : array {
-		if ($version > 0)
-			$filename = "{$this->migrations_path}/${version}.sql";
-		else
-			$filename = "{$this->base_path}/{$this->base_filename}";
-
-		if (file_exists($filename)) {
-			$lines =	array_filter(preg_split("/[\r\n]/", file_get_contents($filename)),
-							function ($line) {
-								return strlen(trim($line)) > 0 && strpos($line, "--") !== 0;
-							});
-
-			return array_filter(explode(";", implode("", $lines)), function ($line) {
-				return strlen(trim($line)) > 0 && !in_array(strtolower($line), ["begin", "commit"]);
-			});
-
-		} else {
-			user_error("Requested schema file ${filename} not found.", E_USER_ERROR);
-			return [];
-		}
-	}
+    private string $base_filename = "schema.sql";
+    private string $base_path;
+    private string $migrations_path;
+    private string $migrations_table;
+    private bool $base_is_latest;
+    private PDO $pdo;
+
+    private int $cached_version;
+    private int $cached_max_version;
+    private int $max_version_override;
+
+    function __construct() {
+        $this->pdo = Db::pdo();
+    }
+
+    function initialize(string $root_path, string $migrations_table, bool $base_is_latest = true, int $max_version_override = 0) : void {
+        $this->base_path = "$root_path/" . Config::get(Config::DB_TYPE);
+        $this->migrations_path = $this->base_path . "/migrations";
+        $this->migrations_table = $migrations_table;
+        $this->base_is_latest = $base_is_latest;
+        $this->max_version_override =  $max_version_override;
+    }
+
+    private function set_version(int $version) : void {
+        Debug::log("Updating table {$this->migrations_table} with version ${version}...", Debug::LOG_EXTENDED);
+
+        $sth = $this->pdo->query("SELECT * FROM {$this->migrations_table}");
+
+        if ($res = $sth->fetch()) {
+            $sth = $this->pdo->prepare("UPDATE {$this->migrations_table} SET schema_version = ?");
+        } else {
+            $sth = $this->pdo->prepare("INSERT INTO {$this->migrations_table} (schema_version) VALUES (?)");
+        }
+
+        $sth->execute([$version]);
+
+        $this->cached_version = $version;
+    }
+
+    function get_version() : int {
+        if (isset($this->cached_version))
+            return $this->cached_version;
+
+        try {
+            $sth = $this->pdo->query("SELECT * FROM {$this->migrations_table}");
+
+            if ($res = $sth->fetch()) {
+                return (int) $res['schema_version'];
+            } else {
+                return -1;
+            }
+        } catch (PDOException $e) {
+            $this->create_migrations_table();
+
+            return -1;
+        }
+    }
+
+    private function create_migrations_table() : void {
+        $this->pdo->query("CREATE TABLE IF NOT EXISTS {$this->migrations_table} (schema_version integer not null)");
+    }
+
+    private function migrate_to(int $version) : bool {
+        try {
+            if ($version <= $this->get_version()) {
+                Debug::log("Refusing to apply version $version: current version is higher", Debug::LOG_VERBOSE);
+                return false;
+            }
+
+            if ($version == 0)
+                Debug::log("Loading base database schema...", Debug::LOG_VERBOSE);
+            else
+                Debug::log("Starting migration to $version...", Debug::LOG_VERBOSE);
+
+            $lines = $this->get_lines($version);
+
+            if (count($lines) > 0) {
+                // mysql doesn't support transactions for DDL statements
+                if (Config::get(Config::DB_TYPE) != "mysql")
+                    $this->pdo->beginTransaction();
+
+                foreach ($lines as $line) {
+                    Debug::log($line, Debug::LOG_EXTENDED);
+                    try {
+                        $this->pdo->query($line);
+                    } catch (PDOException $e) {
+                        Debug::log("Failed on line: $line", Debug::LOG_VERBOSE);
+                        throw $e;
+                    }
+                }
+
+                if ($version == 0 && $this->base_is_latest)
+                    $this->set_version($this->get_max_version());
+                else
+                    $this->set_version($version);
+
+                if (Config::get(Config::DB_TYPE) != "mysql")
+                    $this->pdo->commit();
+
+                Debug::log("Migration finished, current version: " . $this->get_version(), Debug::LOG_VERBOSE);
+
+                return true;
+            } else {
+                Debug::log("Migration failed: schema file is empty or missing.", Debug::LOG_VERBOSE);
+            }
+
+        } catch (PDOException $e) {
+            Debug::log("Migration failed: " . $e->getMessage(), Debug::LOG_VERBOSE);
+            try {
+                $this->pdo->rollback();
+            } catch (PDOException $ie) {
+                //
+            }
+            throw $e;
+        }
+
+        return false;
+    }
+
+    function get_max_version() : int {
+        if ($this->max_version_override > 0)
+            return $this->max_version_override;
+
+        if (isset($this->cached_max_version))
+            return $this->cached_max_version;
+
+        $migrations = glob("{$this->migrations_path}/*.sql");
+
+        if (count($migrations) > 0) {
+            natsort($migrations);
+
+            $this->cached_max_version = (int) basename(array_pop($migrations), ".sql");
+
+        } else {
+            $this->cached_max_version = 0;
+        }
+
+        return $this->cached_max_version;
+    }
+
+    function is_migration_needed() : bool {
+        return $this->get_version() != $this->get_max_version();
+    }
+
+    function migrate() : bool {
+
+        if ($this->get_version() == -1) {
+            try {
+                $this->migrate_to(0);
+            } catch (PDOException $e) {
+                user_error("Failed to load base schema for {$this->migrations_table}: " . $e->getMessage(), E_USER_WARNING);
+                return false;
+            }
+        }
+
+        for ($i = $this->get_version() + 1; $i <= $this->get_max_version(); $i++) {
+            try {
+                $this->migrate_to($i);
+            } catch (PDOException $e) {
+                user_error("Failed to apply migration ${i} for {$this->migrations_table}: " . $e->getMessage(), E_USER_WARNING);
+                return false;
+                //throw $e;
+            }
+        }
+
+        return !$this->is_migration_needed();
+    }
+
+    /** @return array<string> */
+    private function get_lines(int $version) : array {
+        if ($version > 0)
+            $filename = "{$this->migrations_path}/${version}.sql";
+        else
+            $filename = "{$this->base_path}/{$this->base_filename}";
+
+        if (file_exists($filename)) {
+            $lines =    array_filter(preg_split("/[\r\n]/", file_get_contents($filename)),
+                            function ($line) {
+                                return strlen(trim($line)) > 0 && strpos($line, "--") !== 0;
+                            });
+
+            return array_filter(explode(";", implode("", $lines)), function ($line) {
+                return strlen(trim($line)) > 0 && !in_array(strtolower($line), ["begin", "commit"]);
+            });
+
+        } else {
+            user_error("Requested schema file ${filename} not found.", E_USER_ERROR);
+            return [];
+        }
+    }
 }
diff --git a/classes/Debug.php b/classes/Debug.php
index 7e7cc29..0384c87 100644
--- a/classes/Debug.php
+++ b/classes/Debug.php
@@ -1,91 +1,91 @@
 <?php
 class Debug {
-	const LOG_DISABLED = -1;
-	const LOG_NORMAL = 0;
-	const LOG_VERBOSE = 1;
-	const LOG_EXTENDED = 2;
+    const LOG_DISABLED = -1;
+    const LOG_NORMAL = 0;
+    const LOG_VERBOSE = 1;
+    const LOG_EXTENDED = 2;
 
-	public static int $LOG_DISABLED = -1;
-	public static int $LOG_NORMAL = 0;
-	public static int $LOG_VERBOSE = 1;
-	public static int $LOG_EXTENDED = 2;
+    public static int $LOG_DISABLED = -1;
+    public static int $LOG_NORMAL = 0;
+    public static int $LOG_VERBOSE = 1;
+    public static int $LOG_EXTENDED = 2;
 
-	private static bool $enabled = false;
-	private static bool $quiet = false;
-	private static string $logfile = "";
-	private static int $loglevel = 0;
+    private static bool $enabled = false;
+    private static bool $quiet = false;
+    private static string $logfile = "";
+    private static int $loglevel = 0;
 
-	public static function set_logfile(string $logfile) : void {
-		self::$logfile = $logfile;
-	}
+    public static function set_logfile(string $logfile) : void {
+        self::$logfile = $logfile;
+    }
 
-	public static function enabled() : bool {
-		return self::$enabled;
-	}
+    public static function enabled() : bool {
+        return self::$enabled;
+    }
 
-	public static function set_enabled(bool $enable) : void {
-		self::$enabled = $enable;
-	}
+    public static function set_enabled(bool $enable) : void {
+        self::$enabled = $enable;
+    }
 
-	public static function set_quiet(bool $quiet) : void {
-		self::$quiet = $quiet;
-	}
+    public static function set_quiet(bool $quiet) : void {
+        self::$quiet = $quiet;
+    }
 
-	public static function set_loglevel(int $level) : void {
-		self::$loglevel = $level;
-	}
+    public static function set_loglevel(int $level) : void {
+        self::$loglevel = $level;
+    }
 
-	public static function get_loglevel() : int {
-		return self::$loglevel;
-	}
+    public static function get_loglevel() : int {
+        return self::$loglevel;
+    }
 
-	public static function log(string $message, int $level = 0) : void {
+    public static function log(string $message, int $level = 0) : void {
 
-		if (!self::$enabled || self::$loglevel < $level) return;
+        if (!self::$enabled || self::$loglevel < $level) return;
 
-		$ts = strftime("%H:%M:%S", time());
-		if (function_exists('posix_getpid')) {
-			$ts = "$ts/" . posix_getpid();
-		}
+        $ts = strftime("%H:%M:%S", time());
+        if (function_exists('posix_getpid')) {
+            $ts = "$ts/" . posix_getpid();
+        }
 
-		if (self::$logfile) {
-			$fp = fopen(self::$logfile, 'a+');
+        if (self::$logfile) {
+            $fp = fopen(self::$logfile, 'a+');
 
-			if ($fp) {
-				$locked = false;
+            if ($fp) {
+                $locked = false;
 
-				if (function_exists("flock")) {
-					$tries = 0;
+                if (function_exists("flock")) {
+                    $tries = 0;
 
-					// try to lock logfile for writing
-					while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
-						sleep(1);
-						++$tries;
-					}
+                    // try to lock logfile for writing
+                    while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
+                        sleep(1);
+                        ++$tries;
+                    }
 
-					if (!$locked) {
-						fclose($fp);
-						user_error("Unable to lock debugging log file: " . self::$logfile, E_USER_WARNING);
-						return;
-					}
-				}
+                    if (!$locked) {
+                        fclose($fp);
+                        user_error("Unable to lock debugging log file: " . self::$logfile, E_USER_WARNING);
+                        return;
+                    }
+                }
 
-				fputs($fp, "[$ts] $message\n");
+                fputs($fp, "[$ts] $message\n");
 
-				if (function_exists("flock")) {
-					flock($fp, LOCK_UN);
-				}
+                if (function_exists("flock")) {
+                    flock($fp, LOCK_UN);
+                }
 
-				fclose($fp);
+                fclose($fp);
 
-				if (self::$quiet)
-					return;
+                if (self::$quiet)
+                    return;
 
-			} else {
-				user_error("Unable to open debugging log file: " . self::$logfile, E_USER_WARNING);
-			}
-		}
+            } else {
+                user_error("Unable to open debugging log file: " . self::$logfile, E_USER_WARNING);
+            }
+        }
 
-		print "[$ts] $message\n";
-	}
+        print "[$ts] $message\n";
+    }
 }
diff --git a/classes/Handler/CoverHandler.php b/classes/Handler/CoverHandler.php
index cd502ba..4e95e54 100644
--- a/classes/Handler/CoverHandler.php
+++ b/classes/Handler/CoverHandler.php
@@ -11,32 +11,32 @@ use PDO;
 
 class CoverHandler implements RequestHandlerInterface, AuthRequired
 {
-	public function handle(Request $request): Response
-	{
-		$id = (int) $request->getAttribute('id');
-		$db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
-		$sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?");
-		$sth->execute([$id]);
+    public function handle(Request $request): Response
+    {
+        $id = (int) $request->getAttribute('id');
+        $db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
+        $sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?");
+        $sth->execute([$id]);
 
-		while ($line = $sth->fetch()) {
-			$filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg";
+        while ($line = $sth->fetch()) {
+            $filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg";
 
-			if (file_exists($filename)) {
-				return (new Response())
-					->withHeader("Content-type", mime_content_type($filename))
-					->withHeader('Cache-control', "max-age=" . STATIC_EXPIRES)
-					->withHeader("Expires", gmdate("D, d M Y H:i:s \G\M\T", time()+STATIC_EXPIRES))
-					->withHeader("Last-Modified", gmdate("D, d M Y H:i:s \G\M\T", filemtime($filename)))
-					->withBody(file_get_contents($filename) ?: '');
-			} else {
-				return (new Response())
-					->withStatus(404)
-					->withBody(json_encode(["error" => "Not found."]));
-			}
-		}
+            if (file_exists($filename)) {
+                return (new Response())
+                    ->withHeader("Content-type", mime_content_type($filename))
+                    ->withHeader('Cache-control', "max-age=" . STATIC_EXPIRES)
+                    ->withHeader("Expires", gmdate("D, d M Y H:i:s \G\M\T", time()+STATIC_EXPIRES))
+                    ->withHeader("Last-Modified", gmdate("D, d M Y H:i:s \G\M\T", filemtime($filename)))
+                    ->withBody(file_get_contents($filename) ?: '');
+            } else {
+                return (new Response())
+                    ->withStatus(404)
+                    ->withBody(json_encode(["error" => "Not found."]));
+            }
+        }
 
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "Not found."]));
-	}
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "Not found."]));
+    }
 }
diff --git a/classes/Handler/DefineHandler.php b/classes/Handler/DefineHandler.php
index 87fd3f9..60d5b11 100644
--- a/classes/Handler/DefineHandler.php
+++ b/classes/Handler/DefineHandler.php
@@ -10,59 +10,59 @@ use Response;
 
 class DefineHandler implements RequestHandlerInterface, AuthRequired
 {
-	/** @return array<string> */
-	private function parseDictReply(string $reply): array
-	{
-		$tmp = [];
+    /** @return array<string> */
+    private function parseDictReply(string $reply): array
+    {
+        $tmp = [];
 
-		foreach (explode("\n", $reply) as $line) {
-			list($code, $message) = explode(" ", $line, 2);
+        foreach (explode("\n", $reply) as $line) {
+            list($code, $message) = explode(" ", $line, 2);
 
-			if (!$code && $message) {
-				array_push($tmp, $message);
-			}
-		}
+            if (!$code && $message) {
+                array_push($tmp, $message);
+            }
+        }
 
-		return $tmp;
-	}
+        return $tmp;
+    }
 
-	public function handle(Request $request): Response
-	{
-		if (!Config::get(Config::DICT_SERVER)) {
-			return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]]));
-		}
+    public function handle(Request $request): Response
+    {
+        if (!Config::get(Config::DICT_SERVER)) {
+            return (new Response())->withBody(json_encode(["result" => ["Dictionary lookups are disabled."]]));
+        }
 
-		$word = strip_tags(str_replace("­", "", $request->getAttribute('word')));
-		$origWord = $word;
-		$result = [];
+        $word = strip_tags(str_replace("­", "", $request->getAttribute('word')));
+        $origWord = $word;
+        $result = [];
 
-		for ($i = 0; $i < 3; $i++) {
-			$ch = curl_init();
-			curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", Config::get(Config::DICT_SERVER), $word));
-			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-			$dictReply = curl_exec($ch);
+        for ($i = 0; $i < 3; $i++) {
+            $ch = curl_init();
+            curl_setopt($ch, CURLOPT_URL, sprintf("dict://%s/define:%s", Config::get(Config::DICT_SERVER), $word));
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+            $dictReply = curl_exec($ch);
 
-			if ($dictReply) {
-				$retParsed = $this->parseDictReply($dictReply);
+            if ($dictReply) {
+                $retParsed = $this->parseDictReply($dictReply);
 
-				if (count($retParsed) > 0) {
-					array_push($result, "<strong>$word</strong>");
-					$result = array_merge($result, $retParsed);
-					break;
-				} else {
-					$word = mb_substr($word, 0, mb_strlen($word) - 1);
-				}
-			} else {
-				array_push($result, curl_error($ch));
-			}
+                if (count($retParsed) > 0) {
+                    array_push($result, "<strong>$word</strong>");
+                    $result = array_merge($result, $retParsed);
+                    break;
+                } else {
+                    $word = mb_substr($word, 0, mb_strlen($word) - 1);
+                }
+            } else {
+                array_push($result, curl_error($ch));
+            }
 
-			curl_close($ch);
-		}
+            curl_close($ch);
+        }
 
-		if (count($result) == 0) {
-			array_push($result, "No results for: <b>$origWord</b>");
-		}
+        if (count($result) == 0) {
+            array_push($result, "No results for: <b>$origWord</b>");
+        }
 
-		return (new Response())->withBody(json_encode(["result" => $result]));
-	}
+        return (new Response())->withBody(json_encode(["result" => $result]));
+    }
 }
diff --git a/classes/Handler/DownloadHandler.php b/classes/Handler/DownloadHandler.php
index 023ae8a..330c04f 100644
--- a/classes/Handler/DownloadHandler.php
+++ b/classes/Handler/DownloadHandler.php
@@ -11,26 +11,26 @@ 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]);
+    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"]);
+        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(file_get_contents($filename) ?: '');
-			}
-		}
+            if (file_exists($filename)) {
+                return (new Response())
+                    ->withHeader("Content-type", mime_content_type($filename))
+                    ->withHeader("Content-Disposition", 'attachment; filename="' . basename($filename) . '"')
+                    ->withBody(file_get_contents($filename) ?: '');
+            }
+        }
 
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "Not found."]));
-	}
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "Not found."]));
+    }
 }
diff --git a/classes/Handler/GetinfoHandler.php b/classes/Handler/GetinfoHandler.php
index 8914040..ee4a69a 100644
--- a/classes/Handler/GetinfoHandler.php
+++ b/classes/Handler/GetinfoHandler.php
@@ -12,27 +12,27 @@ 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));
+    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]);
+        $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'] ?? "");
+        if ($row = $sth->fetch()) {
+            $row['comment'] = Sanitizer::sanitize($row['comment'] ?? "");
 
-			return (new Response())->withBody(json_encode($row));
-		}
+            return (new Response())->withBody(json_encode($row));
+        }
 
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "Not found."]));
-	}
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "Not found."]));
+    }
 }
diff --git a/classes/Handler/HealthzHandler.php b/classes/Handler/HealthzHandler.php
index a243b9f..722422c 100644
--- a/classes/Handler/HealthzHandler.php
+++ b/classes/Handler/HealthzHandler.php
@@ -11,39 +11,39 @@ use Response;
 
 class HealthzHandler implements RequestHandlerInterface
 {
-	public function handle(Request $request): Response
-	{
-		$status = "ok";
-		$errors = [];
-
-		// Test Calibre SQLite database
-		try {
-			$caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
-			$caldb->query("SELECT 1 FROM books LIMIT 1");
-		} catch (\PDOException $e) {
-			$status = "degraded";
-			$errors["calibre_db"] = "Connection failed: " . $e->getMessage();
-		}
-
-		// Test main database (via ORM/Db)
-		try {
-			Db::pdo()->query("SELECT 1");
-		} catch (\PDOException $e) {
-			$status = "degraded";
-			$errors["main_db"] = "Connection failed: " . $e->getMessage();
-		}
-
-		$response = (new Response())
-			->withHeader("Content-Type", "application/json")
-			->withBody(json_encode([
-				"status" => $status,
-				"errors" => $errors,
-			]));
-
-		if ($status === "degraded") {
-			$response = $response->withStatus(503);
-		}
-
-		return $response;
-	}
+    public function handle(Request $request): Response
+    {
+        $status = "ok";
+        $errors = [];
+
+        // Test Calibre SQLite database
+        try {
+            $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
+            $caldb->query("SELECT 1 FROM books LIMIT 1");
+        } catch (\PDOException $e) {
+            $status = "degraded";
+            $errors["calibre_db"] = "Connection failed: " . $e->getMessage();
+        }
+
+        // Test main database (via ORM/Db)
+        try {
+            Db::pdo()->query("SELECT 1");
+        } catch (\PDOException $e) {
+            $status = "degraded";
+            $errors["main_db"] = "Connection failed: " . $e->getMessage();
+        }
+
+        $response = (new Response())
+            ->withHeader("Content-Type", "application/json")
+            ->withBody(json_encode([
+                "status" => $status,
+                "errors" => $errors,
+            ]));
+
+        if ($status === "degraded") {
+            $response = $response->withStatus(503);
+        }
+
+        return $response;
+    }
 }
diff --git a/classes/Handler/LastreadHandler.php b/classes/Handler/LastreadHandler.php
index cdaade0..ab177ed 100644
--- a/classes/Handler/LastreadHandler.php
+++ b/classes/Handler/LastreadHandler.php
@@ -10,76 +10,76 @@ use Response;
 
 class LastreadHandler implements RequestHandlerInterface, AuthRequired
 {
-	private function handleGet(int $bookid): Response
-	{
-		if ($bookid) {
-			$book = ORM::for_table('epube_books')
-				->where('bookid', $bookid)
-				->where('owner', $_SESSION["owner"] ?? "")
-				->find_one();
+    private function handleGet(int $bookid): Response
+    {
+        if ($bookid) {
+            $book = ORM::for_table('epube_books')
+                ->where('bookid', $bookid)
+                ->where('owner', $_SESSION["owner"] ?? "")
+                ->find_one();
 
-			if ($book) {
-				return (new Response())->withBody(json_encode([
-					"page" => (int)$book->lastread,
-					"cfi" => $book->lastcfi,
-					"total" => 100,
-					"timestamp" => (int)$book->lastts
-				]));
-			}
-		}
+            if ($book) {
+                return (new Response())->withBody(json_encode([
+                    "page" => (int)$book->lastread,
+                    "cfi" => $book->lastcfi,
+                    "total" => 100,
+                    "timestamp" => (int)$book->lastts
+                ]));
+            }
+        }
 
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "Not found."]));
-	}
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "Not found."]));
+    }
 
-	private function handleStore(int $bookid, int $page, string $cfi, int $timestamp): Response
-	{
-		if ($bookid) {
-			$book = ORM::for_table('epube_books')
-				->where('bookid', $bookid)
-				->where('owner', $_SESSION["owner"] ?? "")
-				->find_one();
+    private function handleStore(int $bookid, int $page, string $cfi, int $timestamp): Response
+    {
+        if ($bookid) {
+            $book = ORM::for_table('epube_books')
+                ->where('bookid', $bookid)
+                ->where('owner', $_SESSION["owner"] ?? "")
+                ->find_one();
 
-			if ($book) {
-				if (($timestamp >= $book->lastts) && ($page >= $book->lastread || $page == PAGE_RESET_PROGRESS)) {
-					$book->set([
-						'lastread' => $page,
-						'lastcfi' => $cfi,
-						'lastts' => $timestamp,
-					]);
-				}
-			} else {
-				$book = ORM::for_table('epube_books')->create();
-				$book->set([
-					'bookid' => $bookid,
-					'owner' => $_SESSION["owner"] ?? "",
-					'lastread' => $page,
-					'lastcfi' => $cfi,
-					'lastts' => $timestamp,
-				]);
-			}
+            if ($book) {
+                if (($timestamp >= $book->lastts) && ($page >= $book->lastread || $page == PAGE_RESET_PROGRESS)) {
+                    $book->set([
+                        'lastread' => $page,
+                        'lastcfi' => $cfi,
+                        'lastts' => $timestamp,
+                    ]);
+                }
+            } else {
+                $book = ORM::for_table('epube_books')->create();
+                $book->set([
+                    'bookid' => $bookid,
+                    'owner' => $_SESSION["owner"] ?? "",
+                    'lastread' => $page,
+                    'lastcfi' => $cfi,
+                    'lastts' => $timestamp,
+                ]);
+            }
 
-			$book->save();
-		}
+            $book->save();
+        }
 
-		return (new Response())->withBody(json_encode(["page" => $page, "cfi" => $cfi]));
-	}
+        return (new Response())->withBody(json_encode(["page" => $page, "cfi" => $cfi]));
+    }
 
-	public function handle(Request $request): Response
-	{
-		$subOp = $request->getAttribute('op', '');
-		$bookid = (int) $request->getAttribute('id');
+    public function handle(Request $request): Response
+    {
+        $subOp = $request->getAttribute('op', '');
+        $bookid = (int) $request->getAttribute('id');
 
-		return match ($subOp) {
-			'getlastread'    => $this->handleGet($bookid),
-			'storelastread'  => $this->handleStore(
-				$bookid,
-				(int) $request->getAttribute('page'),
-				(string) $request->getAttribute('cfi', ''),
-				(int) $request->getAttribute('timestamp'),
-			),
-			default          => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])),
-		};
-	}
+        return match ($subOp) {
+            'getlastread'    => $this->handleGet($bookid),
+            'storelastread'  => $this->handleStore(
+                $bookid,
+                (int) $request->getAttribute('page'),
+                (string) $request->getAttribute('cfi', ''),
+                (int) $request->getAttribute('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 fbfb2b3..e4f6455 100644
--- a/classes/Handler/ListHandler.php
+++ b/classes/Handler/ListHandler.php
@@ -11,154 +11,154 @@ use PDO;
 
 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);
-
-		$ldb = \Db::pdo();
-		$caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
-
-		$ids_qpart = "1";
-
-		if ($mode == "favorites") {
-			$fav_sth = $ldb->prepare("SELECT bookid FROM epube_favorites WHERE owner = ?");
-			$fav_sth->execute([$owner]);
-
-			$fav_ids = [];
-			while ($line = $fav_sth->fetch()) {
-				array_push($fav_ids, $line["bookid"]);
-			}
-
-			if (empty($fav_ids)) {
-				return (new Response())->withBody(json_encode(["books" => [], "total" => 0]));
-			}
-
-			$ids_qpart = "books.id IN (" . implode(",", $fav_ids) . ")";
-		}
-
-		$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,
-			(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
-				((:query = '') OR
-					(
-						LOWER(books.author_sort) LIKE LOWER(:query) OR
-						LOWER(books.title) LIKE LOWER(:query) OR
-						LOWER(series_name) LIKE LOWER(:query)
-					))
-				AND $ids_qpart
-			ORDER BY $order_by LIMIT :limit OFFSET :offset");
-
-		$sth->execute([':limit' => $limit, ':offset' => $offset, ':query' => '%' . $query . '%']);
-
-		$books = [];
-		$total = 0;
-
-		while ($line = $sth->fetch()) {
-			$cover_link = "";
-			if ($line['has_cover']) {
-				$cover_filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg";
-				if (file_exists($cover_filename)) {
-					$cover_mtime = filemtime($cover_filename);
-					$cover_link = "backend.php?" . http_build_query(["op" => "cover", "id" => $line["id"], "ts" => $cover_mtime]);
-				}
-			}
-
-			$read_link = "";
-			$in_progress = false;
-			$is_read = false;
-
-			if ($line["epub_id"]) {
-				$read_link = "read.html?" . http_build_query(["id" => $line["epub_id"], "rt" => $mode, "b" => $line["id"], "ts" => time()]);
-
-				$lastread_sth = $ldb->prepare("SELECT lastread, total_pages FROM epube_books, epube_pagination
-					WHERE epube_pagination.bookid = epube_books.bookid AND
-						epube_books.bookid = ? AND owner = ?");
-				$lastread_sth->execute([$line['epub_id'], $owner]);
-
-				if ($lastread_line = $lastread_sth->fetch()) {
-					$lastread = $lastread_line["lastread"];
-					$total_pages = $lastread_line["total_pages"];
-
-					$is_read = $total_pages - $lastread < 5;
-					$in_progress = $lastread > 1;
-				}
-			}
-
-			$series_link = "";
-			$series_full = "";
-
-			if ($line["series_name"]) {
-				$series_link = "?" . http_build_query(["query" => $line["series_name"]]);
-				$series_full = $line["series_name"] . " [" . $line["series_index"] . "]";
-			}
-
-			$data_sth = $caldb->prepare("SELECT * FROM data WHERE book = ? LIMIT 3");
-			$data_sth->execute([$line['id']]);
-
-			$download_formats = [];
-			while ($data_line = $data_sth->fetch()) {
-				if ($data_line["format"] != "ORIGINAL_EPUB") {
-					$download_formats[] = [
-						"format" => $data_line["format"],
-						"id" => $data_line["id"],
-					];
-				}
-			}
-
-			$is_fav = false;
-			$fav_sth = $ldb->prepare("SELECT id FROM epube_favorites
-				WHERE bookid = ? AND owner = ? LIMIT 1");
-			$fav_sth->execute([$line['id'], $owner]);
-			if ($fav_sth->fetch()) {
-				$is_fav = true;
-			}
-
-			$books[] = [
-				"id" => $line["id"],
-				"title" => $line["title"],
-				"author_sort" => $line["author_sort"],
-				"series_name" => $line["series_name"] ?? "",
-				"series_index" => $line["series_index"] ?? 0,
-				"series_link" => $series_link,
-				"series_full" => $series_full,
-				"cover_link" => $cover_link,
-				"read_link" => $read_link,
-				"in_progress" => $in_progress,
-				"is_read" => $is_read,
-				"is_fav" => $is_fav,
-				"epub_id" => $line["epub_id"] ?? 0,
-				"download_formats" => $download_formats,
-			];
-		}
-
-		// count total for pagination
-		$count_sth = $caldb->prepare("SELECT COUNT(*) 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
-				((:query = '%%') OR
-					(
-						LOWER(books.author_sort) LIKE LOWER(:query) OR
-						LOWER(books.title) LIKE LOWER(:query) OR
-						LOWER(s.name) LIKE LOWER(:query)
-					))
-				AND $ids_qpart");
-		$count_sth->execute([':query' => '%' . $query . '%']);
-		$total = (int) $count_sth->fetchColumn();
-
-		return (new Response())->withBody(json_encode([
-			"books" => $books,
-			"total" => $total,
-			"offset" => $offset,
-			"limit" => $limit,
-		]));
-	}
+    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);
+
+        $ldb = \Db::pdo();
+        $caldb = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
+
+        $ids_qpart = "1";
+
+        if ($mode == "favorites") {
+            $fav_sth = $ldb->prepare("SELECT bookid FROM epube_favorites WHERE owner = ?");
+            $fav_sth->execute([$owner]);
+
+            $fav_ids = [];
+            while ($line = $fav_sth->fetch()) {
+                array_push($fav_ids, $line["bookid"]);
+            }
+
+            if (empty($fav_ids)) {
+                return (new Response())->withBody(json_encode(["books" => [], "total" => 0]));
+            }
+
+            $ids_qpart = "books.id IN (" . implode(",", $fav_ids) . ")";
+        }
+
+        $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,
+            (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
+                ((:query = '') OR
+                    (
+                        LOWER(books.author_sort) LIKE LOWER(:query) OR
+                        LOWER(books.title) LIKE LOWER(:query) OR
+                        LOWER(series_name) LIKE LOWER(:query)
+                    ))
+                AND $ids_qpart
+            ORDER BY $order_by LIMIT :limit OFFSET :offset");
+
+        $sth->execute([':limit' => $limit, ':offset' => $offset, ':query' => '%' . $query . '%']);
+
+        $books = [];
+        $total = 0;
+
+        while ($line = $sth->fetch()) {
+            $cover_link = "";
+            if ($line['has_cover']) {
+                $cover_filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg";
+                if (file_exists($cover_filename)) {
+                    $cover_mtime = filemtime($cover_filename);
+                    $cover_link = "backend.php?" . http_build_query(["op" => "cover", "id" => $line["id"], "ts" => $cover_mtime]);
+                }
+            }
+
+            $read_link = "";
+            $in_progress = false;
+            $is_read = false;
+
+            if ($line["epub_id"]) {
+                $read_link = "read.html?" . http_build_query(["id" => $line["epub_id"], "rt" => $mode, "b" => $line["id"], "ts" => time()]);
+
+                $lastread_sth = $ldb->prepare("SELECT lastread, total_pages FROM epube_books, epube_pagination
+                    WHERE epube_pagination.bookid = epube_books.bookid AND
+                        epube_books.bookid = ? AND owner = ?");
+                $lastread_sth->execute([$line['epub_id'], $owner]);
+
+                if ($lastread_line = $lastread_sth->fetch()) {
+                    $lastread = $lastread_line["lastread"];
+                    $total_pages = $lastread_line["total_pages"];
+
+                    $is_read = $total_pages - $lastread < 5;
+                    $in_progress = $lastread > 1;
+                }
+            }
+
+            $series_link = "";
+            $series_full = "";
+
+            if ($line["series_name"]) {
+                $series_link = "?" . http_build_query(["query" => $line["series_name"]]);
+                $series_full = $line["series_name"] . " [" . $line["series_index"] . "]";
+            }
+
+            $data_sth = $caldb->prepare("SELECT * FROM data WHERE book = ? LIMIT 3");
+            $data_sth->execute([$line['id']]);
+
+            $download_formats = [];
+            while ($data_line = $data_sth->fetch()) {
+                if ($data_line["format"] != "ORIGINAL_EPUB") {
+                    $download_formats[] = [
+                        "format" => $data_line["format"],
+                        "id" => $data_line["id"],
+                    ];
+                }
+            }
+
+            $is_fav = false;
+            $fav_sth = $ldb->prepare("SELECT id FROM epube_favorites
+                WHERE bookid = ? AND owner = ? LIMIT 1");
+            $fav_sth->execute([$line['id'], $owner]);
+            if ($fav_sth->fetch()) {
+                $is_fav = true;
+            }
+
+            $books[] = [
+                "id" => $line["id"],
+                "title" => $line["title"],
+                "author_sort" => $line["author_sort"],
+                "series_name" => $line["series_name"] ?? "",
+                "series_index" => $line["series_index"] ?? 0,
+                "series_link" => $series_link,
+                "series_full" => $series_full,
+                "cover_link" => $cover_link,
+                "read_link" => $read_link,
+                "in_progress" => $in_progress,
+                "is_read" => $is_read,
+                "is_fav" => $is_fav,
+                "epub_id" => $line["epub_id"] ?? 0,
+                "download_formats" => $download_formats,
+            ];
+        }
+
+        // count total for pagination
+        $count_sth = $caldb->prepare("SELECT COUNT(*) 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
+                ((:query = '%%') OR
+                    (
+                        LOWER(books.author_sort) LIKE LOWER(:query) OR
+                        LOWER(books.title) LIKE LOWER(:query) OR
+                        LOWER(s.name) LIKE LOWER(:query)
+                    ))
+                AND $ids_qpart");
+        $count_sth->execute([':query' => '%' . $query . '%']);
+        $total = (int) $count_sth->fetchColumn();
+
+        return (new Response())->withBody(json_encode([
+            "books" => $books,
+            "total" => $total,
+            "offset" => $offset,
+            "limit" => $limit,
+        ]));
+    }
 }
diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php
index 9064bbb..8eb8846 100644
--- a/classes/Handler/LoginHandler.php
+++ b/classes/Handler/LoginHandler.php
@@ -11,168 +11,168 @@ use Response;
 
 class LoginHandler implements RequestHandlerInterface
 {
-	/** @return array<string, string>|null */
-	private function doLocalLogin(string $username, string $password): ?array
-	{
-		$pass_hash = 'SHA256:' . hash('sha256', "$username:" . $password);
-
-		$user = ORM::for_table('epube_users')
-			->where('username', $username)
-			->where('pass', $pass_hash)
-			->find_one();
-
-		if (!$user) {
-			return null;
-		}
-
-		if (session_status() != PHP_SESSION_ACTIVE) {
-			session_start();
-		}
-
-		session_regenerate_id(true);
-
-		$_SESSION["owner"] = $username;
-		$_SESSION["pass_hash"] = sha1($user->pass);
-		$_SESSION["csrf_token"] = bin2hex(random_bytes(16));
-
-		setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
-			"/", "", Config::is_server_https());
-
-		return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]];
-	}
-
-	private function doOidcLogin(): void
-	{
-		$oidc = new OpenIDConnectClient(
-			Config::get(Config::OIDC_URL),
-			Config::get(Config::OIDC_CLIENT_ID),
-			Config::get(Config::OIDC_CLIENT_SECRET)
-		);
-
-		$oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback");
-		$oidc->addScope(['openid', 'profile', 'email']);
-		$oidc->authenticate();
-	}
-
-	/** @return array<string, string> */
-	private function handleOidcCallback(): array
-	{
-		$oidc = new OpenIDConnectClient(
-			Config::get(Config::OIDC_URL),
-			Config::get(Config::OIDC_CLIENT_ID),
-			Config::get(Config::OIDC_CLIENT_SECRET)
-		);
-
-		$oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback");
-		$oidc->addScope(['openid', 'profile', 'email']);
-
-		try {
-			$oidc->authenticate();
-
-			$username = trim(mb_strtolower($oidc->requestUserInfo("preferred_username")));
-
-			if (!$username) {
-				return ["error" => "No username received from OIDC provider."];
-			}
-
-			$user = ORM::for_table('epube_users')
-				->where('username', $username)
-				->find_one();
-
-			if (!$user) {
-				return ["error" => "User not found: $username"];
-			}
-
-			if (session_status() != PHP_SESSION_ACTIVE) {
-				session_start();
-			}
-
-			session_regenerate_id(true);
-
-			$_SESSION["access_token"] = $oidc->getAccessToken();
-			$_SESSION["access_token_last_check"] = time();
-			$_SESSION["owner"] = $username;
-			$_SESSION["pass_hash"] = sha1($user->pass);
-			$_SESSION["csrf_token"] = bin2hex(random_bytes(16));
-
-			setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
-				"/", "", Config::is_server_https());
-
-			return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]];
-
-		} catch (\Exception $e) {
-			return ["error" => "OIDC Error: " . $e->getMessage()];
-		}
-	}
-
-	public function handle(Request $request): Response
-	{
-		$op = $request->getAttribute('op', '');
-
-		// Redirect to OIDC provider
-		if ($op === "perform-oidc-login") {
-			if (empty(Config::get(Config::OIDC_URL))) {
-				return (new Response())
-					->withStatus(400)
-					->withBody(json_encode(["error" => "OIDC is not configured."]));
-			}
-
-			$this->doOidcLogin();
-
-			// unreachable - authenticate() redirects
-			return new Response();
-		}
-
-		// OIDC callback
-		if ($op === "oidc-login-callback") {
-			if (empty(Config::get(Config::OIDC_URL))) {
-				return (new Response())
-					->withStatus(400)
-					->withBody(json_encode(["error" => "OIDC is not configured."]));
-			}
-
-			$result = $this->handleOidcCallback();
-
-			if (isset($result["error"])) {
-				// Logout any partial session state
-				if (function_exists('logout_user')) {
-					logout_user();
-				}
-				return (new Response())
-					->withStatus(401)
-					->withBody(json_encode($result));
-			}
-
-			return (new Response())
-				->withHeader("Location", Config::get_self_url() . "/index.php")
-				->withBody(json_encode($result));
-		}
-
-		// Local username/password login
-		if ($op === "perform-login") {
-			$username = trim(mb_strtolower($request->getAttribute('user', '')));
-			$password = $request->getAttribute('password', '');
-
-			if (!$username || !$password) {
-				return (new Response())
-					->withStatus(400)
-					->withBody(json_encode(["error" => "Username and password are required."]));
-			}
-
-			$result = $this->doLocalLogin($username, $password);
-
-			if (!$result) {
-				return (new Response())
-					->withStatus(401)
-					->withBody(json_encode(["error" => "Incorrect username or password."]));
-			}
-
-			return (new Response())
-				->withBody(json_encode($result));
-		}
-
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "Not found."]));
-	}
+    /** @return array<string, string>|null */
+    private function doLocalLogin(string $username, string $password): ?array
+    {
+        $pass_hash = 'SHA256:' . hash('sha256', "$username:" . $password);
+
+        $user = ORM::for_table('epube_users')
+            ->where('username', $username)
+            ->where('pass', $pass_hash)
+            ->find_one();
+
+        if (!$user) {
+            return null;
+        }
+
+        if (session_status() != PHP_SESSION_ACTIVE) {
+            session_start();
+        }
+
+        session_regenerate_id(true);
+
+        $_SESSION["owner"] = $username;
+        $_SESSION["pass_hash"] = sha1($user->pass);
+        $_SESSION["csrf_token"] = bin2hex(random_bytes(16));
+
+        setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
+            "/", "", Config::is_server_https());
+
+        return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]];
+    }
+
+    private function doOidcLogin(): void
+    {
+        $oidc = new OpenIDConnectClient(
+            Config::get(Config::OIDC_URL),
+            Config::get(Config::OIDC_CLIENT_ID),
+            Config::get(Config::OIDC_CLIENT_SECRET)
+        );
+
+        $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback");
+        $oidc->addScope(['openid', 'profile', 'email']);
+        $oidc->authenticate();
+    }
+
+    /** @return array<string, string> */
+    private function handleOidcCallback(): array
+    {
+        $oidc = new OpenIDConnectClient(
+            Config::get(Config::OIDC_URL),
+            Config::get(Config::OIDC_CLIENT_ID),
+            Config::get(Config::OIDC_CLIENT_SECRET)
+        );
+
+        $oidc->setRedirectURL(Config::get_self_url() . "/backend.php?op=oidc-login-callback");
+        $oidc->addScope(['openid', 'profile', 'email']);
+
+        try {
+            $oidc->authenticate();
+
+            $username = trim(mb_strtolower($oidc->requestUserInfo("preferred_username")));
+
+            if (!$username) {
+                return ["error" => "No username received from OIDC provider."];
+            }
+
+            $user = ORM::for_table('epube_users')
+                ->where('username', $username)
+                ->find_one();
+
+            if (!$user) {
+                return ["error" => "User not found: $username"];
+            }
+
+            if (session_status() != PHP_SESSION_ACTIVE) {
+                session_start();
+            }
+
+            session_regenerate_id(true);
+
+            $_SESSION["access_token"] = $oidc->getAccessToken();
+            $_SESSION["access_token_last_check"] = time();
+            $_SESSION["owner"] = $username;
+            $_SESSION["pass_hash"] = sha1($user->pass);
+            $_SESSION["csrf_token"] = bin2hex(random_bytes(16));
+
+            setcookie("epube_csrf_token", $_SESSION["csrf_token"], time() + Config::get(Config::SESSION_LIFETIME),
+                "/", "", Config::is_server_https());
+
+            return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]];
+
+        } catch (\Exception $e) {
+            return ["error" => "OIDC Error: " . $e->getMessage()];
+        }
+    }
+
+    public function handle(Request $request): Response
+    {
+        $op = $request->getAttribute('op', '');
+
+        // Redirect to OIDC provider
+        if ($op === "perform-oidc-login") {
+            if (empty(Config::get(Config::OIDC_URL))) {
+                return (new Response())
+                    ->withStatus(400)
+                    ->withBody(json_encode(["error" => "OIDC is not configured."]));
+            }
+
+            $this->doOidcLogin();
+
+            // unreachable - authenticate() redirects
+            return new Response();
+        }
+
+        // OIDC callback
+        if ($op === "oidc-login-callback") {
+            if (empty(Config::get(Config::OIDC_URL))) {
+                return (new Response())
+                    ->withStatus(400)
+                    ->withBody(json_encode(["error" => "OIDC is not configured."]));
+            }
+
+            $result = $this->handleOidcCallback();
+
+            if (isset($result["error"])) {
+                // Logout any partial session state
+                if (function_exists('logout_user')) {
+                    logout_user();
+                }
+                return (new Response())
+                    ->withStatus(401)
+                    ->withBody(json_encode($result));
+            }
+
+            return (new Response())
+                ->withHeader("Location", Config::get_self_url() . "/index.php")
+                ->withBody(json_encode($result));
+        }
+
+        // Local username/password login
+        if ($op === "perform-login") {
+            $username = trim(mb_strtolower($request->getAttribute('user', '')));
+            $password = $request->getAttribute('password', '');
+
+            if (!$username || !$password) {
+                return (new Response())
+                    ->withStatus(400)
+                    ->withBody(json_encode(["error" => "Username and password are required."]));
+            }
+
+            $result = $this->doLocalLogin($username, $password);
+
+            if (!$result) {
+                return (new Response())
+                    ->withStatus(401)
+                    ->withBody(json_encode(["error" => "Incorrect username or password."]));
+            }
+
+            return (new Response())
+                ->withBody(json_encode($result));
+        }
+
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "Not found."]));
+    }
 }
diff --git a/classes/Handler/LogoutHandler.php b/classes/Handler/LogoutHandler.php
index ac07c31..2ed8b75 100644
--- a/classes/Handler/LogoutHandler.php
+++ b/classes/Handler/LogoutHandler.php
@@ -10,9 +10,9 @@ use Response;
 
 class LogoutHandler implements RequestHandlerInterface, AuthRequired
 {
-	public function handle(Request $request): Response
-	{
-		logout_user();
-		return (new Response())->withBody(json_encode(["result" => "ok"]));
-	}
+    public function handle(Request $request): Response
+    {
+        logout_user();
+        return (new Response())->withBody(json_encode(["result" => "ok"]));
+    }
 }
diff --git a/classes/Handler/PaginationHandler.php b/classes/Handler/PaginationHandler.php
index 54421d5..a027c58 100644
--- a/classes/Handler/PaginationHandler.php
+++ b/classes/Handler/PaginationHandler.php
@@ -10,71 +10,71 @@ use Response;
 
 class PaginationHandler implements RequestHandlerInterface, AuthRequired
 {
-	private function handleGet(int $bookid): Response
-	{
-		if ($bookid) {
-			$pag = ORM::for_table('epube_pagination')
-				->where('bookid', $bookid)
-				->find_one();
+    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);
-			}
-		}
+            if ($pag) {
+                return (new Response())->withBody($pag->pagination);
+            }
+        }
 
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "File not found."]));
-	}
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "File not found."]));
+    }
 
-	private function handleStore(int $bookid, ?string $payload): Response
-	{
-		if ($bookid && $payload) {
-			$pag = ORM::for_table('epube_pagination')
-				->where('bookid', $bookid)
-				->find_one();
+    private function handleStore(int $bookid, ?string $payload): Response
+    {
+        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;
-			}
+            if (!$pag) {
+                $pag = ORM::for_table('epube_pagination')->create();
+                $pag->bookid = $bookid;
+            }
 
-			$pag->pagination = $payload;
-			$pag->total_pages = 100;
-			$pag->save();
-		}
+            $pag->pagination = $payload;
+            $pag->total_pages = 100;
+            $pag->save();
+        }
 
-		return new Response();
-	}
+        return new Response();
+    }
 
-	private function handleDelete(int $bookid): Response
-	{
-		if ($bookid) {
-			$pag = ORM::for_table('epube_pagination')
-				->where('bookid', $bookid)
-				->find_one();
+    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();
-			}
-		}
+            if ($pag) {
+                $pag->delete();
+                return new Response();
+            }
+        }
 
-		return (new Response())
-			->withStatus(404)
-			->withBody(json_encode(["error" => "Not found."]));
-	}
+        return (new Response())
+            ->withStatus(404)
+            ->withBody(json_encode(["error" => "Not found."]));
+    }
 
-	public function handle(Request $request): Response
-	{
-		$subOp = $request->getAttribute('op', '');
-		$bookid = (int) $request->getAttribute('id');
+    public function handle(Request $request): Response
+    {
+        $subOp = $request->getAttribute('op', '');
+        $bookid = (int) $request->getAttribute('id');
 
-		return match ($subOp) {
-			'getpagination'   => $this->handleGet($bookid),
-			'storepagination' => $this->handleStore($bookid, $request->getAttribute('payload')),
-			'deletepagination' => $this->handleDelete($bookid),
-			default           => (new Response())->withStatus(404)->withBody(json_encode(["error" => "Not found."])),
-		};
-	}
+        return match ($subOp) {
+            'getpagination'   => $this->handleGet($bookid),
+            'storepagination' => $this->handleStore($bookid, $request->getAttribute('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 543b7a4..3b203ad 100644
--- a/classes/Handler/TogglefavHandler.php
+++ b/classes/Handler/TogglefavHandler.php
@@ -10,27 +10,27 @@ use Response;
 
 class TogglefavHandler implements RequestHandlerInterface, AuthRequired
 {
-	public function handle(Request $request): Response
-	{
-		$bookid = (int) $request->getAttribute('id');
-		$owner = $_SESSION["owner"] ?? "";
+    public function handle(Request $request): Response
+    {
+        $bookid = (int) $request->getAttribute('id');
+        $owner = $_SESSION["owner"] ?? "";
 
-		$fav = ORM::for_table('epube_favorites')
-			->where('bookid', $bookid)
-			->where('owner', $owner)
-			->find_one();
+        $fav = ORM::for_table('epube_favorites')
+            ->where('bookid', $bookid)
+            ->where('owner', $owner)
+            ->find_one();
 
-		if ($fav) {
-			$fav->delete();
-			$status = 0;
-		} else {
-			$fav = ORM::for_table('epube_favorites')->create();
-			$fav->bookid = $bookid;
-			$fav->owner = $owner;
-			$fav->save();
-			$status = 1;
-		}
+        if ($fav) {
+            $fav->delete();
+            $status = 0;
+        } else {
+            $fav = ORM::for_table('epube_favorites')->create();
+            $fav->bookid = $bookid;
+            $fav->owner = $owner;
+            $fav->save();
+            $status = 1;
+        }
 
-		return (new Response())->withBody(json_encode(["id" => $bookid, "status" => $status]));
-	}
+        return (new Response())->withBody(json_encode(["id" => $bookid, "status" => $status]));
+    }
 }
diff --git a/classes/MiddlewareInterface.php b/classes/MiddlewareInterface.php
index ac43ef2..ae1949e 100644
--- a/classes/MiddlewareInterface.php
+++ b/classes/MiddlewareInterface.php
@@ -2,5 +2,5 @@
 
 interface MiddlewareInterface
 {
-	public function process(Request $request, callable $next): Response;
+    public function process(Request $request, callable $next): Response;
 }
diff --git a/classes/Request.php b/classes/Request.php
index d337740..b3d2b62 100644
--- a/classes/Request.php
+++ b/classes/Request.php
@@ -2,56 +2,56 @@
 
 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 function __construct()
-	{
-		$this->serverParams = $_SERVER;
-		$this->queryParams  = $_GET;
-		$this->bodyParams   = $_POST;
-		$this->cookies      = $_COOKIE;
-	}
-
-	/** @return array<string, mixed> */
-	public function getServerParams(): array
-	{
-		return $this->serverParams;
-	}
-
-	/** @return array<string, mixed> */
-	public function getQueryParams(): array
-	{
-		return $this->queryParams;
-	}
-
-	/** @return array<string, mixed> */
-	public function getParsedBody(): array
-	{
-		return array_merge($this->queryParams, $this->bodyParams);
-	}
-
-	/** @return array<string, mixed> */
-	public function getCookieParams(): array
-	{
-		return $this->cookies;
-	}
-
-	public function getAttribute(string $name, mixed $default = null): mixed
-	{
-		return $this->getParsedBody()[$name] ?? $default;
-	}
-
-	public function withAttribute(string $name, mixed $value): self
-	{
-		$clone = clone $this;
-		$clone->bodyParams[$name] = $value;
-		return $clone;
-	}
+    /** @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 function __construct()
+    {
+        $this->serverParams = $_SERVER;
+        $this->queryParams  = $_GET;
+        $this->bodyParams   = $_POST;
+        $this->cookies      = $_COOKIE;
+    }
+
+    /** @return array<string, mixed> */
+    public function getServerParams(): array
+    {
+        return $this->serverParams;
+    }
+
+    /** @return array<string, mixed> */
+    public function getQueryParams(): array
+    {
+        return $this->queryParams;
+    }
+
+    /** @return array<string, mixed> */
+    public function getParsedBody(): array
+    {
+        return array_merge($this->queryParams, $this->bodyParams);
+    }
+
+    /** @return array<string, mixed> */
+    public function getCookieParams(): array
+    {
+        return $this->cookies;
+    }
+
+    public function getAttribute(string $name, mixed $default = null): mixed
+    {
+        return $this->getParsedBody()[$name] ?? $default;
+    }
+
+    public function withAttribute(string $name, mixed $value): self
+    {
+        $clone = clone $this;
+        $clone->bodyParams[$name] = $value;
+        return $clone;
+    }
 }
diff --git a/classes/RequestHandlerInterface.php b/classes/RequestHandlerInterface.php
index 364ed3a..fefe816 100644
--- a/classes/RequestHandlerInterface.php
+++ b/classes/RequestHandlerInterface.php
@@ -2,5 +2,5 @@
 
 interface RequestHandlerInterface
 {
-	public function handle(Request $request): Response;
+    public function handle(Request $request): Response;
 }
diff --git a/classes/Response.php b/classes/Response.php
index 8d32496..ea5e93d 100644
--- a/classes/Response.php
+++ b/classes/Response.php
@@ -2,55 +2,55 @@
 
 class Response
 {
-	private int $status = 200;
-	/** @var array<string, string> */
-	private array $headers = [];
-	private string $body = '';
-	private string $contentType = "text/json";
-
-	public function withStatus(int $code, string $reasonPhrase = ''): self
-	{
-		$clone = clone $this;
-		$clone->status = $code;
-		return $clone;
-	}
-
-	public function withHeader(string $name, string $value): self
-	{
-		$clone = clone $this;
-		$clone->headers[$name] = $value;
-		return $clone;
-	}
-
-	public function getBody(): string
-	{
-		return $this->body;
-	}
-
-	public function withBody(string $body): self
-	{
-		$clone = clone $this;
-		$clone->body = $body;
-		return $clone;
-	}
-
-	public function send(): void
-	{
-		$contentTypeFound = false;
-
-		if ($this->headers) {
-			foreach ($this->headers as $name => $value) {
-				header("$name: $value");
-
-				if (strtolower($name) === "content-type")
-					$contentTypeFound = true;
-			}
-		}
-
-		if (!$contentTypeFound)
-			header("Content-type: {$this->contentType}");
-
-		http_response_code($this->status);
-		echo $this->body;
-	}
+    private int $status = 200;
+    /** @var array<string, string> */
+    private array $headers = [];
+    private string $body = '';
+    private string $contentType = "text/json";
+
+    public function withStatus(int $code, string $reasonPhrase = ''): self
+    {
+        $clone = clone $this;
+        $clone->status = $code;
+        return $clone;
+    }
+
+    public function withHeader(string $name, string $value): self
+    {
+        $clone = clone $this;
+        $clone->headers[$name] = $value;
+        return $clone;
+    }
+
+    public function getBody(): string
+    {
+        return $this->body;
+    }
+
+    public function withBody(string $body): self
+    {
+        $clone = clone $this;
+        $clone->body = $body;
+        return $clone;
+    }
+
+    public function send(): void
+    {
+        $contentTypeFound = false;
+
+        if ($this->headers) {
+            foreach ($this->headers as $name => $value) {
+                header("$name: $value");
+
+                if (strtolower($name) === "content-type")
+                    $contentTypeFound = true;
+            }
+        }
+
+        if (!$contentTypeFound)
+            header("Content-type: {$this->contentType}");
+
+        http_response_code($this->status);
+        echo $this->body;
+    }
 }
diff --git a/classes/Router.php b/classes/Router.php
index d5d4349..34e0bde 100644
--- a/classes/Router.php
+++ b/classes/Router.php
@@ -2,66 +2,66 @@
 
 class Router
 {
-	/** @var array<string, RequestHandlerInterface> */
-	private array $routes = [];
+    /** @var array<string, RequestHandlerInterface> */
+    private array $routes = [];
 
-	/** @var MiddlewareInterface[] */
-	private array $middleware = [];
+    /** @var MiddlewareInterface[] */
+    private array $middleware = [];
 
-	public function addRoute(string $op, RequestHandlerInterface $handler): void
-	{
-		$this->routes[$op] = $handler;
-	}
+    public function addRoute(string $op, RequestHandlerInterface $handler): void
+    {
+        $this->routes[$op] = $handler;
+    }
 
-	public function addMiddleware(MiddlewareInterface $middleware): void
-	{
-		$this->middleware[] = $middleware;
-	}
+    public function addMiddleware(MiddlewareInterface $middleware): void
+    {
+        $this->middleware[] = $middleware;
+    }
 
-	/**
-	 * Dispatch an operation and send the response.
-	 * Calls exit after sending the response.
-	 */
-	public function dispatch(string $op): void
-	{
-		$response = $this->dispatchResponse($op);
-		$response->send();
-		exit;
-	}
+    /**
+     * Dispatch an operation and send the response.
+     * Calls exit after sending the response.
+     */
+    public function dispatch(string $op): void
+    {
+        $response = $this->dispatchResponse($op);
+        $response->send();
+        exit;
+    }
 
-	/**
-	 * Get the Response for a dispatch without sending it.
-	 * Used for testing and for cases where the caller
-	 * wants to modify the response before sending.
-	 */
-	public function dispatchResponse(string $op): Response
-	{
-		$handler = $this->routes[$op] ?? null;
+    /**
+     * Get the Response for a dispatch without sending it.
+     * Used for testing and for cases where the caller
+     * wants to modify the response before sending.
+     */
+    public function dispatchResponse(string $op): Response
+    {
+        $handler = $this->routes[$op] ?? null;
 
-		if (!$handler) {
-			return (new Response())
-				->withStatus(404)
-				->withBody(json_encode(["error" => "Method not found"]));
-		}
+        if (!$handler) {
+            return (new Response())
+                ->withStatus(404)
+                ->withBody(json_encode(["error" => "Method not found"]));
+        }
 
-		// Check auth for handlers that require it
-		if ($handler instanceof AuthRequired && empty($_SESSION["owner"])) {
-			return (new Response())
-				->withStatus(401)
-				->withBody(json_encode(["error" => "Unauthorized"]));
-		}
+        // Check auth for handlers that require it
+        if ($handler instanceof AuthRequired && empty($_SESSION["owner"])) {
+            return (new Response())
+                ->withStatus(401)
+                ->withBody(json_encode(["error" => "Unauthorized"]));
+        }
 
-		$pipe = $handler->handle(...);
+        $pipe = $handler->handle(...);
 
-		// wrap middleware in reverse order (last added = outermost)
-		foreach (array_reverse($this->middleware) as $mw) {
-			$previous = $pipe;
-			$pipe = fn(Request $r) => $mw->process($r, $previous);
-		}
+        // wrap middleware in reverse order (last added = outermost)
+        foreach (array_reverse($this->middleware) as $mw) {
+            $previous = $pipe;
+            $pipe = fn(Request $r) => $mw->process($r, $previous);
+        }
 
-		$request = new Request();
-		$request = $request->withAttribute('op', $op);
+        $request = new Request();
+        $request = $request->withAttribute('op', $op);
 
-		return $pipe($request);
-	}
+        return $pipe($request);
+    }
 }
diff --git a/classes/Sanitizer.php b/classes/Sanitizer.php
index 9d2f5a3..47e9d1f 100644
--- a/classes/Sanitizer.php
+++ b/classes/Sanitizer.php
@@ -1,263 +1,263 @@
 <?php
 class Sanitizer {
 
-	public static function rewrite_relative(string $url, string $rel_url) : string {
-
-		$rel_parts = parse_url($rel_url);
-
-		if (!empty($rel_parts['host']) && !empty($rel_parts['scheme'])) {
-			return self::validate($rel_url);
-		} else if (strpos($rel_url, "//") === 0) {
-			# protocol-relative URL (rare but they exist)
-			return self::validate("https:" . $rel_url);
-		} else if (strpos($rel_url, "magnet:") === 0) {
-			# allow magnet links
-			return $rel_url;
-		} else {
-			$parts = parse_url($url);
-
-			$rel_parts['host'] = $parts['host'];
-			$rel_parts['scheme'] = $parts['scheme'];
-
-			if (isset($rel_parts['path'])) {
-				if (strpos($rel_parts['path'], '/') !== 0)
-					$rel_parts['path'] = '/' . $rel_parts['path'];
-
-				$rel_parts['path'] = str_replace("/./", "/", $rel_parts['path']);
-				$rel_parts['path'] = str_replace("//", "/", $rel_parts['path']);
-			}
-
-			return self::validate(self::build_url($rel_parts));
-		}
-	}
-
-	public static function sanitize(string $str) : string {
-
-		$res = trim($str); if (!$res) return '';
-
-		$doc = new DOMDocument();
-		$doc->loadHTML('<?xml encoding="UTF-8">' . $res);
-		$xpath = new DOMXPath($doc);
-
-		// is it a good idea to possibly rewrite urls to our own prefix?
-		// $rewrite_base_url = $site_url ? $site_url : Config::get_self_url();
-		$rewrite_base_url = "http://domain.invalid/";
-
-		$entries = $xpath->query('(//a[@href]|//img[@src]|//source[@srcset|@src])');
-
-		foreach ($entries as $entry) {
-		/** @var DOMElement $entry */
-
-			if ($entry->hasAttribute('href')) {
-				$entry->setAttribute('href',
-					self::rewrite_relative($rewrite_base_url, $entry->getAttribute('href')));
-
-				$entry->setAttribute('rel', 'noopener noreferrer');
-				$entry->setAttribute("target", "_blank");
-			}
-
-			if ($entry->hasAttribute('src')) {
-				$entry->setAttribute('src',
-					self::rewrite_relative($rewrite_base_url, $entry->getAttribute('src')));
-			}
-
-			if ($entry->nodeName == 'img') {
-				$entry->setAttribute('referrerpolicy', 'no-referrer');
-				$entry->setAttribute('loading', 'lazy');
-			}
-
-			if ($entry->hasAttribute('srcset')) {
-				$entry->removeAttribute('srcset');
-			}
-		}
-
-		$allowed_elements = array('a', 'abbr', 'address', 'acronym', 'audio', 'article', 'aside',
-			'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
-			'caption', 'cite', 'center', 'code', 'col', 'colgroup',
-			'data', 'dd', 'del', 'details', 'description', 'dfn', 'div', 'dl', 'font',
-			'dt', 'em', 'footer', 'figure', 'figcaption',
-			'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'html', 'i',
-			'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
-			'ol', 'p', 'picture', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
-			'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
-			'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
-			'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video', 'xml:namespace' );
-
-		$disallowed_attributes = array('id', 'style', 'class', 'width', 'height', 'allow');
-
-		$doc->removeChild($doc->firstChild); //remove doctype
-		$doc = self::strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
-
-		$res = $doc->saveHTML();
-
-		/* strip everything outside of <body>...</body> */
-
-		$res_frag = array();
-		if (preg_match('/<body>(.*)<\/body>/is', $res, $res_frag)) {
-			return $res_frag[1];
-		} else {
-			return $res;
-		}
-	}
-
-	/**
-	 * 	@param array<string> $allowed_elements
-	 * 	@param array<string> $disallowed_attributes
-	 * */
-	private static function strip_harmful_tags(DOMDocument $doc, array $allowed_elements, array $disallowed_attributes) : DOMDocument {
-		$xpath = new DOMXPath($doc);
-		$entries = $xpath->query('//*');
-
-		foreach ($entries as $entry) {
-		/** @var DOMElement $entry */
-			if (!in_array($entry->nodeName, $allowed_elements)) {
-				$entry->parentNode->removeChild($entry);
-				continue;
-			}
-
-
-			if ($entry->hasAttributes()) {
-				$attrs_to_remove = array();
-
-				foreach ($entry->attributes as $attr) {
-
-					if (strpos($attr->nodeName, 'on') === 0) {
-						array_push($attrs_to_remove, $attr);
-					}
-
-					if (strpos($attr->nodeName, "data-") === 0) {
-						array_push($attrs_to_remove, $attr);
-					}
-
-					if ($attr->nodeName == 'href' && stripos($attr->value, 'javascript:') === 0) {
-						array_push($attrs_to_remove, $attr);
-					}
-
-					if (in_array($attr->nodeName, $disallowed_attributes)) {
-						array_push($attrs_to_remove, $attr);
-					}
-				}
-
-				foreach ($attrs_to_remove as $attr) {
-					$entry->removeAttributeNode($attr);
-				}
-			}
-		}
-
-		return $doc;
-	}
-
-	// extended filtering involves validation for safe ports and loopback
-	/** @return string|bool */
-	static function validate(string $url, bool $extended_filtering = false) : mixed {
-
-		$url = trim($url);
-
-		# fix protocol-relative URLs
-		if (strpos($url, "//") === 0)
-			$url = "https:" . $url;
-
-		$tokens = parse_url($url);
-
-		// this isn't really necessary because filter_var(... FILTER_VALIDATE_URL) requires host and scheme
-		// as per https://php.watch/versions/7.3/filter-var-flag-deprecation but it might save time
-		if (empty($tokens['host']))
-			return false;
-
-		if (!in_array(strtolower($tokens['scheme']), ['http', 'https']))
-			return false;
-
-		//convert IDNA hostname to punycode if possible
-		if (function_exists("idn_to_ascii")) {
-			if (mb_detect_encoding($tokens['host']) != 'ASCII') {
-				if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) {
-					$tokens['host'] = idn_to_ascii($tokens['host'], IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
-				} else {
-					$tokens['host'] = idn_to_ascii($tokens['host']);
-				}
-			}
-		}
-
-		// separate set of tokens with urlencoded 'path' because filter_var() rightfully fails on non-latin characters
-		// (used for validation only, we actually request the original URL, in case of urlencode breaking it)
-		$tokens_filter_var = $tokens;
-
-		if ($tokens['path'] ?? false) {
-			$tokens_filter_var['path'] = implode("/",
-										array_map("rawurlencode",
-											array_map("rawurldecode",
-												explode("/", $tokens['path']))));
-		}
-
-		$url = self::build_url($tokens);
-		$url_filter_var = self::build_url($tokens_filter_var);
-
-		if (filter_var($url_filter_var, FILTER_VALIDATE_URL) === false)
-			return false;
-
-		if ($extended_filtering) {
-			if (!in_array($tokens['port'] ?? '', [80, 443, '']))
-				return false;
-
-			if (strtolower($tokens['host']) == 'localhost' || $tokens['host'] == '::1' || strpos($tokens['host'], '127.') === 0)
-				return false;
-		}
-
-		return $url;
-	}
-
-	/** @param array<string, int|string|false> $parts */
-	static function build_url(array $parts) : string {
-		$tmp = $parts['scheme'] . "://" . $parts['host'];
-
-		if (isset($parts['path'])) $tmp .= $parts['path'];
-		if (isset($parts['query'])) $tmp .= '?' . $parts['query'];
-		if (isset($parts['fragment'])) $tmp .= '#' . $parts['fragment'];
+    public static function rewrite_relative(string $url, string $rel_url) : string {
+
+        $rel_parts = parse_url($rel_url);
+
+        if (!empty($rel_parts['host']) && !empty($rel_parts['scheme'])) {
+            return self::validate($rel_url);
+        } else if (strpos($rel_url, "//") === 0) {
+            # protocol-relative URL (rare but they exist)
+            return self::validate("https:" . $rel_url);
+        } else if (strpos($rel_url, "magnet:") === 0) {
+            # allow magnet links
+            return $rel_url;
+        } else {
+            $parts = parse_url($url);
+
+            $rel_parts['host'] = $parts['host'];
+            $rel_parts['scheme'] = $parts['scheme'];
+
+            if (isset($rel_parts['path'])) {
+                if (strpos($rel_parts['path'], '/') !== 0)
+                    $rel_parts['path'] = '/' . $rel_parts['path'];
+
+                $rel_parts['path'] = str_replace("/./", "/", $rel_parts['path']);
+                $rel_parts['path'] = str_replace("//", "/", $rel_parts['path']);
+            }
+
+            return self::validate(self::build_url($rel_parts));
+        }
+    }
+
+    public static function sanitize(string $str) : string {
+
+        $res = trim($str); if (!$res) return '';
+
+        $doc = new DOMDocument();
+        $doc->loadHTML('<?xml encoding="UTF-8">' . $res);
+        $xpath = new DOMXPath($doc);
+
+        // is it a good idea to possibly rewrite urls to our own prefix?
+        // $rewrite_base_url = $site_url ? $site_url : Config::get_self_url();
+        $rewrite_base_url = "http://domain.invalid/";
+
+        $entries = $xpath->query('(//a[@href]|//img[@src]|//source[@srcset|@src])');
+
+        foreach ($entries as $entry) {
+        /** @var DOMElement $entry */
+
+            if ($entry->hasAttribute('href')) {
+                $entry->setAttribute('href',
+                    self::rewrite_relative($rewrite_base_url, $entry->getAttribute('href')));
+
+                $entry->setAttribute('rel', 'noopener noreferrer');
+                $entry->setAttribute("target", "_blank");
+            }
+
+            if ($entry->hasAttribute('src')) {
+                $entry->setAttribute('src',
+                    self::rewrite_relative($rewrite_base_url, $entry->getAttribute('src')));
+            }
+
+            if ($entry->nodeName == 'img') {
+                $entry->setAttribute('referrerpolicy', 'no-referrer');
+                $entry->setAttribute('loading', 'lazy');
+            }
+
+            if ($entry->hasAttribute('srcset')) {
+                $entry->removeAttribute('srcset');
+            }
+        }
+
+        $allowed_elements = array('a', 'abbr', 'address', 'acronym', 'audio', 'article', 'aside',
+            'b', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br',
+            'caption', 'cite', 'center', 'code', 'col', 'colgroup',
+            'data', 'dd', 'del', 'details', 'description', 'dfn', 'div', 'dl', 'font',
+            'dt', 'em', 'footer', 'figure', 'figcaption',
+            'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'html', 'i',
+            'img', 'ins', 'kbd', 'li', 'main', 'mark', 'nav', 'noscript',
+            'ol', 'p', 'picture', 'pre', 'q', 'ruby', 'rp', 'rt', 's', 'samp', 'section',
+            'small', 'source', 'span', 'strike', 'strong', 'sub', 'summary',
+            'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
+            'tr', 'track', 'tt', 'u', 'ul', 'var', 'wbr', 'video', 'xml:namespace' );
+
+        $disallowed_attributes = array('id', 'style', 'class', 'width', 'height', 'allow');
+
+        $doc->removeChild($doc->firstChild); //remove doctype
+        $doc = self::strip_harmful_tags($doc, $allowed_elements, $disallowed_attributes);
+
+        $res = $doc->saveHTML();
+
+        /* strip everything outside of <body>...</body> */
+
+        $res_frag = array();
+        if (preg_match('/<body>(.*)<\/body>/is', $res, $res_frag)) {
+            return $res_frag[1];
+        } else {
+            return $res;
+        }
+    }
+
+    /**
+     *     @param array<string> $allowed_elements
+     *     @param array<string> $disallowed_attributes
+     * */
+    private static function strip_harmful_tags(DOMDocument $doc, array $allowed_elements, array $disallowed_attributes) : DOMDocument {
+        $xpath = new DOMXPath($doc);
+        $entries = $xpath->query('//*');
+
+        foreach ($entries as $entry) {
+        /** @var DOMElement $entry */
+            if (!in_array($entry->nodeName, $allowed_elements)) {
+                $entry->parentNode->removeChild($entry);
+                continue;
+            }
+
+
+            if ($entry->hasAttributes()) {
+                $attrs_to_remove = array();
+
+                foreach ($entry->attributes as $attr) {
+
+                    if (strpos($attr->nodeName, 'on') === 0) {
+                        array_push($attrs_to_remove, $attr);
+                    }
+
+                    if (strpos($attr->nodeName, "data-") === 0) {
+                        array_push($attrs_to_remove, $attr);
+                    }
+
+                    if ($attr->nodeName == 'href' && stripos($attr->value, 'javascript:') === 0) {
+                        array_push($attrs_to_remove, $attr);
+                    }
+
+                    if (in_array($attr->nodeName, $disallowed_attributes)) {
+                        array_push($attrs_to_remove, $attr);
+                    }
+                }
+
+                foreach ($attrs_to_remove as $attr) {
+                    $entry->removeAttributeNode($attr);
+                }
+            }
+        }
+
+        return $doc;
+    }
+
+    // extended filtering involves validation for safe ports and loopback
+    /** @return string|bool */
+    static function validate(string $url, bool $extended_filtering = false) : mixed {
+
+        $url = trim($url);
+
+        # fix protocol-relative URLs
+        if (strpos($url, "//") === 0)
+            $url = "https:" . $url;
+
+        $tokens = parse_url($url);
+
+        // this isn't really necessary because filter_var(... FILTER_VALIDATE_URL) requires host and scheme
+        // as per https://php.watch/versions/7.3/filter-var-flag-deprecation but it might save time
+        if (empty($tokens['host']))
+            return false;
+
+        if (!in_array(strtolower($tokens['scheme']), ['http', 'https']))
+            return false;
+
+        //convert IDNA hostname to punycode if possible
+        if (function_exists("idn_to_ascii")) {
+            if (mb_detect_encoding($tokens['host']) != 'ASCII') {
+                if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) {
+                    $tokens['host'] = idn_to_ascii($tokens['host'], IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
+                } else {
+                    $tokens['host'] = idn_to_ascii($tokens['host']);
+                }
+            }
+        }
+
+        // separate set of tokens with urlencoded 'path' because filter_var() rightfully fails on non-latin characters
+        // (used for validation only, we actually request the original URL, in case of urlencode breaking it)
+        $tokens_filter_var = $tokens;
+
+        if ($tokens['path'] ?? false) {
+            $tokens_filter_var['path'] = implode("/",
+                                        array_map("rawurlencode",
+                                            array_map("rawurldecode",
+                                                explode("/", $tokens['path']))));
+        }
+
+        $url = self::build_url($tokens);
+        $url_filter_var = self::build_url($tokens_filter_var);
+
+        if (filter_var($url_filter_var, FILTER_VALIDATE_URL) === false)
+            return false;
+
+        if ($extended_filtering) {
+            if (!in_array($tokens['port'] ?? '', [80, 443, '']))
+                return false;
+
+            if (strtolower($tokens['host']) == 'localhost' || $tokens['host'] == '::1' || strpos($tokens['host'], '127.') === 0)
+                return false;
+        }
+
+        return $url;
+    }
+
+    /** @param array<string, int|string|false> $parts */
+    static function build_url(array $parts) : string {
+        $tmp = $parts['scheme'] . "://" . $parts['host'];
+
+        if (isset($parts['path'])) $tmp .= $parts['path'];
+        if (isset($parts['query'])) $tmp .= '?' . $parts['query'];
+        if (isset($parts['fragment'])) $tmp .= '#' . $parts['fragment'];
 
-		return $tmp;
-	}
-
-	/** @return string|bool */
-	static function resolve_redirects(string $url, int $timeout, int $nest = 0) : mixed {
-
-		// too many redirects
-		if ($nest > 10)
-			return false;
-
-		if (version_compare(PHP_VERSION, '7.1.0', '>=')) {
-			$context_options = array(
-				'http' => array(
-					'header' => array(
-						'Connection: close'
-					),
-					'method' => 'HEAD',
-					'timeout' => $timeout,
-					'protocol_version'=> 1.1)
-				);
-
-			$context = stream_context_create($context_options);
-
-			$headers = get_headers($url, false, $context);
-		} else {
-			$headers = get_headers($url, false);
-		}
-
-		if (is_array($headers)) {
-			$headers = array_reverse($headers); // last one is the correct one
-
-			foreach($headers as $header) {
-				if (stripos($header, 'Location:') === 0) {
-					$url = self::rewrite_relative($url, trim(substr($header, strlen('Location:'))));
-
-					return self::resolve_redirects($url, $timeout, $nest + 1);
-				}
-			}
-
-			return $url;
-		}
-
-		// request failed?
-		return false;
-	}
+        return $tmp;
+    }
+
+    /** @return string|bool */
+    static function resolve_redirects(string $url, int $timeout, int $nest = 0) : mixed {
+
+        // too many redirects
+        if ($nest > 10)
+            return false;
+
+        if (version_compare(PHP_VERSION, '7.1.0', '>=')) {
+            $context_options = array(
+                'http' => array(
+                    'header' => array(
+                        'Connection: close'
+                    ),
+                    'method' => 'HEAD',
+                    'timeout' => $timeout,
+                    'protocol_version'=> 1.1)
+                );
+
+            $context = stream_context_create($context_options);
+
+            $headers = get_headers($url, false, $context);
+        } else {
+            $headers = get_headers($url, false);
+        }
+
+        if (is_array($headers)) {
+            $headers = array_reverse($headers); // last one is the correct one
+
+            foreach($headers as $header) {
+                if (stripos($header, 'Location:') === 0) {
+                    $url = self::rewrite_relative($url, trim(substr($header, strlen('Location:'))));
+
+                    return self::resolve_redirects($url, $timeout, $nest + 1);
+                }
+            }
+
+            return $url;
+        }
+
+        // request failed?
+        return false;
+    }
 
 }