2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
4 define("PROXY_DEFAULT_TIME", 86400); // 1 Day
6 define("PROXY_SIZE_MICRO", "micro");
7 define("PROXY_SIZE_THUMB", "thumb");
8 define("PROXY_SIZE_SMALL", "small");
9 define("PROXY_SIZE_MEDIUM", "medium");
10 define("PROXY_SIZE_LARGE", "large");
12 require_once('include/security.php');
13 require_once("include/Photo.php");
15 function proxy_init() {
18 // Pictures are stored in one of the following ways:
19 // 1. If a folder "proxy" exists and is writeable, then use this for caching
20 // 2. If a cache path is defined, use this
21 // 3. If everything else failed, cache into the database
23 // Question: Do we really need these three methods?
25 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
26 header('HTTP/1.1 304 Not Modified');
27 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
28 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
29 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
30 header("Cache-Control: max-age=31536000");
31 if(function_exists('header_remove')) {
32 header_remove('Last-Modified');
33 header_remove('Expires');
34 header_remove('Cache-Control');
39 if(function_exists('header_remove')) {
40 header_remove('Pragma');
41 header_remove('pragma');
47 $basepath = $a->get_basepath();
49 // If the cache path isn't there, try to create it
50 if (!is_dir($basepath."/proxy"))
51 if (is_writable($basepath))
52 mkdir($basepath."/proxy");
54 // Checking if caching into a folder in the webroot is activated and working
55 $direct_cache = (is_dir($basepath."/proxy") AND is_writable($basepath."/proxy"));
57 // Look for filename in the arguments
58 if ((isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) AND !isset($_REQUEST["url"])) {
59 if (isset($a->argv[3]))
61 elseif (isset($a->argv[2]))
66 if (isset($a->argv[3]) and ($a->argv[3] == "thumb"))
69 // thumb, small, medium and large.
70 if (substr($url, -6) == ":micro") {
73 $url = substr($url, 0, -6);
74 } elseif (substr($url, -6) == ":thumb") {
77 $url = substr($url, 0, -6);
78 } elseif (substr($url, -6) == ":small") {
80 $url = substr($url, 0, -6);
82 } elseif (substr($url, -7) == ":medium") {
84 $url = substr($url, 0, -7);
85 $sizetype = ":medium";
86 } elseif (substr($url, -6) == ":large") {
88 $url = substr($url, 0, -6);
92 $pos = strrpos($url, "=.");
94 $url = substr($url, 0, $pos+1);
96 $url = str_replace(array(".jpg", ".jpeg", ".gif", ".png"), array("","","",""), $url);
98 $url = base64_decode(strtr($url, '-_', '+/'), true);
101 $_REQUEST['url'] = $url;
103 $direct_cache = false;
105 if (!$direct_cache) {
106 $urlhash = 'pic:' . sha1($_REQUEST['url']);
108 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
109 if ($cachefile != '') {
110 if (file_exists($cachefile)) {
111 $img_str = file_get_contents($cachefile);
112 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
114 header("Content-type: $mime");
115 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
116 header('Etag: "'.md5($img_str).'"');
117 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
118 header("Cache-Control: max-age=31536000");
120 // reduce quality - if it isn't a GIF
121 if ($mime != "image/gif") {
122 $img = new Photo($img_str, $mime);
123 if($img->is_valid()) {
124 $img_str = $img->imageString();
137 if (!$direct_cache AND ($cachefile == "")) {
138 $r = qu("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
139 if (dbm::is_result($r)) {
140 $img_str = $r[0]['data'];
141 $mime = $r[0]["desc"];
142 if ($mime == "") $mime = "image/jpeg";
147 if (!dbm::is_result($r)) {
148 // It shouldn't happen but it does - spaces in URL
149 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
151 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
153 $tempfile = tempnam(get_temppath(), "cache");
154 file_put_contents($tempfile, $img_str);
155 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
158 // If there is an error then return a blank image
159 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
160 $img_str = file_get_contents("images/blank.png");
162 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
164 $img = new Photo($img_str, "image/png");
165 if($img->is_valid()) {
166 $img->scaleImage(10);
167 $img_str = $img->imageString();
169 } else if (($mime != "image/jpeg") AND !$direct_cache AND ($cachefile == "")) {
170 $image = @imagecreatefromstring($img_str);
172 if($image === FALSE) die();
174 q("INSERT INTO `photo`
175 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
176 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
177 0, 0, get_guid(), dbesc($urlhash),
178 dbesc(datetime_convert()),
179 dbesc(datetime_convert()),
180 dbesc(basename(dbesc($_REQUEST["url"]))),
182 intval(imagesy($image)),
183 intval(imagesx($image)),
188 dbesc(''), dbesc(''), dbesc(''), dbesc('')
192 $img = new Photo($img_str, $mime);
193 if($img->is_valid()) {
194 if (!$direct_cache AND ($cachefile == ""))
195 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
200 $img_str_orig = $img_str;
202 // reduce quality - if it isn't a GIF
203 if ($mime != "image/gif") {
204 $img = new Photo($img_str, $mime);
205 if($img->is_valid()) {
206 $img->scaleImage($size);
207 $img_str = $img->imageString();
211 // If there is a real existing directory then put the cache file there
212 // advantage: real file access is really fast
213 // Otherwise write in cachefile
214 if ($valid AND $direct_cache) {
215 file_put_contents($basepath."/proxy/".proxy_url($_REQUEST['url'], true), $img_str_orig);
217 file_put_contents($basepath."/proxy/".proxy_url($_REQUEST['url'], true).$sizetype, $img_str);
218 } elseif ($cachefile != '')
219 file_put_contents($cachefile, $img_str_orig);
221 header("Content-type: $mime");
223 // Only output the cache headers when the file is valid
225 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
226 header('Etag: "'.md5($img_str).'"');
227 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
228 header("Cache-Control: max-age=31536000");
237 * @brief Transform a remote URL into a local one
239 * This function only performs the URL replacement on http URL and if the
240 * provided URL isn't local, "the isn't deactivated" (sic) and if the config
241 * system.proxy_disabled is set to false.
243 * @param string $url The URL to proxyfy
244 * @param bool $writemode Returns a local path the remote URL should be saved to
245 * @param string $size One of the PROXY_SIZE_* constants
247 * @return string The proxyfied URL or relative path
249 function proxy_url($url, $writemode = false, $size = '') {
252 if (substr($url, 0, strlen('http')) !== 'http') {
256 // Only continue if it isn't a local image and the isn't deactivated
257 if (proxy_is_local_image($url)) {
258 $url = str_replace(normalise_link(App::get_baseurl()) . '/', App::get_baseurl() . '/', $url);
262 if (get_config('system', 'proxy_disabled')) {
266 // Image URL may have encoded ampersands for display which aren't desirable for proxy
267 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
269 // Creating a sub directory to reduce the amount of files in the cache directory
270 $basepath = $a->get_basepath() . '/proxy';
272 $shortpath = hash('md5', $url);
273 $longpath = substr($shortpath, 0, 2);
275 if (is_dir($basepath) and $writemode) {
276 if (!is_dir($basepath . '/' . $longpath)) {
277 mkdir($basepath . '/' . $longpath);
278 chmod($basepath . '/' . $longpath, 0777);
282 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
284 // Checking for valid extensions. Only add them if they are safe
285 $pos = strrpos($url, '.');
287 $extension = strtolower(substr($url, $pos + 1));
288 $pos = strpos($extension, '?');
290 $extension = substr($extension, 0, $pos);
294 $extensions = array('jpg', 'jpeg', 'gif', 'png');
295 if (in_array($extension, $extensions)) {
296 $shortpath .= '.' . $extension;
297 $longpath .= '.' . $extension;
300 $proxypath = App::get_baseurl() . '/proxy/' . $longpath;
306 // Too long files aren't supported by Apache
307 // Writemode in combination with long files shouldn't be possible
308 if ((strlen($proxypath) > 250) AND $writemode) {
310 } elseif (strlen($proxypath) > 250) {
311 return App::get_baseurl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
312 } elseif ($writemode) {
315 return $proxypath . $size;
323 function proxy_is_local_image($url) {
324 if ($url[0] == '/') return true;
326 if (strtolower(substr($url, 0, 5)) == "data:") return true;
328 // links normalised - bug #431
329 $baseurl = normalise_link(get_app()->get_baseurl());
330 $url = normalise_link($url);
331 return (substr($url, 0, strlen($baseurl)) == $baseurl);
334 function proxy_parse_query($var) {
336 * Use this function to parse out the query array element from
337 * the output of parse_url().
339 $var = parse_url($var, PHP_URL_QUERY);
340 $var = html_entity_decode($var);
341 $var = explode('&', $var);
344 foreach($var as $val) {
345 $x = explode('=', $val);
349 unset($val, $x, $var);
353 function proxy_img_cb($matches) {
355 // if the picture seems to be from another picture cache then take the original source
356 $queryvar = proxy_parse_query($matches[2]);
357 if (($queryvar['url'] != "") AND (substr($queryvar['url'], 0, 4) == "http"))
358 $matches[2] = urldecode($queryvar['url']);
360 // following line changed per bug #431
361 if (proxy_is_local_image($matches[2]))
362 return $matches[1] . $matches[2] . $matches[3];
364 return $matches[1].proxy_url(htmlspecialchars_decode($matches[2])).$matches[3];
367 function proxy_parse_html($html) {
369 $html = str_replace(normalise_link(App::get_baseurl())."/", App::get_baseurl()."/", $html);
371 return preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "proxy_img_cb", $html);