]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/DownloadImages.php
Fix srcset attribute on images downloaded
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / DownloadImages.php
CommitLineData
419214d7
TC
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
7f559418 5use GuzzleHttp\Client;
577c0b6d 6use GuzzleHttp\Message\Response;
f808b016
JB
7use Psr\Log\LoggerInterface;
8use Symfony\Component\DomCrawler\Crawler;
e0597476 9use Symfony\Component\Finder\Finder;
f808b016 10use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
419214d7 11
156bf627
JB
12class 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 &amp;
fcad69a4
JB
63 if (false !== stripos($image, '&') && false === stripos($html, $image)) {
64 $image = str_replace('&', '&amp;', $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 {
e0597476
JB
88 if (null === $relativePath) {
89 $relativePath = $this->getRelativePath($entryId);
419214d7
TC
90 }
91
f808b016 92 $this->logger->debug('DownloadImages: working on image: ' . $imagePath);
e0597476 93
f808b016 94 $folderPath = $this->baseFolder . '/' . $relativePath;
419214d7 95
7f559418
JB
96 // build image path
97 $absolutePath = $this->getAbsoluteLink($url, $imagePath);
98 if (false === $absolutePath) {
e0597476 99 $this->logger->error('DownloadImages: Can not determine the absolute path for that image, skipping.');
419214d7
TC
100
101 return false;
102 }
103
48656e0e
JB
104 try {
105 $res = $this->client->get($absolutePath);
106 } catch (\Exception $e) {
e0597476 107 $this->logger->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]);
48656e0e
JB
108
109 return false;
110 }
7f559418 111
577c0b6d
JB
112 $ext = $this->getExtensionFromResponse($res, $imagePath);
113 if (false === $res) {
419214d7
TC
114 return false;
115 }
577c0b6d 116
7f559418 117 $hashImage = hash('crc32', $absolutePath);
f808b016 118 $localPath = $folderPath . '/' . $hashImage . '.' . $ext;
7f559418
JB
119
120 try {
121 $im = imagecreatefromstring($res->getBody());
122 } catch (\Exception $e) {
123 $im = false;
124 }
419214d7 125
48656e0e 126 if (false === $im) {
e0597476 127 $this->logger->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
419214d7
TC
128
129 return false;
130 }
131
7f559418
JB
132 switch ($ext) {
133 case 'gif':
001cc716 134 imagegif($im, $localPath);
e0597476 135 $this->logger->debug('DownloadImages: Re-creating gif');
419214d7 136 break;
7f559418
JB
137 case 'jpeg':
138 case 'jpg':
001cc716 139 imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY);
e0597476 140 $this->logger->debug('DownloadImages: Re-creating jpg');
419214d7 141 break;
7f559418 142 case 'png':
7a3260ae
KD
143 imagealphablending($im, false);
144 imagesavealpha($im, true);
001cc716 145 imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9));
e0597476 146 $this->logger->debug('DownloadImages: Re-creating png');
419214d7 147 }
7f559418 148
419214d7
TC
149 imagedestroy($im);
150
f808b016 151 return $this->wallabagUrl . '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext;
419214d7
TC
152 }
153
e0597476
JB
154 /**
155 * Remove all images for the given entry id.
156 *
157 * @param int $entryId ID of the entry
158 */
159 public function removeImages($entryId)
160 {
161 $relativePath = $this->getRelativePath($entryId);
f808b016 162 $folderPath = $this->baseFolder . '/' . $relativePath;
e0597476
JB
163
164 $finder = new Finder();
165 $finder
166 ->files()
167 ->ignoreDotFiles(true)
168 ->in($folderPath);
169
170 foreach ($finder as $file) {
171 @unlink($file->getRealPath());
172 }
173
174 @rmdir($folderPath);
175 }
176
c15bb5ad
S
177 /**
178 * Get images urls from the srcset image attribute.
179 *
180 * @param Crawler $imagesCrawler
181 *
182 * @return array An array of urls
183 */
184 protected function getSrcsetUrls(Crawler $imagesCrawler)
185 {
186 $urls = [];
187 $iterator = $imagesCrawler
188 ->getIterator();
189 while ($iterator->valid()) {
190 $srcsetAttribute = $iterator->current()->getAttribute('srcset');
191 if ('' !== $srcsetAttribute) {
192 $srcset = array_map('trim', explode(',', $srcsetAttribute));
193 $srcsetUrls = array_map(function ($src) {
194 return explode(' ', $src)[0];
195 }, $srcset);
196 $urls = array_merge($srcsetUrls, $urls);
197 }
198 $iterator->next();
199 }
200
201 return $urls;
202 }
203
f808b016
JB
204 /**
205 * Setup base folder where all images are going to be saved.
206 */
207 private function setFolder()
208 {
209 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
210 if (!file_exists($this->baseFolder)) {
211 mkdir($this->baseFolder, 0755, true);
212 }
213 }
214
7f559418
JB
215 /**
216 * Generate the folder where we are going to save images based on the entry url.
217 *
e0597476 218 * @param int $entryId ID of the entry
7f559418
JB
219 *
220 * @return string
221 */
e0597476 222 private function getRelativePath($entryId)
419214d7 223 {
e0597476 224 $hashId = hash('crc32', $entryId);
f808b016
JB
225 $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId;
226 $folderPath = $this->baseFolder . '/' . $relativePath;
419214d7 227
7f559418
JB
228 if (!file_exists($folderPath)) {
229 mkdir($folderPath, 0777, true);
419214d7
TC
230 }
231
e0597476 232 $this->logger->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
419214d7 233
7f559418
JB
234 return $relativePath;
235 }
419214d7 236
7f559418
JB
237 /**
238 * Make an $url absolute based on the $base.
239 *
240 * @see Graby->makeAbsoluteStr
241 *
242 * @param string $base Base url
243 * @param string $url Url to make it absolute
244 *
245 * @return false|string
246 */
247 private function getAbsoluteLink($base, $url)
248 {
249 if (preg_match('!^https?://!i', $url)) {
250 // already absolute
251 return $url;
419214d7
TC
252 }
253
7f559418 254 $base = new \SimplePie_IRI($base);
419214d7 255
7f559418
JB
256 // remove '//' in URL path (causes URLs not to resolve properly)
257 if (isset($base->ipath)) {
258 $base->ipath = preg_replace('!//+!', '/', $base->ipath);
419214d7
TC
259 }
260
7f559418
JB
261 if ($absolute = \SimplePie_IRI::absolutize($base, $url)) {
262 return $absolute->get_uri();
94654765 263 }
156bf627 264
e0597476 265 $this->logger->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
48656e0e 266
7f559418 267 return false;
94654765 268 }
577c0b6d
JB
269
270 /**
271 * Retrieve and validate the extension from the response of the url of the image.
272 *
273 * @param Response $res Guzzle Response
274 * @param string $imagePath Path from the src image from the content (used for log only)
275 *
276 * @return string|false Extension name or false if validation failed
277 */
278 private function getExtensionFromResponse(Response $res, $imagePath)
279 {
280 $ext = $this->mimeGuesser->guess($res->getHeader('content-type'));
281 $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
282
283 // ok header doesn't have the extension, try a different way
284 if (empty($ext)) {
285 $types = [
286 'jpeg' => "\xFF\xD8\xFF",
287 'gif' => 'GIF',
288 'png' => "\x89\x50\x4e\x47\x0d\x0a",
289 ];
290 $bytes = substr((string) $res->getBody(), 0, 8);
291
292 foreach ($types as $type => $header) {
293 if (0 === strpos($bytes, $header)) {
294 $ext = $type;
295 break;
296 }
297 }
298
299 $this->logger->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]);
300 }
301
302 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
f808b016 303 $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath);
577c0b6d
JB
304
305 return false;
306 }
307
308 return $ext;
309 }
419214d7 310}