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() {}
34 function privacy_image_cache_init() {
37 if ($a->config["system"]["db_log"] != "")
38 $stamp1 = microtime(true);
40 if(function_exists('header_remove')) {
41 header_remove('Pragma');
42 header_remove('pragma');
45 $urlhash = 'pic:' . sha1($_REQUEST['url']);
46 // Double encoded url - happens with Diaspora
47 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
49 $cache = get_config('system','itemcache');
50 if (($cache != '') and is_dir($cache)) {
51 $cachefile = $cache."/".hash("md5", $_REQUEST['url']);
52 if (file_exists($cachefile)) {
53 $img_str = file_get_contents($cachefile);
55 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
57 header("Content-type: $mime");
58 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
59 header("Cache-Control: max-age=" . (3600*24));
63 if ($a->config["system"]["db_log"] != "") {
64 $stamp2 = microtime(true);
65 $duration = round($stamp2-$stamp1, 3);
66 if ($duration > $a->config["system"]["db_loglimit"])
67 @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
74 require_once("Photo.php");
76 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
78 $img_str = $r[0]['data'];
79 $mime = $r[0]["desc"];
80 if ($mime == "") $mime = "image/jpeg";
83 //if ($mime == "image/jpeg") {
84 // $img = new Photo($img_str);
85 // if($img->is_valid()) {
86 // $img->scaleImage(1000);
87 // $img_str = $img->imageString();
91 // It shouldn't happen but it does - spaces in URL
92 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
94 $img_str = fetch_url($_REQUEST['url'],true);
96 $tempfile = tempnam("", "cache");
97 file_put_contents($tempfile, $img_str);
98 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
101 // If there is an error then return a blank image
102 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
103 $img_str = file_get_contents("images/blank.png");
105 //} else if (substr($img_str, 0, 6) == "GIF89a") {
106 } else if ($mime != "image/jpeg") {
107 $image = @imagecreatefromstring($img_str);
109 if($image === FALSE) die();
111 q("INSERT INTO `photo`
112 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
113 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
114 0, 0, get_guid(), dbesc($urlhash),
115 dbesc(datetime_convert()),
116 dbesc(datetime_convert()),
117 dbesc(basename(dbesc($_REQUEST["url"]))),
119 intval(imagesy($image)),
120 intval(imagesx($image)),
125 dbesc(''), dbesc(''), dbesc(''), dbesc('')
129 $img = new Photo($img_str);
130 if($img->is_valid()) {
131 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
132 //$img->scaleImage(1000); // Test
133 $img_str = $img->imageString();
135 $mime = "image/jpeg";
139 // Writing in cachefile
140 if (isset($cachefile) && ($cachefile != '') and (file_exists($cachefile)) and (exif_imagetype($cachefile) > 0))
141 file_put_contents($cachefile, $img_str);
143 header("Content-type: $mime");
144 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
145 header("Cache-Control: max-age=" . (3600*24));
149 if ($a->config["system"]["db_log"] != "") {
150 $stamp2 = microtime(true);
151 $duration = round($stamp2-$stamp1, 3);
152 if ($duration > $a->config["system"]["db_loglimit"])
153 @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
163 function privacy_image_cache_is_local_image($url) {
164 if ($url[0] == '/') return true;
165 if (strtolower(substr($url, 0, 5)) == "data:") return true;
167 // links normalised - bug #431
168 $baseurl = normalise_link(get_app()->get_baseurl());
169 $url = normalise_link($url);
170 return (substr($url, 0, strlen($baseurl)) == $baseurl);
174 * @param array $matches
177 function privacy_image_cache_img_cb($matches) {
178 // following line changed per bug #431
179 if (privacy_image_cache_is_local_image($matches[2]))
180 return $matches[1] . $matches[2] . $matches[3];
182 return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
189 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
190 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
196 * Function disabled because the plugin moved
198 function privacy_image_cache_bbcode_hook(&$a, &$o) {
199 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
207 function privacy_image_cache_display_item_hook(&$a, &$o) {
208 if (isset($o["output"])) {
209 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
210 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
211 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
212 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
221 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
222 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
223 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
229 * @param null|object $b
231 function privacy_image_cache_cron(&$a = null, &$b = null) {
232 $cachetime = get_config('privacy_image_cache','cache_time');
233 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
235 $last = get_config('pi_cache','last_delete');
237 if ($time < ($last + 3600)) return;
239 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
240 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
241 set_config('pi_cache', 'last_delete', $time);
249 * @param null|object $o
251 function privacy_image_cache_plugin_admin(&$a, &$o){
254 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
256 $cachetime = get_config('privacy_image_cache','cache_time');
257 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
258 $cachetime_h = Ceil($cachetime / 3600);
260 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
261 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
263 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
265 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
267 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
268 $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;">';
269 $size = Ceil($num[0]['size'] / (1024 * 1024));
270 $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;">';
272 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
278 * @param null|object $o
280 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
281 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
283 if (isset($_REQUEST['save'])) {
284 $cachetime_h = IntVal($_REQUEST['cachetime']);
285 if ($cachetime_h < 1) $cachetime_h = 1;
286 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
288 if (isset($_REQUEST['delete_all'])) {
289 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');