]> git.mxchange.org Git - friendica.git/blob - src/Module/Proxy.php
Merge pull request #7044 from MrPetovan/task/router
[friendica.git] / src / Module / Proxy.php
1 <?php
2 /**
3  * @file src/Module/Proxy.php
4  * @brief 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\Model\Photo;
12 use Friendica\Object\Image;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Util\Proxy as ProxyUtils;
15
16 /**
17  * @brief 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          * @brief Initializer method for this class.
28          *
29          * Sets application instance and checks if /proxy/ path is writable.
30          *
31          */
32         public static function init()
33         {
34                 // Set application instance here
35                 $a = self::getApp();
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                         System::httpExit(400, ['title' => L10n::t('Bad Request.')]);
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') || (!$img_str)) {
96                         self::responseError();
97                         // stop.
98                 }
99
100                 $tempfile = tempnam(get_temppath(), 'cache');
101                 file_put_contents($tempfile, $img_str);
102                 $mime = mime_content_type($tempfile);
103                 unlink($tempfile);
104
105                 $image = new Image($img_str, $mime);
106                 if (!$image->isValid()) {
107                         self::responseError();
108                         // stop.
109                 }
110
111                 $basepath = $a->getBasePath();
112
113                 // Store original image
114                 if ($direct_cache) {
115                         // direct cache , store under ./proxy/
116                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
117                 } elseif($cachefile !== '') {
118                         // cache file
119                         file_put_contents($cachefile, $image->asString());
120                 } else {
121                         // database
122                         Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
123                 }
124
125
126                 // reduce quality - if it isn't a GIF
127                 if ($image->getType() != 'image/gif') {
128                         $image->scaleDown($request['size']);
129                 }
130
131
132                 // Store scaled image
133                 if ($direct_cache && $request['sizetype'] != '') {
134                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
135                 }
136
137                 self::responseImageHttpCache($image);
138                 // stop.
139         }
140
141
142         /**
143          * @brief Build info about requested image to be proxied
144          *
145          * @return array
146          *    [
147          *      'url' => requested url,
148          *      'urlhash' => sha1 has of the url prefixed with 'pic:',
149          *      'size' => requested image size (int)
150          *      'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
151          *    ]
152          * @throws \Exception
153          */
154         private static function getRequestInfo()
155         {
156                 $a = self::getApp();
157                 $size = 1024;
158                 $sizetype = '';
159
160                 // Look for filename in the arguments
161                 // @TODO: Replace with parameter from router
162                 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
163                         if (isset($a->argv[3])) {
164                                 $url = $a->argv[3];
165                         } elseif (isset($a->argv[2])) {
166                                 $url = $a->argv[2];
167                         } else {
168                                 $url = $a->argv[1];
169                         }
170
171                         /// @TODO: Why? And what about $url in this case?
172                         /// @TODO: Replace with parameter from router
173                         if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
174                                 $size = 200;
175                         }
176
177                         // thumb, small, medium and large.
178                         if (substr($url, -6) == ':micro') {
179                                 $size = 48;
180                                 $sizetype = ':micro';
181                                 $url = substr($url, 0, -6);
182                         } elseif (substr($url, -6) == ':thumb') {
183                                 $size = 80;
184                                 $sizetype = ':thumb';
185                                 $url = substr($url, 0, -6);
186                         } elseif (substr($url, -6) == ':small') {
187                                 $size = 300;
188                                 $url = substr($url, 0, -6);
189                                 $sizetype = ':small';
190                         } elseif (substr($url, -7) == ':medium') {
191                                 $size = 600;
192                                 $url = substr($url, 0, -7);
193                                 $sizetype = ':medium';
194                         } elseif (substr($url, -6) == ':large') {
195                                 $size = 1024;
196                                 $url = substr($url, 0, -6);
197                                 $sizetype = ':large';
198                         }
199
200                         $pos = strrpos($url, '=.');
201                         if ($pos) {
202                                 $url = substr($url, 0, $pos + 1);
203                         }
204
205                         $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
206
207                         $url = base64_decode(strtr($url, '-_', '+/'), true);
208
209                 } else {
210                         $url = defaults($_REQUEST, 'url', '');
211                 }
212
213                 return [
214                         'url' => $url,
215                         'urlhash' => 'pic:' . sha1($url),
216                         'size' => $size,
217                         'sizetype' => $sizetype,
218                 ];
219         }
220
221
222         /**
223          * @brief setup ./proxy folder for direct cache
224          *
225          * @return bool  False if direct cache can't be used.
226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227          */
228         private static function setupDirectCache()
229         {
230                 $a = self::getApp();
231                 $basepath = $a->getBasePath();
232
233                 // If the cache path isn't there, try to create it
234                 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
235                         mkdir($basepath . '/proxy');
236                 }
237
238                 // Checking if caching into a folder in the webroot is activated and working
239                 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
240                 // we don't use direct cache if image url is passed in args and not in querystring
241                 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
242
243                 return $direct_cache;
244         }
245
246
247         /**
248          * @brief Try to reply with image in cachefile
249          *
250          * @param array $request Array from getRequestInfo
251          *
252          * @return string  Cache file name, empty string if cache is not enabled.
253          *
254          * If cachefile exists, script ends here and this function will never returns
255          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256          * @throws \ImagickException
257          */
258         private static function responseFromCache(&$request)
259         {
260                 $cachefile = get_cachefile(hash('md5', $request['url']));
261                 if ($cachefile != '' && file_exists($cachefile)) {
262                         $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
263                         self::responseImageHttpCache($img);
264                         // stop.
265                 }
266                 return $cachefile;
267         }
268
269         /**
270          * @brief Try to reply with image in database
271          *
272          * @param array $request Array from getRequestInfo
273          *
274          * If the image exists in database, then script ends here and this function will never returns
275          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276          * @throws \ImagickException
277          */
278         private static function responseFromDB(&$request)
279         {
280                 $photo = Photo::getPhoto($request['urlhash']);
281
282                 if ($photo !== false) {
283                         $img = Photo::getImageForPhoto($photo);
284                         self::responseImageHttpCache($img);
285                         // stop.
286                 }
287         }
288
289         /**
290          * @brief Output a blank image, without cache headers, in case of errors
291          *
292          */
293         private static function responseError()
294         {
295                 header('Content-type: image/png');
296                 echo file_get_contents('images/blank.png');
297                 exit();
298         }
299
300         /**
301          * @brief Output the image with cache headers
302          *
303          * @param Image $img
304          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305          */
306         private static function responseImageHttpCache(Image $img)
307         {
308                 if (is_null($img) || !$img->isValid()) {
309                         self::responseError();
310                         // stop.
311                 }
312                 header('Content-type: ' . $img->getType());
313                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
314                 header('Etag: "' . md5($img->asString()) . '"');
315                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
316                 header('Cache-Control: max-age=31536000');
317                 echo $img->asString();
318                 exit();
319         }
320 }