]> git.mxchange.org Git - friendica.git/blob - src/Module/Proxy.php
6ca383f59b344a3100e19f425aadae627217ec58
[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\Network;
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                 //
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
91                 // It shouldn't happen but it does - spaces in URL
92                 $request['url'] = str_replace(' ', '+', $request['url']);
93                 $redirects = 0;
94                 $fetchResult = Network::fetchUrlFull($request['url'], true, $redirects, 10);
95                 $img_str = $fetchResult->getBody();
96
97                 $tempfile = tempnam(get_temppath(), 'cache');
98                 file_put_contents($tempfile, $img_str);
99                 $mime = mime_content_type($tempfile);
100                 unlink($tempfile);
101
102                 // If there is an error then return a blank image
103                 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || (!$img_str)) {
104                         self::responseError($request);
105                         // stop.
106                 }
107
108                 $image = new Image($img_str, $mime);
109                 if (!$image->isValid()) {
110                         self::responseError($request);
111                         // stop.
112                 }
113                 
114                 $basepath = $a->getBasePath();
115                 
116                 // Store original image
117                 if ($direct_cache) {
118                         // direct cache , store under ./proxy/
119                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
120                 } elseif($cachefile !== '') {
121                         // cache file
122                         file_put_contents($cachefile, $image->asString());
123                 } else {
124                         // database
125                         Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
126                 }
127
128
129                 // reduce quality - if it isn't a GIF
130                 if ($image->getType() != 'image/gif') {
131                         $image->scaleDown($request['size']);
132                 }
133
134
135                 // Store scaled image
136                 if ($direct_cache && $request['sizetype'] != '') {
137                         file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
138                 }
139
140                 self::responseImageHttpCache($image);
141                 // stop.
142         }
143
144
145         /**
146          * @brief Build info about requested image to be proxied
147          *
148          * @return array
149          *    [
150          *      'url' => requested url,
151          *      'urlhash' => sha1 has of the url prefixed with 'pic:',
152          *      'size' => requested image size (int)
153          *      'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
154          *    ]
155          * @throws \Exception
156          */
157         private static function getRequestInfo()
158         {
159                 $a = self::getApp();
160                 $url = '';
161                 $size = 1024;
162                 $sizetype = '';
163                 
164                 
165                 // Look for filename in the arguments
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                         if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
177                                 $size = 200;
178                         }
179
180                         // thumb, small, medium and large.
181                         if (substr($url, -6) == ':micro') {
182                                 $size = 48;
183                                 $sizetype = ':micro';
184                                 $url = substr($url, 0, -6);
185                         } elseif (substr($url, -6) == ':thumb') {
186                                 $size = 80;
187                                 $sizetype = ':thumb';
188                                 $url = substr($url, 0, -6);
189                         } elseif (substr($url, -6) == ':small') {
190                                 $size = 300;
191                                 $url = substr($url, 0, -6);
192                                 $sizetype = ':small';
193                         } elseif (substr($url, -7) == ':medium') {
194                                 $size = 600;
195                                 $url = substr($url, 0, -7);
196                                 $sizetype = ':medium';
197                         } elseif (substr($url, -6) == ':large') {
198                                 $size = 1024;
199                                 $url = substr($url, 0, -6);
200                                 $sizetype = ':large';
201                         }
202
203                         $pos = strrpos($url, '=.');
204                         if ($pos) {
205                                 $url = substr($url, 0, $pos + 1);
206                         }
207
208                         $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
209
210                         $url = base64_decode(strtr($url, '-_', '+/'), true);
211
212                 } else {
213                         $url = defaults($_REQUEST, 'url', '');
214                 }
215                 
216                 return [
217                         'url' => $url,
218                         'urlhash' => 'pic:' . sha1($url),
219                         'size' => $size,
220                         'sizetype' => $sizetype,
221                 ];
222         }
223
224
225         /**
226          * @brief setup ./proxy folder for direct cache
227          *
228          * @return bool  False if direct cache can't be used.
229          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230          */
231         private static function setupDirectCache()
232         {
233                 $a = self::getApp();
234                 $basepath = $a->getBasePath();
235
236                 // If the cache path isn't there, try to create it
237                 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
238                         mkdir($basepath . '/proxy');
239                 }
240
241                 // Checking if caching into a folder in the webroot is activated and working
242                 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
243                 // we don't use direct cache if image url is passed in args and not in querystring 
244                 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
245                 
246                 return $direct_cache;
247         }
248
249
250         /**
251          * @brief Try to reply with image in cachefile
252          *
253          * @param array $request Array from getRequestInfo
254          *
255          * @return string  Cache file name, empty string if cache is not enabled.
256          *
257          * If cachefile exists, script ends here and this function will never returns
258          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259          * @throws \ImagickException
260          */
261         private static function responseFromCache(&$request)
262         {
263                 $cachefile = get_cachefile(hash('md5', $request['url']));
264                 if ($cachefile != '' && file_exists($cachefile)) {
265                         $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
266                         self::responseImageHttpCache($img);
267                         // stop.
268                 }
269                 return $cachefile;
270         }
271
272         /**
273          * @brief Try to reply with image in database
274          *
275          * @param array $request Array from getRequestInfo
276          *
277          * If the image exists in database, then script ends here and this function will never returns
278          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279          * @throws \ImagickException
280          */
281         private static function responseFromDB(&$request) {
282         
283                 $photo = Photo::getPhoto($request['urlhash']);
284
285                 if ($photo !== false) {
286                         $img = Photo::getImageForPhoto($photo);
287                         self::responseImageHttpCache($img);
288                         // stop.
289                 }
290         }
291         
292         /**
293          * @brief Output a blank image, without cache headers, in case of errors
294          *
295          */
296         private static function responseError() {
297                 header('Content-type: ' . $img->getType());
298                 echo file_get_contents('images/blank.png');
299                 exit();
300         }
301
302         /**
303          * @brief Output the image with cache headers
304          *
305          * @param Image $img
306          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
307          */
308         private static function responseImageHttpCache(Image $img)
309         {
310                 if (is_null($img) || !$img->isValid()) {
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 }
323
324