Completed
Pull Request — master (#233)
by
unknown
11:31
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
define ("VERSION", "1.0.0RC4");
10
define ("DB", "db");
11
date_default_timezone_set($config['default_timezone']);
12
13
14
function useServerSideRendering () {
15 3
    global $config;
16 3
    return preg_match("/" . $config['cops_server_side_render'] . "/", $_SERVER['HTTP_USER_AGENT']);
17
}
18
19
function serverSideRender ($data) {
20
    // Get the templates
21 2
    $theme = getCurrentTemplate ();
22 2
    $header = file_get_contents('templates/' . $theme . '/header.html');
23 2
    $footer = file_get_contents('templates/' . $theme . '/footer.html');
24 2
    $main = file_get_contents('templates/' . $theme . '/main.html');
25 2
    $bookdetail = file_get_contents('templates/' . $theme . '/bookdetail.html');
26 2
    $page = file_get_contents('templates/' . $theme . '/page.html');
27
28
    // Generate the function for the template
29 2
    $template = new doT ();
30 2
    $dot = $template->template ($page, array ("bookdetail" => $bookdetail,
31 2
                                              "header" => $header,
32 2
                                              "footer" => $footer,
33 2
                                              "main" => $main));
34
    // If there is a syntax error in the function created
35
    // $dot will be equal to FALSE
36 2
    if (!$dot) {
37
        return FALSE;
38
    }
39
    // Execute the template
40 2
    if (!empty ($data)) {
41
        return $dot ($data);
42
    }
43
44 2
    return NULL;
45
}
46
47
function getQueryString () {
48 18
    if ( isset($_SERVER['QUERY_STRING']) ) {
49 16
        return $_SERVER['QUERY_STRING'];
50
    }
51 2
    return "";
52
}
53
54
function notFound () {
55
    header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
56
    header("Status: 404 Not Found");
57
58
    $_SERVER['REDIRECT_STATUS'] = 404;
59
}
60
61
function getURLParam ($name, $default = NULL) {
62 101
    if (!empty ($_GET) && isset($_GET[$name]) && $_GET[$name] != "") {
63 24
        return $_GET[$name];
64
    }
65 101
    return $default;
66
}
67
68
function getCurrentOption ($option) {
69 87
    global $config;
70 87
    if (isset($_COOKIE[$option])) {
71 2
        if (isset($config ["cops_" . $option]) && is_array ($config ["cops_" . $option])) {
72
            return explode (",", $_COOKIE[$option]);
73
        } else {
74 2
            return $_COOKIE[$option];
75
        }
76
    }
77 85
    if ($option == "style") {
78 2
        return "default";
79
    }
80
81 85
    if (isset($config ["cops_" . $option])) {
82 85
        return $config ["cops_" . $option];
83
    }
84
85
    return "";
86
}
87
88
function getCurrentCss () {
89 2
    return "templates/" . getCurrentTemplate () . "/styles/style-" . getCurrentOption ("style") . ".css";
90
}
91
92
function getCurrentTemplate () {
93 4
    return getCurrentOption ("template");
94
}
95
96
function getUrlWithVersion ($url) {
97 50
    return $url . "?v=" . VERSION;
98
}
99
100
function xml2xhtml($xml) {
101 35
    return preg_replace_callback('#<(\w+)([^>]*)\s*/>#s', create_function('$m', '
102
        $xhtml_tags = array("br", "hr", "input", "frame", "img", "area", "link", "col", "base", "basefont", "param");
103
        return in_array($m[1], $xhtml_tags) ? "<$m[1]$m[2] />" : "<$m[1]$m[2]></$m[1]>";
104 35
    '), $xml);
105
}
106
107
function display_xml_error($error)
108
{
109
    $return = "";
110
    $return .= str_repeat('-', $error->column) . "^\n";
111
112
    switch ($error->level) {
113
        case LIBXML_ERR_WARNING:
114
            $return .= "Warning $error->code: ";
115
            break;
116
         case LIBXML_ERR_ERROR:
117
            $return .= "Error $error->code: ";
118
            break;
119
        case LIBXML_ERR_FATAL:
120
            $return .= "Fatal Error $error->code: ";
121
            break;
122
    }
123
124
    $return .= trim($error->message) .
125
               "\n  Line: $error->line" .
126
               "\n  Column: $error->column";
127
128
    if ($error->file) {
129
        $return .= "\n  File: $error->file";
130
    }
131
132
    return "$return\n\n--------------------------------------------\n\n";
133
}
134
135
function are_libxml_errors_ok ()
136
{
137 35
    $errors = libxml_get_errors();
138
139 35
    foreach ($errors as $error) {
140
        if ($error->code == 801) return false;
141 35
    }
142 35
    return true;
143
}
144
145
function html2xhtml ($html) {
146 35
    $doc = new DOMDocument();
147 35
    libxml_use_internal_errors(true);
148
149 35
    $doc->loadHTML('<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' .
150 35
                        $html  . '</body></html>'); // Load the HTML
151 35
    $output = $doc->saveXML($doc->documentElement); // Transform to an Ansi xml stream
152 35
    $output = xml2xhtml($output);
153 35
    if (preg_match ('#<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></meta></head><body>(.*)</body></html>#ms', $output, $matches)) {
154 35
        $output = $matches [1]; // Remove <html><body>
155 35
    }
156
    /*
157
    // In case of error with summary, use it to debug
158
    $errors = libxml_get_errors();
159
160
    foreach ($errors as $error) {
161
        $output .= display_xml_error($error);
162
    }
163
    */
164
165 35
    if (!are_libxml_errors_ok ()) $output = "HTML code not valid.";
166
167 35
    libxml_use_internal_errors(false);
168 35
    return $output;
169
}
170
171
/**
172
 * This method is a direct copy-paste from
173
 * http://tmont.com/blargh/2010/1/string-format-in-php
174
 */
175
function str_format($format) {
176 94
    $args = func_get_args();
177 94
    $format = array_shift($args);
178
179 94
    preg_match_all('/(?=\{)\{(\d+)\}(?!\})/', $format, $matches, PREG_OFFSET_CAPTURE);
180 94
    $offset = 0;
181 94
    foreach ($matches[1] as $data) {
182 94
        $i = $data[0];
183 94
        $format = substr_replace($format, @$args[$i], $offset + $data[1] - 1, 2 + strlen($i));
184 94
        $offset += strlen(@$args[$i]) - 2 - strlen($i);
185 94
    }
186
187 94
    return $format;
188
}
189
190
/**
191
 * Get all accepted languages from the browser and put them in a sorted array
192
 * languages id are normalized : fr-fr -> fr_FR
193
 * @return array of languages
194
 */
195
function getAcceptLanguages() {
196 16
    $langs = array();
197
198 16
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
199
        // break up string into pieces (languages and q factors)
200 16
        $accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
201 16
        if (preg_match('/^(\w{2})-\w{2}$/', $accept, $matches)) {
202
            // Special fix for IE11 which send fr-FR and nothing else
203 3
            $accept = $accept . "," . $matches[1] . ";q=0.8";
204 3
        }
205 16
        preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $accept, $lang_parse);
206
207 16
        if (count($lang_parse[1])) {
208 16
            $langs = array();
209 16
            foreach ($lang_parse[1] as $lang) {
210
                // Format the language code (not standard among browsers)
211 16
                if (strlen($lang) == 5) {
212 11
                    $lang = str_replace("-", "_", $lang);
213 11
                    $splitted = preg_split("/_/", $lang);
214 11
                    $lang = $splitted[0] . "_" . strtoupper($splitted[1]);
215 11
                }
216 16
                array_push($langs, $lang);
217 16
            }
218
            // create a list like "en" => 0.8
219 16
            $langs = array_combine($langs, $lang_parse[4]);
220
221
            // set default to 1 for any without q factor
222 16
            foreach ($langs as $lang => $val) {
223 16
                if ($val === '') $langs[$lang] = 1;
224 16
            }
225
226
            // sort list based on value
227 16
            arsort($langs, SORT_NUMERIC);
228 16
        }
229 16
    }
230
231 16
    return $langs;
232
}
233
234
/**
235
 * Find the best translation file possible based on the accepted languages
236
 * @return array of language and language file
237
 */
238
function getLangAndTranslationFile() {
239 17
    global $config;
240 17
    $langs = array();
241 17
    $lang = "en";
242 17
    if (!empty($config['cops_language'])) {
243
        $lang = $config['cops_language'];
244
    }
245 17
    elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
246 16
        $langs = getAcceptLanguages();
247 16
    }
248
    //echo var_dump($langs);
249 17
    $lang_file = NULL;
250 17
    foreach ($langs as $language => $val) {
251 16
        $temp_file = dirname(__FILE__). '/lang/Localization_' . $language . '.json';
252 16
        if (file_exists($temp_file)) {
253 16
            $lang = $language;
254 16
            $lang_file = $temp_file;
255 16
            break;
256
        }
257 17
    }
258 17
    if (empty ($lang_file)) {
259 3
        $lang_file = dirname(__FILE__). '/lang/Localization_' . $lang . '.json';
260 3
    }
261 17
    return array($lang, $lang_file);
262
}
263
264
/**
265
 * This method is based on this page
266
 * http://www.mind-it.info/2010/02/22/a-simple-approach-to-localization-in-php/
267
 */
