3 namespace Wallabag\CoreBundle\Helper
;
6 use JMS\Serializer\SerializationContext
;
7 use JMS\Serializer\SerializerBuilder
;
9 use PHPePub\Core\Structure\OPF\DublinCore
;
10 use Symfony\Component\HttpFoundation\Response
;
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 just one entry.
78 * @param string $method Method to get articles
80 * @return EntriesExport
82 public function updateAuthor($method)
84 $this->author
= $method.' authors';
86 if ('entry' === $method) {
87 $this->author
= $this->entries
[0]->getDomainName();
94 * Sets the output format.
96 * @param string $format
100 public function exportAs($format)
102 $functionName = 'produce' . ucfirst($format);
103 if (method_exists($this, $functionName)) {
104 return $this->$functionName();
107 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
110 public function exportJsonData()
112 return $this->prepareSerializingContent('json');
116 * Use PHPePub to dump a .epub file.
120 private function produceEpub()
123 * Start and End of the book
126 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
127 . "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
129 . "<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
130 . "<title>wallabag articles book</title>\n"
134 $bookEnd = "</body>\n</html>\n";
136 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
142 $book->setTitle($this->title
);
143 // Could also be the ISBN number, prefered for published books, or a UUID.
144 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
145 // 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.
146 $book->setLanguage($this->language
);
147 $book->setDescription('Some articles saved on my wallabag');
149 $book->setAuthor($this->author
, $this->author
);
151 // I hope this is a non existant address :)
152 $book->setPublisher('wallabag', 'wallabag');
153 // Strictly not needed as the book date defaults to time().
154 $book->setDate(time());
155 $book->setSourceURL($this->wallabagUrl
);
157 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
158 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
163 if (file_exists($this->logoPath
)) {
164 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
170 * Adding actual entries
173 // set tags as subjects
174 foreach ($this->entries
as $entry) {
175 foreach ($entry->getTags() as $tag) {
176 $book->setSubject($tag->getLabel());
179 // the reader in Kobo Devices doesn't likes special caracters
180 // in filenames, we limit to A-z/0-9
181 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
183 $chapter = $content_start . $entry->getContent() . $bookEnd;
184 $book->addChapter($entry->getTitle(), htmlspecialchars($filename) . '.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
187 $book->addChapter('Notices', 'Cover2.html', $content_start . $this->getExportInformation('PHPePub') . $bookEnd);
189 return Response
::create(
193 'Content-Description' => 'File Transfer',
194 'Content-type' => 'application/epub+zip',
195 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.epub"',
196 'Content-Transfer-Encoding' => 'binary',
202 * Use PHPMobi to dump a .mobi file.
206 private function produceMobi()
209 $content = new \
MOBIFile();
214 $content->set('title', $this->title
);
215 $content->set('author', $this->author
);
216 $content->set('subject', $this->title
);
221 $content->appendParagraph($this->getExportInformation('PHPMobi'));
222 if (file_exists($this->logoPath
)) {
223 $content->appendImage(imagecreatefrompng($this->logoPath
));
225 $content->appendPageBreak();
228 * Adding actual entries
230 foreach ($this->entries
as $entry) {
231 $content->appendChapterTitle($entry->getTitle());
232 $content->appendParagraph($entry->getContent());
233 $content->appendPageBreak();
235 $mobi->setContentProvider($content);
237 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
238 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
240 return Response
::create(
244 'Accept-Ranges' => 'bytes',
245 'Content-Description' => 'File Transfer',
246 'Content-type' => 'application/x-mobipocket-ebook',
247 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.mobi"',
248 'Content-Transfer-Encoding' => 'binary',
254 * Use TCPDF to dump a .pdf file.
258 private function producePdf()
260 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
265 $pdf->SetCreator(PDF_CREATOR
);
266 $pdf->SetAuthor($this->author
);
267 $pdf->SetTitle($this->title
);
268 $pdf->SetSubject('Articles via wallabag');
269 $pdf->SetKeywords('wallabag');
275 $intro = '<h1>' . $this->title
. '</h1>' . $this->getExportInformation('tcpdf');
277 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
280 * Adding actual entries
282 foreach ($this->entries
as $entry) {
283 foreach ($entry->getTags() as $tag) {
284 $pdf->SetKeywords($tag->getLabel());
288 $html = '<h1>' . $entry->getTitle() . '</h1>';
289 $html .= $entry->getContent();
291 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
294 // set image scale factor
295 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
297 return Response
::create(
298 $pdf->Output('', 'S'),
301 'Content-Description' => 'File Transfer',
302 'Content-type' => 'application/pdf',
303 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.pdf"',
304 'Content-Transfer-Encoding' => 'binary',
310 * Inspired from CsvFileDumper.
314 private function produceCsv()
318 $handle = fopen('php://memory', 'rb+');
320 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
322 foreach ($this->entries
as $entry) {
328 // remove new line to avoid crazy results
329 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
330 implode(', ', $entry->getTags()->toArray()),
331 $entry->getMimetype(),
332 $entry->getLanguage(),
333 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
341 $output = stream_get_contents($handle);
344 return Response
::create(
348 'Content-type' => 'application/csv',
349 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.csv"',
350 'Content-Transfer-Encoding' => 'UTF-8',
360 private function produceJson()
362 return Response
::create(
363 $this->prepareSerializingContent('json'),
366 'Content-type' => 'application/json',
367 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.json"',
368 'Content-Transfer-Encoding' => 'UTF-8',
378 private function produceXml()
380 return Response
::create(
381 $this->prepareSerializingContent('xml'),
384 'Content-type' => 'application/xml',
385 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.xml"',
386 'Content-Transfer-Encoding' => 'UTF-8',
396 private function produceTxt()
399 $bar = str_repeat('=', 100);
400 foreach ($this->entries
as $entry) {
401 $content .= "\n\n" . $bar . "\n\n" . $entry->getTitle() . "\n\n" . $bar . "\n\n";
402 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent()))) . "\n\n";
405 return Response
::create(
409 'Content-type' => 'text/plain',
410 'Content-Disposition' => 'attachment; filename="' . $this->title
. '.txt"',
411 'Content-Transfer-Encoding' => 'UTF-8',
417 * Return a Serializer object for producing processes that need it (JSON & XML).
419 * @param string $format
423 private function prepareSerializingContent($format)
425 $serializer = SerializerBuilder
::create()->build();
427 return $serializer->serialize(
430 SerializationContext
::create()->setGroups(['entries_for_user'])
435 * Return a kind of footer / information for the epub.
437 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
441 private function getExportInformation($type)
443 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
445 if ('tcpdf' === $type) {
446 return str_replace('%IMAGE%', '<img src="' . $this->logoPath
. '" />', $info);
449 return str_replace('%IMAGE%', '', $info);