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