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)
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.
95 private function produceEpub()
98 * Start and End of the book
101 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
102 ."<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\">\n"
104 ."<meta http-equiv=\"Default-Style\" content=\"text/html; charset=utf-8\" />\n"
105 ."<title>wallabag articles book</title>\n"
109 $bookEnd = "</body>\n</html>\n";
111 $book = new EPub(EPub
::BOOK_VERSION_EPUB3
);
117 $book->setTitle($this->title
);
118 // Could also be the ISBN number, prefered for published books, or a UUID.
119 $book->setIdentifier($this->title
, EPub
::IDENTIFIER_URI
);
120 // 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.
121 $book->setLanguage($this->language
);
122 $book->setDescription('Some articles saved on my wallabag');
124 foreach ($this->authors
as $author) {
125 $book->setAuthor($author, $author);
128 // I hope this is a non existant address :)
129 $book->setPublisher('wallabag', 'wallabag');
130 // Strictly not needed as the book date defaults to time().
131 $book->setDate(time());
132 $book->setSourceURL($this->wallabagUrl
);
134 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'PHP');
135 $book->addDublinCoreMetadata(DublinCore
::CONTRIBUTOR
, 'wallabag');
140 if (file_exists($this->logoPath
)) {
141 $book->setCoverImage('Cover.png', file_get_contents($this->logoPath
), 'image/png');
144 $book->addChapter('Notices', 'Cover2.html', $content_start.$this->getExportInformation('PHPePub').$bookEnd);
149 * Adding actual entries
152 // set tags as subjects
153 foreach ($this->entries
as $entry) {
154 foreach ($this->tags
as $tag) {
155 $book->setSubject($tag['value']);
158 $chapter = $content_start.$entry->getContent().$bookEnd;
159 $book->addChapter($entry->getTitle(), htmlspecialchars($entry->getTitle()).'.html', $chapter, true, EPub
::EXTERNAL_REF_ADD
);
162 return Response
::create(
166 'Content-Description' => 'File Transfer',
167 'Content-type' => 'application/epub+zip',
168 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.epub"',
169 'Content-Transfer-Encoding' => 'binary',
175 * Use PHPMobi to dump a .mobi file.
177 private function produceMobi()
180 $content = new \
MOBIFile();
185 $content->set('title', $this->title
);
186 $content->set('author', implode($this->authors
));
187 $content->set('subject', $this->title
);
192 $content->appendParagraph($this->getExportInformation('PHPMobi'));
193 if (file_exists($this->logoPath
)) {
194 $content->appendImage(imagecreatefrompng($this->logoPath
));
196 $content->appendPageBreak();
199 * Adding actual entries
201 foreach ($this->entries
as $entry) {
202 $content->appendChapterTitle($entry->getTitle());
203 $content->appendParagraph($entry->getContent());
204 $content->appendPageBreak();
206 $mobi->setContentProvider($content);
208 // the browser inside Kindle Devices doesn't likes special caracters either, we limit to A-z/0-9
209 $this->title
= preg_replace('/[^A-Za-z0-9\-]/', '', $this->title
);
211 return Response
::create(
215 'Accept-Ranges' => 'bytes',
216 'Content-Description' => 'File Transfer',
217 'Content-type' => 'application/x-mobipocket-ebook',
218 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.mobi"',
219 'Content-Transfer-Encoding' => 'binary',
225 * Use TCPDF to dump a .pdf file.
227 private function producePdf()
229 $pdf = new \
TCPDF(PDF_PAGE_ORIENTATION
, PDF_UNIT
, PDF_PAGE_FORMAT
, true, 'UTF-8', false);
234 $pdf->SetCreator(PDF_CREATOR
);
235 $pdf->SetAuthor('wallabag');
236 $pdf->SetTitle($this->title
);
237 $pdf->SetSubject('Articles via wallabag');
238 $pdf->SetKeywords('wallabag');
244 $intro = '<h1>'.$this->title
.'</h1>'.$this->getExportInformation('tcpdf');
246 $pdf->writeHTMLCell(0, 0, '', '', $intro, 0, 1, 0, true, '', true);
249 * Adding actual entries
251 foreach ($this->entries
as $entry) {
252 foreach ($this->tags
as $tag) {
253 $pdf->SetKeywords($tag['value']);
257 $html = '<h1>'.$entry->getTitle().'</h1>';
258 $html .= $entry->getContent();
260 $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
263 // set image scale factor
264 $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO
);
266 return Response
::create(
267 $pdf->Output('', 'S'),
270 'Content-Description' => 'File Transfer',
271 'Content-type' => 'application/pdf',
272 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.pdf"',
273 'Content-Transfer-Encoding' => 'binary',
279 * Inspired from CsvFileDumper.
281 private function produceCsv()
285 $handle = fopen('php://memory', 'rb+');
287 fputcsv($handle, array('Title', 'URL', 'Content', 'Tags', 'MIME Type', 'Language'), $delimiter, $enclosure);
289 foreach ($this->entries
as $entry) {
295 // remove new line to avoid crazy results
296 str_replace(array("\r\n", "\r", "\n"), '', $entry->getContent()),
297 implode(', ', $entry->getTags()->toArray()),
298 $entry->getMimetype(),
299 $entry->getLanguage(),
307 $output = stream_get_contents($handle);
310 return Response
::create(
314 'Content-type' => 'application/csv',
315 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.csv"',
316 'Content-Transfer-Encoding' => 'UTF-8',
321 private function produceJson()
323 return Response
::create(
324 $this->prepareSerializingContent('json'),
327 'Content-type' => 'application/json',
328 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.json"',
329 'Content-Transfer-Encoding' => 'UTF-8',
334 private function produceXml()
336 return Response
::create(
337 $this->prepareSerializingContent('xml'),
340 'Content-type' => 'application/xml',
341 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.xml"',
342 'Content-Transfer-Encoding' => 'UTF-8',
347 private function produceTxt()
350 $bar = str_repeat('=', 100);
351 foreach ($this->entries
as $entry) {
352 $content .= "\n\n".$bar."\n\n".$entry->getTitle()."\n\n".$bar."\n\n";
353 $content .= trim(preg_replace('/\s+/S', ' ', strip_tags($entry->getContent())))."\n\n";
356 return Response
::create(
360 'Content-type' => 'text/plain',
361 'Content-Disposition' => 'attachment; filename="'.$this->title
.'.txt"',
362 'Content-Transfer-Encoding' => 'UTF-8',
368 * Return a Serializer object for producing processes that need it (JSON & XML).
372 private function prepareSerializingContent($format)
374 $serializer = SerializerBuilder
::create()->build();
376 return $serializer->serialize(
379 SerializationContext
::create()->setGroups(array('entries_for_user'))
384 * Return a kind of footer / information for the epub.
386 * @param string $type Generator of the export, can be: tdpdf, PHPePub, PHPMobi
390 private function getExportInformation($type)
392 $info = str_replace('%EXPORT_METHOD%', $type, $this->footerTemplate
);
394 if ('tcpdf' === $type) {
395 return str_replace('%IMAGE%', '<img src="'.$this->logoPath
.'" />', $info);
398 return str_replace('%IMAGE%', '', $info);