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 = array();
22 private $authors = array('wallabag');
23 private $language = '';
24 private $tags = array();
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 public function setEntries($entries)
47 if (!is_array($entries)) {
48 $this->language
= $entries->getLanguage();
49 $entries = array($entries);
52 $this->entries
= $entries;
54 foreach ($entries as $entry) {
55 $this->tags
[] = $entry->getTags();
62 * Sets the category of which we want to get articles, or just one entry.
64 * @param string $method Method to get articles
66 public function updateTitle($method)
68 $this->title
= $method.' articles';
70 if ('entry' === $method) {
71 $this->title
= $this->entries
[0]->getTitle();
78 * Sets the output format.
80 * @param string $format
82 public function exportAs($format)
86 return $this->produceEpub();
89 return $this->produceMobi();
92 return $this->producePDF();
95 return $this->produceCSV();
98 return $this->produceJSON();
101 return $this->produceXML();
103 return $this->produceTXT();
106 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
110 * Use PHPePub to dump a .epub file.
112 private function produceEpub()
115 * Start and End of the book
118 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
119 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
121 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
122 ."<title>wallabag articles book</title>\n"
126 $bookEnd = "</body>\n</html>\n";
128 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
134 $book->setTitle($this->title
);
135 // Could also be the ISBN number, prefered for published books, or a UUID.
136 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
137 // 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.
138 $book->setLanguage($this->language
);
139 $book->setDescription('Some articles saved on my wallabag');
141 foreach ($this->authors
as $author) {
142 $book->setAuthor($author, $author);
145 // I hope this is a non existant address :)
146 $book->setPublisher('wallabag', 'wallabag');
147 // Strictly not needed as the book date defaults to time().
148 $book->setDate(time());
149 $book->setSourceURL($this->wallabagUrl
);
151 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
152 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
157 if (file_exists($this->logoPath
)) {
158 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
161 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
166 * Adding actual entries
169 // set tags as subjects
170 foreach ($this->entries
as $entry) {
171 foreach ($this->tags
as $tag) {
172 $book->setSubject($tag['value']);
175 $chapter = $content_start.$entry->getContent().$bookEnd;
176 $book->addChapter($entry->getTitle(), htmlspecialchars($entry->getTitle()).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
179 return Response
::create(
183 'Content-Description' => 'File Transfer',
184 'Content-type' => 'application/epub+zip',
185 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
186 'Content-Transfer-Encoding' => 'binary',
192 * Use PHPMobi to dump a .mobi file.
194 private function produceMobi()
197 $content = new \
MOBIFile();
202 $content->set('title', $this->title
);
203 $content->set('author', implode($this->authors
));
204 $content->set('subject', $this->title
);
209 $content->appendParagraph($this->getExportInformation('PHPMobi'));
210 if (file_exists($this->logoPath
)) {
211 $content->appendImage(imagecreatefrompng($this->logoPath
));
213 $content->appendPageBreak();
216 * Adding actual entries
218 foreach ($this->entries
as $entry) {
219 $content->appendChapterTitle($entry->getTitle());
220 $content->appendParagraph($entry->getContent());
221 $content->appendPageBreak();
223 $mobi->setContentProvider($content);
225 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
226 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
228 return Response
::create(
232 'Accept-Ranges' => 'bytes',
233 'Content-Description' => 'File Transfer',
234 'Content-type' => 'application/x-mobipocket-ebook',
235 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
236 'Content-Transfer-Encoding' => 'binary',
242 * Use TCPDF to dump a .pdf file.
244 private function producePDF()
246 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
251 $pdf->SetCreator(PDF_CREATOR
);
252 $pdf->SetAuthor('wallabag');
253 $pdf->SetTitle($this->title
);
254 $pdf->SetSubject('Articles via wallabag');
255 $pdf->SetKeywords('wallabag');
261 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
263 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
266 * Adding actual entries
268 foreach ($this->entries
as $entry) {
269 foreach ($this->tags
as $tag) {
270 $pdf->SetKeywords($tag['value']);
274 $html = '<h1>'.$entry->getTitle().'</h1>';
275 $html .= $entry->getContent();
277 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
280 // set image scale factor
281 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
283 return Response
::create(
284 $pdf->Output('', 'S'),
287 'Content-Description' => 'File Transfer',
288 'Content-type' => 'application/pdf',
289 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
290 'Content-Transfer-Encoding' => 'binary',
296 * Inspired from CsvFileDumper.
298 private function produceCSV()
302 $handle = fopen('php://memory', 'rb+');
304 fputcsv($handle, array('Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language'), $delimiter, $enclosure);
306 foreach ($this->entries
as $entry) {
312 // remove new line to avoid crazy results
313 str_replace(array("\r\n", "\r", "\n"), '', $entry->getContent()),
314 implode(', ', $entry->getTags()->toArray()),
315 $entry->getMimetype(),
316 $entry->getLanguage(),
324 $output = stream_get_contents($handle);
327 return Response
::create(
331 'Content-type' => 'application/csv',
332 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.csv"',
333 'Content-Transfer-Encoding' => 'UTF-8',
338 private function produceJSON()
340 return Response
::create(
341 $this->prepareSerializingContent('json'),
344 'Content-type' => 'application/json',
345 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.json"',
346 'Content-Transfer-Encoding' => 'UTF-8',
351 private function produceXML()
353 return Response
::create(
354 $this->prepareSerializingContent('xml'),
357 'Content-type' => 'application/xml',
358 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
359 'Content-Transfer-Encoding' => 'UTF-8',
364 private function produceTXT()
367 $bar = str_repeat('=', 100);
368 foreach ($this->entries
as $entry) {
369 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
370 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
373 return Response
::create(
377 'Content-type' => 'text/plain',
378 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
379 'Content-Transfer-Encoding' => 'UTF-8',
385 * Return a Serializer object for producing processes that need it (JSON & XML).
389 private function prepareSerializingContent($format)
391 $serializer = SerializerBuilder
::create()->build();
393 return $serializer->serialize(
396 SerializationContext
::create()->setGroups(array('entries_for_user'))
401 * Return a kind of footer / information for the epub.
403 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
407 private function getExportInformation($type)
409 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
411 if ('tcpdf' === $type) {
412 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
415 return str_replace('%IMAGE%', '', $info);