]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/ContentProxy.php
Validate language & preview picture fields
[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;
558d9aab 7use Wallabag\CoreBundle\Entity\Entry;
da3d4998 8use Wallabag\CoreBundle\Tools\Utils;
8d7b4f0e 9use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
0d349ea6
JB
10use Symfony\Component\Validator\Constraints\Language as LanguageConstraint;
11use Symfony\Component\Validator\Constraints\Url as UrlConstraint;
12use Symfony\Component\Validator\Validator\ValidatorInterface;
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;
1c9cd2a7 22 protected $logger;
8d7b4f0e 23 protected $mimeGuesser;
29dca432 24 protected $fetchingErrorMessage;
6bc6fb1f 25 protected $eventDispatcher;
558d9aab 26
0d349ea6 27 public function __construct(Graby $graby, RuleBasedTagger $tagger, ValidatorInterface $validator, LoggerInterface $logger, $fetchingErrorMessage)
558d9aab 28 {
347fa6be 29 $this->graby = $graby;
c3510620 30 $this->tagger = $tagger;
0d349ea6 31 $this->validator = $validator;
1c9cd2a7 32 $this->logger = $logger;
8d7b4f0e 33 $this->mimeGuesser = new MimeTypeExtensionGuesser();
29dca432 34 $this->fetchingErrorMessage = $fetchingErrorMessage;
558d9aab
JB
35 }
36
37 /**
6acadf8e 38 * Update entry using either fetched or provided content.
4d0ec0e7 39 *
6acadf8e
JB
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
558d9aab 44 */
6acadf8e 45 public function updateEntry(Entry $entry, $url, array $content = [], $disableContentUpdate = false)
558d9aab 46 {
6acadf8e
JB
47 if (!empty($content['html'])) {
48 $content['html'] = $this->graby->cleanupHtml($content['html'], $url);
d5c2cc54 49 }
e668a812 50
6acadf8e 51 if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) {
ec970721 52 $fetchedContent = $this->graby->fetchContent($url);
106bdbcd
JB
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
6acadf8e 56 if (empty($content) || $fetchedContent['html'] !== $this->fetchingErrorMessage) {
29dca432
JC
57 $content = $fetchedContent;
58 }
4d0ec0e7 59 }
558d9aab 60
6acadf8e
JB
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
d0e9b3d6
JC
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 *
d5c2cc54 72 * @param Entry $entry Entry to stock
ec970721 73 * @param array $content Array with at least title, url & html
d0e9b3d6
JC
74 */
75 private function stockEntry(Entry $entry, array $content)
76 {
558d9aab 77 $title = $content['title'];
e668a812 78 if (!$title && !empty($content['open_graph']['og_title'])) {
558d9aab
JB
79 $title = $content['open_graph']['og_title'];
80 }
81
82 $html = $content['html'];
83 if (false === $html) {
36e6ef52 84 $html = $this->fetchingErrorMessage;
558d9aab 85
e668a812 86 if (!empty($content['open_graph']['og_description'])) {
558d9aab
JB
87 $html .= '<p><i>But we found a short description: </i></p>';
88 $html .= $content['open_graph']['og_description'];
89 }
90 }
91
d0e9b3d6 92 $entry->setUrl($content['url']);
558d9aab 93 $entry->setTitle($title);
48656e0e 94 $entry->setContent($html);
10b35097 95 $entry->setHttpStatus(isset($content['status']) ? $content['status'] : '');
419214d7 96
e668a812 97 if (!empty($content['date'])) {
f0378b4d
JB
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
e668a812 105 try {
f0378b4d 106 $entry->setPublishedAt(new \DateTime($date));
e668a812 107 } catch (\Exception $e) {
6acadf8e 108 $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $content['url'], 'date' => $content['date']]);
e668a812 109 }
5e9009ce
NL
110 }
111
645291e8 112 if (!empty($content['authors']) && is_array($content['authors'])) {
7b0b3622
NL
113 $entry->setPublishedBy($content['authors']);
114 }
115
dda6a6ad
NL
116 if (!empty($content['all_headers'])) {
117 $entry->setHeaders($content['all_headers']);
118 }
119
0d349ea6
JB
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
e858018f 138 $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : '');
da3d4998 139 $entry->setReadingTime(Utils::getReadingTime($html));
4d0ec0e7
JB
140
141 $domainName = parse_url($entry->getUrl(), PHP_URL_HOST);
142 if (false !== $domainName) {
143 $entry->setDomainName($domainName);
144 }
558d9aab 145
1c9cd2a7
KG
146 try {
147 $this->tagger->tag($entry);
148 } catch (\Exception $e) {
4094ea47 149 $this->logger->error('Error while trying to automatically tag an entry.', [
d0e9b3d6 150 'entry_url' => $content['url'],
1c9cd2a7 151 'error_msg' => $e->getMessage(),
4094ea47 152 ]);
1c9cd2a7 153 }
558d9aab 154 }
c2656f96 155
4d0ec0e7 156 /**
d0e9b3d6 157 * Validate that the given content has at least a title, an html and a url.
4d0ec0e7
JB
158 *
159 * @param array $content
6acadf8e
JB
160 *
161 * @return bool true if valid otherwise false
4d0ec0e7
JB
162 */
163 private function validateContent(array $content)
164 {
6acadf8e 165 return !empty($content['title']) && !empty($content['html']) && !empty($content['url']);
4d0ec0e7 166 }
0d349ea6
JB
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 }
558d9aab 211}