Calibre OPDS (and HTML) PHP Server : web-based light alternative to Calibre content server / Calibre2OPDS to serve ebooks (epub, mobi, pdf, ...) http://blog.slucas.fr/en/oss/calibre-opds-php-server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1152 lines
40KB

  1. <?php
  2. /**
  3. * COPS (Calibre OPDS PHP Server) class file
  4. *
  5. * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
  6. * @author Sébastien Lucas <sebastien@slucas.fr>
  7. */
  8. define ("VERSION", "0.9.1beta");
  9. define ("DB", "db");
  10. date_default_timezone_set($config['default_timezone']);
  11. function useServerSideRendering () {
  12. global $config;
  13. return preg_match("/" . $config['cops_server_side_render'] . "/", $_SERVER['HTTP_USER_AGENT']);
  14. }
  15. function serverSideRender ($data) {
  16. // Get the templates
  17. $theme = getCurrentTemplate ();
  18. $header = file_get_contents('templates/' . $theme . '/header.html');
  19. $footer = file_get_contents('templates/' . $theme . '/footer.html');
  20. $main = file_get_contents('templates/' . $theme . '/main.html');
  21. $bookdetail = file_get_contents('templates/' . $theme . '/bookdetail.html');
  22. $page = file_get_contents('templates/' . $theme . '/page.html');
  23. // Generate the function for the template
  24. $template = new doT ();
  25. $dot = $template->template ($page, array ("bookdetail" => $bookdetail,
  26. "header" => $header,
  27. "footer" => $footer,
  28. "main" => $main));
  29. // Execute the template
  30. if (!empty ($data)) {
  31. return $dot ($data);
  32. }
  33. return NULL;
  34. }
  35. function getQueryString () {
  36. if ( isset($_SERVER['QUERY_STRING']) ) {
  37. return $_SERVER['QUERY_STRING'];
  38. }
  39. return "";
  40. }
  41. function notFound () {
  42. header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
  43. header("Status: 404 Not Found");
  44. $_SERVER['REDIRECT_STATUS'] = 404;
  45. }
  46. function getURLParam ($name, $default = NULL) {
  47. if (!empty ($_GET) && isset($_GET[$name]) && $_GET[$name] != "") {
  48. return $_GET[$name];
  49. }
  50. return $default;
  51. }
  52. function getCurrentOption ($option) {
  53. global $config;
  54. if (isset($_COOKIE[$option])) {
  55. if (isset($config ["cops_" . $option]) && is_array ($config ["cops_" . $option])) {
  56. return explode (",", $_COOKIE[$option]);
  57. } else {
  58. return $_COOKIE[$option];
  59. }
  60. }
  61. if ($option == "style") {
  62. return "default";
  63. }
  64. if (isset($config ["cops_" . $option])) {
  65. return $config ["cops_" . $option];
  66. }
  67. return "";
  68. }
  69. function getCurrentCss () {
  70. return "styles/style-" . getCurrentOption ("style") . ".css";
  71. }
  72. function getCurrentTemplate () {
  73. return "default";
  74. }
  75. function getUrlWithVersion ($url) {
  76. return $url . "?v=" . VERSION;
  77. }
  78. function xml2xhtml($xml) {
  79. return preg_replace_callback('#<(\w+)([^>]*)\s*/>#s', create_function('$m', '
  80. $xhtml_tags = array("br", "hr", "input", "frame", "img", "area", "link", "col", "base", "basefont", "param");
  81. return in_array($m[1], $xhtml_tags) ? "<$m[1]$m[2] />" : "<$m[1]$m[2]></$m[1]>";
  82. '), $xml);
  83. }
  84. function display_xml_error($error)
  85. {
  86. $return = "";
  87. $return .= str_repeat('-', $error->column) . "^\n";
  88. switch ($error->level) {
  89. case LIBXML_ERR_WARNING:
  90. $return .= "Warning $error->code: ";
  91. break;
  92. case LIBXML_ERR_ERROR:
  93. $return .= "Error $error->code: ";
  94. break;
  95. case LIBXML_ERR_FATAL:
  96. $return .= "Fatal Error $error->code: ";
  97. break;
  98. }
  99. $return .= trim($error->message) .
  100. "\n Line: $error->line" .
  101. "\n Column: $error->column";
  102. if ($error->file) {
  103. $return .= "\n File: $error->file";
  104. }
  105. return "$return\n\n--------------------------------------------\n\n";
  106. }
  107. function are_libxml_errors_ok ()
  108. {
  109. $errors = libxml_get_errors();
  110. foreach ($errors as $error) {
  111. if ($error->code == 801) return false;
  112. }
  113. return true;
  114. }
  115. function html2xhtml ($html) {
  116. $doc = new DOMDocument();
  117. libxml_use_internal_errors(true);
  118. $doc->loadHTML('<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' .
  119. $html . '</body></html>'); // Load the HTML
  120. $output = $doc->saveXML($doc->documentElement); // Transform to an Ansi xml stream
  121. $output = xml2xhtml($output);
  122. if (preg_match ('#<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></meta></head><body>(.*)</body></html>#ms', $output, $matches)) {
  123. $output = $matches [1]; // Remove <html><body>
  124. }
  125. /*
  126. // In case of error with summary, use it to debug
  127. $errors = libxml_get_errors();
  128. foreach ($errors as $error) {
  129. $output .= display_xml_error($error);
  130. }
  131. */
  132. if (!are_libxml_errors_ok ()) $output = "HTML code not valid.";
  133. libxml_use_internal_errors(false);
  134. return $output;
  135. }
  136. /**
  137. * This method is a direct copy-paste from
  138. * http://tmont.com/blargh/2010/1/string-format-in-php
  139. */
  140. function str_format($format) {
  141. $args = func_get_args();
  142. $format = array_shift($args);
  143. preg_match_all('/(?=\{)\{(\d+)\}(?!\})/', $format, $matches, PREG_OFFSET_CAPTURE);
  144. $offset = 0;
  145. foreach ($matches[1] as $data) {
  146. $i = $data[0];
  147. $format = substr_replace($format, @$args[$i], $offset + $data[1] - 1, 2 + strlen($i));
  148. $offset += strlen(@$args[$i]) - 2 - strlen($i);
  149. }
  150. return $format;
  151. }
  152. /**
  153. * This method is based on this page
  154. * http://www.mind-it.info/2010/02/22/a-simple-approach-to-localization-in-php/
  155. */
  156. function localize($phrase, $count=-1, $reset=false) {
  157. if ($count == 0)
  158. $phrase .= ".none";
  159. if ($count == 1)
  160. $phrase .= ".one";
  161. if ($count > 1)
  162. $phrase .= ".many";
  163. /* Static keyword is used to ensure the file is loaded only once */
  164. static $translations = NULL;
  165. if ($reset) {
  166. $translations = NULL;
  167. }
  168. /* If no instance of $translations has occured load the language file */
  169. if (is_null($translations)) {
  170. $lang = "en";
  171. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  172. {
  173. $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  174. }
  175. $lang_file_en = NULL;
  176. $lang_file = dirname(__FILE__). '/lang/Localization_' . $lang . '.json';
  177. if (!file_exists($lang_file)) {
  178. $lang_file = dirname(__FILE__). '/lang/' . 'Localization_en.json';
  179. }
  180. elseif ($lang != "en") {
  181. $lang_file_en = dirname(__FILE__). '/lang/' . 'Localization_en.json';
  182. }
  183. $lang_file_content = file_get_contents($lang_file);
  184. /* Load the language file as a JSON object and transform it into an associative array */
  185. $translations = json_decode($lang_file_content, true);
  186. /* Clean the array of all unfinished translations */
  187. foreach (array_keys ($translations) as $key) {
  188. if (preg_match ("/^##TODO##/", $key)) {
  189. unset ($translations [$key]);
  190. }
  191. }
  192. if ($lang_file_en)
  193. {
  194. $lang_file_content = file_get_contents($lang_file_en);
  195. $translations_en = json_decode($lang_file_content, true);
  196. $translations = array_merge ($translations_en, $translations);
  197. }
  198. }
  199. if (array_key_exists ($phrase, $translations)) {
  200. return $translations[$phrase];
  201. }
  202. return $phrase;
  203. }
  204. function addURLParameter($urlParams, $paramName, $paramValue) {
  205. if (empty ($urlParams)) {
  206. $urlParams = "";
  207. }
  208. $start = "";
  209. if (preg_match ("#^\?(.*)#", $urlParams, $matches)) {
  210. $start = "?";
  211. $urlParams = $matches[1];
  212. }
  213. $params = array();
  214. parse_str($urlParams, $params);
  215. if (empty ($paramValue) && $paramValue != 0) {
  216. unset ($params[$paramName]);
  217. } else {
  218. $params[$paramName] = $paramValue;
  219. }
  220. return $start . http_build_query($params);
  221. }
  222. class Link
  223. {
  224. const OPDS_THUMBNAIL_TYPE = "http://opds-spec.org/image/thumbnail";
  225. const OPDS_IMAGE_TYPE = "http://opds-spec.org/image";
  226. const OPDS_ACQUISITION_TYPE = "http://opds-spec.org/acquisition";
  227. const OPDS_NAVIGATION_TYPE = "application/atom+xml;profile=opds-catalog;kind=navigation";
  228. const OPDS_PAGING_TYPE = "application/atom+xml;profile=opds-catalog;kind=acquisition";
  229. public $href;
  230. public $type;
  231. public $rel;
  232. public $title;
  233. public $facetGroup;
  234. public $activeFacet;
  235. public function __construct($phref, $ptype, $prel = NULL, $ptitle = NULL, $pfacetGroup = NULL, $pactiveFacet = FALSE) {
  236. $this->href = $phref;
  237. $this->type = $ptype;
  238. $this->rel = $prel;
  239. $this->title = $ptitle;
  240. $this->facetGroup = $pfacetGroup;
  241. $this->activeFacet = $pactiveFacet;
  242. }
  243. public function hrefXhtml () {
  244. return $this->href;
  245. }
  246. }
  247. class LinkNavigation extends Link
  248. {
  249. public function __construct($phref, $prel = NULL, $ptitle = NULL) {
  250. parent::__construct ($phref, Link::OPDS_NAVIGATION_TYPE, $prel, $ptitle);
  251. if (!is_null (GetUrlParam (DB))) $this->href = addURLParameter ($this->href, DB, GetUrlParam (DB));
  252. if (!preg_match ("#^\?(.*)#", $this->href) && !empty ($this->href)) $this->href = "?" . $this->href;
  253. if (preg_match ("/(bookdetail|getJSON).php/", $_SERVER["SCRIPT_NAME"])) {
  254. $this->href = "index.php" . $this->href;
  255. } else {
  256. $this->href = $_SERVER["SCRIPT_NAME"] . $this->href;
  257. }
  258. }
  259. }
  260. class LinkFacet extends Link
  261. {
  262. public function __construct($phref, $ptitle = NULL, $pfacetGroup = NULL, $pactiveFacet = FALSE) {
  263. parent::__construct ($phref, Link::OPDS_PAGING_TYPE, "http://opds-spec.org/facet", $ptitle, $pfacetGroup, $pactiveFacet);
  264. if (!is_null (GetUrlParam (DB))) $this->href = addURLParameter ($this->href, DB, GetUrlParam (DB));
  265. $this->href = $_SERVER["SCRIPT_NAME"] . $this->href;
  266. }
  267. }
  268. class Entry
  269. {
  270. public $title;
  271. public $id;
  272. public $content;
  273. public $contentType;
  274. public $linkArray;
  275. public $localUpdated;
  276. public $className;
  277. private static $updated = NULL;
  278. public static $icons = array(
  279. Author::ALL_AUTHORS_ID => 'images/author.png',
  280. Serie::ALL_SERIES_ID => 'images/serie.png',
  281. Book::ALL_RECENT_BOOKS_ID => 'images/recent.png',
  282. Tag::ALL_TAGS_ID => 'images/tag.png',
  283. Language::ALL_LANGUAGES_ID => 'images/language.png',
  284. CustomColumn::ALL_CUSTOMS_ID => 'images/tag.png',
  285. "cops:books$" => 'images/allbook.png',
  286. "cops:books:letter" => 'images/allbook.png',
  287. Publisher::ALL_PUBLISHERS_ID => 'images/publisher.png'
  288. );
  289. public function getUpdatedTime () {
  290. if (!is_null ($this->localUpdated)) {
  291. return date (DATE_ATOM, $this->localUpdated);
  292. }
  293. if (is_null (self::$updated)) {
  294. self::$updated = time();
  295. }
  296. return date (DATE_ATOM, self::$updated);
  297. }
  298. public function getNavLink () {
  299. foreach ($this->linkArray as $link) {
  300. if ($link->type != Link::OPDS_NAVIGATION_TYPE) { continue; }
  301. return $link->hrefXhtml ();
  302. }
  303. return "#";
  304. }
  305. public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pclass = "") {
  306. global $config;
  307. $this->title = $ptitle;
  308. $this->id = $pid;
  309. $this->content = $pcontent;
  310. $this->contentType = $pcontentType;
  311. $this->linkArray = $plinkArray;
  312. $this->className = $pclass;
  313. if ($config['cops_show_icons'] == 1)
  314. {
  315. foreach (self::$icons as $reg => $image)
  316. {
  317. if (preg_match ("/" . $reg . "/", $pid)) {
  318. array_push ($this->linkArray, new Link (getUrlWithVersion ($image), "image/png", Link::OPDS_THUMBNAIL_TYPE));
  319. break;
  320. }
  321. }
  322. }
  323. if (!is_null (GetUrlParam (DB))) $this->id = str_replace ("cops:", "cops:" . GetUrlParam (DB) . ":", $this->id);
  324. }
  325. }
  326. class EntryBook extends Entry
  327. {
  328. public $book;
  329. public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pbook) {
  330. parent::__construct ($ptitle, $pid, $pcontent, $pcontentType, $plinkArray);
  331. $this->book = $pbook;
  332. $this->localUpdated = $pbook->timestamp;
  333. }
  334. public function getCoverThumbnail () {
  335. foreach ($this->linkArray as $link) {
  336. if ($link->rel == Link::OPDS_THUMBNAIL_TYPE)
  337. return $link->hrefXhtml ();
  338. }
  339. return null;
  340. }
  341. public function getCover () {
  342. foreach ($this->linkArray as $link) {
  343. if ($link->rel == Link::OPDS_IMAGE_TYPE)
  344. return $link->hrefXhtml ();
  345. }
  346. return null;
  347. }
  348. }
  349. class Page
  350. {
  351. public $title;
  352. public $subtitle = "";
  353. public $authorName = "";
  354. public $authorUri = "";
  355. public $authorEmail = "";
  356. public $idPage;
  357. public $idGet;
  358. public $query;
  359. public $favicon;
  360. public $n;
  361. public $book;
  362. public $totalNumber = -1;
  363. public $entryArray = array();
  364. public static function getPage ($pageId, $id, $query, $n)
  365. {
  366. switch ($pageId) {
  367. case Base::PAGE_ALL_AUTHORS :
  368. return new PageAllAuthors ($id, $query, $n);
  369. case Base::PAGE_AUTHORS_FIRST_LETTER :
  370. return new PageAllAuthorsLetter ($id, $query, $n);
  371. case Base::PAGE_AUTHOR_DETAIL :
  372. return new PageAuthorDetail ($id, $query, $n);
  373. case Base::PAGE_ALL_TAGS :
  374. return new PageAllTags ($id, $query, $n);
  375. case Base::PAGE_TAG_DETAIL :
  376. return new PageTagDetail ($id, $query, $n);
  377. case Base::PAGE_ALL_LANGUAGES :
  378. return new PageAllLanguages ($id, $query, $n);
  379. case Base::PAGE_LANGUAGE_DETAIL :
  380. return new PageLanguageDetail ($id, $query, $n);
  381. case Base::PAGE_ALL_CUSTOMS :
  382. return new PageAllCustoms ($id, $query, $n);
  383. case Base::PAGE_CUSTOM_DETAIL :
  384. return new PageCustomDetail ($id, $query, $n);
  385. case Base::PAGE_ALL_SERIES :
  386. return new PageAllSeries ($id, $query, $n);
  387. case Base::PAGE_ALL_BOOKS :
  388. return new PageAllBooks ($id, $query, $n);
  389. case Base::PAGE_ALL_BOOKS_LETTER:
  390. return new PageAllBooksLetter ($id, $query, $n);
  391. case Base::PAGE_ALL_RECENT_BOOKS :
  392. return new PageRecentBooks ($id, $query, $n);
  393. case Base::PAGE_SERIE_DETAIL :
  394. return new PageSerieDetail ($id, $query, $n);
  395. case Base::PAGE_OPENSEARCH_QUERY :
  396. return new PageQueryResult ($id, $query, $n);
  397. case Base::PAGE_BOOK_DETAIL :
  398. return new PageBookDetail ($id, $query, $n);
  399. case Base::PAGE_ALL_PUBLISHERS:
  400. return new PageAllPublishers ($id, $query, $n);
  401. case Base::PAGE_PUBLISHER_DETAIL :
  402. return new PagePublisherDetail ($id, $query, $n);
  403. case Base::PAGE_ABOUT :
  404. return new PageAbout ($id, $query, $n);
  405. case Base::PAGE_CUSTOMIZE :
  406. return new PageCustomize ($id, $query, $n);
  407. default:
  408. $page = new Page ($id, $query, $n);
  409. $page->idPage = "cops:catalog";
  410. return $page;
  411. }
  412. }
  413. public function __construct($pid, $pquery, $pn) {
  414. global $config;
  415. $this->idGet = $pid;
  416. $this->query = $pquery;
  417. $this->n = $pn;
  418. $this->favicon = $config['cops_icon'];
  419. $this->authorName = empty($config['cops_author_name']) ? utf8_encode('Sébastien Lucas') : $config['cops_author_name'];
  420. $this->authorUri = empty($config['cops_author_uri']) ? 'http://blog.slucas.fr' : $config['cops_author_uri'];
  421. $this->authorEmail = empty($config['cops_author_email']) ? 'sebastien@slucas.fr' : $config['cops_author_email'];
  422. }
  423. public function InitializeContent ()
  424. {
  425. global $config;
  426. $this->title = $config['cops_title_default'];
  427. $this->subtitle = $config['cops_subtitle_default'];
  428. if (Base::noDatabaseSelected ()) {
  429. $i = 0;
  430. foreach (Base::getDbNameList () as $key) {
  431. $nBooks = Book::getBookCount ($i);
  432. array_push ($this->entryArray, new Entry ($key, "cops:{$i}:catalog",
  433. str_format (localize ("bookword", $nBooks), $nBooks), "text",
  434. array ( new LinkNavigation ("?" . DB . "={$i}"))));
  435. $i++;
  436. Base::clearDb ();
  437. }
  438. } else {
  439. if (!in_array (PageQueryResult::SCOPE_AUTHOR, getCurrentOption ('ignored_categories'))) {
  440. array_push ($this->entryArray, Author::getCount());
  441. }
  442. if (!in_array (PageQueryResult::SCOPE_SERIES, getCurrentOption ('ignored_categories'))) {
  443. $series = Serie::getCount();
  444. if (!is_null ($series)) array_push ($this->entryArray, $series);
  445. }
  446. if (!in_array (PageQueryResult::SCOPE_PUBLISHER, getCurrentOption ('ignored_categories'))) {
  447. $publisher = Publisher::getCount();
  448. if (!is_null ($publisher)) array_push ($this->entryArray, $publisher);
  449. }
  450. if (!in_array (PageQueryResult::SCOPE_TAG, getCurrentOption ('ignored_categories'))) {
  451. $tags = Tag::getCount();
  452. if (!is_null ($tags)) array_push ($this->entryArray, $tags);
  453. }
  454. if (!in_array ("language", getCurrentOption ('ignored_categories'))) {
  455. $languages = Language::getCount();
  456. if (!is_null ($languages)) array_push ($this->entryArray, $languages);
  457. }
  458. foreach ($config['cops_calibre_custom_column'] as $lookup) {
  459. $customId = CustomColumn::getCustomId ($lookup);
  460. if (!is_null ($customId)) {
  461. array_push ($this->entryArray, CustomColumn::getCount($customId));
  462. }
  463. }
  464. $this->entryArray = array_merge ($this->entryArray, Book::getCount());
  465. if (Base::isMultipleDatabaseEnabled ()) $this->title = Base::getDbName ();
  466. }
  467. }
  468. public function isPaginated ()
  469. {
  470. return (getCurrentOption ("max_item_per_page") != -1 &&
  471. $this->totalNumber != -1 &&
  472. $this->totalNumber > getCurrentOption ("max_item_per_page"));
  473. }
  474. public function getNextLink ()
  475. {
  476. $currentUrl = preg_replace ("/\&n=.*?$/", "", "?" . getQueryString ());
  477. if (($this->n) * getCurrentOption ("max_item_per_page") < $this->totalNumber) {
  478. return new LinkNavigation ($currentUrl . "&n=" . ($this->n + 1), "next", localize ("paging.next.alternate"));
  479. }
  480. return NULL;
  481. }
  482. public function getPrevLink ()
  483. {
  484. $currentUrl = preg_replace ("/\&n=.*?$/", "", "?" . getQueryString ());
  485. if ($this->n > 1) {
  486. return new LinkNavigation ($currentUrl . "&n=" . ($this->n - 1), "previous", localize ("paging.previous.alternate"));
  487. }
  488. return NULL;
  489. }
  490. public function getMaxPage ()
  491. {
  492. return ceil ($this->totalNumber / getCurrentOption ("max_item_per_page"));
  493. }
  494. public function containsBook ()
  495. {
  496. if (count ($this->entryArray) == 0) return false;
  497. if (get_class ($this->entryArray [0]) == "EntryBook") return true;
  498. return false;
  499. }
  500. }
  501. class PageAllAuthors extends Page
  502. {
  503. public function InitializeContent ()
  504. {
  505. $this->title = localize("authors.title");
  506. if (getCurrentOption ("author_split_first_letter") == 1) {
  507. $this->entryArray = Author::getAllAuthorsByFirstLetter();
  508. }
  509. else {
  510. $this->entryArray = Author::getAllAuthors();
  511. }
  512. $this->idPage = Author::ALL_AUTHORS_ID;
  513. }
  514. }
  515. class PageAllAuthorsLetter extends Page
  516. {
  517. public function InitializeContent ()
  518. {
  519. $this->idPage = Author::getEntryIdByLetter ($this->idGet);
  520. $this->entryArray = Author::getAuthorsByStartingLetter ($this->idGet);
  521. $this->title = str_format (localize ("splitByLetter.letter"), str_format (localize ("authorword", count ($this->entryArray)), count ($this->entryArray)), $this->idGet);
  522. }
  523. }
  524. class PageAuthorDetail extends Page
  525. {
  526. public function InitializeContent ()
  527. {
  528. $author = Author::getAuthorById ($this->idGet);
  529. $this->idPage = $author->getEntryId ();
  530. $this->title = $author->name;
  531. list ($this->entryArray, $this->totalNumber) = Book::getBooksByAuthor ($this->idGet, $this->n);
  532. }
  533. }
  534. class PageAllPublishers extends Page
  535. {
  536. public function InitializeContent ()
  537. {
  538. $this->title = localize("publishers.title");
  539. $this->entryArray = Publisher::getAllPublishers();
  540. $this->idPage = Publisher::ALL_PUBLISHERS_ID;
  541. }
  542. }
  543. class PagePublisherDetail extends Page
  544. {
  545. public function InitializeContent ()
  546. {
  547. $publisher = Publisher::getPublisherById ($this->idGet);
  548. $this->title = $publisher->name;
  549. list ($this->entryArray, $this->totalNumber) = Book::getBooksByPublisher ($this->idGet, $this->n);
  550. $this->idPage = $publisher->getEntryId ();
  551. }
  552. }
  553. class PageAllTags extends Page
  554. {
  555. public function InitializeContent ()
  556. {
  557. $this->title = localize("tags.title");
  558. $this->entryArray = Tag::getAllTags();
  559. $this->idPage = Tag::ALL_TAGS_ID;
  560. }
  561. }
  562. class PageAllLanguages extends Page
  563. {
  564. public function InitializeContent ()
  565. {
  566. $this->title = localize("languages.title");
  567. $this->entryArray = Language::getAllLanguages();
  568. $this->idPage = Language::ALL_LANGUAGES_ID;
  569. }
  570. }
  571. class PageCustomDetail extends Page
  572. {
  573. public function InitializeContent ()
  574. {
  575. $customId = getURLParam ("custom", NULL);
  576. $custom = CustomColumn::getCustomById ($customId, $this->idGet);
  577. $this->idPage = $custom->getEntryId ();
  578. $this->title = $custom->name;
  579. list ($this->entryArray, $this->totalNumber) = Book::getBooksByCustom ($customId, $this->idGet, $this->n);
  580. }
  581. }
  582. class PageAllCustoms extends Page
  583. {
  584. public function InitializeContent ()
  585. {
  586. $customId = getURLParam ("custom", NULL);
  587. $this->title = CustomColumn::getAllTitle ($customId);
  588. $this->entryArray = CustomColumn::getAllCustoms($customId);
  589. $this->idPage = CustomColumn::getAllCustomsId ($customId);
  590. }
  591. }
  592. class PageTagDetail extends Page
  593. {
  594. public function InitializeContent ()
  595. {
  596. $tag = Tag::getTagById ($this->idGet);
  597. $this->idPage = $tag->getEntryId ();
  598. $this->title = $tag->name;
  599. list ($this->entryArray, $this->totalNumber) = Book::getBooksByTag ($this->idGet, $this->n);
  600. }
  601. }
  602. class PageLanguageDetail extends Page
  603. {
  604. public function InitializeContent ()
  605. {
  606. $language = Language::getLanguageById ($this->idGet);
  607. $this->idPage = $language->getEntryId ();
  608. $this->title = $language->lang_code;
  609. list ($this->entryArray, $this->totalNumber) = Book::getBooksByLanguage ($this->idGet, $this->n);
  610. }
  611. }
  612. class PageAllSeries extends Page
  613. {
  614. public function InitializeContent ()
  615. {
  616. $this->title = localize("series.title");
  617. $this->entryArray = Serie::getAllSeries();
  618. $this->idPage = Serie::ALL_SERIES_ID;
  619. }
  620. }
  621. class PageSerieDetail extends Page
  622. {
  623. public function InitializeContent ()
  624. {
  625. $serie = Serie::getSerieById ($this->idGet);
  626. $this->title = $serie->name;
  627. list ($this->entryArray, $this->totalNumber) = Book::getBooksBySeries ($this->idGet, $this->n);
  628. $this->idPage = $serie->getEntryId ();
  629. }
  630. }
  631. class PageAllBooks extends Page
  632. {
  633. public function InitializeContent ()
  634. {
  635. $this->title = localize ("allbooks.title");
  636. if (getCurrentOption ("titles_split_first_letter") == 1) {
  637. $this->entryArray = Book::getAllBooks();
  638. }
  639. else {
  640. list ($this->entryArray, $this->totalNumber) = Book::getBooks ($this->n);
  641. }
  642. $this->idPage = Book::ALL_BOOKS_ID;
  643. }
  644. }
  645. class PageAllBooksLetter extends Page
  646. {
  647. public function InitializeContent ()
  648. {
  649. list ($this->entryArray, $this->totalNumber) = Book::getBooksByStartingLetter ($this->idGet, $this->n);
  650. $this->idPage = Book::getEntryIdByLetter ($this->idGet);
  651. $count = $this->totalNumber;
  652. if ($count == -1)
  653. $count = count ($this->entryArray);
  654. $this->title = str_format (localize ("splitByLetter.letter"), str_format (localize ("bookword", $count), $count), $this->idGet);
  655. }
  656. }
  657. class PageRecentBooks extends Page
  658. {
  659. public function InitializeContent ()
  660. {
  661. $this->title = localize ("recent.title");
  662. $this->entryArray = Book::getAllRecentBooks ();
  663. $this->idPage = Book::ALL_RECENT_BOOKS_ID;
  664. }
  665. }
  666. class PageQueryResult extends Page
  667. {
  668. const SCOPE_TAG = "tag";
  669. const SCOPE_SERIES = "series";
  670. const SCOPE_AUTHOR = "author";
  671. const SCOPE_BOOK = "book";
  672. const SCOPE_PUBLISHER = "publisher";
  673. private function useTypeahead () {
  674. return !is_null (getURLParam ("search"));
  675. }
  676. private function searchByScope ($scope, $limit = FALSE) {
  677. $n = $this->n;
  678. $numberPerPage = NULL;
  679. if ($limit) {
  680. $n = 1;
  681. $numberPerPage = 5;
  682. }
  683. switch ($scope) {
  684. case self::SCOPE_BOOK :
  685. $array = Book::getBooksByStartingLetter ('%' . $this->query, $n, NULL, $numberPerPage);
  686. break;
  687. case self::SCOPE_AUTHOR :
  688. $array = Author::getAuthorsByStartingLetter ('%' . $this->query);
  689. break;
  690. case self::SCOPE_SERIES :
  691. $array = Serie::getAllSeriesByQuery ($this->query);
  692. break;
  693. case self::SCOPE_TAG :
  694. $array = Tag::getAllTagsByQuery ($this->query, $n, NULL, $numberPerPage);
  695. break;
  696. case self::SCOPE_PUBLISHER :
  697. $array = Publisher::getAllPublishersByQuery ($this->query);
  698. break;
  699. default:
  700. $array = Book::getBooksByQuery (
  701. array ("all" => "%" . $this->query . "%"), $n);
  702. }
  703. return $array;
  704. }
  705. public function doSearchByCategory () {
  706. $database = GetUrlParam (DB);
  707. $out = array ();
  708. $pagequery = Base::PAGE_OPENSEARCH_QUERY;
  709. $dbArray = array ("");
  710. $d = $database;
  711. $query = $this->query;
  712. // Special case when no databases were chosen, we search on all databases
  713. if (Base::noDatabaseSelected ()) {
  714. $dbArray = Base::getDbNameList ();
  715. $d = 0;
  716. }
  717. foreach ($dbArray as $key) {
  718. if (Base::noDatabaseSelected ()) {
  719. array_push ($this->entryArray, new Entry ($key, DB . ":query:{$d}",
  720. " ", "text",
  721. array ( new LinkNavigation ("?" . DB . "={$d}")), "tt-header"));
  722. Base::getDb ($d);
  723. }
  724. foreach (array (PageQueryResult::SCOPE_BOOK,
  725. PageQueryResult::SCOPE_AUTHOR,
  726. PageQueryResult::SCOPE_SERIES,
  727. PageQueryResult::SCOPE_TAG,
  728. PageQueryResult::SCOPE_PUBLISHER) as $key) {
  729. if (in_array($key, getCurrentOption ('ignored_categories'))) {
  730. continue;
  731. }
  732. $array = $this->searchByScope ($key, TRUE);
  733. $i = 0;
  734. if (count ($array) == 2 && is_array ($array [0])) {
  735. $total = $array [1];
  736. $array = $array [0];
  737. } else {
  738. $total = count($array);
  739. }
  740. if ($total > 0) {
  741. // Comment to help the perl i18n script
  742. // str_format (localize("bookword", count($array))
  743. // str_format (localize("authorword", count($array))
  744. // str_format (localize("seriesword", count($array))
  745. // str_format (localize("tagword", count($array))
  746. // str_format (localize("publisherword", count($array))
  747. array_push ($this->entryArray, new Entry (str_format (localize ("search.result.{$key}"), $this->query), DB . ":query:{$d}:{$key}",
  748. str_format (localize("{$key}word", $total), $total), "text",
  749. array ( new LinkNavigation ("?page={$pagequery}&query={$query}&db={$d}&scope={$key}")),
  750. Base::noDatabaseSelected () ? "" : "tt-header"));
  751. }
  752. if (!Base::noDatabaseSelected () && $this->useTypeahead ()) {
  753. foreach ($array as $entry) {
  754. array_push ($this->entryArray, $entry);
  755. $i++;
  756. if ($i > 4) { break; };
  757. }
  758. }
  759. }
  760. $d++;
  761. if (Base::noDatabaseSelected ()) {
  762. Base::clearDb ();
  763. }
  764. }
  765. return $out;
  766. }
  767. public function InitializeContent ()
  768. {
  769. $scope = getURLParam ("scope");
  770. if (empty ($scope)) {
  771. $this->title = str_format (localize ("search.result"), $this->query);
  772. } else {
  773. // Comment to help the perl i18n script
  774. // str_format (localize ("search.result.author"), $this->query)
  775. // str_format (localize ("search.result.tag"), $this->query)
  776. // str_format (localize ("search.result.series"), $this->query)
  777. // str_format (localize ("search.result.book"), $this->query)
  778. // str_format (localize ("search.result.publisher"), $this->query)
  779. $this->title = str_format (localize ("search.result.{$scope}"), $this->query);
  780. }
  781. $crit = "%" . $this->query . "%";
  782. // Special case when we are doing a search and no database is selected
  783. if (Base::noDatabaseSelected () && !$this->useTypeahead ()) {
  784. $i = 0;
  785. foreach (Base::getDbNameList () as $key) {
  786. Base::clearDb ();
  787. list ($array, $totalNumber) = Book::getBooksByQuery (array ("all" => $crit), 1, $i, 1);
  788. array_push ($this->entryArray, new Entry ($key, DB . ":query:{$i}",
  789. str_format (localize ("bookword", $totalNumber), $totalNumber), "text",
  790. array ( new LinkNavigation ("?" . DB . "={$i}&page=9&query=" . $this->query))));
  791. $i++;
  792. }
  793. return;
  794. }
  795. if (empty ($scope)) {
  796. $this->doSearchByCategory ();
  797. return;
  798. }
  799. $array = $this->searchByScope ($scope);
  800. if (count ($array) == 2 && is_array ($array [0])) {
  801. list ($this->entryArray, $this->totalNumber) = $array;
  802. } else {
  803. $this->entryArray = $array;
  804. }
  805. }
  806. }
  807. class PageBookDetail extends Page
  808. {
  809. public function InitializeContent ()
  810. {
  811. $this->book = Book::getBookById ($this->idGet);
  812. $this->title = $this->book->title;
  813. }
  814. }
  815. class PageAbout extends Page
  816. {
  817. public function InitializeContent ()
  818. {
  819. $this->title = localize ("about.title");
  820. }
  821. }
  822. class PageCustomize extends Page
  823. {
  824. private function isChecked ($key, $testedValue = 1) {
  825. $value = getCurrentOption ($key);
  826. if (is_array ($value)) {
  827. if (in_array ($testedValue, $value)) {
  828. return "checked='checked'";
  829. }
  830. } else {
  831. if ($value == $testedValue) {
  832. return "checked='checked'";
  833. }
  834. }
  835. return "";
  836. }
  837. private function isSelected ($key, $value) {
  838. if (getCurrentOption ($key) == $value) {
  839. return "selected='selected'";
  840. }
  841. return "";
  842. }
  843. private function getStyleList () {
  844. $result = array ();
  845. foreach (glob ("styles/style-*.css") as $filename) {
  846. if (preg_match ('/styles\/style-(.*?)\.css/', $filename, $m)) {
  847. array_push ($result, $m [1]);
  848. }
  849. }
  850. return $result;
  851. }
  852. public function InitializeContent ()
  853. {
  854. $this->title = localize ("customize.title");
  855. $this->entryArray = array ();
  856. $ignoredBaseArray = array (PageQueryResult::SCOPE_AUTHOR,
  857. PageQueryResult::SCOPE_TAG,
  858. PageQueryResult::SCOPE_SERIES,
  859. PageQueryResult::SCOPE_PUBLISHER,
  860. "language");
  861. $content = "";
  862. if (!preg_match("/(Kobo|Kindle\/3.0|EBRD1101)/", $_SERVER['HTTP_USER_AGENT'])) {
  863. $content .= '<select id="style" onchange="updateCookie (this);">';
  864. foreach ($this-> getStyleList () as $filename) {
  865. $content .= "<option value='{$filename}' " . $this->isSelected ("style", $filename) . ">{$filename}</option>";
  866. }
  867. $content .= '</select>';
  868. } else {
  869. foreach ($this-> getStyleList () as $filename) {
  870. $content .= "<input type='radio' onchange='updateCookieFromCheckbox (this);' id='style-{$filename}' name='style' value='{$filename}' " . $this->isChecked ("style", $filename) . " /><label for='style-{$filename}'> {$filename} </label>";
  871. }
  872. }
  873. array_push ($this->entryArray, new Entry (localize ("customize.style"), "",
  874. $content, "text",
  875. array ()));
  876. if (!useServerSideRendering ()) {
  877. $content = '<input type="checkbox" onchange="updateCookieFromCheckbox (this);" id="use_fancyapps" ' . $this->isChecked ("use_fancyapps") . ' />';
  878. array_push ($this->entryArray, new Entry (localize ("customize.fancybox"), "",
  879. $content, "text",
  880. array ()));
  881. }
  882. $content = '<input type="number" onchange="updateCookie (this);" id="max_item_per_page" value="' . getCurrentOption ("max_item_per_page") . '" min="-1" max="1200" pattern="^[-+]?[0-9]+$" />';
  883. array_push ($this->entryArray, new Entry (localize ("customize.paging"), "",
  884. $content, "text",
  885. array ()));
  886. $content = '<input type="text" onchange="updateCookie (this);" id="email" value="' . getCurrentOption ("email") . '" />';
  887. array_push ($this->entryArray, new Entry (localize ("customize.email"), "",
  888. $content, "text",
  889. array ()));
  890. $content = '<input type="checkbox" onchange="updateCookieFromCheckbox (this);" id="html_tag_filter" ' . $this->isChecked ("html_tag_filter") . ' />';
  891. array_push ($this->entryArray, new Entry (localize ("customize.filter"), "",
  892. $content, "text",
  893. array ()));
  894. $content = "";
  895. foreach ($ignoredBaseArray as $key) {
  896. $keyPlural = preg_replace ('/(ss)$/', 's', $key . "s");
  897. $content .= '<input type="checkbox" name="ignored_categories[]" onchange="updateCookieFromCheckboxGroup (this);" id="ignored_categories_' . $key . '" ' . $this->isChecked ("ignored_categories", $key) . ' > ' . localize ("{$keyPlural}.title") . '</input> ';
  898. }
  899. array_push ($this->entryArray, new Entry (localize ("customize.ignored"), "",
  900. $content, "text",
  901. array ()));
  902. }
  903. }
  904. abstract class Base
  905. {
  906. const PAGE_INDEX = "index";
  907. const PAGE_ALL_AUTHORS = "1";
  908. const PAGE_AUTHORS_FIRST_LETTER = "2";
  909. const PAGE_AUTHOR_DETAIL = "3";
  910. const PAGE_ALL_BOOKS = "4";
  911. const PAGE_ALL_BOOKS_LETTER = "5";
  912. const PAGE_ALL_SERIES = "6";
  913. const PAGE_SERIE_DETAIL = "7";
  914. const PAGE_OPENSEARCH = "8";
  915. const PAGE_OPENSEARCH_QUERY = "9";
  916. const PAGE_ALL_RECENT_BOOKS = "10";
  917. const PAGE_ALL_TAGS = "11";
  918. const PAGE_TAG_DETAIL = "12";
  919. const PAGE_BOOK_DETAIL = "13";
  920. const PAGE_ALL_CUSTOMS = "14";
  921. const PAGE_CUSTOM_DETAIL = "15";
  922. const PAGE_ABOUT = "16";
  923. const PAGE_ALL_LANGUAGES = "17";
  924. const PAGE_LANGUAGE_DETAIL = "18";
  925. const PAGE_CUSTOMIZE = "19";
  926. const PAGE_ALL_PUBLISHERS = "20";
  927. const PAGE_PUBLISHER_DETAIL = "21";
  928. const COMPATIBILITY_XML_ALDIKO = "aldiko";
  929. private static $db = NULL;
  930. public static function isMultipleDatabaseEnabled () {
  931. global $config;
  932. return is_array ($config['calibre_directory']);
  933. }
  934. public static function noDatabaseSelected () {
  935. return self::isMultipleDatabaseEnabled () && is_null (GetUrlParam (DB));
  936. }
  937. public static function getDbList () {
  938. global $config;
  939. if (self::isMultipleDatabaseEnabled ()) {
  940. return $config['calibre_directory'];
  941. } else {
  942. return array ("" => $config['calibre_directory']);
  943. }
  944. }
  945. public static function getDbNameList () {
  946. global $config;
  947. if (self::isMultipleDatabaseEnabled ()) {
  948. return array_keys ($config['calibre_directory']);
  949. } else {
  950. return array ("");
  951. }
  952. }
  953. public static function getDbName ($database = NULL) {
  954. global $config;
  955. if (self::isMultipleDatabaseEnabled ()) {
  956. if (is_null ($database)) $database = GetUrlParam (DB, 0);
  957. $array = array_keys ($config['calibre_directory']);
  958. return $array[$database];
  959. }
  960. return "";
  961. }
  962. public static function getDbDirectory ($database = NULL) {
  963. global $config;
  964. if (self::isMultipleDatabaseEnabled ()) {
  965. if (is_null ($database)) $database = GetUrlParam (DB, 0);
  966. $array = array_values ($config['calibre_directory']);
  967. return $array[$database];
  968. }
  969. return $config['calibre_directory'];
  970. }
  971. public static function getDbFileName ($database = NULL) {
  972. return self::getDbDirectory ($database) .'metadata.db';
  973. }
  974. private static function error () {
  975. if (php_sapi_name() != "cli") {
  976. header("location: checkconfig.php?err=1");
  977. }
  978. throw new Exception('Database not found.');
  979. }
  980. public static function getDb ($database = NULL) {
  981. if (is_null (self::$db)) {
  982. try {
  983. if (is_readable (self::getDbFileName ($database))) {
  984. self::$db = new PDO('sqlite:'. self::getDbFileName ($database));
  985. } else {
  986. self::error ();
  987. }
  988. } catch (Exception $e) {
  989. self::error ();
  990. }
  991. }
  992. return self::$db;
  993. }
  994. public static function checkDatabaseAvailability () {
  995. if (self::noDatabaseSelected ()) {
  996. for ($i = 0; $i < count (self::getDbList ()); $i++) {
  997. self::getDb ($i);
  998. self::clearDb ();
  999. }
  1000. } else {
  1001. self::getDb ();
  1002. }
  1003. return true;
  1004. }
  1005. public static function clearDb () {
  1006. self::$db = NULL;
  1007. }
  1008. public static function executeQuery($query, $columns, $filter, $params, $n, $database = NULL, $numberPerPage = NULL) {
  1009. $totalResult = -1;
  1010. if (is_null ($numberPerPage)) {
  1011. $numberPerPage = getCurrentOption ("max_item_per_page");
  1012. }
  1013. if ($numberPerPage != -1 && $n != -1)
  1014. {
  1015. // First check total number of results
  1016. $result = self::getDb ($database)->prepare (str_format ($query, "count(*)", $filter));
  1017. $result->execute ($params);
  1018. $totalResult = $result->fetchColumn ();
  1019. // Next modify the query and params
  1020. $query .= " limit ?, ?";
  1021. array_push ($params, ($n - 1) * $numberPerPage, $numberPerPage);
  1022. }
  1023. $result = self::getDb ($database)->prepare(str_format ($query, $columns, $filter));
  1024. $result->execute ($params);
  1025. return array ($totalResult, $result);
  1026. }
  1027. }