3 namespace Wallabag\CoreBundle\Helper
;
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
;
14 const REGENERATE_PICTURES_QUALITY
= 80;
22 public function __construct(Client
$client, $baseFolder, $wallabagUrl, LoggerInterface
$logger)
24 $this->client
= $client;
25 $this->baseFolder
= $baseFolder;
26 $this->wallabagUrl
= rtrim($wallabagUrl, '/');
27 $this->logger
= $logger;
28 $this->mimeGuesser
= new MimeTypeExtensionGuesser();
34 * Process the html and extract image from it, save them to local and return the updated html.
36 * @param int $entryId ID of the entry
38 * @param string $url Used as a base path for relative image and folder
42 public function processHtml($entryId, $html, $url)
44 $crawler = new Crawler($html);
45 $imagesCrawler = $crawler
46 ->filterXpath('//img');
47 $imagesUrls = $imagesCrawler
49 $imagesSrcsetUrls = $this->getSrcsetUrls($imagesCrawler);
50 $imagesUrls = array_unique(array_merge($imagesUrls, $imagesSrcsetUrls));
52 $relativePath = $this->getRelativePath($entryId);
54 // download and save the image to the folder
55 foreach ($imagesUrls as $image) {
56 $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath);
58 if (false === $imagePath) {
62 // if image contains "&" and we can't find it in the html it might be because it's encoded as &
63 if (false !== stripos($image, '&') && false === stripos($html, $image)) {
64 $image = str_replace('&', '&', $image);
67 $html = str_replace($image, $imagePath, $html);
74 * Process a single image:
76 * - re-saved it (for security reason)
77 * - return the new local path.
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
84 * @return string Relative url to access the image from the web
86 public function processSingleImage($entryId, $imagePath, $url, $relativePath = null)
88 if (null === $imagePath) {
92 if (null === $relativePath) {
93 $relativePath = $this->getRelativePath($entryId);
96 $this->logger
->debug('DownloadImages: working on image: ' . $imagePath);
98 $folderPath = $this->baseFolder
. '/' . $relativePath;
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.');
109 $res = $this->client
->get($absolutePath);
110 } catch (\Exception
$e) {
111 $this->logger
->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]);
116 $ext = $this->getExtensionFromResponse($res, $imagePath);
117 if (false === $res) {
121 $hashImage = hash('crc32', $absolutePath);
122 $localPath = $folderPath . '/' . $hashImage . '.' . $ext;
125 $im = imagecreatefromstring($res->getBody());
126 } catch (\Exception
$e) {
131 $this->logger
->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
138 // use Imagick if available to keep GIF animation
139 if (class_exists('\\Imagick')) {
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);
150 imagegif($im, $localPath);
153 $this->logger
->debug('DownloadImages: Re-creating gif');
157 imagejpeg($im, $localPath, self
::REGENERATE_PICTURES_QUALITY
);
158 $this->logger
->debug('DownloadImages: Re-creating jpg');
161 imagealphablending($im, false);
162 imagesavealpha($im, true);
163 imagepng($im, $localPath, ceil(self
::REGENERATE_PICTURES_QUALITY
/ 100 * 9));
164 $this->logger
->debug('DownloadImages: Re-creating png');
169 return $this->wallabagUrl
. '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext;
173 * Remove all images for the given entry id.
175 * @param int $entryId ID of the entry
177 public function removeImages($entryId)
179 $relativePath = $this->getRelativePath($entryId);
180 $folderPath = $this->baseFolder
. '/' . $relativePath;
182 $finder = new Finder();
185 ->ignoreDotFiles(true)
188 foreach ($finder as $file) {
189 @unlink($file->getRealPath());
196 * Get images urls from the srcset image attribute.
198 * @param Crawler $imagesCrawler
200 * @return array An array of urls
202 private function getSrcsetUrls(Crawler
$imagesCrawler)
205 $iterator = $imagesCrawler
207 while ($iterator->valid()) {
208 $srcsetAttribute = $iterator->current()->getAttribute('srcset');
209 if ('' !== $srcsetAttribute) {
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);
215 $srcset = \
call_user_func_array('array_merge', $matches);
216 $srcsetUrls = array_map(function ($src) {
217 return trim(explode(' ', $src, 2)[0]);
219 $urls = array_merge($srcsetUrls, $urls);
228 * Setup base folder where all images are going to be saved.
230 private function setFolder()
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);
239 * Generate the folder where we are going to save images based on the entry url.
241 * @param int $entryId ID of the entry
245 private function getRelativePath($entryId)
247 $hashId = hash('crc32', $entryId);
248 $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId;
249 $folderPath = $this->baseFolder
. '/' . $relativePath;
251 if (!file_exists($folderPath)) {
252 mkdir($folderPath, 0777, true);
255 $this->logger
->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
257 return $relativePath;
261 * Make an $url absolute based on the $base.
263 * @see Graby->makeAbsoluteStr
265 * @param string $base Base url
266 * @param string $url Url to make it absolute
268 * @return false|string
270 private function getAbsoluteLink($base, $url)
272 if (preg_match('!^https?://!i', $url)) {
277 $base = new \
SimplePie_IRI($base);
279 // remove '//' in URL path (causes URLs not to resolve properly)
280 if (isset($base->ipath
)) {
281 $base->ipath
= preg_replace('!//+!', '/', $base->ipath
);
284 if ($absolute = \SimplePie_IRI
::absolutize($base, $url)) {
285 return $absolute->get_uri();
288 $this->logger
->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
294 * Retrieve and validate the extension from the response of the url of the image.
296 * @param Response $res Guzzle Response
297 * @param string $imagePath Path from the src image from the content (used for log only)
299 * @return string|false Extension name or false if validation failed
301 private function getExtensionFromResponse(Response
$res, $imagePath)
303 $ext = $this->mimeGuesser
->guess($res->getHeader('content-type'));
304 $this->logger
->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
306 // ok header doesn't have the extension, try a different way
309 'jpeg' => "\xFF\xD8\xFF",
311 'png' => "\x89\x50\x4e\x47\x0d\x0a",
313 $bytes = substr((string) $res->getBody(), 0, 8);
315 foreach ($types as $type => $header) {
316 if (0 === strpos($bytes, $header)) {
322 $this->logger
->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]);
325 if (!\
in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
326 $this->logger
->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath);