Completed
Push — master ( c7b6c0...9c4d6d )
by Sébastien
05:36
created

epubfs.php ➔ getComponentContent()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 6
Metric Value
cc 6
eloc 25
nc 1
nop 3
dl 0
loc 34
ccs 26
cts 26
cp 1
crap 6
rs 8.439
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 ("config.php");
10
require_once ("base.php");
11
require_once ("book.php");
12
require_once ("resources/php-epub-meta/epub.php");
13
14
function getComponentContent ($book, $component, $add) {
15 7
    $data = $book->component ($component);
16
17
    $callback = function ($m) use ($book, $component, $add) {
18 7
        $method = $m[1];
19 7
        $path = $m[2];
20 7
        $end = "";
21 7
        if (preg_match ("/^src\s*:/", $method)) {
22 1
            $end = ")";
23 1
        }
24 7
        if (preg_match ("/^#/", $path)) {
25 3
            return "{$method}'{$path}'{$end}";
26
        }
27 7
        $hash = "";
28 7
        if (preg_match ("/^(.+)#(.+)$/", $path, $matches)) {
29 3
            $path = $matches [1];
30 3
            $hash = "#" . $matches [2];
31 3
        }
32 7
        $comp = $book->getComponentName ($component, $path);
33 7
        if (!$comp) return "{$method}'#'{$end}";
34 7
        $out = "{$method}'epubfs.php?{$add}comp={$comp}{$hash}'{$end}";
35 7
        if ($end) {
36 1
            return $out;
37
        }
38 7
        return str_replace ("&", "&amp;", $out);
39 7
    };
40
41 7
    $data = preg_replace_callback ("/(src=)[\"']([^:]*?)[\"']/", $callback, $data);
42 7
    $data = preg_replace_callback ("/(href=)[\"']([^:]*?)[\"']/", $callback, $data);
43 7
    $data = preg_replace_callback ("/(\@import\s+)[\"'](.*?)[\"'];/", $callback, $data);
44 7
    $data = preg_replace_callback ("/(src\s*:\s*url\()(.*?)\)/", $callback, $data);
45
46 7
    return $data;
47
}
48
49
if (php_sapi_name() === 'cli') { return; }
50
51
$idData = getURLParam ("data", NULL);
52
$add = "data=$idData&";
53
if (!is_null (GetUrlParam (DB))) $add .= DB . "=" . GetUrlParam (DB) . "&";
54
$myBook = Book::getBookByDataId($idData);
55
56
$book = new EPub ($myBook->getFilePath ("EPUB", $idData));
57
58
$book->initSpineComponent ();
59
60
if (!isset ($_GET["comp"])) {
61
    notFound ();
62
    return;
63
}
64
65
$component = $_GET["comp"];
66
67
try {
68
    $data = getComponentContent ($book, $component, $add);
69
70
    $expires = 60*60*24*14;
71
    header("Pragma: public");
72
    header("Cache-Control: maxage=".$expires);
73
    header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
74
    header ("Content-Type: " . $book->componentContentType($component));
75
    echo $data;
76
}
77
catch (Exception $e) {
78
    error_log ($e);
79
    notFound ();
80
}