]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/EntriesExport.php
Merge pull request #2518 from wallabag/docs-dev-3rd-party-by-strubbl
[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 = '';
add597ba
JB
24 private $footerTemplate = '<div style="text-align:center;">
25 <p>Produced by wallabag with %EXPORT_METHOD%</p>
26 <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 27 </div>';
03690d13 28
add597ba 29 /**
63e40f2d 30 * @param Config $craueConfig CraueConfig instance to get wallabag instance url from database
add597ba
JB
31 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
32 */
63e40f2d 33 public function __construct(Config $craueConfig, $logoPath)
03690d13 34 {
63e40f2d 35 $this->wallabagUrl = $craueConfig->get('wallabag_url');
add597ba
JB
36 $this->logoPath = $logoPath;
37 }
38
39 /**
40 * Define entries.
41 *
42 * @param array|Entry $entries An array of entries or one entry
4094ea47
JB
43 *
44 * @return EntriesExport
add597ba
JB
45 */
46 public function setEntries($entries)
47 {
48 if (!is_array($entries)) {
49 $this->language = $entries->getLanguage();
4094ea47 50 $entries = [$entries];
add597ba
JB
51 }
52
03690d13
TC
53 $this->entries = $entries;
54
add597ba 55 return $this;
03690d13
TC
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
4094ea47
JB
62 *
63 * @return EntriesExport
03690d13 64 */
add597ba 65 public function updateTitle($method)
03690d13 66 {
add597ba
JB
67 $this->title = $method.' articles';
68
69 if ('entry' === $method) {
70 $this->title = $this->entries[0]->getTitle();
03690d13 71 }
add597ba
JB
72
73 return $this;
03690d13
TC
74 }
75
76 /**
77 * Sets the output format.
78 *
79 * @param string $format
4094ea47
JB
80 *
81 * @return Response
03690d13
TC
82 */
83 public function exportAs($format)
84 {
8f336fda
JB
85 $functionName = 'produce'.ucfirst($format);
86 if (method_exists($this, $functionName)) {
87 return $this->$functionName();
03690d13 88 }
add597ba
JB
89
90 throw new \InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
03690d13
TC
91 }
92
add597ba
JB
93 /**
94 * Use PHPePub to dump a .epub file.
4094ea47
JB
95 *
96 * @return Response
add597ba 97 */
03690d13
TC
98 private function produceEpub()
99 {
100 /*
101 * Start and End of the book
102 */
103 $content_start =
104 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
105 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
106 .'<head>'
107 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
add597ba 108 ."<title>wallabag articles book</title>\n"
03690d13
TC
109 ."</head>\n"
110 ."<body>\n";
111
112 $bookEnd = "</body>\n</html>\n";
113
114 $book = new EPub(EPub::BOOK_VERSION_EPUB3);
115
116 /*
117 * Book metadata
118 */
119
120 $book->setTitle($this->title);
add597ba
JB
121 // Could also be the ISBN number, prefered for published books, or a UUID.
122 $book->setIdentifier($this->title, EPub::IDENTIFIER_URI);
123 // 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.
124 $book->setLanguage($this->language);
125 $book->setDescription('Some articles saved on my wallabag');
03690d13
TC
126
127 foreach ($this->authors as $author) {
128 $book->setAuthor($author, $author);
129 }
130
add597ba
JB
131 // I hope this is a non existant address :)
132 $book->setPublisher('wallabag', 'wallabag');
133 // Strictly not needed as the book date defaults to time().
134 $book->setDate(time());
135 $book->setSourceURL($this->wallabagUrl);
03690d13
TC
136
137 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
138 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
139
140 /*
141 * Front page
142 */
add597ba
JB
143 if (file_exists($this->logoPath)) {
144 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
145 }
03690d13 146
add597ba 147 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
03690d13
TC
148
149 $book->buildTOC();
150
151 /*
152 * Adding actual entries
153 */
154
add597ba
JB
155 // set tags as subjects
156 foreach ($this->entries as $entry) {
b0458874
JB
157 foreach ($entry->getTags() as $tag) {
158 $book->setSubject($tag->getLabel());
add597ba 159 }
03690d13 160
45d94a98
ÉG
161 // the reader in Kobo Devices doesn't likes special caracters
162 // in filenames, we limit to A-z/0-9
163 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
164
03690d13 165 $chapter = $content_start.$entry->getContent().$bookEnd;
45d94a98 166 $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
03690d13 167 }
add597ba
JB
168
169 return Response::create(
170 $book->getBook(),
171 200,
4094ea47 172 [
add597ba
JB
173 'Content-Description' => 'File Transfer',
174 'Content-type' => 'application/epub+zip',
175 'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"',
176 'Content-Transfer-Encoding' => 'binary',
4094ea47 177 ]
f898102c 178 );
03690d13
TC
179 }
180
add597ba
JB
181 /**
182 * Use PHPMobi to dump a .mobi file.
4094ea47
JB
183 *
184 * @return Response
add597ba 185 */
03690d13
TC
186 private function produceMobi()
187 {
188 $mobi = new \MOBI();
189 $content = new \MOBIFile();
190
191 /*
192 * Book metadata
193 */
03690d13
TC
194 $content->set('title', $this->title);
195 $content->set('author', implode($this->authors));
196 $content->set('subject', $this->title);
197
198 /*
199 * Front page
200 */
add597ba
JB
201 $content->appendParagraph($this->getExportInformation('PHPMobi'));
202 if (file_exists($this->logoPath)) {
203 $content->appendImage(imagecreatefrompng($this->logoPath));
204 }
03690d13
TC
205 $content->appendPageBreak();
206
207 /*
208 * Adding actual entries
209 */
03690d13
TC
210 foreach ($this->entries as $entry) {
211 $content->appendChapterTitle($entry->getTitle());
212 $content->appendParagraph($entry->getContent());
213 $content->appendPageBreak();
214 }
215 $mobi->setContentProvider($content);
216
217 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
218 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
219
add597ba
JB
220 return Response::create(
221 $mobi->toString(),
222 200,
4094ea47 223 [
add597ba
JB
224 'Accept-Ranges' => 'bytes',
225 'Content-Description' => 'File Transfer',
226 'Content-type' => 'application/x-mobipocket-ebook',
227 'Content-Disposition' => 'attachment; filename="'.$this->title.'.mobi"',
228 'Content-Transfer-Encoding' => 'binary',
4094ea47 229 ]
f898102c 230 );
03690d13
TC
231 }
232
add597ba
JB
233 /**
234 * Use TCPDF to dump a .pdf file.
4094ea47
JB
235 *
236 * @return Response
add597ba 237 */
8f336fda 238 private function producePdf()
03690d13
TC
239 {
240 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
241
242 /*
243 * Book metadata
244 */
03690d13
TC
245 $pdf->SetCreator(PDF_CREATOR);
246 $pdf->SetAuthor('wallabag');
247 $pdf->SetTitle($this->title);
248 $pdf->SetSubject('Articles via wallabag');
249 $pdf->SetKeywords('wallabag');
250
251 /*
252 * Front page
253 */
03690d13 254 $pdf->AddPage();
add597ba 255 $intro = '<h1>'.$this->title.'</h1>'.$this->getExportInformation('tcpdf');
03690d13
TC
256
257 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
258
259 /*
260 * Adding actual entries
261 */
03690d13 262 foreach ($this->entries as $entry) {
b0458874
JB
263 foreach ($entry->getTags() as $tag) {
264 $pdf->SetKeywords($tag->getLabel());
03690d13
TC
265 }
266
267 $pdf->AddPage();
268 $html = '<h1>'.$entry->getTitle().'</h1>';
269 $html .= $entry->getContent();
add597ba 270
03690d13
TC
271 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
272 }
273
274 // set image scale factor
275 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
276
add597ba
JB
277 return Response::create(
278 $pdf->Output('', 'S'),
279 200,
4094ea47 280 [
add597ba
JB
281 'Content-Description' => 'File Transfer',
282 'Content-type' => 'application/pdf',
283 'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"',
284 'Content-Transfer-Encoding' => 'binary',
4094ea47 285 ]
f898102c 286 );
03690d13
TC
287 }
288
add597ba
JB
289 /**
290 * Inspired from CsvFileDumper.
4094ea47
JB
291 *
292 * @return Response
add597ba 293 */
8f336fda 294 private function produceCsv()
03690d13 295 {
add597ba
JB
296 $delimiter = ';';
297 $enclosure = '"';
298 $handle = fopen('php://memory', 'rb+');
03690d13 299
9401696f 300 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
03690d13 301
03690d13 302 foreach ($this->entries as $entry) {
add597ba
JB
303 fputcsv(
304 $handle,
4094ea47 305 [
add597ba
JB
306 $entry->getTitle(),
307 $entry->getURL(),
cceca9ea 308 // remove new line to avoid crazy results
4094ea47 309 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
add597ba
JB
310 implode(', ', $entry->getTags()->toArray()),
311 $entry->getMimetype(),
312 $entry->getLanguage(),
9401696f 313 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
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}