4 * @brief Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
8 use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Photo;
12 use Friendica\Object\Image;
14 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
16 define('PROXY_SIZE_MICRO', 'micro');
17 define('PROXY_SIZE_THUMB', 'thumb');
18 define('PROXY_SIZE_SMALL', 'small');
19 define('PROXY_SIZE_MEDIUM', 'medium');
20 define('PROXY_SIZE_LARGE', 'large');
22 require_once 'include/security.php';
24 function proxy_init(App $a) {
25 // Pictures are stored in one of the following ways:
26 // 1. If a folder "proxy" exists and is writeable, then use this for caching
27 // 2. If a cache path is defined, use this
28 // 3. If everything else failed, cache into the database
30 // Question: Do we really need these three methods?
32 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
33 header('HTTP/1.1 304 Not Modified');
34 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
35 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
36 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
37 header('Cache-Control: max-age=31536000');
39 if (function_exists('header_remove')) {
40 header_remove('Last-Modified');
41 header_remove('Expires');
42 header_remove('Cache-Control');
47 if (function_exists('header_remove')) {
48 header_remove('Pragma');
49 header_remove('pragma');
55 $basepath = $a->get_basepath();
57 // If the cache path isn't there, try to create it
58 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
59 mkdir($basepath . '/proxy');
62 // Checking if caching into a folder in the webroot is activated and working
63 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
65 // Look for filename in the arguments
66 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
67 if (isset($a->argv[3])) {
69 } elseif (isset($a->argv[2])) {
75 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
79 // thumb, small, medium and large.
80 if (substr($url, -6) == ':micro') {
83 $url = substr($url, 0, -6);
84 } elseif (substr($url, -6) == ':thumb') {
87 $url = substr($url, 0, -6);
88 } elseif (substr($url, -6) == ':small') {
90 $url = substr($url, 0, -6);
92 } elseif (substr($url, -7) == ':medium') {
94 $url = substr($url, 0, -7);
95 $sizetype = ':medium';
96 } elseif (substr($url, -6) == ':large') {
98 $url = substr($url, 0, -6);
102 $pos = strrpos($url, '=.');
104 $url = substr($url, 0, $pos + 1);
107 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
109 $url = base64_decode(strtr($url, '-_', '+/'), true);
112 $_REQUEST['url'] = $url;
115 $direct_cache = false;
118 if (!$direct_cache) {
119 $urlhash = 'pic:' . sha1($_REQUEST['url']);
121 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
122 if ($cachefile != '' && file_exists($cachefile)) {
123 $img_str = file_get_contents($cachefile);
124 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
126 header('Content-type: ' . $mime);
127 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
128 header('Etag: "' . md5($img_str) . '"');
129 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
130 header('Cache-Control: max-age=31536000');
132 // reduce quality - if it isn't a GIF
133 if ($mime != 'image/gif') {
134 $Image = new Image($img_str, $mime);
135 if ($Image->isValid()) {
136 $img_str = $Image->asString();
150 if (!$direct_cache && ($cachefile == '')) {
151 $r = dba::select('photo', array('data', 'desc'), array('resource-id' => $urlhash), array('limit' => 1));
152 if (DBM::is_result($r)) {
153 $img_str = $r['data'];
156 $mime = 'image/jpeg';
161 if (!DBM::is_result($r)) {
162 // It shouldn't happen but it does - spaces in URL
163 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
165 $img_str = fetch_url($_REQUEST['url'], true, $redirects, 10);
167 $tempfile = tempnam(get_temppath(), 'cache');
168 file_put_contents($tempfile, $img_str);
169 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
172 // If there is an error then return a blank image
173 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
174 $img_str = file_get_contents('images/blank.png');
176 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
178 $Image = new Image($img_str, 'image/png');
179 if ($Image->isValid()) {
180 $Image->scaleDown(10);
181 $img_str = $Image->asString();
183 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
184 $image = @imagecreatefromstring($img_str);
186 if ($image === FALSE) {
190 $fields = array('uid' => 0, 'contact-id' => 0, 'guid' => get_guid(), 'resource-id' => $urlhash, 'created' => datetime_convert(), 'edited' => datetime_convert(),
191 'filename' => basename($_REQUEST['url']), 'type' => '', 'album' => '', 'height' => imagesy($image), 'width' => imagesx($image),
192 'datasize' => 0, 'data' => $img_str, 'scale' => 100, 'profile' => 0,
193 'allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '', 'desc' => $mime);
194 dba::insert('photo', $fields);
196 $Image = new Image($img_str, $mime);
197 if ($Image->isValid() && !$direct_cache && ($cachefile == '')) {
198 Photo::store($Image, 0, 0, $urlhash, $_REQUEST['url'], '', 100);
203 $img_str_orig = $img_str;
205 // reduce quality - if it isn't a GIF
206 if ($mime != 'image/gif') {
207 $Image = new Image($img_str, $mime);
208 if ($Image->isValid()) {
209 $Image->scaleDown($size);
210 $img_str = $Image->asString();
214 // If there is a real existing directory then put the cache file there
215 // advantage: real file access is really fast
216 // Otherwise write in cachefile
217 if ($valid && $direct_cache) {
218 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
219 if ($sizetype != '') {
220 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
222 } elseif ($cachefile != '') {
223 file_put_contents($cachefile, $img_str_orig);
226 header('Content-type: ' . $mime);
228 // Only output the cache headers when the file is valid
230 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
231 header('Etag: "' . md5($img_str) . '"');
232 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
233 header('Cache-Control: max-age=31536000');
242 * @brief Transform a remote URL into a local one
244 * This function only performs the URL replacement on http URL and if the
245 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
246 * system.proxy_disabled is set to false.
248 * @param string $url The URL to proxyfy
249 * @param bool $writemode Returns a local path the remote URL should be saved to
250 * @param string $size One of the PROXY_SIZE_* constants
252 * @return string The proxyfied URL or relative path
254 function proxy_url($url, $writemode = false, $size = '') {
257 if (substr($url, 0, strlen('http')) !== 'http') {
261 // Only continue if it isn't a local image and the isn't deactivated
262 if (proxy_is_local_image($url)) {
263 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
267 if (Config::get('system', 'proxy_disabled')) {
271 // Image URL may have encoded ampersands for display which aren't desirable for proxy
272 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
274 // Creating a sub directory to reduce the amount of files in the cache directory
275 $basepath = $a->get_basepath() . '/proxy';
277 $shortpath = hash('md5', $url);
278 $longpath = substr($shortpath, 0, 2);
280 if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
281 mkdir($basepath . '/' . $longpath);
282 chmod($basepath . '/' . $longpath, 0777);
285 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
287 // Extract the URL extension
288 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
290 $extensions = array('jpg', 'jpeg', 'gif', 'png');
291 if (in_array($extension, $extensions)) {
292 $shortpath .= '.' . $extension;
293 $longpath .= '.' . $extension;
296 $proxypath = System::baseUrl() . '/proxy/' . $longpath;
302 // Too long files aren't supported by Apache
303 // Writemode in combination with long files shouldn't be possible
304 if ((strlen($proxypath) > 250) && $writemode) {
306 } elseif (strlen($proxypath) > 250) {
307 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
308 } elseif ($writemode) {
311 return $proxypath . $size;
319 function proxy_is_local_image($url) {
320 if ($url[0] == '/') {
324 if (strtolower(substr($url, 0, 5)) == 'data:') {
328 // links normalised - bug #431
329 $baseurl = normalise_link(System::baseUrl());
330 $url = normalise_link($url);
331 return (substr($url, 0, strlen($baseurl)) == $baseurl);
335 * @brief Return the array of query string parameters from a URL
338 * @return array Associative array of query string parameters
340 function proxy_parse_query($url) {
341 $query = parse_url($url, PHP_URL_QUERY);
342 $query = html_entity_decode($query);
343 $query_list = explode('&', $query);
346 foreach ($query_list as $key_value) {
347 $key_value_list = explode('=', $key_value);
348 $arr[$key_value_list[0]] = $key_value_list[1];
351 unset($url, $query_list, $url);
355 function proxy_img_cb($matches) {
356 // if the picture seems to be from another picture cache then take the original source
357 $queryvar = proxy_parse_query($matches[2]);
358 if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
359 $matches[2] = urldecode($queryvar['url']);
362 // following line changed per bug #431
363 if (proxy_is_local_image($matches[2])) {
364 return $matches[1] . $matches[2] . $matches[3];
367 return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
370 function proxy_parse_html($html) {
371 $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
373 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);