3 namespace Wallabag\CoreBundle\Helper
;
5 use Html2Text\Html2Text
;
6 use JMS\Serializer\SerializationContext
;
7 use JMS\Serializer\SerializerBuilder
;
9 use PHPePub\Core\Structure\OPF\DublinCore
;
10 use Symfony\Component\HttpFoundation\Response
;
11 use Symfony\Component\Translation\TranslatorInterface
;
12 use Wallabag\CoreBundle\Entity\Entry
;
15 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
23 private $entries = [];
24 private $author = 'wallabag';
25 private $language = '';
26 private $footerTemplate = '<div style="text-align:center;">
27 <p>Produced by wallabag with %EXPORT_METHOD%</p>
28 <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>
32 * @param string $wallabagUrl Wallabag instance url
33 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
35 public function __construct($wallabagUrl, $logoPath, TranslatorInterface
$translator)
37 $this->wallabagUrl
= $wallabagUrl;
38 $this->logoPath
= $logoPath;
39 $this->translator
= $translator;
45 * @param array|Entry $entries An array of entries or one entry
47 * @return EntriesExport
49 public function setEntries($entries)
51 if (!is_array($entries)) {
52 $this->language
= $entries->getLanguage();
53 $entries = [$entries];
56 $this->entries
= $entries;
62 * Sets the category of which we want to get articles, or just one entry.
64 * @param string $method Method to get articles
66 * @return EntriesExport
68 public function updateTitle($method)
70 $this->title
= $method . ' articles';
72 if ('entry' === $method) {
73 $this->title
= $this->entries
[0]->getTitle();
80 * Sets the author for one entry or category.
82 * The publishers are used, or the domain name if empty.
84 * @param string $method Method to get articles
86 * @return EntriesExport
88 public function updateAuthor($method)
90 if ('entry' !== $method) {
91 $this->author
= $method . ' authors';
96 $this->author
= $this->entries
[0]->getDomainName();
98 $publishedBy = $this->entries
[0]->getPublishedBy();
99 if (!empty($publishedBy)) {
100 $this->author
= implode(', ', $publishedBy);
107 * Sets the output format.
109 * @param string $format
113 public function exportAs($format)
115 $functionName = 'produce' . ucfirst($format);
116 if (method_exists($this, $functionName)) {
117 return $this->$functionName();
120 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
123 public function exportJsonData()
125 return $this->prepareSerializingContent('json');
129 * Use PHPePub to dump a .epub file.
133 private function produceEpub()
136 * Start and End of the book
139 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
140 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
142 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
143 . "<title>wallabag articles book</title>\n"
147 $bookEnd = "</body>\n</html>\n";
149 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
155 $book->setTitle($this->title
);
156 // Could also be the ISBN number, prefered for published books, or a UUID.
157 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
158 // 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.
159 $book->setLanguage($this->language
);
160 $book->setDescription('Some articles saved on my wallabag');
162 $book->setAuthor($this->author
, $this->author
);
164 // I hope this is a non existant address :)
165 $book->setPublisher('wallabag', 'wallabag');
166 // Strictly not needed as the book date defaults to time().
167 $book->setDate(time());
168 $book->setSourceURL($this->wallabagUrl
);
170 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
171 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
176 if (file_exists($this->logoPath
)) {
177 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
183 * Adding actual entries
186 // set tags as subjects
187 foreach ($this->entries
as $entry) {
188 foreach ($entry->getTags() as $tag) {
189 $book->setSubject($tag->getLabel());
192 // the reader in Kobo Devices doesn't likes special caracters
193 // in filenames, we limit to A-z/0-9
194 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
196 $chapter = $content_start . $entry->getContent() . $bookEnd;
197 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
200 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
202 return Response
::create(
206 'Content-Description' => 'File Transfer',
207 'Content-type' => 'application/epub+zip',
208 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.epub"',
209 'Content-Transfer-Encoding' => 'binary',
215 * Use PHPMobi to dump a .mobi file.
219 private function produceMobi()
222 $content = new \
MOBIFile();
227 $content->set('title', $this->title
);
228 $content->set('author', $this->author
);
229 $content->set('subject', $this->title
);
234 $content->appendParagraph($this->getExportInformation('PHPMobi'));
235 if (file_exists($this->logoPath
)) {
236 $content->appendImage(imagecreatefrompng($this->logoPath
));
238 $content->appendPageBreak();
241 * Adding actual entries
243 foreach ($this->entries
as $entry) {
244 $content->appendChapterTitle($entry->getTitle());
245 $content->appendParagraph($entry->getContent());
246 $content->appendPageBreak();
248 $mobi->setContentProvider($content);
250 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
251 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
253 return Response
::create(
257 'Accept-Ranges' => 'bytes',
258 'Content-Description' => 'File Transfer',
259 'Content-type' => 'application/x-mobipocket-ebook',
260 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.mobi"',
261 'Content-Transfer-Encoding' => 'binary',
267 * Use TCPDF to dump a .pdf file.
271 private function producePdf()
273 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
278 $pdf->SetCreator(PDF_CREATOR
);
279 $pdf->SetAuthor($this->author
);
280 $pdf->SetTitle($this->title
);
281 $pdf->SetSubject('Articles via wallabag');
282 $pdf->SetKeywords('wallabag');
288 $intro = '<h1>' . $this->title
. '</h1>' . $this->getExportInformation('tcpdf');
290 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
293 * Adding actual entries
295 foreach ($this->entries
as $entry) {
296 foreach ($entry->getTags() as $tag) {
297 $pdf->SetKeywords($tag->getLabel());
301 $html = '<h1>' . $entry->getTitle() . '</h1>';
302 $html .= $entry->getContent();
304 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
307 // set image scale factor
308 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
310 return Response
::create(
311 $pdf->Output('', 'S'),
314 'Content-Description' => 'File Transfer',
315 'Content-type' => 'application/pdf',
316 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.pdf"',
317 'Content-Transfer-Encoding' => 'binary',
323 * Inspired from CsvFileDumper.
327 private function produceCsv()
331 $handle = fopen('php://memory', 'rb+');
333 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
335 foreach ($this->entries
as $entry) {
341 // remove new line to avoid crazy results
342 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
343 implode(', ', $entry->getTags()->toArray()),
344 $entry->getMimetype(),
345 $entry->getLanguage(),
346 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
354 $output = stream_get_contents($handle);
357 return Response
::create(
361 'Content-type' => 'application/csv',
362 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.csv"',
363 'Content-Transfer-Encoding' => 'UTF-8',
373 private function produceJson()
375 return Response
::create(
376 $this->prepareSerializingContent('json'),
379 'Content-type' => 'application/json',
380 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.json"',
381 'Content-Transfer-Encoding' => 'UTF-8',
391 private function produceXml()
393 return Response
::create(
394 $this->prepareSerializingContent('xml'),
397 'Content-type' => 'application/xml',
398 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.xml"',
399 'Content-Transfer-Encoding' => 'UTF-8',
409 private function produceTxt()
412 $bar = str_repeat('=', 100);
413 foreach ($this->entries
as $entry) {
414 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
415 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
416 $content .= $html->getText();
419 return Response
::create(
423 'Content-type' => 'text/plain',
424 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.txt"',
425 'Content-Transfer-Encoding' => 'UTF-8',
431 * Return a Serializer object for producing processes that need it (JSON & XML).
433 * @param string $format
437 private function prepareSerializingContent($format)
439 $serializer = SerializerBuilder
::create()->build();
441 return $serializer->serialize(
444 SerializationContext
::create()->setGroups(['entries_for_user'])
449 * Return a kind of footer / information for the epub.
451 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
455 private function getExportInformation($type)
457 $info = $this->translator
->trans('export.footer_template', [
461 if ('tcpdf' === $type) {
462 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
465 return str_replace('%IMAGE%', '', $info);