Completed
Pull Request — master (#274)
by Markus
07:36
created

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 <[email protected]>
7
 */
8
9
require_once('base.php');
10
require_once('serie.php');
11
require_once('author.php');
12
require_once('rating.php');
13
require_once('publisher.php');
14
require_once('tag.php');
15
require_once('language.php');
16
require_once("customcolumn.php");
17
require_once('data.php');
18
require_once('resources/php-epub-meta/epub.php');
19
20
// Silly thing because PHP forbid string concatenation in class const
21
define ('SQL_BOOKS_LEFT_JOIN', "left outer join comments on comments.book = books.id
22
                                left outer join books_ratings_link on books_ratings_link.book = books.id
23
                                left outer join ratings on books_ratings_link.rating = ratings.id ");
24
define ('SQL_BOOKS_ALL', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . " order by books.sort ");
25
define ('SQL_BOOKS_BY_PUBLISHER', "select {0} from books_publishers_link, books " . SQL_BOOKS_LEFT_JOIN . "
26
                                                    where books_publishers_link.book = books.id and publisher = ? {1} order by publisher");
27
define ('SQL_BOOKS_BY_FIRST_LETTER', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
28
                                                    where upper (books.sort) like ? order by books.sort");
29
define ('SQL_BOOKS_BY_AUTHOR', "select {0} from books_authors_link, books " . SQL_BOOKS_LEFT_JOIN . "
30
                                                    left outer join books_series_link on books_series_link.book = books.id
31
                                                    where books_authors_link.book = books.id and author = ? {1} order by series desc, series_index asc, pubdate asc");
32
define ('SQL_BOOKS_BY_SERIE', "select {0} from books_series_link, books " . SQL_BOOKS_LEFT_JOIN . "
33
                                                    where books_series_link.book = books.id and series = ? {1} order by series_index");
34
define ('SQL_BOOKS_BY_TAG', "select {0} from books_tags_link, books " . SQL_BOOKS_LEFT_JOIN . "
35
                                                    where books_tags_link.book = books.id and tag = ? {1} order by sort");
36
define ('SQL_BOOKS_BY_LANGUAGE', "select {0} from books_languages_link, books " . SQL_BOOKS_LEFT_JOIN . "
37
                                                    where books_languages_link.book = books.id and lang_code = ? {1} order by sort");
38
define ('SQL_BOOKS_BY_CUSTOM', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
39
                                                    where {2}.book = books.id and {2}.{3} = ? {1} order by sort");
40
define ('SQL_BOOKS_BY_CUSTOM_BOOL_TRUE', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
41
                                                    where {2}.book = books.id and {2}.value = 1 {1} order by sort");
42
define ('SQL_BOOKS_BY_CUSTOM_BOOL_FALSE', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
43
                                                    where {2}.book = books.id and {2}.value = 0 {1} order by sort");
44
define ('SQL_BOOKS_BY_CUSTOM_BOOL_NULL', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
45
                                                    where books.id not in (select book from {2}) {1} order by sort");
46
define ('SQL_BOOKS_BY_CUSTOM_RATING', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
47
                                                    left join {2} on {2}.book = books.id
48
                                                    left join {3} on {3}.id = {2}.{4}
49
                                                    where {3}.value = ?  order by sort");
50
define ('SQL_BOOKS_BY_CUSTOM_RATING_NULL', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
51
								                    left join {2} on {2}.book = books.id
52
								                    left join {3} on {3}.id = {2}.{4}
53
                                                    where ((books.id not in (select {2}.book from {2})) or ({3}.value = 0)) {1} order by sort");
54
define ('SQL_BOOKS_BY_CUSTOM_DATE', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
55
                                                    where {2}.book = books.id and date({2}.value) = ? {1} order by sort");
56
define ('SQL_BOOKS_BY_CUSTOM_DIRECT', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
57
                                                    where {2}.book = books.id and {2}.value = ? {1} order by sort");
58
define ('SQL_BOOKS_BY_CUSTOM_DIRECT_ID', "select {0} from {2}, books " . SQL_BOOKS_LEFT_JOIN . "
59
                                                    where {2}.book = books.id and {2}.id = ? {1} order by sort");
60
define ('SQL_BOOKS_QUERY', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
61
                                                    where (
62
                                                    exists (select null from authors, books_authors_link where book = books.id and author = authors.id and authors.name like ?) or
63
                                                    exists (select null from tags, books_tags_link where book = books.id and tag = tags.id and tags.name like ?) or
64
                                                    exists (select null from series, books_series_link on book = books.id and books_series_link.series = series.id and series.name like ?) or
65
                                                    exists (select null from publishers, books_publishers_link where book = books.id and books_publishers_link.publisher = publishers.id and publishers.name like ?) or
66
                                                    title like ?) {1} order by books.sort");
67
define ('SQL_BOOKS_RECENT', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
68
                                                    where 1=1 {1} order by timestamp desc limit ");
69
define ('SQL_BOOKS_BY_RATING', "select {0} from books " . SQL_BOOKS_LEFT_JOIN . "
70
                                                    where books_ratings_link.book = books.id and ratings.id = ? {1} order by sort");
71
72
class Book extends Base {
73
    const ALL_BOOKS_UUID = "urn:uuid";
74
    const ALL_BOOKS_ID = "cops:books";
75
    const ALL_RECENT_BOOKS_ID = "cops:recentbooks";
76
    const BOOK_COLUMNS = "books.id as id, books.title as title, text as comment, path, timestamp, pubdate, series_index, uuid, has_cover, ratings.rating";
77
78
    const SQL_BOOKS_LEFT_JOIN = SQL_BOOKS_LEFT_JOIN;
79
    const SQL_BOOKS_ALL = SQL_BOOKS_ALL;
80
    const SQL_BOOKS_BY_PUBLISHER = SQL_BOOKS_BY_PUBLISHER;
81
    const SQL_BOOKS_BY_FIRST_LETTER = SQL_BOOKS_BY_FIRST_LETTER;
82
    const SQL_BOOKS_BY_AUTHOR = SQL_BOOKS_BY_AUTHOR;
83
    const SQL_BOOKS_BY_SERIE = SQL_BOOKS_BY_SERIE;
84
    const SQL_BOOKS_BY_TAG = SQL_BOOKS_BY_TAG;
85
    const SQL_BOOKS_BY_LANGUAGE = SQL_BOOKS_BY_LANGUAGE;
86
    const SQL_BOOKS_BY_CUSTOM = SQL_BOOKS_BY_CUSTOM;
87
    const SQL_BOOKS_BY_CUSTOM_BOOL_TRUE = SQL_BOOKS_BY_CUSTOM_BOOL_TRUE;
88
    const SQL_BOOKS_BY_CUSTOM_BOOL_FALSE = SQL_BOOKS_BY_CUSTOM_BOOL_FALSE;
89
    const SQL_BOOKS_BY_CUSTOM_BOOL_NULL = SQL_BOOKS_BY_CUSTOM_BOOL_NULL;
90
    const SQL_BOOKS_BY_CUSTOM_RATING = SQL_BOOKS_BY_CUSTOM_RATING;
91
    const SQL_BOOKS_BY_CUSTOM_RATING_NULL = SQL_BOOKS_BY_CUSTOM_RATING_NULL;
92
    const SQL_BOOKS_BY_CUSTOM_DATE = SQL_BOOKS_BY_CUSTOM_DATE;
93
    const SQL_BOOKS_BY_CUSTOM_DIRECT = SQL_BOOKS_BY_CUSTOM_DIRECT;
94
    const SQL_BOOKS_BY_CUSTOM_DIRECT_ID = SQL_BOOKS_BY_CUSTOM_DIRECT_ID;
95
    const SQL_BOOKS_QUERY = SQL_BOOKS_QUERY;
96
    const SQL_BOOKS_RECENT = SQL_BOOKS_RECENT;
97
    const SQL_BOOKS_BY_RATING = SQL_BOOKS_BY_RATING;
98
99
    const BAD_SEARCH = "QQQQQ";
100
101
    public $id;
102
    public $title;
103
    public $timestamp;
104
    public $pubdate;
105
    public $path;
106
    public $uuid;
107
    public $hasCover;
108
    public $relativePath;
109
    public $seriesIndex;
110
    public $comment;
111
    public $rating;
112
    public $datas = NULL;
113
    public $authors = NULL;
114
    public $publisher = NULL;
115
    public $serie = NULL;
116
    public $tags = NULL;
117
    public $languages = NULL;
118
    public $format = array ();
119
120
121 78
    public function __construct($line) {
122 78
        $this->id = $line->id;
123 78
        $this->title = $line->title;
124 78
        $this->timestamp = strtotime ($line->timestamp);
125 78
        $this->pubdate = $line->pubdate;
126 78
        $this->path = Base::getDbDirectory () . $line->path;
127 78
        $this->relativePath = $line->path;
128 78
        $this->seriesIndex = $line->series_index;
129 78
        $this->comment = $line->comment;
130 78
        $this->uuid = $line->uuid;
131 78
        $this->hasCover = $line->has_cover;
132 78
        if (!file_exists ($this->getFilePath ("jpg"))) {
133
            // double check
134 44
            $this->hasCover = 0;
135 44
        }
136 78
        $this->rating = $line->rating;
137 78
    }
138
139 42
    public function getEntryId () {
140 42
        return self::ALL_BOOKS_UUID.":".$this->uuid;
141
    }
142
143 4
    public static function getEntryIdByLetter ($startingLetter) {
144 4
        return self::ALL_BOOKS_ID.":letter:".$startingLetter;
145
    }
146
147 3
    public function getUri () {
148 3
        return "?page=".parent::PAGE_BOOK_DETAIL."&id=$this->id";
149
    }
150
151 3
    public function getDetailUrl () {
152 3
        $urlParam = $this->getUri ();
153 3
        if (!is_null (GetUrlParam (DB))) $urlParam = addURLParameter ($urlParam, DB, GetUrlParam (DB));
154 3
        return 'index.php' . $urlParam;
155
    }
156
157 43
    public function getTitle () {
158 43
        return $this->title;
159
    }
160
161
    /* Other class (author, series, tag, ...) initialization and accessors */
162
163
    /**
164
     * @return Author[]
165
     */
166 49
    public function getAuthors () {
167 49
        if (is_null ($this->authors)) {
168 49
            $this->authors = Author::getAuthorByBookId ($this->id);
169 49
        }
170 49
        return $this->authors;
171
    }
172
173
    public function getAuthorsName () {
174
        return implode (", ", array_map (function ($author) { return $author->name; }, $this->getAuthors ()));
175
    }
176
177
    public function getAuthorsSort () {
178
        return implode (", ", array_map (function ($author) { return $author->sort; }, $this->getAuthors ()));
179
    }
180
181 5
    public function getPublisher () {
182 5
        if (is_null ($this->publisher)) {
183 5
            $this->publisher = Publisher::getPublisherByBookId ($this->id);
184 5
        }
185 5
        return $this->publisher;
186
    }
187
188
    /**
189
     * @return Serie
190
     */
191 48
    public function getSerie () {
192 48
        if (is_null ($this->serie)) {
193 48
            $this->serie = Serie::getSerieByBookId ($this->id);
194 48
        }
195 48
        return $this->serie;
196
    }
197
198
    /**
199
     * @return string
200
     */
201 10
    public function getLanguages () {
202 10
        $lang = array ();
203 10
        $result = parent::getDb ()->prepare('select languages.lang_code
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getDb() instead of getLanguages()). Are you sure this is correct? If so, you might want to change this to $this->getDb().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
204
                from books_languages_link, languages
205
                where books_languages_link.lang_code = languages.id
206
                and book = ?
207 10
                order by item_order');
208 10
        $result->execute (array ($this->id));
209 10
        while ($post = $result->fetchObject ())
210
        {
211 10
            array_push ($lang, Language::getLanguageString($post->lang_code));
212 10
        }
213 10
        return implode (", ", $lang);
214
    }
215
216
    /**
217
     * @return Tag[]
218
     */
219 10
    public function getTags () {
220 10
        if (is_null ($this->tags)) {
221 10
            $this->tags = array ();
222
223 10
            $result = parent::getDb ()->prepare('select tags.id as id, name
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getDb() instead of getTags()). Are you sure this is correct? If so, you might want to change this to $this->getDb().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
224
                from books_tags_link, tags
225
                where tag = tags.id
226
                and book = ?
227 10
                order by name');
228 10
            $result->execute (array ($this->id));
229 10
            while ($post = $result->fetchObject ())
230
            {
231 9
                array_push ($this->tags, new Tag ($post));
232 9
            }
233 10
        }
234 10
        return $this->tags;
235
    }
236
237
    public function getTagsName () {
238
        return implode (", ", array_map (function ($tag) { return $tag->name; }, $this->getTags ()));
239
    }
240
241
    /**
242
     * @return Data[]
243
     */
244 62
    public function getDatas ()
245
    {
246 62
        if (is_null ($this->datas)) {
247 62
            $this->datas = Data::getDataByBook ($this);
248 62
        }
249 62
        return $this->datas;
250
    }
251
252
    /* End of other class (author, series, tag, ...) initialization and accessors */
253
254 58
    public static function getFilterString () {
255 58
        $filter = getURLParam ("tag", NULL);
256 58
        if (empty ($filter)) return "";
257
258 3
        $exists = true;
259 3
        if (preg_match ("/^!(.*)$/", $filter, $matches)) {
260 1
            $exists = false;
261 1
            $filter = $matches[1];
262 1
        }
263
264 3
        $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 . "')";
265
266 3
        if (!$exists) {
267 1
            $result = "not " . $result;
268 1
        }
269
270 3
        return "and " . $result;
271
    }
272
273 4
    public function GetMostInterestingDataToSendToKindle ()
274
    {
275 4
        $bestFormatForKindle = array ("EPUB", "PDF", "AZW3", "MOBI");
276 4
        $bestRank = -1;
277 4
        $bestData = NULL;
278 4
        foreach ($this->getDatas () as $data) {
279 4
            $key = array_search ($data->format, $bestFormatForKindle);
280 4
            if ($key !== false && $key > $bestRank) {
281 4
                $bestRank = $key;
282 4
                $bestData = $data;
283 4
            }
284 4
        }
285 4
        return $bestData;
286
    }
287
288 3
    public function getDataById ($idData)
289
    {
290
        $reduced = array_filter ($this->getDatas (), function ($data) use ($idData) {
291 3
            return $data->id == $idData;
292 3
        });
293 3
        return reset ($reduced);
294
    }
295
296 8
    public function getRating () {
297 8
        if (is_null ($this->rating) || $this->rating == 0) {
298 3
            return "";
299
        }
300 5
        $retour = "";
301 5
        for ($i = 0; $i < $this->rating / 2; $i++) {
302 5
            $retour .= "&#9733;";
303 5
        }
304 5
        for ($i = 0; $i < 5 - $this->rating / 2; $i++) {
305 3
            $retour .= "&#9734;";
306 3
        }
307 5
        return $retour;
308
    }
309
310 15
    public function getPubDate () {
311 15
        if (empty ($this->pubdate)) {
312 2
            return "";
313
        }
314 13
        $dateY = (int) substr($this->pubdate, 0, 4);
315 13
        if ($dateY > 102) {
316 12
            return str_pad($dateY, 4, "0", STR_PAD_LEFT);
317
        }
318 1
        return "";
319
    }
320
321 43
    public function getComment ($withSerie = true) {
322 43
        $addition = "";
323 43
        $se = $this->getSerie ();
324 43
        if (!is_null ($se) && $withSerie) {
325 38
            $addition = $addition . "<strong>" . localize("content.series") . "</strong>" . str_format (localize ("content.series.data"), $this->seriesIndex, htmlspecialchars ($se->name)) . "<br />\n";
326 38
        }
327 43
        if (preg_match ("/<\/(div|p|a|span)>/", $this->comment))
328 43
        {
329 37
            return $addition . html2xhtml ($this->comment);
330
        }
331
        else
332
        {
333 31
            return $addition . htmlspecialchars ($this->comment);
334
        }
335
    }
336
337
    public function getDataFormat ($format) {
338 12
        $reduced = array_filter ($this->getDatas (), function ($data) use ($format) {
339 12
            return $data->format == $format;
340 12
        });
341 12
        return reset ($reduced);
342
    }
343
344 78
    public function getFilePath ($extension, $idData = NULL, $relative = false)
345
    {
346 78
        if ($extension == "jpg")
347 78
        {
348 78
            $file = "cover.jpg";
349 78
        }
350
        else
351
        {
352 2
            $data = $this->getDataById ($idData);
353 2
            if (!$data) return NULL;
354 2
            $file = $data->name . "." . strtolower ($data->format);
355
        }
356
357
        if ($relative)
358 78
        {
359 3
            return $this->relativePath."/".$file;
360
        }
361
        else
362
        {
363 78
            return $this->path."/".$file;
364
        }
365
    }
366
367
    public function getUpdatedEpub ($idData)
368
    {
369
        global $config;
370
        $data = $this->getDataById ($idData);
371
372
        try
373
        {
374
            $epub = new EPub ($data->getLocalPath ());
375
376
            $epub->Title ($this->title);
377
            $authorArray = array ();
378
            foreach ($this->getAuthors() as $author) {
379
                $authorArray [$author->sort] = $author->name;
380
            }
381
            $epub->Authors ($authorArray);
382
            $epub->Language ($this->getLanguages ());
383
            $epub->Description ($this->getComment (false));
384
            $epub->Subjects ($this->getTagsName ());
385
            $epub->Cover2 ($this->getFilePath ("jpg"), "image/jpeg");
386
            $epub->Calibre ($this->uuid);
387
            $se = $this->getSerie ();
388
            if (!is_null ($se)) {
389
                $epub->Serie ($se->name);
390
                $epub->SerieIndex ($this->seriesIndex);
391
            }
392
            if ($config['cops_provide_kepub'] == "1"  && preg_match("/Kobo/", $_SERVER['HTTP_USER_AGENT'])) {
393
                $epub->updateForKepub ();
394
            }
395
            $epub->download ($data->getUpdatedFilenameEpub ());
396
        }
397
        catch (Exception $e)
398
        {
399
            echo "Exception : " . $e->getMessage();
400
        }
401
    }
402
403 3
    public function getThumbnail ($width, $height, $outputfile = NULL) {
404 3
        if (is_null ($width) && is_null ($height)) {
405 1
            return false;
406
        }
407
408 3
        $file = $this->getFilePath ("jpg");
409
        // get image size
410 3
        if ($size = GetImageSize($file)) {
411 3
            $w = $size[0];
412 3
            $h = $size[1];
413
            //set new size
414 3
            if (!is_null ($width)) {
415 2
                $nw = $width;
416 2
                if ($nw >= $w) { return false; }
417 1
                $nh = ($nw*$h)/$w;
418 1
            } else {
419 2
                $nh = $height;
420 2
                if ($nh >= $h) { return false; }
421 1
                $nw = ($nh*$w)/$h;
422
            }
423 2
        } else {
424
            return false;
425
        }
426
427
        //draw the image
428 2
        $src_img = imagecreatefromjpeg($file);
429 2
        $dst_img = imagecreatetruecolor($nw,$nh);
430 2
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);//resizing the image
431 2
        imagejpeg($dst_img,$outputfile,80);
432 2
        imagedestroy($src_img);
433 2
        imagedestroy($dst_img);
434
435 2
        return true;
436
    }
437
438 44
    public function getLinkArray ()
439
    {
440 44
        $linkArray = array();
441
442 44
        if ($this->hasCover)
443 44
        {
444 18
            array_push ($linkArray, Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_IMAGE_TYPE, "cover.jpg", NULL));
445
446 18
            array_push ($linkArray, Data::getLink ($this, "jpg", "image/jpeg", Link::OPDS_THUMBNAIL_TYPE, "cover.jpg", NULL));
447 18
        }
448
449 44
        foreach ($this->getDatas () as $data)
450
        {
451 44
            if ($data->isKnownType ())
452 44
            {
453 44
                array_push ($linkArray, $data->getDataLink (Link::OPDS_ACQUISITION_TYPE, $data->format));
454 44
            }
455 44
        }
456
457 44
        foreach ($this->getAuthors () as $author) {
458
            /* @var $author Author */
459 44
            array_push ($linkArray, new LinkNavigation ($author->getUri (), "related", str_format (localize ("bookentry.author"), localize ("splitByLetter.book.other"), $author->name)));
460 44
        }
461
462 44
        $serie = $this->getSerie ();
463 44
        if (!is_null ($serie)) {
464 41
            array_push ($linkArray, new LinkNavigation ($serie->getUri (), "related", str_format (localize ("content.series.data"), $this->seriesIndex, $serie->name)));
465 41
        }
466
467 44
        return $linkArray;
468
    }
469
470
471 41
    public function getEntry () {
472 41
        return new EntryBook ($this->getTitle (), $this->getEntryId (),
473 41
            $this->getComment (), "text/html",
474 41
            $this->getLinkArray (), $this);
475
    }
476
477 3
    public static function getBookCount($database = NULL) {
478 3
        return parent::executeQuerySingle ('select count(*) from books', $database);
479
    }
480
481 21
    public static function getCount() {
482 21
        global $config;
483 21
        $nBooks = parent::executeQuerySingle ('select count(*) from books');
484 21
        $result = array();
485 21
        $entry = new Entry (localize ("allbooks.title"),
486 21
                          self::ALL_BOOKS_ID,
487 21
                          str_format (localize ("allbooks.alphabetical", $nBooks), $nBooks), "text",
488 21
                          array ( new LinkNavigation ("?page=".parent::PAGE_ALL_BOOKS)), "", $nBooks);
489 21
        array_push ($result, $entry);
490 21
        if ($config['cops_recentbooks_limit'] > 0) {
491 21
            $entry = new Entry (localize ("recent.title"),
492 21
                              self::ALL_RECENT_BOOKS_ID,
493 21
                              str_format (localize ("recent.list"), $config['cops_recentbooks_limit']), "text",
494 21
                              array ( new LinkNavigation ("?page=".parent::PAGE_ALL_RECENT_BOOKS)), "", $config['cops_recentbooks_limit']);
495 21
            array_push ($result, $entry);
496 21
        }
497 21
        return $result;
498
    }
499
500 8
    public static function getBooksByAuthor($authorId, $n) {
501 8
        return self::getEntryArray (self::SQL_BOOKS_BY_AUTHOR, array ($authorId), $n);
502
    }
503
504 1
    public static function getBooksByRating($ratingId, $n) {
505 1
        return self::getEntryArray (self::SQL_BOOKS_BY_RATING, array ($ratingId), $n);
506
    }
507
508 2
    public static function getBooksByPublisher($publisherId, $n) {
509 2
        return self::getEntryArray (self::SQL_BOOKS_BY_PUBLISHER, array ($publisherId), $n);
510
    }
511
512 2
    public static function getBooksBySeries($serieId, $n) {
513 2
        return self::getEntryArray (self::SQL_BOOKS_BY_SERIE, array ($serieId), $n);
514
    }
515
516 2
    public static function getBooksByTag($tagId, $n) {
517 2
        return self::getEntryArray (self::SQL_BOOKS_BY_TAG, array ($tagId), $n);
518
    }
519
520 2
    public static function getBooksByLanguage($languageId, $n) {
521 2
        return self::getEntryArray (self::SQL_BOOKS_BY_LANGUAGE, array ($languageId), $n);
522
    }
523
524
    /**
525
     * @param $customColumn CustomColumn
526
     * @param $id integer
527
     * @param $n integer
528
     * @return array
529
     */
530 4
    public static function getBooksByCustom($customColumn, $id, $n) {
531 4
        list($query, $params) = $customColumn->getQuery($id);
532
533 4
        return self::getEntryArray ($query, $params, $n);
534
    }
535
536 37
    public static function getBookById($bookId) {
537 37
        $result = parent::getDb ()->prepare('select ' . self::BOOK_COLUMNS . '
538 37
from books ' . self::SQL_BOOKS_LEFT_JOIN . '
539 37
where books.id = ?');
540 37
        $result->execute (array ($bookId));
541 37
        while ($post = $result->fetchObject ())
542
        {
543 36
            $book = new Book ($post);
544 36
            return $book;
545
        }
546 1
        return NULL;
547
    }
548
549 1
    public static function getBookByDataId($dataId) {
550 1
        $result = parent::getDb ()->prepare('select ' . self::BOOK_COLUMNS . ', data.name, data.format
551 1
from data, books ' . self::SQL_BOOKS_LEFT_JOIN . '
552 1
where data.book = books.id and data.id = ?');
553 1
        $result->execute (array ($dataId));
554 1
        while ($post = $result->fetchObject ())
555
        {
556 1
            $book = new Book ($post);
557 1
            $data = new Data ($post, $book);
558 1
            $data->id = $dataId;
559 1
            $book->datas = array ($data);
560 1
            return $book;
561
        }
562
        return NULL;
563
    }
564
565 2
    public static function getBooksByQuery($query, $n, $database = NULL, $numberPerPage = NULL) {
566 2
        $i = 0;
567 2
        $critArray = array ();
568 2
        foreach (array (PageQueryResult::SCOPE_AUTHOR,
569 2
                        PageQueryResult::SCOPE_TAG,
570 2
                        PageQueryResult::SCOPE_SERIES,
571 2
                        PageQueryResult::SCOPE_PUBLISHER,
572 2
                        PageQueryResult::SCOPE_BOOK) as $key) {
573 2
            if (in_array($key, getCurrentOption ('ignored_categories')) ||
574 2
                (!array_key_exists ($key, $query) && !array_key_exists ("all", $query))) {
575
                $critArray [$i] = self::BAD_SEARCH;
576
            }
577
            else {
578 2
                if (array_key_exists ($key, $query)) {
579
                    $critArray [$i] = $query [$key];
580
                } else {
581 2
                    $critArray [$i] = $query ["all"];
582
                }
583
            }
584 2
            $i++;
585 2
        }
586 2
        return self::getEntryArray (self::SQL_BOOKS_QUERY, $critArray, $n, $database, $numberPerPage);
587
    }
588
589 1
    public static function getBooks($n) {
590 1
        list ($entryArray, $totalNumber) = self::getEntryArray (self::SQL_BOOKS_ALL , array (), $n);
591 1
        return array ($entryArray, $totalNumber);
592
    }
593
594 3
    public static function getAllBooks() {
595
        /* @var $result PDOStatement */
596
597 3
        list (, $result) = parent::executeQuery ("select {0}
598
from books
599
group by substr (upper (sort), 1, 1)
600 3
order by substr (upper (sort), 1, 1)", "substr (upper (sort), 1, 1) as title, count(*) as count", self::getFilterString (), array (), -1);
601
602 3
        $entryArray = array();
603 3
        while ($post = $result->fetchObject ())
604
        {
605 3
            array_push ($entryArray, new Entry ($post->title, Book::getEntryIdByLetter ($post->title),
606 3
                str_format (localize("bookword", $post->count), $post->count), "text",
607 3
                array ( new LinkNavigation ("?page=".parent::PAGE_ALL_BOOKS_LETTER."&id=". rawurlencode ($post->title))), "", $post->count));
608 3
        }
609 3
        return $entryArray;
610
    }
611
612 25
    public static function getBooksByStartingLetter($letter, $n, $database = NULL, $numberPerPage = NULL) {
613 25
        return self::getEntryArray (self::SQL_BOOKS_BY_FIRST_LETTER, array ($letter . "%"), $n, $database, $numberPerPage);
614
    }
615
616 55
    public static function getEntryArray ($query, $params, $n, $database = NULL, $numberPerPage = NULL) {
617
        /* @var $totalNumber integer */
618
        /* @var $result PDOStatement */
619 55
        list($totalNumber, $result) = parent::executeQuery($query, self::BOOK_COLUMNS, self::getFilterString (), $params, $n, $database, $numberPerPage);
620
621 55
        $entryArray = array();
622 55
        while ($post = $result->fetchObject())
623
        {
624 41
            $book = new Book ($post);
625 41
            array_push ($entryArray, $book->getEntry());
626 41
        }
627 55
        return array ($entryArray, $totalNumber);
628
    }
629
630 5
    public static function getAllRecentBooks() {
631 5
        global $config;
632 5
        list ($entryArray, ) = self::getEntryArray (self::SQL_BOOKS_RECENT . $config['cops_recentbooks_limit'], array (), -1);
633 5
        return $entryArray;
634
    }
635
636
    /**
637
     * The values of all the specified columns
638
     *
639
     * @param string[] $columns
640
     * @return CustomColumn[]
641
     */
642 5
    public function getCustomColumnValues($columns, $asArray = false) {
643 5
        $result = array();
644
        
645 5
        foreach ($columns as $lookup) {
646 2
            $col = CustomColumnType::createByLookup($lookup);
647 2
            if (! is_null($col)) {
648 2
                $cust = $col->getCustomByBook($this);
649 2
                if (! is_null($cust)) {
650 2
                    if ($asArray) {
651 1
                        array_push($result, $cust->toArray());
652 1
                    } else {
653 1
                        array_push($result, $cust);
654
                    }
655 2
                }
656 2
            }
657 5
        }
658
659 5
        return $result;
660
    }
661
}
662