]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/EntriesExport.php
EntriesExport: avoid else on $authors
[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 191 $publishedBy = $entry->getPublishedBy();
5e1f2776 192 $authors = $this->translator->trans('export.unknown');
4944703e
KD
193 if (!empty($publishedBy)) {
194 $authors = implode(',', $publishedBy);
4944703e
KD
195 }
196
197 $titlepage = $content_start .
198 '<h1>' . $entry->getTitle() . '</h1>' .
199 '<dl>' .
200 '<dt>' . $this->translator->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
201 '<dt>' . $this->translator->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
202 '<dt>' . $this->translator->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
203 '<dt>' . $this->translator->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
204 '</dl>' .
205 $bookEnd;
edd1825b 206 $book->addChapter("Entry {$i} of {$entryCount}", "{$filename}_cover.html", $titlepage, true, EPub::EXTERNAL_REF_ADD);
15a6402f 207 $chapter = $content_start . $entry->getContent() . $bookEnd;
bf22266a
KD
208
209 $entryIds[] = $entry->getId();
edd1825b 210 $book->addChapter($entry->getTitle(), "{$filename}.html", $chapter, true, EPub::EXTERNAL_REF_ADD);
03690d13 211 }
add597ba 212
30cf72bf
KD
213 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
214
bf22266a
KD
215 // Could also be the ISBN number, prefered for published books, or a UUID.
216 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl, implode(',', $entryIds)));
217 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub::IDENTIFIER_URI);
218
add597ba
JB
219 return Response::create(
220 $book->getBook(),
221 200,
4094ea47 222 [
add597ba
JB
223 'Content-Description' => 'File Transfer',
224 'Content-type' => 'application/epub+zip',
dac93644 225 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.epub"',
add597ba 226 'Content-Transfer-Encoding' => 'binary',
4094ea47 227 ]
f898102c 228 );
03690d13
TC
229 }
230
add597ba
JB
231 /**
232 * Use PHPMobi to dump a .mobi file.
4094ea47
JB
233 *
234 * @return Response
add597ba 235 */
03690d13
TC
236 private function produceMobi()
237 {
238 $mobi = new \MOBI();
239 $content = new \MOBIFile();
240
241 /*
242 * Book metadata
243 */
03690d13 244 $content->set('title', $this->title);
07320a2b 245 $content->set('author', $this->author);
03690d13
TC
246 $content->set('subject', $this->title);
247
248 /*
249 * Front page
250 */
add597ba
JB
251 $content->appendParagraph($this->getExportInformation('PHPMobi'));
252 if (file_exists($this->logoPath)) {
253 $content->appendImage(imagecreatefrompng($this->logoPath));
254 }
03690d13
TC
255 $content->appendPageBreak();
256
257 /*
258 * Adding actual entries
259 */
03690d13
TC
260 foreach ($this->entries as $entry) {
261 $content->appendChapterTitle($entry->getTitle());
262 $content->appendParagraph($entry->getContent());
263 $content->appendPageBreak();
264 }
265 $mobi->setContentProvider($content);
266
add597ba
JB
267 return Response::create(
268 $mobi->toString(),
269 200,
4094ea47 270 [
add597ba
JB
271 'Accept-Ranges' => 'bytes',
272 'Content-Description' => 'File Transfer',
273 'Content-type' => 'application/x-mobipocket-ebook',
dac93644 274 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.mobi"',
add597ba 275 'Content-Transfer-Encoding' => 'binary',
4094ea47 276 ]
f898102c 277 );
03690d13
TC
278 }
279
add597ba
JB
280 /**
281 * Use TCPDF to dump a .pdf file.
4094ea47
JB
282 *
283 * @return Response
add597ba 284 */
8f336fda 285 private function producePdf()
03690d13
TC
286 {
287 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
288
289 /*
290 * Book metadata
291 */
03690d13 292 $pdf->SetCreator(PDF_CREATOR);
07320a2b 293 $pdf->SetAuthor($this->author);
03690d13
TC
294 $pdf->SetTitle($this->title);
295 $pdf->SetSubject('Articles via wallabag');
296 $pdf->SetKeywords('wallabag');
297
03690d13
TC
298 /*
299 * Adding actual entries
300 */
03690d13 301 foreach ($this->entries as $entry) {
b0458874
JB
302 foreach ($entry->getTags() as $tag) {
303 $pdf->SetKeywords($tag->getLabel());
03690d13
TC
304 }
305
ad5ef8bc 306 $publishedBy = $entry->getPublishedBy();
5e1f2776 307 $authors = $this->translator->trans('export.unknown');
ad5ef8bc
KD
308 if (!empty($publishedBy)) {
309 $authors = implode(',', $publishedBy);
ad5ef8bc
KD
310 }
311
312 $pdf->addPage();
313 $html = '<h1>' . $entry->getTitle() . '</h1>' .
314 '<dl>' .
315 '<dt>' . $this->translator->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
316 '<dt>' . $this->translator->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
317 '<dt>' . $this->translator->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
318 '<dt>' . $this->translator->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
319 '</dl>';
320 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
321
03690d13 322 $pdf->AddPage();
15a6402f 323 $html = '<h1>' . $entry->getTitle() . '</h1>';
03690d13 324 $html .= $entry->getContent();
add597ba 325
03690d13
TC
326 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
327 }
328
ad5ef8bc
KD
329 /*
330 * Last page
331 */
332 $pdf->AddPage();
333 $html = $this->getExportInformation('tcpdf');
334
335 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
336
03690d13
TC
337 // set image scale factor
338 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
339
add597ba
JB
340 return Response::create(
341 $pdf->Output('', 'S'),
342 200,
4094ea47 343 [
add597ba
JB
344 'Content-Description' => 'File Transfer',
345 'Content-type' => 'application/pdf',
dac93644 346 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.pdf"',
add597ba 347 'Content-Transfer-Encoding' => 'binary',
4094ea47 348 ]
f898102c 349 );
03690d13
TC
350 }
351
add597ba
JB
352 /**
353 * Inspired from CsvFileDumper.
4094ea47
JB
354 *
355 * @return Response
add597ba 356 */
8f336fda 357 private function produceCsv()
03690d13 358 {
add597ba
JB
359 $delimiter = ';';
360 $enclosure = '"';
2a1ceb67 361 $handle = fopen('php://memory', 'b+r');
03690d13 362
9401696f 363 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
03690d13 364
03690d13 365 foreach ($this->entries as $entry) {
add597ba
JB
366 fputcsv(
367 $handle,
4094ea47 368 [
add597ba
JB
369 $entry->getTitle(),
370 $entry->getURL(),
cceca9ea 371 // remove new line to avoid crazy results
4094ea47 372 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
add597ba
JB
373 implode(', ', $entry->getTags()->toArray()),
374 $entry->getMimetype(),
375 $entry->getLanguage(),
9401696f 376 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
4094ea47 377 ],
add597ba
JB
378 $delimiter,
379 $enclosure
380 );
381 }
382
383 rewind($handle);
384 $output = stream_get_contents($handle);
385 fclose($handle);
386
387 return Response::create(
388 $output,
389 200,
4094ea47 390 [
add597ba 391 'Content-type' => 'application/csv',
dac93644 392 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.csv"',
add597ba 393 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 394 ]
f898102c 395 );
add597ba
JB
396 }
397
4094ea47
JB
398 /**
399 * Dump a JSON file.
400 *
401 * @return Response
402 */
8f336fda 403 private function produceJson()
b3cc1a14 404 {
b3cc1a14 405 return Response::create(
8ac95cbf 406 $this->prepareSerializingContent('json'),
b3cc1a14 407 200,
4094ea47 408 [
b3cc1a14 409 'Content-type' => 'application/json',
dac93644 410 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.json"',
b3cc1a14 411 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 412 ]
f898102c 413 );
b3cc1a14
TC
414 }
415
4094ea47
JB
416 /**
417 * Dump a XML file.
418 *
419 * @return Response
420 */
8f336fda 421 private function produceXml()
b3cc1a14 422 {
b3cc1a14 423 return Response::create(
8ac95cbf 424 $this->prepareSerializingContent('xml'),
b3cc1a14 425 200,
4094ea47 426 [
b3cc1a14 427 'Content-type' => 'application/xml',
dac93644 428 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.xml"',
b3cc1a14 429 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 430 ]
f898102c 431 );
b3cc1a14 432 }
8ac95cbf 433
4094ea47
JB
434 /**
435 * Dump a TXT file.
436 *
437 * @return Response
438 */
8f336fda 439 private function produceTxt()
6c08fb68
TC
440 {
441 $content = '';
d3f31ec4 442 $bar = str_repeat('=', 100);
6c08fb68 443 foreach ($this->entries as $entry) {
15a6402f 444 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
c6608783
NH
445 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
446 $content .= $html->getText();
6c08fb68 447 }
d3f31ec4 448
6c08fb68
TC
449 return Response::create(
450 $content,
451 200,
4094ea47 452 [
6c08fb68 453 'Content-type' => 'text/plain',
dac93644 454 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.txt"',
6c08fb68 455 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 456 ]
f898102c 457 );
6c08fb68
TC
458 }
459
b3cc1a14
TC
460 /**
461 * Return a Serializer object for producing processes that need it (JSON & XML).
462 *
0e49487b
JB
463 * @param string $format
464 *
52b84c11 465 * @return string
b3cc1a14 466 */
8ac95cbf 467 private function prepareSerializingContent($format)
b3cc1a14 468 {
268e9e72 469 $serializer = SerializerBuilder::create()->build();
b3cc1a14 470
cceca9ea
JB
471 return $serializer->serialize(
472 $this->entries,
473 $format,
4094ea47 474 SerializationContext::create()->setGroups(['entries_for_user'])
cceca9ea 475 );
b3cc1a14
TC
476 }
477
add597ba
JB
478 /**
479 * Return a kind of footer / information for the epub.
480 *
481 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
482 *
483 * @return string
484 */
485 private function getExportInformation($type)
486 {
b1428a1c
NL
487 $info = $this->translator->trans('export.footer_template', [
488 '%method%' => $type,
489 ]);
add597ba
JB
490
491 if ('tcpdf' === $type) {
15a6402f 492 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
03690d13 493 }
add597ba
JB
494
495 return str_replace('%IMAGE%', '', $info);
03690d13 496 }
dac93644
KD
497
498 /**
499 * Return a sanitized version of the title by applying translit iconv
500 * and removing non alphanumeric characters, - and space.
501 *
502 * @return string Sanitized filename
503 */
504 private function getSanitizedFilename()
505 {
506 return preg_replace('/[^A-Za-z0-9\- \']/', '', iconv('utf-8', 'us-ascii//TRANSLIT', $this->title));
507 }
03690d13 508}