]> git.mxchange.org Git - friendica.git/blob - src/Module/Proxy.php
Merge pull request #8135 from annando/brief
[friendica.git] / src / Module / Proxy.php
1 <?php
2 /**
3  * @file src/Module/Proxy.php
4  * Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
5  */
6 namespace Friendica\Module;
7
8 use Friendica\BaseModule;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Core\Logger;
12 use Friendica\DI;
13 use Friendica\Model\Photo;
14 use Friendica\Object\Image;
15 use Friendica\Util\HTTPSignature;
16 use Friendica\Util\Proxy as ProxyUtils;
17
18 /**
19  * Module Proxy
20  *
21  * urls:
22  * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
23  * /proxy?url=<image url>
24  */
25 class Proxy extends BaseModule
26 {
27
28         /**
29          * Initializer method for this class.
30          *
31          * Sets application instance and checks if /proxy/ path is writable.
32          *
33          */
34         public static function init(array $parameters = [])
35         {
36                 // Set application instance here
37                 $a = DI::app();
38
39                 /*
40                  * Pictures are stored in one of the following ways:
41                  *
42                  * 1. If a folder "proxy" exists and is writeable, then use this for caching
43                  * 2. If a cache path is defined, use this
44                  * 3. If everything else failed, cache into the database
45                  *
46                  * Question: Do we really need these three methods?
47                  */
48                 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
49                         header('HTTP/1.1 304 Not Modified');
50                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
51                         header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
52                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
53                         header('Cache-Control: max-age=31536000');
54
55                         if (function_exists('header_remove')) {
56                                 header_remove('Last-Modified');
57                                 header_remove('Expires');
58                                 header_remove('Cache-Control');
59                         }
60
61                         /// @TODO Stop here?
62                         exit();
63                 }
64
65                 if (function_exists('header_remove')) {
66                         header_remove('Pragma');
67                         header_remove('pragma');
68                 }
69
70                 $direct_cache = self::setupDirectCache();
71
72                 $request = self::getRequestInfo();
73
74                 if (empty($request['url'])) {
75                         throw new \Friendica\Network\HTTPException\BadRequestException();
76                 }
77
78                 // Webserver already tried direct cache...
79
80                 // Try to use filecache;
81                 $cachefile = self::responseFromCache($request);
82
83                 // Try to use photo from db
84                 self::responseFromDB($request);
85
86                 //
87                 // If script is here, the requested url has never cached before.
88                 // Let's fetch it, scale it if required, then save it in cache.
89                 //
90
91                 // It shouldn't happen but it does - spaces in URL
92                 $request['url'] = str_replace(' ', '+', $request['url']);
93                 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), true, ['timeout' => 10]);
94                 $img_str = $fetchResult->getBody();
95
96                 // If there is an error then return a blank image
97                 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
98                         Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
99                         self::responseError();
100                         // stop.
101                 }
102
103                 $tempfile = tempnam(get_temppath(), 'cache');
104                 file_put_contents($tempfile, $img_str);
105                 $mime = mime_content_type($tempfile);
106                 unlink($tempfile);
107
108                 $image = new Image($img_str, $mime);
109                 if (!$image->isValid()) {
110                         Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
111                         self::responseError();
112                         // stop.
113                 }
114
115                 $basepath = $a->getBasePath();
116
117                 // Store original image
118                 if ($direct_cache) {
119                         // direct cache , store under ./proxy/
120                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
121                 } elseif($cachefile !== '') {
122                         // cache file
123                         file_put_contents($cachefile, $image->asString());
124                 } else {
125                         // database
126                         Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
127                 }
128
129
130                 // reduce quality - if it isn't a GIF
131                 if ($image->getType() != 'image/gif') {
132                         $image->scaleDown($request['size']);
133                 }
134
135
136                 // Store scaled image
137                 if ($direct_cache && $request['sizetype'] != '') {
138                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
139                 }
140
141                 self::responseImageHttpCache($image);
142                 // stop.
143         }
144
145
146         /**
147          * Build info about requested image to be proxied
148          *
149          * @return array
150          *    [
151          *      'url' => requested url,
152          *      'urlhash' => sha1 has of the url prefixed with 'pic:',
153          *      'size' => requested image size (int)
154          *      'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
155          *    ]
156          * @throws \Exception
157          */
158         private static function getRequestInfo()
159         {
160                 $a = DI::app();
161                 $size = 1024;
162                 $sizetype = '';
163
164                 // Look for filename in the arguments
165                 // @TODO: Replace with parameter from router
166                 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
167                         if (isset($a->argv[3])) {
168                                 $url = $a->argv[3];
169                         } elseif (isset($a->argv[2])) {
170                                 $url = $a->argv[2];
171                         } else {
172                                 $url = $a->argv[1];
173                         }
174
175                         /// @TODO: Why? And what about $url in this case?
176                         /// @TODO: Replace with parameter from router
177                         if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
178                                 $size = 200;
179                         }
180
181                         // thumb, small, medium and large.
182                         if (substr($url, -6) == ':micro') {
183                                 $size = 48;
184                                 $sizetype = ':micro';
185                                 $url = substr($url, 0, -6);
186                         } elseif (substr($url, -6) == ':thumb') {
187                                 $size = 80;
188                                 $sizetype = ':thumb';
189                                 $url = substr($url, 0, -6);
190                         } elseif (substr($url, -6) == ':small') {
191                                 $size = 300;
192                                 $url = substr($url, 0, -6);
193                                 $sizetype = ':small';
194                         } elseif (substr($url, -7) == ':medium') {
195                                 $size = 600;
196                                 $url = substr($url, 0, -7);
197                                 $sizetype = ':medium';
198                         } elseif (substr($url, -6) == ':large') {
199                                 $size = 1024;
200                                 $url = substr($url, 0, -6);
201                                 $sizetype = ':large';
202                         }
203
204                         $pos = strrpos($url, '=.');
205                         if ($pos) {
206                                 $url = substr($url, 0, $pos + 1);
207                         }
208
209                         $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
210
211                         $url = base64_decode(strtr($url, '-_', '+/'), true);
212
213                 } else {
214                         $url = $_REQUEST['url'] ?? '';
215                 }
216
217                 return [
218                         'url' => $url,
219                         'urlhash' => 'pic:' . sha1($url),
220                         'size' => $size,
221                         'sizetype' => $sizetype,
222                 ];
223         }
224
225
226         /**
227          * setup ./proxy folder for direct cache
228          *
229          * @return bool  False if direct cache can't be used.
230          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231          */
232         private static function setupDirectCache()
233         {
234                 $a = DI::app();
235                 $basepath = $a->getBasePath();
236
237                 // If the cache path isn't there, try to create it
238                 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
239                         mkdir($basepath . '/proxy');
240                 }
241
242                 // Checking if caching into a folder in the webroot is activated and working
243                 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
244                 // we don't use direct cache if image url is passed in args and not in querystring
245                 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
246
247                 return $direct_cache;
248         }
249
250
251         /**
252          * Try to reply with image in cachefile
253          *
254          * @param array $request Array from getRequestInfo
255          *
256          * @return string  Cache file name, empty string if cache is not enabled.
257          *
258          * If cachefile exists, script ends here and this function will never returns
259          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260          * @throws \ImagickException
261          */
262         private static function responseFromCache(&$request)
263         {
264                 $cachefile = get_cachefile(hash('md5', $request['url']));
265                 if ($cachefile != '' && file_exists($cachefile)) {
266                         $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
267                         self::responseImageHttpCache($img);
268                         // stop.
269                 }
270                 return $cachefile;
271         }
272
273         /**
274          * Try to reply with image in database
275          *
276          * @param array $request Array from getRequestInfo
277          *
278          * If the image exists in database, then script ends here and this function will never returns
279          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
280          * @throws \ImagickException
281          */
282         private static function responseFromDB(&$request)
283         {
284                 $photo = Photo::getPhoto($request['urlhash']);
285
286                 if ($photo !== false) {
287                         $img = Photo::getImageForPhoto($photo);
288                         self::responseImageHttpCache($img);
289                         // stop.
290                 }
291         }
292
293         /**
294          * In case of an error just stop. We don't return content to avoid caching problems
295          *
296          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297          */
298         private static function responseError()
299         {
300                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
301         }
302
303         /**
304          * Output the image with cache headers
305          *
306          * @param Image $img
307          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
308          */
309         private static function responseImageHttpCache(Image $img)
310         {
311                 if (is_null($img) || !$img->isValid()) {
312                         Logger::info('The cached image is invalid');
313                         self::responseError();
314                         // stop.
315                 }
316                 header('Content-type: ' . $img->getType());
317                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
318                 header('Etag: "' . md5($img->asString()) . '"');
319                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
320                 header('Cache-Control: max-age=31536000');
321                 echo $img->asString();
322                 exit();
323         }
324 }