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 // It shouldn't happen but it does - spaces in URL
99 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
101 $img_str = fetch_url($_REQUEST['url'],true);
103 $tempfile = tempnam("", "cache");
104 file_put_contents($tempfile, $img_str);
105 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
108 // If there is an error then return a blank image
109 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
110 $img_str = file_get_contents("images/blank.png");
112 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
113 $img = new Photo($img_str);
114 if($img->is_valid()) {
116 $img_str = $img->imageString();
118 //} else if (substr($img_str, 0, 6) == "GIF89a") {
119 } else if ($mime != "image/jpeg") {
120 $image = @imagecreatefromstring($img_str);
122 if($image === FALSE) die();
124 q("INSERT INTO `photo`
125 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
126 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
127 0, 0, get_guid(), dbesc($urlhash),
128 dbesc(datetime_convert()),
129 dbesc(datetime_convert()),
130 dbesc(basename(dbesc($_REQUEST["url"]))),
132 intval(imagesy($image)),
133 intval(imagesx($image)),
138 dbesc(''), dbesc(''), dbesc(''), dbesc('')
142 $img = new Photo($img_str);
143 if($img->is_valid()) {
144 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
145 //$img->scaleImage(1000); // Test
146 $img_str = $img->imageString();
148 $mime = "image/jpeg";
152 // Writing in cachefile
153 // and (file_exists($cachefile)) and (exif_imagetype($cachefile) > 0))
154 if ($cachefile != '')
155 file_put_contents($cachefile, $img_str);
157 header("Content-type: $mime");
158 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
159 header('Etag: "'.md5($img_str).'"');
160 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
161 header("Cache-Control: max-age=31536000");
165 if ($a->config["system"]["db_log"] != "") {
166 $stamp2 = microtime(true);
167 $duration = round($stamp2-$stamp1, 3);
168 if ($duration > $a->config["system"]["db_loglimit"])
169 @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
179 function privacy_image_cache_is_local_image($url) {
180 if ($url[0] == '/') return true;
181 if (strtolower(substr($url, 0, 5)) == "data:") return true;
183 // links normalised - bug #431
184 $baseurl = normalise_link(get_app()->get_baseurl());
185 $url = normalise_link($url);
186 return (substr($url, 0, strlen($baseurl)) == $baseurl);
190 * @param array $matches
193 function privacy_image_cache_img_cb($matches) {
194 // following line changed per bug #431
195 if (privacy_image_cache_is_local_image($matches[2]))
196 return $matches[1] . $matches[2] . $matches[3];
198 return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
205 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
206 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
212 * Function disabled because the plugin moved
214 function privacy_image_cache_bbcode_hook(&$a, &$o) {
215 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
223 function privacy_image_cache_display_item_hook(&$a, &$o) {
224 if (isset($o["output"])) {
225 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
226 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
227 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
228 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
229 if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
230 $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
239 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
240 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
241 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
247 * @param null|object $b
249 function privacy_image_cache_cron(&$a = null, &$b = null) {
250 $cachetime = get_config('privacy_image_cache','cache_time');
251 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
253 $last = get_config('pi_cache','last_delete');
255 if ($time < ($last + 3600)) return;
257 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
258 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
259 set_config('pi_cache', 'last_delete', $time);
267 * @param null|object $o
269 function privacy_image_cache_plugin_admin(&$a, &$o){
272 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
274 $cachetime = get_config('privacy_image_cache','cache_time');
275 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
276 $cachetime_h = Ceil($cachetime / 3600);
278 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
279 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
281 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
283 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
285 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
286 $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;">';
287 $size = Ceil($num[0]['size'] / (1024 * 1024));
288 $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;">';
290 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
296 * @param null|object $o
298 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
299 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
301 if (isset($_REQUEST['save'])) {
302 $cachetime_h = IntVal($_REQUEST['cachetime']);
303 if ($cachetime_h < 1) $cachetime_h = 1;
304 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
306 if (isset($_REQUEST['delete_all'])) {
307 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');