3 namespace Wallabag\CoreBundle\Helper
;
5 use Http\Client\Common\HttpMethodsClient
;
6 use Http\Client\Common\Plugin\ErrorPlugin
;
7 use Http\Client\Common\PluginClient
;
8 use Http\Client\HttpClient
;
9 use Http\Discovery\MessageFactoryDiscovery
;
10 use Http\Message\MessageFactory
;
11 use Psr\Http\Message\ResponseInterface
;
12 use Psr\Log\LoggerInterface
;
13 use Symfony\Component\DomCrawler\Crawler
;
14 use Symfony\Component\Finder\Finder
;
15 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser
;
19 const REGENERATE_PICTURES_QUALITY
= 80;
27 public function __construct(HttpClient
$client, $baseFolder, $wallabagUrl, LoggerInterface
$logger, MessageFactory
$messageFactory = null)
29 $this->client
= new HttpMethodsClient(new PluginClient($client, [new ErrorPlugin()]), $messageFactory ?: MessageFactoryDiscovery
::find());
30 $this->baseFolder
= $baseFolder;
31 $this->wallabagUrl
= rtrim($wallabagUrl, '/');
32 $this->logger
= $logger;
33 $this->mimeGuesser
= new MimeTypeExtensionGuesser();
39 * Process the html and extract images URLs from it.
45 public static function extractImagesUrlsFromHtml($html)
47 $crawler = new Crawler($html);
48 $imagesCrawler = $crawler
49 ->filterXpath('//img');
50 $imagesUrls = $imagesCrawler
52 $imagesSrcsetUrls = self
::getSrcsetUrls($imagesCrawler);
54 return array_unique(array_merge($imagesUrls, $imagesSrcsetUrls));
58 * Process the html and extract image from it, save them to local and return the updated html.
60 * @param int $entryId ID of the entry
62 * @param string $url Used as a base path for relative image and folder
66 public function processHtml($entryId, $html, $url)
68 $imagesUrls = self
::extractImagesUrlsFromHtml($html);
70 $relativePath = $this->getRelativePath($entryId);
72 // download and save the image to the folder
73 foreach ($imagesUrls as $image) {
74 $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath);
76 if (false === $imagePath) {
80 // if image contains "&" and we can't find it in the html it might be because it's encoded as &
81 if (false !== stripos($image, '&') && false === stripos($html, $image)) {
82 $image = str_replace('&', '&', $image);
85 $html = str_replace($image, $imagePath, $html);
92 * Process a single image:
94 * - re-saved it (for security reason)
95 * - return the new local path.
97 * @param int $entryId ID of the entry
98 * @param string $imagePath Path to the image to retrieve
99 * @param string $url Url from where the image were found
100 * @param string $relativePath Relative local path to saved the image
102 * @return string Relative url to access the image from the web
104 public function processSingleImage($entryId, $imagePath, $url, $relativePath = null)
106 if (null === $imagePath) {
110 if (null === $relativePath) {
111 $relativePath = $this->getRelativePath($entryId);
114 $this->logger
->debug('DownloadImages: working on image: ' . $imagePath);
116 $folderPath = $this->baseFolder
. '/' . $relativePath;
119 $absolutePath = $this->getAbsoluteLink($url, $imagePath);
120 if (false === $absolutePath) {
121 $this->logger
->error('DownloadImages: Can not determine the absolute path for that image, skipping.');
127 $res = $this->client
->get($absolutePath);
128 } catch (\Exception
$e) {
129 $this->logger
->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]);
134 $ext = $this->getExtensionFromResponse($res, $imagePath);
135 if (false === $res) {
139 $hashImage = hash('crc32', $absolutePath);
140 $localPath = $folderPath . '/' . $hashImage . '.' . $ext;
143 $im = imagecreatefromstring((string) $res->getBody());
144 } catch (\Exception
$e) {
149 $this->logger
->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
156 // use Imagick if available to keep GIF animation
157 if (class_exists('\\Imagick')) {
159 $imagick = new \
Imagick();
160 $imagick->readImageBlob($res->getBody());
161 $imagick->setImageFormat('gif');
162 $imagick->writeImages($localPath, true);
163 } catch (\Exception
$e) {
164 // if Imagick fail, fallback to the default solution
165 imagegif($im, $localPath);
168 imagegif($im, $localPath);
171 $this->logger
->debug('DownloadImages: Re-creating gif');
175 imagejpeg($im, $localPath, self
::REGENERATE_PICTURES_QUALITY
);
176 $this->logger
->debug('DownloadImages: Re-creating jpg');
179 imagealphablending($im, false);
180 imagesavealpha($im, true);
181 imagepng($im, $localPath, ceil(self
::REGENERATE_PICTURES_QUALITY
/ 100 * 9));
182 $this->logger
->debug('DownloadImages: Re-creating png');
187 return $this->wallabagUrl
. '/assets/images/' . $relativePath . '/' . $hashImage . '.' . $ext;
191 * Remove all images for the given entry id.
193 * @param int $entryId ID of the entry
195 public function removeImages($entryId)
197 $relativePath = $this->getRelativePath($entryId);
198 $folderPath = $this->baseFolder
. '/' . $relativePath;
200 $finder = new Finder();
203 ->ignoreDotFiles(true)
206 foreach ($finder as $file) {
207 @unlink($file->getRealPath());
214 * Get images urls from the srcset image attribute.
216 * @param Crawler $imagesCrawler
218 * @return array An array of urls
220 private static function getSrcsetUrls(Crawler
$imagesCrawler)
223 $iterator = $imagesCrawler
225 while ($iterator->valid()) {
226 $srcsetAttribute = $iterator->current()->getAttribute('srcset');
227 if ('' !== $srcsetAttribute) {
228 // Couldn't start with " OR ' OR a white space
229 // Could be one or more white space
230 // Must be one or more digits followed by w OR x
231 $pattern = "/(?:[^\"'\s]+\s*(?:\d+[wx])+)/";
232 preg_match_all($pattern, $srcsetAttribute, $matches);
233 $srcset = \
call_user_func_array('array_merge', $matches);
234 $srcsetUrls = array_map(function ($src) {
235 return trim(explode(' ', $src, 2)[0]);
237 $urls = array_merge($srcsetUrls, $urls);
246 * Setup base folder where all images are going to be saved.
248 private function setFolder()
250 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
251 if (!file_exists($this->baseFolder
)) {
252 mkdir($this->baseFolder
, 0755, true);
257 * Generate the folder where we are going to save images based on the entry url.
259 * @param int $entryId ID of the entry
263 private function getRelativePath($entryId)
265 $hashId = hash('crc32', $entryId);
266 $relativePath = $hashId[0] . '/' . $hashId[1] . '/' . $hashId;
267 $folderPath = $this->baseFolder
. '/' . $relativePath;
269 if (!file_exists($folderPath)) {
270 mkdir($folderPath, 0777, true);
273 $this->logger
->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
275 return $relativePath;
279 * Make an $url absolute based on the $base.
281 * @see Graby->makeAbsoluteStr
283 * @param string $base Base url
284 * @param string $url Url to make it absolute
286 * @return false|string
288 private function getAbsoluteLink($base, $url)
290 if (preg_match('!^https?://!i', $url)) {
295 $base = new \
SimplePie_IRI($base);
297 // remove '//' in URL path (causes URLs not to resolve properly)
298 if (isset($base->ipath
)) {
299 $base->ipath
= preg_replace('!//+!', '/', $base->ipath
);
302 if ($absolute = \SimplePie_IRI
::absolutize($base, $url)) {
303 return $absolute->get_uri();
306 $this->logger
->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
312 * Retrieve and validate the extension from the response of the url of the image.
314 * @param ResponseInterface $res Http Response
315 * @param string $imagePath Path from the src image from the content (used for log only)
317 * @return string|false Extension name or false if validation failed
319 private function getExtensionFromResponse(ResponseInterface
$res, $imagePath)
321 $ext = $this->mimeGuesser
->guess(current($res->getHeader('content-type')));
322 $this->logger
->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
324 // ok header doesn't have the extension, try a different way
327 'jpeg' => "\xFF\xD8\xFF",
329 'png' => "\x89\x50\x4e\x47\x0d\x0a",
331 $bytes = substr((string) $res->getBody(), 0, 8);
333 foreach ($types as $type => $header) {
334 if (0 === strpos($bytes, $header)) {
340 $this->logger
->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]);
343 if (!\
in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
344 $this->logger
->error('DownloadImages: Processed image with not allowed extension. Skipping: ' . $imagePath);