4 * Name: Privacy Image Cache
6 * Author: Tobias Hößl <https://github.com/CatoTH/>
9 define("PRIVACY_IMAGE_CACHE_DEFAULT_TIME", 86400); // 1 Day
11 require_once('include/security.php');
12 require_once("Photo.php");
14 function privacy_image_cache_install() {
15 register_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
16 // register_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
17 register_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
18 register_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
19 register_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
23 function privacy_image_cache_uninstall() {
24 unregister_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
25 unregister_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
26 unregister_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
27 unregister_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
28 unregister_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
32 function privacy_image_cache_module() {}
34 function privacy_image_cache_init() {
37 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
38 header('HTTP/1.1 304 Not Modified');
39 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
40 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
41 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
42 header("Cache-Control: max-age=31536000");
43 if(function_exists('header_remove')) {
44 header_remove('Last-Modified');
45 header_remove('Expires');
46 header_remove('Cache-Control');
51 //if ($a->config["system"]["db_log"] != "")
52 // $stamp1 = microtime(true);
54 if(function_exists('header_remove')) {
55 header_remove('Pragma');
56 header_remove('pragma');
61 // Look for filename in the arguments
62 if (isset($a->argv[1]) OR isset($a->argv[2])) {
63 if (isset($a->argv[2]))
68 $pos = strrpos($url, "==.");
70 $url = substr($url, 0, $pos+2);
72 $url = base64_decode(strtr($url, '-_', '+/'), true);
74 $_REQUEST['url'] = $url;
76 $thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
79 $urlhash = 'pic:' . sha1($_REQUEST['url']);
80 // Double encoded url - happens with Diaspora
81 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
83 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
84 if ($cachefile != '') {
85 if (file_exists($cachefile)) {
86 $img_str = file_get_contents($cachefile);
87 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
89 header("Content-type: $mime");
90 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
91 header('Etag: "'.md5($img_str).'"');
92 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
93 header("Cache-Control: max-age=31536000");
95 $img = new Photo($img_str, $mime);
97 $img_str = $img->imageString();
101 if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
102 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
110 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
112 $img_str = $r[0]['data'];
113 $mime = $r[0]["desc"];
114 if ($mime == "") $mime = "image/jpeg";
117 // It shouldn't happen but it does - spaces in URL
118 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
121 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
123 $tempfile = tempnam(get_config("system","temppath"), "cache");
124 file_put_contents($tempfile, $img_str);
125 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
128 // If there is an error then return a blank image
129 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
130 $img_str = file_get_contents("images/blank.png");
132 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
134 $img = new Photo($img_str, "image/png");
135 if($img->is_valid()) {
136 $img->scaleImage(10);
137 $img_str = $img->imageString();
139 } else if ($mime != "image/jpeg") {
140 $image = @imagecreatefromstring($img_str);
142 if($image === FALSE) die();
144 q("INSERT INTO `photo`
145 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
146 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
147 0, 0, get_guid(), dbesc($urlhash),
148 dbesc(datetime_convert()),
149 dbesc(datetime_convert()),
150 dbesc(basename(dbesc($_REQUEST["url"]))),
152 intval(imagesy($image)),
153 intval(imagesx($image)),
158 dbesc(''), dbesc(''), dbesc(''), dbesc('')
162 $img = new Photo($img_str, $mime);
163 if($img->is_valid()) {
164 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
166 $img->scaleImage(200); // Test
167 $img_str = $img->imageString();
169 //$mime = "image/jpeg";
173 $img = new Photo($img_str, $mime);
175 $img_str = $img->imageString();
177 // If there is a real existing directory then put the cache file there
178 // advantage: real file access is really fast
179 // Otherwise write in cachefile
180 if ($valid AND is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
181 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
182 elseif ($cachefile != '')
183 file_put_contents($cachefile, $img_str);
185 header("Content-type: $mime");
187 // Only output the cache headers when the file is valid
189 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
190 header('Etag: "'.md5($img_str).'"');
191 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
192 header("Cache-Control: max-age=31536000");
200 function privacy_image_cache_cachename($url, $writemode = false) {
203 $basepath = $_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache";
205 $path = substr(hash("md5", $url), 0, 2);
207 if (is_dir($basepath) and $writemode)
208 if (!is_dir($basepath."/".$path)) {
209 mkdir($basepath."/".$path);
210 chmod($basepath."/".$path, 0777);
213 $path .= "/".strtr(base64_encode($url), '+/', '-_');
222 function privacy_image_cache_is_local_image($url) {
223 if ($url[0] == '/') return true;
225 if (strtolower(substr($url, 0, 5)) == "data:") return true;
227 // Check if the cached path would be longer than 255 characters - apache doesn't like it
228 if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache")) {
229 $cachedurl = get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename($url);
230 if (strlen($url) > 150)
234 // links normalised - bug #431
235 $baseurl = normalise_link(get_app()->get_baseurl());
236 $url = normalise_link($url);
237 return (substr($url, 0, strlen($baseurl)) == $baseurl);
241 * @param array $matches
244 function privacy_image_cache_img_cb($matches) {
246 // if the picture seems to be from another picture cache then take the original source
247 $queryvar = privacy_image_cache_parse_query($matches[2]);
248 if ($queryvar['url'] != "")
249 $matches[2] = urldecode($queryvar['url']);
251 // if fetching facebook pictures don't fetch the thumbnail but the big one
252 if (strpos($matches[2], ".fbcdn.net/") and (substr($matches[2], -6) == "_s.jpg"))
253 $matches[2] = substr($matches[2], 0, -6)."_n.jpg";
255 // following line changed per bug #431
256 if (privacy_image_cache_is_local_image($matches[2]))
257 return $matches[1] . $matches[2] . $matches[3];
259 //return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
261 return $matches[1].get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename(htmlspecialchars_decode($matches[2])).$matches[3];
268 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
269 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
275 * Function disabled because the plugin moved
277 function privacy_image_cache_bbcode_hook(&$a, &$o) {
278 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
286 function privacy_image_cache_display_item_hook(&$a, &$o) {
287 if (isset($o["output"])) {
288 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
289 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
290 //$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
291 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
292 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
293 //$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
294 if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
295 $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
296 //$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
305 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
306 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
307 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["photo"]);
308 //$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
314 * @param null|object $b
316 function privacy_image_cache_cron(&$a = null, &$b = null) {
317 $cachetime = get_config('privacy_image_cache','cache_time');
318 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
320 $last = get_config('pi_cache','last_delete');
322 if ($time < ($last + 3600)) return;
324 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
325 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
327 clear_cache($a->get_basepath(), $a->get_basepath()."/privacy_image_cache");
329 set_config('pi_cache', 'last_delete', $time);
334 * @param null|object $o
336 function privacy_image_cache_plugin_admin(&$a, &$o){
339 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
341 $cachetime = get_config('privacy_image_cache','cache_time');
342 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
343 $cachetime_h = Ceil($cachetime / 3600);
345 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
346 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
348 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
350 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
352 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
353 $o .= '<label for="statictics_num">' . t('Number of items') . '</label><input style="color: gray;" id="statistics_num" disabled value="' . escape_tags($num[0]['num']) . '"><br style="clear: both;">';
354 $size = Ceil($num[0]['size'] / (1024 * 1024));
355 $o .= '<label for="statictics_size">' . t('Size of the cache') . '</label><input style="color: gray;" id="statistics_size" disabled value="' . $size . ' MB"><br style="clear: both;">';
357 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
363 * @param null|object $o
365 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
366 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
368 if (isset($_REQUEST['save'])) {
369 $cachetime_h = IntVal($_REQUEST['cachetime']);
370 if ($cachetime_h < 1) $cachetime_h = 1;
371 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
373 if (isset($_REQUEST['delete_all'])) {
374 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
378 function privacy_image_cache_parse_query($var) {
380 * Use this function to parse out the query array element from
381 * the output of parse_url().
383 $var = parse_url($var, PHP_URL_QUERY);
384 $var = html_entity_decode($var);
385 $var = explode('&', $var);
388 foreach($var as $val) {
389 $x = explode('=', $val);
393 unset($val, $x, $var);