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