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