]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/EntriesExport.php
EntriesExport/epub: add metadata to each entry's cover
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / EntriesExport.php
CommitLineData
03690d13
TC
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
c6608783 5use Html2Text\Html2Text;
619cc453
JB
6use JMS\Serializer\SerializationContext;
7use JMS\Serializer\SerializerBuilder;
03690d13
TC
8use PHPePub\Core\EPub;
9use PHPePub\Core\Structure\OPF\DublinCore;
add597ba 10use Symfony\Component\HttpFoundation\Response;
b1428a1c 11use Symfony\Component\Translation\TranslatorInterface;
52b84c11 12use Wallabag\CoreBundle\Entity\Entry;
03690d13 13
cceca9ea
JB
14/**
15 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
16 */
03690d13
TC
17class EntriesExport
18{
add597ba
JB
19 private $wallabagUrl;
20 private $logoPath;
b1428a1c 21 private $translator;
add597ba 22 private $title = '';
4094ea47 23 private $entries = [];
07320a2b 24 private $author = 'wallabag';
add597ba 25 private $language = '';
03690d13 26
add597ba 27 /**
9dd67fa3
JB
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
add597ba 31 */
dc7fa8df 32 public function __construct(TranslatorInterface $translator, $wallabagUrl, $logoPath)
03690d13 33 {
dc7fa8df 34 $this->translator = $translator;
4b3c983a 35 $this->wallabagUrl = $wallabagUrl;
add597ba
JB
36 $this->logoPath = $logoPath;
37 }
38
39 /**
40 * Define entries.
41 *
42 * @param array|Entry $entries An array of entries or one entry
4094ea47
JB
43 *
44 * @return EntriesExport
add597ba
JB
45 */
46 public function setEntries($entries)
47 {
2a1ceb67 48 if (!\is_array($entries)) {
add597ba 49 $this->language = $entries->getLanguage();
4094ea47 50 $entries = [$entries];
add597ba
JB
51 }
52
03690d13
TC
53 $this->entries = $entries;
54
add597ba 55 return $this;
03690d13
TC
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
4094ea47
JB
62 *
63 * @return EntriesExport
03690d13 64 */
add597ba 65 public function updateTitle($method)
03690d13 66 {
15a6402f 67 $this->title = $method . ' articles';
add597ba
JB
68
69 if ('entry' === $method) {
70 $this->title = $this->entries[0]->getTitle();
03690d13 71 }
add597ba
JB
72
73 return $this;
03690d13
TC
74 }
75
07320a2b 76 /**
c57f69d9
ÉG
77 * Sets the author for one entry or category.
78 *
79 * The publishers are used, or the domain name if empty.
07320a2b
ÉG
80 *
81 * @param string $method Method to get articles
82 *
83 * @return EntriesExport
84 */
85 public function updateAuthor($method)
86 {
eeabca80 87 if ('entry' !== $method) {
f8108346 88 $this->author = 'Various authors';
07320a2b 89
eeabca80
ÉG
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);
07320a2b
ÉG
98 }
99
100 return $this;
101 }
102
03690d13
TC
103 /**
104 * Sets the output format.
105 *
106 * @param string $format
4094ea47
JB
107 *
108 * @return Response
03690d13
TC
109 */
110 public function exportAs($format)
111 {
15a6402f 112 $functionName = 'produce' . ucfirst($format);
8f336fda
JB
113 if (method_exists($this, $functionName)) {
114 return $this->$functionName();
03690d13 115 }
add597ba
JB
116
117 throw new \InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
03690d13
TC
118 }
119
8303b037
TC
120 public function exportJsonData()
121 {
122 return $this->prepareSerializingContent('json');
123 }
124
add597ba
JB
125 /**
126 * Use PHPePub to dump a .epub file.
4094ea47
JB
127 *
128 * @return Response
add597ba 129 */
03690d13
TC
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"
15a6402f
JB
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";
03690d13
TC
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);
add597ba
JB
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');
03690d13 156
07320a2b 157 $book->setAuthor($this->author, $this->author);
03690d13 158
add597ba
JB
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);
03690d13
TC
164
165 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
166 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
167
168 /*
169 * Front page
170 */
add597ba
JB
171 if (file_exists($this->logoPath)) {
172 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
173 }
03690d13 174
bf22266a 175 $entryIds = [];
edd1825b
KD
176 $entryCount = \count($this->entries);
177 $i = 0;
bf22266a 178
03690d13
TC
179 /*
180 * Adding actual entries
181 */
182
add597ba
JB
183 // set tags as subjects
184 foreach ($this->entries as $entry) {
edd1825b 185 ++$i;
b0458874
JB
186 foreach ($entry->getTags() as $tag) {
187 $book->setSubject($tag->getLabel());
add597ba 188 }
edd1825b 189 $filename = sha1($entry->getTitle());
45d94a98 190
4944703e
KD
191 $publishedBy = $entry->getPublishedBy();
192 if (!empty($publishedBy)) {
193 $authors = implode(',', $publishedBy);
194 } else {
195 $authors = $this->translator->trans('export.unknown');
196 }
197
198 $titlepage = $content_start .
199 '<h1>' . $entry->getTitle() . '</h1>' .
200 '<dl>' .
201 '<dt>' . $this->translator->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
202 '<dt>' . $this->translator->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
203 '<dt>' . $this->translator->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
204 '<dt>' . $this->translator->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
205 '</dl>' .
206 $bookEnd;
edd1825b 207 $book->addChapter("Entry {$i} of {$entryCount}", "{$filename}_cover.html", $titlepage, true, EPub::EXTERNAL_REF_ADD);
15a6402f 208 $chapter = $content_start . $entry->getContent() . $bookEnd;
bf22266a
KD
209
210 $entryIds[] = $entry->getId();
edd1825b 211 $book->addChapter($entry->getTitle(), "{$filename}.html", $chapter, true, EPub::EXTERNAL_REF_ADD);
03690d13 212 }
add597ba 213
30cf72bf
KD
214 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
215
bf22266a
KD
216 // Could also be the ISBN number, prefered for published books, or a UUID.
217 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl, implode(',', $entryIds)));
218 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub::IDENTIFIER_URI);
219
add597ba
JB
220 return Response::create(
221 $book->getBook(),
222 200,
4094ea47 223 [
add597ba
JB
224 'Content-Description' => 'File Transfer',
225 'Content-type' => 'application/epub+zip',
15a6402f 226 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
add597ba 227 'Content-Transfer-Encoding' => 'binary',
4094ea47 228 ]
f898102c 229 );
03690d13
TC
230 }
231
add597ba
JB
232 /**
233 * Use PHPMobi to dump a .mobi file.
4094ea47
JB
234 *
235 * @return Response
add597ba 236 */
03690d13
TC
237 private function produceMobi()
238 {
239 $mobi = new \MOBI();
240 $content = new \MOBIFile();
241
242 /*
243 * Book metadata
244 */
03690d13 245 $content->set('title', $this->title);
07320a2b 246 $content->set('author', $this->author);
03690d13
TC
247 $content->set('subject', $this->title);
248
249 /*
250 * Front page
251 */
add597ba
JB
252 $content->appendParagraph($this->getExportInformation('PHPMobi'));
253 if (file_exists($this->logoPath)) {
254 $content->appendImage(imagecreatefrompng($this->logoPath));
255 }
03690d13
TC
256 $content->appendPageBreak();
257
258 /*
259 * Adding actual entries
260 */
03690d13
TC
261 foreach ($this->entries as $entry) {
262 $content->appendChapterTitle($entry->getTitle());
263 $content->appendParagraph($entry->getContent());
264 $content->appendPageBreak();
265 }
266 $mobi->setContentProvider($content);
267
268 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
269 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
270
add597ba
JB
271 return Response::create(
272 $mobi->toString(),
273 200,
4094ea47 274 [
add597ba
JB
275 'Accept-Ranges' => 'bytes',
276 'Content-Description' => 'File Transfer',
277 'Content-type' => 'application/x-mobipocket-ebook',
15a6402f 278 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
add597ba 279 'Content-Transfer-Encoding' => 'binary',
4094ea47 280 ]
f898102c 281 );
03690d13
TC
282 }
283
add597ba
JB
284 /**
285 * Use TCPDF to dump a .pdf file.
4094ea47
JB
286 *
287 * @return Response
add597ba 288 */
8f336fda 289 private function producePdf()
03690d13
TC
290 {
291 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
292
293 /*
294 * Book metadata
295 */
03690d13 296 $pdf->SetCreator(PDF_CREATOR);
07320a2b 297 $pdf->SetAuthor($this->author);
03690d13
TC
298 $pdf->SetTitle($this->title);
299 $pdf->SetSubject('Articles via wallabag');
300 $pdf->SetKeywords('wallabag');
301
302 /*
303 * Front page
304 */
03690d13 305 $pdf->AddPage();
15a6402f 306 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
03690d13
TC
307
308 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
309
310 /*
311 * Adding actual entries
312 */
03690d13 313 foreach ($this->entries as $entry) {
b0458874
JB
314 foreach ($entry->getTags() as $tag) {
315 $pdf->SetKeywords($tag->getLabel());
03690d13
TC
316 }
317
318 $pdf->AddPage();
15a6402f 319 $html = '<h1>' . $entry->getTitle() . '</h1>';
03690d13 320 $html .= $entry->getContent();
add597ba 321
03690d13
TC
322 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
323 }
324
325 // set image scale factor
326 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
327
add597ba
JB
328 return Response::create(
329 $pdf->Output('', 'S'),
330 200,
4094ea47 331 [
add597ba
JB
332 'Content-Description' => 'File Transfer',
333 'Content-type' => 'application/pdf',
15a6402f 334 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
add597ba 335 'Content-Transfer-Encoding' => 'binary',
4094ea47 336 ]
f898102c 337 );
03690d13
TC
338 }
339
add597ba
JB
340 /**
341 * Inspired from CsvFileDumper.
4094ea47
JB
342 *
343 * @return Response
add597ba 344 */
8f336fda 345 private function produceCsv()
03690d13 346 {
add597ba
JB
347 $delimiter = ';';
348 $enclosure = '"';
2a1ceb67 349 $handle = fopen('php://memory', 'b+r');
03690d13 350
9401696f 351 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
03690d13 352
03690d13 353 foreach ($this->entries as $entry) {
add597ba
JB
354 fputcsv(
355 $handle,
4094ea47 356 [
add597ba
JB
357 $entry->getTitle(),
358 $entry->getURL(),
cceca9ea 359 // remove new line to avoid crazy results
4094ea47 360 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
add597ba
JB
361 implode(', ', $entry->getTags()->toArray()),
362 $entry->getMimetype(),
363 $entry->getLanguage(),
9401696f 364 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
4094ea47 365 ],
add597ba
JB
366 $delimiter,
367 $enclosure
368 );
369 }
370
371 rewind($handle);
372 $output = stream_get_contents($handle);
373 fclose($handle);
374
375 return Response::create(
376 $output,
377 200,
4094ea47 378 [
add597ba 379 'Content-type' => 'application/csv',
15a6402f 380 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
add597ba 381 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 382 ]
f898102c 383 );
add597ba
JB
384 }
385
4094ea47
JB
386 /**
387 * Dump a JSON file.
388 *
389 * @return Response
390 */
8f336fda 391 private function produceJson()
b3cc1a14 392 {
b3cc1a14 393 return Response::create(
8ac95cbf 394 $this->prepareSerializingContent('json'),
b3cc1a14 395 200,
4094ea47 396 [
b3cc1a14 397 'Content-type' => 'application/json',
15a6402f 398 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
b3cc1a14 399 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 400 ]
f898102c 401 );
b3cc1a14
TC
402 }
403
4094ea47
JB
404 /**
405 * Dump a XML file.
406 *
407 * @return Response
408 */
8f336fda 409 private function produceXml()
b3cc1a14 410 {
b3cc1a14 411 return Response::create(
8ac95cbf 412 $this->prepareSerializingContent('xml'),
b3cc1a14 413 200,
4094ea47 414 [
b3cc1a14 415 'Content-type' => 'application/xml',
15a6402f 416 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
b3cc1a14 417 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 418 ]
f898102c 419 );
b3cc1a14 420 }
8ac95cbf 421
4094ea47
JB
422 /**
423 * Dump a TXT file.
424 *
425 * @return Response
426 */
8f336fda 427 private function produceTxt()
6c08fb68
TC
428 {
429 $content = '';
d3f31ec4 430 $bar = str_repeat('=', 100);
6c08fb68 431 foreach ($this->entries as $entry) {
15a6402f 432 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
c6608783
NH
433 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
434 $content .= $html->getText();
6c08fb68 435 }
d3f31ec4 436
6c08fb68
TC
437 return Response::create(
438 $content,
439 200,
4094ea47 440 [
6c08fb68 441 'Content-type' => 'text/plain',
15a6402f 442 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
6c08fb68 443 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 444 ]
f898102c 445 );
6c08fb68
TC
446 }
447
b3cc1a14
TC
448 /**
449 * Return a Serializer object for producing processes that need it (JSON & XML).
450 *
0e49487b
JB
451 * @param string $format
452 *
52b84c11 453 * @return string
b3cc1a14 454 */
8ac95cbf 455 private function prepareSerializingContent($format)
b3cc1a14 456 {
268e9e72 457 $serializer = SerializerBuilder::create()->build();
b3cc1a14 458
cceca9ea
JB
459 return $serializer->serialize(
460 $this->entries,
461 $format,
4094ea47 462 SerializationContext::create()->setGroups(['entries_for_user'])
cceca9ea 463 );
b3cc1a14
TC
464 }
465
add597ba
JB
466 /**
467 * Return a kind of footer / information for the epub.
468 *
469 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
470 *
471 * @return string
472 */
473 private function getExportInformation($type)
474 {
b1428a1c
NL
475 $info = $this->translator->trans('export.footer_template', [
476 '%method%' => $type,
477 ]);
add597ba
JB
478
479 if ('tcpdf' === $type) {
15a6402f 480 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
03690d13 481 }
add597ba
JB
482
483 return str_replace('%IMAGE%', '', $info);
03690d13
TC
484 }
485}