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.

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