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