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.

1336 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 = $_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. parent::__construct ($phref, Link::OPDS_PAGING_TYPE, "http://opds-spec.org/facet", $ptitle, $pfacetGroup, $pactiveFacet);
  340. if (!is_null (GetUrlParam (DB))) $this->href = addURLParameter ($this->href, DB, GetUrlParam (DB));
  341. $this->href = $_SERVER["SCRIPT_NAME"] . $this->href;
  342. }
  343. }
  344. class Entry
  345. {
  346. public $title;
  347. public $id;
  348. public $content;
  349. public $numberOfElement;
  350. public $contentType;
  351. public $linkArray;
  352. public $localUpdated;
  353. public $className;
  354. private static $updated = NULL;
  355. public static $icons = array(
  356. Author::ALL_AUTHORS_ID => 'images/author.png',
  357. Serie::ALL_SERIES_ID => 'images/serie.png',
  358. Book::ALL_RECENT_BOOKS_ID => 'images/recent.png',
  359. Tag::ALL_TAGS_ID => 'images/tag.png',
  360. Language::ALL_LANGUAGES_ID => 'images/language.png',
  361. CustomColumn::ALL_CUSTOMS_ID => 'images/tag.png',
  362. "cops:books$" => 'images/allbook.png',
  363. "cops:books:letter" => 'images/allbook.png',
  364. Publisher::ALL_PUBLISHERS_ID => 'images/publisher.png'
  365. );
  366. public function getUpdatedTime () {
  367. if (!is_null ($this->localUpdated)) {
  368. return date (DATE_ATOM, $this->localUpdated);
  369. }
  370. if (is_null (self::$updated)) {
  371. self::$updated = time();
  372. }
  373. return date (DATE_ATOM, self::$updated);
  374. }
  375. public function getNavLink () {
  376. foreach ($this->linkArray as $link) {
  377. if ($link->type != Link::OPDS_NAVIGATION_TYPE) { continue; }
  378. return $link->hrefXhtml ();
  379. }
  380. return "#";
  381. }
  382. public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pclass = "", $pcount = 0) {
  383. global $config;
  384. $this->title = $ptitle;
  385. $this->id = $pid;
  386. $this->content = $pcontent;
  387. $this->contentType = $pcontentType;
  388. $this->linkArray = $plinkArray;
  389. $this->className = $pclass;
  390. $this->numberOfElement = $pcount;
  391. if ($config['cops_show_icons'] == 1)
  392. {
  393. foreach (self::$icons as $reg => $image)
  394. {
  395. if (preg_match ("/" . $reg . "/", $pid)) {
  396. array_push ($this->linkArray, new Link (getUrlWithVersion ($image), "image/png", Link::OPDS_THUMBNAIL_TYPE));
  397. break;
  398. }
  399. }
  400. }
  401. if (!is_null (GetUrlParam (DB))) $this->id = str_replace ("cops:", "cops:" . GetUrlParam (DB) . ":", $this->id);
  402. }
  403. }
  404. class EntryBook extends Entry
  405. {
  406. public $book;
  407. public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pbook) {
  408. parent::__construct ($ptitle, $pid, $pcontent, $pcontentType, $plinkArray);
  409. $this->book = $pbook;
  410. $this->localUpdated = $pbook->timestamp;
  411. }
  412. public function getCoverThumbnail () {
  413. foreach ($this->linkArray as $link) {
  414. if ($link->rel == Link::OPDS_THUMBNAIL_TYPE)
  415. return $link->hrefXhtml ();
  416. }
  417. return null;
  418. }
  419. public function getCover () {
  420. foreach ($this->linkArray as $link) {
  421. if ($link->rel == Link::OPDS_IMAGE_TYPE)
  422. return $link->hrefXhtml ();
  423. }
  424. return null;
  425. }
  426. }
  427. class Page
  428. {
  429. public $title;
  430. public $subtitle = "";
  431. public $authorName = "";
  432. public $authorUri = "";
  433. public $authorEmail = "";
  434. public $idPage;
  435. public $idGet;
  436. public $query;
  437. public $favicon;
  438. public $n;
  439. public $book;
  440. public $totalNumber = -1;
  441. public $entryArray = array();
  442. public static function getPage ($pageId, $id, $query, $n)
  443. {
  444. switch ($pageId) {
  445. case Base::PAGE_ALL_AUTHORS :
  446. return new PageAllAuthors ($id, $query, $n);
  447. case Base::PAGE_AUTHORS_FIRST_LETTER :
  448. return new PageAllAuthorsLetter ($id, $query, $n);
  449. case Base::PAGE_AUTHOR_DETAIL :
  450. return new PageAuthorDetail ($id, $query, $n);
  451. case Base::PAGE_ALL_TAGS :
  452. return new PageAllTags ($id, $query, $n);
  453. case Base::PAGE_TAG_DETAIL :
  454. return new PageTagDetail ($id, $query, $n);
  455. case Base::PAGE_ALL_LANGUAGES :
  456. return new PageAllLanguages ($id, $query, $n);
  457. case Base::PAGE_LANGUAGE_DETAIL :
  458. return new PageLanguageDetail ($id, $query, $n);
  459. case Base::PAGE_ALL_CUSTOMS :
  460. return new PageAllCustoms ($id, $query, $n);
  461. case Base::PAGE_CUSTOM_DETAIL :
  462. return new PageCustomDetail ($id, $query, $n);
  463. case Base::PAGE_ALL_RATINGS :
  464. return new PageAllRating ($id, $query, $n);
  465. case Base::PAGE_RATING_DETAIL :
  466. return new PageRatingDetail ($id, $query, $n);
  467. case Base::PAGE_ALL_SERIES :
  468. return new PageAllSeries ($id, $query, $n);
  469. case Base::PAGE_ALL_BOOKS :
  470. return new PageAllBooks ($id, $query, $n);
  471. case Base::PAGE_ALL_BOOKS_LETTER:
  472. return new PageAllBooksLetter ($id, $query, $n);
  473. case Base::PAGE_ALL_RECENT_BOOKS :
  474. return new PageRecentBooks ($id, $query, $n);
  475. case Base::PAGE_SERIE_DETAIL :
  476. return new PageSerieDetail ($id, $query, $n);
  477. case Base::PAGE_OPENSEARCH_QUERY :
  478. return new PageQueryResult ($id, $query, $n);
  479. case Base::PAGE_BOOK_DETAIL :
  480. return new PageBookDetail ($id, $query, $n);
  481. case Base::PAGE_ALL_PUBLISHERS:
  482. return new PageAllPublishers ($id, $query, $n);
  483. case Base::PAGE_PUBLISHER_DETAIL :
  484. return new PagePublisherDetail ($id, $query, $n);
  485. case Base::PAGE_ABOUT :
  486. return new PageAbout ($id, $query, $n);
  487. case Base::PAGE_CUSTOMIZE :
  488. return new PageCustomize ($id, $query, $n);
  489. default:
  490. $page = new Page ($id, $query, $n);
  491. $page->idPage = "cops:catalog";
  492. return $page;
  493. }
  494. }
  495. public function __construct($pid, $pquery, $pn) {
  496. global $config;
  497. $this->idGet = $pid;
  498. $this->query = $pquery;
  499. $this->n = $pn;
  500. $this->favicon = $config['cops_icon'];
  501. $this->authorName = empty($config['cops_author_name']) ? utf8_encode('S�bastien Lucas') : $config['cops_author_name'];
  502. $this->authorUri = empty($config['cops_author_uri']) ? 'http://blog.slucas.fr' : $config['cops_author_uri'];
  503. $this->authorEmail = empty($config['cops_author_email']) ? 'sebastien@slucas.fr' : $config['cops_author_email'];
  504. }
  505. public function InitializeContent ()
  506. {
  507. global $config;
  508. $this->title = $config['cops_title_default'];
  509. $this->subtitle = $config['cops_subtitle_default'];
  510. if (Base::noDatabaseSelected ()) {
  511. $i = 0;
  512. foreach (Base::getDbNameList () as $key) {
  513. $nBooks = Book::getBookCount ($i);
  514. array_push ($this->entryArray, new Entry ($key, "cops:{$i}:catalog",
  515. str_format (localize ("bookword", $nBooks), $nBooks), "text",
  516. array ( new LinkNavigation ("?" . DB . "={$i}")), "", $nBooks));
  517. $i++;
  518. Base::clearDb ();
  519. }
  520. } else {
  521. if (!in_array (PageQueryResult::SCOPE_AUTHOR, getCurrentOption ('ignored_categories'))) {
  522. array_push ($this->entryArray, Author::getCount());
  523. }
  524. if (!in_array (PageQueryResult::SCOPE_SERIES, getCurrentOption ('ignored_categories'))) {
  525. $series = Serie::getCount();
  526. if (!is_null ($series)) array_push ($this->entryArray, $series);
  527. }
  528. if (!in_array (PageQueryResult::SCOPE_PUBLISHER, getCurrentOption ('ignored_categories'))) {
  529. $publisher = Publisher::getCount();
  530. if (!is_null ($publisher)) array_push ($this->entryArray, $publisher);
  531. }
  532. if (!in_array (PageQueryResult::SCOPE_TAG, getCurrentOption ('ignored_categories'))) {
  533. $tags = Tag::getCount();
  534. if (!is_null ($tags)) array_push ($this->entryArray, $tags);
  535. }
  536. if (!in_array (PageQueryResult::SCOPE_RATING, getCurrentOption ('ignored_categories'))) {
  537. $rating = Rating::getCount();
  538. if (!is_null ($rating)) array_push ($this->entryArray, $rating);
  539. }
  540. if (!in_array ("language", getCurrentOption ('ignored_categories'))) {
  541. $languages = Language::getCount();
  542. if (!is_null ($languages)) array_push ($this->entryArray, $languages);
  543. }
  544. foreach ($config['cops_calibre_custom_column'] as $lookup) {
  545. $customId = CustomColumn::getCustomId ($lookup);
  546. if (!is_null ($customId)) {
  547. array_push ($this->entryArray, CustomColumn::getCount($customId));
  548. }
  549. }
  550. $this->entryArray = array_merge ($this->entryArray, Book::getCount());
  551. if (Base::isMultipleDatabaseEnabled ()) $this->title = Base::getDbName ();
  552. }
  553. }
  554. public function isPaginated ()
  555. {
  556. return (getCurrentOption ("max_item_per_page") != -1 &&
  557. $this->totalNumber != -1 &&
  558. $this->totalNumber > getCurrentOption ("max_item_per_page"));
  559. }
  560. public function getNextLink ()
  561. {
  562. $currentUrl = preg_replace ("/\&n=.*?$/", "", "?" . getQueryString ());
  563. if (($this->n) * getCurrentOption ("max_item_per_page") < $this->totalNumber) {
  564. return new LinkNavigation ($currentUrl . "&n=" . ($this->n + 1), "next", localize ("paging.next.alternate"));
  565. }
  566. return NULL;
  567. }
  568. public function getPrevLink ()
  569. {
  570. $currentUrl = preg_replace ("/\&n=.*?$/", "", "?" . getQueryString ());
  571. if ($this->n > 1) {
  572. return new LinkNavigation ($currentUrl . "&n=" . ($this->n - 1), "previous", localize ("paging.previous.alternate"));
  573. }
  574. return NULL;
  575. }
  576. public function getMaxPage ()
  577. {
  578. return ceil ($this->totalNumber / getCurrentOption ("max_item_per_page"));
  579. }
  580. public function containsBook ()
  581. {
  582. if (count ($this->entryArray) == 0) return false;
  583. if (get_class ($this->entryArray [0]) == "EntryBook") return true;
  584. return false;
  585. }
  586. }
  587. class PageAllAuthors extends Page
  588. {
  589. public function InitializeContent ()
  590. {
  591. $this->title = localize("authors.title");
  592. if (getCurrentOption ("author_split_first_letter") == 1) {
  593. $this->entryArray = Author::getAllAuthorsByFirstLetter();
  594. }
  595. else {
  596. $this->entryArray = Author::getAllAuthors();
  597. }
  598. $this->idPage = Author::ALL_AUTHORS_ID;
  599. }
  600. }
  601. class PageAllAuthorsLetter extends Page
  602. {
  603. public function InitializeContent ()
  604. {
  605. $this->idPage = Author::getEntryIdByLetter ($this->idGet);
  606. $this->entryArray = Author::getAuthorsByStartingLetter ($this->idGet);
  607. $this->title = str_format (localize ("splitByLetter.letter"), str_format (localize ("authorword", count ($this->entryArray)), count ($this->entryArray)), $this->idGet);
  608. }
  609. }
  610. class PageAuthorDetail extends Page
  611. {
  612. public function InitializeContent ()
  613. {
  614. $author = Author::getAuthorById ($this->idGet);
  615. $this->idPage = $author->getEntryId ();
  616. $this->title = $author->name;
  617. list ($this->entryArray, $this->totalNumber) = Book::getBooksByAuthor ($this->idGet, $this->n);
  618. }
  619. }
  620. class PageAllPublishers extends Page
  621. {
  622. public function InitializeContent ()
  623. {
  624. $this->title = localize("publishers.title");
  625. $this->entryArray = Publisher::getAllPublishers();
  626. $this->idPage = Publisher::ALL_PUBLISHERS_ID;
  627. }
  628. }
  629. class PagePublisherDetail extends Page
  630. {
  631. public function InitializeContent ()
  632. {
  633. $publisher = Publisher::getPublisherById ($this->idGet);
  634. $this->title = $publisher->name;
  635. list ($this->entryArray, $this->totalNumber) = Book::getBooksByPublisher ($this->idGet, $this->n);
  636. $this->idPage = $publisher->getEntryId ();
  637. }
  638. }
  639. class PageAllTags extends Page
  640. {
  641. public function InitializeContent ()
  642. {
  643. $this->title = localize("tags.title");
  644. $this->entryArray = Tag::getAllTags();
  645. $this->idPage = Tag::ALL_TAGS_ID;
  646. }
  647. }
  648. class PageAllLanguages extends Page
  649. {
  650. public function InitializeContent ()
  651. {
  652. $this->title = localize("languages.title");
  653. $this->entryArray = Language::getAllLanguages();
  654. $this->idPage = Language::ALL_LANGUAGES_ID;
  655. }
  656. }
  657. class PageCustomDetail extends Page
  658. {
  659. public function InitializeContent ()
  660. {
  661. $customId = getURLParam ("custom", NULL);
  662. $custom = CustomColumn::getCustomById ($customId, $this->idGet);
  663. $this->idPage = $custom->getEntryId ();
  664. $this->title = $custom->name;
  665. list ($this->entryArray, $this->totalNumber) = Book::getBooksByCustom ($customId, $this->idGet, $this->n);
  666. }
  667. }
  668. class PageAllCustoms extends Page
  669. {
  670. public function InitializeContent ()
  671. {
  672. $customId = getURLParam ("custom", NULL);
  673. $this->title = CustomColumn::getAllTitle ($customId);
  674. $this->entryArray = CustomColumn::getAllCustoms($customId);
  675. $this->idPage = CustomColumn::getAllCustomsId ($customId);
  676. }
  677. }
  678. class PageTagDetail extends Page
  679. {
  680. public function InitializeContent ()
  681. {
  682. $tag = Tag::getTagById ($this->idGet);
  683. $this->idPage = $tag->getEntryId ();
  684. $this->title = $tag->name;
  685. list ($this->entryArray, $this->totalNumber) = Book::getBooksByTag ($this->idGet, $this->n);
  686. }
  687. }
  688. class PageLanguageDetail extends Page
  689. {
  690. public function InitializeContent ()
  691. {
  692. $language = Language::getLanguageById ($this->idGet);
  693. $this->idPage = $language->getEntryId ();
  694. $this->title = $language->lang_code;
  695. list ($this->entryArray, $this->totalNumber) = Book::getBooksByLanguage ($this->idGet, $this->n);
  696. }
  697. }
  698. class PageAllSeries extends Page
  699. {
  700. public function InitializeContent ()
  701. {
  702. $this->title = localize("series.title");
  703. $this->entryArray = Serie::getAllSeries();
  704. $this->idPage = Serie::ALL_SERIES_ID;
  705. }
  706. }
  707. class PageSerieDetail extends Page
  708. {
  709. public function InitializeContent ()
  710. {
  711. $serie = Serie::getSerieById ($this->idGet);
  712. $this->title = $serie->name;
  713. list ($this->entryArray, $this->totalNumber) = Book::getBooksBySeries ($this->idGet, $this->n);
  714. $this->idPage = $serie->getEntryId ();
  715. }
  716. }
  717. class PageAllRating extends Page
  718. {
  719. public function InitializeContent ()
  720. {
  721. $this->title = localize("ratings.title");
  722. $this->entryArray = Rating::getAllRatings();
  723. $this->idPage = Rating::ALL_RATING_ID;
  724. }
  725. }
  726. class PageRatingDetail extends Page
  727. {
  728. public function InitializeContent ()
  729. {
  730. $rating = Rating::getRatingById ($this->idGet);
  731. $this->idPage = $rating->getEntryId ();
  732. $this->title =str_format (localize ("ratingword", $rating->name/2), $rating->name/2);
  733. list ($this->entryArray, $this->totalNumber) = Book::getBooksByRating ($this->idGet, $this->n);
  734. }
  735. }
  736. class PageAllBooks extends Page
  737. {
  738. public function InitializeContent ()
  739. {
  740. $this->title = localize ("allbooks.title");
  741. if (getCurrentOption ("titles_split_first_letter") == 1) {
  742. $this->entryArray = Book::getAllBooks();
  743. }
  744. else {
  745. list ($this->entryArray, $this->totalNumber) = Book::getBooks ($this->n);
  746. }
  747. $this->idPage = Book::ALL_BOOKS_ID;
  748. }
  749. }
  750. class PageAllBooksLetter extends Page
  751. {
  752. public function InitializeContent ()
  753. {
  754. list ($this->entryArray, $this->totalNumber) = Book::getBooksByStartingLetter ($this->idGet, $this->n);
  755. $this->idPage = Book::getEntryIdByLetter ($this->idGet);
  756. $count = $this->totalNumber;
  757. if ($count == -1)
  758. $count = count ($this->entryArray);
  759. $this->title = str_format (localize ("splitByLetter.letter"), str_format (localize ("bookword", $count), $count), $this->idGet);
  760. }
  761. }
  762. class PageRecentBooks extends Page
  763. {
  764. public function InitializeContent ()
  765. {
  766. $this->title = localize ("recent.title");
  767. $this->entryArray = Book::getAllRecentBooks ();
  768. $this->idPage = Book::ALL_RECENT_BOOKS_ID;
  769. }
  770. }
  771. class PageQueryResult extends Page
  772. {
  773. const SCOPE_TAG = "tag";
  774. const SCOPE_RATING = "rating";
  775. const SCOPE_SERIES = "series";
  776. const SCOPE_AUTHOR = "author";
  777. const SCOPE_BOOK = "book";
  778. const SCOPE_PUBLISHER = "publisher";
  779. private function useTypeahead () {
  780. return !is_null (getURLParam ("search"));
  781. }
  782. private function searchByScope ($scope, $limit = FALSE) {
  783. $n = $this->n;
  784. $numberPerPage = NULL;
  785. $queryNormedAndUp = $this->query;
  786. if (useNormAndUp ()) {
  787. $queryNormedAndUp = normAndUp ($this->query);
  788. }
  789. if ($limit) {
  790. $n = 1;
  791. $numberPerPage = 5;
  792. }
  793. switch ($scope) {
  794. case self::SCOPE_BOOK :
  795. $array = Book::getBooksByStartingLetter ('%' . $queryNormedAndUp, $n, NULL, $numberPerPage);
  796. break;
  797. case self::SCOPE_AUTHOR :
  798. $array = Author::getAuthorsForSearch ('%' . $queryNormedAndUp);
  799. break;
  800. case self::SCOPE_SERIES :
  801. $array = Serie::getAllSeriesByQuery ($queryNormedAndUp);
  802. break;
  803. case self::SCOPE_TAG :
  804. $array = Tag::getAllTagsByQuery ($queryNormedAndUp, $n, NULL, $numberPerPage);
  805. break;
  806. case self::SCOPE_PUBLISHER :
  807. $array = Publisher::getAllPublishersByQuery ($queryNormedAndUp);
  808. break;
  809. default:
  810. $array = Book::getBooksByQuery (
  811. array ("all" => "%" . $queryNormedAndUp . "%"), $n);
  812. }
  813. return $array;
  814. }
  815. public function doSearchByCategory () {
  816. $database = GetUrlParam (DB);
  817. $out = array ();
  818. $pagequery = Base::PAGE_OPENSEARCH_QUERY;
  819. $dbArray = array ("");
  820. $d = $database;
  821. $query = $this->query;
  822. // Special case when no databases were chosen, we search on all databases
  823. if (Base::noDatabaseSelected ()) {
  824. $dbArray = Base::getDbNameList ();
  825. $d = 0;
  826. }
  827. foreach ($dbArray as $key) {
  828. if (Base::noDatabaseSelected ()) {
  829. array_push ($this->entryArray, new Entry ($key, DB . ":query:{$d}",
  830. " ", "text",
  831. array ( new LinkNavigation ("?" . DB . "={$d}")), "tt-header"));
  832. Base::getDb ($d);
  833. }
  834. foreach (array (PageQueryResult::SCOPE_BOOK,
  835. PageQueryResult::SCOPE_AUTHOR,
  836. PageQueryResult::SCOPE_SERIES,
  837. PageQueryResult::SCOPE_TAG,
  838. PageQueryResult::SCOPE_PUBLISHER) as $key) {
  839. if (in_array($key, getCurrentOption ('ignored_categories'))) {
  840. continue;
  841. }
  842. $array = $this->searchByScope ($key, TRUE);
  843. $i = 0;
  844. if (count ($array) == 2 && is_array ($array [0])) {
  845. $total = $array [1];
  846. $array = $array [0];
  847. } else {
  848. $total = count($array);
  849. }
  850. if ($total > 0) {
  851. // Comment to help the perl i18n script
  852. // str_format (localize("bookword", count($array))
  853. // str_format (localize("authorword", count($array))
  854. // str_format (localize("seriesword", count($array))
  855. // str_format (localize("tagword", count($array))
  856. // str_format (localize("publisherword", count($array))
  857. array_push ($this->entryArray, new Entry (str_format (localize ("search.result.{$key}"), $this->query), DB . ":query:{$d}:{$key}",
  858. str_format (localize("{$key}word", $total), $total), "text",
  859. array ( new LinkNavigation ("?page={$pagequery}&query={$query}&db={$d}&scope={$key}")),
  860. Base::noDatabaseSelected () ? "" : "tt-header", $total));
  861. }
  862. if (!Base::noDatabaseSelected () && $this->useTypeahead ()) {
  863. foreach ($array as $entry) {
  864. array_push ($this->entryArray, $entry);
  865. $i++;
  866. if ($i > 4) { break; };
  867. }
  868. }
  869. }
  870. $d++;
  871. if (Base::noDatabaseSelected ()) {
  872. Base::clearDb ();
  873. }
  874. }
  875. return $out;
  876. }
  877. public function InitializeContent ()
  878. {
  879. $scope = getURLParam ("scope");
  880. if (empty ($scope)) {
  881. $this->title = str_format (localize ("search.result"), $this->query);
  882. } else {
  883. // Comment to help the perl i18n script
  884. // str_format (localize ("search.result.author"), $this->query)
  885. // str_format (localize ("search.result.tag"), $this->query)
  886. // str_format (localize ("search.result.series"), $this->query)
  887. // str_format (localize ("search.result.book"), $this->query)
  888. // str_format (localize ("search.result.publisher"), $this->query)
  889. $this->title = str_format (localize ("search.result.{$scope}"), $this->query);
  890. }
  891. $crit = "%" . $this->query . "%";
  892. // Special case when we are doing a search and no database is selected
  893. if (Base::noDatabaseSelected () && !$this->useTypeahead ()) {
  894. $i = 0;
  895. foreach (Base::getDbNameList () as $key) {
  896. Base::clearDb ();
  897. list ($array, $totalNumber) = Book::getBooksByQuery (array ("all" => $crit), 1, $i, 1);
  898. array_push ($this->entryArray, new Entry ($key, DB . ":query:{$i}",
  899. str_format (localize ("bookword", $totalNumber), $totalNumber), "text",
  900. array ( new LinkNavigation ("?" . DB . "={$i}&page=9&query=" . $this->query)), "", $totalNumber));
  901. $i++;
  902. }
  903. return;
  904. }
  905. if (empty ($scope)) {
  906. $this->doSearchByCategory ();
  907. return;
  908. }
  909. $array = $this->searchByScope ($scope);
  910. if (count ($array) == 2 && is_array ($array [0])) {
  911. list ($this->entryArray, $this->totalNumber) = $array;
  912. } else {
  913. $this->entryArray = $array;
  914. }
  915. }
  916. }
  917. class PageBookDetail extends Page
  918. {
  919. public function InitializeContent ()
  920. {
  921. $this->book = Book::getBookById ($this->idGet);
  922. $this->title = $this->book->title;
  923. }
  924. }
  925. class PageAbout extends Page
  926. {
  927. public function InitializeContent ()
  928. {
  929. $this->title = localize ("about.title");
  930. }
  931. }
  932. class PageCustomize extends Page
  933. {
  934. private function isChecked ($key, $testedValue = 1) {
  935. $value = getCurrentOption ($key);
  936. if (is_array ($value)) {
  937. if (in_array ($testedValue, $value)) {
  938. return "checked='checked'";
  939. }
  940. } else {
  941. if ($value == $testedValue) {
  942. return "checked='checked'";
  943. }
  944. }
  945. return "";
  946. }
  947. private function isSelected ($key, $value) {
  948. if (getCurrentOption ($key) == $value) {
  949. return "selected='selected'";
  950. }
  951. return "";
  952. }
  953. private function getStyleList () {
  954. $result = array ();
  955. foreach (glob ("templates/" . getCurrentTemplate () . "/styles/style-*.css") as $filename) {
  956. if (preg_match ('/styles\/style-(.*?)\.css/', $filename, $m)) {
  957. array_push ($result, $m [1]);
  958. }
  959. }
  960. return $result;
  961. }
  962. public function InitializeContent ()
  963. {
  964. $this->title = localize ("customize.title");
  965. $this->entryArray = array ();
  966. $ignoredBaseArray = array (PageQueryResult::SCOPE_AUTHOR,
  967. PageQueryResult::SCOPE_TAG,
  968. PageQueryResult::SCOPE_SERIES,
  969. PageQueryResult::SCOPE_PUBLISHER,
  970. PageQueryResult::SCOPE_RATING,
  971. "language");
  972. $content = "";
  973. array_push ($this->entryArray, new Entry ("Template", "",
  974. "<span style='cursor: pointer;' onclick='$.cookie(\"template\", \"bootstrap\", { expires: 365 });window.location=$(\".headleft\").attr(\"href\");'>Click to switch to Bootstrap</span>", "text",
  975. array ()));
  976. if (!preg_match("/(Kobo|Kindle\/3.0|EBRD1101)/", $_SERVER['HTTP_USER_AGENT'])) {
  977. $content .= '<select id="style" onchange="updateCookie (this);">';
  978. foreach ($this-> getStyleList () as $filename) {
  979. $content .= "<option value='{$filename}' " . $this->isSelected ("style", $filename) . ">{$filename}</option>";
  980. }
  981. $content .= '</select>';
  982. } else {
  983. foreach ($this-> getStyleList () as $filename) {
  984. $content .= "<input type='radio' onchange='updateCookieFromCheckbox (this);' id='style-{$filename}' name='style' value='{$filename}' " . $this->isChecked ("style", $filename) . " /><label for='style-{$filename}'> {$filename} </label>";
  985. }
  986. }
  987. array_push ($this->entryArray, new Entry (localize ("customize.style"), "",
  988. $content, "text",
  989. array ()));
  990. if (!useServerSideRendering ()) {
  991. $content = '<input type="checkbox" onchange="updateCookieFromCheckbox (this);" id="use_fancyapps" ' . $this->isChecked ("use_fancyapps") . ' />';
  992. array_push ($this->entryArray, new Entry (localize ("customize.fancybox"), "",
  993. $content, "text",
  994. array ()));
  995. }
  996. $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]+$" />';
  997. array_push ($this->entryArray, new Entry (localize ("customize.paging"), "",
  998. $content, "text",
  999. array ()));
  1000. $content = '<input type="text" onchange="updateCookie (this);" id="email" value="' . getCurrentOption ("email") . '" />';
  1001. array_push ($this->entryArray, new Entry (localize ("customize.email"), "",
  1002. $content, "text",
  1003. array ()));
  1004. $content = '<input type="checkbox" onchange="updateCookieFromCheckbox (this);" id="html_tag_filter" ' . $this->isChecked ("html_tag_filter") . ' />';
  1005. array_push ($this->entryArray, new Entry (localize ("customize.filter"), "",
  1006. $content, "text",
  1007. array ()));
  1008. $content = "";
  1009. foreach ($ignoredBaseArray as $key) {
  1010. $keyPlural = preg_replace ('/(ss)$/', 's', $key . "s");
  1011. $content .= '<input type="checkbox" name="ignored_categories[]" onchange="updateCookieFromCheckboxGroup (this);" id="ignored_categories_' . $key . '" ' . $this->isChecked ("ignored_categories", $key) . ' > ' . localize ("{$keyPlural}.title") . '</input> ';
  1012. }
  1013. array_push ($this->entryArray, new Entry (localize ("customize.ignored"), "",
  1014. $content, "text",
  1015. array ()));
  1016. }
  1017. }
  1018. abstract class Base
  1019. {
  1020. const PAGE_INDEX = "index";
  1021. const PAGE_ALL_AUTHORS = "1";
  1022. const PAGE_AUTHORS_FIRST_LETTER = "2";
  1023. const PAGE_AUTHOR_DETAIL = "3";
  1024. const PAGE_ALL_BOOKS = "4";
  1025. const PAGE_ALL_BOOKS_LETTER = "5";
  1026. const PAGE_ALL_SERIES = "6";
  1027. const PAGE_SERIE_DETAIL = "7";
  1028. const PAGE_OPENSEARCH = "8";
  1029. const PAGE_OPENSEARCH_QUERY = "9";
  1030. const PAGE_ALL_RECENT_BOOKS = "10";
  1031. const PAGE_ALL_TAGS = "11";
  1032. const PAGE_TAG_DETAIL = "12";
  1033. const PAGE_BOOK_DETAIL = "13";
  1034. const PAGE_ALL_CUSTOMS = "14";
  1035. const PAGE_CUSTOM_DETAIL = "15";
  1036. const PAGE_ABOUT = "16";
  1037. const PAGE_ALL_LANGUAGES = "17";
  1038. const PAGE_LANGUAGE_DETAIL = "18";
  1039. const PAGE_CUSTOMIZE = "19";
  1040. const PAGE_ALL_PUBLISHERS = "20";
  1041. const PAGE_PUBLISHER_DETAIL = "21";
  1042. const PAGE_ALL_RATINGS = "22";
  1043. const PAGE_RATING_DETAIL = "23";
  1044. const COMPATIBILITY_XML_ALDIKO = "aldiko";
  1045. private static $db = NULL;
  1046. public static function isMultipleDatabaseEnabled () {
  1047. global $config;
  1048. return is_array ($config['calibre_directory']);
  1049. }
  1050. public static function useAbsolutePath () {
  1051. global $config;
  1052. $path = self::getDbDirectory();
  1053. return preg_match ('/^\//', $path) || // Linux /
  1054. preg_match ('/^\w\:/', $path); // Windows X:
  1055. }
  1056. public static function noDatabaseSelected () {
  1057. return self::isMultipleDatabaseEnabled () && is_null (GetUrlParam (DB));
  1058. }
  1059. public static function getDbList () {
  1060. global $config;
  1061. if (self::isMultipleDatabaseEnabled ()) {
  1062. return $config['calibre_directory'];
  1063. } else {
  1064. return array ("" => $config['calibre_directory']);
  1065. }
  1066. }
  1067. public static function getDbNameList () {
  1068. global $config;
  1069. if (self::isMultipleDatabaseEnabled ()) {
  1070. return array_keys ($config['calibre_directory']);
  1071. } else {
  1072. return array ("");
  1073. }
  1074. }
  1075. public static function getDbName ($database = NULL) {
  1076. global $config;
  1077. if (self::isMultipleDatabaseEnabled ()) {
  1078. if (is_null ($database)) $database = GetUrlParam (DB, 0);
  1079. if (!is_null($database) && !preg_match('/^\d+$/', $database)) {
  1080. return self::error ($database);
  1081. }
  1082. $array = array_keys ($config['calibre_directory']);
  1083. return $array[$database];
  1084. }
  1085. return "";
  1086. }
  1087. public static function getDbDirectory ($database = NULL) {
  1088. global $config;
  1089. if (self::isMultipleDatabaseEnabled ()) {
  1090. if (is_null ($database)) $database = GetUrlParam (DB, 0);
  1091. if (!is_null($database) && !preg_match('/^\d+$/', $database)) {
  1092. return self::error ($database);
  1093. }
  1094. $array = array_values ($config['calibre_directory']);
  1095. return $array[$database];
  1096. }
  1097. return $config['calibre_directory'];
  1098. }
  1099. public static function getDbFileName ($database = NULL) {
  1100. return self::getDbDirectory ($database) .'metadata.db';
  1101. }
  1102. private static function error ($database) {
  1103. if (php_sapi_name() != "cli") {
  1104. header("location: checkconfig.php?err=1");
  1105. }
  1106. throw new Exception("Database <{$database}> not found.");
  1107. }
  1108. public static function getDb ($database = NULL) {
  1109. if (is_null (self::$db)) {
  1110. try {
  1111. if (is_readable (self::getDbFileName ($database))) {
  1112. self::$db = new PDO('sqlite:'. self::getDbFileName ($database));
  1113. if (useNormAndUp ()) {
  1114. self::$db->sqliteCreateFunction ('normAndUp', 'normAndUp', 1);
  1115. }
  1116. } else {
  1117. self::error ($database);
  1118. }
  1119. } catch (Exception $e) {
  1120. self::error ($database);
  1121. }
  1122. }
  1123. return self::$db;
  1124. }
  1125. public static function checkDatabaseAvailability () {
  1126. if (self::noDatabaseSelected ()) {
  1127. for ($i = 0; $i < count (self::getDbList ()); $i++) {
  1128. self::getDb ($i);
  1129. self::clearDb ();
  1130. }
  1131. } else {
  1132. self::getDb ();
  1133. }
  1134. return true;
  1135. }
  1136. public static function clearDb () {
  1137. self::$db = NULL;
  1138. }
  1139. public static function executeQuerySingle ($query, $database = NULL) {
  1140. return self::getDb ($database)->query($query)->fetchColumn();
  1141. }
  1142. public static function getCountGeneric($table, $id, $pageId, $numberOfString = NULL) {
  1143. if (!$numberOfString) {
  1144. $numberOfString = $table . ".alphabetical";
  1145. }
  1146. $count = self::executeQuerySingle ('select count(*) from ' . $table);
  1147. if ($count == 0) return NULL;
  1148. $entry = new Entry (localize($table . ".title"), $id,
  1149. str_format (localize($numberOfString, $count), $count), "text",
  1150. array ( new LinkNavigation ("?page=".$pageId)), "", $count);
  1151. return $entry;
  1152. }
  1153. public static function getEntryArrayWithBookNumber ($query, $columns, $params, $category) {
  1154. list (, $result) = self::executeQuery ($query, $columns, "", $params, -1);
  1155. $entryArray = array();
  1156. while ($post = $result->fetchObject ())
  1157. {
  1158. $instance = new $category ($post);
  1159. if (property_exists($post, "sort")) {
  1160. $title = $post->sort;
  1161. } else {
  1162. $title = $post->name;
  1163. }
  1164. array_push ($entryArray, new Entry ($title, $instance->getEntryId (),
  1165. str_format (localize("bookword", $post->count), $post->count), "text",
  1166. array ( new LinkNavigation ($instance->getUri ())), "", $post->count));
  1167. }
  1168. return $entryArray;
  1169. }
  1170. public static function executeQuery($query, $columns, $filter, $params, $n, $database = NULL, $numberPerPage = NULL) {
  1171. $totalResult = -1;
  1172. if (useNormAndUp ()) {
  1173. $query = preg_replace("/upper/", "normAndUp", $query);
  1174. $columns = preg_replace("/upper/", "normAndUp", $columns);
  1175. }
  1176. if (is_null ($numberPerPage)) {
  1177. $numberPerPage = getCurrentOption ("max_item_per_page");
  1178. }
  1179. if ($numberPerPage != -1 && $n != -1)
  1180. {
  1181. // First check total number of results
  1182. $result = self::getDb ($database)->prepare (str_format ($query, "count(*)", $filter));
  1183. $result->execute ($params);
  1184. $totalResult = $result->fetchColumn ();
  1185. // Next modify the query and params
  1186. $query .= " limit ?, ?";
  1187. array_push ($params, ($n - 1) * $numberPerPage, $numberPerPage);
  1188. }
  1189. $result = self::getDb ($database)->prepare(str_format ($query, $columns, $filter));
  1190. $result->execute ($params);
  1191. return array ($totalResult, $result);
  1192. }
  1193. }