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