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