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
;
11 use Craue\ConfigBundle\Util\Config
;
14 * This class doesn't have unit test BUT it's fully covered by a functional test with ExportControllerTest.
21 private $entries = [];
22 private $authors = ['wallabag'];
23 private $language = '';
25 private $footerTemplate = '<div style="text-align:center;">
26 <p>Produced by wallabag with %EXPORT_METHOD%</p>
27 <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>
31 * @param Config $craueConfig CraueConfig instance to get wallabag instance url from database
32 * @param string $logoPath Path to the logo FROM THE BUNDLE SCOPE
34 public function __construct(Config
$craueConfig, $logoPath)
36 $this->wallabagUrl
= $craueConfig->get('wallabag_url');
37 $this->logoPath
= $logoPath;
43 * @param array|Entry $entries An array of entries or one entry
45 * @return EntriesExport
47 public function setEntries($entries)
49 if (!is_array($entries)) {
50 $this->language
= $entries->getLanguage();
51 $entries = [$entries];
54 $this->entries
= $entries;
56 foreach ($entries as $entry) {
57 $this->tags
[] = $entry->getTags();
64 * Sets the category of which we want to get articles, or just one entry.
66 * @param string $method Method to get articles
68 * @return EntriesExport
70 public function updateTitle($method)
72 $this->title
= $method.' articles';
74 if ('entry' === $method) {
75 $this->title
= $this->entries
[0]->getTitle();
82 * Sets the output format.
84 * @param string $format
88 public function exportAs($format)
90 $functionName = 'produce'.ucfirst($format);
91 if (method_exists($this, $functionName)) {
92 return $this->$functionName();
95 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
99 * Use PHPePub to dump a .epub file.
103 private function produceEpub()
106 * Start and End of the book
109 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
110 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
112 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
113 ."<title>wallabag articles book</title>\n"
117 $bookEnd = "</body>\n</html>\n";
119 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
125 $book->setTitle($this->title
);
126 // Could also be the ISBN number, prefered for published books, or a UUID.
127 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
128 // 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.
129 $book->setLanguage($this->language
);
130 $book->setDescription('Some articles saved on my wallabag');
132 foreach ($this->authors
as $author) {
133 $book->setAuthor($author, $author);
136 // I hope this is a non existant address :)
137 $book->setPublisher('wallabag', 'wallabag');
138 // Strictly not needed as the book date defaults to time().
139 $book->setDate(time());
140 $book->setSourceURL($this->wallabagUrl
);
142 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
143 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
148 if (file_exists($this->logoPath
)) {
149 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
152 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
157 * Adding actual entries
160 // set tags as subjects
161 foreach ($this->entries
as $entry) {
162 foreach ($this->tags
as $tag) {
163 $book->setSubject($tag['value']);
166 // the reader in Kobo Devices doesn't likes special caracters
167 // in filenames, we limit to A-z/0-9
168 $filename = preg_replace('/[^A-Za-z0-9\-]/', '', $entry->getTitle());
170 $chapter = $content_start.$entry->getContent().$bookEnd;
171 $book->addChapter($entry->getTitle(), htmlspecialchars($filename).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
174 return Response
::create(
178 'Content-Description' => 'File Transfer',
179 'Content-type' => 'application/epub+zip',
180 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
181 'Content-Transfer-Encoding' => 'binary',
187 * Use PHPMobi to dump a .mobi file.
191 private function produceMobi()
194 $content = new \
MOBIFile();
199 $content->set('title', $this->title
);
200 $content->set('author', implode($this->authors
));
201 $content->set('subject', $this->title
);
206 $content->appendParagraph($this->getExportInformation('PHPMobi'));
207 if (file_exists($this->logoPath
)) {
208 $content->appendImage(imagecreatefrompng($this->logoPath
));
210 $content->appendPageBreak();
213 * Adding actual entries
215 foreach ($this->entries
as $entry) {
216 $content->appendChapterTitle($entry->getTitle());
217 $content->appendParagraph($entry->getContent());
218 $content->appendPageBreak();
220 $mobi->setContentProvider($content);
222 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
223 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
225 return Response
::create(
229 'Accept-Ranges' => 'bytes',
230 'Content-Description' => 'File Transfer',
231 'Content-type' => 'application/x-mobipocket-ebook',
232 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
233 'Content-Transfer-Encoding' => 'binary',
239 * Use TCPDF to dump a .pdf file.
243 private function producePdf()
245 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
250 $pdf->SetCreator(PDF_CREATOR
);
251 $pdf->SetAuthor('wallabag');
252 $pdf->SetTitle($this->title
);
253 $pdf->SetSubject('Articles via wallabag');
254 $pdf->SetKeywords('wallabag');
260 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
262 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
265 * Adding actual entries
267 foreach ($this->entries
as $entry) {
268 foreach ($this->tags
as $tag) {
269 $pdf->SetKeywords($tag['value']);
273 $html = '<h1>'.$entry->getTitle().'</h1>';
274 $html .= $entry->getContent();
276 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
279 // set image scale factor
280 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
282 return Response
::create(
283 $pdf->Output('', 'S'),
286 'Content-Description' => 'File Transfer',
287 'Content-type' => 'application/pdf',
288 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
289 'Content-Transfer-Encoding' => 'binary',
295 * Inspired from CsvFileDumper.
299 private function produceCsv()
303 $handle = fopen('php://memory', 'rb+');
305 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language'], $delimiter, $enclosure);
307 foreach ($this->entries
as $entry) {
313 // remove new line to avoid crazy results
314 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
315 implode(', ', $entry->getTags()->toArray()),
316 $entry->getMimetype(),
317 $entry->getLanguage(),
325 $output = stream_get_contents($handle);
328 return Response
::create(
332 'Content-type' => 'application/csv',
333 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.csv"',
334 'Content-Transfer-Encoding' => 'UTF-8',
344 private function produceJson()
346 return Response
::create(
347 $this->prepareSerializingContent('json'),
350 'Content-type' => 'application/json',
351 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.json"',
352 'Content-Transfer-Encoding' => 'UTF-8',
362 private function produceXml()
364 return Response
::create(
365 $this->prepareSerializingContent('xml'),
368 'Content-type' => 'application/xml',
369 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
370 'Content-Transfer-Encoding' => 'UTF-8',
380 private function produceTxt()
383 $bar = str_repeat('=', 100);
384 foreach ($this->entries
as $entry) {
385 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
386 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
389 return Response
::create(
393 'Content-type' => 'text/plain',
394 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
395 'Content-Transfer-Encoding' => 'UTF-8',
401 * Return a Serializer object for producing processes that need it (JSON & XML).
403 * @param string $format
407 private function prepareSerializingContent($format)
409 $serializer = SerializerBuilder
::create()->build();
411 return $serializer->serialize(
414 SerializationContext
::create()->setGroups(['entries_for_user'])
419 * Return a kind of footer / information for the epub.
421 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
425 private function getExportInformation($type)
427 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
429 if ('tcpdf' === $type) {
430 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
433 return str_replace('%IMAGE%', '', $info);