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(function_exists('header_remove')) {
38 header_remove('Pragma');
39 header_remove('pragma');
42 $urlhash = 'pic:' . sha1($_REQUEST['url']);
43 // Double encoded url - happens with Diaspora
44 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
46 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
48 $img_str = $r[0]['data'];
49 $mime = $r[0]["desc"];
50 if ($mime == "") $mime = "image/jpeg";
52 require_once("Photo.php");
54 // It shouldn't happen but it does - spaces in URL
55 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
57 $img_str = fetch_url($_REQUEST['url'],true);
59 $tempfile = tempnam("", "cache");
60 file_put_contents($tempfile, $img_str);
61 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
64 // If there is an error then return a blank image
65 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
66 $img_str = file_get_contents("images/blank.png");
68 //} else if (substr($img_str, 0, 6) == "GIF89a") {
69 } else if ($mime != "image/jpeg") {
70 $image = @imagecreatefromstring($img_str);
72 if($image === FALSE) die();
74 q("INSERT INTO `photo`
75 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
76 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
77 0, 0, get_guid(), dbesc($urlhash),
78 dbesc(datetime_convert()),
79 dbesc(datetime_convert()),
80 dbesc(basename(dbesc($_REQUEST["url"]))),
82 intval(imagesy($image)),
83 intval(imagesx($image)),
88 dbesc(''), dbesc(''), dbesc(''), dbesc('')
92 $img = new Photo($img_str);
93 if($img->is_valid()) {
94 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
95 $img_str = $img->imageString();
101 header("Content-type: $mime");
102 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
103 header("Cache-Control: max-age=" . (3600*24));
114 function privacy_image_cache_is_local_image($url) {
115 if ($url[0] == '/') return true;
116 if (strtolower(substr($url, 0, 5)) == "data:") return true;
118 // links normalised - bug #431
119 $baseurl = normalise_link(get_app()->get_baseurl());
120 $url = normalise_link($url);
121 return (substr($url, 0, strlen($baseurl)) == $baseurl);
125 * @param array $matches
128 function privacy_image_cache_img_cb($matches) {
129 // following line changed per bug #431
130 if (privacy_image_cache_is_local_image($matches[2]))
131 return $matches[1] . $matches[2] . $matches[3];
133 return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
140 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
141 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
147 * Function disabled because the plugin moved
149 function privacy_image_cache_bbcode_hook(&$a, &$o) {
150 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
158 function privacy_image_cache_display_item_hook(&$a, &$o) {
159 if (isset($o["output"])) {
160 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
161 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
162 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
163 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
172 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
173 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
174 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
180 * @param null|object $b
182 function privacy_image_cache_cron(&$a = null, &$b = null) {
183 $cachetime = get_config('privacy_image_cache','cache_time');
184 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
186 $last = get_config('pi_cache','last_delete');
188 if ($time < ($last + 3600)) return;
190 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
191 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
192 set_config('pi_cache', 'last_delete', $time);
200 * @param null|object $o
202 function privacy_image_cache_plugin_admin(&$a, &$o){
205 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
207 $cachetime = get_config('privacy_image_cache','cache_time');
208 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
209 $cachetime_h = Ceil($cachetime / 3600);
211 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
212 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
214 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
216 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
218 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
219 $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;">';
220 $size = Ceil($num[0]['size'] / (1024 * 1024));
221 $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;">';
223 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
229 * @param null|object $o
231 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
232 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
234 if (isset($_REQUEST['save'])) {
235 $cachetime_h = IntVal($_REQUEST['cachetime']);
236 if ($cachetime_h < 1) $cachetime_h = 1;
237 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
239 if (isset($_REQUEST['delete_all'])) {
240 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');