PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/base.php

https://github.com/giovanisp/cops
PHP | 1392 lines | 1172 code | 152 blank | 68 comment | 165 complexity | 96f0d3a515f271b44aeea2f564d9930f MD5 | raw file
Possible License(s): GPL-2.0, JSON, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file