]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/ContentProxy.php
Validate language & preview picture fields
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / ContentProxy.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Helper;
4
5 use Graby\Graby;
6 use Psr\Log\LoggerInterface;
7 use Wallabag\CoreBundle\Entity\Entry;
8 use Wallabag\CoreBundle\Tools\Utils;
9 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
10 use Symfony\Component\Validator\Constraints\Language as LanguageConstraint;
11 use Symfony\Component\Validator\Constraints\Url as UrlConstraint;
12 use Symfony\Component\Validator\Validator\ValidatorInterface;
13
14 /**
15 * This kind of proxy class take care of getting the content from an url
16 * and update the entry with what it found.
17 */
18 class ContentProxy
19 {
20 protected $graby;
21 protected $tagger;
22 protected $logger;
23 protected $mimeGuesser;
24 protected $fetchingErrorMessage;
25 protected $eventDispatcher;
26
27 public function __construct(Graby $graby, RuleBasedTagger $tagger, ValidatorInterface $validator, LoggerInterface $logger, $fetchingErrorMessage)
28 {
29 $this->graby = $graby;
30 $this->tagger = $tagger;
31 $this->validator = $validator;
32 $this->logger = $logger;
33 $this->mimeGuesser = new MimeTypeExtensionGuesser();
34 $this->fetchingErrorMessage = $fetchingErrorMessage;
35 }
36
37 /**
38 * Update entry using either fetched or provided content.
39 *
40 * @param Entry $entry Entry to update
41 * @param string $url Url of the content
42 * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url
43 * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby
44 */
45 public function updateEntry(Entry $entry, $url, array $content = [], $disableContentUpdate = false)
46 {
47 if (!empty($content['html'])) {
48 $content['html'] = $this->graby->cleanupHtml($content['html'], $url);
49 }
50
51 if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) {
52 $fetchedContent = $this->graby->fetchContent($url);
53
54 // when content is imported, we have information in $content
55 // in case fetching content goes bad, we'll keep the imported information instead of overriding them
56 if (empty($content) || $fetchedContent['html'] !== $this->fetchingErrorMessage) {
57 $content = $fetchedContent;
58 }
59 }
60
61 // be sure to keep the url in case of error
62 // so we'll be able to refetch it in the future
63 $content['url'] = !empty($content['url']) ? $content['url'] : $url;
64
65 $this->stockEntry($entry, $content);
66 }
67
68 /**
69 * Stock entry with fetched or imported content.
70 * Will fall back to OpenGraph data if available.
71 *
72 * @param Entry $entry Entry to stock
73 * @param array $content Array with at least title, url & html
74 */
75 private function stockEntry(Entry $entry, array $content)
76 {
77 $title = $content['title'];
78 if (!$title && !empty($content['open_graph']['og_title'])) {
79 $title = $content['open_graph']['og_title'];
80 }
81
82 $html = $content['html'];
83 if (false === $html) {
84 $html = $this->fetchingErrorMessage;
85
86 if (!empty($content['open_graph']['og_description'])) {
87 $html .= '<p><i>But we found a short description: </i></p>';
88 $html .= $content['open_graph']['og_description'];
89 }
90 }
91
92 $entry->setUrl($content['url']);
93 $entry->setTitle($title);
94 $entry->setContent($html);
95 $entry->setHttpStatus(isset($content['status']) ? $content['status'] : '');
96
97 if (!empty($content['date'])) {
98 $date = $content['date'];
99
100 // is it a timestamp?
101 if (filter_var($date, FILTER_VALIDATE_INT) !== false) {
102 $date = '@'.$content['date'];
103 }
104
105 try {
106 $entry->setPublishedAt(new \DateTime($date));
107 } catch (\Exception $e) {
108 $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $content['url'], 'date' => $content['date']]);
109 }
110 }
111
112 if (!empty($content['authors']) && is_array($content['authors'])) {
113 $entry->setPublishedBy($content['authors']);
114 }
115
116 if (!empty($content['all_headers'])) {
117 $entry->setHeaders($content['all_headers']);
118 }
119
120 $this->validateAndSetLanguage(
121 $entry,
122 isset($content['language']) ? $content['language'] : ''
123 );
124
125 $this->validateAndSetPreviewPicture(
126 $entry,
127 isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : ''
128 );
129
130 // if content is an image define as a preview too
131 if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) {
132 $this->validateAndSetPreviewPicture(
133 $entry,
134 $content['url']
135 );
136 }
137
138 $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : '');
139 $entry->setReadingTime(Utils::getReadingTime($html));
140
141 $domainName = parse_url($entry->getUrl(), PHP_URL_HOST);
142 if (false !== $domainName) {
143 $entry->setDomainName($domainName);
144 }
145
146 try {
147 $this->tagger->tag($entry);
148 } catch (\Exception $e) {
149 $this->logger->error('Error while trying to automatically tag an entry.', [
150 'entry_url' => $content['url'],
151 'error_msg' => $e->getMessage(),
152 ]);
153 }
154 }
155
156 /**
157 * Validate that the given content has at least a title, an html and a url.
158 *
159 * @param array $content
160 *
161 * @return bool true if valid otherwise false
162 */
163 private function validateContent(array $content)
164 {
165 return !empty($content['title']) && !empty($content['html']) && !empty($content['url']);
166 }
167
168 /**
169 * Use a Symfony validator to ensure the language is well formatted.
170 *
171 * @param Entry $entry
172 * @param string $value Language to validate
173 */
174 private function validateAndSetLanguage($entry, $value)
175 {
176 $errors = $this->validator->validate(
177 $value,
178 (new LanguageConstraint())
179 );
180
181 if (0 === count($errors)) {
182 $entry->setLanguage($value);
183
184 return;
185 }
186
187 $this->logger->warning('Language validation failed. '.(string) $errors);
188 }
189
190 /**
191 * Use a Symfony validator to ensure the preview picture is a real url.
192 *
193 * @param Entry $entry
194 * @param string $value URL to validate
195 */
196 private function validateAndSetPreviewPicture($entry, $value)
197 {
198 $errors = $this->validator->validate(
199 $value,
200 (new UrlConstraint())
201 );
202
203 if (0 === count($errors)) {
204 $entry->setPreviewPicture($value);
205
206 return;
207 }
208
209 $this->logger->warning('PreviewPicture validation failed. '.(string) $errors);
210 }
211 }