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