3 namespace Wallabag\CoreBundle\Helper
;
5 use JMS\Serializer\SerializationContext
;
6 use JMS\Serializer\SerializerBuilder
;
8 use PHPePub\Core\Structure\OPF\DublinCore
;
9 use Symfony\Component\HttpFoundation\Response
;
10 use Wallabag\CoreBundle\Entity\Entry
;
13 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
20 private $entries = [];
21 private $author = 'wallabag';
22 private $language = '';
23 private $footerTemplate = '<div style="text-align:center;">
24 <p>Produced by wallabag with %EXPORT_METHOD%</p>
25 <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>
29 * @param string $wallabagUrl Wallabag instance url
30 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
32 public function __construct($wallabagUrl, $logoPath)
34 $this->wallabagUrl
= $wallabagUrl;
35 $this->logoPath
= $logoPath;
41 * @param array|Entry $entries An array of entries or one entry
43 * @return EntriesExport
45 public function setEntries($entries)
47 if (!is_array($entries)) {
48 $this->language
= $entries->getLanguage();
49 $entries = [$entries];
52 $this->entries
= $entries;
58 * Sets the category of which we want to get articles, or just one entry.
60 * @param string $method Method to get articles
62 * @return EntriesExport
64 public function updateTitle($method)
66 $this->title
= $method . ' articles';
68 if ('entry' === $method) {
69 $this->title
= $this->entries
[0]->getTitle();
76 * Sets the author for one entry or category.
78 * The publishers are used, or the domain name if empty.
80 * @param string $method Method to get articles
82 * @return EntriesExport
84 public function updateAuthor($method)
86 if ('entry' !== $method) {
87 $this->author
= $method . ' authors';
92 $this->author
= $this->entries
[0]->getDomainName();
94 $publishedBy = $this->entries
[0]->getPublishedBy();
95 if (!empty($publishedBy)) {
96 $this->author
= implode(', ', $publishedBy);
103 * Sets the output format.
105 * @param string $format
109 public function exportAs($format)
111 $functionName = 'produce' . ucfirst($format);
112 if (method_exists($this, $functionName)) {
113 return $this->$functionName();
116 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
119 public function exportJsonData()
121 return $this->prepareSerializingContent('json');
125 * Use PHPePub to dump a .epub file.
129 private function produceEpub()
132 * Start and End of the book
135 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
136 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
138 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
139 . "<title>wallabag articles book</title>\n"
143 $bookEnd = "</body>\n</html>\n";
145 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
151 $book->setTitle($this->title
);
152 // Could also be the ISBN number, prefered for published books, or a UUID.
153 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
154 // 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.
155 $book->setLanguage($this->language
);
156 $book->setDescription('Some articles saved on my wallabag');
158 $book->setAuthor($this->author
, $this->author
);
160 // I hope this is a non existant address :)
161 $book->setPublisher('wallabag', 'wallabag');
162 // Strictly not needed as the book date defaults to time().
163 $book->setDate(time());
164 $book->setSourceURL($this->wallabagUrl
);
166 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
167 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
172 if (file_exists($this->logoPath
)) {
173 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
179 * Adding actual entries
182 // set tags as subjects
183 foreach ($this->entries
as $entry) {
184 foreach ($entry->getTags() as $tag) {
185 $book->setSubject($tag->getLabel());
188 // the reader in Kobo Devices doesn't likes special caracters
189 // in filenames, we limit to A-z/0-9
190 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
192 $chapter = $content_start . $entry->getContent() . $bookEnd;
193 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
196 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
198 return Response
::create(
202 'Content-Description' => 'File Transfer',
203 'Content-type' => 'application/epub+zip',
204 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.epub"',
205 'Content-Transfer-Encoding' => 'binary',
211 * Use PHPMobi to dump a .mobi file.
215 private function produceMobi()
218 $content = new \
MOBIFile();
223 $content->set('title', $this->title
);
224 $content->set('author', $this->author
);
225 $content->set('subject', $this->title
);
230 $content->appendParagraph($this->getExportInformation('PHPMobi'));
231 if (file_exists($this->logoPath
)) {
232 $content->appendImage(imagecreatefrompng($this->logoPath
));
234 $content->appendPageBreak();
237 * Adding actual entries
239 foreach ($this->entries
as $entry) {
240 $content->appendChapterTitle($entry->getTitle());
241 $content->appendParagraph($entry->getContent());
242 $content->appendPageBreak();
244 $mobi->setContentProvider($content);
246 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
247 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
249 return Response
::create(
253 'Accept-Ranges' => 'bytes',
254 'Content-Description' => 'File Transfer',
255 'Content-type' => 'application/x-mobipocket-ebook',
256 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.mobi"',
257 'Content-Transfer-Encoding' => 'binary',
263 * Use TCPDF to dump a .pdf file.
267 private function producePdf()
269 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
274 $pdf->SetCreator(PDF_CREATOR
);
275 $pdf->SetAuthor($this->author
);
276 $pdf->SetTitle($this->title
);
277 $pdf->SetSubject('Articles via wallabag');
278 $pdf->SetKeywords('wallabag');
284 $intro = '<h1>' . $this->title
. '</h1>' . $this->getExportInformation('tcpdf');
286 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
289 * Adding actual entries
291 foreach ($this->entries
as $entry) {
292 foreach ($entry->getTags() as $tag) {
293 $pdf->SetKeywords($tag->getLabel());
297 $html = '<h1>' . $entry->getTitle() . '</h1>';
298 $html .= $entry->getContent();
300 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
303 // set image scale factor
304 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
306 return Response
::create(
307 $pdf->Output('', 'S'),
310 'Content-Description' => 'File Transfer',
311 'Content-type' => 'application/pdf',
312 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.pdf"',
313 'Content-Transfer-Encoding' => 'binary',
319 * Inspired from CsvFileDumper.
323 private function produceCsv()
327 $handle = fopen('php://memory', 'rb+');
329 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
331 foreach ($this->entries
as $entry) {
337 // remove new line to avoid crazy results
338 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
339 implode(', ', $entry->getTags()->toArray()),
340 $entry->getMimetype(),
341 $entry->getLanguage(),
342 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
350 $output = stream_get_contents($handle);
353 return Response
::create(
357 'Content-type' => 'application/csv',
358 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.csv"',
359 'Content-Transfer-Encoding' => 'UTF-8',
369 private function produceJson()
371 return Response
::create(
372 $this->prepareSerializingContent('json'),
375 'Content-type' => 'application/json',
376 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.json"',
377 'Content-Transfer-Encoding' => 'UTF-8',
387 private function produceXml()
389 return Response
::create(
390 $this->prepareSerializingContent('xml'),
393 'Content-type' => 'application/xml',
394 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.xml"',
395 'Content-Transfer-Encoding' => 'UTF-8',
405 private function produceTxt()
408 $bar = str_repeat('=', 100);
409 foreach ($this->entries
as $entry) {
410 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
411 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent()))) . "\n\n";
414 return Response
::create(
418 'Content-type' => 'text/plain',
419 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.txt"',
420 'Content-Transfer-Encoding' => 'UTF-8',
426 * Return a Serializer object for producing processes that need it (JSON & XML).
428 * @param string $format
432 private function prepareSerializingContent($format)
434 $serializer = SerializerBuilder
::create()->build();
436 return $serializer->serialize(
439 SerializationContext
::create()->setGroups(['entries_for_user'])
444 * Return a kind of footer / information for the epub.
446 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
450 private function getExportInformation($type)
452 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
454 if ('tcpdf' === $type) {
455 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
458 return str_replace('%IMAGE%', '', $info);