3 namespace Wallabag\CoreBundle\Helper
;
6 use Psr\Log\LoggerInterface
;
7 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser
;
8 use Symfony\Component\Validator\Constraints\Locale
as LocaleConstraint
;
9 use Symfony\Component\Validator\Constraints\Url
as UrlConstraint
;
10 use Symfony\Component\Validator\Validator\ValidatorInterface
;
11 use Wallabag\CoreBundle\Entity\Entry
;
12 use Wallabag\CoreBundle\Tools\Utils
;
15 * This kind of proxy class take care of getting the content from an url
16 * and update the entry with what it found.
24 protected $mimeGuesser;
25 protected $fetchingErrorMessage;
26 protected $eventDispatcher;
27 protected $storeArticleHeaders;
29 public function __construct(Graby
$graby, RuleBasedTagger
$tagger, ValidatorInterface
$validator, LoggerInterface
$logger, $fetchingErrorMessage, $storeArticleHeaders = false)
31 $this->graby
= $graby;
32 $this->tagger
= $tagger;
33 $this->validator
= $validator;
34 $this->logger
= $logger;
35 $this->mimeGuesser
= new MimeTypeExtensionGuesser();
36 $this->fetchingErrorMessage
= $fetchingErrorMessage;
37 $this->storeArticleHeaders
= $storeArticleHeaders;
41 * Update entry using either fetched or provided content.
43 * @param Entry $entry Entry to update
44 * @param string $url Url of the content
45 * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url
46 * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby
48 public function updateEntry(Entry
$entry, $url, array $content = [], $disableContentUpdate = false)
50 if (!empty($content['html'])) {
51 $content['html'] = $this->graby
->cleanupHtml($content['html'], $url);
54 if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) {
55 $fetchedContent = $this->graby
->fetchContent($url);
56 $fetchedContent['title'] = $this->sanitizeUTF8Text($fetchedContent['title']);
58 // when content is imported, we have information in $content
59 // in case fetching content goes bad, we'll keep the imported information instead of overriding them
60 if (empty($content) || $fetchedContent['html'] !== $this->fetchingErrorMessage
) {
61 $content = $fetchedContent;
65 // be sure to keep the url in case of error
66 // so we'll be able to refetch it in the future
67 $content['url'] = !empty($content['url']) ? $content['url'] : $url;
69 $this->stockEntry($entry, $content);
73 * Remove invalid UTF-8 characters from the given string in following steps:
74 * - try to interpret the given string as ISO-8859-1, convert it to UTF-8 and return it (if its valid)
75 * - simply remove every invalid UTF-8 character and return the result (https://stackoverflow.com/a/1433665)
76 * @param String $rawText
79 private function sanitizeUTF8Text($rawText) {
80 if (mb_check_encoding($rawText, 'utf-8')) {
81 return $rawText; // return because its valid utf-8 text
84 // we assume that $text is encoded in ISO-8859-1 (and not the similar Windows-1252 or other encoding)
85 $convertedText = utf8_encode($rawText);
86 if (mb_check_encoding($convertedText, 'utf-8')) {
87 return $convertedText;
90 // last resort: simply remove invalid UTF-8 character because $rawText can have some every exotic encoding
91 return iconv("UTF-8", "UTF-8//IGNORE", $rawText);
95 * Use a Symfony validator to ensure the language is well formatted.
98 * @param string $value Language to validate and save
100 public function updateLanguage(Entry
$entry, $value)
102 // some lang are defined as fr-FR, es-ES.
103 // replacing - by _ might increase language support
104 $value = str_replace('-', '_', $value);
106 $errors = $this->validator
->validate(
108 (new LocaleConstraint())
111 if (0 === \
count($errors)) {
112 $entry->setLanguage($value);
117 $this->logger
->warning('Language validation failed. ' . (string) $errors);
121 * Use a Symfony validator to ensure the preview picture is a real url.
123 * @param Entry $entry
124 * @param string $value URL to validate and save
126 public function updatePreviewPicture(Entry
$entry, $value)
128 $errors = $this->validator
->validate(
130 (new UrlConstraint())
133 if (0 === \
count($errors)) {
134 $entry->setPreviewPicture($value);
139 $this->logger
->warning('PreviewPicture validation failed. ' . (string) $errors);
145 * @param Entry $entry
146 * @param string $value Date to validate and save
148 public function updatePublishedAt(Entry
$entry, $value)
152 // is it a timestamp?
153 if (false !== filter_var($date, FILTER_VALIDATE_INT
)) {
158 // is it already a DateTime?
159 // (it's inside the try/catch in case of fail to be parse time string)
160 if (!$date instanceof \DateTime
) {
161 $date = new \
DateTime($date);
164 $entry->setPublishedAt($date);
165 } catch (\Exception
$e) {
166 $this->logger
->warning('Error while defining date', ['e' => $e, 'url' => $entry->getUrl(), 'date' => $value]);
171 * Helper to extract and save host from entry url.
173 * @param Entry $entry
175 public function setEntryDomainName(Entry
$entry)
177 $domainName = parse_url($entry->getUrl(), PHP_URL_HOST
);
178 if (false !== $domainName) {
179 $entry->setDomainName($domainName);
184 * Helper to set a default title using:
185 * - url basename, if applicable
188 * @param Entry $entry
190 public function setDefaultEntryTitle(Entry
$entry)
192 $url = parse_url($entry->getUrl());
193 $path = pathinfo($url['path'], PATHINFO_BASENAME
);
196 $path = $url['host'];
199 $entry->setTitle($path);
203 * Stock entry with fetched or imported content.
204 * Will fall back to OpenGraph data if available.
206 * @param Entry $entry Entry to stock
207 * @param array $content Array with at least title, url & html
209 private function stockEntry(Entry
$entry, array $content)
211 $entry->setUrl($content['url']);
213 $this->setEntryDomainName($entry);
215 if (!empty($content['title'])) {
216 $entry->setTitle($content['title']);
217 } elseif (!empty($content['open_graph']['og_title'])) {
218 $entry->setTitle($content['open_graph']['og_title']);
221 $html = $content['html'];
222 if (false === $html) {
223 $html = $this->fetchingErrorMessage
;
225 if (!empty($content['open_graph']['og_description'])) {
226 $html .= '<p><i>But we found a short description: </i></p>';
227 $html .= $content['open_graph']['og_description'];
231 $entry->setContent($html);
232 $entry->setReadingTime(Utils
::getReadingTime($html));
234 if (!empty($content['status'])) {
235 $entry->setHttpStatus($content['status']);
238 if (!empty($content['authors']) && \
is_array($content['authors'])) {
239 $entry->setPublishedBy($content['authors']);
242 if (!empty($content['all_headers']) && $this->storeArticleHeaders
) {
243 $entry->setHeaders($content['all_headers']);
246 if (!empty($content['date'])) {
247 $this->updatePublishedAt($entry, $content['date']);
250 if (!empty($content['language'])) {
251 $this->updateLanguage($entry, $content['language']);
254 if (!empty($content['open_graph']['og_image'])) {
255 $this->updatePreviewPicture($entry, $content['open_graph']['og_image']);
258 // if content is an image, define it as a preview too
259 if (!empty($content['content_type']) && \
in_array($this->mimeGuesser
->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) {
260 $this->updatePreviewPicture($entry, $content['url']);
263 if (!empty($content['content_type'])) {
264 $entry->setMimetype($content['content_type']);
268 $this->tagger
->tag($entry);
269 } catch (\Exception
$e) {
270 $this->logger
->error('Error while trying to automatically tag an entry.', [
271 'entry_url' => $content['url'],
272 'error_msg' => $e->getMessage(),
278 * Validate that the given content has at least a title, an html and a url.
280 * @param array $content
282 * @return bool true if valid otherwise false
284 private function validateContent(array $content)
286 return !empty($content['title']) && !empty($content['html']) && !empty($content['url']);