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