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