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 $publishedAt = $entry->getPublishedAt();
200 $publishedDate = $this->translator
->trans('export.unknown');
201 if (!empty($publishedAt)) {
202 $publishedDate = $entry->getPublishedAt()->format('Y-m-d');
205 $titlepage = $content_start .
206 '<h1>' . $entry->getTitle() . '</h1>' .
208 '<dt>' . $this->translator
->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
209 '<dt>' . $this->translator
->trans('entry.metadata.published_on') . '</dt><dd>' . $publishedDate . '</dd>' .
210 '<dt>' . $this->translator
->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator
->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
211 '<dt>' . $this->translator
->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
212 '<dt>' . $this->translator
->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
215 $book->addChapter("Entry {$i} of {$entryCount}", "{$filename}_cover.html", $titlepage, true, EPub
::EXTERNAL_REF_ADD
);
216 $chapter = $content_start . $entry->getContent() . $bookEnd;
218 $entryIds[] = $entry->getId();
219 $book->addChapter($entry->getTitle(), "{$filename}.html", $chapter, true, EPub
::EXTERNAL_REF_ADD
);
222 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
224 // Could also be the ISBN number, prefered for published books, or a UUID.
225 $hash = sha1(sprintf('%s:%s', $this->wallabagUrl
, implode(',', $entryIds)));
226 $book->setIdentifier(sprintf('urn:wallabag:%s', $hash), EPub
::IDENTIFIER_URI
);
228 return Response
::create(
232 'Content-Description' => 'File Transfer',
233 'Content-type' => 'application/epub+zip',
234 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.epub"',
235 'Content-Transfer-Encoding' => 'binary',
241 * Use PHPMobi to dump a .mobi file.
245 private function produceMobi()
248 $content = new \
MOBIFile();
253 $content->set('title', $this->title
);
254 $content->set('author', $this->author
);
255 $content->set('subject', $this->title
);
260 $content->appendParagraph($this->getExportInformation('PHPMobi'));
261 if (file_exists($this->logoPath
)) {
262 $content->appendImage(imagecreatefrompng($this->logoPath
));
264 $content->appendPageBreak();
267 * Adding actual entries
269 foreach ($this->entries
as $entry) {
270 $content->appendChapterTitle($entry->getTitle());
271 $content->appendParagraph($entry->getContent());
272 $content->appendPageBreak();
274 $mobi->setContentProvider($content);
276 return Response
::create(
280 'Accept-Ranges' => 'bytes',
281 'Content-Description' => 'File Transfer',
282 'Content-type' => 'application/x-mobipocket-ebook',
283 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.mobi"',
284 'Content-Transfer-Encoding' => 'binary',
290 * Use TCPDF to dump a .pdf file.
294 private function producePdf()
296 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
301 $pdf->SetCreator(PDF_CREATOR
);
302 $pdf->SetAuthor($this->author
);
303 $pdf->SetTitle($this->title
);
304 $pdf->SetSubject('Articles via wallabag');
305 $pdf->SetKeywords('wallabag');
308 * Adding actual entries
310 foreach ($this->entries
as $entry) {
311 foreach ($entry->getTags() as $tag) {
312 $pdf->SetKeywords($tag->getLabel());
315 $publishedBy = $entry->getPublishedBy();
316 $authors = $this->translator
->trans('export.unknown');
317 if (!empty($publishedBy)) {
318 $authors = implode(',', $publishedBy);
322 $html = '<h1>' . $entry->getTitle() . '</h1>' .
324 '<dt>' . $this->translator
->trans('entry.view.published_by') . '</dt><dd>' . $authors . '</dd>' .
325 '<dt>' . $this->translator
->trans('entry.metadata.reading_time') . '</dt><dd>' . $this->translator
->trans('entry.metadata.reading_time_minutes_short', ['%readingTime%' => $entry->getReadingTime()]) . '</dd>' .
326 '<dt>' . $this->translator
->trans('entry.metadata.added_on') . '</dt><dd>' . $entry->getCreatedAt()->format('Y-m-d') . '</dd>' .
327 '<dt>' . $this->translator
->trans('entry.metadata.address') . '</dt><dd><a href="' . $entry->getUrl() . '">' . $entry->getUrl() . '</a></dd>' .
329 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
332 $html = '<h1>' . $entry->getTitle() . '</h1>';
333 $html .= $entry->getContent();
335 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
342 $html = $this->getExportInformation('tcpdf');
344 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
346 // set image scale factor
347 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
349 return Response
::create(
350 $pdf->Output('', 'S'),
353 'Content-Description' => 'File Transfer',
354 'Content-type' => 'application/pdf',
355 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.pdf"',
356 'Content-Transfer-Encoding' => 'binary',
362 * Inspired from CsvFileDumper.
366 private function produceCsv()
370 $handle = fopen('php://memory', 'b+r');
372 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
374 foreach ($this->entries
as $entry) {
380 // remove new line to avoid crazy results
381 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
382 implode(', ', $entry->getTags()->toArray()),
383 $entry->getMimetype(),
384 $entry->getLanguage(),
385 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
393 $output = stream_get_contents($handle);
396 return Response
::create(
400 'Content-type' => 'application/csv',
401 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.csv"',
402 'Content-Transfer-Encoding' => 'UTF-8',
412 private function produceJson()
414 return Response
::create(
415 $this->prepareSerializingContent('json'),
418 'Content-type' => 'application/json',
419 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.json"',
420 'Content-Transfer-Encoding' => 'UTF-8',
430 private function produceXml()
432 return Response
::create(
433 $this->prepareSerializingContent('xml'),
436 'Content-type' => 'application/xml',
437 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.xml"',
438 'Content-Transfer-Encoding' => 'UTF-8',
448 private function produceTxt()
451 $bar = str_repeat('=', 100);
452 foreach ($this->entries
as $entry) {
453 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
454 $html = new Html2Text($entry->getContent(), ['do_links' => 'none', 'width' => 100]);
455 $content .= $html->getText();
458 return Response
::create(
462 'Content-type' => 'text/plain',
463 'Content-Disposition' => 'attachment; filename="' . $this->getSanitizedFilename() . '.txt"',
464 'Content-Transfer-Encoding' => 'UTF-8',
470 * Return a Serializer object for producing processes that need it (JSON & XML).
472 * @param string $format
476 private function prepareSerializingContent($format)
478 $serializer = SerializerBuilder
::create()->build();
480 return $serializer->serialize(
483 SerializationContext
::create()->setGroups(['entries_for_user'])
488 * Return a kind of footer / information for the epub.
490 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
494 private function getExportInformation($type)
496 $info = $this->translator
->trans('export.footer_template', [
500 if ('tcpdf' === $type) {
501 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
504 return str_replace('%IMAGE%', '', $info);
508 * Return a sanitized version of the title by applying translit iconv
509 * and removing non alphanumeric characters, - and space.
511 * @return string Sanitized filename
513 private function getSanitizedFilename()
515 return preg_replace('/[^A-Za-z0-9\- \']/', '', iconv('utf-8', 'us-ascii//TRANSLIT', $this->title
));