3 * @copyright Copyright (C) 2010-2021, 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;
27 use Friendica\Model\Photo;
28 use Friendica\Object\Image;
29 use Friendica\Util\HTTPSignature;
30 use Friendica\Util\Proxy as ProxyUtils;
36 * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
37 * /proxy?url=<image url>
39 class Proxy extends BaseModule
43 * Initializer method for this class.
45 * Sets application instance and checks if /proxy/ path is writable.
48 public static function init(array $parameters = [])
50 // Set application instance here
54 * Pictures are stored in one of the following ways:
56 * 1. If a folder "proxy" exists and is writeable, then use this for caching
57 * 2. If a cache path is defined, use this
58 * 3. If everything else failed, cache into the database
60 * Question: Do we really need these three methods?
62 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
63 header('HTTP/1.1 304 Not Modified');
64 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
65 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
66 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
67 header('Cache-Control: max-age=31536000');
69 if (function_exists('header_remove')) {
70 header_remove('Last-Modified');
71 header_remove('Expires');
72 header_remove('Cache-Control');
79 if (function_exists('header_remove')) {
80 header_remove('Pragma');
81 header_remove('pragma');
84 $direct_cache = self::setupDirectCache();
86 $request = self::getRequestInfo();
88 if (empty($request['url'])) {
89 throw new \Friendica\Network\HTTPException\BadRequestException();
92 // Webserver already tried direct cache...
94 // Try to use filecache;
95 $cachefile = self::responseFromCache($request);
97 // Try to use photo from db
98 self::responseFromDB($request);
101 // If script is here, the requested url has never cached before.
102 // Let's fetch it, scale it if required, then save it in cache.
105 // It shouldn't happen but it does - spaces in URL
106 $request['url'] = str_replace(' ', '+', $request['url']);
107 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), ['timeout' => 10]);
108 $img_str = $fetchResult->getBody();
110 // If there is an error then return a blank image
111 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
112 Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
113 self::responseError();
117 $tempfile = tempnam(get_temppath(), 'cache');
118 file_put_contents($tempfile, $img_str);
119 $mime = mime_content_type($tempfile);
122 $image = new Image($img_str, $mime);
123 if (!$image->isValid()) {
124 Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
125 self::responseError();
129 $basepath = $a->getBasePath();
130 $filepermission = DI::config()->get('system', 'proxy_file_chmod');
132 // Store original image
134 // direct cache , store under ./proxy/
135 $filename = $basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true);
136 file_put_contents($filename, $image->asString());
137 if (!empty($filepermission)) {
138 chmod($filename, $filepermission);
140 } elseif($cachefile !== '') {
142 file_put_contents($cachefile, $image->asString());
145 Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
149 // reduce quality - if it isn't a GIF
150 if ($image->getType() != 'image/gif') {
151 $image->scaleDown($request['size']);
155 // Store scaled image
156 if ($direct_cache && $request['sizetype'] != '') {
157 $filename = $basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'];
158 file_put_contents($filename, $image->asString());
159 if (!empty($filepermission)) {
160 chmod($filename, $filepermission);
164 self::responseImageHttpCache($image);
170 * Build info about requested image to be proxied
174 * 'url' => requested url,
175 * 'urlhash' => sha1 has of the url prefixed with 'pic:',
176 * 'size' => requested image size (int)
177 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
181 private static function getRequestInfo()
187 // Look for filename in the arguments
188 // @TODO: Replace with parameter from router
189 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
190 if (isset($a->argv[3])) {
192 } elseif (isset($a->argv[2])) {
198 /// @TODO: Why? And what about $url in this case?
199 /// @TODO: Replace with parameter from router
200 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
204 // thumb, small, medium and large.
205 if (substr($url, -6) == ':micro') {
207 $sizetype = ':micro';
208 $url = substr($url, 0, -6);
209 } elseif (substr($url, -6) == ':thumb') {
211 $sizetype = ':thumb';
212 $url = substr($url, 0, -6);
213 } elseif (substr($url, -6) == ':small') {
215 $url = substr($url, 0, -6);
216 $sizetype = ':small';
217 } elseif (substr($url, -7) == ':medium') {
219 $url = substr($url, 0, -7);
220 $sizetype = ':medium';
221 } elseif (substr($url, -6) == ':large') {
223 $url = substr($url, 0, -6);
224 $sizetype = ':large';
227 $pos = strrpos($url, '=.');
229 $url = substr($url, 0, $pos + 1);
232 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
234 $url = base64_decode(strtr($url, '-_', '+/'), true);
237 $url = $_REQUEST['url'] ?? '';
242 'urlhash' => 'pic:' . sha1($url),
244 'sizetype' => $sizetype,
250 * setup ./proxy folder for direct cache
252 * @return bool False if direct cache can't be used.
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 private static function setupDirectCache()
258 $basepath = $a->getBasePath();
260 // If the cache path isn't there, try to create it
261 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
262 mkdir($basepath . '/proxy');
265 // Checking if caching into a folder in the webroot is activated and working
266 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
267 // we don't use direct cache if image url is passed in args and not in querystring
268 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
270 return $direct_cache;
275 * Try to reply with image in cachefile
277 * @param array $request Array from getRequestInfo
279 * @return string Cache file name, empty string if cache is not enabled.
281 * If cachefile exists, script ends here and this function will never returns
282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
283 * @throws \ImagickException
285 private static function responseFromCache(&$request)
287 $cachefile = get_cachefile(hash('md5', $request['url']));
288 if ($cachefile != '' && file_exists($cachefile)) {
289 $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
290 self::responseImageHttpCache($img);
297 * Try to reply with image in database
299 * @param array $request Array from getRequestInfo
301 * If the image exists in database, then script ends here and this function will never returns
302 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
303 * @throws \ImagickException
305 private static function responseFromDB(&$request)
307 $photo = Photo::getPhoto($request['urlhash']);
309 if ($photo !== false) {
310 $img = Photo::getImageForPhoto($photo);
311 self::responseImageHttpCache($img);
317 * In case of an error just stop. We don't return content to avoid caching problems
319 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 private static function responseError()
323 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
327 * Output the image with cache headers
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
332 private static function responseImageHttpCache(Image $img)
334 if (is_null($img) || !$img->isValid()) {
335 Logger::info('The cached image is invalid');
336 self::responseError();
339 header('Content-type: ' . $img->getType());
340 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
341 header('Etag: "' . md5($img->asString()) . '"');
342 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
343 header('Cache-Control: max-age=31536000');
344 echo $img->asString();