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
= 'Various 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');
169 $entryCount = \
count($this->entries
);
173 * Adding actual entries
176 // set tags as subjects
177 foreach ($this->entries
as $entry) {
182 * Set if there's only one entry in the given set
184 if (1 === $entryCount && null !== $entry->getPreviewPicture()) {
185 $book->setCoverImage($entry->getPreviewPicture());
188 foreach ($entry->getTags() as $tag) {
189 $book->setSubject($tag->getLabel());
191 $filename = sha1(sprintf('%s:%s', $entry->getUrl(), $entry->getTitle()));
193 $publishedBy = $entry->getPublishedBy();
194 $authors = $this->translator
->trans('export.unknown');
195 if (!empty($publishedBy)) {
196 $authors = implode(',', $publishedBy);
199 $titlepage = $content_start .
200 '<h1>' . $entry->getTitle() . '</h1>' .
202 '<dt>' . $this->translator
->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
203 '<dt>' . $this->translator
->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator
->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
204 '<dt>' . $this->translator
->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
205 '<dt>' . $this->translator
->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
208 $book->addChapter("Entry {$i} of {$entryCount}", "{$filename}_cover.html", $titlepage, true, EPub
::EXTERNAL_REF_ADD
);
209 $chapter = $content_start . $entry->getContent() . $bookEnd;
211 $entryIds[] = $entry->getId();
212 $book->addChapter($entry->getTitle(), "{$filename}.html", $chapter, true, EPub
::EXTERNAL_REF_ADD
);
215 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
217 // Could also be the ISBN number, prefered for published books, or a UUID.
218 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl
, implode(',', $entryIds)));
219 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub
::IDENTIFIER_URI
);
221 return Response
::create(
225 'Content-Description' => 'File Transfer',
226 'Content-type' => 'application/epub+zip',
227 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.epub"',
228 'Content-Transfer-Encoding' => 'binary',
234 * Use PHPMobi to dump a .mobi file.
238 private function produceMobi()
241 $content = new \
MOBIFile();
246 $content->set('title', $this->title
);
247 $content->set('author', $this->author
);
248 $content->set('subject', $this->title
);
253 $content->appendParagraph($this->getExportInformation('PHPMobi'));
254 if (file_exists($this->logoPath
)) {
255 $content->appendImage(imagecreatefrompng($this->logoPath
));
257 $content->appendPageBreak();
260 * Adding actual entries
262 foreach ($this->entries
as $entry) {
263 $content->appendChapterTitle($entry->getTitle());
264 $content->appendParagraph($entry->getContent());
265 $content->appendPageBreak();
267 $mobi->setContentProvider($content);
269 return Response
::create(
273 'Accept-Ranges' => 'bytes',
274 'Content-Description' => 'File Transfer',
275 'Content-type' => 'application/x-mobipocket-ebook',
276 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.mobi"',
277 'Content-Transfer-Encoding' => 'binary',
283 * Use TCPDF to dump a .pdf file.
287 private function producePdf()
289 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
294 $pdf->SetCreator(PDF_CREATOR
);
295 $pdf->SetAuthor($this->author
);
296 $pdf->SetTitle($this->title
);
297 $pdf->SetSubject('Articles via wallabag');
298 $pdf->SetKeywords('wallabag');
301 * Adding actual entries
303 foreach ($this->entries
as $entry) {
304 foreach ($entry->getTags() as $tag) {
305 $pdf->SetKeywords($tag->getLabel());
308 $publishedBy = $entry->getPublishedBy();
309 $authors = $this->translator
->trans('export.unknown');
310 if (!empty($publishedBy)) {
311 $authors = implode(',', $publishedBy);
315 $html = '<h1>' . $entry->getTitle() . '</h1>' .
317 '<dt>' . $this->translator
->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
318 '<dt>' . $this->translator
->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator
->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
319 '<dt>' . $this->translator
->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
320 '<dt>' . $this->translator
->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
322 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
325 $html = '<h1>' . $entry->getTitle() . '</h1>';
326 $html .= $entry->getContent();
328 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
335 $html = $this->getExportInformation('tcpdf');
337 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
339 // set image scale factor
340 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
342 return Response
::create(
343 $pdf->Output('', 'S'),
346 'Content-Description' => 'File Transfer',
347 'Content-type' => 'application/pdf',
348 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.pdf"',
349 'Content-Transfer-Encoding' => 'binary',
355 * Inspired from CsvFileDumper.
359 private function produceCsv()
363 $handle = fopen('php://memory', 'b+r');
365 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
367 foreach ($this->entries
as $entry) {
373 // remove new line to avoid crazy results
374 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
375 implode(', ', $entry->getTags()->toArray()),
376 $entry->getMimetype(),
377 $entry->getLanguage(),
378 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
386 $output = stream_get_contents($handle);
389 return Response
::create(
393 'Content-type' => 'application/csv',
394 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.csv"',
395 'Content-Transfer-Encoding' => 'UTF-8',
405 private function produceJson()
407 return Response
::create(
408 $this->prepareSerializingContent('json'),
411 'Content-type' => 'application/json',
412 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.json"',
413 'Content-Transfer-Encoding' => 'UTF-8',
423 private function produceXml()
425 return Response
::create(
426 $this->prepareSerializingContent('xml'),
429 'Content-type' => 'application/xml',
430 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.xml"',
431 'Content-Transfer-Encoding' => 'UTF-8',
441 private function produceTxt()
444 $bar = str_repeat('=', 100);
445 foreach ($this->entries
as $entry) {
446 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
447 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
448 $content .= $html->getText();
451 return Response
::create(
455 'Content-type' => 'text/plain',
456 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.txt"',
457 'Content-Transfer-Encoding' => 'UTF-8',
463 * Return a Serializer object for producing processes that need it (JSON & XML).
465 * @param string $format
469 private function prepareSerializingContent($format)
471 $serializer = SerializerBuilder
::create()->build();
473 return $serializer->serialize(
476 SerializationContext
::create()->setGroups(['entries_for_user'])
481 * Return a kind of footer / information for the epub.
483 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
487 private function getExportInformation($type)
489 $info = $this->translator
->trans('export.footer_template', [
493 if ('tcpdf' === $type) {
494 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
497 return str_replace('%IMAGE%', '', $info);
501 * Return a sanitized version of the title by applying translit iconv
502 * and removing non alphanumeric characters, - and space.
504 * @return string Sanitized filename
506 private function getSanitizedFilename()
508 return preg_replace('/[^A-Za-z0-9\- \']/', '', iconv('utf-8', 'us-ascii//TRANSLIT', $this->title
));