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 (empty($_REQUEST['url'])) {
137 System::httpExit(400, ["title" => L10n::t('Bad Request.')]);
140 if (!$direct_cache) {
141 $urlhash = 'pic:' . sha1($_REQUEST['url']);
143 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
144 if ($cachefile != '' && file_exists($cachefile)) {
145 $img_str = file_get_contents($cachefile);
146 $mime = mime_content_type($cachefile);
148 header('Content-type: ' . $mime);
149 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
150 header('Etag: "' . md5($img_str) . '"');
151 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
152 header('Cache-Control: max-age=31536000');
154 // reduce quality - if it isn't a GIF
155 if ($mime != 'image/gif') {
156 $image = new Image($img_str, $mime);
158 if ($image->isValid()) {
159 $img_str = $image->asString();
173 if (!$direct_cache && ($cachefile == '')) {
174 $photo = DBA::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
176 if (DBA::isResult($photo)) {
177 $img_str = $photo['data'];
178 $mime = $photo['desc'];
181 $mime = 'image/jpeg';
186 if (!DBA::isResult($photo)) {
187 // It shouldn't happen but it does - spaces in URL
188 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
190 $img_str = Network::fetchUrl($_REQUEST['url'], true, $redirects, 10);
192 $tempfile = tempnam(get_temppath(), 'cache');
193 file_put_contents($tempfile, $img_str);
194 $mime = mime_content_type($tempfile);
197 // If there is an error then return a blank image
198 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
199 $img_str = file_get_contents('images/blank.png');
201 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
203 $image = new Image($img_str, 'image/png');
205 if ($image->isValid()) {
206 $image->scaleDown(10);
207 $img_str = $image->asString();
209 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
210 $image = @imagecreatefromstring($img_str);
212 if ($image === FALSE) {
216 $fields = ['uid' => 0, 'contact-id' => 0, 'guid' => System::createGUID(), 'resource-id' => $urlhash, 'created' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utcNow(),
217 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
218 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
219 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime];
220 DBA::insert('photo', $fields);
222 $image = new Image($img_str, $mime);
224 if ($image->isValid() && !$direct_cache && ($cachefile == '')) {
225 Photo::store($image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
230 $img_str_orig = $img_str;
232 // reduce quality - if it isn't a GIF
233 if ($mime != 'image/gif') {
234 $image = new Image($img_str, $mime);
236 if ($image->isValid()) {
237 $image->scaleDown($size);
238 $img_str = $image->asString();
243 * If there is a real existing directory then put the cache file there
244 * advantage: real file access is really fast
245 * Otherwise write in cachefile
247 if ($valid && $direct_cache) {
248 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true), $img_str_orig);
250 if ($sizetype != '') {
251 file_put_contents($basepath . '/proxy/' . ProxyUtils::proxifyUrl($_REQUEST['url'], true) . $sizetype, $img_str);
253 } elseif ($cachefile != '') {
254 file_put_contents($cachefile, $img_str_orig);
257 header('Content-type: ' . $mime);
259 // Only output the cache headers when the file is valid
261 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
262 header('Etag: "' . md5($img_str) . '"');
263 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
264 header('Cache-Control: max-age=31536000');