]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/EntriesExport.php
9cde27c68bc041fa5a6c463456943f67c982ee13
[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 = '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 /*
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 $entryCount = \count($this->entries);
177 $i = 0;
178
179 /*
180 * Adding actual entries
181 */
182
183 // set tags as subjects
184 foreach ($this->entries as $entry) {
185 ++$i;
186 foreach ($entry->getTags() as $tag) {
187 $book->setSubject($tag->getLabel());
188 }
189 $filename = sha1($entry->getTitle());
190
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;
207 $book->addChapter("Entry {$i} of {$entryCount}", "{$filename}_cover.html", $titlepage, true, EPub::EXTERNAL_REF_ADD);
208 $chapter = $content_start . $entry->getContent() . $bookEnd;
209
210 $entryIds[] = $entry->getId();
211 $book->addChapter($entry->getTitle(), "{$filename}.html", $chapter, true, EPub::EXTERNAL_REF_ADD);
212 }
213
214 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
215
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
220 return Response::create(
221 $book->getBook(),
222 200,
223 [
224 'Content-Description' => 'File Transfer',
225 'Content-type' => 'application/epub+zip',
226 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
227 'Content-Transfer-Encoding' => 'binary',
228 ]
229 );
230 }
231
232 /**
233 * Use PHPMobi to dump a .mobi file.
234 *
235 * @return Response
236 */
237 private function produceMobi()
238 {
239 $mobi = new \MOBI();
240 $content = new \MOBIFile();
241
242 /*
243 * Book metadata
244 */
245 $content->set('title', $this->title);
246 $content->set('author', $this->author);
247 $content->set('subject', $this->title);
248
249 /*
250 * Front page
251 */
252 $content->appendParagraph($this->getExportInformation('PHPMobi'));
253 if (file_exists($this->logoPath)) {
254 $content->appendImage(imagecreatefrompng($this->logoPath));
255 }
256 $content->appendPageBreak();
257
258 /*
259 * Adding actual entries
260 */
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
271 return Response::create(
272 $mobi->toString(),
273 200,
274 [
275 'Accept-Ranges' => 'bytes',
276 'Content-Description' => 'File Transfer',
277 'Content-type' => 'application/x-mobipocket-ebook',
278 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
279 'Content-Transfer-Encoding' => 'binary',
280 ]
281 );
282 }
283
284 /**
285 * Use TCPDF to dump a .pdf file.
286 *
287 * @return Response
288 */
289 private function producePdf()
290 {
291 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
292
293 /*
294 * Book metadata
295 */
296 $pdf->SetCreator(PDF_CREATOR);
297 $pdf->SetAuthor($this->author);
298 $pdf->SetTitle($this->title);
299 $pdf->SetSubject('Articles via wallabag');
300 $pdf->SetKeywords('wallabag');
301
302 /*
303 * Front page
304 */
305 $pdf->AddPage();
306 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
307
308 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
309
310 /*
311 * Adding actual entries
312 */
313 foreach ($this->entries as $entry) {
314 foreach ($entry->getTags() as $tag) {
315 $pdf->SetKeywords($tag->getLabel());
316 }
317
318 $pdf->AddPage();
319 $html = '<h1>' . $entry->getTitle() . '</h1>';
320 $html .= $entry->getContent();
321
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
328 return Response::create(
329 $pdf->Output('', 'S'),
330 200,
331 [
332 'Content-Description' => 'File Transfer',
333 'Content-type' => 'application/pdf',
334 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
335 'Content-Transfer-Encoding' => 'binary',
336 ]
337 );
338 }
339
340 /**
341 * Inspired from CsvFileDumper.
342 *
343 * @return Response
344 */
345 private function produceCsv()
346 {
347 $delimiter = ';';
348 $enclosure = '"';
349 $handle = fopen('php://memory', 'b+r');
350
351 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
352
353 foreach ($this->entries as $entry) {
354 fputcsv(
355 $handle,
356 [
357 $entry->getTitle(),
358 $entry->getURL(),
359 // remove new line to avoid crazy results
360 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
361 implode(', ', $entry->getTags()->toArray()),
362 $entry->getMimetype(),
363 $entry->getLanguage(),
364 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
365 ],
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,
378 [
379 'Content-type' => 'application/csv',
380 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
381 'Content-Transfer-Encoding' => 'UTF-8',
382 ]
383 );
384 }
385
386 /**
387 * Dump a JSON file.
388 *
389 * @return Response
390 */
391 private function produceJson()
392 {
393 return Response::create(
394 $this->prepareSerializingContent('json'),
395 200,
396 [
397 'Content-type' => 'application/json',
398 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
399 'Content-Transfer-Encoding' => 'UTF-8',
400 ]
401 );
402 }
403
404 /**
405 * Dump a XML file.
406 *
407 * @return Response
408 */
409 private function produceXml()
410 {
411 return Response::create(
412 $this->prepareSerializingContent('xml'),
413 200,
414 [
415 'Content-type' => 'application/xml',
416 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
417 'Content-Transfer-Encoding' => 'UTF-8',
418 ]
419 );
420 }
421
422 /**
423 * Dump a TXT file.
424 *
425 * @return Response
426 */
427 private function produceTxt()
428 {
429 $content = '';
430 $bar = str_repeat('=', 100);
431 foreach ($this->entries as $entry) {
432 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
433 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
434 $content .= $html->getText();
435 }
436
437 return Response::create(
438 $content,
439 200,
440 [
441 'Content-type' => 'text/plain',
442 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
443 'Content-Transfer-Encoding' => 'UTF-8',
444 ]
445 );
446 }
447
448 /**
449 * Return a Serializer object for producing processes that need it (JSON & XML).
450 *
451 * @param string $format
452 *
453 * @return string
454 */
455 private function prepareSerializingContent($format)
456 {
457 $serializer = SerializerBuilder::create()->build();
458
459 return $serializer->serialize(
460 $this->entries,
461 $format,
462 SerializationContext::create()->setGroups(['entries_for_user'])
463 );
464 }
465
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 {
475 $info = $this->translator->trans('export.footer_template', [
476 '%method%' => $type,
477 ]);
478
479 if ('tcpdf' === $type) {
480 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
481 }
482
483 return str_replace('%IMAGE%', '', $info);
484 }
485 }