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