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