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;
15 use Friendica\Core\Logger;
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()
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 System::httpExit(400, ['title' => L10n::t('Bad Request.')]);
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') || (!$img_str)) {
97 self::responseError();
101 $tempfile = tempnam(get_temppath(), 'cache');
102 file_put_contents($tempfile, $img_str);
103 $mime = mime_content_type($tempfile);
106 $image = new Image($img_str, $mime);
107 if (!$image->isValid()) {
108 self::responseError();
112 $basepath = $a->getBasePath();
114 // Store original image
116 // direct cache , store under ./proxy/
117 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
118 } elseif($cachefile !== '') {
120 file_put_contents($cachefile, $image->asString());
123 Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
127 // reduce quality - if it isn't a GIF
128 if ($image->getType() != 'image/gif') {
129 $image->scaleDown($request['size']);
133 // Store scaled image
134 if ($direct_cache && $request['sizetype'] != '') {
135 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
138 self::responseImageHttpCache($image);
144 * @brief Build info about requested image to be proxied
148 * 'url' => requested url,
149 * 'urlhash' => sha1 has of the url prefixed with 'pic:',
150 * 'size' => requested image size (int)
151 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
155 private static function getRequestInfo()
161 // Look for filename in the arguments
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 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
176 // thumb, small, medium and large.
177 if (substr($url, -6) == ':micro') {
179 $sizetype = ':micro';
180 $url = substr($url, 0, -6);
181 } elseif (substr($url, -6) == ':thumb') {
183 $sizetype = ':thumb';
184 $url = substr($url, 0, -6);
185 } elseif (substr($url, -6) == ':small') {
187 $url = substr($url, 0, -6);
188 $sizetype = ':small';
189 } elseif (substr($url, -7) == ':medium') {
191 $url = substr($url, 0, -7);
192 $sizetype = ':medium';
193 } elseif (substr($url, -6) == ':large') {
195 $url = substr($url, 0, -6);
196 $sizetype = ':large';
199 $pos = strrpos($url, '=.');
201 $url = substr($url, 0, $pos + 1);
204 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
206 $url = base64_decode(strtr($url, '-_', '+/'), true);
209 $url = defaults($_REQUEST, 'url', '');
214 'urlhash' => 'pic:' . sha1($url),
216 'sizetype' => $sizetype,
222 * @brief setup ./proxy folder for direct cache
224 * @return bool False if direct cache can't be used.
225 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 private static function setupDirectCache()
230 $basepath = $a->getBasePath();
232 // If the cache path isn't there, try to create it
233 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
234 mkdir($basepath . '/proxy');
237 // Checking if caching into a folder in the webroot is activated and working
238 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
239 // we don't use direct cache if image url is passed in args and not in querystring
240 $direct_cache = $direct_cache && ($a->argc > 1) && !isset($_REQUEST['url']);
242 return $direct_cache;
247 * @brief Try to reply with image in cachefile
249 * @param array $request Array from getRequestInfo
251 * @return string Cache file name, empty string if cache is not enabled.
253 * If cachefile exists, script ends here and this function will never returns
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 private static function responseFromCache(&$request)
259 $cachefile = get_cachefile(hash('md5', $request['url']));
260 if ($cachefile != '' && file_exists($cachefile)) {
261 $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
262 self::responseImageHttpCache($img);
269 * @brief Try to reply with image in database
271 * @param array $request Array from getRequestInfo
273 * If the image exists in database, then script ends here and this function will never returns
274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275 * @throws \ImagickException
277 private static function responseFromDB(&$request)
279 $photo = Photo::getPhoto($request['urlhash']);
281 if ($photo !== false) {
282 $img = Photo::getImageForPhoto($photo);
283 self::responseImageHttpCache($img);
289 * @brief Output a blank image, without cache headers, in case of errors
292 private static function responseError()
294 header('Content-type: image/png');
295 echo file_get_contents('images/blank.png');
300 * @brief Output the image with cache headers
303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 private static function responseImageHttpCache(Image $img)
307 if (is_null($img) || !$img->isValid()) {
308 self::responseError();
311 header('Content-type: ' . $img->getType());
312 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
313 header('Etag: "' . md5($img->asString()) . '"');
314 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
315 header('Cache-Control: max-age=31536000');
316 echo $img->asString();