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 // 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.
154 $book->setLanguage($this->language
);
155 $book->setDescription('Some articles saved on my wallabag');
157 $book->setAuthor($this->author
, $this->author
);
159 // I hope this is a non existant address :)
160 $book->setPublisher('wallabag', 'wallabag');
161 // Strictly not needed as the book date defaults to time().
162 $book->setDate(time());
163 $book->setSourceURL($this->wallabagUrl
);
165 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
166 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
171 if (file_exists($this->logoPath
)) {
172 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
178 * Adding actual entries
181 // set tags as subjects
182 foreach ($this->entries
as $entry) {
183 foreach ($entry->getTags() as $tag) {
184 $book->setSubject($tag->getLabel());
187 // the reader in Kobo Devices doesn't likes special caracters
188 // in filenames, we limit to A-z/0-9
189 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
191 $titlepage = $content_start . '<h1>' . $entry->getTitle() . '</h1>' . $this->getExportInformation('PHPePub') . $bookEnd;
192 $book->addChapter('Title', 'Title.html', $titlepage, true, EPub
::EXTERNAL_REF_ADD
);
193 $chapter = $content_start . $entry->getContent() . $bookEnd;
194 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
196 $entryIds[] = $entry->getId();
199 // Could also be the ISBN number, prefered for published books, or a UUID.
200 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl
, implode(',', $entryIds)));
201 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub
::IDENTIFIER_URI
);
205 return Response
::create(
209 'Content-Description' => 'File Transfer',
210 'Content-type' => 'application/epub+zip',
211 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.epub"',
212 'Content-Transfer-Encoding' => 'binary',
218 * Use PHPMobi to dump a .mobi file.
222 private function produceMobi()
225 $content = new \
MOBIFile();
230 $content->set('title', $this->title
);
231 $content->set('author', $this->author
);
232 $content->set('subject', $this->title
);
237 $content->appendParagraph($this->getExportInformation('PHPMobi'));
238 if (file_exists($this->logoPath
)) {
239 $content->appendImage(imagecreatefrompng($this->logoPath
));
241 $content->appendPageBreak();
244 * Adding actual entries
246 foreach ($this->entries
as $entry) {
247 $content->appendChapterTitle($entry->getTitle());
248 $content->appendParagraph($entry->getContent());
249 $content->appendPageBreak();
251 $mobi->setContentProvider($content);
253 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
254 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
256 return Response
::create(
260 'Accept-Ranges' => 'bytes',
261 'Content-Description' => 'File Transfer',
262 'Content-type' => 'application/x-mobipocket-ebook',
263 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.mobi"',
264 'Content-Transfer-Encoding' => 'binary',
270 * Use TCPDF to dump a .pdf file.
274 private function producePdf()
276 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
281 $pdf->SetCreator(PDF_CREATOR
);
282 $pdf->SetAuthor($this->author
);
283 $pdf->SetTitle($this->title
);
284 $pdf->SetSubject('Articles via wallabag');
285 $pdf->SetKeywords('wallabag');
291 $intro = '<h1>' . $this->title
. '</h1>' . $this->getExportInformation('tcpdf');
293 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
296 * Adding actual entries
298 foreach ($this->entries
as $entry) {
299 foreach ($entry->getTags() as $tag) {
300 $pdf->SetKeywords($tag->getLabel());
304 $html = '<h1>' . $entry->getTitle() . '</h1>';
305 $html .= $entry->getContent();
307 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
310 // set image scale factor
311 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
313 return Response
::create(
314 $pdf->Output('', 'S'),
317 'Content-Description' => 'File Transfer',
318 'Content-type' => 'application/pdf',
319 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.pdf"',
320 'Content-Transfer-Encoding' => 'binary',
326 * Inspired from CsvFileDumper.
330 private function produceCsv()
334 $handle = fopen('php://memory', 'b+r');
336 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
338 foreach ($this->entries
as $entry) {
344 // remove new line to avoid crazy results
345 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
346 implode(', ', $entry->getTags()->toArray()),
347 $entry->getMimetype(),
348 $entry->getLanguage(),
349 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
357 $output = stream_get_contents($handle);
360 return Response
::create(
364 'Content-type' => 'application/csv',
365 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.csv"',
366 'Content-Transfer-Encoding' => 'UTF-8',
376 private function produceJson()
378 return Response
::create(
379 $this->prepareSerializingContent('json'),
382 'Content-type' => 'application/json',
383 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.json"',
384 'Content-Transfer-Encoding' => 'UTF-8',
394 private function produceXml()
396 return Response
::create(
397 $this->prepareSerializingContent('xml'),
400 'Content-type' => 'application/xml',
401 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.xml"',
402 'Content-Transfer-Encoding' => 'UTF-8',
412 private function produceTxt()
415 $bar = str_repeat('=', 100);
416 foreach ($this->entries
as $entry) {
417 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
418 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
419 $content .= $html->getText();
422 return Response
::create(
426 'Content-type' => 'text/plain',
427 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.txt"',
428 'Content-Transfer-Encoding' => 'UTF-8',
434 * Return a Serializer object for producing processes that need it (JSON & XML).
436 * @param string $format
440 private function prepareSerializingContent($format)
442 $serializer = SerializerBuilder
::create()->build();
444 return $serializer->serialize(
447 SerializationContext
::create()->setGroups(['entries_for_user'])
452 * Return a kind of footer / information for the epub.
454 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
458 private function getExportInformation($type)
460 $info = $this->translator
->trans('export.footer_template', [
464 if ('tcpdf' === $type) {
465 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
468 return str_replace('%IMAGE%', '', $info);