]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Helper/DownloadImages.php
252ba57c517f94dae8a30674829baa73a3074d80
[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 $result = $crawler
46 ->filterXpath('//img')
47 ->extract(['src']);
48
49 $relativePath = $this->getRelativePath($entryId);
50
51 // download and save the image to the folder
52 foreach ($result as $image) {
53 $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath);
54
55 if (false === $imagePath) {
56 continue;
57 }
58
59 // if image contains "&" and we can't find it in the html it might be because it's encoded as &amp;
60 if (false !== stripos($image, '&') && false === stripos($html, $image)) {
61 $image = str_replace('&', '&amp;', $image);
62 }
63
64 $html = str_replace($image, $imagePath, $html);
65 }
66
67 return $html;
68 }
69
70 /**
71 * Process a single image:
72 * - retrieve it
73 * - re-saved it (for security reason)
74 * - return the new local path.
75 *
76 * @param int $entryId ID of the entry
77 * @param string $imagePath Path to the image to retrieve
78 * @param string $url Url from where the image were found
79 * @param string $relativePath Relative local path to saved the image
80 *
81 * @return string Relative url to access the image from the web
82 */
83 public function processSingleImage($entryId, $imagePath, $url, $relativePath = null)
84 {
85 if (null === $relativePath) {
86 $relativePath = $this->getRelativePath($entryId);
87 }
88
89 $this->logger->debug('DownloadImages: working on image: ' . $imagePath);
90
91 $folderPath = $this->baseFolder . '/' . $relativePath;
92
93 // build image path
94 $absolutePath = $this->getAbsoluteLink($url, $imagePath);
95 if (false === $absolutePath) {
96 $this->logger->error('DownloadImages: Can not determine the absolute path for that image, skipping.');
97
98 return false;
99 }
100
101 try {
102 $res = $this->client->get($absolutePath);
103 } catch (\Exception $e) {
104 $this->logger->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]);
105
106 return false;
107 }
108
109 $ext = $this->getExtensionFromResponse($res, $imagePath);
110 if (false === $res) {
111 return false;
112 }
113
114 $hashImage = hash('crc32', $absolutePath);
115 $localPath = $folderPath . '/' . $hashImage . '.' . $ext;
116
117 try {
118 $im = imagecreatefromstring($res->getBody());
119 } catch (\Exception $e) {
120 $im = false;
121 }
122
123 if (false === $im) {
124 $this->logger->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
125
126 return false;
127 }
128
129 switch ($ext) {
130 case 'gif':
131 imagegif($im, $localPath);
132 $this->logger->debug('DownloadImages: Re-creating gif');
133 break;
134 case 'jpeg':
135 case 'jpg':
136 imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY);
137 $this->logger->debug('DownloadImages: Re-creating jpg');
138 break;
139 case 'png':
140 imagealphablending($im, false);
141 imagesavealpha($im, true);
142 imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9));
143 $this->logger->debug('DownloadImages: Re-creating png');
144 }
145
146 imagedestroy($im);
147
148 return $this->wallabagUrl . '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext;
149 }
150
151 /**
152 * Remove all images for the given entry id.
153 *
154 * @param int $entryId ID of the entry
155 */
156 public function removeImages($entryId)
157 {
158 $relativePath = $this->getRelativePath($entryId);
159 $folderPath = $this->baseFolder . '/' . $relativePath;
160
161 $finder = new Finder();
162 $finder
163 ->files()
164 ->ignoreDotFiles(true)
165 ->in($folderPath);
166
167 foreach ($finder as $file) {
168 @unlink($file->getRealPath());
169 }
170
171 @rmdir($folderPath);
172 }
173
174 /**
175 * Setup base folder where all images are going to be saved.
176 */
177 private function setFolder()
178 {
179 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
180 if (!file_exists($this->baseFolder)) {
181 mkdir($this->baseFolder, 0755, true);
182 }
183 }
184
185 /**
186 * Generate the folder where we are going to save images based on the entry url.
187 *
188 * @param int $entryId ID of the entry
189 *
190 * @return string
191 */
192 private function getRelativePath($entryId)
193 {
194 $hashId = hash('crc32', $entryId);
195 $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId;
196 $folderPath = $this->baseFolder . '/' . $relativePath;
197
198 if (!file_exists($folderPath)) {
199 mkdir($folderPath, 0777, true);
200 }
201
202 $this->logger->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
203
204 return $relativePath;
205 }
206
207 /**
208 * Make an $url absolute based on the $base.
209 *
210 * @see Graby->makeAbsoluteStr
211 *
212 * @param string $base Base url
213 * @param string $url Url to make it absolute
214 *
215 * @return false|string
216 */
217 private function getAbsoluteLink($base, $url)
218 {
219 if (preg_match('!^https?://!i', $url)) {
220 // already absolute
221 return $url;
222 }
223
224 $base = new \SimplePie_IRI($base);
225
226 // remove '//' in URL path (causes URLs not to resolve properly)
227 if (isset($base->ipath)) {
228 $base->ipath = preg_replace('!//+!', '/', $base->ipath);
229 }
230
231 if ($absolute = \SimplePie_IRI::absolutize($base, $url)) {
232 return $absolute->get_uri();
233 }
234
235 $this->logger->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
236
237 return false;
238 }
239
240 /**
241 * Retrieve and validate the extension from the response of the url of the image.
242 *
243 * @param Response $res Guzzle Response
244 * @param string $imagePath Path from the src image from the content (used for log only)
245 *
246 * @return string|false Extension name or false if validation failed
247 */
248 private function getExtensionFromResponse(Response $res, $imagePath)
249 {
250 $ext = $this->mimeGuesser->guess($res->getHeader('content-type'));
251 $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
252
253 // ok header doesn't have the extension, try a different way
254 if (empty($ext)) {
255 $types = [
256 'jpeg' => "\xFF\xD8\xFF",
257 'gif' => 'GIF',
258 'png' => "\x89\x50\x4e\x47\x0d\x0a",
259 ];
260 $bytes = substr((string) $res->getBody(), 0, 8);
261
262 foreach ($types as $type => $header) {
263 if (0 === strpos($bytes, $header)) {
264 $ext = $type;
265 break;
266 }
267 }
268
269 $this->logger->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]);
270 }
271
272 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
273 $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath);
274
275 return false;
276 }
277
278 return $ext;
279 }
280 }