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');
13 function privacy_image_cache_install() {
14 register_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
15 // register_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
16 register_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
17 register_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
18 register_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
22 function privacy_image_cache_uninstall() {
23 unregister_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
24 unregister_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
25 unregister_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
26 unregister_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
27 unregister_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
31 function privacy_image_cache_module() {}
33 function privacy_image_cache_init() {
36 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
37 header('HTTP/1.1 304 Not Modified');
38 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
39 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
40 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
41 header("Cache-Control: max-age=31536000");
42 if(function_exists('header_remove')) {
43 header_remove('Last-Modified');
44 header_remove('Expires');
45 header_remove('Cache-Control');
50 //if ($a->config["system"]["db_log"] != "")
51 // $stamp1 = microtime(true);
53 if(function_exists('header_remove')) {
54 header_remove('Pragma');
55 header_remove('pragma');
60 // Look for filename in the arguments
61 if (isset($a->argv[1]) OR isset($a->argv[2])) {
62 if (isset($a->argv[2]))
67 $pos = strrpos($url, "==.");
69 $url = substr($url, 0, $pos+2);
71 $url = base64_decode(strtr($url, '-_', '+/'), true);
73 $_REQUEST['url'] = $url;
75 $thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
78 $urlhash = 'pic:' . sha1($_REQUEST['url']);
79 // Double encoded url - happens with Diaspora
80 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
82 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
83 if ($cachefile != '') {
84 if (file_exists($cachefile)) {
85 $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");
97 //if ($a->config["system"]["db_log"] != "") {
98 // $stamp2 = microtime(true);
99 // $duration = round($stamp2-$stamp1, 3);
100 // if ($duration > $a->config["system"]["db_loglimit"])
101 // @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
108 require_once("Photo.php");
112 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
114 $img_str = $r[0]['data'];
115 $mime = $r[0]["desc"];
116 if ($mime == "") $mime = "image/jpeg";
119 // It shouldn't happen but it does - spaces in URL
120 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
122 $img_str = fetch_url($_REQUEST['url'],true);
124 $tempfile = tempnam(get_config("system","temppath"), "cache");
125 file_put_contents($tempfile, $img_str);
126 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
129 // If there is an error then return a blank image
130 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
131 $img_str = file_get_contents("images/blank.png");
133 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
135 $img = new Photo($img_str);
136 if($img->is_valid()) {
138 $img_str = $img->imageString();
140 //} else if (substr($img_str, 0, 6) == "GIF89a") {
141 } else if ($mime != "image/jpeg") {
142 $image = @imagecreatefromstring($img_str);
144 if($image === FALSE) die();
146 q("INSERT INTO `photo`
147 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
148 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
149 0, 0, get_guid(), dbesc($urlhash),
150 dbesc(datetime_convert()),
151 dbesc(datetime_convert()),
152 dbesc(basename(dbesc($_REQUEST["url"]))),
154 intval(imagesy($image)),
155 intval(imagesx($image)),
160 dbesc(''), dbesc(''), dbesc(''), dbesc('')
164 $img = new Photo($img_str);
165 if($img->is_valid()) {
166 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
168 $img->scaleImage(200); // Test
169 $img_str = $img->imageString();
171 $mime = "image/jpeg";
176 // If there is a real existing directory then put the cache file there
177 // advantage: real file access is really fast
178 // Otherwise write in cachefile
179 if ($valid AND is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
180 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
181 elseif ($cachefile != '')
182 file_put_contents($cachefile, $img_str);
184 header("Content-type: $mime");
186 // Only output the cache headers when the file is valid
188 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
189 header('Etag: "'.md5($img_str).'"');
190 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
191 header("Cache-Control: max-age=31536000");
196 //if ($a->config["system"]["db_log"] != "") {
197 // $stamp2 = microtime(true);
198 // $duration = round($stamp2-$stamp1, 3);
199 // if ($duration > $a->config["system"]["db_loglimit"])
200 // @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
206 function privacy_image_cache_cachename($url, $writemode = false) {
209 $basepath = $_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache";
211 $path = substr(hash("md5", $url), 0, 2);
213 if (is_dir($basepath) and $writemode)
214 if (!is_dir($basepath."/".$path)) {
215 mkdir($basepath."/".$path);
216 chmod($basepath."/".$path, 0777);
219 $path .= "/".strtr(base64_encode($url), '+/', '-_');
228 function privacy_image_cache_is_local_image($url) {
229 if ($url[0] == '/') return true;
230 if (strtolower(substr($url, 0, 5)) == "data:") return true;
232 // links normalised - bug #431
233 $baseurl = normalise_link(get_app()->get_baseurl());
234 $url = normalise_link($url);
235 return (substr($url, 0, strlen($baseurl)) == $baseurl);
239 * @param array $matches
242 function privacy_image_cache_img_cb($matches) {
243 // following line changed per bug #431
244 if (privacy_image_cache_is_local_image($matches[2]))
245 return $matches[1] . $matches[2] . $matches[3];
247 //return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
249 return $matches[1].get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename(htmlspecialchars_decode($matches[2])).$matches[3];
256 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
257 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
263 * Function disabled because the plugin moved
265 function privacy_image_cache_bbcode_hook(&$a, &$o) {
266 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
274 function privacy_image_cache_display_item_hook(&$a, &$o) {
275 if (isset($o["output"])) {
276 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
277 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
278 //$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
279 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
280 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
281 //$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
282 if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
283 $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
284 //$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
293 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
294 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
295 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["photo"]);
296 //$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
302 * @param null|object $b
304 function privacy_image_cache_cron(&$a = null, &$b = null) {
305 $cachetime = get_config('privacy_image_cache','cache_time');
306 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
308 $last = get_config('pi_cache','last_delete');
310 if ($time < ($last + 3600)) return;
312 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
313 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
314 set_config('pi_cache', 'last_delete', $time);
316 clear_cache($a->get_basepath(), $a->get_basepath()."/privacy_image_cache");
324 * @param null|object $o
326 function privacy_image_cache_plugin_admin(&$a, &$o){
329 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
331 $cachetime = get_config('privacy_image_cache','cache_time');
332 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
333 $cachetime_h = Ceil($cachetime / 3600);
335 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
336 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
338 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
340 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
342 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
343 $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;">';
344 $size = Ceil($num[0]['size'] / (1024 * 1024));
345 $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;">';
347 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
353 * @param null|object $o
355 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
356 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
358 if (isset($_REQUEST['save'])) {
359 $cachetime_h = IntVal($_REQUEST['cachetime']);
360 if ($cachetime_h < 1) $cachetime_h = 1;
361 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
363 if (isset($_REQUEST['delete_all'])) {
364 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');