3 * @file src/Module/Proxy.php
4 * @brief 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;
12 use Friendica\Model\Photo;
13 use Friendica\Object\Image;
14 use Friendica\Util\HTTPSignature;
15 use Friendica\Util\Proxy as ProxyUtils;
21 * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
22 * /proxy?url=<image url>
24 class Proxy extends BaseModule
28 * @brief Initializer method for this class.
30 * Sets application instance and checks if /proxy/ path is writable.
33 public static function init(array $parameters = [])
35 // Set application instance here
39 * Pictures are stored in one of the following ways:
41 * 1. If a folder "proxy" exists and is writeable, then use this for caching
42 * 2. If a cache path is defined, use this
43 * 3. If everything else failed, cache into the database
45 * Question: Do we really need these three methods?
47 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
48 header('HTTP/1.1 304 Not Modified');
49 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
50 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
51 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
52 header('Cache-Control: max-age=31536000');
54 if (function_exists('header_remove')) {
55 header_remove('Last-Modified');
56 header_remove('Expires');
57 header_remove('Cache-Control');
64 if (function_exists('header_remove')) {
65 header_remove('Pragma');
66 header_remove('pragma');
69 $direct_cache = self::setupDirectCache();
71 $request = self::getRequestInfo();
73 if (empty($request['url'])) {
74 throw new \Friendica\Network\HTTPException\BadRequestException();
77 // Webserver already tried direct cache...
79 // Try to use filecache;
80 $cachefile = self::responseFromCache($request);
82 // Try to use photo from db
83 self::responseFromDB($request);
86 // If script is here, the requested url has never cached before.
87 // Let's fetch it, scale it if required, then save it in cache.
90 // It shouldn't happen but it does - spaces in URL
91 $request['url'] = str_replace(' ', '+', $request['url']);
92 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), true, ['timeout' => 10]);
93 $img_str = $fetchResult->getBody();
95 // If there is an error then return a blank image
96 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || empty($img_str)) {
97 Logger::info('Error fetching image', ['image' => $request['url'], 'return' => $fetchResult->getReturnCode(), 'empty' => empty($img_str)]);
98 self::responseError();
102 $tempfile = tempnam(get_temppath(), 'cache');
103 file_put_contents($tempfile, $img_str);
104 $mime = mime_content_type($tempfile);
107 $image = new Image($img_str, $mime);
108 if (!$image->isValid()) {
109 Logger::info('The image is invalid', ['image' => $request['url'], 'mime' => $mime]);
110 self::responseError();
114 $basepath = $a->getBasePath();
116 // Store original image
118 // direct cache , store under ./proxy/
119 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
120 } elseif($cachefile !== '') {
122 file_put_contents($cachefile, $image->asString());
125 Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
129 // reduce quality - if it isn't a GIF
130 if ($image->getType() != 'image/gif') {
131 $image->scaleDown($request['size']);
135 // Store scaled image
136 if ($direct_cache && $request['sizetype'] != '') {
137 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
140 self::responseImageHttpCache($image);
146 * @brief Build info about requested image to be proxied
150 * 'url' => requested url,
151 * 'urlhash' => sha1 has of the url prefixed with 'pic:',
152 * 'size' => requested image size (int)
153 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
157 private static function getRequestInfo()
163 // Look for filename in the arguments
164 // @TODO: Replace with parameter from router
165 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
166 if (isset($a->argv[3])) {
168 } elseif (isset($a->argv[2])) {
174 /// @TODO: Why? And what about $url in this case?
175 /// @TODO: Replace with parameter from router
176 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
180 // thumb, small, medium and large.
181 if (substr($url, -6) == ':micro') {
183 $sizetype = ':micro';
184 $url = substr($url, 0, -6);
185 } elseif (substr($url, -6) == ':thumb') {
187 $sizetype = ':thumb';
188 $url = substr($url, 0, -6);
189 } elseif (substr($url, -6) == ':small') {
191 $url = substr($url, 0, -6);
192 $sizetype = ':small';
193 } elseif (substr($url, -7) == ':medium') {
195 $url = substr($url, 0, -7);
196 $sizetype = ':medium';
197 } elseif (substr($url, -6) == ':large') {
199 $url = substr($url, 0, -6);
200 $sizetype = ':large';
203 $pos = strrpos($url, '=.');
205 $url = substr($url, 0, $pos + 1);
208 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
210 $url = base64_decode(strtr($url, '-_', '+/'), true);
213 $url = $_REQUEST['url'] ?? '';
218 'urlhash' => 'pic:' . sha1($url),
220 'sizetype' => $sizetype,
226 * @brief setup ./proxy folder for direct cache
228 * @return bool False if direct cache can't be used.
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 private static function setupDirectCache()
234 $basepath = $a->getBasePath();
236 // If the cache path isn't there, try to create it
237 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
238 mkdir($basepath . '/proxy');
241 // Checking if caching into a folder in the webroot is activated and working
242 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
243 // we don't use direct cache if image url is passed in args and not in querystring
244 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
246 return $direct_cache;
251 * @brief Try to reply with image in cachefile
253 * @param array $request Array from getRequestInfo
255 * @return string Cache file name, empty string if cache is not enabled.
257 * If cachefile exists, script ends here and this function will never returns
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259 * @throws \ImagickException
261 private static function responseFromCache(&$request)
263 $cachefile = get_cachefile(hash('md5', $request['url']));
264 if ($cachefile != '' && file_exists($cachefile)) {
265 $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
266 self::responseImageHttpCache($img);
273 * @brief Try to reply with image in database
275 * @param array $request Array from getRequestInfo
277 * If the image exists in database, then script ends here and this function will never returns
278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 * @throws \ImagickException
281 private static function responseFromDB(&$request)
283 $photo = Photo::getPhoto($request['urlhash']);
285 if ($photo !== false) {
286 $img = Photo::getImageForPhoto($photo);
287 self::responseImageHttpCache($img);
293 * In case of an error just stop. We don't return content to avoid caching problems
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 private static function responseError()
299 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
303 * @brief Output the image with cache headers
306 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
308 private static function responseImageHttpCache(Image $img)
310 if (is_null($img) || !$img->isValid()) {
311 Logger::info('The cached image is invalid');
312 self::responseError();
315 header('Content-type: ' . $img->getType());
316 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
317 header('Etag: "' . md5($img->asString()) . '"');
318 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
319 header('Cache-Control: max-age=31536000');
320 echo $img->asString();