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 (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');
59 $urlhash = 'pic:' . sha1($_REQUEST['url']);
60 // Double encoded url - happens with Diaspora
61 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
63 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
64 if ($cachefile != '') {
65 if (file_exists($cachefile)) {
66 $img_str = file_get_contents($cachefile);
68 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
70 header("Content-type: $mime");
71 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
72 header('Etag: "'.md5($img_str).'"');
73 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
74 header("Cache-Control: max-age=31536000");
78 if ($a->config["system"]["db_log"] != "") {
79 $stamp2 = microtime(true);
80 $duration = round($stamp2-$stamp1, 3);
81 if ($duration > $a->config["system"]["db_loglimit"])
82 @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
89 require_once("Photo.php");
91 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
93 $img_str = $r[0]['data'];
94 $mime = $r[0]["desc"];
95 if ($mime == "") $mime = "image/jpeg";
98 //if ($mime == "image/jpeg") {
99 // $img = new Photo($img_str);
100 // if($img->is_valid()) {
101 // $img->scaleImage(1000);
102 // $img_str = $img->imageString();
106 // It shouldn't happen but it does - spaces in URL
107 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
109 $img_str = fetch_url($_REQUEST['url'],true);
111 $tempfile = tempnam("", "cache");
112 file_put_contents($tempfile, $img_str);
113 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
116 // If there is an error then return a blank image
117 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
118 $img_str = file_get_contents("images/blank.png");
120 //} else if (substr($img_str, 0, 6) == "GIF89a") {
121 } else if ($mime != "image/jpeg") {
122 $image = @imagecreatefromstring($img_str);
124 if($image === FALSE) die();
126 q("INSERT INTO `photo`
127 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
128 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
129 0, 0, get_guid(), dbesc($urlhash),
130 dbesc(datetime_convert()),
131 dbesc(datetime_convert()),
132 dbesc(basename(dbesc($_REQUEST["url"]))),
134 intval(imagesy($image)),
135 intval(imagesx($image)),
140 dbesc(''), dbesc(''), dbesc(''), dbesc('')
144 $img = new Photo($img_str);
145 if($img->is_valid()) {
146 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
147 //$img->scaleImage(1000); // Test
148 $img_str = $img->imageString();
150 $mime = "image/jpeg";
154 // Writing in cachefile
155 // and (file_exists($cachefile)) and (exif_imagetype($cachefile) > 0))
156 if ($cachefile != '')
157 file_put_contents($cachefile, $img_str);
159 header("Content-type: $mime");
160 //header("Last-Modified: Sat, 01 Apr 1999 12:23:42 GMT");
161 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
162 header('Etag: "'.md5($img_str).'"');
163 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
164 header("Cache-Control: max-age=31536000");
168 if ($a->config["system"]["db_log"] != "") {
169 $stamp2 = microtime(true);
170 $duration = round($stamp2-$stamp1, 3);
171 if ($duration > $a->config["system"]["db_loglimit"])
172 @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
182 function privacy_image_cache_is_local_image($url) {
183 if ($url[0] == '/') return true;
184 if (strtolower(substr($url, 0, 5)) == "data:") return true;
186 // links normalised - bug #431
187 $baseurl = normalise_link(get_app()->get_baseurl());
188 $url = normalise_link($url);
189 return (substr($url, 0, strlen($baseurl)) == $baseurl);
193 * @param array $matches
196 function privacy_image_cache_img_cb($matches) {
197 // following line changed per bug #431
198 if (privacy_image_cache_is_local_image($matches[2]))
199 return $matches[1] . $matches[2] . $matches[3];
201 return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
208 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
209 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
215 * Function disabled because the plugin moved
217 function privacy_image_cache_bbcode_hook(&$a, &$o) {
218 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
226 function privacy_image_cache_display_item_hook(&$a, &$o) {
227 if (isset($o["output"])) {
228 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
229 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
230 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
231 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
232 if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
233 $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
242 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
243 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
244 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
250 * @param null|object $b
252 function privacy_image_cache_cron(&$a = null, &$b = null) {
253 $cachetime = get_config('privacy_image_cache','cache_time');
254 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
256 $last = get_config('pi_cache','last_delete');
258 if ($time < ($last + 3600)) return;
260 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
261 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
262 set_config('pi_cache', 'last_delete', $time);
270 * @param null|object $o
272 function privacy_image_cache_plugin_admin(&$a, &$o){
275 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
277 $cachetime = get_config('privacy_image_cache','cache_time');
278 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
279 $cachetime_h = Ceil($cachetime / 3600);
281 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
282 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
284 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
286 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
288 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
289 $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;">';
290 $size = Ceil($num[0]['size'] / (1024 * 1024));
291 $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;">';
293 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
299 * @param null|object $o
301 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
302 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
304 if (isset($_REQUEST['save'])) {
305 $cachetime_h = IntVal($_REQUEST['cachetime']);
306 if ($cachetime_h < 1) $cachetime_h = 1;
307 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
309 if (isset($_REQUEST['delete_all'])) {
310 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');