268
function localize($phrase, $count=-1, $reset=false) {
269 114
    global $config;
270 114
    if ($count == 0)
271 114
        $phrase .= ".none";
272 114
    if ($count == 1)
273 114
        $phrase .= ".one";
274 114
    if ($count > 1)
275 114
        $phrase .= ".many";
276
277
    /* Static keyword is used to ensure the file is loaded only once */
278 114
    static $translations = NULL;
279 114
    if ($reset) {
280 16
        $translations = NULL;
281 16
    }
282
    /* If no instance of $translations has occured load the language file */
283 114
    if (is_null($translations)) {
284 17
        $lang_file_en = NULL;
285 17
        list ($lang, $lang_file) = getLangAndTranslationFile();
286 17
        if ($lang != "en") {
287 1
            $lang_file_en = dirname(__FILE__). '/lang/' . 'Localization_en.json';
288 1
        }
289
290 17
        $lang_file_content = file_get_contents($lang_file);
291
        /* Load the language file as a JSON object and transform it into an associative array */
292 17
        $translations = json_decode($lang_file_content, true);
293
294
        /* Clean the array of all unfinished translations */
295 17
        foreach (array_keys ($translations) as $key) {
296 17
            if (preg_match ("/^##TODO##/", $key)) {
297 1
                unset ($translations [$key]);
298 1
            }
299 17
        }
300
        if ($lang_file_en)
301 17
        {
302 1
            $lang_file_content = file_get_contents($lang_file_en);
303 1
            $translations_en = json_decode($lang_file_content, true);
304 1
            $translations = array_merge ($translations_en, $translations);
305 1
        }
306 17
    }
307 114
    if (array_key_exists ($phrase, $translations)) {
308 114
        return $translations[$phrase];
309
    }
310 1
    return $phrase;
311
}
312
313
function addURLParameter($urlParams, $paramName, $paramValue) {
314 58
    if (empty ($urlParams)) {
315 48
        $urlParams = "";
316 48
    }
317 58
    $start = "";
318 58
    if (preg_match ("#^\?(.*)#", $urlParams, $matches)) {
319 15
        $start = "?";
320 15
        $urlParams = $matches[1];
321 15
    }
322 58
    $params = array();
323 58
    parse_str($urlParams, $params);
324 58
    if (empty ($paramValue) && $paramValue != 0) {
325
        unset ($params[$paramName]);
326
    } else {
327 58
        $params[$paramName] = $paramValue;
328
    }
329 58
    return $start . http_build_query($params);
330
}
331
332
function useNormAndUp () {
333 107
    global $config;
334 107
    return $config ['cops_normalized_search'] == "1";
335
}
336
337
function normalizeUtf8String( $s) {
338 8
    include_once 'transliteration.php';
339 8
    return _transliteration_process($s);
340
}
341
342
function normAndUp ($s) {
343 7
    return mb_strtoupper (normalizeUtf8String($s), 'UTF-8');
344
}
345
346
class Link
347
{
348
    const OPDS_THUMBNAIL_TYPE = "http://opds-spec.org/image/thumbnail";
349
    const OPDS_IMAGE_TYPE = "http://opds-spec.org/image";
350
    const OPDS_ACQUISITION_TYPE = "http://opds-spec.org/acquisition";
351
    const OPDS_NAVIGATION_TYPE = "application/atom+xml;profile=opds-catalog;kind=navigation";
352
    const OPDS_PAGING_TYPE = "application/atom+xml;profile=opds-catalog;kind=acquisition";
353
354
    public $href;
355
    public $type;
356
    public $rel;
357
    public $title;
358
    public $facetGroup;
359
    public $activeFacet;
360
361 96
    public function __construct($phref, $ptype, $prel = NULL, $ptitle = NULL, $pfacetGroup = NULL, $pactiveFacet = FALSE) {
362 96
        $this->href = $phref;
363 96
        $this->type = $ptype;
364 96
        $this->rel = $prel;
365 96
        $this->title = $ptitle;
366 96
        $this->facetGroup = $pfacetGroup;
367 96
        $this->activeFacet = $pactiveFacet;
368 96
    }
369
370 10
    public function hrefXhtml () {
371 10
        return $this->href;
372
    }
373
}
374
375
class LinkNavigation extends Link
376
{
377 95
    public function __construct($phref, $prel = NULL, $ptitle = NULL) {
378 95
        parent::__construct ($phref, Link::OPDS_NAVIGATION_TYPE, $prel, $ptitle);
379 95
        if (!is_null (GetUrlParam (DB))) $this->href = addURLParameter ($this->href, DB, GetUrlParam (DB));
380 95
        if (!preg_match ("#^\?(.*)#", $this->href) && !empty ($this->href)) $this->href = "?" . $this->href;
381 95
        if (preg_match ("/(bookdetail|getJSON).php/", $_SERVER["SCRIPT_NAME"])) {
382
            $this->href = "index.php" . $this->href;
383
        } else {
384 95
            $this->href = $_SERVER["SCRIPT_NAME"] . $this->href;
385
        }
386 95
    }
387
}
388
389
class LinkFacet extends Link
390
{
391 1
    public function __construct($phref, $ptitle = NULL, $pfacetGroup = NULL, $pactiveFacet = FALSE) {
392 1
        parent::__construct ($phref, Link::OPDS_PAGING_TYPE, "http://opds-spec.org/facet", $ptitle, $pfacetGroup, $pactiveFacet);
393 1
        if (!is_null (GetUrlParam (DB))) $this->href = addURLParameter ($this->href, DB, GetUrlParam (DB));
394 1
        $this->href = $_SERVER["SCRIPT_NAME"] . $this->href;
395 1
    }
396
}
397
398
class Entry
399
{
400
    public $title;
401
    public $id;
402
    public $content;
403
    public $numberOfElement;
404
    public $contentType;
405
    public $linkArray;
406
    public $localUpdated;
407
    public $className;
408
    private static $updated = NULL;
409
410
    public static $icons = array(
411
        Author::ALL_AUTHORS_ID       => 'images/author.png',
412
        Serie::ALL_SERIES_ID         => 'images/serie.png',
413
        Book::ALL_RECENT_BOOKS_ID    => 'images/recent.png',
414
        Tag::ALL_TAGS_ID             => 'images/tag.png',
415
        Language::ALL_LANGUAGES_ID   => 'images/language.png',
416
        CustomColumn::ALL_CUSTOMS_ID => 'images/tag.png',
417
        "cops:books$"             => 'images/allbook.png',
418
        "cops:books:letter"       => 'images/allbook.png',
419
        Publisher::ALL_PUBLISHERS_ID => 'images/publisher.png'
420
    );
421
422
    public function getUpdatedTime () {
423
        if (!is_null ($this->localUpdated)) {
424
            return date (DATE_ATOM, $this->localUpdated);
425
        }
426
        if (is_null (self::$updated)) {
427
            self::$updated = time();
428
        }
429
        return date (DATE_ATOM, self::$updated);
430
    }
431
432 7
    public function getNavLink () {
433 7
        foreach ($this->linkArray as $link) {
434 7
            if ($link->type != Link::OPDS_NAVIGATION_TYPE) { continue; }
435
436 7
            return $link->hrefXhtml ();
437
        }
438
        return "#";
439
    }
440
441 89
    public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pclass = "", $pcount = 0) {
442 89
        global $config;
443 89
        $this->title = $ptitle;
444 89
        $this->id = $pid;
445 89
        $this->content = $pcontent;
446 89
        $this->contentType = $pcontentType;
447 89
        $this->linkArray = $plinkArray;
448 89
        $this->className = $pclass;
449 89
        $this->numberOfElement = $pcount;
450
451 89
        if ($config['cops_show_icons'] == 1)
452 89
        {
453 89
            foreach (self::$icons as $reg => $image)
454
            {
455 89
                if (preg_match ("/" . $reg . "/", $pid)) {
456 50
                    array_push ($this->linkArray, new Link (getUrlWithVersion ($image), "image/png", Link::OPDS_THUMBNAIL_TYPE));
457 50
                    break;
458
                }
459 89
            }
460 89
        }
461
462 89
        if (!is_null (GetUrlParam (DB))) $this->id = str_replace ("cops:", "cops:" . GetUrlParam (DB) . ":", $this->id);
463 89
    }
