3 * @file src/Module/Proxy.php
4 * Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
6 namespace Friendica\Module;
8 use Friendica\BaseModule;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Core\Logger;
13 use Friendica\Model\Photo;
14 use Friendica\Object\Image;
15 use Friendica\Util\HTTPSignature;
16 use Friendica\Util\Proxy as ProxyUtils;
22 * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
23 * /proxy?url=<image url>
25 class Proxy extends BaseModule
29 * Initializer method for this class.
31 * Sets application instance and checks if /proxy/ path is writable.
34 public static function init(array $parameters = [])
36 // Set application instance here
40 * Pictures are stored in one of the following ways:
42 * 1. If a folder "proxy" exists and is writeable, then use this for caching
43 * 2. If a cache path is defined, use this
44 * 3. If everything else failed, cache into the database
46 * Question: Do we really need these three methods?
48 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
49 header('HTTP/1.1 304 Not Modified');
50 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
51 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
52 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
53 header('Cache-Control: max-age=31536000');
55 if (function_exists('header_remove')) {
56 header_remove('Last-Modified');
57 header_remove('Expires');
58 header_remove('Cache-Control');
65 if (function_exists('header_remove')) {
66 header_remove('Pragma');
67 header_remove('pragma');
70 $direct_cache = self::setupDirectCache();
72 $request = self::getRequestInfo();
74 if (empty($request['url'])) {
75 throw new \Friendica\Network\HTTPException\BadRequestException();
78 // Webserver already tried direct cache...
80 // Try to use filecache;
81 $cachefile = self::responseFromCache($request);
83 // Try to use photo from db
84 self::responseFromDB($request);
87 // If script is here, the requested url has never cached before.
88 // Let's fetch it, scale it if required, then save it in cache.
91 // It shouldn't happen but it does - spaces in URL
92 $request['url'] = str_replace(' ', '+', $request['url']);
93 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), true, ['timeout' => 10]);
94 $img_str = $fetchResult->getBody();
96 // If there is an error then return a blank image
97 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
98 Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
99 self::responseError();
103 $tempfile = tempnam(get_temppath(), 'cache');
104 file_put_contents($tempfile, $img_str);
105 $mime = mime_content_type($tempfile);
108 $image = new Image($img_str, $mime);
109 if (!$image->isValid()) {
110 Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
111 self::responseError();
115 $basepath = $a->getBasePath();
117 // Store original image
119 // direct cache , store under ./proxy/
120 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
121 } elseif($cachefile !== '') {
123 file_put_contents($cachefile, $image->asString());
126 Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
130 // reduce quality - if it isn't a GIF
131 if ($image->getType() != 'image/gif') {
132 $image->scaleDown($request['size']);
136 // Store scaled image
137 if ($direct_cache && $request['sizetype'] != '') {
138 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
141 self::responseImageHttpCache($image);
147 * Build info about requested image to be proxied
151 * 'url' => requested url,
152 * 'urlhash' => sha1 has of the url prefixed with 'pic:',
153 * 'size' => requested image size (int)
154 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
158 private static function getRequestInfo()
164 // Look for filename in the arguments
165 // @TODO: Replace with parameter from router
166 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
167 if (isset($a->argv[3])) {
169 } elseif (isset($a->argv[2])) {
175 /// @TODO: Why? And what about $url in this case?
176 /// @TODO: Replace with parameter from router
177 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
181 // thumb, small, medium and large.
182 if (substr($url, -6) == ':micro') {
184 $sizetype = ':micro';
185 $url = substr($url, 0, -6);
186 } elseif (substr($url, -6) == ':thumb') {
188 $sizetype = ':thumb';
189 $url = substr($url, 0, -6);
190 } elseif (substr($url, -6) == ':small') {
192 $url = substr($url, 0, -6);
193 $sizetype = ':small';
194 } elseif (substr($url, -7) == ':medium') {
196 $url = substr($url, 0, -7);
197 $sizetype = ':medium';
198 } elseif (substr($url, -6) == ':large') {
200 $url = substr($url, 0, -6);
201 $sizetype = ':large';
204 $pos = strrpos($url, '=.');
206 $url = substr($url, 0, $pos + 1);
209 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
211 $url = base64_decode(strtr($url, '-_', '+/'), true);
214 $url = $_REQUEST['url'] ?? '';
219 'urlhash' => 'pic:' . sha1($url),
221 'sizetype' => $sizetype,
227 * setup ./proxy folder for direct cache
229 * @return bool False if direct cache can't be used.
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232 private static function setupDirectCache()
235 $basepath = $a->getBasePath();
237 // If the cache path isn't there, try to create it
238 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
239 mkdir($basepath . '/proxy');
242 // Checking if caching into a folder in the webroot is activated and working
243 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
244 // we don't use direct cache if image url is passed in args and not in querystring
245 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
247 return $direct_cache;
252 * Try to reply with image in cachefile
254 * @param array $request Array from getRequestInfo
256 * @return string Cache file name, empty string if cache is not enabled.
258 * If cachefile exists, script ends here and this function will never returns
259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 * @throws \ImagickException
262 private static function responseFromCache(&$request)
264 $cachefile = get_cachefile(hash('md5', $request['url']));
265 if ($cachefile != '' && file_exists($cachefile)) {
266 $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
267 self::responseImageHttpCache($img);
274 * Try to reply with image in database
276 * @param array $request Array from getRequestInfo
278 * If the image exists in database, then script ends here and this function will never returns
279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
280 * @throws \ImagickException
282 private static function responseFromDB(&$request)
284 $photo = Photo::getPhoto($request['urlhash']);
286 if ($photo !== false) {
287 $img = Photo::getImageForPhoto($photo);
288 self::responseImageHttpCache($img);
294 * In case of an error just stop. We don't return content to avoid caching problems
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
298 private static function responseError()
300 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
304 * Output the image with cache headers
307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 private static function responseImageHttpCache(Image $img)
311 if (is_null($img) || !$img->isValid()) {
312 Logger::info('The cached image is invalid');
313 self::responseError();
316 header('Content-type: ' . $img->getType());
317 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
318 header('Etag: "' . md5($img->asString()) . '"');
319 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
320 header('Cache-Control: max-age=31536000');
321 echo $img->asString();