3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module;
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
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;
40 * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
41 * /proxy?url=<image url>
43 class Proxy extends BaseModule
47 * Fetch remote image content
49 protected function rawContent(array $request = [])
51 $request = $this->getRequestInfo();
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();
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']);
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');
70 throw new NotModifiedException();
73 if (empty($request['url'])) {
74 throw new \Friendica\Network\HTTPException\BadRequestException();
77 if (!DI::userSession()->getLocalUserId()) {
78 Logger::debug('Redirecting not logged in user to original address', ['url' => $request['url']]);
79 System::externalRedirect($request['url']);
82 // It shouldn't happen but it does - spaces in URL
83 $request['url'] = str_replace(' ', '+', $request['url']);
85 // Fetch the content with the local user
87 $fetchResult = HTTPSignature::fetchRaw($request['url'], DI::userSession()->getLocalUserId(), [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE], 'timeout' => 10]);
88 $img_str = $fetchResult->getBody();
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();
95 } catch (\Exception $exception) {
96 Logger::notice('Error fetching image', ['image' => $request['url'], 'exception' => $exception]);
97 self::responseError();
100 Logger::debug('Got picture', ['Content-Type' => $fetchResult->getHeader('Content-Type'), 'uid' => DI::userSession()->getLocalUserId(), 'image' => $request['url']]);
102 $mime = Images::getMimeTypeByData($img_str);
104 $image = new Image($img_str, $mime);
105 if (!$image->isValid()) {
106 Logger::notice('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
107 self::responseError();
111 // reduce quality - if it isn't a GIF
112 if ($image->getType() != 'image/gif') {
113 $image->scaleDown($request['size']);
116 self::responseImageHttpCache($image);
121 * Build info about requested image to be proxied
125 * 'url' => requested url,
126 * 'size' => requested image size (int)
127 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
131 private function getRequestInfo(): array
133 $size = ProxyUtils::PIXEL_LARGE;
136 if (!empty($this->parameters['url']) && empty($_REQUEST['url'])) {
137 $url = $this->parameters['url'];
139 // thumb, small, medium and large.
140 if (substr($url, -6) == ':micro') {
141 $size = ProxyUtils::PIXEL_MICRO;
142 $sizetype = ':micro';
143 $url = substr($url, 0, -6);
144 } elseif (substr($url, -6) == ':thumb') {
145 $size = ProxyUtils::PIXEL_THUMB;
146 $sizetype = ':thumb';
147 $url = substr($url, 0, -6);
148 } elseif (substr($url, -6) == ':small') {
149 $size = ProxyUtils::PIXEL_SMALL;
150 $url = substr($url, 0, -6);
151 $sizetype = ':small';
152 } elseif (substr($url, -7) == ':medium') {
153 $size = ProxyUtils::PIXEL_MEDIUM;
154 $url = substr($url, 0, -7);
155 $sizetype = ':medium';
156 } elseif (substr($url, -6) == ':large') {
157 $size = ProxyUtils::PIXEL_LARGE;
158 $url = substr($url, 0, -6);
159 $sizetype = ':large';
162 $pos = strrpos($url, '=.');
164 $url = substr($url, 0, $pos + 1);
167 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
169 $url = base64_decode(strtr($url, '-_', '+/'), true);
171 $url = $_REQUEST['url'] ?? '';
177 'sizetype' => $sizetype,
182 * In case of an error just stop. We don't return content to avoid caching problems
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
186 private static function responseError()
188 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
192 * Output the image with cache headers
196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
198 private static function responseImageHttpCache(Image $img)
200 if (is_null($img) || !$img->isValid()) {
201 Logger::notice('The cached image is invalid');
202 self::responseError();
205 header('Content-type: ' . $img->getType());
206 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
207 header('Etag: "' . md5($img->asString()) . '"');
208 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
209 header('Cache-Control: max-age=31536000');
210 echo $img->asString();