2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
5 use Friendica\Core\System;
7 define('PROXY_DEFAULT_TIME', 86400); // 1 Day
9 define('PROXY_SIZE_MICRO', 'micro');
10 define('PROXY_SIZE_THUMB', 'thumb');
11 define('PROXY_SIZE_SMALL', 'small');
12 define('PROXY_SIZE_MEDIUM', 'medium');
13 define('PROXY_SIZE_LARGE', 'large');
15 require_once 'include/security.php';
16 require_once 'include/Photo.php';
18 function proxy_init(App $a) {
19 // Pictures are stored in one of the following ways:
20 // 1. If a folder "proxy" exists and is writeable, then use this for caching
21 // 2. If a cache path is defined, use this
22 // 3. If everything else failed, cache into the database
24 // Question: Do we really need these three methods?
26 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
27 header('HTTP/1.1 304 Not Modified');
28 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
29 header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
30 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
31 header('Cache-Control: max-age=31536000');
33 if (function_exists('header_remove')) {
34 header_remove('Last-Modified');
35 header_remove('Expires');
36 header_remove('Cache-Control');
41 if (function_exists('header_remove')) {
42 header_remove('Pragma');
43 header_remove('pragma');
49 $basepath = $a->get_basepath();
51 // If the cache path isn't there, try to create it
52 if (!is_dir($basepath . '/proxy') && is_writable($basepath)) {
53 mkdir($basepath . '/proxy');
56 // Checking if caching into a folder in the webroot is activated and working
57 $direct_cache = (is_dir($basepath . '/proxy') && is_writable($basepath . '/proxy'));
59 // Look for filename in the arguments
60 if ((isset($a->argv[1]) || isset($a->argv[2]) || isset($a->argv[3])) && !isset($_REQUEST['url'])) {
61 if (isset($a->argv[3])) {
63 } elseif (isset($a->argv[2])) {
69 if (isset($a->argv[3]) && ($a->argv[3] == 'thumb')) {
73 // thumb, small, medium and large.
74 if (substr($url, -6) == ':micro') {
77 $url = substr($url, 0, -6);
78 } elseif (substr($url, -6) == ':thumb') {
81 $url = substr($url, 0, -6);
82 } elseif (substr($url, -6) == ':small') {
84 $url = substr($url, 0, -6);
86 } elseif (substr($url, -7) == ':medium') {
88 $url = substr($url, 0, -7);
89 $sizetype = ':medium';
90 } elseif (substr($url, -6) == ':large') {
92 $url = substr($url, 0, -6);
96 $pos = strrpos($url, '=.');
98 $url = substr($url, 0, $pos + 1);
101 $url = str_replace(array('.jpg', '.jpeg', '.gif', '.png'), array('','','',''), $url);
103 $url = base64_decode(strtr($url, '-_', '+/'), true);
106 $_REQUEST['url'] = $url;
109 $direct_cache = false;
112 if (!$direct_cache) {
113 $urlhash = 'pic:' . sha1($_REQUEST['url']);
115 $cachefile = get_cachefile(hash('md5', $_REQUEST['url']));
116 if ($cachefile != '' && file_exists($cachefile)) {
117 $img_str = file_get_contents($cachefile);
118 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
120 header('Content-type: ' . $mime);
121 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
122 header('Etag: "' . md5($img_str) . '"');
123 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
124 header('Cache-Control: max-age=31536000');
126 // reduce quality - if it isn't a GIF
127 if ($mime != 'image/gif') {
128 $img = new Photo($img_str, $mime);
129 if ($img->is_valid()) {
130 $img_str = $img->imageString();
144 if (!$direct_cache && ($cachefile == '')) {
145 $r = qu("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
146 if (dbm::is_result($r)) {
147 $img_str = $r[0]['data'];
148 $mime = $r[0]['desc'];
150 $mime = 'image/jpeg';
155 if (!dbm::is_result($r)) {
156 // It shouldn't happen but it does - spaces in URL
157 $_REQUEST['url'] = str_replace(' ', '+', $_REQUEST['url']);
159 $img_str = fetch_url($_REQUEST['url'], true, $redirects, 10);
161 $tempfile = tempnam(get_temppath(), 'cache');
162 file_put_contents($tempfile, $img_str);
163 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
166 // If there is an error then return a blank image
167 if ((substr($a->get_curl_code(), 0, 1) == '4') || (!$img_str)) {
168 $img_str = file_get_contents('images/blank.png');
170 $cachefile = ''; // Clear the cachefile so that the dummy isn't stored
172 $img = new Photo($img_str, 'image/png');
173 if ($img->is_valid()) {
174 $img->scaleImage(10);
175 $img_str = $img->imageString();
177 } elseif ($mime != 'image/jpeg' && !$direct_cache && $cachefile == '') {
178 $image = @imagecreatefromstring($img_str);
180 if ($image === FALSE) {
184 q("INSERT INTO `photo`
185 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
186 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
187 0, 0, get_guid(), dbesc($urlhash),
188 dbesc(datetime_convert()),
189 dbesc(datetime_convert()),
190 dbesc(basename(dbesc($_REQUEST['url']))),
192 intval(imagesy($image)),
193 intval(imagesx($image)),
198 dbesc(''), dbesc(''), dbesc(''), dbesc('')
202 $img = new Photo($img_str, $mime);
203 if ($img->is_valid() && !$direct_cache && ($cachefile == '')) {
204 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
209 $img_str_orig = $img_str;
211 // reduce quality - if it isn't a GIF
212 if ($mime != 'image/gif') {
213 $img = new Photo($img_str, $mime);
214 if ($img->is_valid()) {
215 $img->scaleImage($size);
216 $img_str = $img->imageString();
220 // If there is a real existing directory then put the cache file there
221 // advantage: real file access is really fast
222 // Otherwise write in cachefile
223 if ($valid && $direct_cache) {
224 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true), $img_str_orig);
225 if ($sizetype != '') {
226 file_put_contents($basepath . '/proxy/' . proxy_url($_REQUEST['url'], true) . $sizetype, $img_str);
228 } elseif ($cachefile != '') {
229 file_put_contents($cachefile, $img_str_orig);
232 header('Content-type: ' . $mime);
234 // Only output the cache headers when the file is valid
236 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
237 header('Etag: "' . md5($img_str) . '"');
238 header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
239 header('Cache-Control: max-age=31536000');
248 * @brief Transform a remote URL into a local one
250 * This function only performs the URL replacement on http URL and if the
251 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
252 * system.proxy_disabled is set to false.
254 * @param string $url The URL to proxyfy
255 * @param bool $writemode Returns a local path the remote URL should be saved to
256 * @param string $size One of the PROXY_SIZE_* constants
258 * @return string The proxyfied URL or relative path
260 function proxy_url($url, $writemode = false, $size = '') {
263 if (substr($url, 0, strlen('http')) !== 'http') {
267 // Only continue if it isn't a local image and the isn't deactivated
268 if (proxy_is_local_image($url)) {
269 $url = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
273 if (get_config('system', 'proxy_disabled')) {
277 // Image URL may have encoded ampersands for display which aren't desirable for proxy
278 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
280 // Creating a sub directory to reduce the amount of files in the cache directory
281 $basepath = $a->get_basepath() . '/proxy';
283 $shortpath = hash('md5', $url);
284 $longpath = substr($shortpath, 0, 2);
286 if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
287 mkdir($basepath . '/' . $longpath);
288 chmod($basepath . '/' . $longpath, 0777);
291 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
293 // Extract the URL extension
294 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
296 $extensions = array('jpg', 'jpeg', 'gif', 'png');
297 if (in_array($extension, $extensions)) {
298 $shortpath .= '.' . $extension;
299 $longpath .= '.' . $extension;
302 $proxypath = System::baseUrl() . '/proxy/' . $longpath;
308 // Too long files aren't supported by Apache
309 // Writemode in combination with long files shouldn't be possible
310 if ((strlen($proxypath) > 250) && $writemode) {
312 } elseif (strlen($proxypath) > 250) {
313 return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
314 } elseif ($writemode) {
317 return $proxypath . $size;
325 function proxy_is_local_image($url) {
326 if ($url[0] == '/') {
330 if (strtolower(substr($url, 0, 5)) == 'data:') {
334 // links normalised - bug #431
335 $baseurl = normalise_link(System::baseUrl());
336 $url = normalise_link($url);
337 return (substr($url, 0, strlen($baseurl)) == $baseurl);
341 * @brief Return the array of query string parameters from a URL
344 * @return array Associative array of query string parameters
346 function proxy_parse_query($url) {
347 $query = parse_url($url, PHP_URL_QUERY);
348 $query = html_entity_decode($query);
349 $query_list = explode('&', $query);
352 foreach ($query_list as $key_value) {
353 $key_value_list = explode('=', $key_value);
354 $arr[$key_value_list[0]] = $key_value_list[1];
357 unset($url, $query_list, $url);
361 function proxy_img_cb($matches) {
362 // if the picture seems to be from another picture cache then take the original source
363 $queryvar = proxy_parse_query($matches[2]);
364 if (($queryvar['url'] != '') && (substr($queryvar['url'], 0, 4) == 'http')) {
365 $matches[2] = urldecode($queryvar['url']);
368 // following line changed per bug #431
369 if (proxy_is_local_image($matches[2])) {
370 return $matches[1] . $matches[2] . $matches[3];
373 return $matches[1] . proxy_url(htmlspecialchars_decode($matches[2])) . $matches[3];
376 function proxy_parse_html($html) {
377 $html = str_replace(normalise_link(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
379 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'proxy_img_cb', $html);