]>
Commit | Line | Data |
---|---|---|
419214d7 TC |
1 | <?php |
2 | ||
3 | namespace Wallabag\CoreBundle\Helper; | |
4 | ||
7f559418 | 5 | use GuzzleHttp\Client; |
577c0b6d | 6 | use GuzzleHttp\Message\Response; |
f808b016 JB |
7 | use Psr\Log\LoggerInterface; |
8 | use Symfony\Component\DomCrawler\Crawler; | |
e0597476 | 9 | use Symfony\Component\Finder\Finder; |
f808b016 | 10 | use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; |
419214d7 | 11 | |
156bf627 JB |
12 | class DownloadImages |
13 | { | |
7f559418 JB |
14 | const REGENERATE_PICTURES_QUALITY = 80; |
15 | ||
16 | private $client; | |
17 | private $baseFolder; | |
419214d7 | 18 | private $logger; |
7f559418 | 19 | private $mimeGuesser; |
41ada277 | 20 | private $wallabagUrl; |
419214d7 | 21 | |
e0597476 | 22 | public function __construct(Client $client, $baseFolder, $wallabagUrl, LoggerInterface $logger) |
156bf627 | 23 | { |
7f559418 JB |
24 | $this->client = $client; |
25 | $this->baseFolder = $baseFolder; | |
e0597476 | 26 | $this->wallabagUrl = rtrim($wallabagUrl, '/'); |
419214d7 | 27 | $this->logger = $logger; |
7f559418 JB |
28 | $this->mimeGuesser = new MimeTypeExtensionGuesser(); |
29 | ||
30 | $this->setFolder(); | |
419214d7 TC |
31 | } |
32 | ||
7f559418 JB |
33 | /** |
34 | * Process the html and extract image from it, save them to local and return the updated html. | |
35 | * | |
e0597476 | 36 | * @param int $entryId ID of the entry |
7f559418 | 37 | * @param string $html |
e0597476 | 38 | * @param string $url Used as a base path for relative image and folder |
7f559418 JB |
39 | * |
40 | * @return string | |
41 | */ | |
e0597476 | 42 | public function processHtml($entryId, $html, $url) |
156bf627 | 43 | { |
7f559418 | 44 | $crawler = new Crawler($html); |
c15bb5ad S |
45 | $imagesCrawler = $crawler |
46 | ->filterXpath('//img'); | |
47 | $imagesUrls = $imagesCrawler | |
9bf7752f | 48 | ->extract(['src']); |
c15bb5ad S |
49 | $imagesSrcsetUrls = $this->getSrcsetUrls($imagesCrawler); |
50 | $imagesUrls = array_unique(array_merge($imagesUrls, $imagesSrcsetUrls)); | |
419214d7 | 51 | |
e0597476 | 52 | $relativePath = $this->getRelativePath($entryId); |
7f559418 | 53 | |
419214d7 | 54 | // download and save the image to the folder |
c15bb5ad | 55 | foreach ($imagesUrls as $image) { |
e0597476 | 56 | $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath); |
7f559418 JB |
57 | |
58 | if (false === $imagePath) { | |
59 | continue; | |
60 | } | |
61 | ||
9bf7752f | 62 | // if image contains "&" and we can't find it in the html it might be because it's encoded as & |
fcad69a4 JB |
63 | if (false !== stripos($image, '&') && false === stripos($html, $image)) { |
64 | $image = str_replace('&', '&', $image); | |
65 | } | |
66 | ||
7f559418 | 67 | $html = str_replace($image, $imagePath, $html); |
419214d7 TC |
68 | } |
69 | ||
7f559418 | 70 | return $html; |
419214d7 TC |
71 | } |
72 | ||
7f559418 JB |
73 | /** |
74 | * Process a single image: | |
75 | * - retrieve it | |
76 | * - re-saved it (for security reason) | |
77 | * - return the new local path. | |
78 | * | |
e0597476 | 79 | * @param int $entryId ID of the entry |
7f559418 JB |
80 | * @param string $imagePath Path to the image to retrieve |
81 | * @param string $url Url from where the image were found | |
82 | * @param string $relativePath Relative local path to saved the image | |
83 | * | |
84 | * @return string Relative url to access the image from the web | |
85 | */ | |
e0597476 | 86 | public function processSingleImage($entryId, $imagePath, $url, $relativePath = null) |
156bf627 | 87 | { |
3fbbe0d9 S |
88 | if (null === $imagePath) { |
89 | return false; | |
90 | } | |
91 | ||
e0597476 JB |
92 | if (null === $relativePath) { |
93 | $relativePath = $this->getRelativePath($entryId); | |
419214d7 TC |
94 | } |
95 | ||
f808b016 | 96 | $this->logger->debug('DownloadImages: working on image: ' . $imagePath); |
e0597476 | 97 | |
f808b016 | 98 | $folderPath = $this->baseFolder . '/' . $relativePath; |
419214d7 | 99 | |
7f559418 JB |
100 | // build image path |
101 | $absolutePath = $this->getAbsoluteLink($url, $imagePath); | |
102 | if (false === $absolutePath) { | |
e0597476 | 103 | $this->logger->error('DownloadImages: Can not determine the absolute path for that image, skipping.'); |
419214d7 TC |
104 | |
105 | return false; | |
106 | } | |
107 | ||
48656e0e JB |
108 | try { |
109 | $res = $this->client->get($absolutePath); | |
110 | } catch (\Exception $e) { | |
e0597476 | 111 | $this->logger->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]); |
48656e0e JB |
112 | |
113 | return false; | |
114 | } | |
7f559418 | 115 | |
577c0b6d JB |
116 | $ext = $this->getExtensionFromResponse($res, $imagePath); |
117 | if (false === $res) { | |
419214d7 TC |
118 | return false; |
119 | } | |
577c0b6d | 120 | |
7f559418 | 121 | $hashImage = hash('crc32', $absolutePath); |
f808b016 | 122 | $localPath = $folderPath . '/' . $hashImage . '.' . $ext; |
7f559418 JB |
123 | |
124 | try { | |
125 | $im = imagecreatefromstring($res->getBody()); | |
126 | } catch (\Exception $e) { | |
127 | $im = false; | |
128 | } | |
419214d7 | 129 | |
48656e0e | 130 | if (false === $im) { |
e0597476 | 131 | $this->logger->error('DownloadImages: Error while regenerating image', ['path' => $localPath]); |
419214d7 TC |
132 | |
133 | return false; | |
134 | } | |
135 | ||
7f559418 JB |
136 | switch ($ext) { |
137 | case 'gif': | |
9306c2a3 JB |
138 | // use Imagick if available to keep GIF animation |
139 | if (class_exists('\\Imagick')) { | |
844fd9fa JB |
140 | try { |
141 | $imagick = new \Imagick(); | |
142 | $imagick->readImageBlob($res->getBody()); | |
143 | $imagick->setImageFormat('gif'); | |
144 | $imagick->writeImages($localPath, true); | |
145 | } catch (\Exception $e) { | |
146 | // if Imagick fail, fallback to the default solution | |
147 | imagegif($im, $localPath); | |
148 | } | |
9306c2a3 JB |
149 | } else { |
150 | imagegif($im, $localPath); | |
151 | } | |
152 | ||
e0597476 | 153 | $this->logger->debug('DownloadImages: Re-creating gif'); |
419214d7 | 154 | break; |
7f559418 JB |
155 | case 'jpeg': |
156 | case 'jpg': | |
001cc716 | 157 | imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY); |
e0597476 | 158 | $this->logger->debug('DownloadImages: Re-creating jpg'); |
419214d7 | 159 | break; |
7f559418 | 160 | case 'png': |
7a3260ae KD |
161 | imagealphablending($im, false); |
162 | imagesavealpha($im, true); | |
001cc716 | 163 | imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9)); |
e0597476 | 164 | $this->logger->debug('DownloadImages: Re-creating png'); |
419214d7 | 165 | } |
7f559418 | 166 | |
419214d7 TC |
167 | imagedestroy($im); |
168 | ||
f808b016 | 169 | return $this->wallabagUrl . '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext; |
419214d7 TC |
170 | } |
171 | ||
e0597476 JB |
172 | /** |
173 | * Remove all images for the given entry id. | |
174 | * | |
175 | * @param int $entryId ID of the entry | |
176 | */ | |
177 | public function removeImages($entryId) | |
178 | { | |
179 | $relativePath = $this->getRelativePath($entryId); | |
f808b016 | 180 | $folderPath = $this->baseFolder . '/' . $relativePath; |
e0597476 JB |
181 | |
182 | $finder = new Finder(); | |
183 | $finder | |
184 | ->files() | |
185 | ->ignoreDotFiles(true) | |
186 | ->in($folderPath); | |
187 | ||
188 | foreach ($finder as $file) { | |
189 | @unlink($file->getRealPath()); | |
190 | } | |
191 | ||
192 | @rmdir($folderPath); | |
193 | } | |
194 | ||
c15bb5ad S |
195 | /** |
196 | * Get images urls from the srcset image attribute. | |
197 | * | |
198 | * @param Crawler $imagesCrawler | |
199 | * | |
200 | * @return array An array of urls | |
201 | */ | |
e6f12c07 | 202 | private function getSrcsetUrls(Crawler $imagesCrawler) |
c15bb5ad S |
203 | { |
204 | $urls = []; | |
205 | $iterator = $imagesCrawler | |
206 | ->getIterator(); | |
207 | while ($iterator->valid()) { | |
208 | $srcsetAttribute = $iterator->current()->getAttribute('srcset'); | |
209 | if ('' !== $srcsetAttribute) { | |
e6f12c07 S |
210 | // Couldn't start with " OR ' OR a white space |
211 | // Could be one or more white space | |
212 | // Must be one or more digits followed by w OR x | |
213 | $pattern = "/(?:[^\"'\s]+\s*(?:\d+[wx])+)/"; | |
214 | preg_match_all($pattern, $srcsetAttribute, $matches); | |
2a1ceb67 | 215 | $srcset = \call_user_func_array('array_merge', $matches); |
c15bb5ad | 216 | $srcsetUrls = array_map(function ($src) { |
e6f12c07 | 217 | return trim(explode(' ', $src, 2)[0]); |
c15bb5ad S |
218 | }, $srcset); |
219 | $urls = array_merge($srcsetUrls, $urls); | |
220 | } | |
221 | $iterator->next(); | |
222 | } | |
223 | ||
224 | return $urls; | |
225 | } | |
226 | ||
f808b016 JB |
227 | /** |
228 | * Setup base folder where all images are going to be saved. | |
229 | */ | |
230 | private function setFolder() | |
231 | { | |
232 | // if folder doesn't exist, attempt to create one and store the folder name in property $folder | |
233 | if (!file_exists($this->baseFolder)) { | |
234 | mkdir($this->baseFolder, 0755, true); | |
235 | } | |
236 | } | |
237 | ||
7f559418 JB |
238 | /** |
239 | * Generate the folder where we are going to save images based on the entry url. | |
240 | * | |
e0597476 | 241 | * @param int $entryId ID of the entry |
7f559418 JB |
242 | * |
243 | * @return string | |
244 | */ | |
e0597476 | 245 | private function getRelativePath($entryId) |
419214d7 | 246 | { |
e0597476 | 247 | $hashId = hash('crc32', $entryId); |
f808b016 JB |
248 | $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId; |
249 | $folderPath = $this->baseFolder . '/' . $relativePath; | |
419214d7 | 250 | |
7f559418 JB |
251 | if (!file_exists($folderPath)) { |
252 | mkdir($folderPath, 0777, true); | |
419214d7 TC |
253 | } |
254 | ||
e0597476 | 255 | $this->logger->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]); |
419214d7 | 256 | |
7f559418 JB |
257 | return $relativePath; |
258 | } | |
419214d7 | 259 | |
7f559418 JB |
260 | /** |
261 | * Make an $url absolute based on the $base. | |
262 | * | |
263 | * @see Graby->makeAbsoluteStr | |
264 | * | |
265 | * @param string $base Base url | |
266 | * @param string $url Url to make it absolute | |
267 | * | |
268 | * @return false|string | |
269 | */ | |
270 | private function getAbsoluteLink($base, $url) | |
271 | { | |
272 | if (preg_match('!^https?://!i', $url)) { | |
273 | // already absolute | |
274 | return $url; | |
419214d7 TC |
275 | } |
276 | ||
7f559418 | 277 | $base = new \SimplePie_IRI($base); |
419214d7 | 278 | |
7f559418 JB |
279 | // remove '//' in URL path (causes URLs not to resolve properly) |
280 | if (isset($base->ipath)) { | |
281 | $base->ipath = preg_replace('!//+!', '/', $base->ipath); | |
419214d7 TC |
282 | } |
283 | ||
7f559418 JB |
284 | if ($absolute = \SimplePie_IRI::absolutize($base, $url)) { |
285 | return $absolute->get_uri(); | |
94654765 | 286 | } |
156bf627 | 287 | |
e0597476 | 288 | $this->logger->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]); |
48656e0e | 289 | |
7f559418 | 290 | return false; |
94654765 | 291 | } |
577c0b6d JB |
292 | |
293 | /** | |
294 | * Retrieve and validate the extension from the response of the url of the image. | |
295 | * | |
296 | * @param Response $res Guzzle Response | |
297 | * @param string $imagePath Path from the src image from the content (used for log only) | |
298 | * | |
299 | * @return string|false Extension name or false if validation failed | |
300 | */ | |
301 | private function getExtensionFromResponse(Response $res, $imagePath) | |
302 | { | |
303 | $ext = $this->mimeGuesser->guess($res->getHeader('content-type')); | |
304 | $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]); | |
305 | ||
306 | // ok header doesn't have the extension, try a different way | |
307 | if (empty($ext)) { | |
308 | $types = [ | |
309 | 'jpeg' => "\xFF\xD8\xFF", | |
310 | 'gif' => 'GIF', | |
311 | 'png' => "\x89\x50\x4e\x47\x0d\x0a", | |
312 | ]; | |
313 | $bytes = substr((string) $res->getBody(), 0, 8); | |
314 | ||
315 | foreach ($types as $type => $header) { | |
316 | if (0 === strpos($bytes, $header)) { | |
317 | $ext = $type; | |
318 | break; | |
319 | } | |
320 | } | |
321 | ||
322 | $this->logger->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]); | |
323 | } | |
324 | ||
2a1ceb67 | 325 | if (!\in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { |
f808b016 | 326 | $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath); |
577c0b6d JB |
327 | |
328 | return false; | |
329 | } | |
330 | ||
331 | return $ext; | |
332 | } | |
419214d7 | 333 | } |