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.

566 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. "seriesIndex" => $this->seriesIndex,
  127. "seriesCompleteName" => $scn,
  128. "seriesurl" => $su);
  129. }
  130. public function getFullContentArray () {
  131. global $config;
  132. $out = $this->getContentArray ();
  133. $out ["coverurl"] = Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", NULL)->hrefXhtml ();
  134. $out ["thumbnailurl"] = Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", NULL, NULL, $config['cops_html_thumbnail_height'] * 2)->hrefXhtml ();
  135. $out ["content"] = $this->getComment (false);
  136. $out ["datas"] = array ();
  137. $dataKindle = $this->GetMostInterestingDataToSendToKindle ();
  138. foreach ($this->getDatas() as $data) {
  139. $tab = array ("id" => $data->id, "format" => $data->format, "url" => $data->getHtmlLink (), "mail" => 0);
  140. if (!empty ($config['cops_mail_configuration']) && !is_null ($dataKindle) && $data->id == $dataKindle->id) {
  141. $tab ["mail"] = 1;
  142. }
  143. array_push ($out ["datas"], $tab);
  144. }
  145. $out ["authors"] = array ();
  146. foreach ($this->getAuthors () as $author) {
  147. $link = new LinkNavigation ($author->getUri ());
  148. array_push ($out ["authors"], array ("name" => $author->name, "url" => $link->hrefXhtml ()));
  149. }
  150. $out ["tags"] = array ();
  151. foreach ($this->getTags () as $tag) {
  152. $link = new LinkNavigation ($tag->getUri ());
  153. array_push ($out ["tags"], array ("name" => $tag->name, "url" => $link->hrefXhtml ()));
  154. }
  155. ;
  156. return $out;
  157. }
  158. public function getDetailUrl ($permalink = false) {
  159. global $config;
  160. $urlParam = $this->getUri ();
  161. if (!is_null (GetUrlParam (DB))) $urlParam = addURLParameter ($urlParam, DB, GetUrlParam (DB));
  162. return 'index.php' . $urlParam;
  163. }
  164. public function getTitle () {
  165. return $this->title;
  166. }
  167. public function getAuthors () {
  168. if (is_null ($this->authors)) {
  169. $this->authors = Author::getAuthorByBookId ($this->id);
  170. }
  171. return $this->authors;
  172. }
  173. public static function getFilterString () {
  174. $filter = getURLParam ("tag", NULL);
  175. if (empty ($filter)) return "";
  176. $exists = true;
  177. if (preg_match ("/^!(.*)$/", $filter, $matches)) {
  178. $exists = false;
  179. $filter = $matches[1];
  180. }
  181. $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 . "')";
  182. if (!$exists) {
  183. $result = "not " . $result;
  184. }
  185. return "and " . $result;
  186. }
  187. public function getAuthorsName () {
  188. return implode (", ", array_map (function ($author) { return $author->name; }, $this->getAuthors ()));
  189. }
  190. public function getSerie () {
  191. if (is_null ($this->serie)) {
  192. $this->serie = Serie::getSerieByBookId ($this->id);
  193. }
  194. return $this->serie;
  195. }
  196. public function getLanguages () {
  197. $lang = array ();
  198. $result = parent::getDb ()->prepare('select languages.lang_code
  199. from books_languages_link, languages
  200. where books_languages_link.lang_code = languages.id
  201. and book = ?
  202. order by item_order');
  203. $result->execute (array ($this->id));
  204. while ($post = $result->fetchObject ())
  205. {
  206. array_push ($lang, Language::getLanguageString($post->lang_code));
  207. }
  208. return implode (", ", $lang);
  209. }
  210. public function getTags () {
  211. if (is_null ($this->tags)) {
  212. $this->tags = array ();
  213. $result = parent::getDb ()->prepare('select tags.id as id, name
  214. from books_tags_link, tags
  215. where tag = tags.id
  216. and book = ?
  217. order by name');
  218. $result->execute (array ($this->id));
  219. while ($post = $result->fetchObject ())
  220. {
  221. array_push ($this->tags, new Tag ($post->id, $post->name));
  222. }
  223. }
  224. return $this->tags;
  225. }
  226. public function getDatas ()
  227. {
  228. if (is_null ($this->datas)) {
  229. $this->datas = array ();
  230. $result = parent::getDb ()->prepare('select id, format, name
  231. from data where book = ?');
  232. $result->execute (array ($this->id));
  233. while ($post = $result->fetchObject ())
  234. {
  235. array_push ($this->datas, new Data ($post, $this));
  236. }
  237. }
  238. return $this->datas;
  239. }
  240. public function GetMostInterestingDataToSendToKindle ()
  241. {
  242. $bestFormatForKindle = array ("EPUB", "PDF", "MOBI");
  243. $bestRank = -1;
  244. $bestData = NULL;
  245. foreach ($this->getDatas () as $data) {
  246. $key = array_search ($data->format, $bestFormatForKindle);
  247. if ($key !== false && $key > $bestRank) {
  248. $bestRank = $key;
  249. $bestData = $data;
  250. }
  251. }
  252. return $bestData;
  253. }
  254. public function getDataById ($idData)
  255. {
  256. foreach ($this->getDatas () as $data) {
  257. if ($data->id == $idData) {
  258. return $data;
  259. }
  260. }
  261. return NULL;
  262. }
  263. public function getTagsName () {
  264. return implode (", ", array_map (function ($tag) { return $tag->name; }, $this->getTags ()));
  265. }
  266. public function getRating () {
  267. if (is_null ($this->rating) || $this->rating == 0) {
  268. return "";
  269. }
  270. $retour = "";
  271. for ($i = 0; $i < $this->rating / 2; $i++) {
  272. $retour .= "&#9733;";
  273. }
  274. for ($i = 0; $i < 5 - $this->rating / 2; $i++) {
  275. $retour .= "&#9734;";
  276. }
  277. return $retour;
  278. }
  279. public function getPubDate () {
  280. if (is_null ($this->pubdate) || ($this->pubdate <= -58979923200)) {
  281. return "";
  282. }
  283. else {
  284. return date ("Y", $this->pubdate);
  285. }
  286. }
  287. public function getComment ($withSerie = true) {
  288. $addition = "";
  289. $se = $this->getSerie ();
  290. if (!is_null ($se) && $withSerie) {
  291. $addition = $addition . "<strong>" . localize("content.series") . "</strong>" . str_format (localize ("content.series.data"), $this->seriesIndex, htmlspecialchars ($se->name)) . "<br />\n";
  292. }
  293. if (preg_match ("/<\/(div|p|a|span)>/", $this->comment))
  294. {
  295. return $addition . html2xhtml ($this->comment);
  296. }
  297. else
  298. {
  299. return $addition . htmlspecialchars ($this->comment);
  300. }
  301. }
  302. public function getDataFormat ($format) {
  303. foreach ($this->getDatas () as $data)
  304. {
  305. if ($data->format == $format)
  306. {
  307. return $data;
  308. }
  309. }
  310. return NULL;
  311. }
  312. public function getFilePath ($extension, $idData = NULL, $relative = false)
  313. {
  314. $file = NULL;
  315. if ($extension == "jpg")
  316. {
  317. $file = "cover.jpg";
  318. }
  319. else
  320. {
  321. $data = $this->getDataById ($idData);
  322. if (!$data) return NULL;
  323. $file = $data->name . "." . strtolower ($data->format);
  324. }
  325. if ($relative)
  326. {
  327. return $this->relativePath."/".$file;
  328. }
  329. else
  330. {
  331. return $this->path."/".$file;
  332. }
  333. }
  334. public function getUpdatedEpub ($idData)
  335. {
  336. global $config;
  337. $data = $this->getDataById ($idData);
  338. try
  339. {
  340. $epub = new EPub ($data->getLocalPath ());
  341. $epub->Title ($this->title);
  342. $authorArray = array ();
  343. foreach ($this->getAuthors() as $author) {
  344. $authorArray [$author->sort] = $author->name;
  345. }
  346. $epub->Authors ($authorArray);
  347. $epub->Language ($this->getLanguages ());
  348. $epub->Description ($this->getComment (false));
  349. $epub->Subjects ($this->getTagsName ());
  350. $epub->Cover2 ($this->getFilePath ("jpg"), "image/jpeg");
  351. $epub->Calibre ($this->uuid);
  352. $se = $this->getSerie ();
  353. if (!is_null ($se)) {
  354. $epub->Serie ($se->name);
  355. $epub->SerieIndex ($this->seriesIndex);
  356. }
  357. if ($config['cops_provide_kepub'] == "1" && preg_match("/Kobo/", $_SERVER['HTTP_USER_AGENT'])) {
  358. $epub->updateForKepub ();
  359. }
  360. $epub->download ($data->getUpdatedFilenameEpub ());
  361. }
  362. catch (Exception $e)
  363. {
  364. echo "Exception : " . $e->getMessage();
  365. }
  366. }
  367. public function getLinkArray ()
  368. {
  369. global $config;
  370. $linkArray = array();
  371. if ($this->hasCover)
  372. {
  373. array_push ($linkArray, Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", NULL));
  374. array_push ($linkArray, Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", NULL));
  375. }
  376. foreach ($this->getDatas () as $data)
  377. {
  378. if ($data->isKnownType ())
  379. {
  380. array_push ($linkArray, $data->getDataLink (Link::OPDS_ACQUISITION_TYPE, "Download"));
  381. }
  382. }
  383. foreach ($this->getAuthors () as $author) {
  384. array_push ($linkArray, new LinkNavigation ($author->getUri (), "related", str_format (localize ("bookentry.author"), localize ("splitByLetter.book.other"), $author->name)));
  385. }
  386. $serie = $this->getSerie ();
  387. if (!is_null ($serie)) {
  388. array_push ($linkArray, new LinkNavigation ($serie->getUri (), "related", str_format (localize ("content.series.data"), $this->seriesIndex, $serie->name)));
  389. }
  390. return $linkArray;
  391. }
  392. public function getEntry () {
  393. return new EntryBook ($this->getTitle (), $this->getEntryId (),
  394. $this->getComment (), "text/html",
  395. $this->getLinkArray (), $this);
  396. }
  397. public static function getBookCount($database = NULL) {
  398. global $config;
  399. $nBooks = parent::getDb ($database)->query('select count(*) from books')->fetchColumn();
  400. return $nBooks;
  401. }
  402. public static function getCount() {
  403. global $config;
  404. $nBooks = parent::getDb ()->query('select count(*) from books')->fetchColumn();
  405. $result = array();
  406. $entry = new Entry (localize ("allbooks.title"),
  407. self::ALL_BOOKS_ID,
  408. str_format (localize ("allbooks.alphabetical", $nBooks), $nBooks), "text",
  409. array ( new LinkNavigation ("?page=".parent::PAGE_ALL_BOOKS)));
  410. array_push ($result, $entry);
  411. $entry = new Entry (localize ("recent.title"),
  412. self::ALL_RECENT_BOOKS_ID,
  413. str_format (localize ("recent.list"), $config['cops_recentbooks_limit']), "text",
  414. array ( new LinkNavigation ("?page=".parent::PAGE_ALL_RECENT_BOOKS)));
  415. array_push ($result, $entry);
  416. return $result;
  417. }
  418. public static function getBooksByAuthor($authorId, $n) {
  419. return self::getEntryArray (self::SQL_BOOKS_BY_AUTHOR, array ($authorId), $n);
  420. }
  421. public static function getBooksBySeries($serieId, $n) {
  422. return self::getEntryArray (self::SQL_BOOKS_BY_SERIE, array ($serieId), $n);
  423. }
  424. public static function getBooksByTag($tagId, $n) {
  425. return self::getEntryArray (self::SQL_BOOKS_BY_TAG, array ($tagId), $n);
  426. }
  427. public static function getBooksByLanguage($languageId, $n) {
  428. return self::getEntryArray (self::SQL_BOOKS_BY_LANGUAGE, array ($languageId), $n);
  429. }
  430. public static function getBooksByCustom($customId, $id, $n) {
  431. $query = str_format (self::SQL_BOOKS_BY_CUSTOM, "{0}", "{1}", CustomColumn::getTableLinkName ($customId), CustomColumn::getTableLinkColumn ($customId));
  432. return self::getEntryArray ($query, array ($id), $n);
  433. }
  434. public static function getBookById($bookId) {
  435. $result = parent::getDb ()->prepare('select ' . self::BOOK_COLUMNS . '
  436. from books ' . self::SQL_BOOKS_LEFT_JOIN . '
  437. where books.id = ?');
  438. $result->execute (array ($bookId));
  439. while ($post = $result->fetchObject ())
  440. {
  441. $book = new Book ($post);
  442. return $book;
  443. }
  444. return NULL;
  445. }
  446. public static function getBookByDataId($dataId) {
  447. $result = parent::getDb ()->prepare('select ' . self::BOOK_COLUMNS . ', data.name, data.format
  448. from data, books ' . self::SQL_BOOKS_LEFT_JOIN . '
  449. where data.book = books.id and data.id = ?');
  450. $result->execute (array ($dataId));
  451. while ($post = $result->fetchObject ())
  452. {
  453. $book = new Book ($post);
  454. $data = new Data ($post, $book);
  455. $data->id = $dataId;
  456. $book->datas = array ($data);
  457. return $book;
  458. }
  459. return NULL;
  460. }
  461. public static function getBooksByQuery($query, $n, $database = NULL) {
  462. return self::getEntryArray (self::SQL_BOOKS_QUERY, array ("%" . $query . "%", "%" . $query . "%"), $n, $database);
  463. }
  464. public static function getAllBooks() {
  465. $result = parent::getDb ()->query("select substr (upper (sort), 1, 1) as title, count(*) as count
  466. from books
  467. group by substr (upper (sort), 1, 1)
  468. order by substr (upper (sort), 1, 1)");
  469. $entryArray = array();
  470. while ($post = $result->fetchObject ())
  471. {
  472. array_push ($entryArray, new Entry ($post->title, Book::getEntryIdByLetter ($post->title),
  473. str_format (localize("bookword", $post->count), $post->count), "text",
  474. array ( new LinkNavigation ("?page=".parent::PAGE_ALL_BOOKS_LETTER."&id=". rawurlencode ($post->title)))));
  475. }
  476. return $entryArray;
  477. }
  478. public static function getBooksByStartingLetter($letter, $n) {
  479. return self::getEntryArray (self::SQL_BOOKS_BY_FIRST_LETTER, array ($letter . "%"), $n);
  480. }
  481. public static function getEntryArray ($query, $params, $n, $database = NULL) {
  482. list ($totalNumber, $result) = parent::executeQuery ($query, self::BOOK_COLUMNS, self::getFilterString (), $params, $n, $database);
  483. $entryArray = array();
  484. while ($post = $result->fetchObject ())
  485. {
  486. $book = new Book ($post);
  487. array_push ($entryArray, $book->getEntry ());
  488. }
  489. return array ($entryArray, $totalNumber);
  490. }
  491. public static function getAllRecentBooks() {
  492. global $config;
  493. list ($entryArray, $totalNumber) = self::getEntryArray (self::SQL_BOOKS_RECENT . $config['cops_recentbooks_limit'], array (), -1);
  494. return $entryArray;
  495. }
  496. }