]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/poche/WallabagEBooks.class.php
removed unnecessary fonts
[github/wallabag/wallabag.git] / inc / poche / WallabagEBooks.class.php
CommitLineData
2f26729c
NL
1<?php
2/**
3 * wallabag, self hostable application allowing you to not miss any content anymore
4 *
5 * @category wallabag
6 * @author Nicolas Lœuillet <nicolas@loeuillet.org>
7 * @copyright 2013
8 * @license http://opensource.org/licenses/MIT see COPYING file
9 */
10
4188f38a 11class WallabagEBooks
2f26729c 12{
4188f38a 13 protected $wallabag;
2f26729c 14 protected $method;
2f26729c 15 protected $value;
4188f38a 16 protected $entries;
17 protected $bookTitle;
18 protected $bookFileName;
f8c37985 19 protected $author = 'wallabag';
2f26729c 20
2b58426b 21 public function __construct(Poche $wallabag, $method, $value)
2f26729c
NL
22 {
23 $this->wallabag = $wallabag;
24 $this->method = $method;
2f26729c
NL
25 $this->value = $value;
26 }
27
4188f38a 28 public function prepareData()
2f26729c
NL
29 {
30 switch ($this->method) {
31 case 'id':
2b58426b 32 $entryID = filter_var($this->value, FILTER_SANITIZE_NUMBER_INT);
2f26729c 33 $entry = $this->wallabag->store->retrieveOneById($entryID, $this->wallabag->user->getId());
fb9df0c2 34 $this->entries = array($entry);
35 $this->bookTitle = $entry['title'];
36 $this->bookFileName = substr($this->bookTitle, 0, 200);
f8c37985 37 $this->author = preg_replace('#^w{3}.#', '', Tools::getdomain($entry["url"])); # if only one article, set author to domain name (we strip the eventual www part)
38 Tools::logm('Producing ebook from article ' . $this->bookTitle);
2f26729c
NL
39 break;
40 case 'all':
fb9df0c2 41 $this->entries = $this->wallabag->store->retrieveAll($this->wallabag->user->getId());
deab6280 42 $this->bookTitle = sprintf(_('All my articles on %s'), date(_('d.m.y'))); #translatable because each country has it's own date format system
fb9df0c2 43 $this->bookFileName = _('Allarticles') . date(_('dmY'));
f8c37985 44 Tools::logm('Producing ebook from all articles');
2f26729c
NL
45 break;
46 case 'tag':
47 $tag = filter_var($this->value, FILTER_SANITIZE_STRING);
48 $tags_id = $this->wallabag->store->retrieveAllTags($this->wallabag->user->getId(), $tag);
49 $tag_id = $tags_id[0]["id"]; // we take the first result, which is supposed to match perfectly. There must be a workaround.
fb9df0c2 50 $this->entries = $this->wallabag->store->retrieveEntriesByTag($tag_id, $this->wallabag->user->getId());
51 $this->bookTitle = sprintf(_('Articles tagged %s'), $tag);
52 $this->bookFileName = substr(sprintf(_('Tag %s'), $tag), 0, 200);
f8c37985 53 Tools::logm('Producing ebook from tag ' . $tag);
2f26729c
NL
54 break;
55 case 'category':
56 $category = filter_var($this->value, FILTER_SANITIZE_STRING);
fb9df0c2 57 $this->entries = $this->wallabag->store->getEntriesByView($category, $this->wallabag->user->getId());
ab86a512 58 $this->bookTitle = sprintf(_('Articles in category %s'), $category);
fb9df0c2 59 $this->bookFileName = substr(sprintf(_('Category %s'), $category), 0, 200);
f8c37985 60 Tools::logm('Producing ebook from category ' . $category);
2f26729c
NL
61 break;
62 case 'search':
63 $search = filter_var($this->value, FILTER_SANITIZE_STRING);
fb9df0c2 64 Tools::logm($search);
65 $this->entries = $this->wallabag->store->search($search, $this->wallabag->user->getId());
ab86a512 66 $this->bookTitle = sprintf(_('Articles for search %s'), $search);
fb9df0c2 67 $this->bookFileName = substr(sprintf(_('Search %s'), $search), 0, 200);
f8c37985 68 Tools::logm('Producing ebook from search ' . $search);
2f26729c
NL
69 break;
70 case 'default':
f8c37985 71 die(_('Uh, there is a problem while generating eBook.'));
2f26729c 72 }
4188f38a 73 }
74}
2f26729c 75
4188f38a 76class WallabagEpub extends WallabagEBooks
77{
78 /**
79 * handle ePub
80 */
81 public function produceEpub()
82 {
f8c37985 83 Tools::logm('Starting to produce ePub 3 file');
2f26729c
NL
84 $content_start =
85 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
86 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
87 . "<head>"
88 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
f8c37985 89 . "<title>" . _("wallabag articles book") . "</title>\n"
2f26729c
NL
90 . "</head>\n"
91 . "<body>\n";
92
93 $bookEnd = "</body>\n</html>\n";
94
95 $log = new Logger("wallabag", TRUE);
96 $fileDir = CACHE;
97
98 $book = new EPub(EPub::BOOK_VERSION_EPUB3, DEBUG_POCHE);
99 $log->logLine("new EPub()");
100 $log->logLine("EPub class version: " . EPub::VERSION);
101 $log->logLine("EPub Req. Zip version: " . EPub::REQ_ZIP_VERSION);
102 $log->logLine("Zip version: " . Zip::VERSION);
103 $log->logLine("getCurrentServerURL: " . $book->getCurrentServerURL());
104 $log->logLine("getCurrentPageURL..: " . $book->getCurrentPageURL());
105
f8c37985 106 Tools::logm('Filling metadata for ePub...');
107
fb9df0c2 108 $book->setTitle($this->bookTitle);
2f26729c
NL
109 $book->setIdentifier("http://$_SERVER[HTTP_HOST]", EPub::IDENTIFIER_URI); // Could also be the ISBN number, prefered for published books, or a UUID.
110 //$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.
111 $book->setDescription(_("Some articles saved on my wallabag"));
f8c37985 112 $book->setAuthor($this->author,$this->author);
2f26729c
NL
113 $book->setPublisher("wallabag", "wallabag"); // I hope this is a non existant address :)
114 $book->setDate(time()); // Strictly not needed as the book date defaults to time().
115 //$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.
116 $book->setSourceURL("http://$_SERVER[HTTP_HOST]");
117
118 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "PHP");
119 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, "wallabag");
120
121 $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";
122
123 $log->logLine("Add Cover");
124
fb9df0c2 125 $fullTitle = "<h1> " . $this->bookTitle . "</h1>\n";
2f26729c
NL
126
127 $book->setCoverImage("Cover.png", file_get_contents("themes/baggy/img/apple-touch-icon-152.png"), "image/png", $fullTitle);
128
129 $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;
130
131 //$book->addChapter("Table of Contents", "TOC.xhtml", NULL, false, EPub::EXTERNAL_REF_IGNORE);
132 $book->addChapter("Notices", "Cover2.html", $cover);
133
134 $book->buildTOC();
135
f8c37985 136 Tools::logm('Adding actual content...');
137
fb9df0c2 138 foreach ($this->entries as $entry) { //set tags as subjects
2f26729c
NL
139 $tags = $this->wallabag->store->retrieveTagsByEntry($entry['id']);
140 foreach ($tags as $tag) {
141 $book->setSubject($tag['value']);
142 }
143
144 $log->logLine("Set up parameters");
145
146 $chapter = $content_start . $entry['content'] . $bookEnd;
147 $book->addChapter($entry['title'], htmlspecialchars($entry['title']) . ".html", $chapter, true, EPub::EXTERNAL_REF_ADD);
148 $log->logLine("Added chapter " . $entry['title']);
149 }
150
151 if (DEBUG_POCHE) {
152 $book->addChapter("Log", "Log.html", $content_start . $log->getLog() . "\n</pre>" . $bookEnd); // log generation
f8c37985 153 Tools::logm('Production log available in produced file');
2f26729c
NL
154 }
155 $book->finalize();
fb9df0c2 156 $zipData = $book->sendBook($this->bookFileName);
f8c37985 157 Tools::logm('Ebook produced');
2f26729c 158 }
4188f38a 159}
160
161class WallabagMobi extends WallabagEBooks
162{
163 /**
fb9df0c2 164 * MOBI Class
165 * @author Sander Kromwijk
4188f38a 166 */
167
dc59f164 168 public function produceMobi($sendByMail = FALSE)
4188f38a 169 {
4188f38a 170
f8c37985 171 Tools::logm('Starting to produce Mobi file');
fb9df0c2 172 $mobi = new MOBI();
fb9df0c2 173 $content = new MOBIFile();
dc59f164 174
175 $messages = new Messages(); // for later
f8c37985 176
177 Tools::logm('Filling metadata for Mobi...');
178
fb9df0c2 179 $content->set("title", $this->bookTitle);
f8c37985 180 $content->set("author", $this->author);
deab6280 181 $content->set("subject", $this->bookTitle);
fb9df0c2 182
183 # introduction
deab6280 184 $content->appendParagraph('<div style="text-align:center;" ><p>' . _('Produced by wallabag with PHPMobi') . '</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>');
fb9df0c2 185 $content->appendImage(imagecreatefrompng("themes/baggy/img/apple-touch-icon-152.png"));
186 $content->appendPageBreak();
187
f8c37985 188 Tools::logm('Adding actual content...');
189
fb9df0c2 190 foreach ($this->entries as $item) {
191 $content->appendChapterTitle($item['title']);
192 $content->appendParagraph($item['content']);
193 $content->appendPageBreak();
4188f38a 194 }
fb9df0c2 195 $mobi->setContentProvider($content);
4188f38a 196
dc59f164 197 if (!$sendByMail) {
198 // we offer file to download
199 $mobi->download($this->bookFileName.'.mobi');
f8c37985 200 Tools::logm('Mobi file produced');
dc59f164 201 }
202 else {
203 // we send file to kindle
204
f8c37985 205 Tools::logm('Preparing to send file by email');
206
207 $error = FALSE;
208 # testing Mail function
209 if (!function_exists('mail')) {
ab86a512 210 $error = _("Mail function is disabled. You can't send emails from your server");
f8c37985 211 }
212
dc59f164 213 $char_in = array('/', '.', ',', ':', '|'); # we sanitize filename to avoid conflicts with special characters (for instance, / goes for a directory)
d49446ff 214 $mobiExportName = preg_replace('/\s+/', '-', str_replace($char_in, '-', $this->bookFileName)) . '.mobi';
dc59f164 215
216 $file = 'cache/' . $mobiExportName;
217 $mobi->save($file);
218
219 $file_size = filesize($file);
220 $filename = basename($file);
221 $handle = fopen($file, "r");
222 $content = fread($handle, $file_size);
223 fclose($handle);
224 $content = chunk_split(base64_encode($content));
225
226 $uid = md5(uniqid(time()));
227
228 //generate header for mail
229 $header = "From: wallabag <". $this->wallabag->user->email .">\r\n";
230 $header .= "MIME-Version: 1.0\r\n";
231 $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
232 $header .= "This is a multi-part message in MIME format.\r\n";
233 $header .= "--".$uid."\r\n";
234 $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
235 $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
236 $header .= "send via wallabag\r\n\r\n";
237 $header .= "--".$uid."\r\n";
238 $header .= "Content-Type: application/x-mobipocket-ebook; name=\"".$filename."\"\r\n";
239 $header .= "Content-Transfer-Encoding: base64\r\n";
240 $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
241 $header .= $content."\r\n\r\n";
242 $header .= "--".$uid."--";
243
244 # trying to get the kindle email adress
f8c37985 245 if (!$this->wallabag->user->getConfigValue('kindleemail'))
dc59f164 246 {
ab86a512 247 $error = _("You didn't set your kindle's email adress !");
dc59f164 248 }
f8c37985 249 if (!$error) {
250 mail($this->wallabag->user->getConfigValue('kindleemail'), '[wallabag] ' . $this->bookTitle, "", $header );
251 $messages->add('s', _('The email has been sent to your kindle !'));
252 Tools::logm('Email sent');
253 } else {
254 $messages->add('e', $error);
255 Tools::logm($error);
dc59f164 256 }
257 }
fb9df0c2 258 }
4188f38a 259}
260
261class WallabagPDF extends WallabagEbooks
262{
263 public function producePDF()
264 {
265 $mpdf = new mPDF('c');
266
f8c37985 267 Tools::logm('Starting to produce PDF file');
fb9df0c2 268
f8c37985 269 Tools::logm('Filling metadata for PDF...');
270
271 # headers
272 $mpdf->SetHeader('{DATE j-m-Y}|{PAGENO}/{nb}|Produced with wallabag');
273 $mpdf->SetFooter('{PAGENO}');
274
275 # intro
deab6280 276 $html = '<h1>' . $this->bookTitle . '<bookmark content="Cover" /></h1><div style="text-align:center;" >
277 <p>' . _('Produced by wallabag with mPDF') . '</p>
278 <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>
279 <img src="themes/baggy/img/apple-touch-icon-152.png" /></div>';
280 $html .= '<pagebreak type="next-odd" />';
281 $i = 1;
fb9df0c2 282
f8c37985 283 Tools::logm('Adding actual content...');
fb9df0c2 284 foreach ($this->entries as $item) {
deab6280 285 $html .= '<h1>' . $item['title'] . '<bookmark content="' . $item['title'] . '" /></h1>';
fb9df0c2 286 $html .= '<indexentry content="'. $item['title'] .'" />';
287 $html .= $item['content'];
deab6280 288 $html .= '<pagebreak type="next-odd" />';
289 $i = $i+1;
fb9df0c2 290 }
fb9df0c2 291
292 $mpdf->WriteHTML($html);
293
294 # remove characters that make mpdf bug
295 $char_in = array('/', '.', ',', ':', '|');
f8c37985 296 $pdfExportName = preg_replace('/\s+/', '-', str_replace($char_in, '-', $this->bookFileName . '.pdf')); # maybe someone can make a proper regex of this ?
deab6280 297
298 # index
299 $html = '<h2>Index<bookmark content="Index" /></h2>
300 <indexinsert cols="2" offset="5" usedivletters="on" div-font-size="15" gap="5" font="Trebuchet" div-font="sans-serif" links="on" />
301 ';
302
303 $mpdf->WriteHTML($html);
fb9df0c2 304
305 $mpdf->Output('cache/' . $pdfExportName);
306
307 header('Content-Disposition: attachment; filename="' . $pdfExportName . '"');
308
309 header('Content-Transfer-Encoding: base64');
310 header('Content-Type: application/pdf');
311 echo file_get_contents('cache/' . $pdfExportName);
f8c37985 312 Tools::logm('PDF file produced');
4188f38a 313 }
314}