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

/book.php

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