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 $author = '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 author for one entry or category.
78 * The publishers are used, or the domain name if empty.
80 * @param string $method Method to get articles
82 * @return EntriesExport
84 public function updateAuthor($method)
86 $this->author
= $method.' authors';
88 if ('entry' === $method) {
89 $publishedBy = $this->entries
[0]->getPublishedBy();
90 if (!empty($publishedBy)) {
91 $this->author
= implode(', ', $this->entries
[0]->getPublishedBy());
93 $this->author
= $this->entries
[0]->getDomainName();
101 * Sets the output format.
103 * @param string $format
107 public function exportAs($format)
109 $functionName = 'produce' . ucfirst($format);
110 if (method_exists($this, $functionName)) {
111 return $this->$functionName();
114 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
117 public function exportJsonData()
119 return $this->prepareSerializingContent('json');
123 * Use PHPePub to dump a .epub file.
127 private function produceEpub()
130 * Start and End of the book
133 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
134 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
136 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
137 . "<title>wallabag articles book</title>\n"
141 $bookEnd = "</body>\n</html>\n";
143 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
149 $book->setTitle($this->title
);
150 // Could also be the ISBN number, prefered for published books, or a UUID.
151 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
152 // 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.
153 $book->setLanguage($this->language
);
154 $book->setDescription('Some articles saved on my wallabag');
156 $book->setAuthor($this->author
, $this->author
);
158 // I hope this is a non existant address :)
159 $book->setPublisher('wallabag', 'wallabag');
160 // Strictly not needed as the book date defaults to time().
161 $book->setDate(time());
162 $book->setSourceURL($this->wallabagUrl
);
164 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
165 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
170 if (file_exists($this->logoPath
)) {
171 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
177 * Adding actual entries
180 // set tags as subjects
181 foreach ($this->entries
as $entry) {
182 foreach ($entry->getTags() as $tag) {
183 $book->setSubject($tag->getLabel());
186 // the reader in Kobo Devices doesn't likes special caracters
187 // in filenames, we limit to A-z/0-9
188 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
190 $chapter = $content_start . $entry->getContent() . $bookEnd;
191 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
194 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
196 return Response
::create(
200 'Content-Description' => 'File Transfer',
201 'Content-type' => 'application/epub+zip',
202 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.epub"',
203 'Content-Transfer-Encoding' => 'binary',
209 * Use PHPMobi to dump a .mobi file.
213 private function produceMobi()
216 $content = new \
MOBIFile();
221 $content->set('title', $this->title
);
222 $content->set('author', $this->author
);
223 $content->set('subject', $this->title
);
228 $content->appendParagraph($this->getExportInformation('PHPMobi'));
229 if (file_exists($this->logoPath
)) {
230 $content->appendImage(imagecreatefrompng($this->logoPath
));
232 $content->appendPageBreak();
235 * Adding actual entries
237 foreach ($this->entries
as $entry) {
238 $content->appendChapterTitle($entry->getTitle());
239 $content->appendParagraph($entry->getContent());
240 $content->appendPageBreak();
242 $mobi->setContentProvider($content);
244 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
245 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
247 return Response
::create(
251 'Accept-Ranges' => 'bytes',
252 'Content-Description' => 'File Transfer',
253 'Content-type' => 'application/x-mobipocket-ebook',
254 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.mobi"',
255 'Content-Transfer-Encoding' => 'binary',
261 * Use TCPDF to dump a .pdf file.
265 private function producePdf()
267 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
272 $pdf->SetCreator(PDF_CREATOR
);
273 $pdf->SetAuthor($this->author
);
274 $pdf->SetTitle($this->title
);
275 $pdf->SetSubject('Articles via wallabag');
276 $pdf->SetKeywords('wallabag');
282 $intro = '<h1>' . $this->title
. '</h1>' . $this->getExportInformation('tcpdf');
284 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
287 * Adding actual entries
289 foreach ($this->entries
as $entry) {
290 foreach ($entry->getTags() as $tag) {
291 $pdf->SetKeywords($tag->getLabel());
295 $html = '<h1>' . $entry->getTitle() . '</h1>';
296 $html .= $entry->getContent();
298 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
301 // set image scale factor
302 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
304 return Response
::create(
305 $pdf->Output('', 'S'),
308 'Content-Description' => 'File Transfer',
309 'Content-type' => 'application/pdf',
310 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.pdf"',
311 'Content-Transfer-Encoding' => 'binary',
317 * Inspired from CsvFileDumper.
321 private function produceCsv()
325 $handle = fopen('php://memory', 'rb+');
327 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
329 foreach ($this->entries
as $entry) {
335 // remove new line to avoid crazy results
336 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
337 implode(', ', $entry->getTags()->toArray()),
338 $entry->getMimetype(),
339 $entry->getLanguage(),
340 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
348 $output = stream_get_contents($handle);
351 return Response
::create(
355 'Content-type' => 'application/csv',
356 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.csv"',
357 'Content-Transfer-Encoding' => 'UTF-8',
367 private function produceJson()
369 return Response
::create(
370 $this->prepareSerializingContent('json'),
373 'Content-type' => 'application/json',
374 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.json"',
375 'Content-Transfer-Encoding' => 'UTF-8',
385 private function produceXml()
387 return Response
::create(
388 $this->prepareSerializingContent('xml'),
391 'Content-type' => 'application/xml',
392 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.xml"',
393 'Content-Transfer-Encoding' => 'UTF-8',
403 private function produceTxt()
406 $bar = str_repeat('=', 100);
407 foreach ($this->entries
as $entry) {
408 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
409 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent()))) . "\n\n";
412 return Response
::create(
416 'Content-type' => 'text/plain',
417 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.txt"',
418 'Content-Transfer-Encoding' => 'UTF-8',
424 * Return a Serializer object for producing processes that need it (JSON & XML).
426 * @param string $format
430 private function prepareSerializingContent($format)
432 $serializer = SerializerBuilder
::create()->build();
434 return $serializer->serialize(
437 SerializationContext
::create()->setGroups(['entries_for_user'])
442 * Return a kind of footer / information for the epub.
444 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
448 private function getExportInformation($type)
450 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
452 if ('tcpdf' === $type) {
453 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
456 return str_replace('%IMAGE%', '', $info);