464
}
465
466
class EntryBook extends Entry
467
{
468
    public $book;
469
470 39
    public function __construct($ptitle, $pid, $pcontent, $pcontentType, $plinkArray, $pbook) {
471 39
        parent::__construct ($ptitle, $pid, $pcontent, $pcontentType, $plinkArray);
472 39
        $this->book = $pbook;
473 39
        $this->localUpdated = $pbook->timestamp;
474 39
    }
475
476
    public function getCoverThumbnail () {
477
        foreach ($this->linkArray as $link) {
478
            if ($link->rel == Link::OPDS_THUMBNAIL_TYPE)
479
                return $link->hrefXhtml ();
480
        }
481
        return null;
482
    }
483
484
    public function getCover () {
485
        foreach ($this->linkArray as $link) {
486
            if ($link->rel == Link::OPDS_IMAGE_TYPE)
487
                return $link->hrefXhtml ();
488
        }
489
        return null;
490
    }
491
}
492
493
class Page
494
{
495
    public $title;
496
    public $subtitle = "";
497
    public $authorName = "";
498
    public $authorUri = "";
499
    public $authorEmail = "";
500
    public $idPage;
501
    public $idGet;
502
    public $query;
503
    public $favicon;
504
    public $n;
505
    public $book;
506
    public $totalNumber = -1;
507
    public $entryArray = array();
508
509 81
    public static function getPage ($pageId, $id, $query, $n)
510
    {
511
        switch ($pageId) {
512 81
            case Base::PAGE_ALL_AUTHORS :
513 3
                return new PageAllAuthors ($id, $query, $n);
514 78
            case Base::PAGE_AUTHORS_FIRST_LETTER :
515 1
                return new PageAllAuthorsLetter ($id, $query, $n);
516 77
            case Base::PAGE_AUTHOR_DETAIL :
517 7
                return new PageAuthorDetail ($id, $query, $n);
518 70
            case Base::PAGE_ALL_TAGS :
519 2
                return new PageAllTags ($id, $query, $n);
520 68
            case Base::PAGE_TAG_DETAIL :
521 1
                return new PageTagDetail ($id, $query, $n);
522 67
            case Base::PAGE_ALL_LANGUAGES :
523 2
                return new PageAllLanguages ($id, $query, $n);
524 65
            case Base::PAGE_LANGUAGE_DETAIL :
525 1
                return new PageLanguageDetail ($id, $query, $n);
526 64
            case Base::PAGE_ALL_CUSTOMS :
527 3
                return new PageAllCustoms ($id, $query, $n);
528 61
            case Base::PAGE_CUSTOM_DETAIL :
529 3
                return new PageCustomDetail ($id, $query, $n);
530 58
            case Base::PAGE_ALL_RATINGS :
531 1
                return new PageAllRating ($id, $query, $n);
532 57
            case Base::PAGE_RATING_DETAIL :
533 1
                return new PageRatingDetail ($id, $query, $n);
534 56
            case Base::PAGE_ALL_SERIES :
535 2
                return new PageAllSeries ($id, $query, $n);
536 54
            case Base::PAGE_ALL_BOOKS :
537 3
                return new PageAllBooks ($id, $query, $n);
538 51
            case Base::PAGE_ALL_BOOKS_LETTER:
539 1
                return new PageAllBooksLetter ($id, $query, $n);
540 50
            case Base::PAGE_ALL_RECENT_BOOKS :
541 4
                return new PageRecentBooks ($id, $query, $n);
542 46
            case Base::PAGE_SERIE_DETAIL :
543 1
                return new PageSerieDetail ($id, $query, $n);
544 45
            case Base::PAGE_OPENSEARCH_QUERY :
545 31
                return new PageQueryResult ($id, $query, $n);
546 14
            case Base::PAGE_BOOK_DETAIL :
547 1
                return new PageBookDetail ($id, $query, $n);
548 13
            case Base::PAGE_ALL_PUBLISHERS:
549 2
                return new PageAllPublishers ($id, $query, $n);
550 11
            case Base::PAGE_PUBLISHER_DETAIL :
551 1
                return new PagePublisherDetail ($id, $query, $n);
552 10
            case Base::PAGE_ABOUT :
553
                return new PageAbout ($id, $query, $n);
554 10
            case Base::PAGE_CUSTOMIZE :
555
                return new PageCustomize ($id, $query, $n);
556 10
            default:
557 10
                $page = new Page ($id, $query, $n);
558 10
                $page->idPage = "cops:catalog";
559 10
                return $page;
560 10
        }
561
    }
562
563 81
    public function __construct($pid, $pquery, $pn) {
564 81
        global $config;
565
566 81
        $this->idGet = $pid;
567 81
        $this->query = $pquery;
568 81
        $this->n = $pn;
569 81
        $this->favicon = $config['cops_icon'];
570 81
        $this->authorName = empty($config['cops_author_name']) ? utf8_encode('S�bastien Lucas') : $config['cops_author_name'];
571 81
        $this->authorUri = empty($config['cops_author_uri']) ? 'http://blog.slucas.fr' : $config['cops_author_uri'];
572 81
        $this->authorEmail = empty($config['cops_author_email']) ? '[email protected]' : $config['cops_author_email'];
573 81
    }
574
575 10
    public function InitializeContent ()
576
    {
577 10
        global $config;
578 10
        $this->title = $config['cops_title_default'];
579 10
        $this->subtitle = $config['cops_subtitle_default'];
580 10
        if (Base::noDatabaseSelected ()) {
581 2
            $i = 0;
582 2
            foreach (Base::getDbNameList () as $key) {
583 2
                $nBooks = Book::getBookCount ($i);
584 2
                array_push ($this->entryArray, new Entry ($key, "cops:{$i}:catalog",
585 2
                                        str_format (localize ("bookword", $nBooks), $nBooks), "text",
586 2
                                        array ( new LinkNavigation ("?" . DB . "={$i}")), "", $nBooks));
587 2
                $i++;
588 2
                Base::clearDb ();
589 2
            }
590 2
        } else {
591 8
            if (!in_array (PageQueryResult::SCOPE_AUTHOR, getCurrentOption ('ignored_categories'))) {
592 7
                array_push ($this->entryArray, Author::getCount());
593 7
            }
594 8
            if (!in_array (PageQueryResult::SCOPE_SERIES, getCurrentOption ('ignored_categories'))) {
595 7
                $series = Serie::getCount();
596 7
                if (!is_null ($series)) array_push ($this->entryArray, $series);
597 7
            }
598 8
            if (!in_array (PageQueryResult::SCOPE_PUBLISHER, getCurrentOption ('ignored_categories'))) {
599 7
                $publisher = Publisher::getCount();
600 7
                if (!is_null ($publisher)) array_push ($this->entryArray, $publisher);
601 7
            }
602 8
            if (!in_array (PageQueryResult::SCOPE_TAG, getCurrentOption ('ignored_categories'))) {
603 7
                $tags = Tag::getCount();
604 7
                if (!is_null ($tags)) array_push ($this->entryArray, $tags);
605 7
            }
606 8
            if (!in_array (PageQueryResult::SCOPE_RATING, getCurrentOption ('ignored_categories'))) {
607 8
                $rating = Rating::getCount();
608 8
                if (!is_null ($rating)) array_push ($this->entryArray, $rating);
609 8
            }
610 8
            if (!in_array ("language", getCurrentOption ('ignored_categories'))) {
611 7
                $languages = Language::getCount();
612 7
                if (!is_null ($languages)) array_push ($this->entryArray, $languages);
613 7
            }
614 8
            foreach ($config['cops_calibre_custom_column'] as $lookup) {
615 4
                $customId = CustomColumn::getCustomId ($lookup);
616 4
                if (!is_null ($customId)) {
617 4
                    array_push ($this->entryArray, CustomColumn::getCount($customId));
618 4
                }
619 8
            }
620 8
            $this->entryArray = array_merge ($this->entryArray, Book::getCount());
621
622 8
            if (Base::isMultipleDatabaseEnabled ()) $this->title =  Base::getDbName ();
623
        }
624 10
    }
625
626 17
    public function isPaginated ()
627
    {
628 17
        return (getCurrentOption ("max_item_per_page") != -1 &&
629 17
                $this->totalNumber != -1 &&
630 17
                $this->totalNumber > getCurrentOption ("max_item_per_page"));
631
    }
632
633 2
    public function getNextLink ()
634
    {
635 2
        $currentUrl = preg_replace ("/\&n=.*?$/", "", "?" . getQueryString ());
636 2
        if (($this->n) * getCurrentOption ("max_item_per_page") < $this->totalNumber) {
637 1
            return new LinkNavigation ($currentUrl . "&n=" . ($this->n + 1), "next", localize ("paging.next.alternate"));
638
        }
639 1
        return NULL;
640
    }
641
642 2
    public function getPrevLink ()
643
    {
644 2
        $currentUrl = preg_replace ("/\&n=.*?$/", "", "?" . getQueryString ());
645 2
        if ($this->n > 1) {
646 1
            return new LinkNavigation ($currentUrl . "&n=" . ($this->n - 1), "previous", localize ("paging.previous.alternate"));
647
        }
648 2
        return NULL;
649
    }
650
651 2
    public function getMaxPage ()
652
    {
653 2
        return ceil ($this->totalNumber / getCurrentOption ("max_item_per_page"));
654
    }
655
656 70
    public function containsBook ()
657
    {
658 70
        if (count ($this->entryArray) == 0) return false;
659 68
        if (get_class ($this->entryArray [0]) == "EntryBook") return true;
660 46
        return false;
661
    }
662
}
663
664
class PageAllAuthors extends Page
665
{
666 3
    public function InitializeContent ()
667
    {
668 3
        $this->title = localize("authors.title");
669 3
        if (getCurrentOption ("author_split_first_letter") == 1) {
670 2
            $this->entryArray = Author::getAllAuthorsByFirstLetter();
671 2
        }
672
        else {
673 1
            $this->entryArray = Author::getAllAuthors();
674
        }
675 3
        $this->idPage = Author::ALL_AUTHORS_ID;
676 3
    }
677
}
678
679
class PageAllAuthorsLetter extends Page
680
{
681 1
    public function InitializeContent ()
682
    {
683 1
        $this->idPage = Author::getEntryIdByLetter ($this->idGet);
684 1
        $this->entryArray = Author::getAuthorsByStartingLetter ($this->idGet);
685 1
        $this->title = str_format (localize ("splitByLetter.letter"), str_format (localize ("authorword", count ($this->entryArray)), count ($this->entryArray)), $this->idGet);
686 1
    }
687
}
688
689
class PageAuthorDetail extends Page
690
{
691 7
    public function InitializeContent ()
692
    {
693 7
        $author = Author::getAuthorById ($this->idGet);
694 7
        $this->idPage = $author->getEntryId ();
695 7
        $this->title = $author->name;
696 7
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByAuthor ($this->idGet, $this->n);
697 7
    }
698
}
699
700
class PageAllPublishers extends Page
701
{
702 2
    public function InitializeContent ()
703
    {
704 2
        $this->title = localize("publishers.title");
705 2
        $this->entryArray = Publisher::getAllPublishers();
706 2
        $this->idPage = Publisher::ALL_PUBLISHERS_ID;
707 2
    }
708
}
709
710
class PagePublisherDetail extends Page
711
{
712 1
    public function InitializeContent ()
713
    {
714 1
        $publisher = Publisher::getPublisherById ($this->idGet);
715 1
        $this->title = $publisher->name;
716 1
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByPublisher ($this->idGet, $this->n);
717 1
        $this->idPage = $publisher->getEntryId ();
718 1
    }
719
}
720
721
class PageAllTags extends Page
722
{
723 2
    public function InitializeContent ()
724
    {
725 2
        $this->title = localize("tags.title");
726 2
        $this->entryArray = Tag::getAllTags();
727 2
        $this->idPage = Tag::ALL_TAGS_ID;
728 2
    }
729
}
730
731
class PageAllLanguages extends Page
732
{
733 2
    public function InitializeContent ()
734
    {
735 2
        $this->title = localize("languages.title");
736 2
        $this->entryArray = Language::getAllLanguages();
737 2
        $this->idPage = Language::ALL_LANGUAGES_ID;
738 2
    }
739
}
740
741
class PageCustomDetail extends Page
742
{
743 3
    public function InitializeContent ()
744
    {
745 3
        $customId = getURLParam ("custom", NULL);
746 3
        $custom = CustomColumn::getCustomById ($customId, $this->idGet);
747 3
        $this->idPage = $custom->getEntryId ();
748 3
        $this->title = $custom->name;
749 3
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByCustom ($customId, $this->idGet, $this->n);
750 3
    }
751
}
752
753
class PageAllCustoms extends Page
754
{
755 3
    public function InitializeContent ()
756
    {
757 3
        $customId = getURLParam ("custom", NULL);
758 3
        $this->title = CustomColumn::getAllTitle ($customId);
759 3
        $this->entryArray = CustomColumn::getAllCustoms($customId);
760 3
        $this->idPage = CustomColumn::getAllCustomsId ($customId);
761 3
    }
762
}
763
764
class PageTagDetail extends Page
765
{
766 1
    public function InitializeContent ()
767
    {
768 1
        $tag = Tag::getTagById ($this->idGet);
769 1
        $this->idPage = $tag->getEntryId ();
770 1
        $this->title = $tag->name;
771 1
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByTag ($this->idGet, $this->n);
772 1
    }
773
}
774
775
class PageLanguageDetail extends Page
776
{
777 1
    public function InitializeContent ()
778
    {
779 1
        $language = Language::getLanguageById ($this->idGet);
780 1
        $this->idPage = $language->getEntryId ();
781 1
        $this->title = $language->lang_code;
782 1
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByLanguage ($this->idGet, $this->n);
783 1
    }
784
}
785
786
class PageAllSeries extends Page
787
{
788 2
    public function InitializeContent ()
789
    {
790 2
        $this->title = localize("series.title");
791 2
        $this->entryArray = Serie::getAllSeries();
792 2
        $this->idPage = Serie::ALL_SERIES_ID;
793 2
    }
794
}
795
796
class PageSerieDetail extends Page
797
{
798 1
    public function InitializeContent ()
799
    {
800 1
        $serie = Serie::getSerieById ($this->idGet);
801 1
        $this->title = $serie->name;
802 1
        list ($this->entryArray, $this->totalNumber) = Book::getBooksBySeries ($this->idGet, $this->n);
803 1
        $this->idPage = $serie->getEntryId ();
804 1
    }
805
}
806
807
class PageAllRating extends Page
808
{
809 1
    public function InitializeContent ()
810
    {
811 1
        $this->title = localize("ratings.title");
812 1
        $this->entryArray = Rating::getAllRatings();
813 1
        $this->idPage = Rating::ALL_RATING_ID;
814 1
    }
815
}
816
817
class PageRatingDetail extends Page
818
{
819 1
    public function InitializeContent ()
820
    {
821 1
        $rating = Rating::getRatingById ($this->idGet);
822 1
        $this->idPage = $rating->getEntryId ();
823 1
        $this->title =str_format (localize ("ratingword", $rating->name/2), $rating->name/2);
824 1
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByRating ($this->idGet, $this->n);
825 1
    }
826
}
827
828
class PageAllBooks extends Page
829
{
830 3
    public function InitializeContent ()
831
    {
832 3
        $this->title = localize ("allbooks.title");
833 3
        if (getCurrentOption ("titles_split_first_letter") == 1) {
834 2
            $this->entryArray = Book::getAllBooks();
835 2
        }
836
        else {
837 1
            list ($this->entryArray, $this->totalNumber) = Book::getBooks ($this->n);
838
        }
839 3
        $this->idPage = Book::ALL_BOOKS_ID;
840 3
    }
841
}
842
843
class PageAllBooksLetter extends Page
844
{
845 1
    public function InitializeContent ()
846
    {
847 1
        list ($this->entryArray, $this->totalNumber) = Book::getBooksByStartingLetter ($this->idGet, $this->n);
848 1
        $this->idPage = Book::getEntryIdByLetter ($this->idGet);
849
850 1
        $count = $this->totalNumber;
851 1
        if ($count == -1)
852 1
            $count = count ($this->entryArray);
853
854 1
        $this->title = str_format (localize ("splitByLetter.letter"), str_format (localize ("bookword", $count), $count), $this->idGet);
855 1
    }
856
}
857
858
class PageRecentBooks extends Page
859
{
860 4
    public function InitializeContent ()
861
    {
862 4
        $this->title = localize ("recent.title");
863 4
        $this->entryArray = Book::getAllRecentBooks ();
864 4
        $this->idPage = Book::ALL_RECENT_BOOKS_ID;
865 4
    }
866
}
867
868
class PageQueryResult extends Page
869
{
870
    const SCOPE_TAG = "tag";
871
    const SCOPE_RATING = "rating";
872
    const SCOPE_SERIES = "series";
873
    const SCOPE_AUTHOR = "author";
874
    const SCOPE_BOOK = "book";
875
    const SCOPE_PUBLISHER = "publisher";
876
877 24
    private function useTypeahead () {
878 24
        return !is_null (getURLParam ("search"));
879
    }
880
881 29
    private function searchByScope ($scope, $limit = FALSE) {
882 29
        $n = $this->n;
883 29
        $numberPerPage = NULL;
884 29
        $queryNormedAndUp = $this->query;
885 29
        if (useNormAndUp ()) {
886 7
            $queryNormedAndUp = normAndUp ($this->query);
887 7
        }
888 29
        if ($limit) {
889 22
            $n = 1;
890 22
            $numberPerPage = 5;
891 22
        }
892
        switch ($scope) {
893 29
            case self::SCOPE_BOOK :
894 23
                $array = Book::getBooksByStartingLetter ('%' . $queryNormedAndUp, $n, NULL, $numberPerPage);
895 23
                break;
896 28
            case self::SCOPE_AUTHOR :
897 23
                $array = Author::getAuthorsForSearch ('%' . $queryNormedAndUp);
898 23
                break;
899 25
            case self::SCOPE_SERIES :
900 22
                $array = Serie::getAllSeriesByQuery ($queryNormedAndUp);
901 22
                break;
902 24
            case self::SCOPE_TAG :
903 23
                $array = Tag::getAllTagsByQuery ($queryNormedAndUp, $n, NULL, $numberPerPage);
904 23
                break;
905 23
            case self::SCOPE_PUBLISHER :
906 23
                $array = Publisher::getAllPublishersByQuery ($queryNormedAndUp);
907 23
                break;
908
            default:
909
                $array = Book::getBooksByQuery (
910
                    array ("all" => "%" . $queryNormedAndUp . "%"), $n);
911
        }
912
913 29
        return $array;
914
    }
915
916 22
    public function doSearchByCategory () {
917 22
        $database = GetUrlParam (DB);
918 22
        $out = array ();
919 22
        $pagequery = Base::PAGE_OPENSEARCH_QUERY;
920 22
        $dbArray = array ("");
921 22
        $d = $database;
922 22
        $query = $this->query;
923
        // Special case when no databases were chosen, we search on all databases
924 22
        if (Base::noDatabaseSelected ()) {
925 1
            $dbArray = Base::getDbNameList ();
926 1
            $d = 0;
927 1
        }
928 22
        foreach ($dbArray as $key) {
929 22
            if (Base::noDatabaseSelected ()) {
930 1
                array_push ($this->entryArray, new Entry ($key, DB . ":query:{$d}",
931 1
                                        " ", "text",
932 1
                                        array ( new LinkNavigation ("?" . DB . "={$d}")), "tt-header"));
933 1
                Base::getDb ($d);
934 1
            }
935 22
            foreach (array (PageQueryResult::SCOPE_BOOK,
936 22
                            PageQueryResult::SCOPE_AUTHOR,
937 22
                            PageQueryResult::SCOPE_SERIES,
938 22
                            PageQueryResult::SCOPE_TAG,
939 22
                            PageQueryResult::SCOPE_PUBLISHER) as $key) {
940 22
                if (in_array($key, getCurrentOption ('ignored_categories'))) {
941 3
                    continue;
942
                }
943 22
                $array = $this->searchByScope ($key, TRUE);
944
945 22
                $i = 0;
946 22
                if (count ($array) == 2 && is_array ($array [0])) {
947 22
                    $total = $array [1];
948 22
                    $array = $array [0];
949 22
                } else {
950 22
                    $total = count($array);
951
                }
952 22
                if ($total > 0) {
953
                    // Comment to help the perl i18n script
954
                    // str_format (localize("bookword", count($array))
955
                    // str_format (localize("authorword", count($array))
956
                    // str_format (localize("seriesword", count($array))
957
                    // str_format (localize("tagword", count($array))
958
                    // str_format (localize("publisherword", count($array))
959 21
                    array_push ($this->entryArray, new Entry (str_format (localize ("search.result.{$key}"), $this->query), DB . ":query:{$d}:{$key}",
960 21
                                        str_format (localize("{$key}word", $total), $total), "text",
961 21
                                        array ( new LinkNavigation ("?page={$pagequery}&query={$query}&db={$d}&scope={$key}")),
962 21
                                        Base::noDatabaseSelected () ? "" : "tt-header", $total));
963 21
                }
964 22
                if (!Base::noDatabaseSelected () && $this->useTypeahead ()) {
965 6
                    foreach ($array as $entry) {
966 6
                        array_push ($this->entryArray, $entry);
967 6
                        $i++;
968 6
                        if ($i > 4) { break; };
969 6
                    }
970 6
                }
971 22
            }
972 22
            $d++;
973 22
            if (Base::noDatabaseSelected ()) {
974 1
                Base::clearDb ();
975 1
            }
976 22
        }
977 22
        return $out;
978
    }
979
980 31
    public function InitializeContent ()
981
    {
982 31
        $scope = getURLParam ("scope");
983 31
        if (empty ($scope)) {
984 24
            $this->title = str_format (localize ("search.result"), $this->query);
985 24
        } else {
986
            // Comment to help the perl i18n script
987
            // str_format (localize ("search.result.author"), $this->query)
988
            // str_format (localize ("search.result.tag"), $this->query)
989
            // str_format (localize ("search.result.series"), $this->query)
990
            // str_format (localize ("search.result.book"), $this->query)
991
            // str_format (localize ("search.result.publisher"), $this->query)
992 7
            $this->title = str_format (localize ("search.result.{$scope}"), $this->query);
993
        }
994
995 31
        $crit = "%" . $this->query . "%";
996
997
        // Special case when we are doing a search and no database is selected
998 31
        if (Base::noDatabaseSelected () && !$this->useTypeahead ()) {
999 2
            $i = 0;
1000 2
            foreach (Base::getDbNameList () as $key) {
1001 2
                Base::clearDb ();
1002 2
                list ($array, $totalNumber) = Book::getBooksByQuery (array ("all" => $crit), 1, $i, 1);
0 ignored issues
show
The assignment to $array is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
1003 2
                array_push ($this->entryArray, new Entry ($key, DB . ":query:{$i}",
1004 2
                                        str_format (localize ("bookword", $totalNumber), $totalNumber), "text",
1005 2
                                        array ( new LinkNavigation ("?" . DB . "={$i}&page=9&query=" . $this->query)), "", $totalNumber));
1006 2
                $i++;
1007 2
            }
1008 2
            return;
1009
        }
1010 29
        if (empty ($scope)) {
1011 22
            $this->doSearchByCategory ();
1012 22
            return;
1013
        }
1014
1015 7
        $array = $this->searchByScope ($scope);
1016 7
        if (count ($array) == 2 && is_array ($array [0])) {
1017 2
            list ($this->entryArray, $this->totalNumber) = $array;
1018 2
        } else {
1019 5
            $this->entryArray = $array;
1020
        }
1021 7
    }
1022
}
1023
1024
class PageBookDetail extends Page
1025
{
1026 1
    public function InitializeContent ()
1027
    {
1028 1
        $this->book = Book::getBookById ($this->idGet);
1029 1
        $this->title = $this->book->title;
1030 1
    }
1031
}
1032
1033
class PageAbout extends Page
1034
{
1035
    public function InitializeContent ()
1036
    {
1037
        $this->title = localize ("about.title");
1038
    }
1039
}
1040
1041
class PageCustomize extends Page
1042
{
1043
    private function isChecked ($key, $testedValue = 1) {
1044
        $value = getCurrentOption ($key);
1045
        if (is_array ($value)) {
1046
            if (in_array ($testedValue, $value)) {
1047
                return "checked='checked'";
1048
            }
1049
        } else {
1050
            if ($value == $testedValue) {
1051
                return "checked='checked'";
1052
            }
1053
        }
1054
        return "";
1055
    }
1056
1057
    private function isSelected ($key, $value) {
1058
        if (getCurrentOption ($key) == $value) {
1059
            return "selected='selected'";
1060
        }
1061
        return "";
1062
    }
1063
1064
    private function getStyleList () {
1065
        $result = array ();
1066
        foreach (glob ("templates/" . getCurrentTemplate () . "/styles/style-*.css") as $filename) {
1067
            if (preg_match ('/styles\/style-(.*?)\.css/', $filename, $m)) {
1068
                array_push ($result, $m [1]);
1069
            }
1070
        }
1071
        return $result;
1072
    }
1073
1074
    public function InitializeContent ()
1075
    {
1076
        $this->title = localize ("customize.title");
1077
        $this->entryArray = array ();
1078
1079
        $ignoredBaseArray = array (PageQueryResult::SCOPE_AUTHOR,
1080
                                   PageQueryResult::SCOPE_TAG,
1081
                                   PageQueryResult::SCOPE_SERIES,
1082
                                   PageQueryResult::SCOPE_PUBLISHER,
1083
                                   PageQueryResult::SCOPE_RATING,
1084
                                   "language");
1085
1086
        $content = "";
1087
        array_push ($this->entryArray, new Entry ("Template", "",
1088
                                        "<span style='cursor: pointer;' onclick='$.cookie(\"template\", \"bootstrap\", { expires: 365 });window.location=$(\".headleft\").attr(\"href\");'>Click to switch to Bootstrap</span>", "text",
1089
                                        array ()));
1090
        if (!preg_match("/(Kobo|Kindle\/3.0|EBRD1101)/", $_SERVER['HTTP_USER_AGENT'])) {
1091
            $content .= '<select id="style" onchange="updateCookie (this);">';
1092
            foreach ($this-> getStyleList () as $filename) {
1093
                $content .= "<option value='{$filename}' " . $this->isSelected ("style", $filename) . ">{$filename}</option>";
1094
            }
1095
            $content .= '</select>';
1096
        } else {
1097
            foreach ($this-> getStyleList () as $filename) {
1098
                $content .= "<input type='radio' onchange='updateCookieFromCheckbox (this);' id='style-{$filename}' name='style' value='{$filename}' " . $this->isChecked ("style", $filename) . " /><label for='style-{$filename}'> {$filename} </label>";
1099
            }
1100
        }
1101
        array_push ($this->entryArray, new Entry (localize ("customize.style"), "",
1102
                                        $content, "text",
1103
                                        array ()));
1104
        if (!useServerSideRendering ()) {
1105
            $content = '<input type="checkbox" onchange="updateCookieFromCheckbox (this);" id="use_fancyapps" ' . $this->isChecked ("use_fancyapps") . ' />';
1106
            array_push ($this->entryArray, new Entry (localize ("customize.fancybox"), "",
1107
                                            $content, "text",
1108
                                            array ()));
1109
        }
1110
        $content = '<input type="number" onchange="updateCookie (this);" id="max_item_per_page" value="' . getCurrentOption ("max_item_per_page") . '" min="-1" max="1200" pattern="^[-+]?[0-9]+$" />';
1111
        array_push ($this->entryArray, new Entry (localize ("customize.paging"), "",
1112
                                        $content, "text",
1113
                                        array ()));
1114
        $content = '<input type="text" onchange="updateCookie (this);" id="email" value="' . getCurrentOption ("email") . '" />';
1115
        array_push ($this->entryArray, new Entry (localize ("customize.email"), "",
1116
                                        $content, "text",
1117
                                        array ()));
1118
        $content = '<input type="checkbox" onchange="updateCookieFromCheckbox (this);" id="html_tag_filter" ' . $this->isChecked ("html_tag_filter") . ' />';
1119
        array_push ($this->entryArray, new Entry (localize ("customize.filter"), "",
1120
                                        $content, "text",
1121
                                        array ()));
1122
        $content = "";
1123
        foreach ($ignoredBaseArray as $key) {
1124
            $keyPlural = preg_replace ('/(ss)$/', 's', $key . "s");
1125
            $content .=  '<input type="checkbox" name="ignored_categories[]" onchange="updateCookieFromCheckboxGroup (this);" id="ignored_categories_' . $key . '" ' . $this->isChecked ("ignored_categories", $key) . ' > ' . localize ("{$keyPlural}.title") . '</input> ';
1126
        }
1127
1128
        array_push ($this->entryArray, new Entry (localize ("customize.ignored"), "",
1129
                                        $content, "text",
1130
                                        array ()));
1131
    }
1132
}
1133
1134
1135
abstract class Base
1136
{
1137
    const PAGE_INDEX = "index";
1138
    const PAGE_ALL_AUTHORS = "1";
1139
    const PAGE_AUTHORS_FIRST_LETTER = "2";
1140
    const PAGE_AUTHOR_DETAIL = "3";
1141
    const PAGE_ALL_BOOKS = "4";
1142
    const PAGE_ALL_BOOKS_LETTER = "5";
1143
    const PAGE_ALL_SERIES = "6";
1144
    const PAGE_SERIE_DETAIL = "7";
1145
    const PAGE_OPENSEARCH = "8";
1146
    const PAGE_OPENSEARCH_QUERY = "9";
1147
    const PAGE_ALL_RECENT_BOOKS = "10";
1148
    const PAGE_ALL_TAGS = "11";
1149
    const PAGE_TAG_DETAIL = "12";
1150
    const PAGE_BOOK_DETAIL = "13";
1151
    const PAGE_ALL_CUSTOMS = "14";
1152
    const PAGE_CUSTOM_DETAIL = "15";
1153
    const PAGE_ABOUT = "16";
1154
    const PAGE_ALL_LANGUAGES = "17";
1155
    const PAGE_LANGUAGE_DETAIL = "18";
1156
    const PAGE_CUSTOMIZE = "19";
1157
    const PAGE_ALL_PUBLISHERS = "20";
1158
    const PAGE_PUBLISHER_DETAIL = "21";
1159
    const PAGE_ALL_RATINGS = "22";
1160
    const PAGE_RATING_DETAIL = "23";
1161
1162
    const COMPATIBILITY_XML_ALDIKO = "aldiko";
1163
1164
    private static $db = NULL;
1165
1166 108
    public static function isMultipleDatabaseEnabled () {
1167 108
        global $config;
1168 108
        return is_array ($config['calibre_directory']);
1169
    }
1170
1171 46
    public static function useAbsolutePath () {
1172 46
        global $config;
1173 46
        $path = self::getDbDirectory();
1174 46
        return preg_match ('/^\//', $path) || // Linux /
1175 46
               preg_match ('/^\w\:/', $path); // Windows X:
1176
    }
1177
1178 45
    public static function noDatabaseSelected () {
1179 45
        return self::isMultipleDatabaseEnabled () && is_null (GetUrlParam (DB));
1180
    }
1181
1182 4
    public static function getDbList () {
1183 4
        global $config;
1184 4
        if (self::isMultipleDatabaseEnabled ()) {
1185 4
            return $config['calibre_directory'];
1186
        } else {
1187 1
            return array ("" => $config['calibre_directory']);
1188
        }
1189
    }
1190
1191 5
    public static function getDbNameList () {
1192 5
        global $config;
1193 5
        if (self::isMultipleDatabaseEnabled ()) {
1194 5
            return array_keys ($config['calibre_directory']);
1195
        } else {
1196
            return array ("");
1197
        }
1198
    }
1199
1200 1
    public static function getDbName ($database = NULL) {
1201 1
        global $config;
1202 1
        if (self::isMultipleDatabaseEnabled ()) {
1203 1
            if (is_null ($database)) $database = GetUrlParam (DB, 0);
1204 1
            if (!is_null($database) && !preg_match('/^\d+$/', $database)) {
1205
                return self::error ($database);
1206
            }
1207 1
            $array = array_keys ($config['calibre_directory']);
1208 1
            return  $array[$database];
1209
        }
1210
        return "";
1211
    }
1212
1213 90
    public static function getDbDirectory ($database = NULL) {
1214 90
        global $config;
1215 90
        if (self::isMultipleDatabaseEnabled ()) {
1216 9
            if (is_null ($database)) $database = GetUrlParam (DB, 0);
1217 9
            if (!is_null($database) && !preg_match('/^\d+$/', $database)) {
1218
                return self::error ($database);
1219
            }
1220 9
            $array = array_values ($config['calibre_directory']);
1221 9
            return  $array[$database];
1222
        }
1223 81
        return $config['calibre_directory'];
1224
    }
1225
1226
1227 61
    public static function getDbFileName ($database = NULL) {
1228 61
        return self::getDbDirectory ($database) .'metadata.db';
1229
    }
1230
1231 2
    private static function error ($database) {
1232 2
        if (php_sapi_name() != "cli") {
1233
            header("location: checkconfig.php?err=1");
1234
        }
1235 2
        throw new Exception("Database <{$database}> not found.");
1236
    }
1237
1238 126
    public static function getDb ($database = NULL) {
1239 126
        if (is_null (self::$db)) {
1240
            try {
1241 61
                if (is_readable (self::getDbFileName ($database))) {
1242 60
                    self::$db = new PDO('sqlite:'. self::getDbFileName ($database));
1243 60
                    if (useNormAndUp ()) {
1244 7
                        self::$db->sqliteCreateFunction ('normAndUp', 'normAndUp', 1);
1245 7
                    }
1246 60
                } else {
1247 2
                    self::error ($database);
1248
                }
1249 61
            } catch (Exception $e) {
1250 2
                self::error ($database);
1251
            }
1252 60
        }
1253 125
        return self::$db;
1254
    }
1255
1256 4
    public static function checkDatabaseAvailability () {
1257 4
        if (self::noDatabaseSelected ()) {
1258 3
            for ($i = 0; $i < count (self::getDbList ()); $i++) {
1259 3
                self::getDb ($i);
1260 2
                self::clearDb ();
1261 2
            }
1262 1
        } else {
1263 1
            self::getDb ();
1264
        }
1265 2
        return true;
1266
    }
1267
1268 58
    public static function clearDb () {
1269 58
        self::$db = NULL;
1270 58
    }
1271
1272 13
    public static function executeQuerySingle ($query, $database = NULL) {
1273 13
        return self::getDb ($database)->query($query)->fetchColumn();
1274
    }
1275
1276 8
    public static function getCountGeneric($table, $id, $pageId, $numberOfString = NULL) {
1277 8
        if (!$numberOfString) {
1278 7
            $numberOfString = $table . ".alphabetical";
1279 7
        }
1280 8
        $count = self::executeQuerySingle ('select count(*) from ' . $table);
1281 8
        if ($count == 0) return NULL;
1282 8
        $entry = new Entry (localize($table . ".title"), $id,
1283 8
            str_format (localize($numberOfString, $count), $count), "text",
1284 8
            array ( new LinkNavigation ("?page=".$pageId)), "", $count);
1285 8
        return $entry;
1286
    }
1287
1288 35
    public static function getEntryArrayWithBookNumber ($query, $columns, $params, $category) {
1289 35
        list (, $result) = self::executeQuery ($query, $columns, "", $params, -1);
1290 35
        $entryArray = array();
1291 35
        while ($post = $result->fetchObject ())
1292
        {
1293 25
            $instance = new $category ($post);
1294 25
            if (property_exists($post, "sort")) {
1295 17
                $title = $post->sort;
1296 17
            } else {
1297 8
                $title = $post->name;
1298
            }
1299 25
            array_push ($entryArray, new Entry ($title, $instance->getEntryId (),
1300 25
                str_format (localize("bookword", $post->count), $post->count), "text",
1301 25
                array ( new LinkNavigation ($instance->getUri ())), "", $post->count));
1302 25
        }
1303 35
        return $entryArray;
1304
    }
1305
1306 73
    public static function executeQuery($query, $columns, $filter, $params, $n, $database = NULL, $numberPerPage = NULL) {
1307 73
        $totalResult = -1;
1308
1309 73
        if (useNormAndUp ()) {
1310 7
            $query = preg_replace("/upper/", "normAndUp", $query);
1311 7
            $columns = preg_replace("/upper/", "normAndUp", $columns);
1312 7
        }
1313
1314 73
        if (is_null ($numberPerPage)) {
1315 71
            $numberPerPage = getCurrentOption ("max_item_per_page");
1316 71
        }
1317
1318 73
        if ($numberPerPage != -1 && $n != -1)
1319 73
        {
1320
            // First check total number of results
1321 28
            $result = self::getDb ($database)->prepare (str_format ($query, "count(*)", $filter));
1322 28
            $result->execute ($params);
1323 28
            $totalResult = $result->fetchColumn ();
1324
1325
            // Next modify the query and params
1326 28
            $query .= " limit ?, ?";
1327 28
            array_push ($params, ($n - 1) * $numberPerPage, $numberPerPage);
1328 28
        }
1329
1330 73
        $result = self::getDb ($database)->prepare(str_format ($query, $columns, $filter));
1331 73
        $result->execute ($params);
1332 73
        return array ($totalResult, $result);
1333
    }
1334
1335
}
1336