]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/EntriesExport.php
add a title page
[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 = $method . ' 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 // 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');
158
159 $book->setAuthor($this->author, $this->author);
160
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);
166
167 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
168 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
169
170 /*
171 * Front page
172 */
173 if (file_exists($this->logoPath)) {
174 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
175 }
176
177 $book->buildTOC();
178
179 /*
180 * Adding actual entries
181 */
182
183 // set tags as subjects
184 foreach ($this->entries as $entry) {
185 foreach ($entry->getTags() as $tag) {
186 $book->setSubject($tag->getLabel());
187 }
188
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
193 $titlepage = "<h1>".$entry->getTitle()."</h1>";
194 $chapter = $content_start . $titlepage . $entry->getContent() . $bookEnd;
195 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
196 }
197
198 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
199
200 return Response::create(
201 $book->getBook(),
202 200,
203 [
204 'Content-Description' => 'File Transfer',
205 'Content-type' => 'application/epub+zip',
206 'Content-Disposition' => 'attachment; filename="' . $this->title . '.epub"',
207 'Content-Transfer-Encoding' => 'binary',
208 ]
209 );
210 }
211
212 /**
213 * Use PHPMobi to dump a .mobi file.
214 *
215 * @return Response
216 */
217 private function produceMobi()
218 {
219 $mobi = new \MOBI();
220 $content = new \MOBIFile();
221
222 /*
223 * Book metadata
224 */
225 $content->set('title', $this->title);
226 $content->set('author', $this->author);
227 $content->set('subject', $this->title);
228
229 /*
230 * Front page
231 */
232 $content->appendParagraph($this->getExportInformation('PHPMobi'));
233 if (file_exists($this->logoPath)) {
234 $content->appendImage(imagecreatefrompng($this->logoPath));
235 }
236 $content->appendPageBreak();
237
238 /*
239 * Adding actual entries
240 */
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
251 return Response::create(
252 $mobi->toString(),
253 200,
254 [
255 'Accept-Ranges' => 'bytes',
256 'Content-Description' => 'File Transfer',
257 'Content-type' => 'application/x-mobipocket-ebook',
258 'Content-Disposition' => 'attachment; filename="' . $this->title . '.mobi"',
259 'Content-Transfer-Encoding' => 'binary',
260 ]
261 );
262 }
263
264 /**
265 * Use TCPDF to dump a .pdf file.
266 *
267 * @return Response
268 */
269 private function producePdf()
270 {
271 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
272
273 /*
274 * Book metadata
275 */
276 $pdf->SetCreator(PDF_CREATOR);
277 $pdf->SetAuthor($this->author);
278 $pdf->SetTitle($this->title);
279 $pdf->SetSubject('Articles via wallabag');
280 $pdf->SetKeywords('wallabag');
281
282 /*
283 * Front page
284 */
285 $pdf->AddPage();
286 $intro = '<h1>' . $this->title . '</h1>' . $this->getExportInformation('tcpdf');
287
288 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
289
290 /*
291 * Adding actual entries
292 */
293 foreach ($this->entries as $entry) {
294 foreach ($entry->getTags() as $tag) {
295 $pdf->SetKeywords($tag->getLabel());
296 }
297
298 $pdf->AddPage();
299 $html = '<h1>' . $entry->getTitle() . '</h1>';
300 $html .= $entry->getContent();
301
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
308 return Response::create(
309 $pdf->Output('', 'S'),
310 200,
311 [
312 'Content-Description' => 'File Transfer',
313 'Content-type' => 'application/pdf',
314 'Content-Disposition' => 'attachment; filename="' . $this->title . '.pdf"',
315 'Content-Transfer-Encoding' => 'binary',
316 ]
317 );
318 }
319
320 /**
321 * Inspired from CsvFileDumper.
322 *
323 * @return Response
324 */
325 private function produceCsv()
326 {
327 $delimiter = ';';
328 $enclosure = '"';
329 $handle = fopen('php://memory', 'rb+');
330
331 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
332
333 foreach ($this->entries as $entry) {
334 fputcsv(
335 $handle,
336 [
337 $entry->getTitle(),
338 $entry->getURL(),
339 // remove new line to avoid crazy results
340 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
341 implode(', ', $entry->getTags()->toArray()),
342 $entry->getMimetype(),
343 $entry->getLanguage(),
344 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
345 ],
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,
358 [
359 'Content-type' => 'application/csv',
360 'Content-Disposition' => 'attachment; filename="' . $this->title . '.csv"',
361 'Content-Transfer-Encoding' => 'UTF-8',
362 ]
363 );
364 }
365
366 /**
367 * Dump a JSON file.
368 *
369 * @return Response
370 */
371 private function produceJson()
372 {
373 return Response::create(
374 $this->prepareSerializingContent('json'),
375 200,
376 [
377 'Content-type' => 'application/json',
378 'Content-Disposition' => 'attachment; filename="' . $this->title . '.json"',
379 'Content-Transfer-Encoding' => 'UTF-8',
380 ]
381 );
382 }
383
384 /**
385 * Dump a XML file.
386 *
387 * @return Response
388 */
389 private function produceXml()
390 {
391 return Response::create(
392 $this->prepareSerializingContent('xml'),
393 200,
394 [
395 'Content-type' => 'application/xml',
396 'Content-Disposition' => 'attachment; filename="' . $this->title . '.xml"',
397 'Content-Transfer-Encoding' => 'UTF-8',
398 ]
399 );
400 }
401
402 /**
403 * Dump a TXT file.
404 *
405 * @return Response
406 */
407 private function produceTxt()
408 {
409 $content = '';
410 $bar = str_repeat('=', 100);
411 foreach ($this->entries as $entry) {
412 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
413 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
414 $content .= $html->getText();
415 }
416
417 return Response::create(
418 $content,
419 200,
420 [
421 'Content-type' => 'text/plain',
422 'Content-Disposition' => 'attachment; filename="' . $this->title . '.txt"',
423 'Content-Transfer-Encoding' => 'UTF-8',
424 ]
425 );
426 }
427
428 /**
429 * Return a Serializer object for producing processes that need it (JSON & XML).
430 *
431 * @param string $format
432 *
433 * @return string
434 */
435 private function prepareSerializingContent($format)
436 {
437 $serializer = SerializerBuilder::create()->build();
438
439 return $serializer->serialize(
440 $this->entries,
441 $format,
442 SerializationContext::create()->setGroups(['entries_for_user'])
443 );
444 }
445
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 {
455 $info = $this->translator->trans('export.footer_template', [
456 '%method%' => $type,
457 ]);
458
459 if ('tcpdf' === $type) {
460 return str_replace('%IMAGE%', '<img src="' . $this->logoPath . '" />', $info);
461 }
462
463 return str_replace('%IMAGE%', '', $info);
464 }
465 }