]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/DownloadImages.php
Add instance url to the downloaded images
[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;
419214d7 9
156bf627
JB
10class DownloadImages
11{
7f559418
JB
12 const REGENERATE_PICTURES_QUALITY = 80;
13
14 private $client;
15 private $baseFolder;
419214d7 16 private $logger;
7f559418 17 private $mimeGuesser;
41ada277 18 private $wallabagUrl;
419214d7 19
7f559418 20 public function __construct(Client $client, $baseFolder, LoggerInterface $logger)
156bf627 21 {
7f559418
JB
22 $this->client = $client;
23 $this->baseFolder = $baseFolder;
419214d7 24 $this->logger = $logger;
7f559418
JB
25 $this->mimeGuesser = new MimeTypeExtensionGuesser();
26
27 $this->setFolder();
419214d7
TC
28 }
29
41ada277
JB
30 /**
31 * Since we can't inject CraueConfig service because it'll generate a circular reference when injected in the subscriber
32 * we use a different way to inject the current wallabag url.
33 *
34 * @param string $url Usually from `$config->get('wallabag_url')`
35 */
36 public function setWallabagUrl($url)
37 {
38 $this->wallabagUrl = rtrim($url, '/');
39 }
40
7f559418
JB
41 /**
42 * Setup base folder where all images are going to be saved.
43 */
44 private function setFolder()
156bf627 45 {
419214d7 46 // if folder doesn't exist, attempt to create one and store the folder name in property $folder
7f559418
JB
47 if (!file_exists($this->baseFolder)) {
48 mkdir($this->baseFolder, 0777, true);
419214d7 49 }
419214d7
TC
50 }
51
7f559418
JB
52 /**
53 * Process the html and extract image from it, save them to local and return the updated html.
54 *
55 * @param string $html
56 * @param string $url Used as a base path for relative image and folder
57 *
58 * @return string
59 */
60 public function processHtml($html, $url)
156bf627 61 {
7f559418 62 $crawler = new Crawler($html);
419214d7
TC
63 $result = $crawler
64 ->filterXpath('//img')
65 ->extract(array('src'));
66
7f559418
JB
67 $relativePath = $this->getRelativePath($url);
68
419214d7
TC
69 // download and save the image to the folder
70 foreach ($result as $image) {
7f559418
JB
71 $imagePath = $this->processSingleImage($image, $url, $relativePath);
72
73 if (false === $imagePath) {
74 continue;
75 }
76
77 $html = str_replace($image, $imagePath, $html);
419214d7
TC
78 }
79
7f559418 80 return $html;
419214d7
TC
81 }
82
7f559418
JB
83 /**
84 * Process a single image:
85 * - retrieve it
86 * - re-saved it (for security reason)
87 * - return the new local path.
88 *
89 * @param string $imagePath Path to the image to retrieve
90 * @param string $url Url from where the image were found
91 * @param string $relativePath Relative local path to saved the image
92 *
93 * @return string Relative url to access the image from the web
94 */
95 public function processSingleImage($imagePath, $url, $relativePath = null)
156bf627 96 {
7f559418
JB
97 if (null == $relativePath) {
98 $relativePath = $this->getRelativePath($url);
419214d7
TC
99 }
100
7f559418 101 $folderPath = $this->baseFolder.'/'.$relativePath;
419214d7 102
7f559418
JB
103 // build image path
104 $absolutePath = $this->getAbsoluteLink($url, $imagePath);
105 if (false === $absolutePath) {
48656e0e 106 $this->logger->log('error', 'Can not determine the absolute path for that image, skipping.');
419214d7
TC
107
108 return false;
109 }
110
48656e0e
JB
111 try {
112 $res = $this->client->get($absolutePath);
113 } catch (\Exception $e) {
114 $this->logger->log('error', 'Can not retrieve image, skipping.', ['exception' => $e]);
115
116 return false;
117 }
7f559418
JB
118
119 $ext = $this->mimeGuesser->guess($res->getHeader('content-type'));
120 $this->logger->log('debug', 'Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]);
48656e0e
JB
121 if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) {
122 $this->logger->log('error', 'Processed image with not allowed extension. Skipping '.$imagePath);
419214d7
TC
123
124 return false;
125 }
7f559418
JB
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 }
419214d7 134
48656e0e 135 if (false === $im) {
7f559418 136 $this->logger->log('error', 'Error while regenerating image', ['path' => $localPath]);
419214d7
TC
137
138 return false;
139 }
140
7f559418
JB
141 switch ($ext) {
142 case 'gif':
143 $result = imagegif($im, $localPath);
156bf627 144 $this->logger->log('debug', 'Re-creating gif');
419214d7 145 break;
7f559418
JB
146 case 'jpeg':
147 case 'jpg':
148 $result = imagejpeg($im, $localPath, self::REGENERATE_PICTURES_QUALITY);
156bf627 149 $this->logger->log('debug', 'Re-creating jpg');
419214d7 150 break;
7f559418
JB
151 case 'png':
152 $result = imagepng($im, $localPath, ceil(self::REGENERATE_PICTURES_QUALITY / 100 * 9));
156bf627 153 $this->logger->log('debug', 'Re-creating png');
419214d7 154 }
7f559418 155
419214d7
TC
156 imagedestroy($im);
157
41ada277 158 return $this->wallabagUrl.'/assets/images/'.$relativePath.'/'.$hashImage.'.'.$ext;
419214d7
TC
159 }
160
7f559418
JB
161 /**
162 * Generate the folder where we are going to save images based on the entry url.
163 *
164 * @param string $url
165 *
166 * @return string
167 */
168 private function getRelativePath($url)
419214d7 169 {
7f559418
JB
170 $hashUrl = hash('crc32', $url);
171 $relativePath = $hashUrl[0].'/'.$hashUrl[1].'/'.$hashUrl;
172 $folderPath = $this->baseFolder.'/'.$relativePath;
419214d7 173
7f559418
JB
174 if (!file_exists($folderPath)) {
175 mkdir($folderPath, 0777, true);
419214d7
TC
176 }
177
7f559418 178 $this->logger->log('debug', 'Folder used for that url', ['folder' => $folderPath, 'url' => $url]);
419214d7 179
7f559418
JB
180 return $relativePath;
181 }
419214d7 182
7f559418
JB
183 /**
184 * Make an $url absolute based on the $base.
185 *
186 * @see Graby->makeAbsoluteStr
187 *
188 * @param string $base Base url
189 * @param string $url Url to make it absolute
190 *
191 * @return false|string
192 */
193 private function getAbsoluteLink($base, $url)
194 {
195 if (preg_match('!^https?://!i', $url)) {
196 // already absolute
197 return $url;
419214d7
TC
198 }
199
7f559418 200 $base = new \SimplePie_IRI($base);
419214d7 201
7f559418
JB
202 // remove '//' in URL path (causes URLs not to resolve properly)
203 if (isset($base->ipath)) {
204 $base->ipath = preg_replace('!//+!', '/', $base->ipath);
419214d7
TC
205 }
206
7f559418
JB
207 if ($absolute = \SimplePie_IRI::absolutize($base, $url)) {
208 return $absolute->get_uri();
94654765 209 }
156bf627 210
48656e0e
JB
211 $this->logger->log('error', 'Can not make an absolute link', ['base' => $base, 'url' => $url]);
212
7f559418 213 return false;
94654765 214 }
419214d7 215}