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