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\Model\Photo;
12 use Friendica\Object\Image;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Util\Proxy as ProxyUtils;
20 * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
21 * /proxy?url=<image url>
23 class Proxy extends BaseModule
27 * @brief Initializer method for this class.
29 * Sets application instance and checks if /proxy/ path is writable.
32 public static function init()
34 // Set application instance here
38 * Pictures are stored in one of the following ways:
40 * 1. If a folder "proxy" exists and is writeable, then use this for caching
41 * 2. If a cache path is defined, use this
42 * 3. If everything else failed, cache into the database
44 * Question: Do we really need these three methods?
46 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
47 header('HTTP/1.1 304 Not Modified');
48 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
49 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
50 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
51 header('Cache-Control: max-age=31536000');
53 if (function_exists('header_remove')) {
54 header_remove('Last-Modified');
55 header_remove('Expires');
56 header_remove('Cache-Control');
63 if (function_exists('header_remove')) {
64 header_remove('Pragma');
65 header_remove('pragma');
68 $direct_cache = self::setupDirectCache();
70 $request = self::getRequestInfo();
72 if (empty($request['url'])) {
73 System::httpExit(400, ['title' => L10n::t('Bad Request.')]);
76 // Webserver already tried direct cache...
78 // Try to use filecache;
79 $cachefile = self::responseFromCache($request);
81 // Try to use photo from db
82 self::responseFromDB($request);
85 // If script is here, the requested url has never cached before.
86 // Let's fetch it, scale it if required, then save it in cache.
89 // It shouldn't happen but it does - spaces in URL
90 $request['url'] = str_replace(' ', '+', $request['url']);
91 $fetchResult = HTTPSignature::fetchRaw($request['url'], local_user(), true, ['timeout' => 10]);
92 $img_str = $fetchResult->getBody();
94 // If there is an error then return a blank image
95 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || (!$img_str)) {
96 self::responseError();
100 $tempfile = tempnam(get_temppath(), 'cache');
101 file_put_contents($tempfile, $img_str);
102 $mime = mime_content_type($tempfile);
105 $image = new Image($img_str, $mime);
106 if (!$image->isValid()) {
107 self::responseError();
111 $basepath = $a->getBasePath();
113 // Store original image
115 // direct cache , store under ./proxy/
116 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
117 } elseif($cachefile !== '') {
119 file_put_contents($cachefile, $image->asString());
122 Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
126 // reduce quality - if it isn't a GIF
127 if ($image->getType() != 'image/gif') {
128 $image->scaleDown($request['size']);
132 // Store scaled image
133 if ($direct_cache && $request['sizetype'] != '') {
134 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
137 self::responseImageHttpCache($image);
143 * @brief Build info about requested image to be proxied
147 * 'url' => requested url,
148 * 'urlhash' => sha1 has of the url prefixed with 'pic:',
149 * 'size' => requested image size (int)
150 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
154 private static function getRequestInfo()
160 // Look for filename in the arguments
161 // @TODO: Replace with parameter from router
162 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
163 if (isset($a->argv[3])) {
165 } elseif (isset($a->argv[2])) {
171 /// @TODO: Why? And what about $url in this case?
172 /// @TODO: Replace with parameter from router
173 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
177 // thumb, small, medium and large.
178 if (substr($url, -6) == ':micro') {
180 $sizetype = ':micro';
181 $url = substr($url, 0, -6);
182 } elseif (substr($url, -6) == ':thumb') {
184 $sizetype = ':thumb';
185 $url = substr($url, 0, -6);
186 } elseif (substr($url, -6) == ':small') {
188 $url = substr($url, 0, -6);
189 $sizetype = ':small';
190 } elseif (substr($url, -7) == ':medium') {
192 $url = substr($url, 0, -7);
193 $sizetype = ':medium';
194 } elseif (substr($url, -6) == ':large') {
196 $url = substr($url, 0, -6);
197 $sizetype = ':large';
200 $pos = strrpos($url, '=.');
202 $url = substr($url, 0, $pos + 1);
205 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
207 $url = base64_decode(strtr($url, '-_', '+/'), true);
210 $url = defaults($_REQUEST, 'url', '');
215 'urlhash' => 'pic:' . sha1($url),
217 'sizetype' => $sizetype,
223 * @brief setup ./proxy folder for direct cache
225 * @return bool False if direct cache can't be used.
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
228 private static function setupDirectCache()
231 $basepath = $a->getBasePath();
233 // If the cache path isn't there, try to create it
234 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
235 mkdir($basepath . '/proxy');
238 // Checking if caching into a folder in the webroot is activated and working
239 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
240 // we don't use direct cache if image url is passed in args and not in querystring
241 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
243 return $direct_cache;
248 * @brief Try to reply with image in cachefile
250 * @param array $request Array from getRequestInfo
252 * @return string Cache file name, empty string if cache is not enabled.
254 * If cachefile exists, script ends here and this function will never returns
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 private static function responseFromCache(&$request)
260 $cachefile = get_cachefile(hash('md5', $request['url']));
261 if ($cachefile != '' && file_exists($cachefile)) {
262 $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
263 self::responseImageHttpCache($img);
270 * @brief Try to reply with image in database
272 * @param array $request Array from getRequestInfo
274 * If the image exists in database, then script ends here and this function will never returns
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 private static function responseFromDB(&$request)
280 $photo = Photo::getPhoto($request['urlhash']);
282 if ($photo !== false) {
283 $img = Photo::getImageForPhoto($photo);
284 self::responseImageHttpCache($img);
290 * @brief Output a blank image, without cache headers, in case of errors
293 private static function responseError()
295 header('Content-type: image/png');
296 echo file_get_contents('images/blank.png');
301 * @brief Output the image with cache headers
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306 private static function responseImageHttpCache(Image $img)
308 if (is_null($img) || !$img->isValid()) {
309 self::responseError();
312 header('Content-type: ' . $img->getType());
313 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
314 header('Etag: "' . md5($img->asString()) . '"');
315 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
316 header('Cache-Control: max-age=31536000');
317 echo $img->asString();