3 namespace Wallabag\CoreBundle\Helper
;
5 use Psr\Log\LoggerInterface
;
6 use Symfony\Component\DomCrawler\Crawler
;
8 use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser
;
9 use Symfony\Component\Finder\Finder
;
13 const REGENERATE_PICTURES_QUALITY
= 80;
21 public function __construct(Client
$client, $baseFolder, $wallabagUrl, LoggerInterface
$logger)
23 $this->client
= $client;
24 $this->baseFolder
= $baseFolder;
25 $this->wallabagUrl
= rtrim($wallabagUrl, '/');
26 $this->logger
= $logger;
27 $this->mimeGuesser
= new MimeTypeExtensionGuesser();
33 * Setup base folder where all images are going to be saved.
35 private function setFolder()
37 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
38 if (!file_exists($this->baseFolder
)) {
39 mkdir($this->baseFolder
, 0755, true);
44 * Process the html and extract image from it, save them to local and return the updated html.
46 * @param int $entryId ID of the entry
48 * @param string $url Used as a base path for relative image and folder
52 public function processHtml($entryId, $html, $url)
54 $crawler = new Crawler($html);
56 ->filterXpath('//img')
57 ->extract(array('src'));
59 $relativePath = $this->getRelativePath($entryId);
61 // download and save the image to the folder
62 foreach ($result as $image) {
63 $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath);
65 if (false === $imagePath) {
69 // if image contains "&"" and we can't find it in the html
70 // 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->mimeGuesser
->guess($res->getHeader('content-type'));
121 $this->logger
->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
122 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
123 $this->logger
->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath);
127 $hashImage = hash('crc32', $absolutePath);
128 $localPath = $folderPath.'/'.$hashImage.'.'.$ext;
131 $im = imagecreatefromstring($res->getBody());
132 } catch (\Exception
$e) {
137 $this->logger
->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
144 imagegif($im, $localPath);
145 $this->logger
->debug('DownloadImages: Re-creating gif');
149 imagejpeg($im, $localPath, self
::REGENERATE_PICTURES_QUALITY
);
150 $this->logger
->debug('DownloadImages: Re-creating jpg');
153 imagealphablending($im, false);
154 imagesavealpha($im, true);
155 imagepng($im, $localPath, ceil(self
::REGENERATE_PICTURES_QUALITY
/ 100 * 9));
156 $this->logger
->debug('DownloadImages: Re-creating png');
161 return $this->wallabagUrl
.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext;
165 * Remove all images for the given entry id.
167 * @param int $entryId ID of the entry
169 public function removeImages($entryId)
171 $relativePath = $this->getRelativePath($entryId);
172 $folderPath = $this->baseFolder
.'/'.$relativePath;
174 $finder = new Finder();
177 ->ignoreDotFiles(true)
180 foreach ($finder as $file) {
181 @unlink($file->getRealPath());
188 * Generate the folder where we are going to save images based on the entry url.
190 * @param int $entryId ID of the entry
194 private function getRelativePath($entryId)
196 $hashId = hash('crc32', $entryId);
197 $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId;
198 $folderPath = $this->baseFolder
.'/'.$relativePath;
200 if (!file_exists($folderPath)) {
201 mkdir($folderPath, 0777, true);
204 $this->logger
->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
206 return $relativePath;
210 * Make an $url absolute based on the $base.
212 * @see Graby->makeAbsoluteStr
214 * @param string $base Base url
215 * @param string $url Url to make it absolute
217 * @return false|string
219 private function getAbsoluteLink($base, $url)
221 if (preg_match('!^https?://!i', $url)) {
226 $base = new \
SimplePie_IRI($base);
228 // remove '//' in URL path (causes URLs not to resolve properly)
229 if (isset($base->ipath
)) {
230 $base->ipath
= preg_replace('!//+!', '/', $base->ipath
);
233 if ($absolute = \SimplePie_IRI
::absolutize($base, $url)) {
234 return $absolute->get_uri();
237 $this->logger
->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);