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.

565 lines
21KB

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