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;
9 use Friendica\BaseModule;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Photo;
15 use Friendica\Object\Image;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Network;
18 use Friendica\Util\Proxy as ProxyUtils;
24 * /proxy/[sub1/[sub2/]]<base64url image url>[.ext][:size]
25 * /proxy?url=<image url>
27 class Proxy extends BaseModule
31 * @brief Initializer method for this class.
33 * Sets application instance and checks if /proxy/ path is writable.
35 * @param \Friendica\App $app Application instance
37 public static function init()
39 // Set application instance here
43 * Pictures are stored in one of the following ways:
45 * 1. If a folder "proxy" exists and is writeable, then use this for caching
46 * 2. If a cache path is defined, use this
47 * 3. If everything else failed, cache into the database
49 * Question: Do we really need these three methods?
51 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
52 header('HTTP/1.1 304 Not Modified');
53 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
54 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
55 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
56 header('Cache-Control: max-age=31536000');
58 if (function_exists('header_remove')) {
59 header_remove('Last-Modified');
60 header_remove('Expires');
61 header_remove('Cache-Control');
68 if (function_exists('header_remove')) {
69 header_remove('Pragma');
70 header_remove('pragma');
73 $direct_cache = self::setupDirectCache();
75 $request = self::getRequestInfo();
77 if (empty($request['url'])) {
78 System::httpExit(400, ['title' => L10n::t('Bad Request.')]);
81 // Webserver already tried direct cache...
83 // Try to use filecache;
84 $cachefile = self::responseFromCache($request);
86 // Try to use photo from db
87 self::responseFromDB($request);
91 // If script is here, the requested url has never cached before.
92 // Let's fetch it, scale it if required, then save it in cache.
96 // It shouldn't happen but it does - spaces in URL
97 $request['url'] = str_replace(' ', '+', $request['url']);
99 $fetchResult = Network::fetchUrlFull($request['url'], true, $redirects, 10);
100 $img_str = $fetchResult->getBody();
102 $tempfile = tempnam(get_temppath(), 'cache');
103 file_put_contents($tempfile, $img_str);
104 $mime = mime_content_type($tempfile);
107 // If there is an error then return a blank image
108 if ((substr($fetchResult->getReturnCode(), 0, 1) == '4') || (!$img_str)) {
109 self::responseError($request);
113 $image = new Image($img_str, $mime);
114 if (!$image->isValid()) {
115 self::responseError($request);
119 // Store original image
121 // direct cache , store under ./proxy/
122 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true), $image->asString());
123 } elseif($cachefile !== '') {
125 file_put_contents($cachefile, $image->asString());
128 Photo::store($image, 0, 0, $request['urlhash'], $request['url'], '', 100);
132 // reduce quality - if it isn't a GIF
133 if ($image->getType() != 'image/gif') {
134 $image->scaleDown($request['size']);
138 // Store scaled image
139 if ($direct_cache && $request['sizetype'] != '') {
140 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($request['url'], true) . $request['sizetype'], $image->asString());
143 self::responseImageHttpCache($image);
149 * @brief Build info about requested image to be proxied
153 * 'url' => requested url,
154 * 'urlhash' => sha1 has of the url prefixed with 'pic:',
155 * 'size' => requested image size (int)
156 * 'sizetype' => requested image size (string): ':micro', ':thumb', ':small', ':medium', ':large'
159 private static function getRequestInfo()
167 // Look for filename in the arguments
168 if (($a->argc > 1) && !isset($_REQUEST['url'])) {
169 if (isset($a->argv[3])) {
171 } elseif (isset($a->argv[2])) {
177 /// @TODO: Why? And what about $url in this case?
178 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
182 // thumb, small, medium and large.
183 if (substr($url, -6) == ':micro') {
185 $sizetype = ':micro';
186 $url = substr($url, 0, -6);
187 } elseif (substr($url, -6) == ':thumb') {
189 $sizetype = ':thumb';
190 $url = substr($url, 0, -6);
191 } elseif (substr($url, -6) == ':small') {
193 $url = substr($url, 0, -6);
194 $sizetype = ':small';
195 } elseif (substr($url, -7) == ':medium') {
197 $url = substr($url, 0, -7);
198 $sizetype = ':medium';
199 } elseif (substr($url, -6) == ':large') {
201 $url = substr($url, 0, -6);
202 $sizetype = ':large';
205 $pos = strrpos($url, '=.');
207 $url = substr($url, 0, $pos + 1);
210 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
212 $url = base64_decode(strtr($url, '-_', '+/'), true);
215 $url = defaults($_REQUEST, 'url', '');
220 'urlhash' => 'pic:' . sha1($url),
222 'sizetype' => $sizetype,
228 * @brief setup ./proxy folder for direct cache
230 * @return bool False if direct cache can't be used.
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 * @brief 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
260 private static function responseFromCache(&$request)
262 $cachefile = get_cachefile(hash('md5', $request['url']));
263 if ($cachefile != '' && file_exists($cachefile)) {
264 $img = new Image(file_get_contents($cachefile), mime_content_type($cachefile));
265 self::responseImageHttpCache($img);
272 * @brief Try to reply with image in database
274 * @param array $request Array from getRequestInfo
276 * If the image exists in database, then script ends here and this function will never returns
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() {
294 header('Content-type: ' . $img->getType());
295 echo file_get_contents('images/blank.png');
300 * @brief Output the image with cache headers
302 * @param Image $image
304 private static function responseImageHttpCache(Image $img)
306 if (is_null($img) || !$img->isValid()) {
307 self::responseError();
310 header('Content-type: ' . $img->getType());
311 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
312 header('Etag: "' . md5($img->asString()) . '"');
313 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
314 header('Cache-Control: max-age=31536000');
315 echo $img->asString();