2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
4 define("PROXY_DEFAULT_TIME", 86400); // 1 Day
6 require_once('include/security.php');
7 require_once("include/Photo.php");
9 function proxy_init() {
12 // Pictures are stored in one of the following ways:
13 // 1. If a folder "proxy" exists and is writeable, then use this for caching
14 // 2. If a cache path is defined, use this
15 // 3. If everything else failed, cache into the database
17 // Question: Do we really need these three methods?
19 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
20 header('HTTP/1.1 304 Not Modified');
21 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
22 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
23 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
24 header("Cache-Control: max-age=31536000");
25 if(function_exists('header_remove')) {
26 header_remove('Last-Modified');
27 header_remove('Expires');
28 header_remove('Cache-Control');
33 if(function_exists('header_remove')) {
34 header_remove('Pragma');
35 header_remove('pragma');
41 // If the cache path isn't there, try to create it
42 if (!is_dir($_SERVER["DOCUMENT_ROOT"]."/proxy"))
43 if (is_writable($_SERVER["DOCUMENT_ROOT"]))
44 mkdir($_SERVER["DOCUMENT_ROOT"]."/proxy");
46 // Checking if caching into a folder in the webroot is activated and working
47 $direct_cache = (is_dir($_SERVER["DOCUMENT_ROOT"]."/proxy") AND is_writable($_SERVER["DOCUMENT_ROOT"]."/proxy"));
49 // Look for filename in the arguments
50 if (isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) {
51 if (isset($a->argv[3]))
53 elseif (isset($a->argv[2]))
58 if (isset($a->argv[3]) and ($a->argv[3] == "thumb"))
61 // thumb, small, medium and large.
62 if (substr($url, -6) == ":thumb")
64 if (substr($url, -6) == ":small")
66 if (substr($url, -7) == ":medium")
68 if (substr($url, -6) == ":large")
71 $pos = strrpos($url, "=.");
73 $url = substr($url, 0, $pos+1);
75 $url = str_replace(array(".jpg", ".jpeg", ".gif", ".png"), array("","","",""), $url);
77 $url = base64_decode(strtr($url, '-_', '+/'), true);
80 $_REQUEST['url'] = $url;
84 $urlhash = 'pic:' . sha1($_REQUEST['url']);
86 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
87 if ($cachefile != '') {
88 if (file_exists($cachefile)) {
89 $img_str = file_get_contents($cachefile);
90 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
92 header("Content-type: $mime");
93 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
94 header('Etag: "'.md5($img_str).'"');
95 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
96 header("Cache-Control: max-age=31536000");
98 // reduce quality - if it isn't a GIF
99 if ($mime != "image/gif") {
100 $img = new Photo($img_str, $mime);
101 if($img->is_valid()) {
102 $img_str = $img->imageString();
115 if (!$direct_cache AND ($cachefile == "")) {
116 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
118 $img_str = $r[0]['data'];
119 $mime = $r[0]["desc"];
120 if ($mime == "") $mime = "image/jpeg";
126 // It shouldn't happen but it does - spaces in URL
127 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
129 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
131 $tempfile = tempnam(get_temppath(), "cache");
132 file_put_contents($tempfile, $img_str);
133 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
136 // If there is an error then return a blank image
137 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
138 $img_str = file_get_contents("images/blank.png");
140 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
142 $img = new Photo($img_str, "image/png");
143 if($img->is_valid()) {
144 $img->scaleImage(10);
145 $img_str = $img->imageString();
147 } else if (($mime != "image/jpeg") AND !$direct_cache AND ($cachefile == "")) {
148 $image = @imagecreatefromstring($img_str);
150 if($image === FALSE) die();
152 q("INSERT INTO `photo`
153 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
154 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
155 0, 0, get_guid(), dbesc($urlhash),
156 dbesc(datetime_convert()),
157 dbesc(datetime_convert()),
158 dbesc(basename(dbesc($_REQUEST["url"]))),
160 intval(imagesy($image)),
161 intval(imagesx($image)),
166 dbesc(''), dbesc(''), dbesc(''), dbesc('')
170 $img = new Photo($img_str, $mime);
171 if($img->is_valid()) {
172 if (!$direct_cache AND ($cachefile == ""))
173 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
178 // reduce quality - if it isn't a GIF
179 if ($mime != "image/gif") {
180 $img = new Photo($img_str, $mime);
181 if($img->is_valid()) {
182 $img->scaleImage($size);
183 $img_str = $img->imageString();
187 // If there is a real existing directory then put the cache file there
188 // advantage: real file access is really fast
189 // Otherwise write in cachefile
190 if ($valid AND $direct_cache)
191 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/proxy/".proxy_url($_REQUEST['url'], true), $img_str);
192 elseif ($cachefile != '')
193 file_put_contents($cachefile, $img_str);
195 header("Content-type: $mime");
197 // Only output the cache headers when the file is valid
199 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
200 header('Etag: "'.md5($img_str).'"');
201 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
202 header("Cache-Control: max-age=31536000");
210 function proxy_url($url, $writemode = false) {
213 // Only continue if it isn't a local image and the isn't deactivated
214 if (get_config("system", "proxy_disabled") OR proxy_is_local_image($url))
219 // Creating a sub directory to reduce the amount of files in the cache directory
220 $basepath = $_SERVER["DOCUMENT_ROOT"]."/proxy";
222 $path = substr(hash("md5", $url), 0, 2);
224 if (is_dir($basepath) and $writemode)
225 if (!is_dir($basepath."/".$path)) {
226 mkdir($basepath."/".$path);
227 chmod($basepath."/".$path, 0777);
230 $path .= "/".strtr(base64_encode($url), '+/', '-_');
232 // Checking for valid extensions. Only add them if they are safe
233 $pos = strrpos($url, ".");
235 $extension = strtolower(substr($url, $pos+1));
236 $pos = strpos($extension, "?");
238 $extension = substr($extension, 0, $pos);
241 $extensions = array("jpg", "jpeg", "gif", "png");
243 if (in_array($extension, $extensions))
244 $path .= ".".$extension;
246 $proxypath = $a->get_baseurl()."/proxy/".$path;
248 // Too long files aren't supported by Apache
249 if (strlen($proxypath) > 250)
261 function proxy_is_local_image($url) {
262 if ($url[0] == '/') return true;
264 if (strtolower(substr($url, 0, 5)) == "data:") return true;
266 // links normalised - bug #431
267 $baseurl = normalise_link(get_app()->get_baseurl());
268 $url = normalise_link($url);
269 return (substr($url, 0, strlen($baseurl)) == $baseurl);
272 function proxy_parse_query($var) {
274 * Use this function to parse out the query array element from
275 * the output of parse_url().
277 $var = parse_url($var, PHP_URL_QUERY);
278 $var = html_entity_decode($var);
279 $var = explode('&', $var);
282 foreach($var as $val) {
283 $x = explode('=', $val);
287 unset($val, $x, $var);
291 function proxy_img_cb($matches) {
293 // if the picture seems to be from another picture cache then take the original source
294 $queryvar = proxy_parse_query($matches[2]);
295 if (($queryvar['url'] != "") AND (substr($queryvar['url'], 0, 4) == "http"))
296 $matches[2] = urldecode($queryvar['url']);
298 // following line changed per bug #431
299 if (proxy_is_local_image($matches[2]))
300 return $matches[1] . $matches[2] . $matches[3];
302 return $matches[1].proxy_url(htmlspecialchars_decode($matches[2])).$matches[3];
305 function proxy_parse_html($html) {
306 return preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "proxy_img_cb", $html);