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