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 = '';
28 * @param TranslatorInterface $translator Translator service
29 * @param string $wallabagUrl Wallabag instance url
30 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
32 public function __construct(TranslatorInterface
$translator, $wallabagUrl, $logoPath)
34 $this->translator
= $translator;
35 $this->wallabagUrl
= $wallabagUrl;
36 $this->logoPath
= $logoPath;
42 * @param array|Entry $entries An array of entries or one entry
44 * @return EntriesExport
46 public function setEntries($entries)
48 if (!is_array($entries)) {
49 $this->language
= $entries->getLanguage();
50 $entries = [$entries];
53 $this->entries
= $entries;
59 * Sets the category of which we want to get articles, or just one entry.
61 * @param string $method Method to get articles
63 * @return EntriesExport
65 public function updateTitle($method)
67 $this->title
= $method . ' articles';
69 if ('entry' === $method) {
70 $this->title
= $this->entries
[0]->getTitle();
77 * Sets the author for one entry or category.
79 * The publishers are used, or the domain name if empty.
81 * @param string $method Method to get articles
83 * @return EntriesExport
85 public function updateAuthor($method)
87 if ('entry' !== $method) {
88 $this->author
= $method . ' authors';
93 $this->author
= $this->entries
[0]->getDomainName();
95 $publishedBy = $this->entries
[0]->getPublishedBy();
96 if (!empty($publishedBy)) {
97 $this->author
= implode(', ', $publishedBy);
104 * Sets the output format.
106 * @param string $format
110 public function exportAs($format)
112 $functionName = 'produce' . ucfirst($format);
113 if (method_exists($this, $functionName)) {
114 return $this->$functionName();
117 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
120 public function exportJsonData()
122 return $this->prepareSerializingContent('json');
126 * Use PHPePub to dump a .epub file.
130 private function produceEpub()
133 * Start and End of the book
136 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
137 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
139 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
140 . "<title>wallabag articles book</title>\n"
144 $bookEnd = "</body>\n</html>\n";
146 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
152 $book->setTitle($this->title
);
153 // Could also be the ISBN number, prefered for published books, or a UUID.
154 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
155 // 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.
156 $book->setLanguage($this->language
);
157 $book->setDescription('Some articles saved on my wallabag');
159 $book->setAuthor($this->author
, $this->author
);
161 // I hope this is a non existant address :)
162 $book->setPublisher('wallabag', 'wallabag');
163 // Strictly not needed as the book date defaults to time().
164 $book->setDate(time());
165 $book->setSourceURL($this->wallabagUrl
);
167 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
168 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
173 if (file_exists($this->logoPath
)) {
174 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
180 * Adding actual entries
183 // set tags as subjects
184 foreach ($this->entries
as $entry) {
185 foreach ($entry->getTags() as $tag) {
186 $book->setSubject($tag->getLabel());
189 // the reader in Kobo Devices doesn't likes special caracters
190 // in filenames, we limit to A-z/0-9
191 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
193 $titlepage = "<h1>".$entry->getTitle()."</h1>";
194 $chapter = $content_start . $titlepage . $entry->getContent() . $bookEnd;
195 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
198 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
200 return Response
::create(
204 'Content-Description' => 'File Transfer',
205 'Content-type' => 'application/epub+zip',
206 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.epub"',
207 'Content-Transfer-Encoding' => 'binary',
213 * Use PHPMobi to dump a .mobi file.
217 private function produceMobi()
220 $content = new \
MOBIFile();
225 $content->set('title', $this->title
);
226 $content->set('author', $this->author
);
227 $content->set('subject', $this->title
);
232 $content->appendParagraph($this->getExportInformation('PHPMobi'));
233 if (file_exists($this->logoPath
)) {
234 $content->appendImage(imagecreatefrompng($this->logoPath
));
236 $content->appendPageBreak();
239 * Adding actual entries
241 foreach ($this->entries
as $entry) {
242 $content->appendChapterTitle($entry->getTitle());
243 $content->appendParagraph($entry->getContent());
244 $content->appendPageBreak();
246 $mobi->setContentProvider($content);
248 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
249 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
251 return Response
::create(
255 'Accept-Ranges' => 'bytes',
256 'Content-Description' => 'File Transfer',
257 'Content-type' => 'application/x-mobipocket-ebook',
258 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.mobi"',
259 'Content-Transfer-Encoding' => 'binary',
265 * Use TCPDF to dump a .pdf file.
269 private function producePdf()
271 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
276 $pdf->SetCreator(PDF_CREATOR
);
277 $pdf->SetAuthor($this->author
);
278 $pdf->SetTitle($this->title
);
279 $pdf->SetSubject('Articles via wallabag');
280 $pdf->SetKeywords('wallabag');
286 $intro = '<h1>' . $this->title
. '</h1>' . $this->getExportInformation('tcpdf');
288 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
291 * Adding actual entries
293 foreach ($this->entries
as $entry) {
294 foreach ($entry->getTags() as $tag) {
295 $pdf->SetKeywords($tag->getLabel());
299 $html = '<h1>' . $entry->getTitle() . '</h1>';
300 $html .= $entry->getContent();
302 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
305 // set image scale factor
306 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
308 return Response
::create(
309 $pdf->Output('', 'S'),
312 'Content-Description' => 'File Transfer',
313 'Content-type' => 'application/pdf',
314 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.pdf"',
315 'Content-Transfer-Encoding' => 'binary',
321 * Inspired from CsvFileDumper.
325 private function produceCsv()
329 $handle = fopen('php://memory', 'rb+');
331 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
333 foreach ($this->entries
as $entry) {
339 // remove new line to avoid crazy results
340 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
341 implode(', ', $entry->getTags()->toArray()),
342 $entry->getMimetype(),
343 $entry->getLanguage(),
344 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
352 $output = stream_get_contents($handle);
355 return Response
::create(
359 'Content-type' => 'application/csv',
360 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.csv"',
361 'Content-Transfer-Encoding' => 'UTF-8',
371 private function produceJson()
373 return Response
::create(
374 $this->prepareSerializingContent('json'),
377 'Content-type' => 'application/json',
378 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.json"',
379 'Content-Transfer-Encoding' => 'UTF-8',
389 private function produceXml()
391 return Response
::create(
392 $this->prepareSerializingContent('xml'),
395 'Content-type' => 'application/xml',
396 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.xml"',
397 'Content-Transfer-Encoding' => 'UTF-8',
407 private function produceTxt()
410 $bar = str_repeat('=', 100);
411 foreach ($this->entries
as $entry) {
412 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
413 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
414 $content .= $html->getText();
417 return Response
::create(
421 'Content-type' => 'text/plain',
422 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.txt"',
423 'Content-Transfer-Encoding' => 'UTF-8',
429 * Return a Serializer object for producing processes that need it (JSON & XML).
431 * @param string $format
435 private function prepareSerializingContent($format)
437 $serializer = SerializerBuilder
::create()->build();
439 return $serializer->serialize(
442 SerializationContext
::create()->setGroups(['entries_for_user'])
447 * Return a kind of footer / information for the epub.
449 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
453 private function getExportInformation($type)
455 $info = $this->translator
->trans('export.footer_template', [
459 if ('tcpdf' === $type) {
460 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
463 return str_replace('%IMAGE%', '', $info);