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