]>
Commit | Line | Data |
---|---|---|
419214d7 TC |
1 | <?php |
2 | ||
3 | namespace Wallabag\CoreBundle\Helper; | |
4 | ||
7f559418 | 5 | use Psr\Log\LoggerInterface; |
419214d7 | 6 | use Symfony\Component\DomCrawler\Crawler; |
7f559418 | 7 | use GuzzleHttp\Client; |
577c0b6d | 8 | use GuzzleHttp\Message\Response; |
7f559418 | 9 | use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser; |
e0597476 | 10 | use Symfony\Component\Finder\Finder; |
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 | * Setup base folder where all images are going to be saved. | |
35 | */ | |
36 | private function setFolder() | |
156bf627 | 37 | { |
419214d7 | 38 | // if folder doesn't exist, attempt to create one and store the folder name in property $folder |
7f559418 | 39 | if (!file_exists($this->baseFolder)) { |
e044d27f | 40 | mkdir($this->baseFolder, 0755, true); |
419214d7 | 41 | } |
419214d7 TC |
42 | } |
43 | ||
7f559418 JB |
44 | /** |
45 | * Process the html and extract image from it, save them to local and return the updated html. | |
46 | * | |
e0597476 | 47 | * @param int $entryId ID of the entry |
7f559418 | 48 | * @param string $html |
e0597476 | 49 | * @param string $url Used as a base path for relative image and folder |
7f559418 JB |
50 | * |
51 | * @return string | |
52 | */ | |
e0597476 | 53 | public function processHtml($entryId, $html, $url) |
156bf627 | 54 | { |
7f559418 | 55 | $crawler = new Crawler($html); |
419214d7 TC |
56 | $result = $crawler |
57 | ->filterXpath('//img') | |
9bf7752f | 58 | ->extract(['src']); |
419214d7 | 59 | |
e0597476 | 60 | $relativePath = $this->getRelativePath($entryId); |
7f559418 | 61 | |
419214d7 TC |
62 | // download and save the image to the folder |
63 | foreach ($result as $image) { | |
e0597476 | 64 | $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath); |
7f559418 JB |
65 | |
66 | if (false === $imagePath) { | |
67 | continue; | |
68 | } | |
69 | ||
9bf7752f | 70 | // if image contains "&" and we can't find it in the html it might be because it's encoded as & |
fcad69a4 JB |
71 | if (false !== stripos($image, '&') && false === stripos($html, $image)) { |
72 | $image = str_replace('&', '&', $image); | |
73 | } | |
74 | ||
7f559418 | 75 | $html = str_replace($image, $imagePath, $html); |
419214d7 TC |
76 | } |
77 | ||
7f559418 | 78 | return $html; |
419214d7 TC |
79 | } |
80 | ||
7f559418 JB |
81 | /** |
82 | * Process a single image: | |
83 | * - retrieve it | |
84 | * - re-saved it (for security reason) | |
85 | * - return the new local path. | |
86 | * | |
e0597476 | 87 | * @param int $entryId ID of the entry |
7f559418 JB |
88 | * @param string $imagePath Path to the image to retrieve |
89 | * @param string $url Url from where the image were found | |
90 | * @param string $relativePath Relative local path to saved the image | |
91 | * | |
92 | * @return string Relative url to access the image from the web | |
93 | */ | |
e0597476 | 94 | public function processSingleImage($entryId, $imagePath, $url, $relativePath = null) |
156bf627 | 95 | { |
e0597476 JB |
96 | if (null === $relativePath) { |
97 | $relativePath = $this->getRelativePath($entryId); | |
419214d7 TC |
98 | } |
99 | ||
e0597476 JB |
100 | $this->logger->debug('DownloadImages: working on image: '.$imagePath); |
101 | ||
7f559418 | 102 | $folderPath = $this->baseFolder.'/'.$relativePath; |
419214d7 | 103 | |
7f559418 JB |
104 | // build image path |
105 | $absolutePath = $this->getAbsoluteLink($url, $imagePath); | |
106 | if (false === $absolutePath) { | |
e0597476 | 107 | $this->logger->error('DownloadImages: Can not determine the absolute path for that image, skipping.'); |
419214d7 TC |
108 | |
109 | return false; | |
110 | } | |
111 | ||
48656e0e JB |
112 | try { |
113 | $res = $this->client->get($absolutePath); | |
114 | } catch (\Exception $e) { | |
e0597476 | 115 | $this->logger->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]); |
48656e0e JB |
116 | |
117 | return false; | |
118 | } | |
7f559418 | 119 | |
577c0b6d JB |
120 | $ext = $this->getExtensionFromResponse($res, $imagePath); |
121 | if (false === $res) { | |
419214d7 TC |
122 | return false; |
123 | } | |
577c0b6d | 124 | |
7f559418 JB |
125 | $hashImage = hash('crc32', $absolutePath); |
126 | $localPath = $folderPath.'/'.$hashImage.'.'.$ext; | |
127 | ||
128 | try { | |
129 | $im = imagecreatefromstring($res->getBody()); | |
130 | } catch (\Exception $e) { | |
131 | $im = false; | |
132 | } | |
419214d7 | 133 | |
48656e0e | 134 | if (false === $im) { |
e0597476 | 135 | $this->logger->error('DownloadImages: Error while regenerating image', ['path' => $localPath]); |
419214d7 TC |
136 | |
137 | return false; | |
138 | } | |
139 | ||
7f559418 JB |
140 | switch ($ext) { |
141 | case 'gif': | |
001cc716 | 142 | imagegif($im, $localPath); |
e0597476 | 143 | $this->logger->debug('DownloadImages: Re-creating gif'); |
419214d7 | 144 | break; |
7f559418 JB |
145 | case 'jpeg': |
146 | case 'jpg': | |
001cc716 | 147 | imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY); |
e0597476 | 148 | $this->logger->debug('DownloadImages: Re-creating jpg'); |
419214d7 | 149 | break; |
7f559418 | 150 | case 'png': |
7a3260ae KD |
151 | imagealphablending($im, false); |
152 | imagesavealpha($im, true); | |
001cc716 | 153 | imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9)); |
e0597476 | 154 | $this->logger->debug('DownloadImages: Re-creating png'); |
419214d7 | 155 | } |
7f559418 | 156 | |
419214d7 TC |
157 | imagedestroy($im); |
158 | ||
41ada277 | 159 | return $this->wallabagUrl.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext; |
419214d7 TC |
160 | } |
161 | ||
e0597476 JB |
162 | /** |
163 | * Remove all images for the given entry id. | |
164 | * | |
165 | * @param int $entryId ID of the entry | |
166 | */ | |
167 | public function removeImages($entryId) | |
168 | { | |
169 | $relativePath = $this->getRelativePath($entryId); | |
170 | $folderPath = $this->baseFolder.'/'.$relativePath; | |
171 | ||
172 | $finder = new Finder(); | |
173 | $finder | |
174 | ->files() | |
175 | ->ignoreDotFiles(true) | |
176 | ->in($folderPath); | |
177 | ||
178 | foreach ($finder as $file) { | |
179 | @unlink($file->getRealPath()); | |
180 | } | |
181 | ||
182 | @rmdir($folderPath); | |
183 | } | |
184 | ||
7f559418 JB |
185 | /** |
186 | * Generate the folder where we are going to save images based on the entry url. | |
187 | * | |
e0597476 | 188 | * @param int $entryId ID of the entry |
7f559418 JB |
189 | * |
190 | * @return string | |
191 | */ | |
e0597476 | 192 | private function getRelativePath($entryId) |
419214d7 | 193 | { |
e0597476 JB |
194 | $hashId = hash('crc32', $entryId); |
195 | $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId; | |
7f559418 | 196 | $folderPath = $this->baseFolder.'/'.$relativePath; |
419214d7 | 197 | |
7f559418 JB |
198 | if (!file_exists($folderPath)) { |
199 | mkdir($folderPath, 0777, true); | |
419214d7 TC |
200 | } |
201 | ||
e0597476 | 202 | $this->logger->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]); |
419214d7 | 203 | |
7f559418 JB |
204 | return $relativePath; |
205 | } | |
419214d7 | 206 | |
7f559418 JB |
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; | |
419214d7 TC |
222 | } |
223 | ||
7f559418 | 224 | $base = new \SimplePie_IRI($base); |
419214d7 | 225 | |
7f559418 JB |
226 | // remove '//' in URL path (causes URLs not to resolve properly) |
227 | if (isset($base->ipath)) { | |
228 | $base->ipath = preg_replace('!//+!', '/', $base->ipath); | |
419214d7 TC |
229 | } |
230 | ||
7f559418 JB |
231 | if ($absolute = \SimplePie_IRI::absolutize($base, $url)) { |
232 | return $absolute->get_uri(); | |
94654765 | 233 | } |
156bf627 | 234 | |
e0597476 | 235 | $this->logger->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]); |
48656e0e | 236 | |
7f559418 | 237 | return false; |
94654765 | 238 | } |
577c0b6d JB |
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 | } | |
419214d7 | 280 | } |