]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/ContentProxy.php
Fix validateAndSetPreviewPicture
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / ContentProxy.php
CommitLineData
558d9aab
JB
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
5use Graby\Graby;
45fd7e09 6use Psr\Log\LoggerInterface;
8d7b4f0e 7use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
42f3bb2c 8use Symfony\Component\Validator\Constraints\Locale as LocaleConstraint;
0d349ea6
JB
9use Symfony\Component\Validator\Constraints\Url as UrlConstraint;
10use Symfony\Component\Validator\Validator\ValidatorInterface;
f808b016
JB
11use Wallabag\CoreBundle\Entity\Entry;
12use Wallabag\CoreBundle\Tools\Utils;
558d9aab
JB
13
14/**
15 * This kind of proxy class take care of getting the content from an url
f1e29e69 16 * and update the entry with what it found.
558d9aab
JB
17 */
18class ContentProxy
19{
20 protected $graby;
c3510620 21 protected $tagger;
be54dfe4 22 protected $validator;
1c9cd2a7 23 protected $logger;
8d7b4f0e 24 protected $mimeGuesser;
29dca432 25 protected $fetchingErrorMessage;
6bc6fb1f 26 protected $eventDispatcher;
558d9aab 27
0d349ea6 28 public function __construct(Graby $graby, RuleBasedTagger $tagger, ValidatorInterface $validator, LoggerInterface $logger, $fetchingErrorMessage)
558d9aab 29 {
347fa6be 30 $this->graby = $graby;
c3510620 31 $this->tagger = $tagger;
0d349ea6 32 $this->validator = $validator;
1c9cd2a7 33 $this->logger = $logger;
8d7b4f0e 34 $this->mimeGuesser = new MimeTypeExtensionGuesser();
29dca432 35 $this->fetchingErrorMessage = $fetchingErrorMessage;
558d9aab
JB
36 }
37
38 /**
6acadf8e 39 * Update entry using either fetched or provided content.
4d0ec0e7 40 *
6acadf8e
JB
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
558d9aab 45 */
6acadf8e 46 public function updateEntry(Entry $entry, $url, array $content = [], $disableContentUpdate = false)
558d9aab 47 {
6acadf8e
JB
48 if (!empty($content['html'])) {
49 $content['html'] = $this->graby->cleanupHtml($content['html'], $url);
d5c2cc54 50 }
e668a812 51
6acadf8e 52 if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) {
ec970721 53 $fetchedContent = $this->graby->fetchContent($url);
106bdbcd
JB
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
6acadf8e 57 if (empty($content) || $fetchedContent['html'] !== $this->fetchingErrorMessage) {
29dca432
JC
58 $content = $fetchedContent;
59 }
4d0ec0e7 60 }
558d9aab 61
6acadf8e
JB
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
d0e9b3d6
JC
66 $this->stockEntry($entry, $content);
67 }
68
69 /**
70 * Stock entry with fetched or imported content.
71 * Will fall back to OpenGraph data if available.
72 *
d5c2cc54 73 * @param Entry $entry Entry to stock
ec970721 74 * @param array $content Array with at least title, url & html
d0e9b3d6
JC
75 */
76 private function stockEntry(Entry $entry, array $content)
77 {
a05b6115
JB
78 $entry->setUrl($content['url']);
79
80 $domainName = parse_url($entry->getUrl(), PHP_URL_HOST);
81 if (false !== $domainName) {
82 $entry->setDomainName($domainName);
83 }
84
85 if (!empty($content['title'])) {
86 $entry->setTitle($content['title']);
87 } elseif (!empty($content['open_graph']['og_title'])) {
88 $entry->setTitle($content['open_graph']['og_title']);
558d9aab
JB
89 }
90
91 $html = $content['html'];
92 if (false === $html) {
36e6ef52 93 $html = $this->fetchingErrorMessage;
558d9aab 94
e668a812 95 if (!empty($content['open_graph']['og_description'])) {
558d9aab
JB
96 $html .= '<p><i>But we found a short description: </i></p>';
97 $html .= $content['open_graph']['og_description'];
98 }
99 }
100
48656e0e 101 $entry->setContent($html);
a05b6115 102 $entry->setReadingTime(Utils::getReadingTime($html));
f0378b4d 103
a05b6115
JB
104 if (!empty($content['status'])) {
105 $entry->setHttpStatus($content['status']);
5e9009ce
NL
106 }
107
645291e8 108 if (!empty($content['authors']) && is_array($content['authors'])) {
7b0b3622
NL
109 $entry->setPublishedBy($content['authors']);
110 }
111
dda6a6ad
NL
112 if (!empty($content['all_headers'])) {
113 $entry->setHeaders($content['all_headers']);
114 }
115
a05b6115
JB
116 if (!empty($content['date'])) {
117 $this->updatePublishedAt($entry, $content['date']);
118 }
0d349ea6 119
a05b6115
JB
120 if (!empty($content['language'])) {
121 $this->updateLanguage($entry, $content['language']);
122 }
123
124 if (!empty($content['open_graph']['og_image'])) {
125 $this->updatePreviewPicture($entry, $content['open_graph']['og_image']);
126 }
0d349ea6 127
be54dfe4 128 // if content is an image, define it as a preview too
0d349ea6 129 if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) {
d0ec2ddd 130 $this->updatePreviewPicture($entry, $content['url']);
0d349ea6
JB
131 }
132
a05b6115
JB
133 if (!empty($content['content_type'])) {
134 $entry->setMimetype($content['content_type']);
4d0ec0e7 135 }
558d9aab 136
1c9cd2a7
KG
137 try {
138 $this->tagger->tag($entry);
139 } catch (\Exception $e) {
4094ea47 140 $this->logger->error('Error while trying to automatically tag an entry.', [
d0e9b3d6 141 'entry_url' => $content['url'],
1c9cd2a7 142 'error_msg' => $e->getMessage(),
4094ea47 143 ]);
1c9cd2a7 144 }
558d9aab 145 }
c2656f96 146
4d0ec0e7 147 /**
d0e9b3d6 148 * Validate that the given content has at least a title, an html and a url.
4d0ec0e7
JB
149 *
150 * @param array $content
6acadf8e
JB
151 *
152 * @return bool true if valid otherwise false
4d0ec0e7
JB
153 */
154 private function validateContent(array $content)
155 {
6acadf8e 156 return !empty($content['title']) && !empty($content['html']) && !empty($content['url']);
4d0ec0e7 157 }
0d349ea6
JB
158
159 /**
160 * Use a Symfony validator to ensure the language is well formatted.
161 *
162 * @param Entry $entry
a05b6115 163 * @param string $value Language to validate and save
0d349ea6 164 */
a05b6115 165 public function updateLanguage(Entry $entry, $value)
0d349ea6 166 {
80e49ba7
JB
167 // some lang are defined as fr-FR, es-ES.
168 // replacing - by _ might increase language support
169 $value = str_replace('-', '_', $value);
170
0d349ea6
JB
171 $errors = $this->validator->validate(
172 $value,
42f3bb2c 173 (new LocaleConstraint())
0d349ea6
JB
174 );
175
176 if (0 === count($errors)) {
177 $entry->setLanguage($value);
178
179 return;
180 }
181
f808b016 182 $this->logger->warning('Language validation failed. ' . (string) $errors);
0d349ea6
JB
183 }
184
185 /**
186 * Use a Symfony validator to ensure the preview picture is a real url.
187 *
188 * @param Entry $entry
a05b6115 189 * @param string $value URL to validate and save
0d349ea6 190 */
a05b6115 191 public function updatePreviewPicture(Entry $entry, $value)
0d349ea6
JB
192 {
193 $errors = $this->validator->validate(
194 $value,
195 (new UrlConstraint())
196 );
197
198 if (0 === count($errors)) {
199 $entry->setPreviewPicture($value);
200
201 return;
202 }
203
f808b016 204 $this->logger->warning('PreviewPicture validation failed. ' . (string) $errors);
0d349ea6 205 }
a05b6115
JB
206
207 /**
208 * Update date.
209 *
210 * @param Entry $entry
211 * @param string $value Date to validate and save
212 */
213 public function updatePublishedAt(Entry $entry, $value)
214 {
215 $date = $value;
216
217 // is it a timestamp?
218 if (filter_var($date, FILTER_VALIDATE_INT) !== false) {
219 $date = '@'.$value;
220 }
221
222 try {
223 $entry->setPublishedAt(new \DateTime($date));
224 } catch (\Exception $e) {
225 $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $entry->getUrl(), 'date' => $value]);
226 }
227 }
558d9aab 228}