]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/EntriesExport.php
Translated first page of exported article
[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 private $footerTemplate = '<div style="text-align:center;">
27 <p>Produced by wallabag with %EXPORT_METHOD%</p>
28 <p>Please open <a href="https://github.com/wallabag/wallabag/issues">an issue</a> if you have trouble with the display of this E-Book on your device.</p>
29 </div>';
30
31 /**
32 * @param string $wallabagUrl Wallabag instance url
33 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
34 */
35 public function __construct($wallabagUrl, $logoPath, TranslatorInterface $translator)
36 {
37 $this->wallabagUrl = $wallabagUrl;
38 $this->logoPath = $logoPath;
39 $this->translator = $translator;
40 }
41
42 /**
43 * Define entries.
44 *
45 * @param array|Entry $entries An array of entries or one entry
46 *
47 * @return EntriesExport
48 */
49 public function setEntries($entries)
50 {
51 if (!is_array($entries)) {
52 $this->language = $entries->getLanguage();
53 $entries = [$entries];
54 }
55
56 $this->entries = $entries;
57
58 return $this;
59 }
60
61 /**
62 * Sets the category of which we want to get articles, or just one entry.
63 *
64 * @param string $method Method to get articles
65 *
66 * @return EntriesExport
67 */
68 public function updateTitle($method)
69 {
70 $this->title = $method . ' articles';
71
72 if ('entry' === $method) {
73 $this->title = $this->entries[0]->getTitle();
74 }
75
76 return $this;
77 }
78
79 /**
80 * Sets the author for one entry or category.
81 *
82 * The publishers are used, or the domain name if empty.
83 *
84 * @param string $method Method to get articles
85 *
86 * @return EntriesExport
87 */
88 public function updateAuthor($method)
89 {
90 if ('entry' !== $method) {
91 $this->author = $method . ' authors';
92
93 return $this;
94 }
95
96 $this->author = $this->entries[0]->getDomainName();
97
98 $publishedBy = $this->entries[0]->getPublishedBy();
99 if (!empty($publishedBy)) {
100 $this->author = implode(', ', $publishedBy);
101 }
102
103 return $this;
104 }
105
106 /**
107 * Sets the output format.
108 *
109 * @param string $format
110 *
111 * @return Response
112 */
113 public function exportAs($format)
114 {
115 $functionName = 'produce' . ucfirst($format);
116 if (method_exists($this, $functionName)) {
117 return $this->$functionName();
118 }
119
120 throw new \InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
121 }
122
123 public function exportJsonData()
124 {
125 return $this->prepareSerializingContent('json');
126 }
127
128 /**
129 * Use PHPePub to dump a .epub file.
130 *
131 * @return Response
132 */
133 private function produceEpub()
134 {
135 /*
136 * Start and End of the book
137 */
138 $content_start =
139 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
140 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
141 . '<head>'
142 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
143 . "<title>wallabag articles book</title>\n"
144 . "</head>\n"
145 . "<body>\n";
146
147 $bookEnd = "</body>\n</html>\n";
148
149 $book = new EPub(EPub::BOOK_VERSION_EPUB3);
150
151 /*
152 * Book metadata
153 */
154
155 $book->setTitle($this->title);
156 // Could also be the ISBN number, prefered for published books, or a UUID.
157 $book->setIdentifier($this->title, EPub::IDENTIFIER_URI);
158 // 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.
159 $book->setLanguage($this->language);
160 $book->setDescription('Some articles saved on my wallabag');
161
162 $book->setAuthor($this->author, $this->author);
163
164 // I hope this is a non existant address :)
165 $book->setPublisher('wallabag', 'wallabag');
166 // Strictly not needed as the book date defaults to time().
167 $book->setDate(time());
168 $book->setSourceURL($this->wallabagUrl);
169
170 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
171 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
172
173 /*
174 * Front page
175 */
176 if (file_exists($this->logoPath)) {
177 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
178 }
179
180 $book->buildTOC();
181
182 /*
183 * Adding actual entries
184 */
185
186 // set tags as subjects
187 foreach ($this->entries as $entry) {
188 foreach ($entry->getTags() as $tag) {
189 $book->setSubject($tag->getLabel());
190 }
191
192 // the reader in Kobo Devices doesn't likes special caracters
193 // in filenames, we limit to A-z/0-9
194 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
195
196 $chapter = $content_start . $entry->getContent() . $bookEnd;
197 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
198 }
199
200 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
201
202 return Response::create(
203 $book->getBook(),
204 200,
205 [
206 'Content-Description' => 'File Transfer',
207 'Content-type' => 'application/epub+zip',
208 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
209 'Content-Transfer-Encoding' => 'binary',
210 ]
211 );
212 }
213
214 /**
215 * Use PHPMobi to dump a .mobi file.
216 *
217 * @return Response
218 */
219 private function produceMobi()
220 {
221 $mobi = new \MOBI();
222 $content = new \MOBIFile();
223
224 /*
225 * Book metadata
226 */
227 $content->set('title', $this->title);
228 $content->set('author', $this->author);
229 $content->set('subject', $this->title);
230
231 /*
232 * Front page
233 */
234 $content->appendParagraph($this->getExportInformation('PHPMobi'));
235 if (file_exists($this->logoPath)) {
236 $content->appendImage(imagecreatefrompng($this->logoPath));
237 }
238 $content->appendPageBreak();
239
240 /*
241 * Adding actual entries
242 */
243 foreach ($this->entries as $entry) {
244 $content->appendChapterTitle($entry->getTitle());
245 $content->appendParagraph($entry->getContent());
246 $content->appendPageBreak();
247 }
248 $mobi->setContentProvider($content);
249
250 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
251 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
252
253 return Response::create(
254 $mobi->toString(),
255 200,
256 [
257 'Accept-Ranges' => 'bytes',
258 'Content-Description' => 'File Transfer',
259 'Content-type' => 'application/x-mobipocket-ebook',
260 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
261 'Content-Transfer-Encoding' => 'binary',
262 ]
263 );
264 }
265
266 /**
267 * Use TCPDF to dump a .pdf file.
268 *
269 * @return Response
270 */
271 private function producePdf()
272 {
273 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
274
275 /*
276 * Book metadata
277 */
278 $pdf->SetCreator(PDF_CREATOR);
279 $pdf->SetAuthor($this->author);
280 $pdf->SetTitle($this->title);
281 $pdf->SetSubject('Articles via wallabag');
282 $pdf->SetKeywords('wallabag');
283
284 /*
285 * Front page
286 */
287 $pdf->AddPage();
288 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
289
290 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
291
292 /*
293 * Adding actual entries
294 */
295 foreach ($this->entries as $entry) {
296 foreach ($entry->getTags() as $tag) {
297 $pdf->SetKeywords($tag->getLabel());
298 }
299
300 $pdf->AddPage();
301 $html = '<h1>' . $entry->getTitle() . '</h1>';
302 $html .= $entry->getContent();
303
304 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
305 }
306
307 // set image scale factor
308 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
309
310 return Response::create(
311 $pdf->Output('', 'S'),
312 200,
313 [
314 'Content-Description' => 'File Transfer',
315 'Content-type' => 'application/pdf',
316 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
317 'Content-Transfer-Encoding' => 'binary',
318 ]
319 );
320 }
321
322 /**
323 * Inspired from CsvFileDumper.
324 *
325 * @return Response
326 */
327 private function produceCsv()
328 {
329 $delimiter = ';';
330 $enclosure = '"';
331 $handle = fopen('php://memory', 'rb+');
332
333 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
334
335 foreach ($this->entries as $entry) {
336 fputcsv(
337 $handle,
338 [
339 $entry->getTitle(),
340 $entry->getURL(),
341 // remove new line to avoid crazy results
342 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
343 implode(', ', $entry->getTags()->toArray()),
344 $entry->getMimetype(),
345 $entry->getLanguage(),
346 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
347 ],
348 $delimiter,
349 $enclosure
350 );
351 }
352
353 rewind($handle);
354 $output = stream_get_contents($handle);
355 fclose($handle);
356
357 return Response::create(
358 $output,
359 200,
360 [
361 'Content-type' => 'application/csv',
362 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
363 'Content-Transfer-Encoding' => 'UTF-8',
364 ]
365 );
366 }
367
368 /**
369 * Dump a JSON file.
370 *
371 * @return Response
372 */
373 private function produceJson()
374 {
375 return Response::create(
376 $this->prepareSerializingContent('json'),
377 200,
378 [
379 'Content-type' => 'application/json',
380 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
381 'Content-Transfer-Encoding' => 'UTF-8',
382 ]
383 );
384 }
385
386 /**
387 * Dump a XML file.
388 *
389 * @return Response
390 */
391 private function produceXml()
392 {
393 return Response::create(
394 $this->prepareSerializingContent('xml'),
395 200,
396 [
397 'Content-type' => 'application/xml',
398 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
399 'Content-Transfer-Encoding' => 'UTF-8',
400 ]
401 );
402 }
403
404 /**
405 * Dump a TXT file.
406 *
407 * @return Response
408 */
409 private function produceTxt()
410 {
411 $content = '';
412 $bar = str_repeat('=', 100);
413 foreach ($this->entries as $entry) {
414 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
415 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
416 $content .= $html->getText();
417 }
418
419 return Response::create(
420 $content,
421 200,
422 [
423 'Content-type' => 'text/plain',
424 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
425 'Content-Transfer-Encoding' => 'UTF-8',
426 ]
427 );
428 }
429
430 /**
431 * Return a Serializer object for producing processes that need it (JSON & XML).
432 *
433 * @param string $format
434 *
435 * @return string
436 */
437 private function prepareSerializingContent($format)
438 {
439 $serializer = SerializerBuilder::create()->build();
440
441 return $serializer->serialize(
442 $this->entries,
443 $format,
444 SerializationContext::create()->setGroups(['entries_for_user'])
445 );
446 }
447
448 /**
449 * Return a kind of footer / information for the epub.
450 *
451 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
452 *
453 * @return string
454 */
455 private function getExportInformation($type)
456 {
457 $info = $this->translator->trans('export.footer_template', [
458 '%method%' => $type,
459 ]);
460
461 if ('tcpdf' === $type) {
462 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
463 }
464
465 return str_replace('%IMAGE%', '', $info);
466 }
467 }