示例#1
0
 /**
  * Get book metadata of contents.
  *
  * @access public
  * @return string
  */
 public function getContents()
 {
     $contents = array_map(function ($content) {
         return '{title: \'' . addslashes($content['title']) . '\', src: \'' . $content['src'] . '\'}';
     }, $this->epub->contents());
     return '[' . implode(', ', $contents) . ']';
 }
示例#2
0
<?php

error_reporting(0);
$metadatas = $this->GetMetaDatas($this->GetPageTag());
if (isset($metadatas["ebook-title"]) && isset($metadatas["ebook-description"]) && isset($metadatas["ebook-author"]) && isset($metadatas["ebook-biblio-author"]) && isset($metadatas["ebook-cover-image"])) {
    // ePub uses XHTML 1.1, preferably strict.
    $content_start = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n" . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" . "<head>" . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" . "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" />\n" . "<title>" . $metadatas["ebook-title"] . "</title>\n" . "</head>\n" . "<body>\n";
    $bookEnd = "</body>\n</html>\n";
    include_once "tools/tags/libs/tags.functions.php";
    include_once "tools/tags/libs/vendor/PHPePub/EPub.php";
    $book = new EPub();
    // Title and Identifier are mandatory!
    $book->setTitle($metadatas["ebook-title"]);
    $book->setIdentifier($this->href('', $this->getPageTag()), EPub::IDENTIFIER_URI);
    // Could also be the ISBN number, prefered for published books, or a UUID.
    $book->setLanguage($this->config["lang"]);
    // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
    $book->setDescription($metadatas["ebook-description"]);
    $book->setAuthor($metadatas["ebook-author"], $metadatas["ebook-author-biblio"]);
    $book->setPublisher($metadatas["ebook-author"], $this->href('', $this->getPageTag()));
    // I hope this is a non existant address :)
    $book->setDate(time());
    // Strictly not needed as the book date defaults to time().
    $book->setRights(_t('TAGS_PUBLISHED_UNDER_CREATIVE_COMMONS_BY_SA'));
    // As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
    $book->setSourceURL($this->href('', $this->getPageTag()));
    // on concatene tous les styles dans un css
    $styles = $this->Format("{{linkstyle}}");
    preg_match_all('/href="(.*css)"/U', $styles, $matches);
    $cssData = '';
    foreach ($matches[1] as $key => $value) {
error_reporting(E_ALL | E_STRICT);
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 1);
// Example.
// Create a test book for download.
// ePub uses XHTML 1.1, preferably strict.
$content_start = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n" . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" . "<head>" . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" . "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" />\n" . "<title>Test Book</title>\n" . "</head>\n" . "<body>\n";
$bookEnd = "</body>\n</html>\n";
// setting timezone for time functions used for logging to work properly
date_default_timezone_set('Europe/Berlin');
include_once "Logger.php";
$log = new Logger("Example", TRUE);
$fileDir = './PHPePub';
include_once "EPub.php";
$log->logLine("include EPub");
$book = new EPub();
// Default is EPub::BOOK_VERSION_EPUB2
$log->logLine("new EPub()");
$log->logLine("EPub class version: " . EPub::VERSION);
$log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION);
$log->logLine("Zip version: " . Zip::VERSION);
$log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL());
$log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL());
// Title and Identifier are mandatory!
$book->setTitle("Test book");
$book->setIdentifier("http://JohnJaneDoePublications.com/books/TestBook.html", EPub::IDENTIFIER_URI);
// Could also be the ISBN number, prefered for published books, or a UUID.
$book->setLanguage("en");
// Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
$book->setDescription("This is a brief description\nA test ePub book as an example of building a book in PHP");
$book->setAuthor("John Doe Johnson", "Johnson, John Doe");
示例#4
0
     }
     $pdf->addTOCPage();
     $pdf->SetFont('helvetica', 'B', 16);
     $pdf->MultiCell(0, 0, 'Table Of Contents', 0, 'C', 0, 1, '', '', true, 0);
     $pdf->Ln();
     $pdf->SetFont('helvetica', '', 12);
     $pdf->addTOC(2, 'helvetica', '.', 'TOC', 'B', array(0, 0, 0));
     $pdf->endTOCPage();
     $pdf->Output("./tmp/" . $filename, 'F');
     if (!empty($email)) {
         mailAttachment($filename, "./tmp/", $email, $uniqid);
     }
 } else {
     if ($format == "epub") {
         require_once "epub/EPub.php";
         $book = new EPub();
         $book->setTitle($story["title"]);
         $book->setIdentifier($story["story_url"], EPub::IDENTIFIER_URI);
         $book->setDescription($story["desc"]);
         $book->setAuthor($story["author"], "");
         $book->setPublisher("FanFiction.net", "https://www.fanfiction.net/");
         $book->setSourceURL($story["story_url"]);
         //$book->setCoverImage("Cover.jpg", getImagePath($story_id), "image/jpeg");
         $cover = $content_start . "<div class='coverPage'><h1>{$story["title"]}</h1>\n<h2>by: {$story["author"]}</h2></div>" . $bookEnd;
         $book->addChapter($story["title"], "Cover.html", $cover);
         $book->buildTOC();
         for ($i = 0; $i < $numChapter; $i++) {
             $title = isset($story["chapters"]["title"][$i]) ? $story["chapters"]["title"][$i] : "";
             $content = isset($story["chapters"]["content"][$i]) ? $story["chapters"]["content"][$i] : "";
             if (!empty($content) && !empty($title)) {
                 $title = formatTitle($title, $i);
示例#5
0
文件: book.php 项目: ha-y/cops
 public function getUpdatedEpub($idData)
 {
     global $config;
     $data = $this->getDataById($idData);
     try {
         $epub = new EPub($data->getLocalPath());
         $epub->Title($this->title);
         $authorArray = array();
         foreach ($this->getAuthors() as $author) {
             $authorArray[$author->sort] = $author->name;
         }
         $epub->Authors($authorArray);
         $epub->Language($this->getLanguages());
         $epub->Description($this->getComment(false));
         $epub->Subjects($this->getTagsName());
         $epub->Cover2($this->getFilePath("jpg"), "image/jpeg");
         $epub->Calibre($this->uuid);
         $se = $this->getSerie();
         if (!is_null($se)) {
             $epub->Serie($se->name);
             $epub->SerieIndex($this->seriesIndex);
         }
         if ($config['cops_provide_kepub'] == "1" && preg_match("/Kobo/", $_SERVER['HTTP_USER_AGENT'])) {
             $epub->updateForKepub();
         }
         $epub->download($data->getUpdatedFilenameEpub());
     } catch (Exception $e) {
         echo "Exception : " . $e->getMessage();
     }
 }
示例#6
0
文件: epubfs.php 项目: BreizhCat/cops
    $data = preg_replace_callback("/(src=)[\"']([^:]*?)[\"']/", $callback, $data);
    $data = preg_replace_callback("/(href=)[\"']([^:]*?)[\"']/", $callback, $data);
    $data = preg_replace_callback("/(\\@import\\s+)[\"'](.*?)[\"'];/", $callback, $data);
    $data = preg_replace_callback("/(src\\s*:\\s*url\\()(.*?)\\)/", $callback, $data);
    return $data;
}
if (php_sapi_name() === 'cli') {
    return;
}
$idData = getURLParam("data", NULL);
$add = "data={$idData}&";
if (!is_null(GetUrlParam(DB))) {
    $add .= DB . "=" . GetUrlParam(DB) . "&";
}
$myBook = Book::getBookByDataId($idData);
$book = new EPub($myBook->getFilePath("EPUB", $idData));
$book->initSpineComponent();
if (!isset($_GET["comp"])) {
    notFound();
    return;
}
$component = $_GET["comp"];
try {
    $data = getComponentContent($book, $component, $add);
    $expires = 60 * 60 * 24 * 14;
    header("Pragma: public");
    header("Cache-Control: maxage=" . $expires);
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
    header("Content-Type: " . $book->componentContentType($component));
    echo $data;
} catch (Exception $e) {
 /**
  * Create an EPUB and export to defined path
  * @param $dir str directory of the source file to convert
  * @param $src str filename of the source file to convert
  * @param $path str path to export the resultant EPUB to
  * @param $chapters array chapters to convert into a single EPUB
  * @param $journalId int Id of the journal(imprint)
  * @param $args array arguments for the conversion (e.g. Description, cover image, etc)
  */
 function createEpub($dir = null, $src, $path, $chapters = array(), $journalId, $args = array())
 {
     $book = new EPub();
     if (isset($args['title'])) {
         $book->setTitle($args['title']);
     } else {
         $book->setTitle("No Title");
     }
     $book->setLanguage("en");
     $book->setPublisher(Config::getVar('general', 'base_url'), Config::getVar('general', 'base_url'));
     $book->setDate(time());
     $book->setRights("Copyright and licence information specific for the book.");
     //TODO: import specific copyright/licence information
     $book->setSourceURL(Config::getVar('general', 'base_url'));
     $CBPPlatformDao =& DAORegistry::getDAO('CBPPlatformDAO');
     $imprintType = $CBPPlatformDao->getImprintType($journalId);
     $stylesheet = $CBPPlatformDao->getImprintStylesheet($journalId);
     $book->addCSSFile("styles.css", "css1", file_get_contents($this->stylesheetDir . "{$stylesheet}.css"));
     isset($args['description']) ? $book->setDescription($args['description']) : $book->setDescription("No description");
     isset($args['author']) ? $book->setAuthor($args['author'], $args['author']) : $book->setAuthor("No author", "No author");
     $args['isbn'] != null ? $book->setIdentifier($args['isbn'], EPub::IDENTIFIER_URI) : $book->setIdentifier(Config::getVar('general', 'base_url'), EPub::IDENTIFIER_URI);
     if (isset($args['cover'])) {
         $cover = $args['cover'];
         $coverSrc = "\n\t\t\t\t\t<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='100%' height='100%' viewBox='0 0 410 597' preserveAspectRatio='xMidYMid meet'>\n\t\t\t\t\t\t<image width='410' height='597' xlink:href='images/Cover.jpg' />\n\t\t\t\t\t</svg>";
         $book->addChapter("Cover Page", "Cover.html", $this->contentStart . "{$coverSrc}</body>\n</html>\n", false, EPub::EXTERNAL_REF_ADD, $this->fileDir);
         $book->setCoverImage("Cover.jpg", file_get_contents($args['cover']));
     } else {
         $book->addChapter("Cover Page", "Cover.html", $this->contentStart . "<h1>" . $book->getTitle() . "</h1><h3>" . $book->getAuthor() . "</h3></body>\n</html>\n", false, EPub::EXTERNAL_REF_ADD, $this->fileDir);
     }
     $copyrightStatement = $CBPPlatformDao->getJournalCopyrightStatement($journalId);
     if (!empty($copyrightStatement)) {
         $copyrightStatement = reset($copyrightStatement);
         $copyrightStatement = "<div style='width: 75%; text-align: center; margin: 0 auto;'><p>" . $copyrightStatement . "</p></div>";
         $book->addChapter("Copyright Notice", "notice.html", $this->contentStart . $copyrightStatement, false, EPub::EXTERNAL_REF_ADD, $this->fileDir);
     }
     if (!empty($chapters)) {
         $chapterCount = 0;
         foreach ($chapters as $chapter) {
             if (!isset($chapter['type']) && $chapter['type'] != "supp") {
                 $chapterCount++;
             } else {
                 $suppChapters = true;
             }
         }
         for ($i = 0; $i < count($chapters); $i++) {
             $document = new TransformDoc();
             $document->setStrFile($chapters[$i]['src'], $chapters[$i]['dir']);
             $document->generateXHTML();
             //problem, here
             $document->validatorXHTML();
             $contentPreg = $this->stripTags($document->getStrXHTML());
             if ($chapterCount == 1) {
                 $splitter = new EPubChapterSplitter();
                 $xhtml = $this->contentStart . $contentPreg . "</body></html>";
                 $html2 = $splitter->splitChapter($xhtml, true, '@<h1[^>]*?.*?</h1>@siu');
                 /* '#^<.+?>Chapter \d*#i'); */
                 foreach ($html2 as $key => $value) {
                     $cTitles[] = $key;
                     $cContent[] = $value;
                 }
                 for ($i = 0; $i < count($cContent); $i++) {
                     $html3[$cTitles[$i]] = $cContent[$i];
                 }
                 $idx = 0;
                 if (!empty($html3)) {
                     foreach ($html3 as $k => $v) {
                         $idx++;
                         $cName = preg_replace('#<br.+?>#i', " - ", $k);
                         // Remove any other tags
                         $cName = preg_replace('/<[^>]*>/', '', $cName);
                         // clean the chapter name by removing any double spaces left behind to single space.
                         $cName = preg_replace('#\\s+#i', " ", $cName);
                         $book->addChapter($cName, "Chapter" . $idx . ".html", $v, false, EPub::EXTERNAL_REF_ADD, $fileDir);
                     }
                 }
                 if ($suppChapters == true) {
                     $i = 0;
                     foreach ($chapters as $chapter) {
                         if (isset($chapter['type']) && $chapter['type'] == "supp") {
                             $document = new TransformDoc();
                             $document->setStrFile($chapter['src'], $chapter['dir']);
                             $document->generateXHTML();
                             $document->validatorXHTML();
                             $contentPreg = $this->stripTags($document->getStrXHTML());
                             $book->addChapter($chapter['name'], "Chapter{$i}.html", $this->contentStart . $contentPreg . "</body></html>", false, EPub::EXTERNAL_REF_ADD, $this->fileDir);
                         }
                     }
                     $i++;
                 }
                 break;
             } else {
                 if ($imprintType == "atomistic") {
                     $book->addChapter($cName, "Chapter" . $i . ".html", $this->contentStart . $contentPreg . "</body></html>", false, EPub::EXTERNAL_REF_ADD, $fileDir);
                 } elseif ($imprintType == "collection") {
                     if ($chapters[$i]['description'] != "") {
                         $book->addChapter("Introduction to " . $chapters[$i]['name'] . " by " . $chapters[$i]['author'], "Chapter" . "{$i}-I" . ".html", $this->contentStart . "<div class='submissionIntroEpub'><h1>" . $chapters[$i]['author'] . "</h1>" . $this->stripTags($chapters[$i]['description'], true) . "</div></body></html>", false, EPub::EXTERNAL_REF_ADD, $fileDir, false);
                     }
                     $book->addChapter($chapters[$i]['name'] . " by " . $chapters[$i]['author'], "Chapter" . $i . ".html", $this->contentStart . "{$contentPreg}</body></html>", false, EPub::EXTERNAL_REF_ADD, $fileDir);
                 }
             }
         }
     } else {
         $content = new TransformDoc();
         $splitter = new EPubChapterSplitter();
         $content->setStrFile($src, $dir);
         $content->generateXHTML();
         $content->validatorXHTML();
         $contentPreg = $this->stripTags($content->getStrXHTML());
         $xhtml = $this->contentStart . $contentPreg . "</body></html>";
         $html2 = $splitter->splitChapter($xhtml, true, '@<h1[^>]*?.*?</h1>@siu');
         foreach ($html2 as $key => $value) {
             $cTitles[] = $key;
             $cContent[] = $value;
         }
         array_shift($cContent);
         for ($i = 0; $i < count($cContent); $i++) {
             $html3[$cTitles[$i]] = $cContent[$i];
         }
         $idx = 0;
         if (!empty($html3)) {
             foreach ($html3 as $k => $v) {
                 $idx++;
                 $cName = preg_replace('#<br.+?>#i', " - ", $k);
                 // Remove any other tags
                 $cName = preg_replace('/<[^>]*>/', '', $cName);
                 //clean the chapter name by removing any double spaces left behind to single space.
                 $cName = preg_replace('#\\s+#i', " ", $cName);
                 $book->addChapter($cName, "Chapter" . $idx . ".html", $v, false, EPub::EXTERNAL_REF_ADD, $fileDir);
             }
         } else {
             $book->addChapter("Body Text", "Chapter1.html", $xhtml, false, EPub::EXTERNAL_REF_ADD, $fileDir);
         }
     }
     $book->finalize();
     $zipData = $book->getBook();
     file_put_contents($path, $zipData);
 }
示例#8
0
 /**
  * Loads book infos from an epub file
  *
  * @param string Epub full file name
  * @throws Exception if error
  *
  * @return void
  */
 public function LoadFromEpub($inFileName)
 {
     // Load the epub file
     $ePub = new EPub($inFileName, 'ZipFile');
     // Get the epub infos
     $this->mFormat = 'epub';
     $this->mPath = pathinfo($inFileName, PATHINFO_DIRNAME);
     $this->mName = pathinfo($inFileName, PATHINFO_FILENAME);
     $this->mUuid = $ePub->Uuid();
     $this->mUri = $ePub->Uri();
     $this->mTitle = $ePub->Title();
     $this->mAuthors = $ePub->Authors();
     $this->mLanguage = $ePub->Language();
     $this->mDescription = $ePub->Description();
     $this->mSubjects = $ePub->Subjects();
     $cover = $ePub->Cover();
     $this->mCover = $cover['found'] !== false ? $cover['found'] : '';
     $this->mIsbn = $ePub->ISBN();
     $this->mRights = $ePub->Copyright();
     $this->mPublisher = $ePub->Publisher();
     $this->mSerie = $ePub->Serie();
     $this->mSerieIndex = $ePub->SerieIndex();
     $this->mCreationDate = $ePub->CreationDate();
     $this->mModificationDate = $ePub->ModificationDate();
 }
<?php

// Example.
// Create a test book for download.
$fileDir = './';
include_once "EPub.php";
$book = new EPub();
// Title and Identifier are mandatory!
$book->setTitle("Test book");
$book->setIdentifier("http://JohnJaneDoePublications.com/books/TestBook.html", EPub::IDENTIFIER_URI);
// Could also be the ISBN number, prefered for published books, or a UUID.
$book->setLanguage("en");
// Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
$book->setDescription("This is a brief description\nA test ePub book as an example of building a book in PHP");
$book->setAuthor("John Doe Johnson", "Johnson, John Doe");
$book->setPublisher("John and Jane Doe Publications", "http://JohnJaneDoePublications.com/");
// I hope this is a non existant address :)
$book->setDate(time());
// Strictly not needed as the book date defaults to time().
$book->setRights("Copyright and licence information specific for the book.");
// As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
$book->setSourceURL("http://JohnJaneDoePublications.com/books/TestBook.html");
$cssData = "body {\n  margin-left: .5em;\n  margin-right: .5em;\n  text-align: justify;\n}\n\np {\n  font-family: serif;\n  font-size: 10pt;\n  text-align: justify;\n  text-indent: 1em;\n  margin-top: 0px;\n  margin-bottom: 1ex;\n}\n\nh1, h2 {\n  font-family: sans-serif;\n  font-style: italic;\n  text-align: center;\n  background-color: #6b879c;\n  color: white;\n  width: 100%;\n}\n\nh1 {\n    margin-bottom: 2px;\n}\n\nh2 {\n    margin-top: -2px;\n    margin-bottom: 2px;\n}\n";
$book->addCSSFile("styles.css", "css1", $cssData);
// This test requires you have an image, change "images/_cover_.jpg" to match your location.
//$book->setCoverImage("Cover.jpg", file_get_contents("images/_cover_.jpg"), "image/jpeg");
// A better way is to let EPub handle the image itself, as it may need resizing. Most Ebooks are only about 600x800
//  pixels, adding megapix images is a waste of place and spends bandwidth. setCoverImage can resize the image.
//  When using this method, the given image path must be the absolute path from the servers Document root.
$book->setCoverImage("/test/images/_cover_.jpg");
// setCoverImage can only be called once per book, but can be called at any point in the book creation.
error_reporting(E_ALL | E_STRICT);
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 1);
// Example.
// Create a test book for download.
// ePub uses XHTML 1.1, preferably strict.
// This is the minimalistic version.
// This is for the example, this is the XHTML 1.1 header
$content_start = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n" . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" . "<head>" . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" . "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" />\n" . "<title>Test Book</title>\n" . "</head>\n" . "<body>\n";
$bookEnd = "</body>\n</html>\n";
// setting timezone for time functions used for logging to work properly
date_default_timezone_set('Europe/Berlin');
$fileDir = './PHPePub';
include_once "EPub.php";
$book = new EPub();
// no argumetns gives us the default ePub 2, lang=en and dir="ltr"
// Title and Identifier are mandatory!
$book->setTitle("Simple Test book");
$book->setIdentifier("http://JohnJaneDoePublications.com/books/TestBookSimple.html", EPub::IDENTIFIER_URI);
// Could also be the ISBN number, prefered for published books, or a UUID.
$book->setLanguage("en");
// Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
$book->setDescription("This is a brief description\nA test ePub book as an example of building a book in PHP");
$book->setAuthor("John Doe Johnson", "Johnson, John Doe");
$book->setPublisher("John and Jane Doe Publications", "http://JohnJaneDoePublications.com/");
// I hope this is a non existant address :)
$book->setDate(time());
// Strictly not needed as the book date defaults to time().
$book->setRights("Copyright and licence information specific for the book.");
// As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
示例#11
0
 /**
  * handle ePub
  */
 public function produceEpub()
 {
     Tools::logm('Starting to produce ePub 3 file');
     try {
         $content_start = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n" . "<head>" . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n" . "<title>" . _("wallabag articles book") . "</title>\n" . "</head>\n" . "<body>\n";
         $bookEnd = "</body>\n</html>\n";
         $log = new Logger("wallabag", TRUE);
         $fileDir = CACHE;
         $book = new EPub(EPub::BOOK_VERSION_EPUB3, DEBUG_POCHE);
         $log->logLine("new EPub()");
         $log->logLine("EPub class version: " . EPub::VERSION);
         $log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION);
         $log->logLine("Zip version: " . Zip::VERSION);
         $log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL());
         $log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL());
         Tools::logm('Filling metadata for ePub...');
         $book->setTitle($this->bookTitle);
         $book->setIdentifier("http://{$_SERVER['HTTP_HOST']}", EPub::IDENTIFIER_URI);
         // Could also be the ISBN number, prefered for published books, or a UUID.
         //$book->setLanguage("en"); // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
         $book->setDescription(_("Some articles saved on my wallabag"));
         $book->setAuthor($this->author, $this->author);
         $book->setPublisher("wallabag", "wallabag");
         // I hope this is a non existant address :)
         $book->setDate(time());
         // Strictly not needed as the book date defaults to time().
         //$book->setRights("Copyright and licence information specific for the book."); // As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
         $book->setSourceURL("http://{$_SERVER['HTTP_HOST']}");
         $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "PHP");
         $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "wallabag");
         $cssData = "body {\n margin-left: .5em;\n margin-right: .5em;\n text-align: justify;\n}\n\np {\n font-family: serif;\n font-size: 10pt;\n text-align: justify;\n text-indent: 1em;\n margin-top: 0px;\n margin-bottom: 1ex;\n}\n\nh1, h2 {\n font-family: sans-serif;\n font-style: italic;\n text-align: center;\n background-color: #6b879c;\n color: white;\n width: 100%;\n}\n\nh1 {\n margin-bottom: 2px;\n}\n\nh2 {\n margin-top: -2px;\n margin-bottom: 2px;\n}\n";
         $log->logLine("Add Cover");
         $fullTitle = "<h1> " . $this->bookTitle . "</h1>\n";
         $book->setCoverImage("Cover.png", file_get_contents("themes/_global/img/appicon/apple-touch-icon-152.png"), "image/png", $fullTitle);
         $cover = $content_start . '<div style="text-align:center;"><p>' . _('Produced by wallabag with PHPePub') . '</p><p>' . _('Please open <a href="https://github.com/wallabag/wallabag/issues" >an issue</a> if you have trouble with the display of this E-Book on your device.') . '</p></div>' . $bookEnd;
         //$book->addChapter("Table of Contents", "TOC.xhtml", NULL, false, EPub::EXTERNAL_REF_IGNORE);
         $book->addChapter("Notices", "Cover2.html", $cover);
         $book->buildTOC();
         Tools::logm('Adding actual content...');
         foreach ($this->entries as $entry) {
             //set tags as subjects
             $tags = $this->wallabag->store->retrieveTagsByEntry($entry['id']);
             foreach ($tags as $tag) {
                 $book->setSubject($tag['value']);
             }
             $log->logLine("Set up parameters");
             $chapter = $content_start . $entry['content'] . $bookEnd;
             $book->addChapter($entry['title'], htmlspecialchars($entry['title']) . ".html", $chapter, true, EPub::EXTERNAL_REF_ADD);
             $log->logLine("Added chapter " . $entry['title']);
         }
         if (DEBUG_POCHE) {
             $book->addChapter("Log", "Log.html", $content_start . $log->getLog() . "\n</pre>" . $bookEnd);
             // log generation
             Tools::logm('Production log available in produced file');
         }
         $book->finalize();
         $zipData = $book->sendBook($this->bookFileName);
         Tools::logm('Ebook produced');
     } catch (Exception $e) {
         Tools::logm('PHPePub has encountered an error : ' . $e->getMessage());
         $this->wallabag->messages->add('e', $e->getMessage());
     }
 }
