]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/DownloadImages.php
Merge pull request #3123 from X-dark/master
[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
69 $html = str_replace($image, $imagePath, $html);
419214d7
TC
70 }
71
7f559418 72 return $html;
419214d7
TC
73 }
74
7f559418
JB
75 /**
76 * Process a single image:
77 * - retrieve it
78 * - re-saved it (for security reason)
79 * - return the new local path.
80 *
e0597476 81 * @param int $entryId ID of the entry
7f559418
JB
82 * @param string $imagePath Path to the image to retrieve
83 * @param string $url Url from where the image were found
84 * @param string $relativePath Relative local path to saved the image
85 *
86 * @return string Relative url to access the image from the web
87 */
e0597476 88 public function processSingleImage($entryId, $imagePath, $url, $relativePath = null)
156bf627 89 {
e0597476
JB
90 if (null === $relativePath) {
91 $relativePath = $this->getRelativePath($entryId);
419214d7
TC
92 }
93
e0597476
JB
94 $this->logger->debug('DownloadImages: working on image: '.$imagePath);
95
7f559418 96 $folderPath = $this->baseFolder.'/'.$relativePath;
419214d7 97
7f559418
JB
98 // build image path
99 $absolutePath = $this->getAbsoluteLink($url, $imagePath);
100 if (false === $absolutePath) {
e0597476 101 $this->logger->error('DownloadImages: Can not determine the absolute path for that image, skipping.');
419214d7
TC
102
103 return false;
104 }
105
48656e0e
JB
106 try {
107 $res = $this->client->get($absolutePath);
108 } catch (\Exception $e) {
e0597476 109 $this->logger->error('DownloadImages: Can not retrieve image, skipping.', ['exception' => $e]);
48656e0e
JB
110
111 return false;
112 }
7f559418
JB
113
114 $ext = $this->mimeGuesser->guess($res->getHeader('content-type'));
e0597476 115 $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
48656e0e 116 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
e0597476 117 $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping '.$imagePath);
419214d7
TC
118
119 return false;
120 }
7f559418
JB
121 $hashImage = hash('crc32', $absolutePath);
122 $localPath = $folderPath.'/'.$hashImage.'.'.$ext;
123
124 try {
125 $im = imagecreatefromstring($res->getBody());
126 } catch (\Exception $e) {
127 $im = false;
128 }
419214d7 129
48656e0e 130 if (false === $im) {
e0597476 131 $this->logger->error('DownloadImages: Error while regenerating image', ['path' => $localPath]);
419214d7
TC
132
133 return false;
134 }
135
7f559418
JB
136 switch ($ext) {
137 case 'gif':
001cc716 138 imagegif($im, $localPath);
e0597476 139 $this->logger->debug('DownloadImages: Re-creating gif');
419214d7 140 break;
7f559418
JB
141 case 'jpeg':
142 case 'jpg':
001cc716 143 imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY);
e0597476 144 $this->logger->debug('DownloadImages: Re-creating jpg');
419214d7 145 break;
7f559418 146 case 'png':
7a3260ae
KD
147 imagealphablending($im, false);
148 imagesavealpha($im, true);
001cc716 149 imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9));
e0597476 150 $this->logger->debug('DownloadImages: Re-creating png');
419214d7 151 }
7f559418 152
419214d7
TC
153 imagedestroy($im);
154
41ada277 155 return $this->wallabagUrl.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext;
419214d7
TC
156 }
157
e0597476
JB
158 /**
159 * Remove all images for the given entry id.
160 *
161 * @param int $entryId ID of the entry
162 */
163 public function removeImages($entryId)
164 {
165 $relativePath = $this->getRelativePath($entryId);
166 $folderPath = $this->baseFolder.'/'.$relativePath;
167
168 $finder = new Finder();
169 $finder
170 ->files()
171 ->ignoreDotFiles(true)
172 ->in($folderPath);
173
174 foreach ($finder as $file) {
175 @unlink($file->getRealPath());
176 }
177
178 @rmdir($folderPath);
179 }
180
7f559418
JB
181 /**
182 * Generate the folder where we are going to save images based on the entry url.
183 *
e0597476 184 * @param int $entryId ID of the entry
7f559418
JB
185 *
186 * @return string
187 */
e0597476 188 private function getRelativePath($entryId)
419214d7 189 {
e0597476
JB
190 $hashId = hash('crc32', $entryId);
191 $relativePath = $hashId[0].'/'.$hashId[1].'/'.$hashId;
7f559418 192 $folderPath = $this->baseFolder.'/'.$relativePath;
419214d7 193
7f559418
JB
194 if (!file_exists($folderPath)) {
195 mkdir($folderPath, 0777, true);
419214d7
TC
196 }
197
e0597476 198 $this->logger->debug('DownloadImages: Folder used for that Entry id', ['folder' => $folderPath, 'entryId' => $entryId]);
419214d7 199
7f559418
JB
200 return $relativePath;
201 }
419214d7 202
7f559418
JB
203 /**
204 * Make an $url absolute based on the $base.
205 *
206 * @see Graby->makeAbsoluteStr
207 *
208 * @param string $base Base url
209 * @param string $url Url to make it absolute
210 *
211 * @return false|string
212 */
213 private function getAbsoluteLink($base, $url)
214 {
215 if (preg_match('!^https?://!i', $url)) {
216 // already absolute
217 return $url;
419214d7
TC
218 }
219
7f559418 220 $base = new \SimplePie_IRI($base);
419214d7 221
7f559418
JB
222 // remove '//' in URL path (causes URLs not to resolve properly)
223 if (isset($base->ipath)) {
224 $base->ipath = preg_replace('!//+!', '/', $base->ipath);
419214d7
TC
225 }
226
7f559418
JB
227 if ($absolute = \SimplePie_IRI::absolutize($base, $url)) {
228 return $absolute->get_uri();
94654765 229 }
156bf627 230
e0597476 231 $this->logger->error('DownloadImages: Can not make an absolute link', ['base' => $base, 'url' => $url]);
48656e0e 232
7f559418 233 return false;
94654765 234 }
419214d7 235}