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 $chapter = $content_start.$entry->getContent().$bookEnd;
167 $book->addChapter($entry->getTitle(), htmlspecialchars($entry->getTitle()).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
170 return Response
::create(
174 'Content-Description' => 'File Transfer',
175 'Content-type' => 'application/epub+zip',
176 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
177 'Content-Transfer-Encoding' => 'binary',
183 * Use PHPMobi to dump a .mobi file.
187 private function produceMobi()
190 $content = new \
MOBIFile();
195 $content->set('title', $this->title
);
196 $content->set('author', implode($this->authors
));
197 $content->set('subject', $this->title
);
202 $content->appendParagraph($this->getExportInformation('PHPMobi'));
203 if (file_exists($this->logoPath
)) {
204 $content->appendImage(imagecreatefrompng($this->logoPath
));
206 $content->appendPageBreak();
209 * Adding actual entries
211 foreach ($this->entries
as $entry) {
212 $content->appendChapterTitle($entry->getTitle());
213 $content->appendParagraph($entry->getContent());
214 $content->appendPageBreak();
216 $mobi->setContentProvider($content);
218 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
219 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
221 return Response
::create(
225 'Accept-Ranges' => 'bytes',
226 'Content-Description' => 'File Transfer',
227 'Content-type' => 'application/x-mobipocket-ebook',
228 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
229 'Content-Transfer-Encoding' => 'binary',
235 * Use TCPDF to dump a .pdf file.
239 private function producePdf()
241 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
246 $pdf->SetCreator(PDF_CREATOR
);
247 $pdf->SetAuthor('wallabag');
248 $pdf->SetTitle($this->title
);
249 $pdf->SetSubject('Articles via wallabag');
250 $pdf->SetKeywords('wallabag');
256 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
258 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
261 * Adding actual entries
263 foreach ($this->entries
as $entry) {
264 foreach ($this->tags
as $tag) {
265 $pdf->SetKeywords($tag['value']);
269 $html = '<h1>'.$entry->getTitle().'</h1>';
270 $html .= $entry->getContent();
272 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
275 // set image scale factor
276 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
278 return Response
::create(
279 $pdf->Output('', 'S'),
282 'Content-Description' => 'File Transfer',
283 'Content-type' => 'application/pdf',
284 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
285 'Content-Transfer-Encoding' => 'binary',
291 * Inspired from CsvFileDumper.
295 private function produceCsv()
299 $handle = fopen('php://memory', 'rb+');
301 fputcsv($handle, ['Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language'], $delimiter, $enclosure);
303 foreach ($this->entries
as $entry) {
309 // remove new line to avoid crazy results
310 str_replace(["\r\n", "\r", "\n"], '', $entry->getContent()),
311 implode(', ', $entry->getTags()->toArray()),
312 $entry->getMimetype(),
313 $entry->getLanguage(),
321 $output = stream_get_contents($handle);
324 return Response
::create(
328 'Content-type' => 'application/csv',
329 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.csv"',
330 'Content-Transfer-Encoding' => 'UTF-8',
340 private function produceJson()
342 return Response
::create(
343 $this->prepareSerializingContent('json'),
346 'Content-type' => 'application/json',
347 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.json"',
348 'Content-Transfer-Encoding' => 'UTF-8',
358 private function produceXml()
360 return Response
::create(
361 $this->prepareSerializingContent('xml'),
364 'Content-type' => 'application/xml',
365 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
366 'Content-Transfer-Encoding' => 'UTF-8',
376 private function produceTxt()
379 $bar = str_repeat('=', 100);
380 foreach ($this->entries
as $entry) {
381 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
382 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
385 return Response
::create(
389 'Content-type' => 'text/plain',
390 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
391 'Content-Transfer-Encoding' => 'UTF-8',
397 * Return a Serializer object for producing processes that need it (JSON & XML).
399 * @param string $format
403 private function prepareSerializingContent($format)
405 $serializer = SerializerBuilder
::create()->build();
407 return $serializer->serialize(
410 SerializationContext
::create()->setGroups(['entries_for_user'])
415 * Return a kind of footer / information for the epub.
417 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
421 private function getExportInformation($type)
423 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
425 if ('tcpdf' === $type) {
426 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
429 return str_replace('%IMAGE%', '', $info);