]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/DownloadImages.php
Replace images with &
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / DownloadImages.php
CommitLineData
419214d7
TC
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
7f559418 5use Psr\Log\LoggerInterface;
419214d7 6use Symfony\Component\DomCrawler\Crawler;
7f559418
JB
7use GuzzleHttp\Client;
8use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
e0597476 9use Symfony\Component\Finder\Finder;
419214d7 10
156bf627
JB
11class DownloadImages
12{
7f559418
JB
13 const REGENERATE_PICTURES_QUALITY = 80;
14
15 private $client;
16 private $baseFolder;
419214d7 17 private $logger;
7f559418 18 private $mimeGuesser;
41ada277 19 private $wallabagUrl;
419214d7 20
e0597476 21 public function __construct(Client $client, $baseFolder, $wallabagUrl, LoggerInterface $logger)
156bf627 22 {
7f559418
JB
23 $this->client = $client;
24 $this->baseFolder = $baseFolder;
e0597476 25 $this->wallabagUrl = rtrim($wallabagUrl, '/');
419214d7 26 $this->logger = $logger;
7f559418
JB
27 $this->mimeGuesser = new MimeTypeExtensionGuesser();
28
29 $this->setFolder();
419214d7
TC
30 }
31
7f559418
JB
32 /**
33 * Setup base folder where all images are going to be saved.
34 */
35 private function setFolder()
156bf627 36 {
419214d7 37 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
7f559418 38 if (!file_exists($this->baseFolder)) {
e044d27f 39 mkdir($this->baseFolder, 0755, true);
419214d7 40 }
419214d7
TC
41 }
42
7f559418
JB
43 /**
44 * Process the html and extract image from it, save them to local and return the updated html.
45 *
e0597476 46 * @param int $entryId ID of the entry
7f559418 47 * @param string $html
e0597476 48 * @param string $url Used as a base path for relative image and folder
7f559418
JB
49 *
50 * @return string
51 */
e0597476 52 public function processHtml($entryId, $html, $url)
156bf627 53 {
7f559418 54 $crawler = new Crawler($html);
419214d7
TC
55 $result = $crawler
56 ->filterXpath('//img')
57 ->extract(array('src'));
58
e0597476 59 $relativePath = $this->getRelativePath($entryId);
7f559418 60
419214d7
TC
61 // download and save the image to the folder
62 foreach ($result as $image) {
e0597476 63 $imagePath = $this->processSingleImage($entryId, $image, $url, $relativePath);
7f559418
JB
64
65 if (false === $imagePath) {
66 continue;
67 }
68
fcad69a4
JB
69 // if image contains "&"" and we can't find it in the html
70 // it might be because it's encoded as &amp;
71 if (false !== stripos($image, '&') && false === stripos($html, $image)) {
72 $image = str_replace('&', '&amp;', $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
JB
119
120 $ext = $this->mimeGuesser->guess($res->getHeader('content-type'));
e0597476 121 $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
48656e0e 122 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
fcad69a4 123 $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath);
419214d7
TC
124
125 return false;
126 }
7f559418
JB
127 $hashImage = hash('crc32', $absolutePath);
128 $localPath = $folderPath.'/'.$hashImage.'.'.$ext;
129
130 try {
131 $im = imagecreatefromstring($res->getBody());
132 } catch (\Exception $e) {
133 $im = false;
134 }
419214d7 135
48656e0e 136 if (false === $im) {
e0597476 137 $this->logger->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
419214d7
TC
138
139 return false;
140 }
141
7f559418
JB
142 switch ($ext) {
143 case 'gif':
001cc716 144 imagegif($im, $localPath);
e0597476 145 $this->logger->debug('DownloadImages: Re-creating gif');
419214d7 146 break;
7f559418
JB
147 case 'jpeg':
148 case 'jpg':
001cc716 149 imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY);
e0597476 150 $this->logger->debug('DownloadImages: Re-creating jpg');
419214d7 151 break;
7f559418 152 case 'png':
7a3260ae
KD
153 imagealphablending($im, false);
154 imagesavealpha($im, true);
001cc716 155 imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9));
e0597476 156 $this->logger->debug('DownloadImages: Re-creating png');
419214d7 157 }
7f559418 158
419214d7
TC
159 imagedestroy($im);
160
41ada277 161 return $this->wallabagUrl.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext;
419214d7
TC
162 }
163
e0597476
JB
164 /**
165 * Remove all images for the given entry id.
166 *
167 * @param int $entryId ID of the entry
168 */
169 public function removeImages($entryId)
170 {
171 $relativePath = $this->getRelativePath($entryId);
172 $folderPath = $this->baseFolder.'/'.$relativePath;
173
174 $finder = new Finder();
175 $finder
176 ->files()
177 ->ignoreDotFiles(true)
178 ->in($folderPath);
179
180 foreach ($finder as $file) {
181 @unlink($file->getRealPath());
182 }
183
184 @rmdir($folderPath);
185 }
186
7f559418
JB
187 /**
188 * Generate the folder where we are going to save images based on the entry url.
189 *
e0597476 190 * @param int $entryId ID of the entry
7f559418
JB
191 *
192 * @return string
193 */
e0597476 194 private function getRelativePath($entryId)
419214d7 195 {
e0597476
JB
196 $hashId = hash('crc32', $entryId);
197 $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId;
7f559418 198 $folderPath = $this->baseFolder.'/'.$relativePath;
419214d7 199
7f559418
JB
200 if (!file_exists($folderPath)) {
201 mkdir($folderPath, 0777, true);
419214d7
TC
202 }
203
e0597476 204 $this->logger->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
419214d7 205
7f559418
JB
206 return $relativePath;
207 }
419214d7 208
7f559418
JB
209 /**
210 * Make an $url absolute based on the $base.
211 *
212 * @see Graby->makeAbsoluteStr
213 *
214 * @param string $base Base url
215 * @param string $url Url to make it absolute
216 *
217 * @return false|string
218 */
219 private function getAbsoluteLink($base, $url)
220 {
221 if (preg_match('!^https?://!i', $url)) {
222 // already absolute
223 return $url;
419214d7
TC
224 }
225
7f559418 226 $base = new \SimplePie_IRI($base);
419214d7 227
7f559418
JB
228 // remove '//' in URL path (causes URLs not to resolve properly)
229 if (isset($base->ipath)) {
230 $base->ipath = preg_replace('!//+!', '/', $base->ipath);
419214d7
TC
231 }
232
7f559418
JB
233 if ($absolute = \SimplePie_IRI::absolutize($base, $url)) {
234 return $absolute->get_uri();
94654765 235 }
156bf627 236
e0597476 237 $this->logger->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
48656e0e 238
7f559418 239 return false;
94654765 240 }
419214d7 241}