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