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\System;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Photo;
14 use Friendica\Object\Image;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Network;
17 use Friendica\Util\Proxy as ProxyUtils;
19 require_once 'include/security.php';
24 class Proxy extends BaseModule
28 * @brief Initializer method for this class.
30 * Sets application instance and checks if /proxy/ path is writable.
32 * @param \Friendica\App $app Application instance
34 public static function init()
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');
73 $basepath = $a->get_basepath();
75 // If the cache path isn't there, try to create it
76 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
77 mkdir($basepath . '/proxy');
80 // Checking if caching into a folder in the webroot is activated and working
81 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
83 // Look for filename in the arguments
84 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
85 if (isset($a->argv[3])) {
87 } elseif (isset($a->argv[2])) {
93 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
97 // thumb, small, medium and large.
98 if (substr($url, -6) == ':micro') {
100 $sizetype = ':micro';
101 $url = substr($url, 0, -6);
102 } elseif (substr($url, -6) == ':thumb') {
104 $sizetype = ':thumb';
105 $url = substr($url, 0, -6);
106 } elseif (substr($url, -6) == ':small') {
108 $url = substr($url, 0, -6);
109 $sizetype = ':small';
110 } elseif (substr($url, -7) == ':medium') {
112 $url = substr($url, 0, -7);
113 $sizetype = ':medium';
114 } elseif (substr($url, -6) == ':large') {
116 $url = substr($url, 0, -6);
117 $sizetype = ':large';
120 $pos = strrpos($url, '=.');
122 $url = substr($url, 0, $pos + 1);
125 $url = str_replace(['.jpg', '.jpeg', '.gif', '.png'], ['','','',''], $url);
127 $url = base64_decode(strtr($url, '-_', '+/'), true);
130 $_REQUEST['url'] = $url;
133 $direct_cache = false;
136 if (!$direct_cache) {
137 $urlhash = 'pic:' . sha1($_REQUEST['url']);
139 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
140 if ($cachefile != '' && file_exists($cachefile)) {
141 $img_str = file_get_contents($cachefile);
142 $mime = mime_content_type($cachefile);
144 header('Content-type: ' . $mime);
145 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
146 header('Etag: "' . md5($img_str) . '"');
147 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
148 header('Cache-Control: max-age=31536000');
150 // reduce quality - if it isn't a GIF
151 if ($mime != 'image/gif') {
152 $image = new Image($img_str, $mime);
154 if ($image->isValid()) {
155 $img_str = $image->asString();
169 if (!$direct_cache && ($cachefile == '')) {
170 $photo = DBA::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
172 if (DBA::isResult($photo)) {
173 $img_str = $photo['data'];
174 $mime = $photo['desc'];
177 $mime = 'image/jpeg';
182 if (!DBA::isResult($photo)) {
183 // It shouldn't happen but it does - spaces in URL
184 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
186 $img_str = Network::fetchUrl($_REQUEST['url'], true, $redirects, 10);
188 $tempfile = tempnam(get_temppath(), 'cache');
189 file_put_contents($tempfile, $img_str);
190 $mime = mime_content_type($tempfile);
193 // If there is an error then return a blank image
194 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
195 $img_str = file_get_contents('images/blank.png');
197 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
199 $image = new Image($img_str, 'image/png');
201 if ($image->isValid()) {
202 $image->scaleDown(10);
203 $img_str = $image->asString();
205 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
206 $image = @imagecreatefromstring($img_str);
208 if ($image === FALSE) {
212 $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => System::createGUID(), 'resource-id' => $urlhash, 'created' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utcNow(),
213 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
214 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
215 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime];
216 DBA::insert('photo', $fields);
218 $image = new Image($img_str, $mime);
220 if ($image->isValid() && !$direct_cache && ($cachefile == '')) {
221 Photo::store($image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
226 $img_str_orig = $img_str;
228 // reduce quality - if it isn't a GIF
229 if ($mime != 'image/gif') {
230 $image = new Image($img_str, $mime);
232 if ($image->isValid()) {
233 $image->scaleDown($size);
234 $img_str = $image->asString();
239 * If there is a real existing directory then put the cache file there
240 * advantage: real file access is really fast
241 * Otherwise write in cachefile
243 if ($valid && $direct_cache) {
244 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true), $img_str_orig);
246 if ($sizetype != '') {
247 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true) . $sizetype, $img_str);
249 } elseif ($cachefile != '') {
250 file_put_contents($cachefile, $img_str_orig);
253 header('Content-type: ' . $mime);
255 // Only output the cache headers when the file is valid
257 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
258 header('Etag: "' . md5($img_str) . '"');
259 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
260 header('Cache-Control: max-age=31536000');