<?php

error_reporting(E_ALL | E_STRICT);
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 1);
// Example.
// Create a test book for download.
// ePub uses XHTML 1.1, preferably strict.
include_once "EPub.php";
$book = new EPub();
$book->setTitle("Test book");
$book->setIdentifier("http://JohnJaneDoePublications.com/books/TestBook.html", EPub::IDENTIFIER_URI);
// Could also be the ISBN number, prefered for published books, or a UUID.
$book->setLanguage("en");
// Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
$book->setDescription("This is a brief description\nA test ePub book as an example of building a book in PHP");
$book->setAuthor("John Doe Johnson", "Johnson, John Doe");
$book->setPublisher("John and Jane Doe Publications", "http://JohnJaneDoePublications.com/");
// I hope this is a non existant address :)
$book->setDate(time());
// Strictly not needed as the book date defaults to time().
$book->setRights("Copyright and licence information specific for the book.");
// As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
$book->setSourceURL("http://JohnJaneDoePublications.com/books/TestBook.html");
$cssData = "body {\n  margin-left: .5em;\n  margin-right: .5em;\n  text-align: justify;\n}\n\np {\n  font-family: serif;\n  font-size: 10pt;\n  text-align: justify;\n  text-indent: 1em;\n  margin-top: 0px;\n  margin-bottom: 1ex;\n}\n\nh1, h2 {\n  font-family: sans-serif;\n  font-style: italic;\n  text-align: center;\n  background-color: #6b879c;\n  color: white;\n  width: 100%;\n}\n\nh1 {\n    margin-bottom: 2px;\n}\n\nh2 {\n    margin-top: -2px;\n    margin-bottom: 2px;\n}\n";
$book->addCSSFile("Styles/styles.css", "css1", $cssData);
$content_start = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" . "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n" . "    \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" . "<head>" . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" . "<link rel=\"stylesheet\" type=\"text/css\" href=\"../Styles/styles.css\" />\n" . "<title>Test Book</title>\n" . "</head>\n" . "<body>\n";
$bookEnd = "</body>\n</html>\n";
$fileDir = './PHPePub';
// setting timezone for time functions used for logging to work properly
date_default_timezone_set('Europe/Berlin');
示例#13
0
function create_epub($title, $qry_articles, $external_content)
{
    $configManager = new Configuration();
    $configManager->getAll();
    $nbArticles = mysql_num_rows($qry_articles);
    // TODO PHP 5.5.0, remove this function to use mysqli_stmt_num_rows or PDO
    if ($nbArticles > 0) {
        // Epub initialisation
        switch ($configManager->get('epub_version')) {
            case 3:
                $book = new EPub(EPub::BOOK_VERSION_EPUB3);
                $epubbook_start = constant("EPUBBOOK_HEAD_START_v3") . $title . constant("EPUBBOOK_HEAD_END");
                break;
            case 2:
            default:
                $book = new EPub(EPub::BOOK_VERSION_EPUB2);
                $epubbook_start = constant("EPUBBOOK_HEAD_START_v2") . $title . constant("EPUBBOOK_HEAD_END");
                break;
        }
        $book->setTitle($title);
        $book->setIdentifier("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "/" . $title, EPub::IDENTIFIER_URI);
        $book->setLanguage("fr");
        // TODO L10N
        $book->setDescription(_t('P_EPUB_BOOK_DESCRIPTION'));
        //$book->addCSSFile("styles.css", "css1", $cssData); //TODO add Leed css ?
        //$book->setCoverImage("Cover.jpg", file_get_contents("demo/cover-image.jpg"), "image/jpeg");
        $cover = $epubbook_start . "<h1>" . $title . "</h1>\n<h2>" . _t('P_EPUB_BYLEED') . "</h2>\n" . constant("EPUBBOOK_END");
        $book->addChapter("Notices", "Cover.html", $cover);
        // Epub chapters (articles) creation
        $chapNb = 1;
        while ($data = mysql_fetch_array($qry_articles)) {
            $title_article = html_entity_decode($data['title'], ENT_QUOTES, 'UTF-8');
            $author_article = html_entity_decode($data['creator'], ENT_QUOTES, 'UTF-8');
            $html_content = $epubbook_start . '<h2 class="articleTitle">' . $title_article . '</h2>' . '<h3 class="articleDetails">' . _t('P_EPUB_BY') . ' ' . $author_article . ' ' . _t('P_EPUB_ON_DATE') . ' ' . date("d/m/Y", $data['pubdate']) . ' ' . _t('P_EPUB_AT_TIME') . ' ' . date("H:i:s", $data['pubdate']) . '</h3>' . $data['content'] . constant("EPUBBOOK_END");
            $html_content = html_entity_decode($html_content, ENT_QUOTES, 'UTF-8');
            switch ($external_content) {
                case "textonly":
                    // Replace img tags by their alt value if possible (PHPePub make it only for Epub::EXTERNAL_REF_REPLACE_IMAGES)
                    $html_content = preg_replace('/<\\s*?img.*alt="(.*?)".*?>/', '[image: ${1}]', $html_content);
                    $html_content = preg_replace('/<\\s*?br.*(.*?)".*?>/', '[image: ${1}]', $html_content);
                    $book->addChapter($title_article, _t('P_EPUB_CHAPTER') . "_" . $chapNb . ".html", $html_content, true, EPub::EXTERNAL_REF_IGNORE);
                    break;
                case "noimage":
                    $book->addChapter($title_article, _t('P_EPUB_CHAPTER') . "_" . $chapNb . ".html", $html_content, true, EPub::EXTERNAL_REF_REPLACE_IMAGES);
                    break;
                case "full":
                default:
                    $book->addChapter($title_article, _t('P_EPUB_CHAPTER') . "_" . $chapNb . ".html", $html_content, true, EPub::EXTERNAL_REF_ADD);
                    break;
            }
            $chapNb++;
        }
        // Epub finalization
        $book->buildTOC();
        $book->finalize();
        $zipData = $book->sendBook(preg_replace("( )", '_', preg_replace("([^\\w\\s\\d\\,;\\[\\]\\(\\]])", '', $title)));
        exit;
    } else {
        echo _t('P_EPUB_NOARTICLES_WARNING');
    }
}
示例#14
0
// modify this to point to your book directory
$bookdir = '/home/andi/Dropbox/ebooks/';
// proxy google requests
if (isset($_GET['api'])) {
    header('application/json; charset=UTF-8');
    echo file_get_contents('https://www.googleapis.com/books/v1/volumes?q=' . rawurlencode($_GET['api']) . '&maxResults=25&printType=books&projection=full');
    exit;
}
require_once dirname(__FILE__) . '/vendor/autoload.php';
require_once dirname(__FILE__) . '/util.php';
if (isset($_REQUEST['book'])) {
    try {
        $book = $_REQUEST['book'];
        $book = str_replace('..', '', $book);
        // no upper dirs, lowers might be supported later
        $epub = new EPub($bookdir . $book . '.epub');
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
// return image data
if (isset($_REQUEST['img']) && isset($epub)) {
    $img = $epub->Cover();
    header('Content-Type: ' . $img['mime']);
    echo $img['data'];
    exit;
}
// save epub data
if ($_REQUEST['save'] && isset($epub)) {
    $epub->Title($_POST['title']);
    $epub->Description($_POST['description']);
示例#15
0
 /**
  * handle epub
  */
 public function createEpub()
 {
     switch ($_GET['method']) {
         case 'id':
             $entryID = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
             $entry = $this->store->retrieveOneById($entryID, $this->user->getId());
             $entries = array($entry);
             $bookTitle = $entry['title'];
             $bookFileName = substr($bookTitle, 0, 200);
             break;
         case 'all':
             $entries = $this->store->retrieveAll($this->user->getId());
             $bookTitle = sprintf(_('All my articles on '), date(_('d.m.y')));
             #translatable because each country has it's own date format system
             $bookFileName = _('Allarticles') . date(_('dmY'));
             break;
         case 'tag':
             $tag = filter_var($_GET['tag'], FILTER_SANITIZE_STRING);
             $tags_id = $this->store->retrieveAllTags($this->user->getId(), $tag);
             $tag_id = $tags_id[0]["id"];
             // we take the first result, which is supposed to match perfectly. There must be a workaround.
             $entries = $this->store->retrieveEntriesByTag($tag_id, $this->user->getId());
             $bookTitle = sprintf(_('Articles tagged %s'), $tag);
             $bookFileName = substr(sprintf(_('Tag %s'), $tag), 0, 200);
             break;
         case 'category':
             $category = filter_var($_GET['category'], FILTER_SANITIZE_STRING);
             $entries = $this->store->getEntriesByView($category, $this->user->getId());
             $bookTitle = sprintf(_('All articles in category %s'), $category);
             $bookFileName = substr(sprintf(_('Category %s'), $category), 0, 200);
             break;
         case 'search':
             $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
             $entries = $this->store->search($search, $this->user->getId());
             $bookTitle = sprintf(_('All articles for search %s'), $search);
             $bookFileName = substr(sprintf(_('Search %s'), $search), 0, 200);
             break;
         case 'default':
             die(_('Uh, there is a problem while generating epub.'));
     }
     $content_start = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n" . "<head>" . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n" . "<title>wallabag articles book</title>\n" . "</head>\n" . "<body>\n";
     $bookEnd = "</body>\n</html>\n";
     $log = new Logger("wallabag", TRUE);
     $fileDir = CACHE;
     $book = new EPub(EPub::BOOK_VERSION_EPUB3, DEBUG_POCHE);
     $log->logLine("new EPub()");
     $log->logLine("EPub class version: " . EPub::VERSION);
     $log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION);
     $log->logLine("Zip version: " . Zip::VERSION);
     $log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL());
     $log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL());
     $book->setTitle(_('wallabag\'s articles'));
     $book->setIdentifier("http://{$_SERVER['HTTP_HOST']}", EPub::IDENTIFIER_URI);
     // Could also be the ISBN number, prefered for published books, or a UUID.
     //$book->setLanguage("en"); // Not needed, but included for the example, Language is mandatory, but EPub defaults to "en". Use RFC3066 Language codes, such as "en", "da", "fr" etc.
     $book->setDescription(_("Some articles saved on my wallabag"));
     $book->setAuthor("wallabag", "wallabag");
     $book->setPublisher("wallabag", "wallabag");
     // I hope this is a non existant address :)
     $book->setDate(time());
     // Strictly not needed as the book date defaults to time().
     //$book->setRights("Copyright and licence information specific for the book."); // As this is generated, this _could_ contain the name or licence information of the user who purchased the book, if needed. If this is used that way, the identifier must also be made unique for the book.
     $book->setSourceURL("http://{$_SERVER['HTTP_HOST']}");
     $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "PHP");
     $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "wallabag");
     $cssData = "body {\n margin-left: .5em;\n margin-right: .5em;\n text-align: justify;\n}\n\np {\n font-family: serif;\n font-size: 10pt;\n text-align: justify;\n text-indent: 1em;\n margin-top: 0px;\n margin-bottom: 1ex;\n}\n\nh1, h2 {\n font-family: sans-serif;\n font-style: italic;\n text-align: center;\n background-color: #6b879c;\n color: white;\n width: 100%;\n}\n\nh1 {\n margin-bottom: 2px;\n}\n\nh2 {\n margin-top: -2px;\n margin-bottom: 2px;\n}\n";
     $log->logLine("Add Cover");
     $fullTitle = "<h1> " . $bookTitle . "</h1>\n";
     $book->setCoverImage("Cover.png", file_get_contents("themes/baggy/img/apple-touch-icon-152.png"), "image/png", $fullTitle);
     $cover = $content_start . '<div style="text-align:center;"><p>' . _('Produced by wallabag with PHPePub') . '</p><p>' . _('Please open <a href="https://github.com/wallabag/wallabag/issues" >an issue</a> if you have trouble with the display of this E-Book on your device.') . '</p></div>' . $bookEnd;
     //$book->addChapter("Table of Contents", "TOC.xhtml", NULL, false, EPub::EXTERNAL_REF_IGNORE);
     $book->addChapter("Notices", "Cover2.html", $cover);
     $book->buildTOC();
     foreach ($entries as $entry) {
         //set tags as subjects
         $tags = $this->store->retrieveTagsByEntry($entry['id']);
         foreach ($tags as $tag) {
             $book->setSubject($tag['value']);
         }
         $log->logLine("Set up parameters");
         $chapter = $content_start . $entry['content'] . $bookEnd;
         $book->addChapter($entry['title'], htmlspecialchars($entry['title']) . ".html", $chapter, true, EPub::EXTERNAL_REF_ADD);
         $log->logLine("Added chapter " . $entry['title']);
     }
     if (DEBUG_POCHE) {
         $epuplog = $book->getLog();
         $book->addChapter("Log", "Log.html", $content_start . $log->getLog() . "\n</pre>" . $bookEnd);
         // log generation
     }
     $book->finalize();
     $zipData = $book->sendBook($bookFileName);
 }
示例#16
0
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Sébastien Lucas <*****@*****.**>
 */
require_once "config.php";
require_once "base.php";
require_once "book.php";
require_once "resources/php-epub-meta/epub.php";
header("Content-Type: text/html;charset=utf-8");
$idData = getURLParam("data", NULL);
$add = "data={$idData}&";
if (!is_null(GetUrlParam(DB))) {
    $add .= DB . "=" . GetUrlParam(DB) . "&";
}
$myBook = Book::getBookByDataId($idData);
$book = new EPub($myBook->getFilePath("EPUB", $idData));
$book->initSpineComponent();
?>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="imagetoolbar" content="no" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>COPS's Epub Reader</title>
    <script type="text/javascript" src="<?php 
echo getUrlWithVersion("resources/monocle/scripts/monocore.js");
?>
"></script>
    <script type="text/javascript" src="<?php 
echo getUrlWithVersion("resources/monocle/scripts/monoctrl.js");
?>
"></script>