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 $authors = ['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 output format.
78 * @param string $format
82 public function exportAs($format)
84 $functionName = 'produce'.ucfirst($format);
85 if (method_exists($this, $functionName)) {
86 return $this->$functionName();
89 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
93 * Use PHPePub to dump a .epub file.
97 private function produceEpub()
100 * Start and End of the book
103 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
104 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
106 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
107 ."<title>wallabag articles book</title>\n"
111 $bookEnd = "</body>\n</html>\n";
113 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
119 $book->setTitle($this->title
);
120 // Could also be the ISBN number, prefered for published books, or a UUID.
121 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
122 // 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.
123 $book->setLanguage($this->language
);
124 $book->setDescription('Some articles saved on my wallabag');
126 foreach ($this->authors
as $author) {
127 $book->setAuthor($author, $author);
130 // I hope this is a non existant address :)
131 $book->setPublisher('wallabag', 'wallabag');
132 // Strictly not needed as the book date defaults to time().
133 $book->setDate(time());
134 $book->setSourceURL($this->wallabagUrl
);
136 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
137 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
142 if (file_exists($this->logoPath
)) {
143 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
146 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
151 * Adding actual entries
154 // set tags as subjects
155 foreach ($this->entries
as $entry) {
156 foreach ($entry->getTags() as $tag) {
157 $book->setSubject($tag->getLabel());
160 // the reader in Kobo Devices doesn't likes special caracters
161 // in filenames, we limit to A-z/0-9
162 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
164 $chapter = $content_start.$entry->getContent().$bookEnd;
165 $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
168 return Response
::create(
172 'Content-Description' => 'File Transfer',
173 'Content-type' => 'application/epub+zip',
174 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
175 'Content-Transfer-Encoding' => 'binary',
181 * Use PHPMobi to dump a .mobi file.
185 private function produceMobi()
188 $content = new \
MOBIFile();
193 $content->set('title', $this->title
);
194 $content->set('author', implode($this->authors
));
195 $content->set('subject', $this->title
);
200 $content->appendParagraph($this->getExportInformation('PHPMobi'));
201 if (file_exists($this->logoPath
)) {
202 $content->appendImage(imagecreatefrompng($this->logoPath
));
204 $content->appendPageBreak();
207 * Adding actual entries
209 foreach ($this->entries
as $entry) {
210 $content->appendChapterTitle($entry->getTitle());
211 $content->appendParagraph($entry->getContent());
212 $content->appendPageBreak();
214 $mobi->setContentProvider($content);
216 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
217 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
219 return Response
::create(
223 'Accept-Ranges' => 'bytes',
224 'Content-Description' => 'File Transfer',
225 'Content-type' => 'application/x-mobipocket-ebook',
226 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
227 'Content-Transfer-Encoding' => 'binary',
233 * Use TCPDF to dump a .pdf file.
237 private function producePdf()
239 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
244 $pdf->SetCreator(PDF_CREATOR
);
245 $pdf->SetAuthor('wallabag');
246 $pdf->SetTitle($this->title
);
247 $pdf->SetSubject('Articles via wallabag');
248 $pdf->SetKeywords('wallabag');
254 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
256 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
259 * Adding actual entries
261 foreach ($this->entries
as $entry) {
262 foreach ($entry->getTags() as $tag) {
263 $pdf->SetKeywords($tag->getLabel());
267 $html = '<h1>'.$entry->getTitle().'</h1>';
268 $html .= $entry->getContent();
270 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
273 // set image scale factor
274 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
276 return Response
::create(
277 $pdf->Output('', 'S'),
280 'Content-Description' => 'File Transfer',
281 'Content-type' => 'application/pdf',
282 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
283 'Content-Transfer-Encoding' => 'binary',
289 * Inspired from CsvFileDumper.
293 private function produceCsv()
297 $handle = fopen('php://memory', 'rb+');
299 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language', 'Creation date'], $delimiter, $enclosure);
301 foreach ($this->entries
as $entry) {
307 // remove new line to avoid crazy results
308 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
309 implode(', ', $entry->getTags()->toArray()),
310 $entry->getMimetype(),
311 $entry->getLanguage(),
312 $entry->getCreatedAt()->format('d/m/Y h:i:s'),
320 $output = stream_get_contents($handle);
323 return Response
::create(
327 'Content-type' => 'application/csv',
328 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.csv"',
329 'Content-Transfer-Encoding' => 'UTF-8',
339 private function produceJson()
341 return Response
::create(
342 $this->prepareSerializingContent('json'),
345 'Content-type' => 'application/json',
346 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.json"',
347 'Content-Transfer-Encoding' => 'UTF-8',
357 private function produceXml()
359 return Response
::create(
360 $this->prepareSerializingContent('xml'),
363 'Content-type' => 'application/xml',
364 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
365 'Content-Transfer-Encoding' => 'UTF-8',
375 private function produceTxt()
378 $bar = str_repeat('=', 100);
379 foreach ($this->entries
as $entry) {
380 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
381 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
384 return Response
::create(
388 'Content-type' => 'text/plain',
389 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
390 'Content-Transfer-Encoding' => 'UTF-8',
396 * Return a Serializer object for producing processes that need it (JSON & XML).
398 * @param string $format
402 private function prepareSerializingContent($format)
404 $serializer = SerializerBuilder
::create()->build();
406 return $serializer->serialize(
409 SerializationContext
::create()->setGroups(['entries_for_user'])
414 * Return a kind of footer / information for the epub.
416 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
420 private function getExportInformation($type)
422 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
424 if ('tcpdf' === $type) {
425 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
428 return str_replace('%IMAGE%', '', $info);