]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/EntriesExport.php
Inject parameter instead of service
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / EntriesExport.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Helper;
4
5 use JMS\Serializer;
6 use JMS\Serializer\SerializationContext;
7 use JMS\Serializer\SerializerBuilder;
8 use PHPePub\Core\EPub;
9 use PHPePub\Core\Structure\OPF\DublinCore;
10 use Symfony\Component\HttpFoundation\Response;
11
12 /**
13 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
14 */
15 class EntriesExport
16 {
17 private $wallabagUrl;
18 private $logoPath;
19 private $title = '';
20 private $entries = [];
21 private $authors = ['wallabag'];
22 private $language = '';
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>
26 </div>';
27
28 /**
29 * @param string $wallabagUrl Wallabag instance url
30 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
31 */
32 public function __construct($wallabagUrl, $logoPath)
33 {
34 $this->wallabagUrl = $wallabagUrl;
35 $this->logoPath = $logoPath;
36 }
37
38 /**
39 * Define entries.
40 *
41 * @param array|Entry $entries An array of entries or one entry
42 *
43 * @return EntriesExport
44 */
45 public function setEntries($entries)
46 {
47 if (!is_array($entries)) {
48 $this->language = $entries->getLanguage();
49 $entries = [$entries];
50 }
51
52 $this->entries = $entries;
53
54 return $this;
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
61 *
62 * @return EntriesExport
63 */
64 public function updateTitle($method)
65 {
66 $this->title = $method.' articles';
67
68 if ('entry' === $method) {
69 $this->title = $this->entries[0]->getTitle();
70 }
71
72 return $this;
73 }
74
75 /**
76 * Sets the output format.
77 *
78 * @param string $format
79 *
80 * @return Response
81 */
82 public function exportAs($format)
83 {
84 $functionName = 'produce'.ucfirst($format);
85 if (method_exists($this, $functionName)) {
86 return $this->$functionName();
87 }
88
89 throw new \InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
90 }
91
92 /**
93 * Use PHPePub to dump a .epub file.
94 *
95 * @return Response
96 */
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"
107 ."<title>wallabag articles book</title>\n"
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);
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');
125
126 foreach ($this->authors as $author) {
127 $book->setAuthor($author, $author);
128 }
129
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);
135
136 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
137 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
138
139 /*
140 * Front page
141 */
142 if (file_exists($this->logoPath)) {
143 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
144 }
145
146 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
147
148 $book->buildTOC();
149
150 /*
151 * Adding actual entries
152 */
153
154 // set tags as subjects
155 foreach ($this->entries as $entry) {
156 foreach ($entry->getTags() as $tag) {
157 $book->setSubject($tag->getLabel());
158 }
159
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
164 $chapter = $content_start.$entry->getContent().$bookEnd;
165 $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
166 }
167
168 return Response::create(
169 $book->getBook(),
170 200,
171 [
172 'Content-Description' => 'File Transfer',
173 'Content-type' => 'application/epub+zip',
174 'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"',
175 'Content-Transfer-Encoding' => 'binary',
176 ]
177 );
178 }
179
180 /**
181 * Use PHPMobi to dump a .mobi file.
182 *
183 * @return Response
184 */
185 private function produceMobi()
186 {
187 $mobi = new \MOBI();
188 $content = new \MOBIFile();
189
190 /*
191 * Book metadata
192 */
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 */
200 $content->appendParagraph($this->getExportInformation('PHPMobi'));
201 if (file_exists($this->logoPath)) {
202 $content->appendImage(imagecreatefrompng($this->logoPath));
203 }
204 $content->appendPageBreak();
205
206 /*
207 * Adding actual entries
208 */
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
219 return Response::create(
220 $mobi->toString(),
221 200,
222 [
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',
228 ]
229 );
230 }
231
232 /**
233 * Use TCPDF to dump a .pdf file.
234 *
235 * @return Response
236 */
237 private function producePdf()
238 {
239 $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
240
241 /*
242 * Book metadata
243 */
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 */
253 $pdf->AddPage();
254 $intro = '<h1>'.$this->title.'</h1>'.$this->getExportInformation('tcpdf');
255
256 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
257
258 /*
259 * Adding actual entries
260 */
261 foreach ($this->entries as $entry) {
262 foreach ($entry->getTags() as $tag) {
263 $pdf->SetKeywords($tag->getLabel());
264 }
265
266 $pdf->AddPage();
267 $html = '<h1>'.$entry->getTitle().'</h1>';
268 $html .= $entry->getContent();
269
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
276 return Response::create(
277 $pdf->Output('', 'S'),
278 200,
279 [
280 'Content-Description' => 'File Transfer',
281 'Content-type' => 'application/pdf',
282 'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"',
283 'Content-Transfer-Encoding' => 'binary',
284 ]
285 );
286 }
287
288 /**
289 * Inspired from CsvFileDumper.
290 *
291 * @return Response
292 */
293 private function produceCsv()
294 {
295 $delimiter = ';';
296 $enclosure = '"';
297 $handle = fopen('php://memory', 'rb+');
298
299 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
300
301 foreach ($this->entries as $entry) {
302 fputcsv(
303 $handle,
304 [
305 $entry->getTitle(),
306 $entry->getURL(),
307 // remove new line to avoid crazy results
308 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
309 implode(', ', $entry->getTags()->toArray()),
310 $entry->getMimetype(),
311 $entry->getLanguage(),
312 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
313 ],
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,
326 [
327 'Content-type' => 'application/csv',
328 'Content-Disposition' => 'attachment; filename="'.$this->title.'.csv"',
329 'Content-Transfer-Encoding' => 'UTF-8',
330 ]
331 );
332 }
333
334 /**
335 * Dump a JSON file.
336 *
337 * @return Response
338 */
339 private function produceJson()
340 {
341 return Response::create(
342 $this->prepareSerializingContent('json'),
343 200,
344 [
345 'Content-type' => 'application/json',
346 'Content-Disposition' => 'attachment; filename="'.$this->title.'.json"',
347 'Content-Transfer-Encoding' => 'UTF-8',
348 ]
349 );
350 }
351
352 /**
353 * Dump a XML file.
354 *
355 * @return Response
356 */
357 private function produceXml()
358 {
359 return Response::create(
360 $this->prepareSerializingContent('xml'),
361 200,
362 [
363 'Content-type' => 'application/xml',
364 'Content-Disposition' => 'attachment; filename="'.$this->title.'.xml"',
365 'Content-Transfer-Encoding' => 'UTF-8',
366 ]
367 );
368 }
369
370 /**
371 * Dump a TXT file.
372 *
373 * @return Response
374 */
375 private function produceTxt()
376 {
377 $content = '';
378 $bar = str_repeat('=', 100);
379 foreach ($this->entries as $entry) {
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";
382 }
383
384 return Response::create(
385 $content,
386 200,
387 [
388 'Content-type' => 'text/plain',
389 'Content-Disposition' => 'attachment; filename="'.$this->title.'.txt"',
390 'Content-Transfer-Encoding' => 'UTF-8',
391 ]
392 );
393 }
394
395 /**
396 * Return a Serializer object for producing processes that need it (JSON & XML).
397 *
398 * @param string $format
399 *
400 * @return Serializer
401 */
402 private function prepareSerializingContent($format)
403 {
404 $serializer = SerializerBuilder::create()->build();
405
406 return $serializer->serialize(
407 $this->entries,
408 $format,
409 SerializationContext::create()->setGroups(['entries_for_user'])
410 );
411 }
412
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);
426 }
427
428 return str_replace('%IMAGE%', '', $info);
429 }
430 }