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