]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/EntriesExport.php
EntriesExport: change authors and title when not single entry export
[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 $titlepage = $content_start . '<h1>' . $entry->getTitle() . '</h1>' . $bookEnd;
192 $book->addChapter("Entry {$i} of {$entryCount}", "{$filename}_cover.html", $titlepage, true, EPub::EXTERNAL_REF_ADD);
193 $chapter = $content_start . $entry->getContent() . $bookEnd;
194
195 $entryIds[] = $entry->getId();
196 $book->addChapter($entry->getTitle(), "{$filename}.html", $chapter, true, EPub::EXTERNAL_REF_ADD);
197 }
198
199 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
200
201 // Could also be the ISBN number, prefered for published books, or a UUID.
202 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl, implode(',', $entryIds)));
203 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub::IDENTIFIER_URI);
204
205 return Response::create(
206 $book->getBook(),
207 200,
208 [
209 'Content-Description' => 'File Transfer',
210 'Content-type' => 'application/epub+zip',
211 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
212 'Content-Transfer-Encoding' => 'binary',
213 ]
214 );
215 }
216
217 /**
218 * Use PHPMobi to dump a .mobi file.
219 *
220 * @return Response
221 */
222 private function produceMobi()
223 {
224 $mobi = new \MOBI();
225 $content = new \MOBIFile();
226
227 /*
228 * Book metadata
229 */
230 $content->set('title', $this->title);
231 $content->set('author', $this->author);
232 $content->set('subject', $this->title);
233
234 /*
235 * Front page
236 */
237 $content->appendParagraph($this->getExportInformation('PHPMobi'));
238 if (file_exists($this->logoPath)) {
239 $content->appendImage(imagecreatefrompng($this->logoPath));
240 }
241 $content->appendPageBreak();
242
243 /*
244 * Adding actual entries
245 */
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
256 return Response::create(
257 $mobi->toString(),
258 200,
259 [
260 'Accept-Ranges' => 'bytes',
261 'Content-Description' => 'File Transfer',
262 'Content-type' => 'application/x-mobipocket-ebook',
263 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
264 'Content-Transfer-Encoding' => 'binary',
265 ]
266 );
267 }
268
269 /**
270 * Use TCPDF to dump a .pdf file.
271 *
272 * @return Response
273 */
274 private function producePdf()
275 {
276 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
277
278 /*
279 * Book metadata
280 */
281 $pdf->SetCreator(PDF_CREATOR);
282 $pdf->SetAuthor($this->author);
283 $pdf->SetTitle($this->title);
284 $pdf->SetSubject('Articles via wallabag');
285 $pdf->SetKeywords('wallabag');
286
287 /*
288 * Front page
289 */
290 $pdf->AddPage();
291 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
292
293 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
294
295 /*
296 * Adding actual entries
297 */
298 foreach ($this->entries as $entry) {
299 foreach ($entry->getTags() as $tag) {
300 $pdf->SetKeywords($tag->getLabel());
301 }
302
303 $pdf->AddPage();
304 $html = '<h1>' . $entry->getTitle() . '</h1>';
305 $html .= $entry->getContent();
306
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
313 return Response::create(
314 $pdf->Output('', 'S'),
315 200,
316 [
317 'Content-Description' => 'File Transfer',
318 'Content-type' => 'application/pdf',
319 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
320 'Content-Transfer-Encoding' => 'binary',
321 ]
322 );
323 }
324
325 /**
326 * Inspired from CsvFileDumper.
327 *
328 * @return Response
329 */
330 private function produceCsv()
331 {
332 $delimiter = ';';
333 $enclosure = '"';
334 $handle = fopen('php://memory', 'b+r');
335
336 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
337
338 foreach ($this->entries as $entry) {
339 fputcsv(
340 $handle,
341 [
342 $entry->getTitle(),
343 $entry->getURL(),
344 // remove new line to avoid crazy results
345 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
346 implode(', ', $entry->getTags()->toArray()),
347 $entry->getMimetype(),
348 $entry->getLanguage(),
349 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
350 ],
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,
363 [
364 'Content-type' => 'application/csv',
365 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
366 'Content-Transfer-Encoding' => 'UTF-8',
367 ]
368 );
369 }
370
371 /**
372 * Dump a JSON file.
373 *
374 * @return Response
375 */
376 private function produceJson()
377 {
378 return Response::create(
379 $this->prepareSerializingContent('json'),
380 200,
381 [
382 'Content-type' => 'application/json',
383 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
384 'Content-Transfer-Encoding' => 'UTF-8',
385 ]
386 );
387 }
388
389 /**
390 * Dump a XML file.
391 *
392 * @return Response
393 */
394 private function produceXml()
395 {
396 return Response::create(
397 $this->prepareSerializingContent('xml'),
398 200,
399 [
400 'Content-type' => 'application/xml',
401 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
402 'Content-Transfer-Encoding' => 'UTF-8',
403 ]
404 );
405 }
406
407 /**
408 * Dump a TXT file.
409 *
410 * @return Response
411 */
412 private function produceTxt()
413 {
414 $content = '';
415 $bar = str_repeat('=', 100);
416 foreach ($this->entries as $entry) {
417 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
418 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
419 $content .= $html->getText();
420 }
421
422 return Response::create(
423 $content,
424 200,
425 [
426 'Content-type' => 'text/plain',
427 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
428 'Content-Transfer-Encoding' => 'UTF-8',
429 ]
430 );
431 }
432
433 /**
434 * Return a Serializer object for producing processes that need it (JSON & XML).
435 *
436 * @param string $format
437 *
438 * @return string
439 */
440 private function prepareSerializingContent($format)
441 {
442 $serializer = SerializerBuilder::create()->build();
443
444 return $serializer->serialize(
445 $this->entries,
446 $format,
447 SerializationContext::create()->setGroups(['entries_for_user'])
448 );
449 }
450
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 {
460 $info = $this->translator->trans('export.footer_template', [
461 '%method%' => $type,
462 ]);
463
464 if ('tcpdf' === $type) {
465 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
466 }
467
468 return str_replace('%IMAGE%', '', $info);
469 }
470 }