]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/EntriesExport.php
EntriesExport/epub: replace epub identifier with unique urn
[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) {
15a6402f 88 $this->author = $method . ' 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
KD
175 $entryIds = [];
176
03690d13
TC
177 /*
178 * Adding actual entries
179 */
180
add597ba
JB
181 // set tags as subjects
182 foreach ($this->entries as $entry) {
b0458874
JB
183 foreach ($entry->getTags() as $tag) {
184 $book->setSubject($tag->getLabel());
add597ba 185 }
03690d13 186
45d94a98
ÉG
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
15a6402f 191 $titlepage = $content_start . '<h1>' . $entry->getTitle() . '</h1>' . $this->getExportInformation('PHPePub') . $bookEnd;
385e6516 192 $book->addChapter('Title', 'Title.html', $titlepage, true, EPub::EXTERNAL_REF_ADD);
15a6402f
JB
193 $chapter = $content_start . $entry->getContent() . $bookEnd;
194 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
bf22266a
KD
195
196 $entryIds[] = $entry->getId();
03690d13 197 }
add597ba 198
bf22266a
KD
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
c779373f 203 $book->buildTOC();
1b70990b 204
add597ba
JB
205 return Response::create(
206 $book->getBook(),
207 200,
4094ea47 208 [
add597ba
JB
209 'Content-Description' => 'File Transfer',
210 'Content-type' => 'application/epub+zip',
15a6402f 211 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
add597ba 212 'Content-Transfer-Encoding' => 'binary',
4094ea47 213 ]
f898102c 214 );
03690d13
TC
215 }
216
add597ba
JB
217 /**
218 * Use PHPMobi to dump a .mobi file.
4094ea47
JB
219 *
220 * @return Response
add597ba 221 */
03690d13
TC
222 private function produceMobi()
223 {
224 $mobi = new \MOBI();
225 $content = new \MOBIFile();
226
227 /*
228 * Book metadata
229 */
03690d13 230 $content->set('title', $this->title);
07320a2b 231 $content->set('author', $this->author);
03690d13
TC
232 $content->set('subject', $this->title);
233
234 /*
235 * Front page
236 */
add597ba
JB
237 $content->appendParagraph($this->getExportInformation('PHPMobi'));
238 if (file_exists($this->logoPath)) {
239 $content->appendImage(imagecreatefrompng($this->logoPath));
240 }
03690d13
TC
241 $content->appendPageBreak();
242
243 /*
244 * Adding actual entries
245 */
03690d13
TC
246 foreach ($this->entries as $entry) {
247 $content->appendChapterTitle($entry->getTitle());
248 $content->appendParagraph($entry->getContent());
249 $content->appendPageBreak();
250 }
251 $mobi->setContentProvider($content);
252
253 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
254 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
255
add597ba
JB
256 return Response::create(
257 $mobi->toString(),
258 200,
4094ea47 259 [
add597ba
JB
260 'Accept-Ranges' => 'bytes',
261 'Content-Description' => 'File Transfer',
262 'Content-type' => 'application/x-mobipocket-ebook',
15a6402f 263 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
add597ba 264 'Content-Transfer-Encoding' => 'binary',
4094ea47 265 ]
f898102c 266 );
03690d13
TC
267 }
268
add597ba
JB
269 /**
270 * Use TCPDF to dump a .pdf file.
4094ea47
JB
271 *
272 * @return Response
add597ba 273 */
8f336fda 274 private function producePdf()
03690d13
TC
275 {
276 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
277
278 /*
279 * Book metadata
280 */
03690d13 281 $pdf->SetCreator(PDF_CREATOR);
07320a2b 282 $pdf->SetAuthor($this->author);
03690d13
TC
283 $pdf->SetTitle($this->title);
284 $pdf->SetSubject('Articles via wallabag');
285 $pdf->SetKeywords('wallabag');
286
287 /*
288 * Front page
289 */
03690d13 290 $pdf->AddPage();
15a6402f 291 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
03690d13
TC
292
293 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
294
295 /*
296 * Adding actual entries
297 */
03690d13 298 foreach ($this->entries as $entry) {
b0458874
JB
299 foreach ($entry->getTags() as $tag) {
300 $pdf->SetKeywords($tag->getLabel());
03690d13
TC
301 }
302
303 $pdf->AddPage();
15a6402f 304 $html = '<h1>' . $entry->getTitle() . '</h1>';
03690d13 305 $html .= $entry->getContent();
add597ba 306
03690d13
TC
307 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
308 }
309
310 // set image scale factor
311 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
312
add597ba
JB
313 return Response::create(
314 $pdf->Output('', 'S'),
315 200,
4094ea47 316 [
add597ba
JB
317 'Content-Description' => 'File Transfer',
318 'Content-type' => 'application/pdf',
15a6402f 319 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
add597ba 320 'Content-Transfer-Encoding' => 'binary',
4094ea47 321 ]
f898102c 322 );
03690d13
TC
323 }
324
add597ba
JB
325 /**
326 * Inspired from CsvFileDumper.
4094ea47
JB
327 *
328 * @return Response
add597ba 329 */
8f336fda 330 private function produceCsv()
03690d13 331 {
add597ba
JB
332 $delimiter = ';';
333 $enclosure = '"';
2a1ceb67 334 $handle = fopen('php://memory', 'b+r');
03690d13 335
9401696f 336 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
03690d13 337
03690d13 338 foreach ($this->entries as $entry) {
add597ba
JB
339 fputcsv(
340 $handle,
4094ea47 341 [
add597ba
JB
342 $entry->getTitle(),
343 $entry->getURL(),
cceca9ea 344 // remove new line to avoid crazy results
4094ea47 345 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
add597ba
JB
346 implode(', ', $entry->getTags()->toArray()),
347 $entry->getMimetype(),
348 $entry->getLanguage(),
9401696f 349 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
4094ea47 350 ],
add597ba
JB
351 $delimiter,
352 $enclosure
353 );
354 }
355
356 rewind($handle);
357 $output = stream_get_contents($handle);
358 fclose($handle);
359
360 return Response::create(
361 $output,
362 200,
4094ea47 363 [
add597ba 364 'Content-type' => 'application/csv',
15a6402f 365 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
add597ba 366 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 367 ]
f898102c 368 );
add597ba
JB
369 }
370
4094ea47
JB
371 /**
372 * Dump a JSON file.
373 *
374 * @return Response
375 */
8f336fda 376 private function produceJson()
b3cc1a14 377 {
b3cc1a14 378 return Response::create(
8ac95cbf 379 $this->prepareSerializingContent('json'),
b3cc1a14 380 200,
4094ea47 381 [
b3cc1a14 382 'Content-type' => 'application/json',
15a6402f 383 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
b3cc1a14 384 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 385 ]
f898102c 386 );
b3cc1a14
TC
387 }
388
4094ea47
JB
389 /**
390 * Dump a XML file.
391 *
392 * @return Response
393 */
8f336fda 394 private function produceXml()
b3cc1a14 395 {
b3cc1a14 396 return Response::create(
8ac95cbf 397 $this->prepareSerializingContent('xml'),
b3cc1a14 398 200,
4094ea47 399 [
b3cc1a14 400 'Content-type' => 'application/xml',
15a6402f 401 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
b3cc1a14 402 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 403 ]
f898102c 404 );
b3cc1a14 405 }
8ac95cbf 406
4094ea47
JB
407 /**
408 * Dump a TXT file.
409 *
410 * @return Response
411 */
8f336fda 412 private function produceTxt()
6c08fb68
TC
413 {
414 $content = '';
d3f31ec4 415 $bar = str_repeat('=', 100);
6c08fb68 416 foreach ($this->entries as $entry) {
15a6402f 417 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
c6608783
NH
418 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
419 $content .= $html->getText();
6c08fb68 420 }
d3f31ec4 421
6c08fb68
TC
422 return Response::create(
423 $content,
424 200,
4094ea47 425 [
6c08fb68 426 'Content-type' => 'text/plain',
15a6402f 427 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
6c08fb68 428 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 429 ]
f898102c 430 );
6c08fb68
TC
431 }
432
b3cc1a14
TC
433 /**
434 * Return a Serializer object for producing processes that need it (JSON & XML).
435 *
0e49487b
JB
436 * @param string $format
437 *
52b84c11 438 * @return string
b3cc1a14 439 */
8ac95cbf 440 private function prepareSerializingContent($format)
b3cc1a14 441 {
268e9e72 442 $serializer = SerializerBuilder::create()->build();
b3cc1a14 443
cceca9ea
JB
444 return $serializer->serialize(
445 $this->entries,
446 $format,
4094ea47 447 SerializationContext::create()->setGroups(['entries_for_user'])
cceca9ea 448 );
b3cc1a14
TC
449 }
450
add597ba
JB
451 /**
452 * Return a kind of footer / information for the epub.
453 *
454 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
455 *
456 * @return string
457 */
458 private function getExportInformation($type)
459 {
b1428a1c
NL
460 $info = $this->translator->trans('export.footer_template', [
461 '%method%' => $type,
462 ]);
add597ba
JB
463
464 if ('tcpdf' === $type) {
15a6402f 465 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
03690d13 466 }
add597ba
JB
467
468 return str_replace('%IMAGE%', '', $info);
03690d13
TC
469 }
470}