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.

1337 lines
47KB

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