]> git.mxchange.org Git - friendica.git/blob - src/Module/Proxy.php
Simplified proxy handling
[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\Object\Image;
28 use Friendica\Util\HTTPSignature;
29 use Friendica\Util\Images;
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 rawContent(array $parameters = [])
49         {
50                 if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
51                         header("HTTP/1.1 304 Not Modified");
52                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
53                         if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) {
54                                 header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]);
55                         }
56                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
57                         header("Cache-Control: max-age=31536000");
58                         if (function_exists("header_remove")) {
59                                 header_remove("Last-Modified");
60                                 header_remove("Expires");
61                                 header_remove("Cache-Control");
62                         }
63                         exit;
64                 }
65
66                 $request = self::getRequestInfo($parameters);
67
68                 if (empty($request['url'])) {
69                         throw new \Friendica\Network\HTTPException\BadRequestException();
70                 }
71
72                 if (!local_user()) {
73                         Logger::info('Redirecting not logged in user to original address', ['url' => $request['url']]);
74                         System::externalRedirect($request['url']);
75                 }
76
77                 // It shouldn't happen but it does - spaces in URL
78                 $request['url'] = str_replace(' ', '+', $request['url']);
79
80                 // Fetch the content with the local user
81                 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), ['timeout' => 10]);
82                 $img_str = $fetchResult->getBody();
83
84                 // If there is an error then return an error
85                 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
86                         Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
87                         self::responseError();
88                         // stop.
89                 }
90
91                 $mime = Images::getMimeTypeByData($img_str);
92
93                 $image = new Image($img_str, $mime);
94                 if (!$image->isValid()) {
95                         Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
96                         self::responseError();
97                         // stop.
98                 }
99
100                 // reduce quality - if it isn't a GIF
101                 if ($image->getType() != 'image/gif') {
102                         $image->scaleDown($request['size']);
103                 }
104
105                 self::responseImageHttpCache($image);
106                 // stop.
107         }
108
109         /**
110          * Build info about requested image to be proxied
111          *
112          * @return array
113          *    [
114          *      'url' => requested url,
115          *      'size' => requested image size (int)
116          *      'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
117          *    ]
118          * @throws \Exception
119          */
120         private static function getRequestInfo(array $parameters)
121         {
122                 $size = ProxyUtils::PIXEL_LARGE;
123                 $sizetype = '';
124
125                 if (!empty($parameters['url']) && empty($_REQUEST['url'])) {
126                         $url = $parameters['url'];
127
128                         // thumb, small, medium and large.
129                         if (substr($url, -6) == ':micro') {
130                                 $size = ProxyUtils::PIXEL_MICRO;
131                                 $sizetype = ':micro';
132                                 $url = substr($url, 0, -6);
133                         } elseif (substr($url, -6) == ':thumb') {
134                                 $size = ProxyUtils::PIXEL_THUMB;
135                                 $sizetype = ':thumb';
136                                 $url = substr($url, 0, -6);
137                         } elseif (substr($url, -6) == ':small') {
138                                 $size = ProxyUtils::PIXEL_SMALL;
139                                 $url = substr($url, 0, -6);
140                                 $sizetype = ':small';
141                         } elseif (substr($url, -7) == ':medium') {
142                                 $size = ProxyUtils::PIXEL_MEDIUM;
143                                 $url = substr($url, 0, -7);
144                                 $sizetype = ':medium';
145                         } elseif (substr($url, -6) == ':large') {
146                                 $size = ProxyUtils::PIXEL_LARGE;
147                                 $url = substr($url, 0, -6);
148                                 $sizetype = ':large';
149                         }
150
151                         $pos = strrpos($url, '=.');
152                         if ($pos) {
153                                 $url = substr($url, 0, $pos + 1);
154                         }
155
156                         $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
157
158                         $url = base64_decode(strtr($url, '-_', '+/'), true);
159                 } else {
160                         $url = $_REQUEST['url'] ?? '';
161                 }
162
163                 return [
164                         'url' => $url,
165                         'size' => $size,
166                         'sizetype' => $sizetype,
167                 ];
168         }
169
170         /**
171          * In case of an error just stop. We don't return content to avoid caching problems
172          *
173          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
174          */
175         private static function responseError()
176         {
177                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
178         }
179
180         /**
181          * Output the image with cache headers
182          *
183          * @param Image $img
184          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185          */
186         private static function responseImageHttpCache(Image $img)
187         {
188                 if (is_null($img) || !$img->isValid()) {
189                         Logger::info('The cached image is invalid');
190                         self::responseError();
191                         // stop.
192                 }
193                 header('Content-type: ' . $img->getType());
194                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
195                 header('Etag: "' . md5($img->asString()) . '"');
196                 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
197                 header('Cache-Control: max-age=31536000');
198                 echo $img->asString();
199                 exit();
200         }
201 }