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