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