]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/EntriesExport.php
EntriesExport/epub: remove TOC page
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / EntriesExport.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Helper;
4
5 use Html2Text\Html2Text;
6 use JMS\Serializer\SerializationContext;
7 use JMS\Serializer\SerializerBuilder;
8 use PHPePub\Core\EPub;
9 use PHPePub\Core\Structure\OPF\DublinCore;
10 use Symfony\Component\HttpFoundation\Response;
11 use Symfony\Component\Translation\TranslatorInterface;
12 use Wallabag\CoreBundle\Entity\Entry;
13
14 /**
15 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
16 */
17 class EntriesExport
18 {
19 private $wallabagUrl;
20 private $logoPath;
21 private $translator;
22 private $title = '';
23 private $entries = [];
24 private $author = 'wallabag';
25 private $language = '';
26
27 /**
28 * @param TranslatorInterface $translator Translator service
29 * @param string $wallabagUrl Wallabag instance url
30 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
31 */
32 public function __construct(TranslatorInterface $translator, $wallabagUrl, $logoPath)
33 {
34 $this->translator = $translator;
35 $this->wallabagUrl = $wallabagUrl;
36 $this->logoPath = $logoPath;
37 }
38
39 /**
40 * Define entries.
41 *
42 * @param array|Entry $entries An array of entries or one entry
43 *
44 * @return EntriesExport
45 */
46 public function setEntries($entries)
47 {
48 if (!\is_array($entries)) {
49 $this->language = $entries->getLanguage();
50 $entries = [$entries];
51 }
52
53 $this->entries = $entries;
54
55 return $this;
56 }
57
58 /**
59 * Sets the category of which we want to get articles, or just one entry.
60 *
61 * @param string $method Method to get articles
62 *
63 * @return EntriesExport
64 */
65 public function updateTitle($method)
66 {
67 $this->title = $method . ' articles';
68
69 if ('entry' === $method) {
70 $this->title = $this->entries[0]->getTitle();
71 }
72
73 return $this;
74 }
75
76 /**
77 * Sets the author for one entry or category.
78 *
79 * The publishers are used, or the domain name if empty.
80 *
81 * @param string $method Method to get articles
82 *
83 * @return EntriesExport
84 */
85 public function updateAuthor($method)
86 {
87 if ('entry' !== $method) {
88 $this->author = $method . ' authors';
89
90 return $this;
91 }
92
93 $this->author = $this->entries[0]->getDomainName();
94
95 $publishedBy = $this->entries[0]->getPublishedBy();
96 if (!empty($publishedBy)) {
97 $this->author = implode(', ', $publishedBy);
98 }
99
100 return $this;
101 }
102
103 /**
104 * Sets the output format.
105 *
106 * @param string $format
107 *
108 * @return Response
109 */
110 public function exportAs($format)
111 {
112 $functionName = 'produce' . ucfirst($format);
113 if (method_exists($this, $functionName)) {
114 return $this->$functionName();
115 }
116
117 throw new \InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
118 }
119
120 public function exportJsonData()
121 {
122 return $this->prepareSerializingContent('json');
123 }
124
125 /**
126 * Use PHPePub to dump a .epub file.
127 *
128 * @return Response
129 */
130 private function produceEpub()
131 {
132 /*
133 * Start and End of the book
134 */
135 $content_start =
136 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
137 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
138 . '<head>'
139 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
140 . "<title>wallabag articles book</title>\n"
141 . "</head>\n"
142 . "<body>\n";
143
144 $bookEnd = "</body>\n</html>\n";
145
146 $book = new EPub(EPub::BOOK_VERSION_EPUB3);
147
148 /*
149 * Book metadata
150 */
151
152 $book->setTitle($this->title);
153 // 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.
154 $book->setLanguage($this->language);
155 $book->setDescription('Some articles saved on my wallabag');
156
157 $book->setAuthor($this->author, $this->author);
158
159 // I hope this is a non existant address :)
160 $book->setPublisher('wallabag', 'wallabag');
161 // Strictly not needed as the book date defaults to time().
162 $book->setDate(time());
163 $book->setSourceURL($this->wallabagUrl);
164
165 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
166 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
167
168 /*
169 * Front page
170 */
171 if (file_exists($this->logoPath)) {
172 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
173 }
174
175 $entryIds = [];
176
177 /*
178 * Adding actual entries
179 */
180
181 // set tags as subjects
182 foreach ($this->entries as $entry) {
183 foreach ($entry->getTags() as $tag) {
184 $book->setSubject($tag->getLabel());
185 }
186
187 // the reader in Kobo Devices doesn't likes special caracters
188 // in filenames, we limit to A-z/0-9
189 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
190
191 $titlepage = $content_start . '<h1>' . $entry->getTitle() . '</h1>' . $this->getExportInformation('PHPePub') . $bookEnd;
192 $book->addChapter('Title', 'Title.html', $titlepage, true, EPub::EXTERNAL_REF_ADD);
193 $chapter = $content_start . $entry->getContent() . $bookEnd;
194 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
195
196 $entryIds[] = $entry->getId();
197 }
198
199 // Could also be the ISBN number, prefered for published books, or a UUID.
200 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl, implode(',', $entryIds)));
201 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub::IDENTIFIER_URI);
202
203 return Response::create(
204 $book->getBook(),
205 200,
206 [
207 'Content-Description' => 'File Transfer',
208 'Content-type' => 'application/epub+zip',
209 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
210 'Content-Transfer-Encoding' => 'binary',
211 ]
212 );
213 }
214
215 /**
216 * Use PHPMobi to dump a .mobi file.
217 *
218 * @return Response
219 */
220 private function produceMobi()
221 {
222 $mobi = new \MOBI();
223 $content = new \MOBIFile();
224
225 /*
226 * Book metadata
227 */
228 $content->set('title', $this->title);
229 $content->set('author', $this->author);
230 $content->set('subject', $this->title);
231
232 /*
233 * Front page
234 */
235 $content->appendParagraph($this->getExportInformation('PHPMobi'));
236 if (file_exists($this->logoPath)) {
237 $content->appendImage(imagecreatefrompng($this->logoPath));
238 }
239 $content->appendPageBreak();
240
241 /*
242 * Adding actual entries
243 */
244 foreach ($this->entries as $entry) {
245 $content->appendChapterTitle($entry->getTitle());
246 $content->appendParagraph($entry->getContent());
247 $content->appendPageBreak();
248 }
249 $mobi->setContentProvider($content);
250
251 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
252 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
253
254 return Response::create(
255 $mobi->toString(),
256 200,
257 [
258 'Accept-Ranges' => 'bytes',
259 'Content-Description' => 'File Transfer',
260 'Content-type' => 'application/x-mobipocket-ebook',
261 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
262 'Content-Transfer-Encoding' => 'binary',
263 ]
264 );
265 }
266
267 /**
268 * Use TCPDF to dump a .pdf file.
269 *
270 * @return Response
271 */
272 private function producePdf()
273 {
274 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
275
276 /*
277 * Book metadata
278 */
279 $pdf->SetCreator(PDF_CREATOR);
280 $pdf->SetAuthor($this->author);
281 $pdf->SetTitle($this->title);
282 $pdf->SetSubject('Articles via wallabag');
283 $pdf->SetKeywords('wallabag');
284
285 /*
286 * Front page
287 */
288 $pdf->AddPage();
289 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
290
291 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
292
293 /*
294 * Adding actual entries
295 */
296 foreach ($this->entries as $entry) {
297 foreach ($entry->getTags() as $tag) {
298 $pdf->SetKeywords($tag->getLabel());
299 }
300
301 $pdf->AddPage();
302 $html = '<h1>' . $entry->getTitle() . '</h1>';
303 $html .= $entry->getContent();
304
305 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
306 }
307
308 // set image scale factor
309 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
310
311 return Response::create(
312 $pdf->Output('', 'S'),
313 200,
314 [
315 'Content-Description' => 'File Transfer',
316 'Content-type' => 'application/pdf',
317 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
318 'Content-Transfer-Encoding' => 'binary',
319 ]
320 );
321 }
322
323 /**
324 * Inspired from CsvFileDumper.
325 *
326 * @return Response
327 */
328 private function produceCsv()
329 {
330 $delimiter = ';';
331 $enclosure = '"';
332 $handle = fopen('php://memory', 'b+r');
333
334 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
335
336 foreach ($this->entries as $entry) {
337 fputcsv(
338 $handle,
339 [
340 $entry->getTitle(),
341 $entry->getURL(),
342 // remove new line to avoid crazy results
343 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
344 implode(', ', $entry->getTags()->toArray()),
345 $entry->getMimetype(),
346 $entry->getLanguage(),
347 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
348 ],
349 $delimiter,
350 $enclosure
351 );
352 }
353
354 rewind($handle);
355 $output = stream_get_contents($handle);
356 fclose($handle);
357
358 return Response::create(
359 $output,
360 200,
361 [
362 'Content-type' => 'application/csv',
363 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
364 'Content-Transfer-Encoding' => 'UTF-8',
365 ]
366 );
367 }
368
369 /**
370 * Dump a JSON file.
371 *
372 * @return Response
373 */
374 private function produceJson()
375 {
376 return Response::create(
377 $this->prepareSerializingContent('json'),
378 200,
379 [
380 'Content-type' => 'application/json',
381 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
382 'Content-Transfer-Encoding' => 'UTF-8',
383 ]
384 );
385 }
386
387 /**
388 * Dump a XML file.
389 *
390 * @return Response
391 */
392 private function produceXml()
393 {
394 return Response::create(
395 $this->prepareSerializingContent('xml'),
396 200,
397 [
398 'Content-type' => 'application/xml',
399 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
400 'Content-Transfer-Encoding' => 'UTF-8',
401 ]
402 );
403 }
404
405 /**
406 * Dump a TXT file.
407 *
408 * @return Response
409 */
410 private function produceTxt()
411 {
412 $content = '';
413 $bar = str_repeat('=', 100);
414 foreach ($this->entries as $entry) {
415 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
416 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
417 $content .= $html->getText();
418 }
419
420 return Response::create(
421 $content,
422 200,
423 [
424 'Content-type' => 'text/plain',
425 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
426 'Content-Transfer-Encoding' => 'UTF-8',
427 ]
428 );
429 }
430
431 /**
432 * Return a Serializer object for producing processes that need it (JSON & XML).
433 *
434 * @param string $format
435 *
436 * @return string
437 */
438 private function prepareSerializingContent($format)
439 {
440 $serializer = SerializerBuilder::create()->build();
441
442 return $serializer->serialize(
443 $this->entries,
444 $format,
445 SerializationContext::create()->setGroups(['entries_for_user'])
446 );
447 }
448
449 /**
450 * Return a kind of footer / information for the epub.
451 *
452 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
453 *
454 * @return string
455 */
456 private function getExportInformation($type)
457 {
458 $info = $this->translator->trans('export.footer_template', [
459 '%method%' => $type,
460 ]);
461
462 if ('tcpdf' === $type) {
463 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
464 }
465
466 return str_replace('%IMAGE%', '', $info);
467 }
468 }