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.

586 lines
22KB

  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. require_once('base.php');
  9. require_once('serie.php');
  10. require_once('author.php');
  11. require_once('publisher.php');
  12. require_once('tag.php');
  13. require_once('language.php');
  14. require_once("customcolumn.php");
  15. require_once('data.php');
  16. require_once('resources/php-epub-meta/epub.php');
  17. // Silly thing because PHP forbid string concatenation in class const
  18. define ('SQL_BOOKS_LEFT_JOIN', "left outer join comments on comments.book = books.id
  19. left outer join books_ratings_link on books_ratings_link.book = books.id
  20. left outer join ratings on books_ratings_link.rating = ratings.id ");
  21. define ('SQL_BOOKS_ALL', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . " order by books.sort ");
  22. define ('SQL_BOOKS_BY_PUBLISHER', "select {0} from books_publishers_link, books " . SQL_BOOKS_LEFT_JOIN . "
  23. where books_publishers_link.book = books.id and publisher = ? {1} order by publisher");
  24. define ('SQL_BOOKS_BY_FIRST_LETTER', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
  25. where upper (books.sort) like ? order by books.sort");
  26. define ('SQL_BOOKS_BY_AUTHOR', "select {0} from books_authors_link, books " . SQL_BOOKS_LEFT_JOIN . "
  27. where books_authors_link.book = books.id and author = ? {1} order by pubdate");
  28. define ('SQL_BOOKS_BY_SERIE', "select {0} from books_series_link, books " . SQL_BOOKS_LEFT_JOIN . "
  29. where books_series_link.book = books.id and series = ? {1} order by series_index");
  30. define ('SQL_BOOKS_BY_TAG', "select {0} from books_tags_link, books " . SQL_BOOKS_LEFT_JOIN . "
  31. where books_tags_link.book = books.id and tag = ? {1} order by sort");
  32. define ('SQL_BOOKS_BY_LANGUAGE', "select {0} from books_languages_link, books " . SQL_BOOKS_LEFT_JOIN . "
  33. where books_languages_link.book = books.id and lang_code = ? {1} order by sort");
  34. define ('SQL_BOOKS_BY_CUSTOM', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
  35. where {2}.book = books.id and {2}.{3} = ? {1} order by sort");
  36. define ('SQL_BOOKS_QUERY', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
  37. where (
  38. exists (select null from authors, books_authors_link where book = books.id and author = authors.id and authors.name like ?) or
  39. exists (select null from tags, books_tags_link where book = books.id and tag = tags.id and tags.name like ?) or
  40. exists (select null from series, books_series_link on book = books.id and books_series_link.series = series.id and series.name like ?) or
  41. exists (select null from publishers, books_publishers_link where book = books.id and books_publishers_link.publisher = publishers.id and publishers.name like ?) or
  42. title like ?) {1} order by books.sort");
  43. define ('SQL_BOOKS_RECENT', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
  44. where 1=1 {1} order by timestamp desc limit ");
  45. class Book extends Base {
  46. const ALL_BOOKS_UUID = "urn:uuid";
  47. const ALL_BOOKS_ID = "cops:books";
  48. const ALL_RECENT_BOOKS_ID = "cops:recentbooks";
  49. const BOOK_COLUMNS = "books.id as id, books.title as title, text as comment, path, timestamp, pubdate, series_index, uuid, has_cover, ratings.rating";
  50. const SQL_BOOKS_LEFT_JOIN = SQL_BOOKS_LEFT_JOIN;
  51. const SQL_BOOKS_ALL = SQL_BOOKS_ALL;
  52. const SQL_BOOKS_BY_PUBLISHER = SQL_BOOKS_BY_PUBLISHER;
  53. const SQL_BOOKS_BY_FIRST_LETTER = SQL_BOOKS_BY_FIRST_LETTER;
  54. const SQL_BOOKS_BY_AUTHOR = SQL_BOOKS_BY_AUTHOR;
  55. const SQL_BOOKS_BY_SERIE = SQL_BOOKS_BY_SERIE;
  56. const SQL_BOOKS_BY_TAG = SQL_BOOKS_BY_TAG;
  57. const SQL_BOOKS_BY_LANGUAGE = SQL_BOOKS_BY_LANGUAGE;
  58. const SQL_BOOKS_BY_CUSTOM = SQL_BOOKS_BY_CUSTOM;
  59. const SQL_BOOKS_QUERY = SQL_BOOKS_QUERY;
  60. const SQL_BOOKS_RECENT = SQL_BOOKS_RECENT;
  61. const BAD_SEARCH = "QQQQQ";
  62. public $id;
  63. public $title;
  64. public $timestamp;
  65. public $pubdate;
  66. public $path;
  67. public $uuid;
  68. public $hasCover;
  69. public $relativePath;
  70. public $seriesIndex;
  71. public $comment;
  72. public $rating;
  73. public $datas = NULL;
  74. public $authors = NULL;
  75. public $publisher = NULL;
  76. public $serie = NULL;
  77. public $tags = NULL;
  78. public $languages = NULL;
  79. public $format = array ();
  80. public function __construct($line) {
  81. $this->id = $line->id;
  82. $this->title = $line->title;
  83. $this->timestamp = strtotime ($line->timestamp);
  84. $this->pubdate = strtotime ($line->pubdate);
  85. $this->path = Base::getDbDirectory () . $line->path;
  86. $this->relativePath = $line->path;
  87. $this->seriesIndex = $line->series_index;
  88. $this->comment = $line->comment;
  89. $this->uuid = $line->uuid;
  90. $this->hasCover = $line->has_cover;
  91. if (!file_exists ($this->getFilePath ("jpg"))) {
  92. // double check
  93. $this->hasCover = 0;
  94. }
  95. $this->rating = $line->rating;
  96. }
  97. public function getEntryId () {
  98. return self::ALL_BOOKS_UUID.":".$this->uuid;
  99. }
  100. public static function getEntryIdByLetter ($startingLetter) {
  101. return self::ALL_BOOKS_ID.":letter:".$startingLetter;
  102. }
  103. public function getUri () {
  104. return "?page=".parent::PAGE_BOOK_DETAIL."&id=$this->id";
  105. }
  106. public function getDetailUrl ($permalink = false) {
  107. $urlParam = $this->getUri ();
  108. if (!is_null (GetUrlParam (DB))) $urlParam = addURLParameter ($urlParam, DB, GetUrlParam (DB));
  109. return 'index.php' . $urlParam;
  110. }
  111. public function getTitle () {
  112. return $this->title;
  113. }
  114. /* Other class (author, series, tag, ...) initialization and accessors */
  115. public function getAuthors () {
  116. if (is_null ($this->authors)) {
  117. $this->authors = Author::getAuthorByBookId ($this->id);
  118. }
  119. return $this->authors;
  120. }
  121. public function getAuthorsName () {
  122. return implode (", ", array_map (function ($author) { return $author->name; }, $this->getAuthors ()));
  123. }
  124. public function getPublisher () {
  125. if (is_null ($this->publisher)) {
  126. $this->publisher = Publisher::getPublisherByBookId ($this->id);
  127. }
  128. return $this->publisher;
  129. }
  130. public function getSerie () {
  131. if (is_null ($this->serie)) {
  132. $this->serie = Serie::getSerieByBookId ($this->id);
  133. }
  134. return $this->serie;
  135. }
  136. public function getLanguages () {
  137. $lang = array ();
  138. $result = parent::getDb ()->prepare('select languages.lang_code
  139. from books_languages_link, languages
  140. where books_languages_link.lang_code = languages.id
  141. and book = ?
  142. order by item_order');
  143. $result->execute (array ($this->id));
  144. while ($post = $result->fetchObject ())
  145. {
  146. array_push ($lang, Language::getLanguageString($post->lang_code));
  147. }
  148. return implode (", ", $lang);
  149. }
  150. public function getTags () {
  151. if (is_null ($this->tags)) {
  152. $this->tags = array ();
  153. $result = parent::getDb ()->prepare('select tags.id as id, name
  154. from books_tags_link, tags
  155. where tag = tags.id
  156. and book = ?
  157. order by name');
  158. $result->execute (array ($this->id));
  159. while ($post = $result->fetchObject ())
  160. {
  161. array_push ($this->tags, new Tag ($post->id, $post->name));
  162. }
  163. }
  164. return $this->tags;
  165. }
  166. public function getTagsName () {
  167. return implode (", ", array_map (function ($tag) { return $tag->name; }, $this->getTags ()));
  168. }
  169. public function getDatas ()
  170. {
  171. if (is_null ($this->datas)) {
  172. $this->datas = array ();
  173. $result = parent::getDb ()->prepare('select id, format, name
  174. from data where book = ?');
  175. $result->execute (array ($this->id));
  176. while ($post = $result->fetchObject ())
  177. {
  178. array_push ($this->datas, new Data ($post, $this));
  179. }
  180. }
  181. return $this->datas;
  182. }
  183. /* End of other class (author, series, tag, ...) initialization and accessors */
  184. public static function getFilterString () {
  185. $filter = getURLParam ("tag", NULL);
  186. if (empty ($filter)) return "";
  187. $exists = true;
  188. if (preg_match ("/^!(.*)$/", $filter, $matches)) {
  189. $exists = false;
  190. $filter = $matches[1];
  191. }
  192. $result = "exists (select null from books_tags_link, tags where books_tags_link.book = books.id and books_tags_link.tag = tags.id and tags.name = '" . $filter . "')";
  193. if (!$exists) {
  194. $result = "not " . $result;
  195. }
  196. return "and " . $result;
  197. }
  198. public function GetMostInterestingDataToSendToKindle ()
  199. {
  200. $bestFormatForKindle = array ("EPUB", "PDF", "MOBI");
  201. $bestRank = -1;
  202. $bestData = NULL;
  203. foreach ($this->getDatas () as $data) {
  204. $key = array_search ($data->format, $bestFormatForKindle);
  205. if ($key !== false && $key > $bestRank) {
  206. $bestRank = $key;
  207. $bestData = $data;
  208. }
  209. }
  210. return $bestData;
  211. }
  212. public function getDataById ($idData)
  213. {
  214. foreach ($this->getDatas () as $data) {
  215. if ($data->id == $idData) {
  216. return $data;
  217. }
  218. }
  219. return NULL;
  220. }
  221. public function getRating () {
  222. if (is_null ($this->rating) || $this->rating == 0) {
  223. return "";
  224. }
  225. $retour = "";
  226. for ($i = 0; $i < $this->rating / 2; $i++) {
  227. $retour .= "&#9733;";
  228. }
  229. for ($i = 0; $i < 5 - $this->rating / 2; $i++) {
  230. $retour .= "&#9734;";
  231. }
  232. return $retour;
  233. }
  234. public function getPubDate () {
  235. if (is_null ($this->pubdate) || ($this->pubdate <= -58979923200)) {
  236. return "";
  237. }
  238. else {
  239. return date ("Y", $this->pubdate);
  240. }
  241. }
  242. public function getComment ($withSerie = true) {
  243. $addition = "";
  244. $se = $this->getSerie ();
  245. if (!is_null ($se) && $withSerie) {
  246. $addition = $addition . "<strong>" . localize("content.series") . "</strong>" . str_format (localize ("content.series.data"), $this->seriesIndex, htmlspecialchars ($se->name)) . "<br />\n";
  247. }
  248. if (preg_match ("/<\/(div|p|a|span)>/", $this->comment))
  249. {
  250. return $addition . html2xhtml ($this->comment);
  251. }
  252. else
  253. {
  254. return $addition . htmlspecialchars ($this->comment);
  255. }
  256. }
  257. public function getDataFormat ($format) {
  258. foreach ($this->getDatas () as $data)
  259. {
  260. if ($data->format == $format)
  261. {
  262. return $data;
  263. }
  264. }
  265. return NULL;
  266. }
  267. public function getFilePath ($extension, $idData = NULL, $relative = false)
  268. {
  269. $file = NULL;
  270. if ($extension == "jpg")
  271. {
  272. $file = "cover.jpg";
  273. }
  274. else
  275. {
  276. $data = $this->getDataById ($idData);
  277. if (!$data) return NULL;
  278. $file = $data->name . "." . strtolower ($data->format);
  279. }
  280. if ($relative)
  281. {
  282. return $this->relativePath."/".$file;
  283. }
  284. else
  285. {
  286. return $this->path."/".$file;
  287. }
  288. }
  289. public function getUpdatedEpub ($idData)
  290. {
  291. global $config;
  292. $data = $this->getDataById ($idData);
  293. try
  294. {
  295. $epub = new EPub ($data->getLocalPath ());
  296. $epub->Title ($this->title);
  297. $authorArray = array ();
  298. foreach ($this->getAuthors() as $author) {
  299. $authorArray [$author->sort] = $author->name;
  300. }
  301. $epub->Authors ($authorArray);
  302. $epub->Language ($this->getLanguages ());
  303. $epub->Description ($this->getComment (false));
  304. $epub->Subjects ($this->getTagsName ());
  305. $epub->Cover2 ($this->getFilePath ("jpg"), "image/jpeg");
  306. $epub->Calibre ($this->uuid);
  307. $se = $this->getSerie ();
  308. if (!is_null ($se)) {
  309. $epub->Serie ($se->name);
  310. $epub->SerieIndex ($this->seriesIndex);
  311. }
  312. if ($config['cops_provide_kepub'] == "1" && preg_match("/Kobo/", $_SERVER['HTTP_USER_AGENT'])) {
  313. $epub->updateForKepub ();
  314. }
  315. $epub->download ($data->getUpdatedFilenameEpub ());
  316. }
  317. catch (Exception $e)
  318. {
  319. echo "Exception : " . $e->getMessage();
  320. }
  321. }
  322. public function getThumbnail ($width, $height, $outputfile = NULL) {
  323. if (is_null ($width) && is_null ($height)) {
  324. return false;
  325. }
  326. // In case something bad happen below set a default size
  327. $nw = "160";
  328. $nh = "120";
  329. $file = $this->getFilePath ("jpg");
  330. // get image size
  331. if ($size = GetImageSize($file)) {
  332. $w = $size[0];
  333. $h = $size[1];
  334. //set new size
  335. if (!is_null ($width)) {
  336. $nw = $width;
  337. if ($nw >= $w) { return false; }
  338. $nh = ($nw*$h)/$w;
  339. } else {
  340. $nh = $height;
  341. if ($nh >= $h) { return false; }
  342. $nw = ($nh*$w)/$h;
  343. }
  344. }
  345. //draw the image
  346. $src_img = imagecreatefromjpeg($file);
  347. $dst_img = imagecreatetruecolor($nw,$nh);
  348. imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);//resizing the image
  349. imagejpeg($dst_img,$outputfile,80);
  350. imagedestroy($src_img);
  351. imagedestroy($dst_img);
  352. return true;
  353. }
  354. public function getLinkArray ()
  355. {
  356. $linkArray = array();
  357. if ($this->hasCover)
  358. {
  359. array_push ($linkArray, Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", NULL));
  360. array_push ($linkArray, Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", NULL));
  361. }
  362. foreach ($this->getDatas () as $data)
  363. {
  364. if ($data->isKnownType ())
  365. {
  366. array_push ($linkArray, $data->getDataLink (Link::OPDS_ACQUISITION_TYPE, $data->format));
  367. }
  368. }
  369. foreach ($this->getAuthors () as $author) {
  370. array_push ($linkArray, new LinkNavigation ($author->getUri (), "related", str_format (localize ("bookentry.author"), localize ("splitByLetter.book.other"), $author->name)));
  371. }
  372. $serie = $this->getSerie ();
  373. if (!is_null ($serie)) {
  374. array_push ($linkArray, new LinkNavigation ($serie->getUri (), "related", str_format (localize ("content.series.data"), $this->seriesIndex, $serie->name)));
  375. }
  376. return $linkArray;
  377. }
  378. public function getEntry () {
  379. return new EntryBook ($this->getTitle (), $this->getEntryId (),
  380. $this->getComment (), "text/html",
  381. $this->getLinkArray (), $this);
  382. }
  383. public static function getBookCount($database = NULL) {
  384. $nBooks = parent::getDb ($database)->query('select count(*) from books')->fetchColumn();
  385. return $nBooks;
  386. }
  387. public static function getCount() {
  388. global $config;
  389. $nBooks = parent::getDb ()->query('select count(*) from books')->fetchColumn();
  390. $result = array();
  391. $entry = new Entry (localize ("allbooks.title"),
  392. self::ALL_BOOKS_ID,
  393. str_format (localize ("allbooks.alphabetical", $nBooks), $nBooks), "text",
  394. array ( new LinkNavigation ("?page=".parent::PAGE_ALL_BOOKS)));
  395. array_push ($result, $entry);
  396. if ($config['cops_recentbooks_limit'] > 0) {
  397. $entry = new Entry (localize ("recent.title"),
  398. self::ALL_RECENT_BOOKS_ID,
  399. str_format (localize ("recent.list"), $config['cops_recentbooks_limit']), "text",
  400. array ( new LinkNavigation ("?page=".parent::PAGE_ALL_RECENT_BOOKS)));
  401. array_push ($result, $entry);
  402. }
  403. return $result;
  404. }
  405. public static function getBooksByAuthor($authorId, $n) {
  406. return self::getEntryArray (self::SQL_BOOKS_BY_AUTHOR, array ($authorId), $n);
  407. }
  408. public static function getBooksByPublisher($publisherId, $n) {
  409. return self::getEntryArray (self::SQL_BOOKS_BY_PUBLISHER, array ($publisherId), $n);
  410. }
  411. public static function getBooksBySeries($serieId, $n) {
  412. return self::getEntryArray (self::SQL_BOOKS_BY_SERIE, array ($serieId), $n);
  413. }
  414. public static function getBooksByTag($tagId, $n) {
  415. return self::getEntryArray (self::SQL_BOOKS_BY_TAG, array ($tagId), $n);
  416. }
  417. public static function getBooksByLanguage($languageId, $n) {
  418. return self::getEntryArray (self::SQL_BOOKS_BY_LANGUAGE, array ($languageId), $n);
  419. }
  420. public static function getBooksByCustom($customId, $id, $n) {
  421. $query = str_format (self::SQL_BOOKS_BY_CUSTOM, "{0}", "{1}", CustomColumn::getTableLinkName ($customId), CustomColumn::getTableLinkColumn ($customId));
  422. return self::getEntryArray ($query, array ($id), $n);
  423. }
  424. public static function getBookById($bookId) {
  425. $result = parent::getDb ()->prepare('select ' . self::BOOK_COLUMNS . '
  426. from books ' . self::SQL_BOOKS_LEFT_JOIN . '
  427. where books.id = ?');
  428. $result->execute (array ($bookId));
  429. while ($post = $result->fetchObject ())
  430. {
  431. $book = new Book ($post);
  432. return $book;
  433. }
  434. return NULL;
  435. }
  436. public static function getBookByDataId($dataId) {
  437. $result = parent::getDb ()->prepare('select ' . self::BOOK_COLUMNS . ', data.name, data.format
  438. from data, books ' . self::SQL_BOOKS_LEFT_JOIN . '
  439. where data.book = books.id and data.id = ?');
  440. $result->execute (array ($dataId));
  441. while ($post = $result->fetchObject ())
  442. {
  443. $book = new Book ($post);
  444. $data = new Data ($post, $book);
  445. $data->id = $dataId;
  446. $book->datas = array ($data);
  447. return $book;
  448. }
  449. return NULL;
  450. }
  451. public static function getBooksByQuery($query, $n, $database = NULL, $numberPerPage = NULL) {
  452. $i = 0;
  453. $critArray = array ();
  454. foreach (array (PageQueryResult::SCOPE_AUTHOR,
  455. PageQueryResult::SCOPE_TAG,
  456. PageQueryResult::SCOPE_SERIES,
  457. PageQueryResult::SCOPE_PUBLISHER,
  458. PageQueryResult::SCOPE_BOOK) as $key) {
  459. if (in_array($key, getCurrentOption ('ignored_categories')) ||
  460. (!array_key_exists ($key, $query) && !array_key_exists ("all", $query))) {
  461. $critArray [$i] = self::BAD_SEARCH;
  462. }
  463. else {
  464. if (array_key_exists ($key, $query)) {
  465. $critArray [$i] = $query [$key];
  466. } else {
  467. $critArray [$i] = $query ["all"];
  468. }
  469. }
  470. $i++;
  471. }
  472. return self::getEntryArray (self::SQL_BOOKS_QUERY, $critArray, $n, $database, $numberPerPage);
  473. }
  474. public static function getBooks($n) {
  475. list ($entryArray, $totalNumber) = self::getEntryArray (self::SQL_BOOKS_ALL , array (), $n);
  476. return array ($entryArray, $totalNumber);
  477. }
  478. public static function getAllBooks() {
  479. $result = parent::getDb ()->query("select substr (upper (sort), 1, 1) as title, count(*) as count
  480. from books
  481. group by substr (upper (sort), 1, 1)
  482. order by substr (upper (sort), 1, 1)");
  483. $entryArray = array();
  484. while ($post = $result->fetchObject ())
  485. {
  486. array_push ($entryArray, new Entry ($post->title, Book::getEntryIdByLetter ($post->title),
  487. str_format (localize("bookword", $post->count), $post->count), "text",
  488. array ( new LinkNavigation ("?page=".parent::PAGE_ALL_BOOKS_LETTER."&id=". rawurlencode ($post->title)))));
  489. }
  490. return $entryArray;
  491. }
  492. public static function getBooksByStartingLetter($letter, $n, $database = NULL, $numberPerPage = NULL) {
  493. return self::getEntryArray (self::SQL_BOOKS_BY_FIRST_LETTER, array ($letter . "%"), $n, $database, $numberPerPage);
  494. }
  495. public static function getEntryArray ($query, $params, $n, $database = NULL, $numberPerPage = NULL) {
  496. list ($totalNumber, $result) = parent::executeQuery ($query, self::BOOK_COLUMNS, self::getFilterString (), $params, $n, $database, $numberPerPage);
  497. $entryArray = array();
  498. while ($post = $result->fetchObject ())
  499. {
  500. $book = new Book ($post);
  501. array_push ($entryArray, $book->getEntry ());
  502. }
  503. return array ($entryArray, $totalNumber);
  504. }
  505. public static function getAllRecentBooks() {
  506. global $config;
  507. $entryArray = self::getEntryArray (self::SQL_BOOKS_RECENT . $config['cops_recentbooks_limit'], array (), -1);
  508. $entryArray = $entryArray [0];
  509. return $entryArray;
  510. }
  511. }