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