From 71bb7738fba42ca90cc8349e357087434ff669d4 Mon Sep 17 00:00:00 2001 From: mikespub Date: Thu, 20 Jul 2023 23:25:11 +0200 Subject: [PATCH] pass database to static calls + add request class --- base.php | 277 +++++++++++++------- checkconfig.php | 16 +- config.php | 4 +- epubfs.php | 17 +- epubreader.php | 11 +- feed.php | 21 +- fetch.php | 36 +-- getJSON.php | 5 +- index.php | 38 ++- lib/Calibre/Author.php | 33 +-- lib/Calibre/Base.php | 168 ++++++++++-- lib/Calibre/Book.php | 101 +++---- lib/Calibre/CustomColumn.php | 5 +- lib/Calibre/CustomColumnType.php | 54 ++-- lib/Calibre/CustomColumnTypeBool.php | 10 +- lib/Calibre/CustomColumnTypeComment.php | 6 +- lib/Calibre/CustomColumnTypeDate.php | 10 +- lib/Calibre/CustomColumnTypeEnumeration.php | 12 +- lib/Calibre/CustomColumnTypeFloat.php | 10 +- lib/Calibre/CustomColumnTypeInteger.php | 12 +- lib/Calibre/CustomColumnTypeRating.php | 10 +- lib/Calibre/CustomColumnTypeSeries.php | 12 +- lib/Calibre/CustomColumnTypeText.php | 12 +- lib/Calibre/Data.php | 27 +- lib/Calibre/Language.php | 13 +- lib/Calibre/Publisher.php | 20 +- lib/Calibre/Rating.php | 17 +- lib/Calibre/Serie.php | 20 +- lib/Calibre/Tag.php | 15 +- lib/Model/Entry.php | 13 +- lib/Model/EntryBook.php | 2 +- lib/Model/Link.php | 5 +- lib/Model/LinkFacet.php | 4 +- lib/Model/LinkNavigation.php | 4 +- lib/Output/EPubReader.php | 28 +- lib/Output/JSON_renderer.php | 55 ++-- lib/Output/OPDS_renderer.php | 45 ++-- lib/Output/RestApi.php | 67 +++-- lib/Pages/Page.php | 126 +++++---- lib/Pages/PageAllAuthors.php | 8 +- lib/Pages/PageAllAuthorsLetter.php | 2 +- lib/Pages/PageAllBooks.php | 8 +- lib/Pages/PageAllBooksLetter.php | 2 +- lib/Pages/PageAllCustoms.php | 6 +- lib/Pages/PageAllLanguages.php | 2 +- lib/Pages/PageAllPublishers.php | 2 +- lib/Pages/PageAllRating.php | 2 +- lib/Pages/PageAllSeries.php | 2 +- lib/Pages/PageAllTags.php | 2 +- lib/Pages/PageAuthorDetail.php | 4 +- lib/Pages/PageBookDetail.php | 2 +- lib/Pages/PageCustomDetail.php | 9 +- lib/Pages/PageCustomize.php | 43 +-- lib/Pages/PageLanguageDetail.php | 4 +- lib/Pages/PagePublisherDetail.php | 4 +- lib/Pages/PageQueryResult.php | 52 ++-- lib/Pages/PageRatingDetail.php | 4 +- lib/Pages/PageRecentBooks.php | 2 +- lib/Pages/PageSerieDetail.php | 4 +- lib/Pages/PageTagDetail.php | 4 +- restapi.php | 13 +- test/EpubFsTest.php | 2 +- test/OPDSTest.php | 47 ++-- test/RestApiTest.php | 54 ++-- test/baseTest.php | 29 +- test/bookTest.php | 97 +++---- test/configTest.php | 14 +- test/customColumnsTest.php | 102 ++++--- test/jsonTest.php | 39 +-- test/pageTest.php | 213 ++++++++------- 70 files changed, 1236 insertions(+), 883 deletions(-) diff --git a/base.php b/base.php index 677d183b3..71f266442 100644 --- a/base.php +++ b/base.php @@ -6,13 +6,16 @@ * @author Sébastien Lucas */ -namespace SebLucas\Cops; +namespace SebLucas\Cops\Input; require 'config.php'; /** @var array $config */ date_default_timezone_set($config['default_timezone']); +/** + * Summary of Config + */ class Config { public const VERSION = '1.3.6'; @@ -29,128 +32,200 @@ class Config ]; } -namespace SebLucas\Cops\Request; - -use SebLucas\Cops\Config; - -function useServerSideRendering() +/** + * Summary of Request + */ +class Request { - global $config; - return preg_match('/' . $config['cops_server_side_render'] . '/', $_SERVER['HTTP_USER_AGENT']); -} + /** + * Summary of urlParams + * @var array + */ + public $urlParams = []; -function getQueryString() -{ - if (isset($_SERVER['QUERY_STRING'])) { - return $_SERVER['QUERY_STRING']; + public function __construct() + { + $this->init(); } - return ""; -} -function notFound() -{ - header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); - header('Status: 404 Not Found'); - - $_SERVER['REDIRECT_STATUS'] = 404; -} + /** + * Summary of useServerSideRendering + * @return bool|int + */ + public function render() + { + global $config; + return preg_match('/' . $config['cops_server_side_render'] . '/', self::agent()); + } -$urlParams = []; -function initURLParam() -{ - global $urlParams; - if (!empty($_GET)) { - foreach ($_GET as $name => $value) { - $urlParams[$name] = $_GET[$name]; + /** + * Summary of query + * @return mixed + */ + public function query() + { + if (isset($_SERVER['QUERY_STRING'])) { + return $_SERVER['QUERY_STRING']; } + return ""; } -} -function getURLParam($name, $default = null) -{ - static $initialized = false; - global $urlParams; - if (!$initialized) { - initURLParam(); - $initialized = true; - } - if (!empty($urlParams) && isset($urlParams[$name]) && $urlParams[$name] != '') { - return $urlParams[$name]; + /** + * Summary of agent + * @return mixed + */ + public function agent() + { + if (isset($_SERVER['HTTP_USER_AGENT'])) { + return $_SERVER['HTTP_USER_AGENT']; + } + return ""; } - return $default; -} -function setURLParam($name, $value) -{ - global $urlParams; - $urlParams[$name] = $value; -} + /** + * Summary of init + * @return void + */ + public function init() + { + $this->urlParams = []; + if (!empty($_GET)) { + foreach ($_GET as $name => $value) { + $this->urlParams[$name] = $_GET[$name]; + } + } + } -function getCurrentOption($option) -{ - global $config; - if (isset($_COOKIE[$option])) { - if (isset($config ['cops_' . $option]) && is_array($config ['cops_' . $option])) { - return explode(',', $_COOKIE[$option]); - } elseif (!preg_match('/[^A-Za-z0-9\-_.@]/', $_COOKIE[$option])) { - return $_COOKIE[$option]; + /** + * Summary of get + * @param mixed $name + * @param mixed $default + * @return mixed + */ + public function get($name, $default = null) + { + if (!empty($this->urlParams) && isset($this->urlParams[$name]) && $this->urlParams[$name] != '') { + return $this->urlParams[$name]; } + return $default; } - if (isset($config ['cops_' . $option])) { - return $config ['cops_' . $option]; + + /** + * Summary of set + * @param mixed $name + * @param mixed $value + * @return void + */ + public function set($name, $value) + { + $this->urlParams[$name] = $value; } - return ''; -} + /** + * Summary of option + * @param mixed $option + * @return mixed + */ + public function option($option) + { + global $config; + if (isset($_COOKIE[$option])) { + if (isset($config ['cops_' . $option]) && is_array($config ['cops_' . $option])) { + return explode(',', $_COOKIE[$option]); + } elseif (!preg_match('/[^A-Za-z0-9\-_.@]/', $_COOKIE[$option])) { + return $_COOKIE[$option]; + } + } + if (isset($config ['cops_' . $option])) { + return $config ['cops_' . $option]; + } -function getCurrentCss() -{ - global $config; - $style = getCurrentOption('style'); - if (!preg_match('/[^A-Za-z0-9\-_]/', $style)) { - return 'templates/' . getCurrentTemplate() . '/styles/style-' . getCurrentOption('style') . '.css'; + return ''; } - return 'templates/' . $config['cops_template'] . '/styles/style-' . $config['cops_template'] . '.css'; -} -function getCurrentTemplate() -{ - global $config; - $template = getCurrentOption('template'); - if (!preg_match('/[^A-Za-z0-9\-_]/', $template)) { - return $template; + /** + * Summary of style + * @return string + */ + public function style() + { + global $config; + $style = self::option('style'); + if (!preg_match('/[^A-Za-z0-9\-_]/', $style)) { + return 'templates/' . self::template() . '/styles/style-' . self::option('style') . '.css'; + } + return 'templates/' . $config['cops_template'] . '/styles/style-' . $config['cops_template'] . '.css'; } - return $config['cops_template']; -} -function getUrlWithVersion($url) -{ - return $url . '?v=' . Config::VERSION; -} + /** + * Summary of template + * @return mixed + */ + public function template() + { + global $config; + $template = self::option('template'); + if (!preg_match('/[^A-Za-z0-9\-_]/', $template)) { + return $template; + } + return $config['cops_template']; + } -function verifyLogin() -{ - global $config; - if (isset($config['cops_basic_authentication']) && - is_array($config['cops_basic_authentication'])) { - if (!isset($_SERVER['PHP_AUTH_USER']) || - (isset($_SERVER['PHP_AUTH_USER']) && - ($_SERVER['PHP_AUTH_USER'] != $config['cops_basic_authentication']['username'] || - $_SERVER['PHP_AUTH_PW'] != $config['cops_basic_authentication']['password']))) { - return false; + /** + * Summary of verifyLogin + * @return bool + */ + public static function verifyLogin($serverVars = null) + { + global $config; + $serverVars ??= $_SERVER; + if (isset($config['cops_basic_authentication']) && + is_array($config['cops_basic_authentication'])) { + if (!isset($serverVars['PHP_AUTH_USER']) || + (isset($serverVars['PHP_AUTH_USER']) && + ($serverVars['PHP_AUTH_USER'] != $config['cops_basic_authentication']['username'] || + $serverVars['PHP_AUTH_PW'] != $config['cops_basic_authentication']['password']))) { + return false; + } } + return true; + } + + /** + * Summary of notFound + * @return void + */ + public static function notFound() + { + header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); + header('Status: 404 Not Found'); + + $_SERVER['REDIRECT_STATUS'] = 404; + } + + /** + * Summary of build + * @param array $params + * @param ?array $server + * @param ?array $cookie + * @param ?array $config + * @return Request + */ + public static function build($params, $server = null, $cookie = null, $config = null) + { + // ['db' => $db, 'page' => $pageId, 'id' => $id, 'query' => $query, 'n' => $n] + $request = new self(); + $request->urlParams = $params; + return $request; } - return true; } namespace SebLucas\Cops\Output; +use SebLucas\Cops\Input\Config; use SebLucas\Template\doT; use DOMDocument; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\getCurrentTemplate; - class Format { /** @@ -193,19 +268,27 @@ public static function addURLParam($urlParams, $paramName, $paramValue) return $start . http_build_query($params); } - public static function addDatabaseParam($urlParams) + public static function addDatabaseParam($urlParams, $database) { - $database = getURLParam('db'); if (!is_null($database)) { $urlParams = self::addURLParam($urlParams, 'db', $database); } return $urlParams; } - public static function serverSideRender($data) + public static function addVersion($url) + { + if (str_contains($url, '?')) { + $url .= '&v=' . Config::VERSION; + } else { + $url .= '?v=' . Config::VERSION; + } + return $url; + } + + public static function serverSideRender($data, $theme = 'default') { // Get the templates - $theme = getCurrentTemplate(); $header = file_get_contents('templates/' . $theme . '/header.html'); $footer = file_get_contents('templates/' . $theme . '/footer.html'); $main = file_get_contents('templates/' . $theme . '/main.html'); diff --git a/checkconfig.php b/checkconfig.php index 33d194dff..79de0997d 100644 --- a/checkconfig.php +++ b/checkconfig.php @@ -10,17 +10,15 @@ */ use SebLucas\Cops\Calibre\Base; - -use function SebLucas\Cops\Request\getCurrentCss; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\getUrlWithVersion; -use function SebLucas\Cops\Request\useServerSideRendering; +use SebLucas\Cops\Input\Request; +use SebLucas\Cops\Output\Format; require_once dirname(__FILE__) . '/config.php'; /** @var array $config */ -$err = getURLParam('err', -1); -$full = getURLParam('full'); +$request = new Request(); +$err = $request->get('err', -1); +$full = $request->get('full'); $error = null; switch ($err) { case 1: @@ -33,7 +31,7 @@ COPS Configuration Check - +
@@ -158,7 +156,7 @@

Check if the rendering will be done on client side or server side

render()) { echo 'Server side rendering'; } else { echo 'Client side rendering'; diff --git a/config.php b/config.php index b7970b8d7..bcd00e9f9 100644 --- a/config.php +++ b/config.php @@ -13,7 +13,7 @@ } /** @var array $config */ -use function SebLucas\Cops\Request\verifyLogin; +use SebLucas\Cops\Input\Request; $remote_user = array_key_exists('PHP_AUTH_USER', $_SERVER) ? $_SERVER['PHP_AUTH_USER'] : ''; // Clean username, only allow a-z, A-Z, 0-9, -_ chars @@ -23,7 +23,7 @@ require dirname(__FILE__) . '/' . $user_config_file; } require_once dirname(__FILE__) . '/base.php'; -if (!verifyLogin()) { +if (!Request::verifyLogin()) { header('WWW-Authenticate: Basic realm="COPS Authentication"'); header('HTTP/1.0 401 Unauthorized'); echo 'This site is password protected'; diff --git a/epubfs.php b/epubfs.php index 97386eb8c..4cf682788 100644 --- a/epubfs.php +++ b/epubfs.php @@ -8,31 +8,30 @@ namespace SebLucas\Cops\Output\EPubReader; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\EPubReader; use Exception; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\notFound; - require_once dirname(__FILE__) . '/config.php'; if (php_sapi_name() === 'cli') { return; } -$idData = (int) getURLParam('data', null); +$request = new Request(); +$idData = (int) $request->get('data', null); if (empty($idData)) { - notFound(); + $request->notFound(); return; } -$component = getURLParam('comp', null); +$component = $request->get('comp', null); if (empty($component)) { - notFound(); + $request->notFound(); return; } try { - $data = EPubReader::getContent($idData, $component); + $data = EPubReader::getContent($idData, $component, $request); $expires = 60*60*24*14; header('Pragma: public'); @@ -42,5 +41,5 @@ echo $data; } catch (Exception $e) { error_log($e); - notFound(); + $request->notFound(); } diff --git a/epubreader.php b/epubreader.php index c10d08c90..41b859c15 100644 --- a/epubreader.php +++ b/epubreader.php @@ -6,20 +6,19 @@ * @author Sébastien Lucas */ +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\EPubReader; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\notFound; - require_once dirname(__FILE__) . '/config.php'; /** @var array $config */ -$idData = (int) getURLParam('data', null); +$request = new Request(); +$idData = (int) $request->get('data', null); if (empty($idData)) { - notFound(); + $request->notFound(); exit; } header('Content-Type: text/html;charset=utf-8'); -echo EPubReader::getReader($idData); +echo EPubReader::getReader($idData, $request); diff --git a/feed.php b/feed.php index a8707d973..0bb291d0b 100644 --- a/feed.php +++ b/feed.php @@ -6,22 +6,21 @@ * @author Sébastien Lucas * */ +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\OPDSRenderer; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\getURLParam; - require_once dirname(__FILE__) . '/config.php'; /** @var array $config */ -header('Content-Type:application/xml'); -$page = getURLParam('page', Page::INDEX); -$query = getURLParam('query'); -$n = getURLParam('n', '1'); +$request = new Request(); +$page = $request->get('page', Page::INDEX); +$query = $request->get('query'); +$n = $request->get('n', '1'); if ($query) { $page = Page::OPENSEARCH_QUERY; } -$qid = getURLParam('id'); +$qid = $request->get('id'); if ($config ['cops_fetch_protect'] == '1') { session_start(); @@ -30,15 +29,17 @@ } } +header('Content-Type:application/xml'); + $OPDSRender = new OPDSRenderer(); switch ($page) { case Page::OPENSEARCH : - echo $OPDSRender->getOpenSearch(); + echo $OPDSRender->getOpenSearch($request); return; default: - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); - echo $OPDSRender->render($currentPage); + echo $OPDSRender->render($currentPage, $request); return; } diff --git a/fetch.php b/fetch.php index 939015119..481afd6e1 100644 --- a/fetch.php +++ b/fetch.php @@ -5,20 +5,20 @@ * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Sébastien Lucas */ +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Calibre\Book; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\notFound; - require_once dirname(__FILE__) . '/config.php'; /** @var array $config */ global $config; +$request = new Request(); + if ($config['cops_fetch_protect'] == '1') { session_start(); if (!isset($_SESSION['connected'])) { - notFound(); + $request->notFound(); return; } } @@ -31,19 +31,20 @@ header('Pragma: public'); header('Cache-Control: max-age=' . $expires); header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT'); -$bookId = getURLParam('id', null); -$type = getURLParam('type', 'jpg'); -$idData = getURLParam('data', null); -$viewOnly = getURLParam('view', false); +$bookId = $request->get('id', null); +$type = $request->get('type', 'jpg'); +$idData = $request->get('data', null); +$viewOnly = $request->get('view', false); +$database = $request->get('db'); if (is_null($bookId)) { - $book = Book::getBookByDataId($idData); + $book = Book::getBookByDataId($idData, $database); } else { - $book = Book::getBookById($bookId); + $book = Book::getBookById($bookId, $database); } if (!$book) { - notFound(); + $request->notFound(); return; } @@ -55,7 +56,7 @@ $file = $book->getFilePath($type, $idData); } if (is_null($file) || !file_exists($file)) { - notFound(); + $request->notFound(); return; } } @@ -74,14 +75,14 @@ if (isset($config['cops_thumbnail_cache_directory']) && $config['cops_thumbnail_cache_directory'] !== '') { $thumbnailCacheFullpath = $config['cops_thumbnail_cache_directory']; //if multiple databases, add a subfolder with the database ID - $thumbnailCacheFullpath .= !is_null(getURLParam('db')) ? 'db-' . getURLParam('db') . DIRECTORY_SEPARATOR : ''; + $thumbnailCacheFullpath .= !is_null($database) ? 'db-' . $database . DIRECTORY_SEPARATOR : ''; //when there are lots of thumbnails, it's better to save files in subfolders, so if the book's uuid is //"01234567-89ab-cdef-0123-456789abcdef", we will save the thumbnail in .../0/12/34567-89ab-cdef-0123-456789abcdef-... $thumbnailCacheFullpath .= substr($book->uuid, 0, 1) . DIRECTORY_SEPARATOR . substr($book->uuid, 1, 2) . DIRECTORY_SEPARATOR; //check if cache folder exists or create it if (file_exists($thumbnailCacheFullpath) || mkdir($thumbnailCacheFullpath, 0700, true)) { //we name the thumbnail from the book's uuid and it's dimensions (width and/or height) - $thumbnailCacheName = substr($book->uuid, 3) . '-' . getURLParam('width') . 'x' . getURLParam('height') . '.' . $type; + $thumbnailCacheName = substr($book->uuid, 3) . '-' . $request->get('width') . 'x' . $request->get('height') . '.' . $type; $thumbnailCacheFullpath = $thumbnailCacheFullpath . $thumbnailCacheName; } else { //error creating the folder, so we don't cache @@ -95,8 +96,8 @@ return; } - $width = getURLParam('width'); - $height = getURLParam('height'); + $width = $request->get('width'); + $height = $request->get('height'); if ($book->getThumbnail($width, $height, $thumbnailCacheFullpath, $type)) { //if we don't cache the thumbnail, imagejpeg() in $book->getThumbnail() already return the image data if ($thumbnailCacheFullpath === null) { @@ -118,6 +119,9 @@ // absolute path for single DB in PHP app here - cfr. internal dir for X-Accel-Redirect with Nginx $file = $book->getFilePath($type, $idData, false); if (!$viewOnly && $type == 'epub' && $config['cops_update_epub-metadata']) { + if ($config['cops_provide_kepub'] == '1' && preg_match('/Kobo/', $request->agent())) { + $book->updateForKepub = true; + } $book->getUpdatedEpub($idData); return; } diff --git a/getJSON.php b/getJSON.php index 598c5c23d..31c9f0982 100644 --- a/getJSON.php +++ b/getJSON.php @@ -6,11 +6,14 @@ * @author Sébastien Lucas * */ +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\JSONRenderer; require_once dirname(__FILE__) . '/config.php'; /** @var array $config */ +$request = new Request(); + header('Content-Type:application/json;charset=utf-8'); -echo json_encode(JSONRenderer::getJson()); +echo json_encode(JSONRenderer::getJson($request)); diff --git a/index.php b/index.php index 25a13ad3d..1a5ac5296 100644 --- a/index.php +++ b/index.php @@ -8,18 +8,13 @@ */ use SebLucas\Cops\Calibre\Base; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\Format; use SebLucas\Cops\Output\JSONRenderer; use SebLucas\Cops\Pages\Page; use SebLucas\Template\doT; -use function SebLucas\Cops\Request\getCurrentCss; -use function SebLucas\Cops\Request\getCurrentTemplate; -use function SebLucas\Cops\Request\getQueryString; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\useServerSideRendering; - require_once dirname(__FILE__) . '/config.php'; /** @var array $config */ @@ -29,16 +24,17 @@ exit(); } -$page = getURLParam('page', Page::INDEX); -$query = getURLParam('query'); -$qid = getURLParam('id'); -$n = getURLParam('n', '1'); -$database = getURLParam('db'); +$request = new Request(); +$page = $request->get('page', Page::INDEX); +$query = $request->get('query'); +$qid = $request->get('id'); +$n = $request->get('n', '1'); +$database = $request->get('db'); // Access the database ASAP to be sure it's readable, redirect if that's not the case. // It has to be done before any header is sent. -Base::checkDatabaseAvailability(); +Base::checkDatabaseAvailability($database); if ($config ['cops_fetch_protect'] == '1') { session_start(); @@ -53,26 +49,26 @@ 'version' => Config::VERSION, 'opds_url' => $config['cops_full_url'] . Config::ENDPOINT["feed"], 'customHeader' => '', - 'template' => getCurrentTemplate(), - 'server_side_rendering' => useServerSideRendering(), - 'current_css' => getCurrentCss(), + 'template' => $request->template(), + 'server_side_rendering' => $request->render(), + 'current_css' => $request->style(), 'favico' => $config['cops_icon'], - 'getjson_url' => JSONRenderer::getCurrentUrl(getQueryString())]; + 'getjson_url' => JSONRenderer::getCurrentUrl($request->query())]; if (preg_match('/Kindle/', $_SERVER['HTTP_USER_AGENT'])) { $data['customHeader'] = ''; } -$headcontent = file_get_contents('templates/' . getCurrentTemplate() . '/file.html'); +$headcontent = file_get_contents('templates/' . $request->template() . '/file.html'); $template = new doT(); $dot = $template->template($headcontent, null); echo($dot($data)); ?> render()) { // Get the data - $data = JSONRenderer::getJson(true); + $data = JSONRenderer::getJson($request, true); - echo Format::serverSideRender($data); + echo Format::serverSideRender($data, $request->template()); } ?> diff --git a/lib/Calibre/Author.php b/lib/Calibre/Author.php index 74226b4bc..c700e7523 100644 --- a/lib/Calibre/Author.php +++ b/lib/Calibre/Author.php @@ -50,18 +50,18 @@ public static function getEntryIdByLetter($startingLetter) return self::PAGE_ID.":letter:".$startingLetter; } - public static function getCount() + public static function getCount($database = null) { // str_format (localize("authors.alphabetical", count(array)) - return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL); + return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, $database); } - public static function getAllAuthorsByFirstLetter() + public static function getAllAuthorsByFirstLetter($database = null, $numberPerPage = null) { [, $result] = parent::executeQuery("select {0} from authors group by substr (upper (sort), 1, 1) -order by substr (upper (sort), 1, 1)", "substr (upper (sort), 1, 1) as title, count(*) as count", "", [], -1); +order by substr (upper (sort), 1, 1)", "substr (upper (sort), 1, 1) as title, count(*) as count", "", [], -1, $database, $numberPerPage); $entryArray = []; while ($post = $result->fetchObject()) { array_push($entryArray, new Entry( @@ -70,6 +70,7 @@ public static function getAllAuthorsByFirstLetter() str_format(localize("authorword", $post->count), $post->count), "text", [ new LinkNavigation("?page=".self::PAGE_LETTER."&id=". rawurlencode($post->title))], + $database, "", $post->count )); @@ -77,37 +78,37 @@ public static function getAllAuthorsByFirstLetter() return $entryArray; } - public static function getAuthorsByStartingLetter($letter) + public static function getAuthorsByStartingLetter($letter, $database = null) { - return self::getEntryArray(self::SQL_AUTHORS_BY_FIRST_LETTER, [$letter . "%"]); + return self::getEntryArray(self::SQL_AUTHORS_BY_FIRST_LETTER, [$letter . "%"], $database); } - public static function getAuthorsForSearch($query) + public static function getAuthorsForSearch($query, $database = null) { - return self::getEntryArray(self::SQL_AUTHORS_FOR_SEARCH, [$query . "%", $query . "%"]); + return self::getEntryArray(self::SQL_AUTHORS_FOR_SEARCH, [$query . "%", $query . "%"], $database); } - public static function getAllAuthors() + public static function getAllAuthors($database = null) { - return self::getEntryArray(self::SQL_ALL_AUTHORS, []); + return self::getEntryArray(self::SQL_ALL_AUTHORS, [], $database); } - public static function getEntryArray($query, $params) + public static function getEntryArray($query, $params, $database = null, $numberPerPage = null) { - return Base::getEntryArrayWithBookNumber($query, self::SQL_COLUMNS, $params, self::class); + return Base::getEntryArrayWithBookNumber($query, self::SQL_COLUMNS, $params, self::class, $database, $numberPerPage); } - public static function getAuthorById($authorId) + public static function getAuthorById($authorId, $database = null) { - $result = parent::getDb()->prepare('select ' . self::SQL_COLUMNS . ' from authors where id = ?'); + $result = parent::getDb($database)->prepare('select ' . self::SQL_COLUMNS . ' from authors where id = ?'); $result->execute([$authorId]); $post = $result->fetchObject(); return new Author($post); } - public static function getAuthorByBookId($bookId) + public static function getAuthorByBookId($bookId, $database = null) { - $result = parent::getDb()->prepare('select authors.id as id, authors.name as name, authors.sort as sort from authors, books_authors_link + $result = parent::getDb($database)->prepare('select authors.id as id, authors.name as name, authors.sort as sort from authors, books_authors_link where author = authors.id and book = ? order by books_authors_link.id'); $result->execute([$bookId]); diff --git a/lib/Calibre/Base.php b/lib/Calibre/Base.php index 4e19d898d..e932bf673 100644 --- a/lib/Calibre/Base.php +++ b/lib/Calibre/Base.php @@ -8,41 +8,76 @@ namespace SebLucas\Cops\Calibre; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; use SebLucas\Cops\Language\Translation; use SebLucas\Cops\Model\Entry; use SebLucas\Cops\Model\LinkNavigation; use Exception; use PDO; -use function SebLucas\Cops\Request\getCurrentOption; -use function SebLucas\Cops\Request\getURLParam; - abstract class Base { public const COMPATIBILITY_XML_ALDIKO = "aldiko"; private static $db = null; + protected $databaseId = null; + + /** + * Summary of getDatabaseId + * @return mixed + */ + public function getDatabaseId() + { + return $this->databaseId; + } + + /** + * Summary of setDatabaseId + * @param mixed $database + * @return void + */ + public function setDatabaseId($database = null) + { + $this->databaseId = $database; + } + /** + * Summary of isMultipleDatabaseEnabled + * @return bool + */ public static function isMultipleDatabaseEnabled() { global $config; return is_array($config['calibre_directory']); } - public static function useAbsolutePath() + /** + * Summary of useAbsolutePath + * @param mixed $database + * @return bool + */ + public static function useAbsolutePath($database) { global $config; - $path = self::getDbDirectory(); + $path = self::getDbDirectory($database); return preg_match('/^\//', $path) || // Linux / preg_match('/^\w\:/', $path); // Windows X: } - public static function noDatabaseSelected() + /** + * Summary of noDatabaseSelected + * @param mixed $database + * @return bool + */ + public static function noDatabaseSelected($database) { - return self::isMultipleDatabaseEnabled() && is_null(getURLParam('db')); + return self::isMultipleDatabaseEnabled() && is_null($database); } + /** + * Summary of getDbList + * @return array + */ public static function getDbList() { global $config; @@ -53,6 +88,10 @@ public static function getDbList() } } + /** + * Summary of getDbNameList + * @return array + */ public static function getDbNameList() { global $config; @@ -63,14 +102,19 @@ public static function getDbNameList() } } - public static function getDbName($database = null) + /** + * Summary of getDbName + * @param mixed $database + * @return string + */ + public static function getDbName($database) { global $config; if (self::isMultipleDatabaseEnabled()) { if (is_null($database)) { - $database = getURLParam('db', 0); + $database = 0; } - if (!is_null($database) && !preg_match('/^\d+$/', $database)) { + if (!preg_match('/^\d+$/', $database)) { self::error($database); } $array = array_keys($config['calibre_directory']); @@ -79,14 +123,19 @@ public static function getDbName($database = null) return ""; } - public static function getDbDirectory($database = null) + /** + * Summary of getDbDirectory + * @param mixed $database + * @return string + */ + public static function getDbDirectory($database) { global $config; if (self::isMultipleDatabaseEnabled()) { if (is_null($database)) { - $database = getURLParam('db', 0); + $database = 0; } - if (!is_null($database) && !preg_match('/^\d+$/', $database)) { + if (!preg_match('/^\d+$/', $database)) { self::error($database); } $array = array_values($config['calibre_directory']); @@ -96,12 +145,17 @@ public static function getDbDirectory($database = null) } // -DC- Add image directory - public static function getImgDirectory($database = null) + /** + * Summary of getImgDirectory + * @param mixed $database + * @return string + */ + public static function getImgDirectory($database) { global $config; if (self::isMultipleDatabaseEnabled()) { if (is_null($database)) { - $database = getURLParam('db', 0); + $database = 0; } $array = array_values($config['image_directory']); return $array[$database]; @@ -109,11 +163,22 @@ public static function getImgDirectory($database = null) return $config['image_directory']; } - public static function getDbFileName($database = null) + /** + * Summary of getDbFileName + * @param mixed $database + * @return string + */ + public static function getDbFileName($database) { return self::getDbDirectory($database) .'metadata.db'; } + /** + * Summary of error + * @param mixed $database + * @throws \Exception + * @return never + */ private static function error($database) { if (php_sapi_name() != "cli") { @@ -122,6 +187,11 @@ private static function error($database) throw new Exception("Database <{$database}> not found."); } + /** + * Summary of getDb + * @param mixed $database + * @return \PDO + */ public static function getDb($database = null) { if (is_null(self::$db)) { @@ -143,35 +213,59 @@ public static function getDb($database = null) return self::$db; } - public static function checkDatabaseAvailability() + /** + * Summary of checkDatabaseAvailability + * @param mixed $database + * @return bool + */ + public static function checkDatabaseAvailability($database) { - if (self::noDatabaseSelected()) { + if (self::noDatabaseSelected($database)) { for ($i = 0; $i < count(self::getDbList()); $i++) { self::getDb($i); self::clearDb(); } } else { - self::getDb(); + self::getDb($database); } return true; } + /** + * Summary of clearDb + * @return void + */ public static function clearDb() { self::$db = null; } + /** + * Summary of executeQuerySingle + * @param mixed $query + * @param mixed $database + * @return mixed + */ public static function executeQuerySingle($query, $database = null) { return self::getDb($database)->query($query)->fetchColumn(); } - public static function getCountGeneric($table, $id, $pageId, $numberOfString = null) + /** + * Summary of getCountGeneric + * @param mixed $table + * @param mixed $id + * @param mixed $pageId + * @param mixed $database + * @param mixed $numberOfString + * @return Entry|null + */ + public static function getCountGeneric($table, $id, $pageId, $database = null, $numberOfString = null) { if (!$numberOfString) { $numberOfString = $table . ".alphabetical"; } - $count = self::executeQuerySingle('select count(*) from ' . $table); + $count = self::executeQuerySingle('select count(*) from ' . $table, $database); if ($count == 0) { return null; } @@ -181,17 +275,28 @@ public static function getCountGeneric($table, $id, $pageId, $numberOfString = n str_format(localize($numberOfString, $count), $count), "text", [ new LinkNavigation("?page=".$pageId)], + $database, "", $count ); return $entry; } - public static function getEntryArrayWithBookNumber($query, $columns, $params, $category) + /** + * Summary of getEntryArrayWithBookNumber + * @param mixed $query + * @param mixed $columns + * @param mixed $params + * @param mixed $category + * @param mixed $database + * @param mixed $numberPerPage + * @return array + */ + public static function getEntryArrayWithBookNumber($query, $columns, $params, $category, $database = null, $numberPerPage = null) { /** @var \PDOStatement $result */ - [, $result] = self::executeQuery($query, $columns, "", $params, -1); + [, $result] = self::executeQuery($query, $columns, "", $params, -1, $database, $numberPerPage); $entryArray = []; while ($post = $result->fetchObject()) { /** @var Author|Tag|Serie|Publisher $instance */ @@ -208,6 +313,7 @@ public static function getEntryArrayWithBookNumber($query, $columns, $params, $c str_format(localize("bookword", $post->count), $post->count), "text", [ new LinkNavigation($instance->getUri())], + $database, "", $post->count )); @@ -215,6 +321,17 @@ public static function getEntryArrayWithBookNumber($query, $columns, $params, $c return $entryArray; } + /** + * Summary of executeQuery + * @param mixed $query + * @param mixed $columns + * @param mixed $filter + * @param mixed $params + * @param mixed $n + * @param mixed $database + * @param mixed $numberPerPage + * @return array + */ public static function executeQuery($query, $columns, $filter, $params, $n, $database = null, $numberPerPage = null) { $totalResult = -1; @@ -225,7 +342,8 @@ public static function executeQuery($query, $columns, $filter, $params, $n, $dat } if (is_null($numberPerPage)) { - $numberPerPage = getCurrentOption("max_item_per_page"); + global $config; + $numberPerPage = $config['cops_max_item_per_page']; } if ($numberPerPage != -1 && $n != -1) { diff --git a/lib/Calibre/Book.php b/lib/Calibre/Book.php index dc59e50aa..4c5270c8a 100644 --- a/lib/Calibre/Book.php +++ b/lib/Calibre/Book.php @@ -8,7 +8,8 @@ namespace SebLucas\Cops\Calibre; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Model\Entry; use SebLucas\Cops\Model\EntryBook; use SebLucas\Cops\Model\Link; @@ -19,9 +20,6 @@ use SebLucas\EPubMeta\EPub; use Exception; -use function SebLucas\Cops\Request\getCurrentOption; -use function SebLucas\Cops\Request\getURLParam; - // Silly thing because PHP forbid string concatenation in class const define('SQL_BOOKS_LEFT_JOIN', 'left outer join comments on comments.book = books.id left outer join books_ratings_link on books_ratings_link.book = books.id @@ -127,8 +125,9 @@ class Book extends Base public $languages = null; public $format = []; private $coverFileName = null; + public $updateForKepub = false; - public function __construct($line) + public function __construct($line, $database = null) { global $config; @@ -141,7 +140,7 @@ public function __construct($line) // -DC- Init relative or full path $this->path = $line->path; if (!is_dir($this->path)) { - $this->path = Base::getDbDirectory() . $line->path; + $this->path = Base::getDbDirectory($database) . $line->path; } $this->seriesIndex = $line->series_index; $this->comment = $line->comment ?? ''; @@ -154,7 +153,7 @@ public function __construct($line) //} if ($this->hasCover) { if (!empty($config['calibre_database_field_cover'])) { - $imgDirectory = Base::getImgDirectory(); + $imgDirectory = Base::getImgDirectory($database); $this->coverFileName = $line->cover; if (!file_exists($this->coverFileName)) { $this->coverFileName = null; @@ -196,6 +195,7 @@ public function __construct($line) } } $this->rating = $line->rating; + $this->databaseId = $database; } // -DC- Get customisable book columns @@ -229,7 +229,7 @@ public function getUri() public function getDetailUrl() { $urlParam = $this->getUri(); - $urlParam = Format::addDatabaseParam($urlParam); + $urlParam = Format::addDatabaseParam($urlParam, $this->databaseId); return self::$endpoint . $urlParam; } @@ -376,7 +376,8 @@ public static function getDataByBook($book) . "')"; } - $result = parent::getDb()->prepare($sql); + $database = $book->getDatabaseId(); + $result = parent::getDb($database)->prepare($sql); $result->execute([$book->id]); while ($post = $result->fetchObject()) { @@ -387,9 +388,12 @@ public static function getDataByBook($book) /* End of other class (author, series, tag, ...) initialization and accessors */ - public static function getFilterString() + public static function getFilterString($request) { - $filter = getURLParam('tag', null); + if (empty($request)) { + return ''; + } + $filter = $request->get('tag', null); if (empty($filter)) { return ''; } @@ -550,7 +554,8 @@ public function getUpdatedEpub($idData) $epub->SerieIndex($this->seriesIndex); } $filename = $data->getUpdatedFilenameEpub(); - if ($config['cops_provide_kepub'] == '1' && preg_match('/Kobo/', $_SERVER['HTTP_USER_AGENT'])) { + // @checkme this is set in fetch.php now + if ($this->updateForKepub) { $epub->updateForKepub(); $filename = $data->getUpdatedFilenameKepub(); } @@ -671,10 +676,10 @@ public static function getBookCount($database = null) return parent::executeQuerySingle('select count(*) from books', $database); } - public static function getCount() + public static function getCount($database = null) { global $config; - $nBooks = parent::executeQuerySingle('select count(*) from books'); + $nBooks = parent::executeQuerySingle('select count(*) from books', $database); $result = []; $entry = new Entry( localize('allbooks.title'), @@ -682,6 +687,7 @@ public static function getCount() str_format(localize('allbooks.alphabetical', $nBooks), $nBooks), 'text', [new LinkNavigation('?page='.self::PAGE_ALL)], + $database, '', $nBooks ); @@ -693,6 +699,7 @@ public static function getCount() str_format(localize('recent.list'), $config['cops_recentbooks_limit']), 'text', [ new LinkNavigation('?page='.Page::ALL_RECENT_BOOKS)], + $database, '', $config['cops_recentbooks_limit'] ); @@ -701,34 +708,34 @@ public static function getCount() return $result; } - public static function getBooksByAuthor($authorId, $n) + public static function getBooksByAuthor($authorId, $n, $database = null) { - return self::getEntryArray(self::SQL_BOOKS_BY_AUTHOR, [$authorId], $n); + return self::getEntryArray(self::SQL_BOOKS_BY_AUTHOR, [$authorId], $n, $database); } - public static function getBooksByRating($ratingId, $n) + public static function getBooksByRating($ratingId, $n, $database = null) { - return self::getEntryArray(self::SQL_BOOKS_BY_RATING, [$ratingId], $n); + return self::getEntryArray(self::SQL_BOOKS_BY_RATING, [$ratingId], $n, $database); } - public static function getBooksByPublisher($publisherId, $n) + public static function getBooksByPublisher($publisherId, $n, $database = null) { - return self::getEntryArray(self::SQL_BOOKS_BY_PUBLISHER, [$publisherId], $n); + return self::getEntryArray(self::SQL_BOOKS_BY_PUBLISHER, [$publisherId], $n, $database); } - public static function getBooksBySeries($serieId, $n) + public static function getBooksBySeries($serieId, $n, $database = null) { - return self::getEntryArray(self::SQL_BOOKS_BY_SERIE, [$serieId], $n); + return self::getEntryArray(self::SQL_BOOKS_BY_SERIE, [$serieId], $n, $database); } - public static function getBooksByTag($tagId, $n) + public static function getBooksByTag($tagId, $n, $database = null) { - return self::getEntryArray(self::SQL_BOOKS_BY_TAG, [$tagId], $n); + return self::getEntryArray(self::SQL_BOOKS_BY_TAG, [$tagId], $n, $database); } - public static function getBooksByLanguage($languageId, $n) + public static function getBooksByLanguage($languageId, $n, $database = null) { - return self::getEntryArray(self::SQL_BOOKS_BY_LANGUAGE, [$languageId], $n); + return self::getEntryArray(self::SQL_BOOKS_BY_LANGUAGE, [$languageId], $n, $database); } /** @@ -737,34 +744,34 @@ public static function getBooksByLanguage($languageId, $n) * @param $n integer * @return array */ - public static function getBooksByCustom($customColumn, $id, $n) + public static function getBooksByCustom($customColumn, $id, $n, $database = null) { [$query, $params] = $customColumn->getQuery($id); - return self::getEntryArray($query, $params, $n); + return self::getEntryArray($query, $params, $n, $database); } - public static function getBookById($bookId) + public static function getBookById($bookId, $database = null) { - $result = parent::getDb()->prepare('select ' . self::getBookColumns() . ' + $result = parent::getDb($database)->prepare('select ' . self::getBookColumns() . ' from books ' . self::SQL_BOOKS_LEFT_JOIN . ' where books.id = ?'); $result->execute([$bookId]); while ($post = $result->fetchObject()) { - $book = new Book($post); + $book = new Book($post, $database); return $book; } return null; } - public static function getBookByDataId($dataId) + public static function getBookByDataId($dataId, $database = null) { - $result = parent::getDb()->prepare('select ' . self::getBookColumns() . ', data.name, data.format + $result = parent::getDb($database)->prepare('select ' . self::getBookColumns() . ', data.name, data.format from data, books ' . self::SQL_BOOKS_LEFT_JOIN . ' where data.book = books.id and data.id = ?'); $result->execute([$dataId]); while ($post = $result->fetchObject()) { - $book = new Book($post); + $book = new Book($post, $database); $data = new Data($post, $book); $data->id = $dataId; $book->datas = [$data]; @@ -773,7 +780,7 @@ public static function getBookByDataId($dataId) return null; } - public static function getBooksByQuery($query, $n, $database = null, $numberPerPage = null) + public static function getBooksByQuery($query, $n, $database = null, $numberPerPage = null, $ignoredCategories = []) { $i = 0; $critArray = []; @@ -782,7 +789,7 @@ public static function getBooksByQuery($query, $n, $database = null, $numberPerP PageQueryResult::SCOPE_SERIES, PageQueryResult::SCOPE_PUBLISHER, PageQueryResult::SCOPE_BOOK] as $key) { - if (in_array($key, getCurrentOption('ignored_categories')) || + if (in_array($key, $ignoredCategories) || (!array_key_exists($key, $query) && !array_key_exists('all', $query))) { $critArray[$i] = self::BAD_SEARCH; } else { @@ -797,20 +804,20 @@ public static function getBooksByQuery($query, $n, $database = null, $numberPerP return self::getEntryArray(self::SQL_BOOKS_QUERY, $critArray, $n, $database, $numberPerPage); } - public static function getBooks($n) + public static function getBooks($n, $database = null, $numberPerPage = null, $request = null) { - [$entryArray, $totalNumber] = self::getEntryArray(self::SQL_BOOKS_ALL, [], $n); + [$entryArray, $totalNumber] = self::getEntryArray(self::SQL_BOOKS_ALL, [], $n, $database, $numberPerPage, $request); return [$entryArray, $totalNumber]; } - public static function getAllBooks() + public static function getAllBooks($database = null, $request = null) { /** @var \PDOStatement $result */ [, $result] = parent::executeQuery('select {0} from books group by substr (upper (sort), 1, 1) -order by substr (upper (sort), 1, 1)', 'substr (upper (sort), 1, 1) as title, count(*) as count', self::getFilterString(), [], -1); +order by substr (upper (sort), 1, 1)', 'substr (upper (sort), 1, 1) as title, count(*) as count', self::getFilterString($request), [], -1, $database); $entryArray = []; while ($post = $result->fetchObject()) { @@ -820,6 +827,7 @@ public static function getAllBooks() str_format(localize('bookword', $post->count), $post->count), 'text', [new LinkNavigation('?page='.self::PAGE_LETTER.'&id='. rawurlencode($post->title))], + $database, '', $post->count )); @@ -832,11 +840,11 @@ public static function getBooksByStartingLetter($letter, $n, $database = null, $ return self::getEntryArray(self::SQL_BOOKS_BY_FIRST_LETTER, [$letter . '%'], $n, $database, $numberPerPage); } - public static function getEntryArray($query, $params, $n, $database = null, $numberPerPage = null) + public static function getEntryArray($query, $params, $n, $database = null, $numberPerPage = null, $request = null) { /** @var integer $totalNumber */ /** @var \PDOStatement $result */ - [$totalNumber, $result] = parent::executeQuery($query, self::getBookColumns(), self::getFilterString(), $params, $n, $database, $numberPerPage); + [$totalNumber, $result] = parent::executeQuery($query, self::getBookColumns(), self::getFilterString($request), $params, $n, $database, $numberPerPage); $entryArray = []; while ($post = $result->fetchObject()) { @@ -846,10 +854,10 @@ public static function getEntryArray($query, $params, $n, $database = null, $num return [$entryArray, $totalNumber]; } - public static function getAllRecentBooks() + public static function getAllRecentBooks($database = null, $numberPerPage = null, $request = null) { global $config; - [$entryArray, ] = self::getEntryArray(self::SQL_BOOKS_RECENT . $config['cops_recentbooks_limit'], [], -1); + [$entryArray, ] = self::getEntryArray(self::SQL_BOOKS_RECENT . $config['cops_recentbooks_limit'], [], -1, $database, $numberPerPage, $request); return $entryArray; } @@ -862,11 +870,12 @@ public static function getAllRecentBooks() public function getCustomColumnValues($columns, $asArray = false) { $result = []; + $database = $this->getDatabaseId(); - $columns = CustomColumnType::checkCustomColumnList($columns); + $columns = CustomColumnType::checkCustomColumnList($columns, $database); foreach ($columns as $lookup) { - $col = CustomColumnType::createByLookup($lookup); + $col = CustomColumnType::createByLookup($lookup, $database); if (!is_null($col)) { $cust = $col->getCustomByBook($this); if (!is_null($cust)) { diff --git a/lib/Calibre/CustomColumn.php b/lib/Calibre/CustomColumn.php index 79c91b4e1..82dd40be0 100644 --- a/lib/Calibre/CustomColumn.php +++ b/lib/Calibre/CustomColumn.php @@ -85,11 +85,12 @@ public function getHTMLEncodedValue() * * @param integer $customId the id of the customColumn * @param integer $id the id of the chosen value + * @param mixed $database * @return CustomColumn|null */ - public static function createCustom($customId, $id) + public static function createCustom($customId, $id, $database = null) { - $columnType = CustomColumnType::createByCustomID($customId); + $columnType = CustomColumnType::createByCustomID($customId, $database); return $columnType->getCustom($id); } diff --git a/lib/Calibre/CustomColumnType.php b/lib/Calibre/CustomColumnType.php index 62ec627ae..f1f877a02 100644 --- a/lib/Calibre/CustomColumnType.php +++ b/lib/Calibre/CustomColumnType.php @@ -51,12 +51,13 @@ abstract class CustomColumnType extends Base /** @var null|Entry[] */ private $customValues = null; - protected function __construct($pcustomId, $pdatatype) + protected function __construct($pcustomId, $pdatatype, $database = null) { - $this->columnTitle = self::getTitleByCustomID($pcustomId); + $this->columnTitle = self::getTitleByCustomID($pcustomId, $database); $this->customId = $pcustomId; $this->datatype = $pdatatype; $this->customValues = null; + $this->databaseId = $database; } /** @@ -118,7 +119,7 @@ public function getTitle() */ public function getDatabaseDescription() { - $result = $this->getDb()->prepare('SELECT display FROM custom_columns WHERE id = ?'); + $result = $this->getDb($this->databaseId)->prepare('SELECT display FROM custom_columns WHERE id = ?'); $result->execute([$this->customId]); if ($post = $result->fetchObject()) { $json = json_decode($post->display); @@ -141,10 +142,11 @@ public function getCount() // @checkme convert "csv" back to "text" here? $pcontentType = $this->datatype; $plinkArray = [new LinkNavigation($this->getUriAllCustoms())]; + $database = $this->getDatabaseId(); $pclass = ""; $pcount = $this->getDistinctValueCount(); - return new Entry($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pclass, $pcount); + return new Entry($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $database, $pclass, $pcount); } /** @@ -174,9 +176,9 @@ public function encodeHTMLValue($value) * @param integer $customId * @return string|null */ - private static function getDatatypeByCustomID($customId) + private static function getDatatypeByCustomID($customId, $database = null) { - $result = parent::getDb()->prepare('SELECT datatype, is_multiple FROM custom_columns WHERE id = ?'); + $result = parent::getDb($database)->prepare('SELECT datatype, is_multiple FROM custom_columns WHERE id = ?'); $result->execute([$customId]); if ($post = $result->fetchObject()) { // handle case where we have several values, e.g. array of text for type 2 (csv) @@ -195,36 +197,36 @@ private static function getDatatypeByCustomID($customId) * @return CustomColumnType|null * @throws Exception If the $customId is not found or the datatype is unknown */ - public static function createByCustomID($customId) + public static function createByCustomID($customId, $database = null) { // Reuse already created CustomColumns for performance if (array_key_exists($customId, self::$customColumnCacheID)) { return self::$customColumnCacheID[$customId]; } - $datatype = self::getDatatypeByCustomID($customId); + $datatype = self::getDatatypeByCustomID($customId, $database); switch ($datatype) { case self::CUSTOM_TYPE_TEXT: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeText($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeText($customId, self::CUSTOM_TYPE_TEXT, $database); case self::CUSTOM_TYPE_CSV: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeText($customId, self::CUSTOM_TYPE_CSV); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeText($customId, self::CUSTOM_TYPE_CSV, $database); case self::CUSTOM_TYPE_SERIES: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeSeries($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeSeries($customId, $database); case self::CUSTOM_TYPE_ENUM: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeEnumeration($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeEnumeration($customId, $database); case self::CUSTOM_TYPE_COMMENT: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeComment($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeComment($customId, $database); case self::CUSTOM_TYPE_DATE: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeDate($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeDate($customId, $database); case self::CUSTOM_TYPE_FLOAT: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeFloat($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeFloat($customId, $database); case self::CUSTOM_TYPE_INT: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeInteger($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeInteger($customId, self::CUSTOM_TYPE_INT, $database); case self::CUSTOM_TYPE_RATING: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeRating($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeRating($customId, $database); case self::CUSTOM_TYPE_BOOL: - return self::$customColumnCacheID[$customId] = new CustomColumnTypeBool($customId); + return self::$customColumnCacheID[$customId] = new CustomColumnTypeBool($customId, $database); case self::CUSTOM_TYPE_COMPOSITE: return null; //TODO Currently not supported default: @@ -238,14 +240,14 @@ public static function createByCustomID($customId) * @param string $lookup the lookup-name of the custom column * @return CustomColumnType|null */ - public static function createByLookup($lookup) + public static function createByLookup($lookup, $database = null) { // Reuse already created CustomColumns for performance if (array_key_exists($lookup, self::$customColumnCacheLookup)) { return self::$customColumnCacheLookup[$lookup]; } - $result = parent::getDb()->prepare('SELECT id FROM custom_columns WHERE label = ?'); + $result = parent::getDb($database)->prepare('SELECT id FROM custom_columns WHERE label = ?'); $result->execute([$lookup]); if ($post = $result->fetchObject()) { return self::$customColumnCacheLookup[$lookup] = self::createByCustomID($post->id); @@ -275,9 +277,9 @@ public function getAllCustomValues() * @param integer $customId * @return string */ - protected static function getTitleByCustomID($customId) + protected static function getTitleByCustomID($customId, $database = null) { - $result = parent::getDb()->prepare('SELECT name FROM custom_columns WHERE id = ?'); + $result = parent::getDb($database)->prepare('SELECT name FROM custom_columns WHERE id = ?'); $result->execute([$customId]); if ($post = $result->fetchObject()) { return $post->name; @@ -291,10 +293,10 @@ protected static function getTitleByCustomID($customId) * @param array $columnList * @return array */ - public static function checkCustomColumnList($columnList) + public static function checkCustomColumnList($columnList, $database = null) { if ($columnList === self::ALL_WILDCARD) { - $columnList = array_keys(self::getAllCustomColumns()); + $columnList = array_keys(self::getAllCustomColumns($database)); } return $columnList; } @@ -304,9 +306,9 @@ public static function checkCustomColumnList($columnList) * * @return array */ - public static function getAllCustomColumns() + public static function getAllCustomColumns($database = null) { - $result = parent::getDb()->prepare('SELECT id, label, name, datatype, display, is_multiple, normalized FROM custom_columns'); + $result = parent::getDb($database)->prepare('SELECT id, label, name, datatype, display, is_multiple, normalized FROM custom_columns'); $result->execute(); $columns = []; while ($post = $result->fetchObject()) { diff --git a/lib/Calibre/CustomColumnTypeBool.php b/lib/Calibre/CustomColumnTypeBool.php index 0ae92efc4..c50c5b08d 100644 --- a/lib/Calibre/CustomColumnTypeBool.php +++ b/lib/Calibre/CustomColumnTypeBool.php @@ -20,9 +20,9 @@ class CustomColumnTypeBool extends CustomColumnType +1 => "customcolumn.boolean.yes", // localize("customcolumn.boolean.yes") ]; - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_BOOL); + parent::__construct($pcustomId, self::CUSTOM_TYPE_BOOL, $database); } /** @@ -60,14 +60,14 @@ protected function getAllCustomValuesFromDatabase() { $queryFormat = "SELECT coalesce({0}.value, -1) AS id, count(*) AS count FROM books LEFT JOIN {0} ON books.id = {0}.book GROUP BY {0}.value ORDER BY {0}.value"; $query = str_format($queryFormat, $this->getTableName()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $entryArray = []; while ($post = $result->fetchObject()) { $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($post->id))]; - $entry = new Entry(localize($this->BOOLEAN_NAMES[$post->id]), $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry(localize($this->BOOLEAN_NAMES[$post->id]), $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } @@ -84,7 +84,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.value AS boolvalue FROM {0} WHERE {0}.book = {1}"; $query = str_format($queryFormat, $this->getTableName(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->boolvalue, localize($this->BOOLEAN_NAMES[$post->boolvalue]), $this); } else { diff --git a/lib/Calibre/CustomColumnTypeComment.php b/lib/Calibre/CustomColumnTypeComment.php index f034da668..059c418d0 100644 --- a/lib/Calibre/CustomColumnTypeComment.php +++ b/lib/Calibre/CustomColumnTypeComment.php @@ -10,9 +10,9 @@ class CustomColumnTypeComment extends CustomColumnType { - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_COMMENT); + parent::__construct($pcustomId, self::CUSTOM_TYPE_COMMENT, $database); } /** @@ -60,7 +60,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.id AS id, {0}.value AS value FROM {0} WHERE {0}.book = {1}"; $query = str_format($queryFormat, $this->getTableName(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->id, $post->value, $this); } diff --git a/lib/Calibre/CustomColumnTypeDate.php b/lib/Calibre/CustomColumnTypeDate.php index bafc8f306..cc07afb2b 100644 --- a/lib/Calibre/CustomColumnTypeDate.php +++ b/lib/Calibre/CustomColumnTypeDate.php @@ -14,9 +14,9 @@ class CustomColumnTypeDate extends CustomColumnType { - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_DATE); + parent::__construct($pcustomId, self::CUSTOM_TYPE_DATE, $database); } /** @@ -47,7 +47,7 @@ protected function getAllCustomValuesFromDatabase() { $queryFormat = "SELECT date(value) AS datevalue, count(*) AS count FROM {0} GROUP BY datevalue"; $query = str_format($queryFormat, $this->getTableName()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $entryArray = []; while ($post = $result->fetchObject()) { @@ -57,7 +57,7 @@ protected function getAllCustomValuesFromDatabase() $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($id))]; - $entry = new Entry($date->format(localize("customcolumn.date.format")), $this->getEntryId($id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry($date->format(localize("customcolumn.date.format")), $this->getEntryId($id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } @@ -79,7 +79,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT date({0}.value) AS datevalue FROM {0} WHERE {0}.book = {1}"; $query = str_format($queryFormat, $this->getTableName(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { $date = new DateTime($post->datevalue); diff --git a/lib/Calibre/CustomColumnTypeEnumeration.php b/lib/Calibre/CustomColumnTypeEnumeration.php index c89f0508a..89d0f2bc7 100644 --- a/lib/Calibre/CustomColumnTypeEnumeration.php +++ b/lib/Calibre/CustomColumnTypeEnumeration.php @@ -13,9 +13,9 @@ class CustomColumnTypeEnumeration extends CustomColumnType { - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_ENUM); + parent::__construct($pcustomId, self::CUSTOM_TYPE_ENUM, $database); } /** @@ -57,7 +57,7 @@ public function getQuery($id) public function getCustom($id) { - $result = $this->getDb()->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName())); + $result = $this->getDb($this->databaseId)->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName())); $result->execute([$id]); if ($post = $result->fetchObject()) { return new CustomColumn($id, $post->name, $this); @@ -70,13 +70,13 @@ protected function getAllCustomValuesFromDatabase() $queryFormat = "SELECT {0}.id AS id, {0}.value AS name, count(*) AS count FROM {0}, {1} WHERE {0}.id = {1}.{2} GROUP BY {0}.id, {0}.value ORDER BY {0}.value"; $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $entryArray = []; while ($post = $result->fetchObject()) { $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($post->id))]; - $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } @@ -93,7 +93,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.id AS id, {0}.{2} AS name FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3}"; $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->id, $post->name, $this); } diff --git a/lib/Calibre/CustomColumnTypeFloat.php b/lib/Calibre/CustomColumnTypeFloat.php index 6ab7d341a..df397c9ac 100644 --- a/lib/Calibre/CustomColumnTypeFloat.php +++ b/lib/Calibre/CustomColumnTypeFloat.php @@ -13,9 +13,9 @@ class CustomColumnTypeFloat extends CustomColumnType { - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_FLOAT); + parent::__construct($pcustomId, self::CUSTOM_TYPE_FLOAT, $database); } /** @@ -44,13 +44,13 @@ protected function getAllCustomValuesFromDatabase() $queryFormat = "SELECT value AS id, count(*) AS count FROM {0} GROUP BY value"; $query = str_format($queryFormat, $this->getTableName()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $entryArray = []; while ($post = $result->fetchObject()) { $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($post->id))]; - $entry = new Entry($post->id, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry($post->id, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } @@ -71,7 +71,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.value AS value FROM {0} WHERE {0}.book = {1}"; $query = str_format($queryFormat, $this->getTableName(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->value, $post->value, $this); } diff --git a/lib/Calibre/CustomColumnTypeInteger.php b/lib/Calibre/CustomColumnTypeInteger.php index ba7e9882d..84f0e7e8e 100644 --- a/lib/Calibre/CustomColumnTypeInteger.php +++ b/lib/Calibre/CustomColumnTypeInteger.php @@ -14,14 +14,14 @@ class CustomColumnTypeInteger extends CustomColumnType { - protected function __construct($pcustomId, $datatype = self::CUSTOM_TYPE_INT) + protected function __construct($pcustomId, $datatype = self::CUSTOM_TYPE_INT, $database = null) { switch ($datatype) { case self::CUSTOM_TYPE_INT: - parent::__construct($pcustomId, self::CUSTOM_TYPE_INT); + parent::__construct($pcustomId, self::CUSTOM_TYPE_INT, $database); break; case self::CUSTOM_TYPE_FLOAT: - parent::__construct($pcustomId, self::CUSTOM_TYPE_FLOAT); + parent::__construct($pcustomId, self::CUSTOM_TYPE_FLOAT, $database); break; default: throw new UnexpectedValueException(); @@ -54,13 +54,13 @@ protected function getAllCustomValuesFromDatabase() $queryFormat = "SELECT value AS id, count(*) AS count FROM {0} GROUP BY value"; $query = str_format($queryFormat, $this->getTableName()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $entryArray = []; while ($post = $result->fetchObject()) { $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($post->id))]; - $entry = new Entry($post->id, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry($post->id, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } @@ -81,7 +81,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.value AS value FROM {0} WHERE {0}.book = {1}"; $query = str_format($queryFormat, $this->getTableName(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->value, $post->value, $this); } diff --git a/lib/Calibre/CustomColumnTypeRating.php b/lib/Calibre/CustomColumnTypeRating.php index 35d103e3c..db714c4b2 100644 --- a/lib/Calibre/CustomColumnTypeRating.php +++ b/lib/Calibre/CustomColumnTypeRating.php @@ -13,9 +13,9 @@ class CustomColumnTypeRating extends CustomColumnType { - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_RATING); + parent::__construct($pcustomId, self::CUSTOM_TYPE_RATING, $database); } /** @@ -69,7 +69,7 @@ protected function getAllCustomValuesFromDatabase() { $queryFormat = "SELECT coalesce({0}.value, 0) AS value, count(*) AS count FROM books LEFT JOIN {1} ON books.id = {1}.book LEFT JOIN {0} ON {0}.id = {1}.value GROUP BY coalesce({0}.value, -1)"; $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $countArray = [0 => 0, 2 => 0, 4 => 0, 6 => 0, 8 => 0, 10 => 0]; while ($row = $result->fetchObject()) { @@ -84,7 +84,7 @@ protected function getAllCustomValuesFromDatabase() $entryid = $this->getEntryId($i * 2); $content = str_format(localize("bookword", $count), $count); $linkarray = [new LinkNavigation($this->getUri($i * 2))]; - $entry = new Entry($name, $entryid, $content, $this->datatype, $linkarray, "", $count); + $entry = new Entry($name, $entryid, $content, $this->datatype, $linkarray, $this->getDatabaseId(), "", $count); array_push($entryArray, $entry); } @@ -101,7 +101,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.value AS value FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3}"; $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->value, str_format(localize("customcolumn.stars", $post->value / 2), $post->value / 2), $this); } diff --git a/lib/Calibre/CustomColumnTypeSeries.php b/lib/Calibre/CustomColumnTypeSeries.php index f102aa388..2ea9d045a 100644 --- a/lib/Calibre/CustomColumnTypeSeries.php +++ b/lib/Calibre/CustomColumnTypeSeries.php @@ -13,9 +13,9 @@ class CustomColumnTypeSeries extends CustomColumnType { - protected function __construct($pcustomId) + protected function __construct($pcustomId, $database = null) { - parent::__construct($pcustomId, self::CUSTOM_TYPE_SERIES); + parent::__construct($pcustomId, self::CUSTOM_TYPE_SERIES, $database); } /** @@ -57,7 +57,7 @@ public function getQuery($id) public function getCustom($id) { - $result = $this->getDb()->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName())); + $result = $this->getDb($this->databaseId)->prepare(str_format("SELECT id, value AS name FROM {0} WHERE id = ?", $this->getTableName())); $result->execute([$id]); if ($post = $result->fetchObject()) { return new CustomColumn($id, $post->name, $this); @@ -70,13 +70,13 @@ protected function getAllCustomValuesFromDatabase() $queryFormat = "SELECT {0}.id AS id, {0}.value AS name, count(*) AS count FROM {0}, {1} WHERE {0}.id = {1}.{2} GROUP BY {0}.id, {0}.value ORDER BY {0}.value"; $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn()); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); $entryArray = []; while ($post = $result->fetchObject()) { $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($post->id))]; - $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } @@ -93,7 +93,7 @@ public function getCustomByBook($book) $queryFormat = "SELECT {0}.id AS id, {0}.{2} AS value, {1}.{2} AS name, {1}.extra AS extra FROM {0}, {1} WHERE {0}.id = {1}.{2} AND {1}.book = {3}"; $query = str_format($queryFormat, $this->getTableName(), $this->getTableLinkName(), $this->getTableLinkColumn(), $book->id); - $result = $this->getDb()->query($query); + $result = $this->getDb($this->databaseId)->query($query); if ($post = $result->fetchObject()) { return new CustomColumn($post->id, $post->value . " [" . $post->extra . "]", $this); } diff --git a/lib/Calibre/CustomColumnTypeText.php b/lib/Calibre/CustomColumnTypeText.php index 8b04f4d11..7fdf586db 100644 --- a/lib/Calibre/CustomColumnTypeText.php +++ b/lib/Calibre/CustomColumnTypeText.php @@ -14,20 +14,20 @@ class CustomColumnTypeText extends CustomColumnType { - protected function __construct($pcustomId, $datatype = self::CUSTOM_TYPE_TEXT) + protected function __construct($pcustomId, $datatype = self::CUSTOM_TYPE_TEXT, $database = null) { switch ($datatype) { case self::CUSTOM_TYPE_TEXT: - parent::__construct($pcustomId, self::CUSTOM_TYPE_TEXT); + parent::__construct($pcustomId, self::CUSTOM_TYPE_TEXT, $database); return; case self::CUSTOM_TYPE_CSV: - parent::__construct($pcustomId, self::CUSTOM_TYPE_CSV); + parent::__construct($pcustomId, self::CUSTOM_TYPE_CSV, $database); return; case self::CUSTOM_TYPE_ENUM: - parent::__construct($pcustomId, self::CUSTOM_TYPE_ENUM); + parent::__construct($pcustomId, self::CUSTOM_TYPE_ENUM, $database); return; case self::CUSTOM_TYPE_SERIES: - parent::__construct($pcustomId, self::CUSTOM_TYPE_SERIES); + parent::__construct($pcustomId, self::CUSTOM_TYPE_SERIES, $database); return; default: throw new UnexpectedValueException(); @@ -92,7 +92,7 @@ protected function getAllCustomValuesFromDatabase() $entryPContent = str_format(localize("bookword", $post->count), $post->count); $entryPLinkArray = [new LinkNavigation($this->getUri($post->id))]; - $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, "", $post->count); + $entry = new Entry($post->name, $this->getEntryId($post->id), $entryPContent, $this->datatype, $entryPLinkArray, $this->getDatabaseId(), "", $post->count); array_push($entryArray, $entry); } diff --git a/lib/Calibre/Data.php b/lib/Calibre/Data.php index ed3e59ce6..6874df224 100644 --- a/lib/Calibre/Data.php +++ b/lib/Calibre/Data.php @@ -8,12 +8,10 @@ namespace SebLucas\Cops\Calibre; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; use SebLucas\Cops\Model\Link; use SebLucas\Cops\Output\Format; -use function SebLucas\Cops\Request\getURLParam; - class Data { public static $endpoint = Config::ENDPOINT["fetch"]; @@ -23,6 +21,8 @@ class Data public $realFormat; public $extension; public $book; + protected $databaseId; + public $updateForKepub = false; public static $mimetypes = [ 'aac' => 'audio/aac', @@ -64,7 +64,7 @@ class Data 'zip' => 'application/zip', ]; - public function __construct($post, $book = null) + public function __construct($post, $book = null, $database = null) { $this->id = $post->id; $this->name = $post->name; @@ -72,6 +72,11 @@ public function __construct($post, $book = null) $this->realFormat = str_replace("ORIGINAL_", "", $post->format); $this->extension = strtolower($this->realFormat); $this->book = $book; + $this->databaseId = $database; + // this is set on book in JSONRenderer now + if ($book->updateForKepub && $this->isEpubValidOnKobo()) { + $this->updateForKepub = true; + } } public function isKnownType() @@ -156,8 +161,8 @@ public function getHtmlLinkWithRewriting($title = null, $view = false) global $config; $database = ""; - if (!is_null(getURLParam('db'))) { - $database = getURLParam('db') . "/"; + if (!is_null($this->databaseId)) { + $database = $this->databaseId . "/"; } $prefix = "download"; @@ -166,9 +171,8 @@ public function getHtmlLinkWithRewriting($title = null, $view = false) } $href = $prefix . "/" . $this->id . "/" . $database; - if ($config['cops_provide_kepub'] == "1" && - $this->isEpubValidOnKobo() && - preg_match("/Kobo/", $_SERVER['HTTP_USER_AGENT'])) { + // this is set on book in JSONRenderer now + if ($this->updateForKepub) { $href .= rawurlencode($this->getUpdatedFilenameKepub()); } else { $href .= rawurlencode($this->getFilename()); @@ -202,13 +206,14 @@ public static function handleThumbnailLink($urlParam, $height) public static function getLink($book, $type, $mime, $rel, $filename, $idData, $title = null, $height = null, $view = false) { global $config; + /** @var Book $book */ $urlParam = Format::addURLParam("", "data", $idData); if ($view) { $urlParam = Format::addURLParam($urlParam, "view", 1); } - if (Base::useAbsolutePath() || + if (Base::useAbsolutePath($book->getDatabaseId()) || $rel == Link::OPDS_THUMBNAIL_TYPE || ($type == "epub" && $config['cops_update_epub-metadata'])) { if ($type != "jpg") { @@ -218,7 +223,7 @@ public static function getLink($book, $type, $mime, $rel, $filename, $idData, $t $urlParam = self::handleThumbnailLink($urlParam, $height); } $urlParam = Format::addURLParam($urlParam, "id", $book->id); - $urlParam = Format::addDatabaseParam($urlParam); + $urlParam = Format::addDatabaseParam($urlParam, $book->getDatabaseId()); if ($config['cops_thumbnail_handling'] != "1" && !empty($config['cops_thumbnail_handling']) && $rel == Link::OPDS_THUMBNAIL_TYPE) { diff --git a/lib/Calibre/Language.php b/lib/Calibre/Language.php index 6e9b02f39..546a525e6 100644 --- a/lib/Calibre/Language.php +++ b/lib/Calibre/Language.php @@ -47,15 +47,15 @@ public static function getLanguageString($code) return $string; } - public static function getCount() + public static function getCount($database = null) { // str_format (localize("languages.alphabetical", count(array)) - return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL); + return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, $database); } - public static function getLanguageById($languageId) + public static function getLanguageById($languageId, $database = null) { - $result = parent::getDb()->prepare('select id, lang_code from languages where id = ?'); + $result = parent::getDb($database)->prepare('select id, lang_code from languages where id = ?'); $result->execute([$languageId]); if ($post = $result->fetchObject()) { return new Language($post->id, Language::getLanguageString($post->lang_code)); @@ -65,9 +65,9 @@ public static function getLanguageById($languageId) - public static function getAllLanguages() + public static function getAllLanguages($database = null) { - $result = parent::getDb()->query('select ' . self::SQL_COLUMNS . ' + $result = parent::getDb($database)->query('select ' . self::SQL_COLUMNS . ' from languages, books_languages_link where languages.id = books_languages_link.lang_code group by languages.id, books_languages_link.lang_code @@ -81,6 +81,7 @@ public static function getAllLanguages() str_format(localize("bookword", $post->count), $post->count), "text", [ new LinkNavigation($language->getUri())], + $database, "", $post->count )); diff --git a/lib/Calibre/Publisher.php b/lib/Calibre/Publisher.php index e0104e9c7..dfe6d0bc3 100644 --- a/lib/Calibre/Publisher.php +++ b/lib/Calibre/Publisher.php @@ -40,15 +40,15 @@ public function getEntryId() return self::PAGE_ID.":".$this->id; } - public static function getCount() + public static function getCount($database = null) { // str_format (localize("publishers.alphabetical", count(array)) - return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL); + return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, $database); } - public static function getPublisherByBookId($bookId) + public static function getPublisherByBookId($bookId, $database = null) { - $result = parent::getDb()->prepare('select publishers.id as id, name + $result = parent::getDb($database)->prepare('select publishers.id as id, name from books_publishers_link, publishers where publishers.id = publisher and book = ?'); $result->execute([$bookId]); @@ -58,9 +58,9 @@ public static function getPublisherByBookId($bookId) return null; } - public static function getPublisherById($publisherId) + public static function getPublisherById($publisherId, $database = null) { - $result = parent::getDb()->prepare('select id, name + $result = parent::getDb($database)->prepare('select id, name from publishers where id = ?'); $result->execute([$publisherId]); if ($post = $result->fetchObject()) { @@ -69,13 +69,13 @@ public static function getPublisherById($publisherId) return null; } - public static function getAllPublishers() + public static function getAllPublishers($database = null, $numberPerPage = null) { - return Base::getEntryArrayWithBookNumber(self::SQL_ALL_PUBLISHERS, self::SQL_COLUMNS, [], self::class); + return Base::getEntryArrayWithBookNumber(self::SQL_ALL_PUBLISHERS, self::SQL_COLUMNS, [], self::class, $database, $numberPerPage); } - public static function getAllPublishersByQuery($query) + public static function getAllPublishersByQuery($query, $database = null, $numberPerPage = null) { - return Base::getEntryArrayWithBookNumber(self::SQL_PUBLISHERS_FOR_SEARCH, self::SQL_COLUMNS, ['%' . $query . '%'], self::class); + return Base::getEntryArrayWithBookNumber(self::SQL_PUBLISHERS_FOR_SEARCH, self::SQL_COLUMNS, ['%' . $query . '%'], self::class, $database, $numberPerPage); } } diff --git a/lib/Calibre/Rating.php b/lib/Calibre/Rating.php index 5864d8562..067c00a93 100644 --- a/lib/Calibre/Rating.php +++ b/lib/Calibre/Rating.php @@ -39,20 +39,20 @@ public function getEntryId() return self::PAGE_ID.":".$this->id; } - public static function getCount() + public static function getCount($database = null) { // str_format (localize("ratings", count(array)) - return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, "ratings"); + return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, $database, "ratings"); } - public static function getAllRatings() + public static function getAllRatings($database = null) { - return self::getEntryArray(self::SQL_ALL_RATINGS, []); + return self::getEntryArray(self::SQL_ALL_RATINGS, [], $database); } - public static function getEntryArray($query, $params) + public static function getEntryArray($query, $params, $database = null, $numberPerPage = null) { - [, $result] = parent::executeQuery($query, self::SQL_COLUMNS, "", $params, -1); + [, $result] = parent::executeQuery($query, self::SQL_COLUMNS, "", $params, -1, $database, $numberPerPage); $entryArray = []; while ($post = $result->fetchObject()) { $ratingObj = new Rating($post->id, $post->rating); @@ -64,6 +64,7 @@ public static function getEntryArray($query, $params) str_format(localize("bookword", $post->count), $post->count), "text", [ new LinkNavigation($ratingObj->getUri())], + $database, "", $post->count )); @@ -71,9 +72,9 @@ public static function getEntryArray($query, $params) return $entryArray; } - public static function getRatingById($ratingId) + public static function getRatingById($ratingId, $database = null) { - $result = parent::getDb()->prepare('select rating from ratings where id = ?'); + $result = parent::getDb($database)->prepare('select rating from ratings where id = ?'); $result->execute([$ratingId]); return new Rating($ratingId, $result->fetchColumn()); } diff --git a/lib/Calibre/Serie.php b/lib/Calibre/Serie.php index 716a12b5d..e47f532cd 100644 --- a/lib/Calibre/Serie.php +++ b/lib/Calibre/Serie.php @@ -39,15 +39,15 @@ public function getEntryId() return self::PAGE_ID.":".$this->id; } - public static function getCount() + public static function getCount($database = null) { // str_format (localize("series.alphabetical", count(array)) - return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL); + return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, $database); } - public static function getSerieByBookId($bookId) + public static function getSerieByBookId($bookId, $database = null) { - $result = parent::getDb()->prepare('select series.id as id, name + $result = parent::getDb($database)->prepare('select series.id as id, name from books_series_link, series where series.id = series and book = ?'); $result->execute([$bookId]); @@ -57,9 +57,9 @@ public static function getSerieByBookId($bookId) return null; } - public static function getSerieById($serieId) + public static function getSerieById($serieId, $database = null) { - $result = parent::getDb()->prepare('select id, name from series where id = ?'); + $result = parent::getDb($database)->prepare('select id, name from series where id = ?'); $result->execute([$serieId]); if ($post = $result->fetchObject()) { return new Serie($post); @@ -67,13 +67,13 @@ public static function getSerieById($serieId) return null; } - public static function getAllSeries() + public static function getAllSeries($database = null, $numberPerPage = null) { - return Base::getEntryArrayWithBookNumber(self::SQL_ALL_SERIES, self::SQL_COLUMNS, [], self::class); + return Base::getEntryArrayWithBookNumber(self::SQL_ALL_SERIES, self::SQL_COLUMNS, [], self::class, $database, $numberPerPage); } - public static function getAllSeriesByQuery($query) + public static function getAllSeriesByQuery($query, $database = null, $numberPerPage = null) { - return Base::getEntryArrayWithBookNumber(self::SQL_SERIES_FOR_SEARCH, self::SQL_COLUMNS, ['%' . $query . '%'], self::class); + return Base::getEntryArrayWithBookNumber(self::SQL_SERIES_FOR_SEARCH, self::SQL_COLUMNS, ['%' . $query . '%'], self::class, $database, $numberPerPage); } } diff --git a/lib/Calibre/Tag.php b/lib/Calibre/Tag.php index b2fc526fe..6e02a8303 100644 --- a/lib/Calibre/Tag.php +++ b/lib/Calibre/Tag.php @@ -40,15 +40,15 @@ public function getEntryId() return self::PAGE_ID.":".$this->id; } - public static function getCount() + public static function getCount($database = null) { // str_format (localize("tags.alphabetical", count(array)) - return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL); + return parent::getCountGeneric(self::SQL_TABLE, self::PAGE_ID, self::PAGE_ALL, $database); } - public static function getTagById($tagId) + public static function getTagById($tagId, $database = null) { - $result = parent::getDb()->prepare('select id, name from tags where id = ?'); + $result = parent::getDb($database)->prepare('select id, name from tags where id = ?'); $result->execute([$tagId]); if ($post = $result->fetchObject()) { return new Tag($post); @@ -56,7 +56,7 @@ public static function getTagById($tagId) return null; } - public static function getAllTags() + public static function getAllTags($database = null, $numberPerPage = null) { global $config; @@ -66,7 +66,7 @@ public static function getAllTags() $sql = str_replace('tags.name', 'tags.' . $sortField, $sql); } - return Base::getEntryArrayWithBookNumber($sql, self::SQL_COLUMNS, [], self::class); + return Base::getEntryArrayWithBookNumber($sql, self::SQL_COLUMNS, [], self::class, $database, $numberPerPage); } public static function getAllTagsByQuery($query, $n, $database = null, $numberPerPage = null) @@ -82,7 +82,8 @@ public static function getAllTagsByQuery($query, $n, $database = null, $numberPe $tag->getEntryId(), str_format(localize("bookword", $post->count), $post->count), "text", - [ new LinkNavigation($tag->getUri())] + [ new LinkNavigation($tag->getUri())], + $database )); } return [$entryArray, $totalNumber]; diff --git a/lib/Model/Entry.php b/lib/Model/Entry.php index 01f192b48..83f8f8681 100644 --- a/lib/Model/Entry.php +++ b/lib/Model/Entry.php @@ -8,11 +8,9 @@ namespace SebLucas\Cops\Model; +use SebLucas\Cops\Output\Format; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\getUrlWithVersion; -use function SebLucas\Cops\Request\getURLParam; - class Entry { public $title; @@ -25,6 +23,7 @@ class Entry public $localUpdated; public $className; private static $updated = null; + protected $databaseId; public static $icons = [ Page::ALL_AUTHORS_ID => 'images/author.png', @@ -39,7 +38,7 @@ class Entry Page::ALL_PUBLISHERS_ID => 'images/publisher.png', ]; - public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pclass = "", $pcount = 0) + public function __construct($ptitle, $pid, $pcontent, $pcontentType = "text", $plinkArray = [], $database = null, $pclass = "", $pcount = 0) { global $config; $this->title = $ptitle; @@ -53,14 +52,14 @@ public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray if ($config['cops_show_icons'] == 1) { foreach (self::$icons as $reg => $image) { if (preg_match("/" . $reg . "/", $pid)) { - array_push($this->linkArray, new Link(getUrlWithVersion($image), "image/png", Link::OPDS_THUMBNAIL_TYPE)); + array_push($this->linkArray, new Link(Format::addVersion($image), "image/png", Link::OPDS_THUMBNAIL_TYPE)); break; } } } - if (!is_null(getURLParam('db'))) { - $this->id = str_replace("cops:", "cops:" . getURLParam('db') . ":", $this->id); + if (!is_null($database)) { + $this->id = str_replace("cops:", "cops:" . $database . ":", $this->id); } } diff --git a/lib/Model/EntryBook.php b/lib/Model/EntryBook.php index 54277e94d..342f6bdcf 100644 --- a/lib/Model/EntryBook.php +++ b/lib/Model/EntryBook.php @@ -25,7 +25,7 @@ class EntryBook extends Entry */ public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pbook) { - parent::__construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray); + parent::__construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pbook->getDatabaseId()); $this->book = $pbook; $this->localUpdated = $pbook->timestamp; } diff --git a/lib/Model/Link.php b/lib/Model/Link.php index c219da352..bcfa85e7c 100644 --- a/lib/Model/Link.php +++ b/lib/Model/Link.php @@ -8,9 +8,7 @@ namespace SebLucas\Cops\Model; -use SebLucas\Cops\Config; - -use function SebLucas\Cops\Request\getURLParam; +use SebLucas\Cops\Input\Config; class Link { @@ -51,7 +49,6 @@ public static function getScriptName() public static function getEndpointURL($endpoint = "index", $params = null, $database = null) { - $database ??= getURLParam('db'); if (!empty($database)) { $params ??= []; $params['db'] = $database; diff --git a/lib/Model/LinkFacet.php b/lib/Model/LinkFacet.php index 36b1a46bd..f54878bb7 100644 --- a/lib/Model/LinkFacet.php +++ b/lib/Model/LinkFacet.php @@ -12,10 +12,10 @@ class LinkFacet extends Link { - public function __construct($phref, $ptitle = null, $pfacetGroup = null, $pactiveFacet = false) + public function __construct($phref, $ptitle = null, $pfacetGroup = null, $pactiveFacet = false, $database = null) { parent::__construct($phref, Link::OPDS_PAGING_TYPE, "http://opds-spec.org/facet", $ptitle, $pfacetGroup, $pactiveFacet); - $this->href = Format::addDatabaseParam($this->href); + $this->href = Format::addDatabaseParam($this->href, $database); $this->href = parent::getScriptName() . $this->href; } } diff --git a/lib/Model/LinkNavigation.php b/lib/Model/LinkNavigation.php index 1b494aaa0..0068b04e6 100644 --- a/lib/Model/LinkNavigation.php +++ b/lib/Model/LinkNavigation.php @@ -12,10 +12,10 @@ class LinkNavigation extends Link { - public function __construct($phref, $prel = null, $ptitle = null) + public function __construct($phref, $prel = null, $ptitle = null, $database = null) { parent::__construct($phref, Link::OPDS_NAVIGATION_TYPE, $prel, $ptitle); - $this->href = Format::addDatabaseParam($this->href); + $this->href = Format::addDatabaseParam($this->href, $database); if (!preg_match("#^\?(.*)#", $this->href) && !empty($this->href)) { $this->href = "?" . $this->href; } diff --git a/lib/Output/EPubReader.php b/lib/Output/EPubReader.php index 686890f5e..162fa25f6 100644 --- a/lib/Output/EPubReader.php +++ b/lib/Output/EPubReader.php @@ -10,12 +10,12 @@ namespace SebLucas\Cops\Output; use SebLucas\Cops\Calibre\Book; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; +use SebLucas\Cops\Output\Format; use SebLucas\EPubMeta\EPub; use SebLucas\Template\doT; -use function SebLucas\Cops\Request\getURLParam; - /** * EPub Reader based on Monocle */ @@ -24,6 +24,13 @@ class EPubReader public static $endpoint = Config::ENDPOINT["epubfs"]; public static $template = "templates/epubreader.html"; + /** + * Summary of getComponentContent + * @param EPub $book + * @param string $component + * @param string $add + * @return string|null + */ public static function getComponentContent($book, $component, $add) { $data = $book->component($component); @@ -67,15 +74,15 @@ public static function getComponentContent($book, $component, $add) * Summary of getContent * @param integer $idData * @param string $component + * @param Request $request * @return string */ - public static function getContent($idData, $component) + public static function getContent($idData, $component, $request) { + /** @var Book */ $book = Book::getBookByDataId($idData); $add = 'data=' . $idData; - if (!is_null(getURLParam('db'))) { - $add .= '&db=' . getURLParam('db'); - } + $add = Format::addDatabaseParam($add, $book->getDatabaseId()); $epub = new EPub($book->getFilePath('EPUB', $idData)); $epub->initSpineComponent(); @@ -90,15 +97,14 @@ public static function getContent($idData, $component) /** * Summary of getReader * @param integer $idData + * @param Request $request * @return string */ - public static function getReader($idData) + public static function getReader($idData, $request) { $book = Book::getBookByDataId($idData); $add = 'data=' . $idData; - if (!is_null(getURLParam('db'))) { - $add .= '&db=' . getURLParam('db'); - } + $add = Format::addDatabaseParam($add, $book->getDatabaseId()); $epub = new EPub($book->getFilePath('EPUB', $idData)); $epub->initSpineComponent(); diff --git a/lib/Output/JSON_renderer.php b/lib/Output/JSON_renderer.php index e46ecc4cf..5c72221b8 100644 --- a/lib/Output/JSON_renderer.php +++ b/lib/Output/JSON_renderer.php @@ -11,17 +11,14 @@ use SebLucas\Cops\Calibre\Base; use SebLucas\Cops\Calibre\Book; use SebLucas\Cops\Calibre\Data; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Model\EntryBook; use SebLucas\Cops\Model\Link; use SebLucas\Cops\Model\LinkNavigation; use SebLucas\Cops\Output\Format; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\getQueryString; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\useServerSideRendering; - class JSONRenderer { public static $endpoint = Config::ENDPOINT["index"]; @@ -94,7 +91,7 @@ public static function getFullBookContentArray($book) { global $config; $out = self::getBookContentArray($book); - $database = getURLParam('db'); + $database = $book->getDatabaseId(); $out ["coverurl"] = Data::getLink($book, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", null)->hrefXhtml(); $out ["thumbnailurl"] = Data::getLink($book, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", null, null, $config['cops_html_thumbnail_height'] * 2)->hrefXhtml(); @@ -149,12 +146,13 @@ public static function getContentArray($entry) public static function getContentArrayTypeahead($page) { + /** @var Page $page */ $out = []; foreach ($page->entryArray as $entry) { if ($entry instanceof EntryBook) { array_push($out, ["class" => $entry->className, "title" => $entry->title, "navlink" => $entry->book->getDetailUrl()]); } else { - if (empty($entry->className) xor Base::noDatabaseSelected()) { + if (empty($entry->className) xor Base::noDatabaseSelected($page->getDatabaseId())) { array_push($out, ["class" => $entry->className, "title" => $entry->title, "navlink" => $entry->getNavLink()]); } else { array_push($out, ["class" => $entry->className, "title" => $entry->content, "navlink" => $entry->getNavLink()]); @@ -164,7 +162,7 @@ public static function getContentArrayTypeahead($page) return $out; } - public static function addCompleteArray($in) + public static function addCompleteArray($in, $request) { global $config; $out = $in; @@ -201,36 +199,41 @@ public static function addCompleteArray($in) "use_fancyapps" => $config ["cops_use_fancyapps"], "max_item_per_page" => $config['cops_max_item_per_page'], "kindleHack" => "", - "server_side_rendering" => useServerSideRendering(), + "server_side_rendering" => $request->render(), "html_tag_filter" => $config['cops_html_tag_filter']]]; if ($config['cops_thumbnail_handling'] == "1") { $out ["c"]["url"]["thumbnailUrl"] = $out ["c"]["url"]["coverUrl"]; } elseif (!empty($config['cops_thumbnail_handling'])) { $out ["c"]["url"]["thumbnailUrl"] = $config['cops_thumbnail_handling']; } - if (preg_match("/./", $_SERVER['HTTP_USER_AGENT'])) { + if (preg_match("/./", $request->agent())) { $out ["c"]["config"]["kindleHack"] = 'style="text-decoration: none !important;"'; } return $out; } - public static function getCurrentUrl($queryString = null) + public static function getCurrentUrl($queryString) { - $queryString ??= getQueryString(); return Config::ENDPOINT["json"] . '?' . Format::addURLParam($queryString, 'complete', 1); } - public static function getJson($complete = false) + /** + * Summary of getJson + * @param Request $request + * @param bool $complete + * @return array + */ + public static function getJson($request, $complete = false) { global $config; - $page = getURLParam("page", Page::INDEX); - $query = getURLParam("query"); - $search = getURLParam("search"); - $qid = getURLParam("id"); - $n = getURLParam("n", "1"); - $database = getURLParam('db'); + $page = $request->get("page", Page::INDEX); + $query = $request->get("query"); + $search = $request->get("search"); + $qid = $request->get("id"); + $n = $request->get("n", "1"); + $database = $request->get('db'); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); if ($search) { @@ -243,10 +246,14 @@ public static function getJson($complete = false) array_push($entries, self::getContentArray($entry)); } if (!is_null($currentPage->book)) { + // setting this on Book gets cascaded down to Data if isEpubValidOnKobo() + if ($config['cops_provide_kepub'] == "1" && preg_match("/Kobo/", $request->agent())) { + $currentPage->book->updateForKepub = true; + } $out ["book"] = self::getFullBookContentArray($currentPage->book); } - $out ["databaseId"] = getURLParam('db', ""); - $out ["databaseName"] = Base::getDbName(); + $out ["databaseId"] = $database ?? ""; + $out ["databaseName"] = Base::getDbName($database); if ($out ["databaseId"] == "") { $out ["databaseName"] = ""; } @@ -273,8 +280,8 @@ public static function getJson($complete = false) $out ["maxPage"] = $currentPage->getMaxPage(); $out ["currentPage"] = $currentPage->n; } - if (!is_null(getURLParam("complete")) || $complete) { - $out = self::addCompleteArray($out); + if (!is_null($request->get("complete")) || $complete) { + $out = self::addCompleteArray($out, $request); } $out ["containsBook"] = 0; diff --git a/lib/Output/OPDS_renderer.php b/lib/Output/OPDS_renderer.php index 20b27f562..1b45c10e1 100644 --- a/lib/Output/OPDS_renderer.php +++ b/lib/Output/OPDS_renderer.php @@ -8,7 +8,8 @@ namespace SebLucas\Cops\Output; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Model\EntryBook; use SebLucas\Cops\Model\Link; use SebLucas\Cops\Model\LinkFacet; @@ -17,14 +18,13 @@ use SebLucas\Cops\Pages\Page; use XMLWriter; -use function SebLucas\Cops\Request\getQueryString; -use function SebLucas\Cops\Request\getURLParam; - class OPDSRenderer { public static $endpoint = Config::ENDPOINT["feed"]; private $xmlStream = null; private $updated = null; + /** @var Request */ + protected $request; private function getUpdatedTime() { @@ -44,9 +44,15 @@ private function getXmlStream() return $this->xmlStream; } - public function getOpenSearch() + /** + * Summary of getOpenSearch + * @param Request $request + * @return string + */ + public function getOpenSearch($request) { global $config; + $database = $request->get('db'); $xml = new XMLWriter(); $xml->openMemory(); $xml->setIndent(true); @@ -74,7 +80,7 @@ public function getOpenSearch() $xml->startElement("Url"); $xml->writeAttribute("type", 'application/atom+xml'); $urlparam = "?query={searchTerms}"; - $urlparam = Format::addDatabaseParam($urlparam); + $urlparam = Format::addDatabaseParam($urlparam, $database); $urlparam = str_replace("%7B", "{", $urlparam); $urlparam = str_replace("%7D", "}", $urlparam); $xml->writeAttribute("template", $config['cops_full_url'] . self::$endpoint . $urlparam); @@ -88,9 +94,10 @@ public function getOpenSearch() return $xml->outputMemory(true); } - private function startXmlDocument($page) + private function startXmlDocument($page, $request) { global $config; + $database = $request->get('db'); self::getXmlStream()->startDocument('1.0', 'UTF-8'); self::getXmlStream()->startElement("feed"); self::getXmlStream()->writeAttribute("xmlns", "http://www.w3.org/2005/Atom"); @@ -109,8 +116,8 @@ private function startXmlDocument($page) self::getXmlStream()->startElement("id"); if ($page->idPage) { $idPage = $page->idPage; - if (!is_null(getURLParam('db'))) { - $idPage = str_replace("cops:", "cops:" . getURLParam('db') . ":", $idPage); + if (!is_null($request->get('db'))) { + $idPage = str_replace("cops:", "cops:" . $request->get('db') . ":", $idPage); } self::getXmlStream()->text($idPage); } else { @@ -136,11 +143,11 @@ private function startXmlDocument($page) self::getXmlStream()->endElement(); $link = new LinkNavigation("", "start", "Home"); self::renderLink($link); - $link = new LinkNavigation("?" . getQueryString(), "self"); + $link = new LinkNavigation("?" . $request->query(), "self"); self::renderLink($link); $urlparam = "?"; - $urlparam = Format::addDatabaseParam($urlparam); - if ($config['cops_generate_invalid_opds_stream'] == 0 || preg_match("/(MantanoReader|FBReader)/", $_SERVER['HTTP_USER_AGENT'])) { + $urlparam = Format::addDatabaseParam($urlparam, $database); + if ($config['cops_generate_invalid_opds_stream'] == 0 || preg_match("/(MantanoReader|FBReader)/", $request->agent())) { // Good and compliant way of handling search $urlparam = Format::addURLParam($urlparam, "page", Page::OPENSEARCH); $link = new Link(self::$endpoint . $urlparam, "application/opensearchdescription+xml", "search", "Search here"); @@ -153,9 +160,9 @@ private function startXmlDocument($page) } self::renderLink($link); if ($page->containsBook() && !is_null($config['cops_books_filter']) && count($config['cops_books_filter']) > 0) { - $Urlfilter = getURLParam("tag", ""); + $Urlfilter = $request->get("tag", ""); foreach ($config['cops_books_filter'] as $lib => $filter) { - $link = new LinkFacet("?" . Format::addURLParam(getQueryString(), "tag", $filter), $lib, localize("tagword.title"), $filter == $Urlfilter); + $link = new LinkFacet("?" . Format::addURLParam($request->query(), "tag", $filter), $lib, localize("tagword.title"), $filter == $Urlfilter, $database); self::renderLink($link); } } @@ -260,10 +267,16 @@ private function renderEntry($entry) } } - public function render($page) + /** + * Summary of render + * @param mixed $page + * @param Request $request + * @return string + */ + public function render($page, $request) { global $config; - self::startXmlDocument($page); + self::startXmlDocument($page, $request); if ($page->isPaginated()) { self::getXmlStream()->startElement("opensearch:totalResults"); self::getXmlStream()->text($page->totalNumber); diff --git a/lib/Output/RestApi.php b/lib/Output/RestApi.php index 43e3838ee..83bd068e5 100644 --- a/lib/Output/RestApi.php +++ b/lib/Output/RestApi.php @@ -10,12 +10,11 @@ namespace SebLucas\Cops\Output; use SebLucas\Cops\Calibre\CustomColumnType; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Pages\Page; use Exception; -use function SebLucas\Cops\Request\setURLParam; - /** * Basic REST API routing to JSON Renderer */ @@ -25,7 +24,7 @@ class RestApi /** * Summary of routes - * @var array + * @var array */ public static $routes = [ Page::INDEX => "/index", @@ -56,7 +55,7 @@ class RestApi /** * Summary of extra - * @var array + * @var array */ public static $extra = [ "/custom" => [self::class, 'getCustomColumns'], @@ -67,9 +66,10 @@ class RestApi /** * Summary of getPathInfo + * @param Request $request * @return string */ - public static function getPathInfo() + public static function getPathInfo($request) { return $_SERVER["PATH_INFO"] ?? "/index"; } @@ -77,16 +77,17 @@ public static function getPathInfo() /** * Summary of matchPathInfo * @param string $path + * @param Request $request * @throws Exception if the $path is not found in $routes or $extra * @return array|void */ - public static function matchPathInfo($path) + public static function matchPathInfo($path, $request) { $params = []; // handle extra functions if (array_key_exists($path, self::$extra)) { - echo json_encode(call_user_func(self::$extra[$path]), JSON_UNESCAPED_SLASHES); + echo json_encode(call_user_func(self::$extra[$path], $request), JSON_UNESCAPED_SLASHES); exit; } @@ -129,29 +130,33 @@ public static function matchPathInfo($path) /** * Summary of setParams * @param mixed $params - * @return void + * @param Request $request + * @return Request */ - public static function setParams($params) + public static function setParams($params, $request) { foreach ($params as $param => $value) { - setURLParam($param, $value); + $request->set($param, $value); } + return $request; } /** * Summary of getJson - * @return mixed + * @param Request $request + * @return array */ - public static function getJson() + public static function getJson($request) { - return JSONRenderer::getJson(); + return JSONRenderer::getJson($request); } /** * Summary of getScriptName + * @param Request $request * @return string */ - public static function getScriptName() + public static function getScriptName($request) { $script = explode("/", $_SERVER["SCRIPT_NAME"] ?? "/" . self::$endpoint); $link = array_pop($script); @@ -161,11 +166,12 @@ public static function getScriptName() /** * Summary of replaceLinks * @param string $output + * @param Request $request * @return string */ - public static function replaceLinks($output) + public static function replaceLinks($output, $request) { - $link = self::getScriptName(); + $link = self::getScriptName($request); $endpoint = $link; $search = []; @@ -201,30 +207,32 @@ public static function replaceLinks($output) /** * Summary of getOutput + * @param Request $request * @param mixed $result * @return string */ - public static function getOutput($result = null) + public static function getOutput($request, $result = null) { if (!isset($result)) { - $path = self::getPathInfo(); - $params = self::matchPathInfo($path); - self::setParams($params); - $result = self::getJson(); + $path = self::getPathInfo($request); + $params = self::matchPathInfo($path, $request); + $request = self::setParams($params, $request); + $result = self::getJson($request); } $output = json_encode($result); - return self::replaceLinks($output); + return self::replaceLinks($output, $request); } /** * Summary of getCustomColumns + * @param Request $request * @return array */ - public static function getCustomColumns() + public static function getCustomColumns($request) { $columns = CustomColumnType::getAllCustomColumns(); - $endpoint = self::getScriptName(); + $endpoint = self::getScriptName($request); $result = ["title" => "Custom Columns", "entries" => []]; foreach ($columns as $title => $column) { $column["navlink"] = $endpoint . "/custom/" . $column["id"]; @@ -235,9 +243,10 @@ public static function getCustomColumns() /** * Summary of getDatabases + * @param Request $request * @return array */ - public static function getDatabases() + public static function getDatabases($request) { global $config; @@ -252,9 +261,10 @@ public static function getDatabases() /** * Summary of getOpenApi + * @param Request $request * @return array */ - public static function getOpenApi() + public static function getOpenApi($request) { $result = ["openapi" => "3.1.0", "info" => ["title" => "COPS REST API", "version" => "1.0.0"], "paths" => []]; return $result; @@ -262,9 +272,10 @@ public static function getOpenApi() /** * Summary of getRoutes + * @param Request $request * @return array */ - public static function getRoutes() + public static function getRoutes($request) { $result = ["title" => "Routes", "entries" => []]; foreach (self::$routes as $page => $route) { diff --git a/lib/Pages/Page.php b/lib/Pages/Page.php index b8e93a08f..139f229c6 100644 --- a/lib/Pages/Page.php +++ b/lib/Pages/Page.php @@ -17,13 +17,11 @@ use SebLucas\Cops\Calibre\Rating; use SebLucas\Cops\Calibre\Serie; use SebLucas\Cops\Calibre\Tag; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Model\Entry; use SebLucas\Cops\Model\EntryBook; use SebLucas\Cops\Model\LinkNavigation; -use function SebLucas\Cops\Request\getCurrentOption; -use function SebLucas\Cops\Request\getQueryString; - class Page { public const INDEX = "index"; @@ -77,79 +75,118 @@ class Page /** @var Entry[] */ public $entryArray = []; - public static function getPage($pageId, $id, $query, $n) + /** @var Request */ + protected $request = null; + protected $numberPerPage = -1; + protected $ignoredCategories = []; + protected $databaseId = null; + + public static function getPageForRequest($request) + { + $page = $request->get("page", Page::INDEX); + $query = $request->get("query"); + $id = $request->get("id"); + $n = $request->get("n", "1"); + return self::getPage($page, $id, $query, $n); + } + + public static function getPage($pageId, $id, $query, $n, $request = null) { switch ($pageId) { case Page::ALL_AUTHORS : - return new PageAllAuthors($id, $query, $n); + return new PageAllAuthors($id, $query, $n, $request); case Page::AUTHORS_FIRST_LETTER : - return new PageAllAuthorsLetter($id, $query, $n); + return new PageAllAuthorsLetter($id, $query, $n, $request); case Page::AUTHOR_DETAIL : - return new PageAuthorDetail($id, $query, $n); + return new PageAuthorDetail($id, $query, $n, $request); case Page::ALL_TAGS : - return new PageAllTags($id, $query, $n); + return new PageAllTags($id, $query, $n, $request); case Page::TAG_DETAIL : - return new PageTagDetail($id, $query, $n); + return new PageTagDetail($id, $query, $n, $request); case Page::ALL_LANGUAGES : - return new PageAllLanguages($id, $query, $n); + return new PageAllLanguages($id, $query, $n, $request); case Page::LANGUAGE_DETAIL : - return new PageLanguageDetail($id, $query, $n); + return new PageLanguageDetail($id, $query, $n, $request); case Page::ALL_CUSTOMS : - return new PageAllCustoms($id, $query, $n); + return new PageAllCustoms($id, $query, $n, $request); case Page::CUSTOM_DETAIL : - return new PageCustomDetail($id, $query, $n); + return new PageCustomDetail($id, $query, $n, $request); case Page::ALL_RATINGS : - return new PageAllRating($id, $query, $n); + return new PageAllRating($id, $query, $n, $request); case Page::RATING_DETAIL : - return new PageRatingDetail($id, $query, $n); + return new PageRatingDetail($id, $query, $n, $request); case Page::ALL_SERIES : - return new PageAllSeries($id, $query, $n); + return new PageAllSeries($id, $query, $n, $request); case Page::ALL_BOOKS : - return new PageAllBooks($id, $query, $n); + return new PageAllBooks($id, $query, $n, $request); case Page::ALL_BOOKS_LETTER: - return new PageAllBooksLetter($id, $query, $n); + return new PageAllBooksLetter($id, $query, $n, $request); case Page::ALL_RECENT_BOOKS : - return new PageRecentBooks($id, $query, $n); + return new PageRecentBooks($id, $query, $n, $request); case Page::SERIE_DETAIL : - return new PageSerieDetail($id, $query, $n); + return new PageSerieDetail($id, $query, $n, $request); case Page::OPENSEARCH_QUERY : - return new PageQueryResult($id, $query, $n); + return new PageQueryResult($id, $query, $n, $request); case Page::BOOK_DETAIL : - return new PageBookDetail($id, $query, $n); + return new PageBookDetail($id, $query, $n, $request); case Page::ALL_PUBLISHERS: - return new PageAllPublishers($id, $query, $n); + return new PageAllPublishers($id, $query, $n, $request); case Page::PUBLISHER_DETAIL : - return new PagePublisherDetail($id, $query, $n); + return new PagePublisherDetail($id, $query, $n, $request); case Page::ABOUT : - return new PageAbout($id, $query, $n); + return new PageAbout($id, $query, $n, $request); case Page::CUSTOMIZE : - return new PageCustomize($id, $query, $n); + return new PageCustomize($id, $query, $n, $request); default: - $page = new Page($id, $query, $n); + $page = new Page($id, $query, $n, $request); $page->idPage = "cops:catalog"; return $page; } } - public function __construct($pid, $pquery, $pn) + public function __construct($pid, $pquery, $pn, $request = null) { global $config; $this->idGet = $pid; $this->query = $pquery; $this->n = $pn; + $this->setRequest($request ?? new Request()); $this->favicon = $config['cops_icon']; $this->authorName = $config['cops_author_name'] ?: 'Sébastien Lucas'; $this->authorUri = $config['cops_author_uri'] ?: 'http://blog.slucas.fr'; $this->authorEmail = $config['cops_author_email'] ?: 'sebastien@slucas.fr'; } + public function setRequest($request) + { + $this->request = $request; + $this->numberPerPage = $this->request->option("max_item_per_page"); + $this->ignoredCategories = $this->request->option('ignored_categories'); + $this->databaseId = $this->request->get('db'); + } + + public function getNumberPerPage() + { + return $this->numberPerPage; + } + + public function getIgnoredCategories() + { + return $this->ignoredCategories; + } + + public function getDatabaseId() + { + return $this->databaseId; + } + public function InitializeContent() { global $config; $this->title = $config['cops_title_default']; $this->subtitle = $config['cops_subtitle_default']; - if (Base::noDatabaseSelected()) { + if (Base::noDatabaseSelected($this->databaseId)) { $i = 0; foreach (Base::getDbNameList() as $key) { $nBooks = Book::getBookCount($i); @@ -159,6 +196,7 @@ public function InitializeContent() str_format(localize("bookword", $nBooks), $nBooks), "text", [ new LinkNavigation("?db={$i}")], + null, "", $nBooks )); @@ -166,34 +204,34 @@ public function InitializeContent() Base::clearDb(); } } else { - if (!in_array(PageQueryResult::SCOPE_AUTHOR, getCurrentOption('ignored_categories'))) { + if (!in_array(PageQueryResult::SCOPE_AUTHOR, $this->ignoredCategories)) { array_push($this->entryArray, Author::getCount()); } - if (!in_array(PageQueryResult::SCOPE_SERIES, getCurrentOption('ignored_categories'))) { + if (!in_array(PageQueryResult::SCOPE_SERIES, $this->ignoredCategories)) { $series = Serie::getCount(); if (!is_null($series)) { array_push($this->entryArray, $series); } } - if (!in_array(PageQueryResult::SCOPE_PUBLISHER, getCurrentOption('ignored_categories'))) { + if (!in_array(PageQueryResult::SCOPE_PUBLISHER, $this->ignoredCategories)) { $publisher = Publisher::getCount(); if (!is_null($publisher)) { array_push($this->entryArray, $publisher); } } - if (!in_array(PageQueryResult::SCOPE_TAG, getCurrentOption('ignored_categories'))) { + if (!in_array(PageQueryResult::SCOPE_TAG, $this->ignoredCategories)) { $tags = Tag::getCount(); if (!is_null($tags)) { array_push($this->entryArray, $tags); } } - if (!in_array(PageQueryResult::SCOPE_RATING, getCurrentOption('ignored_categories'))) { + if (!in_array(PageQueryResult::SCOPE_RATING, $this->ignoredCategories)) { $rating = Rating::getCount(); if (!is_null($rating)) { array_push($this->entryArray, $rating); } } - if (!in_array("language", getCurrentOption('ignored_categories'))) { + if (!in_array("language", $this->ignoredCategories)) { $languages = Language::getCount(); if (!is_null($languages)) { array_push($this->entryArray, $languages); @@ -201,30 +239,30 @@ public function InitializeContent() } $config['cops_calibre_custom_column'] = CustomColumnType::checkCustomColumnList($config['cops_calibre_custom_column']); foreach ($config['cops_calibre_custom_column'] as $lookup) { - $customColumn = CustomColumnType::createByLookup($lookup); + $customColumn = CustomColumnType::createByLookup($lookup, $this->getDatabaseId()); if (!is_null($customColumn) && $customColumn->isSearchable()) { array_push($this->entryArray, $customColumn->getCount()); } } - $this->entryArray = array_merge($this->entryArray, Book::getCount()); + $this->entryArray = array_merge($this->entryArray, Book::getCount($this->getDatabaseId())); if (Base::isMultipleDatabaseEnabled()) { - $this->title = Base::getDbName(); + $this->title = Base::getDbName($this->getDatabaseId()); } } } public function isPaginated() { - return (getCurrentOption("max_item_per_page") != -1 && + return ($this->getNumberPerPage() != -1 && $this->totalNumber != -1 && - $this->totalNumber > getCurrentOption("max_item_per_page")); + $this->totalNumber > $this->getNumberPerPage()); } public function getNextLink() { - $currentUrl = preg_replace("/\&n=.*?$/", "", "?" . getQueryString()); - if (($this->n) * getCurrentOption("max_item_per_page") < $this->totalNumber) { + $currentUrl = preg_replace("/\&n=.*?$/", "", "?" . $this->request->query()); + if (($this->n) * $this->getNumberPerPage() < $this->totalNumber) { return new LinkNavigation($currentUrl . "&n=" . ($this->n + 1), "next", localize("paging.next.alternate")); } return null; @@ -232,7 +270,7 @@ public function getNextLink() public function getPrevLink() { - $currentUrl = preg_replace("/\&n=.*?$/", "", "?" . getQueryString()); + $currentUrl = preg_replace("/\&n=.*?$/", "", "?" . $this->request->query()); if ($this->n > 1) { return new LinkNavigation($currentUrl . "&n=" . ($this->n - 1), "previous", localize("paging.previous.alternate")); } @@ -241,7 +279,7 @@ public function getPrevLink() public function getMaxPage() { - return ceil($this->totalNumber / getCurrentOption("max_item_per_page")); + return ceil($this->totalNumber / $this->numberPerPage); } public function containsBook() diff --git a/lib/Pages/PageAllAuthors.php b/lib/Pages/PageAllAuthors.php index 3679d7111..9ebe57735 100644 --- a/lib/Pages/PageAllAuthors.php +++ b/lib/Pages/PageAllAuthors.php @@ -10,17 +10,15 @@ use SebLucas\Cops\Calibre\Author; -use function SebLucas\Cops\Request\getCurrentOption; - class PageAllAuthors extends Page { public function InitializeContent() { $this->title = localize("authors.title"); - if (getCurrentOption("author_split_first_letter") == 1) { - $this->entryArray = Author::getAllAuthorsByFirstLetter(); + if ($this->request->option("author_split_first_letter") == 1) { + $this->entryArray = Author::getAllAuthorsByFirstLetter($this->getDatabaseId()); } else { - $this->entryArray = Author::getAllAuthors(); + $this->entryArray = Author::getAllAuthors($this->getDatabaseId()); } $this->idPage = Author::PAGE_ID; } diff --git a/lib/Pages/PageAllAuthorsLetter.php b/lib/Pages/PageAllAuthorsLetter.php index 2198a4262..f8fb87b36 100644 --- a/lib/Pages/PageAllAuthorsLetter.php +++ b/lib/Pages/PageAllAuthorsLetter.php @@ -15,7 +15,7 @@ class PageAllAuthorsLetter extends Page public function InitializeContent() { $this->idPage = Author::getEntryIdByLetter($this->idGet); - $this->entryArray = Author::getAuthorsByStartingLetter($this->idGet); + $this->entryArray = Author::getAuthorsByStartingLetter($this->idGet, $this->getDatabaseId()); $this->title = str_format(localize("splitByLetter.letter"), str_format(localize("authorword", count($this->entryArray)), count($this->entryArray)), $this->idGet); } } diff --git a/lib/Pages/PageAllBooks.php b/lib/Pages/PageAllBooks.php index 8e457d79c..825bdac98 100644 --- a/lib/Pages/PageAllBooks.php +++ b/lib/Pages/PageAllBooks.php @@ -10,17 +10,15 @@ use SebLucas\Cops\Calibre\Book; -use function SebLucas\Cops\Request\getCurrentOption; - class PageAllBooks extends Page { public function InitializeContent() { $this->title = localize("allbooks.title"); - if (getCurrentOption("titles_split_first_letter") == 1) { - $this->entryArray = Book::getAllBooks(); + if ($this->request->option("titles_split_first_letter") == 1) { + $this->entryArray = Book::getAllBooks($this->getDatabaseId(), $this->request); } else { - [$this->entryArray, $this->totalNumber] = Book::getBooks($this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooks($this->n, $this->getDatabaseId(), $this->getNumberPerPage()); } $this->idPage = Book::PAGE_ID; } diff --git a/lib/Pages/PageAllBooksLetter.php b/lib/Pages/PageAllBooksLetter.php index f50858fd0..8904f2774 100644 --- a/lib/Pages/PageAllBooksLetter.php +++ b/lib/Pages/PageAllBooksLetter.php @@ -14,7 +14,7 @@ class PageAllBooksLetter extends Page { public function InitializeContent() { - [$this->entryArray, $this->totalNumber] = Book::getBooksByStartingLetter($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByStartingLetter($this->idGet, $this->n, $this->getDatabaseId()); $this->idPage = Book::getEntryIdByLetter($this->idGet); $count = $this->totalNumber; diff --git a/lib/Pages/PageAllCustoms.php b/lib/Pages/PageAllCustoms.php index 9b3ccef09..9ad71e2d6 100644 --- a/lib/Pages/PageAllCustoms.php +++ b/lib/Pages/PageAllCustoms.php @@ -10,14 +10,12 @@ use SebLucas\Cops\Calibre\CustomColumnType; -use function SebLucas\Cops\Request\getURLParam; - class PageAllCustoms extends Page { public function InitializeContent() { - $customId = getURLParam("custom", null); - $columnType = CustomColumnType::createByCustomID($customId); + $customId = $this->request->get("custom", null); + $columnType = CustomColumnType::createByCustomID($customId, $this->getDatabaseId()); $this->title = $columnType->getTitle(); $this->entryArray = $columnType->getAllCustomValues(); diff --git a/lib/Pages/PageAllLanguages.php b/lib/Pages/PageAllLanguages.php index 72bf04694..c31d5f7db 100644 --- a/lib/Pages/PageAllLanguages.php +++ b/lib/Pages/PageAllLanguages.php @@ -15,7 +15,7 @@ class PageAllLanguages extends Page public function InitializeContent() { $this->title = localize("languages.title"); - $this->entryArray = Language::getAllLanguages(); + $this->entryArray = Language::getAllLanguages($this->getDatabaseId()); $this->idPage = Language::PAGE_ID; } } diff --git a/lib/Pages/PageAllPublishers.php b/lib/Pages/PageAllPublishers.php index 929e09e05..5f9855d5c 100644 --- a/lib/Pages/PageAllPublishers.php +++ b/lib/Pages/PageAllPublishers.php @@ -15,7 +15,7 @@ class PageAllPublishers extends Page public function InitializeContent() { $this->title = localize("publishers.title"); - $this->entryArray = Publisher::getAllPublishers(); + $this->entryArray = Publisher::getAllPublishers($this->getDatabaseId()); $this->idPage = Publisher::PAGE_ID; } } diff --git a/lib/Pages/PageAllRating.php b/lib/Pages/PageAllRating.php index ed1967b33..d7930edf5 100644 --- a/lib/Pages/PageAllRating.php +++ b/lib/Pages/PageAllRating.php @@ -15,7 +15,7 @@ class PageAllRating extends Page public function InitializeContent() { $this->title = localize("ratings.title"); - $this->entryArray = Rating::getAllRatings(); + $this->entryArray = Rating::getAllRatings($this->getDatabaseId()); $this->idPage = Rating::PAGE_ID; } } diff --git a/lib/Pages/PageAllSeries.php b/lib/Pages/PageAllSeries.php index bdf35c509..66e8f7279 100644 --- a/lib/Pages/PageAllSeries.php +++ b/lib/Pages/PageAllSeries.php @@ -15,7 +15,7 @@ class PageAllSeries extends Page public function InitializeContent() { $this->title = localize("series.title"); - $this->entryArray = Serie::getAllSeries(); + $this->entryArray = Serie::getAllSeries($this->getDatabaseId()); $this->idPage = Serie::PAGE_ID; } } diff --git a/lib/Pages/PageAllTags.php b/lib/Pages/PageAllTags.php index 500bac86a..1aebe8c59 100644 --- a/lib/Pages/PageAllTags.php +++ b/lib/Pages/PageAllTags.php @@ -15,7 +15,7 @@ class PageAllTags extends Page public function InitializeContent() { $this->title = localize("tags.title"); - $this->entryArray = Tag::getAllTags(); + $this->entryArray = Tag::getAllTags($this->getDatabaseId()); $this->idPage = Tag::PAGE_ID; } } diff --git a/lib/Pages/PageAuthorDetail.php b/lib/Pages/PageAuthorDetail.php index c60eb51ea..90ffc518a 100644 --- a/lib/Pages/PageAuthorDetail.php +++ b/lib/Pages/PageAuthorDetail.php @@ -15,9 +15,9 @@ class PageAuthorDetail extends Page { public function InitializeContent() { - $author = Author::getAuthorById($this->idGet); + $author = Author::getAuthorById($this->idGet, $this->getDatabaseId()); $this->idPage = $author->getEntryId(); $this->title = $author->name; - [$this->entryArray, $this->totalNumber] = Book::getBooksByAuthor($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByAuthor($this->idGet, $this->n, $this->getDatabaseId()); } } diff --git a/lib/Pages/PageBookDetail.php b/lib/Pages/PageBookDetail.php index 1ef64e714..4d4eae7ee 100644 --- a/lib/Pages/PageBookDetail.php +++ b/lib/Pages/PageBookDetail.php @@ -14,7 +14,7 @@ class PageBookDetail extends Page { public function InitializeContent() { - $this->book = Book::getBookById($this->idGet); + $this->book = Book::getBookById($this->idGet, $this->getDatabaseId()); $this->title = $this->book->title; } } diff --git a/lib/Pages/PageCustomDetail.php b/lib/Pages/PageCustomDetail.php index 91b5d53a4..f04216952 100644 --- a/lib/Pages/PageCustomDetail.php +++ b/lib/Pages/PageCustomDetail.php @@ -10,17 +10,16 @@ use SebLucas\Cops\Calibre\Book; use SebLucas\Cops\Calibre\CustomColumn; - -use function SebLucas\Cops\Request\getURLParam; +use SebLucas\Cops\Request; class PageCustomDetail extends Page { public function InitializeContent() { - $customId = getURLParam("custom", null); - $custom = CustomColumn::createCustom($customId, $this->idGet); + $customId = $this->request->get("custom", null); + $custom = CustomColumn::createCustom($customId, $this->idGet, $this->getDatabaseId()); $this->idPage = $custom->getEntryId(); $this->title = $custom->value; - [$this->entryArray, $this->totalNumber] = Book::getBooksByCustom($custom, $this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByCustom($custom, $this->idGet, $this->n, $this->getDatabaseId()); } } diff --git a/lib/Pages/PageCustomize.php b/lib/Pages/PageCustomize.php index b8852641f..f9ae86ceb 100644 --- a/lib/Pages/PageCustomize.php +++ b/lib/Pages/PageCustomize.php @@ -10,16 +10,11 @@ use SebLucas\Cops\Model\Entry; -use function SebLucas\Cops\Request\useServerSideRendering; - -use function SebLucas\Cops\Request\getCurrentOption; -use function SebLucas\Cops\Request\getCurrentTemplate; - class PageCustomize extends Page { private function isChecked($key, $testedValue = 1) { - $value = getCurrentOption($key); + $value = $this->request->option($key); if (is_array($value)) { if (in_array($testedValue, $value)) { return "checked='checked'"; @@ -34,7 +29,7 @@ private function isChecked($key, $testedValue = 1) private function isSelected($key, $value) { - if (getCurrentOption($key) == $value) { + if ($this->request->option($key) == $value) { return "selected='selected'"; } return ""; @@ -54,7 +49,7 @@ private function getTemplateList() private function getStyleList() { $result = []; - foreach (glob("templates/" . getCurrentTemplate() . "/styles/style-*.css") as $filename) { + foreach (glob("templates/" . $this->request->template() . "/styles/style-*.css") as $filename) { if (preg_match('/styles\/style-(.*?)\.css/', $filename, $m)) { array_push($result, $m [1]); } @@ -74,8 +69,9 @@ public function InitializeContent() PageQueryResult::SCOPE_RATING, "language"]; + $database = $this->getDatabaseId(); $content = ""; - if (!preg_match("/(Kobo|Kindle\/3.0|EBRD1101)/", $_SERVER['HTTP_USER_AGENT'])) { + if (!preg_match("/(Kobo|Kindle\/3.0|EBRD1101)/", $this->request->agent())) { $content .= "'; foreach ($this-> getStyleList() as $filename) { $content .= ""; @@ -112,33 +109,37 @@ public function InitializeContent() "", $content, "text", - [] + [], + $database )); - if (!useServerSideRendering()) { + if (!$this->request->render()) { $content = 'isChecked("use_fancyapps") . ' />'; array_push($this->entryArray, new Entry( localize("customize.fancybox"), "", $content, "text", - [] + [], + $database )); } - $content = ''; + $content = ''; array_push($this->entryArray, new Entry( localize("customize.paging"), "", $content, "text", - [] + [], + $database )); - $content = ''; + $content = ''; array_push($this->entryArray, new Entry( localize("customize.email"), "", $content, "text", - [] + [], + $database )); $content = 'isChecked("html_tag_filter") . ' />'; array_push($this->entryArray, new Entry( @@ -146,7 +147,8 @@ public function InitializeContent() "", $content, "text", - [] + [], + $database )); $content = ""; foreach ($ignoredBaseArray as $key) { @@ -159,7 +161,8 @@ public function InitializeContent() "", $content, "text", - [] + [], + $database )); } } diff --git a/lib/Pages/PageLanguageDetail.php b/lib/Pages/PageLanguageDetail.php index 08fcfae3b..b1fdef506 100644 --- a/lib/Pages/PageLanguageDetail.php +++ b/lib/Pages/PageLanguageDetail.php @@ -15,9 +15,9 @@ class PageLanguageDetail extends Page { public function InitializeContent() { - $language = Language::getLanguageById($this->idGet); + $language = Language::getLanguageById($this->idGet, $this->getDatabaseId()); $this->idPage = $language->getEntryId(); $this->title = $language->lang_code; - [$this->entryArray, $this->totalNumber] = Book::getBooksByLanguage($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByLanguage($this->idGet, $this->n, $this->getDatabaseId()); } } diff --git a/lib/Pages/PagePublisherDetail.php b/lib/Pages/PagePublisherDetail.php index 8f576d456..fb5331717 100644 --- a/lib/Pages/PagePublisherDetail.php +++ b/lib/Pages/PagePublisherDetail.php @@ -15,9 +15,9 @@ class PagePublisherDetail extends Page { public function InitializeContent() { - $publisher = Publisher::getPublisherById($this->idGet); + $publisher = Publisher::getPublisherById($this->idGet, $this->getDatabaseId()); $this->title = $publisher->name; - [$this->entryArray, $this->totalNumber] = Book::getBooksByPublisher($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByPublisher($this->idGet, $this->n, $this->getDatabaseId()); $this->idPage = $publisher->getEntryId(); } } diff --git a/lib/Pages/PageQueryResult.php b/lib/Pages/PageQueryResult.php index 6605d3e0f..dccd019a3 100644 --- a/lib/Pages/PageQueryResult.php +++ b/lib/Pages/PageQueryResult.php @@ -18,9 +18,6 @@ use SebLucas\Cops\Model\Entry; use SebLucas\Cops\Model\LinkNavigation; -use function SebLucas\Cops\Request\getCurrentOption; -use function SebLucas\Cops\Request\getURLParam; - class PageQueryResult extends Page { public const SCOPE_TAG = "tag"; @@ -32,10 +29,10 @@ class PageQueryResult extends Page private function useTypeahead() { - return !is_null(getURLParam("search")); + return !is_null($this->request->get("search")); } - private function searchByScope($scope, $limit = false) + private function searchByScope($scope, $limit = false, $database = null) { $n = $this->n; $numberPerPage = null; @@ -49,51 +46,52 @@ private function searchByScope($scope, $limit = false) } switch ($scope) { case self::SCOPE_BOOK : - $array = Book::getBooksByStartingLetter('%' . $queryNormedAndUp, $n, null, $numberPerPage); + $array = Book::getBooksByStartingLetter('%' . $queryNormedAndUp, $n, $database, $numberPerPage); break; case self::SCOPE_AUTHOR : - $array = Author::getAuthorsForSearch('%' . $queryNormedAndUp); + $array = Author::getAuthorsForSearch('%' . $queryNormedAndUp, $database); break; case self::SCOPE_SERIES : - $array = Serie::getAllSeriesByQuery($queryNormedAndUp); + $array = Serie::getAllSeriesByQuery($queryNormedAndUp, $database); break; case self::SCOPE_TAG : - $array = Tag::getAllTagsByQuery($queryNormedAndUp, $n, null, $numberPerPage); + $array = Tag::getAllTagsByQuery($queryNormedAndUp, $n, $database, $numberPerPage); break; case self::SCOPE_PUBLISHER : - $array = Publisher::getAllPublishersByQuery($queryNormedAndUp); + $array = Publisher::getAllPublishersByQuery($queryNormedAndUp, $database); break; default: $array = Book::getBooksByQuery( ["all" => "%" . $queryNormedAndUp . "%"], - $n + $n, + $database ); } return $array; } - public function doSearchByCategory() + public function doSearchByCategory($database = null) { - $database = getURLParam('db'); $out = []; $pagequery = Page::OPENSEARCH_QUERY; $dbArray = [""]; $d = $database; $query = $this->query; // Special case when no databases were chosen, we search on all databases - if (Base::noDatabaseSelected()) { + if (Base::noDatabaseSelected($database)) { $dbArray = Base::getDbNameList(); $d = 0; } foreach ($dbArray as $key) { - if (Base::noDatabaseSelected()) { + if (Base::noDatabaseSelected($database)) { array_push($this->entryArray, new Entry( $key, "db:query:{$d}", " ", "text", [ new LinkNavigation("?db={$d}")], + null, "tt-header" )); Base::getDb($d); @@ -103,10 +101,10 @@ public function doSearchByCategory() PageQueryResult::SCOPE_SERIES, PageQueryResult::SCOPE_TAG, PageQueryResult::SCOPE_PUBLISHER] as $key) { - if (in_array($key, getCurrentOption('ignored_categories'))) { + if (in_array($key, $this->getIgnoredCategories())) { continue; } - $array = $this->searchByScope($key, true); + $array = $this->searchByScope($key, true, $database); $i = 0; if (count($array) == 2 && is_array($array [0])) { @@ -128,11 +126,12 @@ public function doSearchByCategory() str_format(localize("{$key}word", $total), $total), "text", [ new LinkNavigation("?page={$pagequery}&query={$query}&db={$d}&scope={$key}")], - Base::noDatabaseSelected() ? "" : "tt-header", + $database, + Base::noDatabaseSelected($database) ? "" : "tt-header", $total )); } - if (!Base::noDatabaseSelected() && $this->useTypeahead()) { + if (!Base::noDatabaseSelected($database) && $this->useTypeahead()) { foreach ($array as $entry) { array_push($this->entryArray, $entry); $i++; @@ -143,7 +142,7 @@ public function doSearchByCategory() } } $d++; - if (Base::noDatabaseSelected()) { + if (Base::noDatabaseSelected($database)) { Base::clearDb(); } } @@ -152,7 +151,8 @@ public function doSearchByCategory() public function InitializeContent() { - $scope = getURLParam("scope"); + $scope = $this->request->get("scope"); + $ignoredCategories = $this->getIgnoredCategories(); if (empty($scope)) { $this->title = str_format(localize("search.result"), $this->query); } else { @@ -164,21 +164,23 @@ public function InitializeContent() // str_format (localize ("search.result.publisher"), $this->query) $this->title = str_format(localize("search.result.{$scope}"), $this->query); } + $database = $this->getDatabaseId(); $crit = "%" . $this->query . "%"; // Special case when we are doing a search and no database is selected - if (Base::noDatabaseSelected() && !$this->useTypeahead()) { + if (Base::noDatabaseSelected($database) && !$this->useTypeahead()) { $i = 0; foreach (Base::getDbNameList() as $key) { Base::clearDb(); - [$array, $totalNumber] = Book::getBooksByQuery(["all" => $crit], 1, $i, 1); + [$array, $totalNumber] = Book::getBooksByQuery(["all" => $crit], 1, $i, 1, $ignoredCategories); array_push($this->entryArray, new Entry( $key, "db:query:{$i}", str_format(localize("bookword", $totalNumber), $totalNumber), "text", [ new LinkNavigation("?db={$i}&page=9&query=" . $this->query)], + $database, "", $totalNumber )); @@ -187,11 +189,11 @@ public function InitializeContent() return; } if (empty($scope)) { - $this->doSearchByCategory(); + $this->doSearchByCategory($database); return; } - $array = $this->searchByScope($scope); + $array = $this->searchByScope($scope, false, $database); if (count($array) == 2 && is_array($array [0])) { [$this->entryArray, $this->totalNumber] = $array; } else { diff --git a/lib/Pages/PageRatingDetail.php b/lib/Pages/PageRatingDetail.php index df6d4d569..58c5fa8d0 100644 --- a/lib/Pages/PageRatingDetail.php +++ b/lib/Pages/PageRatingDetail.php @@ -15,9 +15,9 @@ class PageRatingDetail extends Page { public function InitializeContent() { - $rating = Rating::getRatingById($this->idGet); + $rating = Rating::getRatingById($this->idGet, $this->getDatabaseId()); $this->idPage = $rating->getEntryId(); $this->title =str_format(localize("ratingword", $rating->name/2), $rating->name/2); - [$this->entryArray, $this->totalNumber] = Book::getBooksByRating($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByRating($this->idGet, $this->n, $this->getDatabaseId()); } } diff --git a/lib/Pages/PageRecentBooks.php b/lib/Pages/PageRecentBooks.php index 49982dea7..c2bb94bcf 100644 --- a/lib/Pages/PageRecentBooks.php +++ b/lib/Pages/PageRecentBooks.php @@ -15,7 +15,7 @@ class PageRecentBooks extends Page public function InitializeContent() { $this->title = localize("recent.title"); - $this->entryArray = Book::getAllRecentBooks(); + $this->entryArray = Book::getAllRecentBooks($this->getDatabaseId(), $this->getNumberPerPage(), $this->request); $this->idPage = parent::ALL_RECENT_BOOKS_ID; } } diff --git a/lib/Pages/PageSerieDetail.php b/lib/Pages/PageSerieDetail.php index 8327c35d7..4893af6f8 100644 --- a/lib/Pages/PageSerieDetail.php +++ b/lib/Pages/PageSerieDetail.php @@ -15,9 +15,9 @@ class PageSerieDetail extends Page { public function InitializeContent() { - $serie = Serie::getSerieById($this->idGet); + $serie = Serie::getSerieById($this->idGet, $this->getDatabaseId()); $this->title = $serie->name; - [$this->entryArray, $this->totalNumber] = Book::getBooksBySeries($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksBySeries($this->idGet, $this->n, $this->getDatabaseId()); $this->idPage = $serie->getEntryId(); } } diff --git a/lib/Pages/PageTagDetail.php b/lib/Pages/PageTagDetail.php index 53ebe0991..2dc555d1b 100644 --- a/lib/Pages/PageTagDetail.php +++ b/lib/Pages/PageTagDetail.php @@ -15,9 +15,9 @@ class PageTagDetail extends Page { public function InitializeContent() { - $tag = Tag::getTagById($this->idGet); + $tag = Tag::getTagById($this->idGet, $this->getDatabaseId()); $this->idPage = $tag->getEntryId(); $this->title = $tag->name; - [$this->entryArray, $this->totalNumber] = Book::getBooksByTag($this->idGet, $this->n); + [$this->entryArray, $this->totalNumber] = Book::getBooksByTag($this->idGet, $this->n, $this->getDatabaseId()); } } diff --git a/restapi.php b/restapi.php index 4c58886db..47dbfcfa4 100644 --- a/restapi.php +++ b/restapi.php @@ -8,6 +8,7 @@ * */ +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\RestApi; require_once dirname(__FILE__) . '/config.php'; @@ -17,12 +18,14 @@ $config['cops_author_split_first_letter'] = '0'; $config['cops_titles_split_first_letter'] = '0'; +$request = new Request(); + header('Content-Type:application/json;charset=utf-8'); -$path = RestApi::getPathInfo(); -$params = RestApi::matchPathInfo($path); -RestApi::setParams($params); +$path = RestApi::getPathInfo($request); +$params = RestApi::matchPathInfo($path, $request); +$request = RestApi::setParams($params, $request); -$output = json_encode(RestApi::getJson()); +$output = json_encode(RestApi::getJson($request)); -echo RestApi::replaceLinks($output); +echo RestApi::replaceLinks($output, $request); diff --git a/test/EpubFsTest.php b/test/EpubFsTest.php index 44a9866a0..a5ee9a5b2 100644 --- a/test/EpubFsTest.php +++ b/test/EpubFsTest.php @@ -10,7 +10,7 @@ require(dirname(__FILE__) . "/config_test.php"); use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Book; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; use SebLucas\Cops\Output\EPubReader; use SebLucas\EPubMeta\EPub; diff --git a/test/OPDSTest.php b/test/OPDSTest.php index 0293346ff..805a97daf 100644 --- a/test/OPDSTest.php +++ b/test/OPDSTest.php @@ -11,6 +11,7 @@ require_once(dirname(__FILE__) . "/config_test.php"); use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Base; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Pages\Page; define("OPDS_RELAX_NG", dirname(__FILE__) . "/opds-relax-ng/opds_catalog_1_2.rng"); @@ -82,20 +83,22 @@ public function testPageIndex() $_SERVER['QUERY_STRING'] = ""; $config['cops_subtitle_default'] = "My subtitle"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->jingValidateSchema(TEST_FEED)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); $_SERVER ["HTTP_USER_AGENT"] = "XXX"; $config['cops_generate_invalid_opds_stream'] = "1"; + $request = new Request(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertFalse($this->jingValidateSchema(TEST_FEED)); $this->AssertFalse($this->opdsValidator(TEST_FEED)); @@ -116,13 +119,14 @@ public function testMostPages($page, $query) $_SERVER['QUERY_STRING'] .= "&query={$query}"; } $_SERVER['REQUEST_URI'] = OPDSRenderer::$endpoint . "?" . $_SERVER['QUERY_STRING']; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); unset($_SERVER['QUERY_STRING']); @@ -154,13 +158,14 @@ public function testPageIndexMultipleDatabase() $qid = "1"; $n = "1"; $_SERVER['QUERY_STRING'] = ""; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); unset($_SERVER['QUERY_STRING']); @@ -171,10 +176,11 @@ public function testPageIndexMultipleDatabase() public function testOpenSearchDescription() { $_SERVER['QUERY_STRING'] = ""; + $request = new Request(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->getOpenSearch()); + file_put_contents(TEST_FEED, $OPDSRender->getOpenSearch($request)); $this->AssertTrue($this->jingValidateSchema(TEST_FEED, OPENSEARCHDESCRIPTION_RELAX_NG)); unset($_SERVER['QUERY_STRING']); @@ -192,13 +198,14 @@ public function testPageAuthorMultipleDatabase() $n = "1"; $_SERVER['QUERY_STRING'] = "page=" . Page::AUTHOR_DETAIL . "&id=1"; $_GET ["db"] = "0"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); unset($_SERVER['QUERY_STRING']); @@ -217,26 +224,27 @@ public function testPageAuthorsDetail() $_SERVER['QUERY_STRING'] = "page=" . Page::AUTHOR_DETAIL . "&id=1&n=1"; $config['cops_max_item_per_page'] = 2; + $request = new Request(); // First page - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); // Second page $n = 2; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); unset($_SERVER['QUERY_STRING']); @@ -255,13 +263,14 @@ public function testPageAuthorsDetail_WithFacets() $_GET["tag"] = "Short Stories"; $config['cops_books_filter'] = ["Only Short Stories" => "Short Stories", "No Short Stories" => "!Short Stories"]; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); unset($_SERVER['QUERY_STRING']); @@ -278,15 +287,15 @@ public function testPageAuthorsDetail_WithoutAnyId() $n = "1"; $_SERVER['QUERY_STRING'] = "page=" . Page::AUTHOR_DETAIL . "&id=1&n=1"; $_SERVER['REQUEST_URI'] = "index.php?XXXX"; + $request = new Request(); - - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $currentPage->idPage = null; $OPDSRender = new OPDSRenderer(); - file_put_contents(TEST_FEED, $OPDSRender->render($currentPage)); + file_put_contents(TEST_FEED, $OPDSRender->render($currentPage, $request)); $this->AssertTrue($this->opdsCompleteValidation(TEST_FEED)); unset($_SERVER['QUERY_STRING']); diff --git a/test/RestApiTest.php b/test/RestApiTest.php index 8806252b7..07f3d1b85 100644 --- a/test/RestApiTest.php +++ b/test/RestApiTest.php @@ -12,12 +12,10 @@ require_once(dirname(__FILE__) . "/config_test.php"); use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Base; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\JSONRenderer; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\setURLParam; - class RestApiTest extends TestCase { public static $script; @@ -37,14 +35,16 @@ public static function tearDownAfterClass(): void public function testGetPathInfo(): void { + $request = new Request(); $expected = "/index"; - $test = RestApi::getPathInfo(); + $test = RestApi::getPathInfo($request); $this->assertEquals($expected, $test); $_SERVER["PATH_INFO"] = "/books/2"; + $request = new Request(); $expected = "/books/2"; - $test = RestApi::getPathInfo(); + $test = RestApi::getPathInfo($request); $this->assertEquals($expected, $test); unset($_SERVER["PATH_INFO"]); @@ -53,10 +53,11 @@ public function testGetPathInfo(): void public function testMatchPathInfo(): void { $_SERVER["PATH_INFO"] = "/books/2"; - $path = RestApi::getPathInfo(); + $request = new Request(); + $path = RestApi::getPathInfo($request); $expected = ["page" => Page::BOOK_DETAIL, "id" => 2]; - $test = RestApi::matchPathInfo($path); + $test = RestApi::matchPathInfo($path, $request); $this->assertEquals($expected, $test); unset($_SERVER["PATH_INFO"]); @@ -65,27 +66,27 @@ public function testMatchPathInfo(): void public function testSetParams(): void { $_SERVER["PATH_INFO"] = "/books/2"; - $path = RestApi::getPathInfo(); - $params = RestApi::matchPathInfo($path); - RestApi::setParams($params); + $request = new Request(); + $path = RestApi::getPathInfo($request); + $params = RestApi::matchPathInfo($path, $request); + $request = RestApi::setParams($params, $request); $expected = Page::BOOK_DETAIL; - $test = getURLParam("page"); + $test = $request->get("page"); $this->assertEquals($expected, $test); $expected = 2; - $test = getURLParam("id"); + $test = $request->get("id"); $this->assertEquals($expected, $test); unset($_SERVER["PATH_INFO"]); - setURLParam("page", null); - setURLParam("id", null); } public function testGetJson(): void { - $expected = JSONRenderer::getJson(); - $test = RestApi::getJson(); + $request = new Request(); + $expected = JSONRenderer::getJson($request); + $test = RestApi::getJson($request); $this->assertEquals($expected, $test); } @@ -93,9 +94,10 @@ public function testGetScriptName(): void { $script = $_SERVER["SCRIPT_NAME"]; $_SERVER["SCRIPT_NAME"] = "/" . RestApi::$endpoint; + $request = new Request(); $expected = "restapi.php"; - $test = RestApi::getScriptName(); + $test = RestApi::getScriptName($request); $this->assertEquals($expected, $test); $_SERVER["SCRIPT_NAME"] = $script; @@ -105,6 +107,7 @@ public function testReplaceLinks(): void { $script = $_SERVER["SCRIPT_NAME"]; $_SERVER["SCRIPT_NAME"] = "/" . RestApi::$endpoint; + $request = new Request(); $links = [ "restapi.php?page=index" => "restapi.php/index", "restapi.php?page=1" => "restapi.php/authors", @@ -134,7 +137,7 @@ public function testReplaceLinks(): void $output = json_encode(array_keys($links)); $expected = json_encode(array_values($links), JSON_UNESCAPED_SLASHES); - $test = RestApi::replaceLinks($output); + $test = RestApi::replaceLinks($output, $request); $this->assertEquals($expected, $test); $_SERVER["SCRIPT_NAME"] = $script; @@ -142,36 +145,41 @@ public function testReplaceLinks(): void public function testGetOutput(): void { + $request = new Request(); $expected = true; - $test = RestApi::getOutput(); + $test = RestApi::getOutput($request); $this->assertEquals($expected, str_starts_with($test, '{"title":"COPS",')); } public function testGetCustomColumns(): void { + $request = new Request(); $expected = "Custom Columns"; - $test = RestApi::getCustomColumns(); + $test = RestApi::getCustomColumns($request); $this->assertEquals($expected, $test["title"]); } public function testGetDatabases(): void { + $request = new Request(); $expected = "Databases"; - $test = RestApi::getDatabases(); + $test = RestApi::getDatabases($request); $this->assertEquals($expected, $test["title"]); } public function testGetOpenApi(): void { + $request = new Request(); $expected = "3.1.0"; - $test = RestApi::getOpenApi(); + $test = RestApi::getOpenApi($request); $this->assertEquals($expected, $test["openapi"]); } public function testGetRoutes(): void { + $request = new Request(); $expected = "Routes"; - $test = RestApi::getRoutes(); + $test = RestApi::getRoutes($request); $this->assertEquals($expected, $test["title"]); } } diff --git a/test/baseTest.php b/test/baseTest.php index edc79fac6..3eb3e8c9c 100644 --- a/test/baseTest.php +++ b/test/baseTest.php @@ -9,17 +9,13 @@ require_once(dirname(__FILE__) . "/config_test.php"); use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Base; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\Format; use SebLucas\Cops\Output\JSONRenderer; use SebLucas\Cops\Language\Translation; use SebLucas\Template\doT; -use function SebLucas\Cops\Request\getCurrentCss; -use function SebLucas\Cops\Request\getQueryString; -use function SebLucas\Cops\Request\useServerSideRendering; -use function SebLucas\Cops\Request\verifyLogin; - class BaseTest extends TestCase { public static function setUpBeforeClass(): void @@ -43,7 +39,7 @@ public function testAddURLParameter() public function testServerSideRender($template) { $_COOKIE["template"] = $template; - $this->assertNull(Format::serverSideRender(null)); + $this->assertNull(Format::serverSideRender(null, $template)); unset($_COOKIE['template']); } @@ -55,6 +51,7 @@ public function testServerSideRender($template) public function testGenerateHeader($templateName) { $_SERVER["HTTP_USER_AGENT"] = "Firefox"; + $request = new Request(); global $config; $headcontent = file_get_contents(dirname(__FILE__) . '/../templates/' . $templateName . '/file.html'); $template = new doT(); @@ -64,10 +61,10 @@ public function testGenerateHeader($templateName) "opds_url" => $config['cops_full_url'] . Config::ENDPOINT["feed"], "customHeader" => "", "template" => $templateName, - "server_side_rendering" => useServerSideRendering(), - "current_css" => getCurrentCss(), + "server_side_rendering" => $request->render(), + "current_css" => $request->style(), "favico" => $config['cops_icon'], - "getjson_url" => JSONRenderer::getCurrentUrl(getQueryString())]; + "getjson_url" => JSONRenderer::getCurrentUrl($request->query())]; $head = $tpl($data); $this->assertStringContainsString("", $head); @@ -182,7 +179,7 @@ public function testBaseFunction() public function testCheckDatabaseAvailability_1() { - $this->assertTrue(Base::checkDatabaseAvailability()); + $this->assertTrue(Base::checkDatabaseAvailability(null)); } public function testCheckDatabaseAvailability_2() @@ -193,7 +190,7 @@ public function testCheckDatabaseAvailability_2() "One book" => dirname(__FILE__) . "/BaseWithOneBook/"]; Base::clearDb(); - $this->assertTrue(Base::checkDatabaseAvailability()); + $this->assertTrue(Base::checkDatabaseAvailability(null)); $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); @@ -214,7 +211,7 @@ public function testCheckDatabaseAvailability_Exception1() $this->expectException(Exception::class); $this->expectExceptionMessage('Database <1> not found.'); - $this->assertTrue(Base::checkDatabaseAvailability()); + $this->assertTrue(Base::checkDatabaseAvailability(null)); $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); @@ -235,7 +232,7 @@ public function testCheckDatabaseAvailability_Exception2() $this->expectException(Exception::class); $this->expectExceptionMessage('Database <0> not found.'); - $this->assertTrue(Base::checkDatabaseAvailability()); + $this->assertTrue(Base::checkDatabaseAvailability(null)); $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); @@ -258,7 +255,7 @@ public function testLoginEnabledWithoutCreds() { global $config; $config['cops_basic_authentication'] = [ "username" => "xxx", "password" => "secret"]; - $this->assertFalse(verifyLogin()); + $this->assertFalse(Request::verifyLogin()); } public function testLoginEnabledAndLoggingIn() @@ -267,6 +264,6 @@ public function testLoginEnabledAndLoggingIn() $config['cops_basic_authentication'] = [ "username" => "xxx", "password" => "secret"]; $_SERVER['PHP_AUTH_USER'] = 'xxx'; $_SERVER['PHP_AUTH_PW'] = 'secret'; - $this->assertTrue(verifyLogin()); + $this->assertTrue(Request::verifyLogin($_SERVER)); } } diff --git a/test/bookTest.php b/test/bookTest.php index 57583b38c..ff851c612 100644 --- a/test/bookTest.php +++ b/test/bookTest.php @@ -10,13 +10,11 @@ use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Base; use SebLucas\Cops\Calibre\Book; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Model\Link; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\getURLParam; -use function SebLucas\Cops\Request\setURLParam; - /* Publishers: id:2 (2 books) Macmillan and Co. London: Lewis Caroll @@ -386,11 +384,19 @@ public function testGetDataById() $config['cops_use_url_rewriting'] = "1"; $config['cops_provide_kepub'] = "1"; $_SERVER["HTTP_USER_AGENT"] = "Kobo"; + $book = Book::getBookById(17); + $book->updateForKepub = true; + $epub = $book->getDataById(20); $this->assertEquals("download/20/Carroll%2C%20Lewis%20-%20Alice%27s%20Adventures%20in%20Wonderland.kepub.epub", $epub->getHtmlLink()); $this->assertEquals("download/17/Alice%27s%20Adventures%20in%20Wonderland%20-%20Lewis%20Carroll.mobi", $mobi->getHtmlLink()); + $config['cops_provide_kepub'] = "0"; $_SERVER["HTTP_USER_AGENT"] = "Firefox"; + $book = Book::getBookById(17); + $book->updateForKepub = false; + $epub = $book->getDataById(20); $this->assertEquals("download/20/Alice%27s%20Adventures%20in%20Wonderland%20-%20Lewis%20Carroll.epub", $epub->getHtmlLink()); + $config['cops_use_url_rewriting'] = "0"; $this->assertEquals(Config::ENDPOINT["fetch"] . "?data=20&type=epub&id=17", $epub->getHtmlLink()); } @@ -399,21 +405,21 @@ public function testGetFilePath_Cover() { $book = Book::getBookById(17); - $this->assertEquals(Base::getDbDirectory() . "Lewis Carroll/Alice's Adventures in Wonderland (17)/cover.jpg", $book->getFilePath("jpg", null, false)); + $this->assertEquals(Base::getDbDirectory(null) . "Lewis Carroll/Alice's Adventures in Wonderland (17)/cover.jpg", $book->getFilePath("jpg", null, false)); } public function testGetFilePath_Epub() { $book = Book::getBookById(17); - $this->assertEquals(Base::getDbDirectory() . "Lewis Carroll/Alice's Adventures in Wonderland (17)/Alice's Adventures in Wonderland - Lewis Carroll.epub", $book->getFilePath("epub", 20, false)); + $this->assertEquals(Base::getDbDirectory(null) . "Lewis Carroll/Alice's Adventures in Wonderland (17)/Alice's Adventures in Wonderland - Lewis Carroll.epub", $book->getFilePath("epub", 20, false)); } public function testGetFilePath_Mobi() { $book = Book::getBookById(17); - $this->assertEquals(Base::getDbDirectory() . "Lewis Carroll/Alice's Adventures in Wonderland (17)/Alice's Adventures in Wonderland - Lewis Carroll.mobi", $book->getFilePath("mobi", 17, false)); + $this->assertEquals(Base::getDbDirectory(null) . "Lewis Carroll/Alice's Adventures in Wonderland (17)/Alice's Adventures in Wonderland - Lewis Carroll.mobi", $book->getFilePath("mobi", 17, false)); } public function testGetDataFormat_EPUB() @@ -501,32 +507,32 @@ public function testGetMimeType_Finfo() public function testTypeaheadSearch_Tag() { + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "fic"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(3, $currentPage->entryArray); $this->assertEquals("2 tags", $currentPage->entryArray[0]->content); $this->assertEquals("Fiction", $currentPage->entryArray[1]->title); $this->assertEquals("Science Fiction", $currentPage->entryArray[2]->title); - - setURLParam('search', null); } public function testTypeaheadSearch_BookAndAuthor() { + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "car"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(4, $currentPage->entryArray); @@ -535,19 +541,18 @@ public function testTypeaheadSearch_BookAndAuthor() $this->assertEquals("1 author", $currentPage->entryArray[2]->content); $this->assertEquals("Carroll, Lewis", $currentPage->entryArray[3]->title); - - setURLParam('search', null); } public function testTypeaheadSearch_AuthorAndSeries() { + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "art"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(5, $currentPage->entryArray); @@ -556,84 +561,82 @@ public function testTypeaheadSearch_AuthorAndSeries() $this->assertEquals("2 series", $currentPage->entryArray[2]->content); $this->assertEquals("D'Artagnan Romances", $currentPage->entryArray[3]->title); - - setURLParam('search', null); } public function testTypeaheadSearch_Publisher() { + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "Macmillan"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(3, $currentPage->entryArray); $this->assertEquals("2 publishers", $currentPage->entryArray[0]->content); $this->assertEquals("Macmillan and Co. London", $currentPage->entryArray[1]->title); $this->assertEquals("Macmillan Publishers USA", $currentPage->entryArray[2]->title); - - setURLParam('search', null); } public function testTypeaheadSearchWithIgnored_SingleCategory() { global $config; + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "car"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); $config ['cops_ignored_categories'] = ["author"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(2, $currentPage->entryArray); $this->assertEquals("1 book", $currentPage->entryArray[0]->content); $this->assertEquals("A Study in Scarlet", $currentPage->entryArray[1]->title); - setURLParam('search', null); $config ['cops_ignored_categories'] = []; } public function testTypeaheadSearchWithIgnored_MultipleCategory() { global $config; + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "art"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); $config ['cops_ignored_categories'] = ["series"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(2, $currentPage->entryArray); $this->assertEquals("1 author", $currentPage->entryArray[0]->content); $this->assertEquals("Doyle, Arthur Conan", $currentPage->entryArray[1]->title); - setURLParam('search', null); $config ['cops_ignored_categories'] = []; } public function testTypeaheadSearchMultiDatabase() { global $config; + $request = new Request(); $page = Page::OPENSEARCH_QUERY; - $qid = getURLParam("id"); + $qid = $request->get("id"); $query = "art"; - $n = getURLParam("n", "1"); - setURLParam('search', 1); - setURLParam('multi', 1); + $n = $request->get("n", "1"); + $request->set('search', 1); + $request->set('multi', 1); $config['calibre_directory'] = ["Some books" => dirname(__FILE__) . "/BaseWithSomeBooks/", "One book" => dirname(__FILE__) . "/BaseWithOneBook/"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(5, $currentPage->entryArray); @@ -643,8 +646,6 @@ public function testTypeaheadSearchMultiDatabase() $this->assertEquals("One book", $currentPage->entryArray[3]->title); $this->assertEquals("1 book", $currentPage->entryArray[4]->content); - setURLParam('search', null); - setURLParam('multi', null); $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); } diff --git a/test/configTest.php b/test/configTest.php index 731d507e2..449d812a9 100644 --- a/test/configTest.php +++ b/test/configTest.php @@ -6,14 +6,11 @@ * @author Sébastien Lucas */ use PHPUnit\Framework\TestCase; -use SebLucas\Cops\Config; +use SebLucas\Cops\Input\Config; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Output\JSONRenderer; use SebLucas\Template\doT; -use function SebLucas\Cops\Request\getCurrentCss; -use function SebLucas\Cops\Request\getQueryString; -use function SebLucas\Cops\Request\useServerSideRendering; - class ConfigTest extends TestCase { public function testCheckConfigurationCalibreDirectory() @@ -131,6 +128,7 @@ public function testCheckConfigurationTemplate() $style = 'bootstrap'; $config["cops_template"] = $style; + $request = new Request(); $headcontent = file_get_contents(dirname(__FILE__) . '/../templates/' . $config["cops_template"] . '/file.html'); $template = new doT(); @@ -140,10 +138,10 @@ public function testCheckConfigurationTemplate() "opds_url" => $config['cops_full_url'] . Config::ENDPOINT["feed"], "customHeader" => "", "template" => $config["cops_template"], - "server_side_rendering" => useServerSideRendering(), - "current_css" => getCurrentCss(), + "server_side_rendering" => $request->render(), + "current_css" => $request->style(), "favico" => $config['cops_icon'], - "getjson_url" => JSONRenderer::getCurrentUrl(getQueryString())]; + "getjson_url" => JSONRenderer::getCurrentUrl($request->query())]; $head = $tpl($data); diff --git a/test/customColumnsTest.php b/test/customColumnsTest.php index 426a82111..d164936b8 100644 --- a/test/customColumnsTest.php +++ b/test/customColumnsTest.php @@ -20,12 +20,11 @@ use SebLucas\Cops\Calibre\CustomColumnTypeRating; use SebLucas\Cops\Calibre\CustomColumnTypeSeries; use SebLucas\Cops\Calibre\CustomColumnTypeText; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Model\EntryBook; use SebLucas\Cops\Output\JSONRenderer; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\setURLParam; - class CustomColumnTest extends TestCase { public function testColumnType01() @@ -381,8 +380,9 @@ public function testIndexTypeAll() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(15, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -404,8 +404,9 @@ public function testIndexType01() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_01"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -424,8 +425,9 @@ public function testIndexType02() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_02"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -444,8 +446,9 @@ public function testIndexType03() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_03"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(6, $currentPage->entryArray); // Authors, Series, Publishers, Languages, All, Recent @@ -458,8 +461,9 @@ public function testIndexType04() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_04"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -478,8 +482,9 @@ public function testIndexType05() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_05"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -498,8 +503,9 @@ public function testIndexType06() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_06"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -518,8 +524,9 @@ public function testIndexType07() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_07"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -538,8 +545,9 @@ public function testIndexType08() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_08"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -558,8 +566,9 @@ public function testIndexType09() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_09"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -578,8 +587,9 @@ public function testIndexType10() $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; $config['cops_calibre_custom_column'] = ["custom_10"]; Base::clearDb(); + $request = new Request(); - $currentPage = Page::getPage(Page::INDEX, null, null, "1"); + $currentPage = Page::getPage(Page::INDEX, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertCount(7, $currentPage->entryArray); // Authors, Series, Publishers, Languages, custom, All, Recent @@ -596,9 +606,11 @@ public function testAllCustomsType01() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 8); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 8); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_01", $currentPage->title); @@ -613,9 +625,11 @@ public function testAllCustomsType02() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 6); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 6); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_02", $currentPage->title); @@ -630,9 +644,11 @@ public function testAllCustomsType04() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 4); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 4); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_04", $currentPage->title); @@ -647,9 +663,11 @@ public function testAllCustomsType05() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 5); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 5); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_05", $currentPage->title); @@ -665,9 +683,11 @@ public function testAllCustomsType06() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 12); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 12); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_06", $currentPage->title); @@ -684,9 +704,11 @@ public function testAllCustomsType07() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 14); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 14); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_07", $currentPage->title); @@ -704,9 +726,11 @@ public function testAllCustomsType08() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 10); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 10); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_08", $currentPage->title); @@ -722,9 +746,11 @@ public function testAllCustomsType09() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 9); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 9); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_09", $currentPage->title); @@ -742,9 +768,11 @@ public function testAllCustomsType10() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 11); Base::clearDb(); - $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1"); + $request = new Request(); + $request->set('custom', 11); + + $currentPage = Page::getPage(Page::ALL_CUSTOMS, null, null, "1", $request); $currentPage->InitializeContent(); $this->assertEquals("custom_10", $currentPage->title); @@ -780,11 +808,12 @@ public function testDetailTypeAllEntryIDs() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 11); $config['cops_calibre_custom_column'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10", "custom_11"]; Base::clearDb(); + $request = new Request(); + $request->set('custom', 11); - $currentPage = Page::getPage(Page::CUSTOM_DETAIL, "0", null, "1"); + $currentPage = Page::getPage(Page::CUSTOM_DETAIL, "0", null, "1", $request); $currentPage->InitializeContent(); /** @var EntryBook[] $entries */ @@ -807,7 +836,6 @@ public function testDetailTypeAllEntryIDs() $this->assertEquals("cops:custom:9:2", $customcolumnValues[8]->getEntryId()); $this->assertEquals("cops:custom:11:0", $customcolumnValues[9]->getEntryId()); - setURLParam('custom', null); $config['cops_calibre_custom_column'] = []; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); @@ -819,7 +847,6 @@ public function testRenderCustomColumns() $_SERVER["HTTP_USER_AGENT"] = "Firefox"; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 11); $config['cops_calibre_custom_column'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10", "custom_11"]; $config['cops_calibre_custom_column_list'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10", "custom_11"]; $config['cops_calibre_custom_column_preview'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10", "custom_11"]; @@ -871,7 +898,6 @@ public function testQueries() global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 11); $config['cops_calibre_custom_column'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10", "custom_11"]; Base::clearDb(); @@ -955,12 +981,11 @@ public function testQueries() $this->assertEquals("Yes", $custom[0]['htmlvalue']); } - public function testGetURI() + public function testGetQuery() { global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithCustomColumns/"; - setURLParam('custom', 11); $config['cops_calibre_custom_column'] = ["custom_01", "custom_02", "custom_03", "custom_04", "custom_05", "custom_06", "custom_07", "custom_08", "custom_09", "custom_10", "custom_11"]; Base::clearDb(); @@ -1008,7 +1033,6 @@ public function tearDown(): void { global $config; - setURLParam('custom', null); $config['cops_calibre_custom_column'] = []; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); diff --git a/test/jsonTest.php b/test/jsonTest.php index d6fbca405..2aef66e99 100644 --- a/test/jsonTest.php +++ b/test/jsonTest.php @@ -12,12 +12,13 @@ use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Base; use SebLucas\Cops\Calibre\Book; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\setURLParam; - class JsonTest extends TestCase { + private static $request; + public static function setUpBeforeClass(): void { global $config; @@ -26,6 +27,7 @@ public static function setUpBeforeClass(): void $config['cops_calibre_custom_column_list'] = []; $config['cops_calibre_custom_column_preview'] = []; Base::clearDb(); + self::$request = new Request(); } public function testCompleteArray() @@ -34,7 +36,8 @@ public function testCompleteArray() $_SERVER["HTTP_USER_AGENT"] = "Firefox"; $test = []; - $test = JSONRenderer::addCompleteArray($test); + $request = new Request(); + $test = JSONRenderer::addCompleteArray($test, $request); $this->assertArrayHasKey("c", $test); $this->assertArrayHasKey("version", $test ["c"]); $this->assertArrayHasKey("i18n", $test ["c"]); @@ -46,14 +49,14 @@ public function testCompleteArray() // The thumbnails should be the same as the covers $config['cops_thumbnail_handling'] = "1"; $test = []; - $test = JSONRenderer::addCompleteArray($test); + $test = JSONRenderer::addCompleteArray($test, $request); $this->assertTrue($test ["c"]["url"]["thumbnailUrl"] == $test ["c"]["url"]["coverUrl"]); // The thumbnails should be the same as the covers $config['cops_thumbnail_handling'] = "/images.png"; $test = []; - $test = JSONRenderer::addCompleteArray($test); + $test = JSONRenderer::addCompleteArray($test, $request); $this->assertEquals("/images.png", $test ["c"]["url"]["thumbnailUrl"]); } @@ -96,14 +99,14 @@ public function testGetJson() { $page = Page::ALL_RECENT_BOOKS; - setURLParam('page', $page); - $test = JSONRenderer::getJson(); + self::$request->set('page', $page); + $test = JSONRenderer::getJson(self::$request); $this->assertEquals("Recent additions", $test["title"]); $this->assertCount(15, $test["entries"]); $this->assertEquals("La curée", $test["entries"][0]["title"]); - setURLParam('page', null); + self::$request->set('page', null); } public function testGetJsonSearch() @@ -111,10 +114,10 @@ public function testGetJsonSearch() $page = Page::OPENSEARCH_QUERY; $query = "fic"; - setURLParam('page', $page); - setURLParam('query', $query); - setURLParam('search', 1); - $test = JSONRenderer::getJson(); + self::$request->set('page', $page); + self::$request->set('query', $query); + self::$request->set('search', 1); + $test = JSONRenderer::getJson(self::$request); $check = [ [ 'class' => 'tt-header', @@ -134,23 +137,23 @@ public function testGetJsonSearch() ]; $this->assertEquals($check, $test); - setURLParam('page', null); - setURLParam('query', null); - setURLParam('search', null); + self::$request->set('page', null); + self::$request->set('query', null); + self::$request->set('search', null); } public function testGetJsonComplete() { $page = Page::ALL_RECENT_BOOKS; - setURLParam('page', $page); - $test = JSONRenderer::getJson(true); + self::$request->set('page', $page); + $test = JSONRenderer::getJson(self::$request, true); $this->assertEquals("Recent additions", $test["title"]); $this->assertCount(15, $test["entries"]); $this->assertEquals("La curée", $test["entries"][0]["title"]); $this->assertCount(4, $test["c"]); - setURLParam('page', null); + self::$request->set('page', null); } } diff --git a/test/pageTest.php b/test/pageTest.php index 957faf5ef..f1c9b25c3 100644 --- a/test/pageTest.php +++ b/test/pageTest.php @@ -9,12 +9,11 @@ require_once(dirname(__FILE__) . "/config_test.php"); use PHPUnit\Framework\TestCase; use SebLucas\Cops\Calibre\Base; +use SebLucas\Cops\Input\Request; use SebLucas\Cops\Language\Translation; +use SebLucas\Cops\Output\Format; use SebLucas\Cops\Pages\Page; -use function SebLucas\Cops\Request\getUrlWithVersion; -use function SebLucas\Cops\Request\setURLParam; - class PageTest extends TestCase { public static function setUpBeforeClass(): void @@ -22,6 +21,7 @@ public static function setUpBeforeClass(): void global $config; $config['calibre_directory'] = dirname(__FILE__) . "/BaseWithSomeBooks/"; Base::clearDb(); + $_GET = []; } public function testPageIndex() @@ -31,8 +31,9 @@ public function testPageIndex() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals($config['cops_title_default'], $currentPage->title); @@ -40,7 +41,7 @@ public function testPageIndex() $this->assertEquals("Authors", $currentPage->entryArray [0]->title); $this->assertEquals("Alphabetical index of the 6 authors", $currentPage->entryArray [0]->content); if ($config['cops_show_icons'] == 1) { - $this->assertEquals(getUrlWithVersion("images/author.png"), $currentPage->entryArray [0]->getThumbnail()); + $this->assertEquals(Format::addVersion("images/author.png"), $currentPage->entryArray [0]->getThumbnail()); } else { $this->assertNull($currentPage->entryArray [0]->getThumbnail()); } @@ -76,10 +77,11 @@ public function testPageIndexWithIgnored() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config ['cops_ignored_categories'] = ["author", "series", "tag", "publisher", "language"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals($config['cops_title_default'], $currentPage->title); @@ -101,10 +103,11 @@ public function testPageIndexWithCustomColumn_Type1() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_calibre_custom_column'] = ["type1"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(9, $currentPage->entryArray); @@ -122,10 +125,11 @@ public function testPageIndexWithCustomColumn_Type2() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_calibre_custom_column'] = ["type2"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(9, $currentPage->entryArray); @@ -143,10 +147,11 @@ public function testPageIndexWithCustomColumn_Type4() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_calibre_custom_column'] = ["type4"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(9, $currentPage->entryArray); @@ -164,10 +169,11 @@ public function testPageIndexWithCustomColumn_ManyTypes() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_calibre_custom_column'] = ["type1", "type2", "type4"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(11, $currentPage->entryArray); @@ -182,10 +188,11 @@ public function testPageIndexWithCustomColumn_All() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_calibre_custom_column'] = ["*"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertCount(11, $currentPage->entryArray); @@ -199,10 +206,11 @@ public function testPageAllCustom_Type4() $query = null; $qid = null; $n = "1"; + $request = new Request(); - setURLParam('custom', 1); + $request->set('custom', 1); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Type4", $currentPage->title); @@ -210,8 +218,6 @@ public function testPageAllCustom_Type4() $this->assertEquals("SeriesLike", $currentPage->entryArray [0]->title); $this->assertEquals(2, $currentPage->entryArray [0]->numberOfElement); $this->assertFalse($currentPage->containsBook()); - - setURLParam('custom', null); } public function testPageAllCustom_Type2() @@ -220,10 +226,11 @@ public function testPageAllCustom_Type2() $query = null; $qid = null; $n = "1"; + $request = new Request(); - setURLParam('custom', 2); + $request->set('custom', 2); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Type2", $currentPage->title); @@ -231,8 +238,6 @@ public function testPageAllCustom_Type2() $this->assertEquals("tag1", $currentPage->entryArray [0]->title); $this->assertEquals(2, $currentPage->entryArray [0]->numberOfElement); $this->assertFalse($currentPage->containsBook()); - - setURLParam('custom', null); } public function testPageAllCustom_Type1() @@ -241,10 +246,11 @@ public function testPageAllCustom_Type1() $query = null; $qid = null; $n = "1"; + $request = new Request(); - setURLParam('custom', 3); + $request->set('custom', 3); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Type1", $currentPage->title); @@ -252,8 +258,6 @@ public function testPageAllCustom_Type1() $this->assertEquals("other", $currentPage->entryArray [0]->title); $this->assertEquals(1, $currentPage->entryArray [0]->numberOfElement); $this->assertFalse($currentPage->containsBook()); - - setURLParam('custom', null); } public function testPageCustomDetail_Type4() @@ -262,18 +266,17 @@ public function testPageCustomDetail_Type4() $query = null; $qid = "1"; $n = "1"; + $request = new Request(); - setURLParam('custom', 1); + $request->set('custom', 1); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("SeriesLike", $currentPage->title); $this->assertCount(2, $currentPage->entryArray); $this->assertEquals("Alice's Adventures in Wonderland", $currentPage->entryArray [0]->title); $this->assertTrue($currentPage->containsBook()); - - setURLParam('custom', null); } public function testPageCustomDetail_Type2() @@ -282,18 +285,17 @@ public function testPageCustomDetail_Type2() $query = null; $qid = "1"; $n = "1"; + $request = new Request(); - setURLParam('custom', 2); + $request->set('custom', 2); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("tag1", $currentPage->title); $this->assertCount(2, $currentPage->entryArray); $this->assertEquals("Alice's Adventures in Wonderland", $currentPage->entryArray [0]->title); $this->assertTrue($currentPage->containsBook()); - - setURLParam('custom', null); } public function testPageCustomDetail_Type1() @@ -302,19 +304,18 @@ public function testPageCustomDetail_Type1() $query = null; $qid = "1"; $n = "1"; + $request = new Request(); - setURLParam('custom', 3); + $request->set('custom', 3); $qid = "2"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("other", $currentPage->title); $this->assertCount(1, $currentPage->entryArray); $this->assertEquals("A Study in Scarlet", $currentPage->entryArray [0]->title); $this->assertTrue($currentPage->containsBook()); - - setURLParam('custom', null); } public function testPageAllAuthors_WithFullName() @@ -324,10 +325,11 @@ public function testPageAllAuthors_WithFullName() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_author_split_first_letter'] = "0"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Authors", $currentPage->title); @@ -345,8 +347,9 @@ public function testPageAllAuthors_SplittedByFirstLetter() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Authors", $currentPage->title); @@ -362,9 +365,10 @@ public function testPageAuthorsFirstLetter() $query = null; $qid = "C"; $n = "1"; + $request = new Request(); // Author Lewis Carroll - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("1 author starting with C", $currentPage->title); @@ -380,12 +384,13 @@ public function testPageAuthorsDetail_FirstPage() $qid = "1"; $n = "1"; $_SERVER['QUERY_STRING'] = "page=" . Page::AUTHOR_DETAIL . "&id=1&n=1"; + $request = new Request(); $config['cops_max_item_per_page'] = 2; // First page - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Arthur Conan Doyle", $currentPage->title); @@ -407,12 +412,13 @@ public function testPageAuthorsDetail_LastPage() $qid = "1"; $n = "1"; $_SERVER['QUERY_STRING'] = "page=" . Page::AUTHOR_DETAIL . "&id=1&n=1"; + $request = new Request(); // Last page $config['cops_max_item_per_page'] = 5; $n = "2"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Arthur Conan Doyle", $currentPage->title); @@ -435,11 +441,12 @@ public function testPageAuthorsDetail_NoPagination() $qid = "1"; $n = "1"; $_SERVER['QUERY_STRING'] = "page=" . Page::AUTHOR_DETAIL . "&id=1&n=1"; + $request = new Request(); // No pagination $config['cops_max_item_per_page'] = -1; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Arthur Conan Doyle", $currentPage->title); @@ -457,10 +464,11 @@ public function testPageAllBooks_WithFullName() $query = null; $qid = null; $n = "1"; + $request = new Request(); $config['cops_titles_split_first_letter'] = 0; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("All books", $currentPage->title); @@ -479,8 +487,9 @@ public function testPageAllBooks_SplittedByFirstLetter() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("All books", $currentPage->title); @@ -496,8 +505,9 @@ public function testPageAllBooksByLetter() $query = null; $qid = "C"; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("3 books starting with C", $currentPage->title); @@ -512,8 +522,9 @@ public function testPageAllSeries() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Series", $currentPage->title); @@ -528,7 +539,9 @@ public function testPageSeriesDetail() $query = null; $qid = "1"; $n = "1"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $request = new Request(); + + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Sherlock Holmes", $currentPage->title); @@ -543,8 +556,9 @@ public function testPageAllPublishers() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Publishers", $currentPage->title); @@ -559,8 +573,9 @@ public function testPagePublishersDetail() $query = null; $qid = "6"; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Strand Magazine", $currentPage->title); @@ -575,8 +590,9 @@ public function testPageAllTags() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Tags", $currentPage->title); @@ -591,8 +607,9 @@ public function testPageTagDetail() $query = null; $qid = "1"; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Fiction", $currentPage->title); @@ -607,8 +624,9 @@ public function testPageAllLanguages() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Languages", $currentPage->title); @@ -624,8 +642,9 @@ public function testPageLanguageDetail() $query = null; $qid = "1"; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("English", $currentPage->title); @@ -640,8 +659,9 @@ public function testPageAllRatings() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Ratings", $currentPage->title); @@ -656,8 +676,9 @@ public function testPageRatingDetail() $query = null; $qid = "1"; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("5 stars", $currentPage->title); @@ -672,8 +693,9 @@ public function testPageRecent() $query = null; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Recent additions", $currentPage->title); @@ -688,17 +710,16 @@ public function testPageRecent_WithFacets_IncludedTag() $query = null; $qid = null; $n = "1"; + $request = new Request(); - setURLParam('tag', "Historical"); - $currentPage = Page::getPage($page, $qid, $query, $n); + $request->set('tag', "Historical"); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Recent additions", $currentPage->title); $this->assertCount(2, $currentPage->entryArray); $this->assertEquals("Twenty Years After", $currentPage->entryArray [0]->title); $this->assertTrue($currentPage->containsBook()); - - setURLParam('tag', null); } public function testPageRecent_WithFacets_ExcludedTag() @@ -707,17 +728,16 @@ public function testPageRecent_WithFacets_ExcludedTag() $query = null; $qid = null; $n = "1"; + $request = new Request(); - setURLParam('tag', "!Romance"); - $currentPage = Page::getPage($page, $qid, $query, $n); + $request->set('tag', "!Romance"); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Recent additions", $currentPage->title); $this->assertCount(13, $currentPage->entryArray); $this->assertEquals("La curée", $currentPage->entryArray [0]->title); $this->assertTrue($currentPage->containsBook()); - - setURLParam('tag', null); } public function testPageBookDetail() @@ -726,8 +746,9 @@ public function testPageBookDetail() $query = null; $qid = "2"; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("The Return of Sherlock Holmes", $currentPage->title); @@ -742,9 +763,10 @@ public function testPageSearch_WithOnlyBooksReturned() $query = "alice"; $qid = null; $n = "1"; + $request = new Request(); // Only books returned - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *alice*", $currentPage->title); @@ -762,9 +784,10 @@ public function testPageSearch_WithAuthorsIgnored() $query = "car"; $qid = null; $n = "1"; + $request = new Request(); $config ['cops_ignored_categories'] = ["author"]; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *car*", $currentPage->title); @@ -784,8 +807,9 @@ public function testPageSearch_WithTwoCategories() $query = "car"; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *car*", $currentPage->title); @@ -806,8 +830,9 @@ public function testPageSearch_WithAccentuatedCharacters($query, $count, $conten $page = Page::OPENSEARCH_QUERY; $qid = null; $n = "1"; + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *$query*", $currentPage->title); @@ -843,8 +868,9 @@ public function testPageSearch_WithNormalizedSearch_Book($query, $count, $conten if (!Translation::useNormAndUp()) { $this->markTestIncomplete(); } + $request = new Request(); - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *$query*", $currentPage->title); @@ -876,19 +902,18 @@ public function testAuthorSearch_ByName() global $config; $page = Page::OPENSEARCH_QUERY; $query = "Lewis Carroll"; - setURLParam('scope', "author"); + $request = new Request(); + $request->set('scope', "author"); $qid = null; $n = "1"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *Lewis Carroll* in authors", $currentPage->title); $this->assertCount(1, $currentPage->entryArray); $this->assertEquals("Carroll, Lewis", $currentPage->entryArray [0]->title); $this->assertFalse($currentPage->containsBook()); - - setURLParam('scope', null); } public function testAuthorSearch_BySort() @@ -896,19 +921,18 @@ public function testAuthorSearch_BySort() global $config; $page = Page::OPENSEARCH_QUERY; $query = "Carroll, Lewis"; - setURLParam('scope', "author"); + $request = new Request(); + $request->set('scope', "author"); $qid = null; $n = "1"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *Carroll, Lewis* in authors", $currentPage->title); $this->assertCount(1, $currentPage->entryArray); $this->assertEquals("Carroll, Lewis", $currentPage->entryArray [0]->title); $this->assertFalse($currentPage->containsBook()); - - setURLParam('scope', null); } public function testPageSearchScopeAuthors() @@ -916,19 +940,18 @@ public function testPageSearchScopeAuthors() $page = Page::OPENSEARCH_QUERY; $qid = null; $n = "1"; - setURLParam('scope', "author"); + $request = new Request(); + $request->set('scope', "author"); // Match Lewis Carroll $query = "car"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *car* in authors", $currentPage->title); $this->assertCount(1, $currentPage->entryArray); $this->assertEquals("Carroll, Lewis", $currentPage->entryArray [0]->title); $this->assertFalse($currentPage->containsBook()); - - setURLParam('scope', null); } public function testPageSearchScopeSeries() @@ -936,19 +959,18 @@ public function testPageSearchScopeSeries() $page = Page::OPENSEARCH_QUERY; $qid = null; $n = "1"; - setURLParam('scope', "series"); + $request = new Request(); + $request->set('scope', "series"); // Match Holmes $query = "hol"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *hol* in series", $currentPage->title); $this->assertCount(1, $currentPage->entryArray); $this->assertEquals("Sherlock Holmes", $currentPage->entryArray [0]->title); $this->assertFalse($currentPage->containsBook()); - - setURLParam('scope', null); } public function testPageSearchScopeBooks() @@ -956,18 +978,17 @@ public function testPageSearchScopeBooks() $page = Page::OPENSEARCH_QUERY; $qid = null; $n = "1"; - setURLParam('scope', "book"); + $request = new Request(); + $request->set('scope', "book"); // Match Holmes $query = "hol"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *hol* in books", $currentPage->title); $this->assertCount(4, $currentPage->entryArray); $this->assertTrue($currentPage->containsBook()); - - setURLParam('scope', null); } public function testPageSearchScopePublishers() @@ -975,19 +996,18 @@ public function testPageSearchScopePublishers() $page = Page::OPENSEARCH_QUERY; $qid = null; $n = "1"; - setURLParam('scope', "publisher"); + $request = new Request(); + $request->set('scope', "publisher"); // Match Holmes $query = "millan"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *millan* in publishers", $currentPage->title); $this->assertCount(2, $currentPage->entryArray); $this->assertEquals("Macmillan and Co. London", $currentPage->entryArray [0]->title); $this->assertFalse($currentPage->containsBook()); - - setURLParam('scope', null); } public function testPageSearchScopeTags() @@ -995,17 +1015,16 @@ public function testPageSearchScopeTags() $page = Page::OPENSEARCH_QUERY; $qid = null; $n = "1"; - setURLParam('scope', "tag"); + $request = new Request(); + $request->set('scope', "tag"); // Match Holmes $query = "fic"; - $currentPage = Page::getPage($page, $qid, $query, $n); + $currentPage = Page::getPage($page, $qid, $query, $n, $request); $currentPage->InitializeContent(); $this->assertEquals("Search result for *fic* in tags", $currentPage->title); $this->assertCount(2, $currentPage->entryArray); $this->assertFalse($currentPage->containsBook()); - - setURLParam('scope', null); } }