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