]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/EntriesExport.php
Update md5 checksum for 2.0.8 in documentation
[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>
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
TC
165
166 $chapter = $content_start.$entry->getContent().$bookEnd;
167 $book->addChapter($entry->getTitle(), htmlspecialchars($entry->getTitle()).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
168 }
add597ba
JB
169
170 return Response::create(
171 $book->getBook(),
172 200,
4094ea47 173 [
add597ba
JB
174 'Content-Description' => 'File Transfer',
175 'Content-type' => 'application/epub+zip',
176 'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"',
177 'Content-Transfer-Encoding' => 'binary',
4094ea47 178 ]
f898102c 179 );
03690d13
TC
180 }
181
add597ba
JB
182 /**
183 * Use PHPMobi to dump a .mobi file.
4094ea47
JB
184 *
185 * @return Response
add597ba 186 */
03690d13
TC
187 private function produceMobi()
188 {
189 $mobi = new \MOBI();
190 $content = new \MOBIFile();
191
192 /*
193 * Book metadata
194 */
03690d13
TC
195 $content->set('title', $this->title);
196 $content->set('author', implode($this->authors));
197 $content->set('subject', $this->title);
198
199 /*
200 * Front page
201 */
add597ba
JB
202 $content->appendParagraph($this->getExportInformation('PHPMobi'));
203 if (file_exists($this->logoPath)) {
204 $content->appendImage(imagecreatefrompng($this->logoPath));
205 }
03690d13
TC
206 $content->appendPageBreak();
207
208 /*
209 * Adding actual entries
210 */
03690d13
TC
211 foreach ($this->entries as $entry) {
212 $content->appendChapterTitle($entry->getTitle());
213 $content->appendParagraph($entry->getContent());
214 $content->appendPageBreak();
215 }
216 $mobi->setContentProvider($content);
217
218 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
219 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
220
add597ba
JB
221 return Response::create(
222 $mobi->toString(),
223 200,
4094ea47 224 [
add597ba
JB
225 'Accept-Ranges' => 'bytes',
226 'Content-Description' => 'File Transfer',
227 'Content-type' => 'application/x-mobipocket-ebook',
228 'Content-Disposition' => 'attachment; filename="'.$this->title.'.mobi"',
229 'Content-Transfer-Encoding' => 'binary',
4094ea47 230 ]
f898102c 231 );
03690d13
TC
232 }
233
add597ba
JB
234 /**
235 * Use TCPDF to dump a .pdf file.
4094ea47
JB
236 *
237 * @return Response
add597ba 238 */
8f336fda 239 private function producePdf()
03690d13
TC
240 {
241 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
242
243 /*
244 * Book metadata
245 */
03690d13
TC
246 $pdf->SetCreator(PDF_CREATOR);
247 $pdf->SetAuthor('wallabag');
248 $pdf->SetTitle($this->title);
249 $pdf->SetSubject('Articles via wallabag');
250 $pdf->SetKeywords('wallabag');
251
252 /*
253 * Front page
254 */
03690d13 255 $pdf->AddPage();
add597ba 256 $intro = '<h1>'.$this->title.'</h1>'.$this->getExportInformation('tcpdf');
03690d13
TC
257
258 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
259
260 /*
261 * Adding actual entries
262 */
03690d13
TC
263 foreach ($this->entries as $entry) {
264 foreach ($this->tags as $tag) {
265 $pdf->SetKeywords($tag['value']);
266 }
267
268 $pdf->AddPage();
269 $html = '<h1>'.$entry->getTitle().'</h1>';
270 $html .= $entry->getContent();
add597ba 271
03690d13
TC
272 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
273 }
274
275 // set image scale factor
276 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
277
add597ba
JB
278 return Response::create(
279 $pdf->Output('', 'S'),
280 200,
4094ea47 281 [
add597ba
JB
282 'Content-Description' => 'File Transfer',
283 'Content-type' => 'application/pdf',
284 'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"',
285 'Content-Transfer-Encoding' => 'binary',
4094ea47 286 ]
f898102c 287 );
03690d13
TC
288 }
289
add597ba
JB
290 /**
291 * Inspired from CsvFileDumper.
4094ea47
JB
292 *
293 * @return Response
add597ba 294 */
8f336fda 295 private function produceCsv()
03690d13 296 {
add597ba
JB
297 $delimiter = ';';
298 $enclosure = '"';
299 $handle = fopen('php://memory', 'rb+');
03690d13 300
4094ea47 301 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language'], $delimiter, $enclosure);
03690d13 302
03690d13 303 foreach ($this->entries as $entry) {
add597ba
JB
304 fputcsv(
305 $handle,
4094ea47 306 [
add597ba
JB
307 $entry->getTitle(),
308 $entry->getURL(),
cceca9ea 309 // remove new line to avoid crazy results
4094ea47 310 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
add597ba
JB
311 implode(', ', $entry->getTags()->toArray()),
312 $entry->getMimetype(),
313 $entry->getLanguage(),
4094ea47 314 ],
add597ba
JB
315 $delimiter,
316 $enclosure
317 );
318 }
319
320 rewind($handle);
321 $output = stream_get_contents($handle);
322 fclose($handle);
323
324 return Response::create(
325 $output,
326 200,
4094ea47 327 [
add597ba
JB
328 'Content-type' => 'application/csv',
329 'Content-Disposition' => 'attachment; filename="'.$this->title.'.csv"',
330 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 331 ]
f898102c 332 );
add597ba
JB
333 }
334
4094ea47
JB
335 /**
336 * Dump a JSON file.
337 *
338 * @return Response
339 */
8f336fda 340 private function produceJson()
b3cc1a14 341 {
b3cc1a14 342 return Response::create(
8ac95cbf 343 $this->prepareSerializingContent('json'),
b3cc1a14 344 200,
4094ea47 345 [
b3cc1a14
TC
346 'Content-type' => 'application/json',
347 'Content-Disposition' => 'attachment; filename="'.$this->title.'.json"',
348 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 349 ]
f898102c 350 );
b3cc1a14
TC
351 }
352
4094ea47
JB
353 /**
354 * Dump a XML file.
355 *
356 * @return Response
357 */
8f336fda 358 private function produceXml()
b3cc1a14 359 {
b3cc1a14 360 return Response::create(
8ac95cbf 361 $this->prepareSerializingContent('xml'),
b3cc1a14 362 200,
4094ea47 363 [
b3cc1a14
TC
364 'Content-type' => 'application/xml',
365 'Content-Disposition' => 'attachment; filename="'.$this->title.'.xml"',
366 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 367 ]
f898102c 368 );
b3cc1a14 369 }
8ac95cbf 370
4094ea47
JB
371 /**
372 * Dump a TXT file.
373 *
374 * @return Response
375 */
8f336fda 376 private function produceTxt()
6c08fb68
TC
377 {
378 $content = '';
d3f31ec4 379 $bar = str_repeat('=', 100);
6c08fb68 380 foreach ($this->entries as $entry) {
d3f31ec4
JB
381 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
382 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
6c08fb68 383 }
d3f31ec4 384
6c08fb68
TC
385 return Response::create(
386 $content,
387 200,
4094ea47 388 [
6c08fb68
TC
389 'Content-type' => 'text/plain',
390 'Content-Disposition' => 'attachment; filename="'.$this->title.'.txt"',
391 'Content-Transfer-Encoding' => 'UTF-8',
4094ea47 392 ]
f898102c 393 );
6c08fb68
TC
394 }
395
b3cc1a14
TC
396 /**
397 * Return a Serializer object for producing processes that need it (JSON & XML).
398 *
0e49487b
JB
399 * @param string $format
400 *
b3cc1a14
TC
401 * @return Serializer
402 */
8ac95cbf 403 private function prepareSerializingContent($format)
b3cc1a14 404 {
268e9e72 405 $serializer = SerializerBuilder::create()->build();
b3cc1a14 406
cceca9ea
JB
407 return $serializer->serialize(
408 $this->entries,
409 $format,
4094ea47 410 SerializationContext::create()->setGroups(['entries_for_user'])
cceca9ea 411 );
b3cc1a14
TC
412 }
413
add597ba
JB
414 /**
415 * Return a kind of footer / information for the epub.
416 *
417 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
418 *
419 * @return string
420 */
421 private function getExportInformation($type)
422 {
423 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate);
424
425 if ('tcpdf' === $type) {
426 return str_replace('%IMAGE%', '<img src="'.$this->logoPath.'" />', $info);
03690d13 427 }
add597ba
JB
428
429 return str_replace('%IMAGE%', '', $info);
03690d13
TC
430 }
431}