3 namespace Wallabag\CoreBundle\Helper
;
5 use Psr\Log\LoggerInterface
;
6 use Symfony\Component\DomCrawler\Crawler
;
8 use GuzzleHttp\Message\Response
;
9 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser
;
10 use Symfony\Component\Finder\Finder
;
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 * Setup base folder where all images are going to be saved.
36 private function setFolder()
38 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
39 if (!file_exists($this->baseFolder
)) {
40 mkdir($this->baseFolder
, 0755, true);
45 * Process the html and extract image from it, save them to local and return the updated html.
47 * @param int $entryId ID of the entry
49 * @param string $url Used as a base path for relative image and folder
53 public function processHtml($entryId, $html, $url)
55 $crawler = new Crawler($html);
57 ->filterXpath('//img')
60 $relativePath = $this->getRelativePath($entryId);
62 // download and save the image to the folder
63 foreach ($result as $image) {
64 $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath);
66 if (false === $imagePath) {
70 // if image contains "&" and we can't find it in the html it might be because it's encoded as &
71 if (false !== stripos($image, '&') && false === stripos($html, $image)) {
72 $image = str_replace('&', '&', $image);
75 $html = str_replace($image, $imagePath, $html);
82 * Process a single image:
84 * - re-saved it (for security reason)
85 * - return the new local path.
87 * @param int $entryId ID of the entry
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
92 * @return string Relative url to access the image from the web
94 public function processSingleImage($entryId, $imagePath, $url, $relativePath = null)
96 if (null === $relativePath) {
97 $relativePath = $this->getRelativePath($entryId);
100 $this->logger
->debug('DownloadImages: working on image: '.$imagePath);
102 $folderPath = $this->baseFolder
.'/'.$relativePath;
105 $absolutePath = $this->getAbsoluteLink($url, $imagePath);
106 if (false === $absolutePath) {
107 $this->logger
->error('DownloadImages: Can not determine the absolute path for that image, skipping.');
113 $res = $this->client
->get($absolutePath);
114 } catch (\Exception
$e) {
115 $this->logger
->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]);
120 $ext = $this->getExtensionFromResponse($res, $imagePath);
121 if (false === $res) {
125 $hashImage = hash('crc32', $absolutePath);
126 $localPath = $folderPath.'/'.$hashImage.'.'.$ext;
129 $im = imagecreatefromstring($res->getBody());
130 } catch (\Exception
$e) {
135 $this->logger
->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
142 imagegif($im, $localPath);
143 $this->logger
->debug('DownloadImages: Re-creating gif');
147 imagejpeg($im, $localPath, self
::REGENERATE_PICTURES_QUALITY
);
148 $this->logger
->debug('DownloadImages: Re-creating jpg');
151 imagealphablending($im, false);
152 imagesavealpha($im, true);
153 imagepng($im, $localPath, ceil(self
::REGENERATE_PICTURES_QUALITY
/ 100 * 9));
154 $this->logger
->debug('DownloadImages: Re-creating png');
159 return $this->wallabagUrl
.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext;
163 * Remove all images for the given entry id.
165 * @param int $entryId ID of the entry
167 public function removeImages($entryId)
169 $relativePath = $this->getRelativePath($entryId);
170 $folderPath = $this->baseFolder
.'/'.$relativePath;
172 $finder = new Finder();
175 ->ignoreDotFiles(true)
178 foreach ($finder as $file) {
179 @unlink($file->getRealPath());
186 * Generate the folder where we are going to save images based on the entry url.
188 * @param int $entryId ID of the entry
192 private function getRelativePath($entryId)
194 $hashId = hash('crc32', $entryId);
195 $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId;
196 $folderPath = $this->baseFolder
.'/'.$relativePath;
198 if (!file_exists($folderPath)) {
199 mkdir($folderPath, 0777, true);
202 $this->logger
->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
204 return $relativePath;
208 * Make an $url absolute based on the $base.
210 * @see Graby->makeAbsoluteStr
212 * @param string $base Base url
213 * @param string $url Url to make it absolute
215 * @return false|string
217 private function getAbsoluteLink($base, $url)
219 if (preg_match('!^https?://!i', $url)) {
224 $base = new \
SimplePie_IRI($base);
226 // remove '//' in URL path (causes URLs not to resolve properly)
227 if (isset($base->ipath
)) {
228 $base->ipath
= preg_replace('!//+!', '/', $base->ipath
);
231 if ($absolute = \SimplePie_IRI
::absolutize($base, $url)) {
232 return $absolute->get_uri();
235 $this->logger
->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
241 * Retrieve and validate the extension from the response of the url of the image.
243 * @param Response $res Guzzle Response
244 * @param string $imagePath Path from the src image from the content (used for log only)
246 * @return string|false Extension name or false if validation failed
248 private function getExtensionFromResponse(Response
$res, $imagePath)
250 $ext = $this->mimeGuesser
->guess($res->getHeader('content-type'));
251 $this->logger
->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
253 // ok header doesn't have the extension, try a different way
256 'jpeg' => "\xFF\xD8\xFF",
258 'png' => "\x89\x50\x4e\x47\x0d\x0a",
260 $bytes = substr((string) $res->getBody(), 0, 8);
262 foreach ($types as $type => $header) {
263 if (0 === strpos($bytes, $header)) {
269 $this->logger
->debug('DownloadImages: Checking extension (alternative)', ['ext' => $ext]);
272 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
273 $this->logger
->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath);