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