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();
104 return $this->produceTXT();
107 throw new \
InvalidArgumentException(sprintf('The format "%s" is not yet supported.', $format));
111 * Use PHPePub to dump a .epub file.
113 private function produceEpub()
116 * Start and End of the book
119 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
120 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
122 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
123 ."<title>wallabag articles book</title>\n"
127 $bookEnd = "</body>\n</html>\n";
129 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
135 $book->setTitle($this->title
);
136 // Could also be the ISBN number, prefered for published books, or a UUID.
137 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
138 // 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.
139 $book->setLanguage($this->language
);
140 $book->setDescription('Some articles saved on my wallabag');
142 foreach ($this->authors
as $author) {
143 $book->setAuthor($author, $author);
146 // I hope this is a non existant address :)
147 $book->setPublisher('wallabag', 'wallabag');
148 // Strictly not needed as the book date defaults to time().
149 $book->setDate(time());
150 $book->setSourceURL($this->wallabagUrl
);
152 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
153 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
158 if (file_exists($this->logoPath
)) {
159 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
162 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
167 * Adding actual entries
170 // set tags as subjects
171 foreach ($this->entries
as $entry) {
172 foreach ($this->tags
as $tag) {
173 $book->setSubject($tag['value']);
176 $chapter = $content_start.$entry->getContent().$bookEnd;
177 $book->addChapter($entry->getTitle(), htmlspecialchars($entry->getTitle()).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
180 return Response
::create(
184 'Content-Description' => 'File Transfer',
185 'Content-type' => 'application/epub+zip',
186 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
187 'Content-Transfer-Encoding' => 'binary',
193 * Use PHPMobi to dump a .mobi file.
195 private function produceMobi()
198 $content = new \
MOBIFile();
203 $content->set('title', $this->title
);
204 $content->set('author', implode($this->authors
));
205 $content->set('subject', $this->title
);
210 $content->appendParagraph($this->getExportInformation('PHPMobi'));
211 if (file_exists($this->logoPath
)) {
212 $content->appendImage(imagecreatefrompng($this->logoPath
));
214 $content->appendPageBreak();
217 * Adding actual entries
219 foreach ($this->entries
as $entry) {
220 $content->appendChapterTitle($entry->getTitle());
221 $content->appendParagraph($entry->getContent());
222 $content->appendPageBreak();
224 $mobi->setContentProvider($content);
226 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
227 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
229 return Response
::create(
233 'Accept-Ranges' => 'bytes',
234 'Content-Description' => 'File Transfer',
235 'Content-type' => 'application/x-mobipocket-ebook',
236 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
237 'Content-Transfer-Encoding' => 'binary',
243 * Use TCPDF to dump a .pdf file.
245 private function producePDF()
247 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
252 $pdf->SetCreator(PDF_CREATOR
);
253 $pdf->SetAuthor('wallabag');
254 $pdf->SetTitle($this->title
);
255 $pdf->SetSubject('Articles via wallabag');
256 $pdf->SetKeywords('wallabag');
262 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
264 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
267 * Adding actual entries
269 foreach ($this->entries
as $entry) {
270 foreach ($this->tags
as $tag) {
271 $pdf->SetKeywords($tag['value']);
275 $html = '<h1>'.$entry->getTitle().'</h1>';
276 $html .= $entry->getContent();
278 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
281 // set image scale factor
282 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
284 return Response
::create(
285 $pdf->Output('', 'S'),
288 'Content-Description' => 'File Transfer',
289 'Content-type' => 'application/pdf',
290 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
291 'Content-Transfer-Encoding' => 'binary',
297 * Inspired from CsvFileDumper.
299 private function produceCSV()
303 $handle = fopen('php://memory', 'rb+');
305 fputcsv($handle, array('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(array("\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',
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',
352 private function produceXML()
354 return Response
::create(
355 $this->prepareSerializingContent('xml'),
358 'Content-type' => 'application/xml',
359 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
360 'Content-Transfer-Encoding' => 'UTF-8',
365 private function produceTXT()
368 $bar = str_repeat('=', 100);
369 foreach ($this->entries
as $entry) {
370 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
371 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
374 return Response
::create(
378 'Content-type' => 'text/plain',
379 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
380 'Content-Transfer-Encoding' => 'UTF-8',
386 * Return a Serializer object for producing processes that need it (JSON & XML).
390 private function prepareSerializingContent($format)
392 $serializer = SerializerBuilder
::create()->build();
394 return $serializer->serialize(
397 SerializationContext
::create()->setGroups(array('entries_for_user'))
402 * Return a kind of footer / information for the epub.
404 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
408 private function getExportInformation($type)
410 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
412 if ('tcpdf' === $type) {
413 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
416 return str_replace('%IMAGE%', '', $info);