]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/ContentProxy.php
CS
[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;
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 {
558d9aab 78 $title = $content['title'];
e668a812 79 if (!$title && !empty($content['open_graph']['og_title'])) {
558d9aab
JB
80 $title = $content['open_graph']['og_title'];
81 }
82
83 $html = $content['html'];
84 if (false === $html) {
36e6ef52 85 $html = $this->fetchingErrorMessage;
558d9aab 86
e668a812 87 if (!empty($content['open_graph']['og_description'])) {
558d9aab
JB
88 $html .= '<p><i>But we found a short description: </i></p>';
89 $html .= $content['open_graph']['og_description'];
90 }
91 }
92
d0e9b3d6 93 $entry->setUrl($content['url']);
558d9aab 94 $entry->setTitle($title);
48656e0e 95 $entry->setContent($html);
10b35097 96 $entry->setHttpStatus(isset($content['status']) ? $content['status'] : '');
419214d7 97
e668a812 98 if (!empty($content['date'])) {
f0378b4d
JB
99 $date = $content['date'];
100
101 // is it a timestamp?
102 if (filter_var($date, FILTER_VALIDATE_INT) !== false) {
103 $date = '@'.$content['date'];
104 }
105
e668a812 106 try {
f0378b4d 107 $entry->setPublishedAt(new \DateTime($date));
e668a812 108 } catch (\Exception $e) {
6acadf8e 109 $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $content['url'], 'date' => $content['date']]);
e668a812 110 }
5e9009ce
NL
111 }
112
645291e8 113 if (!empty($content['authors']) && is_array($content['authors'])) {
7b0b3622
NL
114 $entry->setPublishedBy($content['authors']);
115 }
116
dda6a6ad
NL
117 if (!empty($content['all_headers'])) {
118 $entry->setHeaders($content['all_headers']);
119 }
120
0d349ea6
JB
121 $this->validateAndSetLanguage(
122 $entry,
123 isset($content['language']) ? $content['language'] : ''
124 );
125
126 $this->validateAndSetPreviewPicture(
127 $entry,
128 isset($content['open_graph']['og_image']) ? $content['open_graph']['og_image'] : ''
129 );
130
be54dfe4 131 // if content is an image, define it as a preview too
0d349ea6
JB
132 if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) {
133 $this->validateAndSetPreviewPicture(
134 $entry,
135 $content['url']
136 );
137 }
138
e858018f 139 $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : '');
da3d4998 140 $entry->setReadingTime(Utils::getReadingTime($html));
4d0ec0e7
JB
141
142 $domainName = parse_url($entry->getUrl(), PHP_URL_HOST);
143 if (false !== $domainName) {
144 $entry->setDomainName($domainName);
145 }
558d9aab 146
1c9cd2a7
KG
147 try {
148 $this->tagger->tag($entry);
149 } catch (\Exception $e) {
4094ea47 150 $this->logger->error('Error while trying to automatically tag an entry.', [
d0e9b3d6 151 'entry_url' => $content['url'],
1c9cd2a7 152 'error_msg' => $e->getMessage(),
4094ea47 153 ]);
1c9cd2a7 154 }
558d9aab 155 }
c2656f96 156
4d0ec0e7 157 /**
d0e9b3d6 158 * Validate that the given content has at least a title, an html and a url.
4d0ec0e7
JB
159 *
160 * @param array $content
6acadf8e
JB
161 *
162 * @return bool true if valid otherwise false
4d0ec0e7
JB
163 */
164 private function validateContent(array $content)
165 {
6acadf8e 166 return !empty($content['title']) && !empty($content['html']) && !empty($content['url']);
4d0ec0e7 167 }
0d349ea6
JB
168
169 /**
170 * Use a Symfony validator to ensure the language is well formatted.
171 *
172 * @param Entry $entry
173 * @param string $value Language to validate
174 */
175 private function validateAndSetLanguage($entry, $value)
176 {
177 $errors = $this->validator->validate(
178 $value,
179 (new LanguageConstraint())
180 );
181
182 if (0 === count($errors)) {
183 $entry->setLanguage($value);
184
185 return;
186 }
187
188 $this->logger->warning('Language validation failed. '.(string) $errors);
189 }
190
191 /**
192 * Use a Symfony validator to ensure the preview picture is a real url.
193 *
194 * @param Entry $entry
195 * @param string $value URL to validate
196 */
197 private function validateAndSetPreviewPicture($entry, $value)
198 {
199 $errors = $this->validator->validate(
200 $value,
201 (new UrlConstraint())
202 );
203
204 if (0 === count($errors)) {
205 $entry->setPreviewPicture($value);
206
207 return;
208 }
209
210 $this->logger->warning('PreviewPicture validation failed. '.(string) $errors);
211 }
558d9aab 212}