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