]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/EntriesExport.php
use JMS Serializer
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / EntriesExport.php
CommitLineData
03690d13
TC
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
5use PHPePub\Core\EPub;
6use PHPePub\Core\Structure\OPF\DublinCore;
add597ba 7use Symfony\Component\HttpFoundation\Response;
268e9e72
TC
8use JMS\Serializer;
9use JMS\Serializer\SerializerBuilder;
10use JMS\Serializer\SerializationContext;
03690d13
TC
11
12class EntriesExport
13{
add597ba
JB
14 private $wallabagUrl;
15 private $logoPath;
16 private $title = '';
17 private $entries = array();
03690d13 18 private $authors = array('wallabag');
add597ba
JB
19 private $language = '';
20 private $tags = array();
21 private $footerTemplate = '<div style="text-align:center;">
22 <p>Produced by wallabag with %EXPORT_METHOD%</p>
23 <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>
24 </div';
03690d13 25
add597ba
JB
26 /**
27 * @param string $wallabagUrl Wallabag instance url
28 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
29 */
30 public function __construct($wallabagUrl, $logoPath)
03690d13 31 {
add597ba
JB
32 $this->wallabagUrl = $wallabagUrl;
33 $this->logoPath = $logoPath;
34 }
35
36 /**
37 * Define entries.
38 *
39 * @param array|Entry $entries An array of entries or one entry
40 */
41 public function setEntries($entries)
42 {
43 if (!is_array($entries)) {
44 $this->language = $entries->getLanguage();
45 $entries = array($entries);
46 }
47
03690d13
TC
48 $this->entries = $entries;
49
50 foreach ($entries as $entry) {
51 $this->tags[] = $entry->getTags();
52 }
add597ba
JB
53
54 return $this;
03690d13
TC
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 */
add597ba 62 public function updateTitle($method)
03690d13 63 {
add597ba
JB
64 $this->title = $method.' articles';
65
66 if ('entry' === $method) {
67 $this->title = $this->entries[0]->getTitle();
03690d13 68 }
add597ba
JB
69
70 return $this;
03690d13
TC
71 }
72
73 /**
74 * Sets the output format.
75 *
76 * @param string $format
77 */
78 public function exportAs($format)
79 {
add597ba 80 switch ($format) {
03690d13 81 case 'epub':
add597ba 82 return $this->produceEpub();
03690d13
TC
83
84 case 'mobi':
add597ba 85 return $this->produceMobi();
03690d13
TC
86
87 case 'pdf':
add597ba 88 return $this->producePDF();
03690d13
TC
89
90 case 'csv':
add597ba 91 return $this->produceCSV();
b3cc1a14
TC
92
93 case 'json':
94 return $this->produceJSON();
95
96 case 'xml':
97 return $this->produceXML();
03690d13 98 }
add597ba
JB
99
100 throw new \InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
03690d13
TC
101 }
102
add597ba
JB
103 /**
104 * Use PHPePub to dump a .epub file.
105 */
03690d13
TC
106 private function produceEpub()
107 {
108 /*
109 * Start and End of the book
110 */
111 $content_start =
112 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
113 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
114 .'<head>'
115 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
add597ba 116 ."<title>wallabag articles book</title>\n"
03690d13
TC
117 ."</head>\n"
118 ."<body>\n";
119
120 $bookEnd = "</body>\n</html>\n";
121
122 $book = new EPub(EPub::BOOK_VERSION_EPUB3);
123
124 /*
125 * Book metadata
126 */
127
128 $book->setTitle($this->title);
add597ba
JB
129 // Could also be the ISBN number, prefered for published books, or a UUID.
130 $book->setIdentifier($this->title, EPub::IDENTIFIER_URI);
131 // 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.
132 $book->setLanguage($this->language);
133 $book->setDescription('Some articles saved on my wallabag');
03690d13
TC
134
135 foreach ($this->authors as $author) {
136 $book->setAuthor($author, $author);
137 }
138
add597ba
JB
139 // I hope this is a non existant address :)
140 $book->setPublisher('wallabag', 'wallabag');
141 // Strictly not needed as the book date defaults to time().
142 $book->setDate(time());
143 $book->setSourceURL($this->wallabagUrl);
03690d13
TC
144
145 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'PHP');
146 $book->addDublinCoreMetadata(DublinCore::CONTRIBUTOR, 'wallabag');
147
148 /*
149 * Front page
150 */
add597ba
JB
151 if (file_exists($this->logoPath)) {
152 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath), 'image/png');
153 }
03690d13 154
add597ba 155 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
03690d13
TC
156
157 $book->buildTOC();
158
159 /*
160 * Adding actual entries
161 */
162
add597ba
JB
163 // set tags as subjects
164 foreach ($this->entries as $entry) {
165 foreach ($this->tags as $tag) {
166 $book->setSubject($tag['value']);
167 }
03690d13
TC
168
169 $chapter = $content_start.$entry->getContent().$bookEnd;
170 $book->addChapter($entry->getTitle(), htmlspecialchars($entry->getTitle()).'.html', $chapter, true, EPub::EXTERNAL_REF_ADD);
171 }
add597ba
JB
172
173 return Response::create(
174 $book->getBook(),
175 200,
176 array(
177 'Content-Description' => 'File Transfer',
178 'Content-type' => 'application/epub+zip',
179 'Content-Disposition' => 'attachment; filename="'.$this->title.'.epub"',
180 'Content-Transfer-Encoding' => 'binary',
181 )
182 )->send();
03690d13
TC
183 }
184
add597ba
JB
185 /**
186 * Use PHPMobi to dump a .mobi file.
187 */
03690d13
TC
188 private function produceMobi()
189 {
190 $mobi = new \MOBI();
191 $content = new \MOBIFile();
192
193 /*
194 * Book metadata
195 */
03690d13
TC
196 $content->set('title', $this->title);
197 $content->set('author', implode($this->authors));
198 $content->set('subject', $this->title);
199
200 /*
201 * Front page
202 */
add597ba
JB
203 $content->appendParagraph($this->getExportInformation('PHPMobi'));
204 if (file_exists($this->logoPath)) {
205 $content->appendImage(imagecreatefrompng($this->logoPath));
206 }
03690d13
TC
207 $content->appendPageBreak();
208
209 /*
210 * Adding actual entries
211 */
03690d13
TC
212 foreach ($this->entries as $entry) {
213 $content->appendChapterTitle($entry->getTitle());
214 $content->appendParagraph($entry->getContent());
215 $content->appendPageBreak();
216 }
217 $mobi->setContentProvider($content);
218
219 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
220 $this->title = preg_replace('/[^A-Za-z0-9\-]/', '', $this->title);
221
add597ba
JB
222 return Response::create(
223 $mobi->toString(),
224 200,
225 array(
226 'Accept-Ranges' => 'bytes',
227 'Content-Description' => 'File Transfer',
228 'Content-type' => 'application/x-mobipocket-ebook',
229 'Content-Disposition' => 'attachment; filename="'.$this->title.'.mobi"',
230 'Content-Transfer-Encoding' => 'binary',
231 )
232 )->send();
03690d13
TC
233 }
234
add597ba
JB
235 /**
236 * Use TCPDF to dump a .pdf file.
237 */
03690d13
TC
238 private function producePDF()
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
TC
262 foreach ($this->entries as $entry) {
263 foreach ($this->tags as $tag) {
264 $pdf->SetKeywords($tag['value']);
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,
280 array(
281 'Content-Description' => 'File Transfer',
282 'Content-type' => 'application/pdf',
283 'Content-Disposition' => 'attachment; filename="'.$this->title.'.pdf"',
284 'Content-Transfer-Encoding' => 'binary',
285 )
286 )->send();
03690d13
TC
287 }
288
add597ba
JB
289 /**
290 * Inspired from CsvFileDumper.
291 */
03690d13
TC
292 private function produceCSV()
293 {
add597ba
JB
294 $delimiter = ';';
295 $enclosure = '"';
296 $handle = fopen('php://memory', 'rb+');
03690d13 297
add597ba 298 fputcsv($handle, array('Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language'), $delimiter, $enclosure);
03690d13 299
03690d13 300 foreach ($this->entries as $entry) {
add597ba
JB
301 fputcsv(
302 $handle,
303 array(
304 $entry->getTitle(),
305 $entry->getURL(),
306 $entry->getContent(),
307 implode(', ', $entry->getTags()->toArray()),
308 $entry->getMimetype(),
309 $entry->getLanguage(),
310 ),
311 $delimiter,
312 $enclosure
313 );
314 }
315
316 rewind($handle);
317 $output = stream_get_contents($handle);
318 fclose($handle);
319
320 return Response::create(
321 $output,
322 200,
323 array(
324 'Content-type' => 'application/csv',
325 'Content-Disposition' => 'attachment; filename="'.$this->title.'.csv"',
326 'Content-Transfer-Encoding' => 'UTF-8',
327 )
328 )->send();
329 }
330
b3cc1a14
TC
331 private function produceJSON()
332 {
b3cc1a14 333 return Response::create(
8ac95cbf 334 $this->prepareSerializingContent('json'),
b3cc1a14
TC
335 200,
336 array(
337 'Content-type' => 'application/json',
338 'Content-Disposition' => 'attachment; filename="'.$this->title.'.json"',
339 'Content-Transfer-Encoding' => 'UTF-8',
340 )
341 )->send();
342 }
343
344 private function produceXML()
345 {
b3cc1a14 346 return Response::create(
8ac95cbf 347 $this->prepareSerializingContent('xml'),
b3cc1a14
TC
348 200,
349 array(
350 'Content-type' => 'application/xml',
351 'Content-Disposition' => 'attachment; filename="'.$this->title.'.xml"',
352 'Content-Transfer-Encoding' => 'UTF-8',
353 )
354 )->send();
355 }
8ac95cbf 356
b3cc1a14
TC
357 /**
358 * Return a Serializer object for producing processes that need it (JSON & XML).
359 *
360 * @return Serializer
361 */
8ac95cbf 362 private function prepareSerializingContent($format)
b3cc1a14 363 {
268e9e72 364 $serializer = SerializerBuilder::create()->build();
b3cc1a14 365
268e9e72 366 return $serializer->serialize($this->entries, $format, SerializationContext::create()->setGroups(array('entries_for_user')));
b3cc1a14
TC
367 }
368
add597ba
JB
369 /**
370 * Return a kind of footer / information for the epub.
371 *
372 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
373 *
374 * @return string
375 */
376 private function getExportInformation($type)
377 {
378 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate);
379
380 if ('tcpdf' === $type) {
381 return str_replace('%IMAGE%', '<img src="'.$this->logoPath.'" />', $info);
03690d13 382 }
add597ba
JB
383
384 return str_replace('%IMAGE%', '', $info);
03690d13
TC
385 }
386}