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.

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