3 namespace Wallabag\CoreBundle\Helper
;
6 use JMS\Serializer\SerializationContext
;
7 use JMS\Serializer\SerializerBuilder
;
9 use PHPePub\Core\Structure\OPF\DublinCore
;
10 use Symfony\Component\HttpFoundation\Response
;
13 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
20 private $entries = [];
21 private $authors = ['wallabag'];
22 private $language = '';
23 private $footerTemplate = '<div style="text-align:center;">
24 <p>Produced by wallabag with %EXPORT_METHOD%</p>
25 <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>
29 * @param string $wallabagUrl Wallabag instance url
30 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
32 public function __construct($wallabagUrl, $logoPath)
34 $this->wallabagUrl
= $wallabagUrl;
35 $this->logoPath
= $logoPath;
41 * @param array|Entry $entries An array of entries or one entry
43 * @return EntriesExport
45 public function setEntries($entries)
47 if (!is_array($entries)) {
48 $this->language
= $entries->getLanguage();
49 $entries = [$entries];
52 $this->entries
= $entries;
58 * Sets the category of which we want to get articles, or just one entry.
60 * @param string $method Method to get articles
62 * @return EntriesExport
64 public function updateTitle($method)
66 $this->title
= $method.' articles';
68 if ('entry' === $method) {
69 $this->title
= $this->entries
[0]->getTitle();
76 * Sets the output format.
78 * @param string $format
82 public function exportAs($format)
84 $functionName = 'produce'.ucfirst($format);
85 if (method_exists($this, $functionName)) {
86 return $this->$functionName();
89 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
92 public function exportJsonData()
94 return $this->prepareSerializingContent('json');
98 * Use PHPePub to dump a .epub file.
102 private function produceEpub()
105 * Start and End of the book
108 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
109 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
111 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
112 ."<title>wallabag articles book</title>\n"
116 $bookEnd = "</body>\n</html>\n";
118 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
124 $book->setTitle($this->title
);
125 // Could also be the ISBN number, prefered for published books, or a UUID.
126 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
127 // 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.
128 $book->setLanguage($this->language
);
129 $book->setDescription('Some articles saved on my wallabag');
131 foreach ($this->authors
as $author) {
132 $book->setAuthor($author, $author);
135 // I hope this is a non existant address :)
136 $book->setPublisher('wallabag', 'wallabag');
137 // Strictly not needed as the book date defaults to time().
138 $book->setDate(time());
139 $book->setSourceURL($this->wallabagUrl
);
141 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
142 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
147 if (file_exists($this->logoPath
)) {
148 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
151 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
156 * Adding actual entries
159 // set tags as subjects
160 foreach ($this->entries
as $entry) {
161 foreach ($entry->getTags() as $tag) {
162 $book->setSubject($tag->getLabel());
165 // the reader in Kobo Devices doesn't likes special caracters
166 // in filenames, we limit to A-z/0-9
167 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
169 $chapter = $content_start.$entry->getContent().$bookEnd;
170 $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
173 return Response
::create(
177 'Content-Description' => 'File Transfer',
178 'Content-type' => 'application/epub+zip',
179 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
180 'Content-Transfer-Encoding' => 'binary',
186 * Use PHPMobi to dump a .mobi file.
190 private function produceMobi()
193 $content = new \
MOBIFile();
198 $content->set('title', $this->title
);
199 $content->set('author', implode($this->authors
));
200 $content->set('subject', $this->title
);
205 $content->appendParagraph($this->getExportInformation('PHPMobi'));
206 if (file_exists($this->logoPath
)) {
207 $content->appendImage(imagecreatefrompng($this->logoPath
));
209 $content->appendPageBreak();
212 * Adding actual entries
214 foreach ($this->entries
as $entry) {
215 $content->appendChapterTitle($entry->getTitle());
216 $content->appendParagraph($entry->getContent());
217 $content->appendPageBreak();
219 $mobi->setContentProvider($content);
221 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
222 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
224 return Response
::create(
228 'Accept-Ranges' => 'bytes',
229 'Content-Description' => 'File Transfer',
230 'Content-type' => 'application/x-mobipocket-ebook',
231 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
232 'Content-Transfer-Encoding' => 'binary',
238 * Use TCPDF to dump a .pdf file.
242 private function producePdf()
244 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
249 $pdf->SetCreator(PDF_CREATOR
);
250 $pdf->SetAuthor('wallabag');
251 $pdf->SetTitle($this->title
);
252 $pdf->SetSubject('Articles via wallabag');
253 $pdf->SetKeywords('wallabag');
259 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
261 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
264 * Adding actual entries
266 foreach ($this->entries
as $entry) {
267 foreach ($entry->getTags() as $tag) {
268 $pdf->SetKeywords($tag->getLabel());
272 $html = '<h1>'.$entry->getTitle().'</h1>';
273 $html .= $entry->getContent();
275 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
278 // set image scale factor
279 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
281 return Response
::create(
282 $pdf->Output('', 'S'),
285 'Content-Description' => 'File Transfer',
286 'Content-type' => 'application/pdf',
287 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
288 'Content-Transfer-Encoding' => 'binary',
294 * Inspired from CsvFileDumper.
298 private function produceCsv()
302 $handle = fopen('php://memory', 'rb+');
304 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
306 foreach ($this->entries
as $entry) {
312 // remove new line to avoid crazy results
313 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
314 implode(', ', $entry->getTags()->toArray()),
315 $entry->getMimetype(),
316 $entry->getLanguage(),
317 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
325 $output = stream_get_contents($handle);
328 return Response
::create(
332 'Content-type' => 'application/csv',
333 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.csv"',
334 'Content-Transfer-Encoding' => 'UTF-8',
344 private function produceJson()
346 return Response
::create(
347 $this->prepareSerializingContent('json'),
350 'Content-type' => 'application/json',
351 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.json"',
352 'Content-Transfer-Encoding' => 'UTF-8',
362 private function produceXml()
364 return Response
::create(
365 $this->prepareSerializingContent('xml'),
368 'Content-type' => 'application/xml',
369 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
370 'Content-Transfer-Encoding' => 'UTF-8',
380 private function produceTxt()
383 $bar = str_repeat('=', 100);
384 foreach ($this->entries
as $entry) {
385 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
386 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
389 return Response
::create(
393 'Content-type' => 'text/plain',
394 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
395 'Content-Transfer-Encoding' => 'UTF-8',
401 * Return a Serializer object for producing processes that need it (JSON & XML).
403 * @param string $format
407 private function prepareSerializingContent($format)
409 $serializer = SerializerBuilder
::create()->build();
411 return $serializer->serialize(
414 SerializationContext
::create()->setGroups(['entries_for_user'])
419 * Return a kind of footer / information for the epub.
421 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
425 private function getExportInformation($type)
427 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
429 if ('tcpdf' === $type) {
430 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
433 return str_replace('%IMAGE%', '', $info);