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