]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/ContentProxy.php
Added headers field in Entry
[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\Entity\Tag;
9 use Wallabag\CoreBundle\Tools\Utils;
10 use Wallabag\CoreBundle\Repository\TagRepository;
11 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
12
13 /**
14 * This kind of proxy class take care of getting the content from an url
15 * and update the entry with what it found.
16 */
17 class ContentProxy
18 {
19 protected $graby;
20 protected $tagger;
21 protected $logger;
22 protected $tagRepository;
23 protected $mimeGuesser;
24 protected $fetchingErrorMessage;
25
26 public function __construct(Graby $graby, RuleBasedTagger $tagger, TagRepository $tagRepository, LoggerInterface $logger, $fetchingErrorMessage)
27 {
28 $this->graby = $graby;
29 $this->tagger = $tagger;
30 $this->logger = $logger;
31 $this->tagRepository = $tagRepository;
32 $this->mimeGuesser = new MimeTypeExtensionGuesser();
33 $this->fetchingErrorMessage = $fetchingErrorMessage;
34 }
35
36 /**
37 * Fetch content using graby and hydrate given entry with results information.
38 * In case we couldn't find content, we'll try to use Open Graph data.
39 *
40 * We can also force the content, in case of an import from the v1 for example, so the function won't
41 * fetch the content from the website but rather use information given with the $content parameter.
42 *
43 * @param Entry $entry Entry to update
44 * @param string $url Url to grab content for
45 * @param array $content An array with AT LEAST keys title, html, url, language & content_type to skip the fetchContent from the url
46 *
47 * @return Entry
48 */
49 public function updateEntry(Entry $entry, $url, array $content = [])
50 {
51 // do we have to fetch the content or the provided one is ok?
52 if (empty($content) || false === $this->validateContent($content)) {
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 $title = $content['title'];
63 if (!$title && isset($content['open_graph']['og_title'])) {
64 $title = $content['open_graph']['og_title'];
65 }
66
67 $html = $content['html'];
68 if (false === $html) {
69 $html = $this->fetchingErrorMessage;
70
71 if (isset($content['open_graph']['og_description'])) {
72 $html .= '<p><i>But we found a short description: </i></p>';
73 $html .= $content['open_graph']['og_description'];
74 }
75 }
76
77 $entry->setUrl($content['url'] ?: $url);
78 $entry->setTitle($title);
79 $entry->setContent($html);
80 $entry->setHttpStatus(isset($content['status']) ? $content['status'] : '');
81
82 if (isset($content['date']) && null !== $content['date'] && '' !== $content['date']) {
83 $entry->setPublishedAt(new \DateTime($content['date']));
84 }
85
86 if (!empty($content['authors'])) {
87 $entry->setPublishedBy($content['authors']);
88 }
89
90 if (!empty($content['all_headers'])) {
91 $entry->setHeaders($content['all_headers']);
92 }
93
94 $entry->setLanguage(isset($content['language']) ? $content['language'] : '');
95 $entry->setMimetype(isset($content['content_type']) ? $content['content_type'] : '');
96 $entry->setReadingTime(Utils::getReadingTime($html));
97
98 $domainName = parse_url($entry->getUrl(), PHP_URL_HOST);
99 if (false !== $domainName) {
100 $entry->setDomainName($domainName);
101 }
102
103 if (isset($content['open_graph']['og_image']) && $content['open_graph']['og_image']) {
104 $entry->setPreviewPicture($content['open_graph']['og_image']);
105 }
106
107 // if content is an image define as a preview too
108 if (isset($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) {
109 $entry->setPreviewPicture($content['url']);
110 }
111
112 try {
113 $this->tagger->tag($entry);
114 } catch (\Exception $e) {
115 $this->logger->error('Error while trying to automatically tag an entry.', [
116 'entry_url' => $url,
117 'error_msg' => $e->getMessage(),
118 ]);
119 }
120
121 return $entry;
122 }
123
124 /**
125 * Assign some tags to an entry.
126 *
127 * @param Entry $entry
128 * @param array|string $tags An array of tag or a string coma separated of tag
129 * @param array $entitiesReady Entities from the EntityManager which are persisted but not yet flushed
130 * It is mostly to fix duplicate tag on import @see http://stackoverflow.com/a/7879164/569101
131 */
132 public function assignTagsToEntry(Entry $entry, $tags, array $entitiesReady = [])
133 {
134 if (!is_array($tags)) {
135 $tags = explode(',', $tags);
136 }
137
138 // keeps only Tag entity from the "not yet flushed entities"
139 $tagsNotYetFlushed = [];
140 foreach ($entitiesReady as $entity) {
141 if ($entity instanceof Tag) {
142 $tagsNotYetFlushed[$entity->getLabel()] = $entity;
143 }
144 }
145
146 foreach ($tags as $label) {
147 $label = trim($label);
148
149 // avoid empty tag
150 if (0 === strlen($label)) {
151 continue;
152 }
153
154 if (isset($tagsNotYetFlushed[$label])) {
155 $tagEntity = $tagsNotYetFlushed[$label];
156 } else {
157 $tagEntity = $this->tagRepository->findOneByLabel($label);
158
159 if (is_null($tagEntity)) {
160 $tagEntity = new Tag();
161 $tagEntity->setLabel($label);
162 }
163 }
164
165 // only add the tag on the entry if the relation doesn't exist
166 if (false === $entry->getTags()->contains($tagEntity)) {
167 $entry->addTag($tagEntity);
168 }
169 }
170 }
171
172 /**
173 * Validate that the given content as enough value to be used
174 * instead of fetch the content from the url.
175 *
176 * @param array $content
177 *
178 * @return bool true if valid otherwise false
179 */
180 private function validateContent(array $content)
181 {
182 return isset($content['title']) && isset($content['html']) && isset($content['url']) && isset($content['language']) && isset($content['content_type']);
183 }
184 }