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