]> git.mxchange.org Git - friendica.git/blob - src/Module/Proxy.php
317ec530a5335ab22dc9024182087ba21de09dc4
[friendica.git] / src / Module / Proxy.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\DI;
28 use Friendica\Model\Photo;
29 use Friendica\Object\Image;
30 use Friendica\Util\HTTPSignature;
31 use Friendica\Util\Proxy as ProxyUtils;
32
33 /**
34  * Module Proxy
35  *
36  * urls:
37  * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
38  * /proxy?url=<image url>
39  */
40 class Proxy extends BaseModule
41 {
42
43         /**
44          * Initializer method for this class.
45          *
46          * Sets application instance and checks if /proxy/ path is writable.
47          *
48          */
49         public static function rawContent(array $parameters = [])
50         {
51                 // Set application instance here
52                 $a = DI::app();
53
54                 /*
55                  * Pictures are stored in one of the following ways:
56                  *
57                  * 1. If a folder "proxy" exists and is writeable, then use this for caching
58                  * 2. If a cache path is defined, use this
59                  * 3. If everything else failed, cache into the database
60                  *
61                  * Question: Do we really need these three methods?
62                  */
63                 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
64                         header('HTTP/1.1 304 Not Modified');
65                         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
66                         header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
67                         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
68                         header('Cache-Control: max-age=31536000');
69
70                         if (function_exists('header_remove')) {
71                                 header_remove('Last-Modified');
72                                 header_remove('Expires');
73                                 header_remove('Cache-Control');
74                         }
75
76                         /// @TODO Stop here?
77                         exit();
78                 }
79
80                 if (function_exists('header_remove')) {
81                         header_remove('Pragma');
82                         header_remove('pragma');
83                 }
84
85                 $direct_cache = self::setupDirectCache();
86
87                 $request = self::getRequestInfo();
88
89                 if (empty($request['url'])) {
90                         throw new \Friendica\Network\HTTPException\BadRequestException();
91                 }
92
93                 if (!local_user()) {
94                         Logger::info('Redirecting not logged in user to original address', ['url' => $request['url']]);
95                         System::externalRedirect($request['url']);
96                 }
97
98                 // Webserver already tried direct cache...
99
100                 // Try to use filecache;
101                 $cachefile = self::responseFromCache($request);
102
103                 // Try to use photo from db
104                 self::responseFromDB($request);
105
106                 //
107                 // If script is here, the requested url has never cached before.
108                 // Let's fetch it, scale it if required, then save it in cache.
109                 //
110
111                 // It shouldn't happen but it does - spaces in URL
112                 $request['url'] = str_replace(' ', '+', $request['url']);
113                 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), ['timeout' => 10]);
114                 $img_str = $fetchResult->getBody();
115
116                 // If there is an error then return a blank image
117                 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
118                         Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
119                         self::responseError();
120                         // stop.
121                 }
122
123                 $tempfile = tempnam(get_temppath(), 'cache');
124                 file_put_contents($tempfile, $img_str);
125                 $mime = mime_content_type($tempfile);
126                 unlink($tempfile);
127
128                 $image = new Image($img_str, $mime);
129                 if (!$image->isValid()) {
130                         Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
131                         self::responseError();
132                         // stop.
133                 }
134
135                 $basepath = $a->getBasePath();
136                 $filepermission = DI::config()->get('system', 'proxy_file_chmod');
137
138                 // Store original image
139                 if ($direct_cache) {
140                         // direct cache , store under ./proxy/
141                         $filename = $basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true);
142                         file_put_contents($filename, $image->asString());
143                         if (!empty($filepermission)) {
144                                 chmod($filename, $filepermission);
145                         }
146                 } elseif($cachefile !== '') {
147                         // cache file
148                         file_put_contents($cachefile, $image->asString());
149                 } else {
150                         // database
151                         Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
152                 }
153
154
155                 // reduce quality - if it isn't a GIF
156                 if ($image->getType() != 'image/gif') {
157                         $image->scaleDown($request['size']);
158                 }
159
160
161                 // Store scaled image
162                 if ($direct_cache && $request['sizetype'] != '') {
163                         $filename = $basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'];
164                         file_put_contents($filename, $image->asString());
165                         if (!empty($filepermission)) {
166                                 chmod($filename, $filepermission);
167                         }
168                 }
169
170                 self::responseImageHttpCache($image);
171                 // stop.
172         }
173
174
175         /**
176          * Build info about requested image to be proxied
177          *
178          * @return array
179          *    [
180          *      'url' => requested url,
181          *      'urlhash' => sha1 has of the url prefixed with 'pic:',
182          *      'size' => requested image size (int)
183          *      'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
184          *    ]
185          * @throws \Exception
186          */
187         private static function getRequestInfo()
188         {
189                 $a = DI::app();
190                 $size = ProxyUtils::PIXEL_LARGE;
191                 $sizetype = '';
192
193                 // Look for filename in the arguments
194                 // @TODO: Replace with parameter from router
195                 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
196                         if (isset($a->argv[3])) {
197                                 $url = $a->argv[3];
198                         } elseif (isset($a->argv[2])) {
199                                 $url = $a->argv[2];
200                         } else {
201                                 $url = $a->argv[1];
202                         }
203
204                         /// @TODO: Why? And what about $url in this case?
205                         /// @TODO: Replace with parameter from router
206                         if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
207                                 $size = 200;
208                         }
209
210                         // thumb, small, medium and large.
211                         if (substr($url, -6) == ':micro') {
212                                 $size = ProxyUtils::PIXEL_MICRO;
213                                 $sizetype = ':micro';
214                                 $url = substr($url, 0, -6);
215                         } elseif (substr($url, -6) == ':thumb') {
216                                 $size = ProxyUtils::PIXEL_THUMB;
217                                 $sizetype = ':thumb';
218                                 $url = substr($url, 0, -6);
219                         } elseif (substr($url, -6) == ':small') {
220                                 $size = ProxyUtils::PIXEL_SMALL;
221                                 $url = substr($url, 0, -6);
222                                 $sizetype = ':small';
223                         } elseif (substr($url, -7) == ':medium') {
224                                 $size = ProxyUtils::PIXEL_MEDIUM;
225                                 $url = substr($url, 0, -7);
226                                 $sizetype = ':medium';
227                         } elseif (substr($url, -6) == ':large') {
228                                 $size = ProxyUtils::PIXEL_LARGE;
229                                 $url = substr($url, 0, -6);
230                                 $sizetype = ':large';
231                         }
232
233                         $pos = strrpos($url, '=.');
234                         if ($pos) {
235                                 $url = substr($url, 0, $pos + 1);
236                         }
237
238                         $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
239
240                         $url = base64_decode(strtr($url, '-_', '+/'), true);
241
242                 } else {
243                         $url = $_REQUEST['url'] ?? '';
244                 }
245
246                 return [
247                         'url' => $url,
248                         'urlhash' => 'pic:' . sha1($url),
249                         'size' => $size,
250                         'sizetype' => $sizetype,
251                 ];
252         }
253
254
255         /**
256          * setup ./proxy folder for direct cache
257          *
258          * @return bool  False if direct cache can't be used.
259          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260          */
261         private static function setupDirectCache()
262         {
263                 $a = DI::app();
264                 $basepath = $a->getBasePath();
265
266                 // If the cache path isn't there, try to create it
267                 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
268                         mkdir($basepath . '/proxy');
269                 }
270
271                 // Checking if caching into a folder in the webroot is activated and working
272                 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
273                 // we don't use direct cache if image url is passed in args and not in querystring
274                 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
275
276                 return $direct_cache;
277         }
278
279
280         /**
281          * Try to reply with image in cachefile
282          *
283          * @param array $request Array from getRequestInfo
284          *
285          * @return string  Cache file name, empty string if cache is not enabled.
286          *
287          * If cachefile exists, script ends here and this function will never returns
288          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289          * @throws \ImagickException
290          */
291         private static function responseFromCache(&$request)
292         {
293                 $cachefile = get_cachefile(hash('md5', $request['url']));
294                 if ($cachefile != '' && file_exists($cachefile)) {
295                         $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
296                         self::responseImageHttpCache($img);
297                         // stop.
298                 }
299                 return $cachefile;
300         }
301
302         /**
303          * Try to reply with image in database
304          *
305          * @param array $request Array from getRequestInfo
306          *
307          * If the image exists in database, then script ends here and this function will never returns
308          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309          * @throws \ImagickException
310          */
311         private static function responseFromDB(&$request)
312         {
313                 $photo = Photo::getPhoto($request['urlhash']);
314
315                 if ($photo !== false) {
316                         $img = Photo::getImageForPhoto($photo);
317                         self::responseImageHttpCache($img);
318                         // stop.
319                 }
320         }
321
322         /**
323          * In case of an error just stop. We don't return content to avoid caching problems
324          *
325          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326          */
327         private static function responseError()
328         {
329                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
330         }
331
332         /**
333          * Output the image with cache headers
334          *
335          * @param Image $img
336          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
337          */
338         private static function responseImageHttpCache(Image $img)
339         {
340                 if (is_null($img) || !$img->isValid()) {
341                         Logger::info('The cached image is invalid');
342                         self::responseError();
343                         // stop.
344                 }
345                 header('Content-type: ' . $img->getType());
346                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
347                 header('Etag: "' . md5($img->asString()) . '"');
348                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
349                 header('Cache-Control: max-age=31536000');
350                 echo $img->asString();
351                 exit();
352         }
353 }