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');
12 require_once("include/Photo.php");
14 function privacy_image_cache_install() {
15 register_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
16 // register_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
17 register_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
18 register_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
19 register_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
23 function privacy_image_cache_uninstall() {
24 unregister_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
25 unregister_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
26 unregister_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
27 unregister_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
28 unregister_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
32 function privacy_image_cache_module() {}
34 function privacy_image_cache_init() {
37 // The code needs to be reworked, it is too complicated
39 // it is doing the following:
40 // 1. If a folder "privacy_image_cache" exists and is writeable, then use this for caching
41 // 2. If a cache path is defined, use this
42 // 3. If everything else failed, cache into the database
44 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
45 header('HTTP/1.1 304 Not Modified');
46 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
47 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
48 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
49 header("Cache-Control: max-age=31536000");
50 if(function_exists('header_remove')) {
51 header_remove('Last-Modified');
52 header_remove('Expires');
53 header_remove('Cache-Control');
58 if(function_exists('header_remove')) {
59 header_remove('Pragma');
60 header_remove('pragma');
65 // If the cache path isn't there, try to create it
66 if (!is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
67 if (is_writable($_SERVER["DOCUMENT_ROOT"]))
68 mkdir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache");
70 // Checking if caching into a folder in the webroot is activated and working
71 $direct_cache = (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache") AND is_writable($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"));
73 // Look for filename in the arguments
74 if (isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) {
75 if (isset($a->argv[3]))
77 elseif (isset($a->argv[2]))
82 $pos = strrpos($url, "=.");
84 $url = substr($url, 0, $pos+1);
86 $url = str_replace(array(".jpg", ".jpeg", ".gif", ".png"), array("","","",""), $url);
88 $url = base64_decode(strtr($url, '-_', '+/'), true);
91 $_REQUEST['url'] = $url;
92 $thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
96 $urlhash = 'pic:' . sha1($_REQUEST['url']);
97 // Double encoded url - happens with Diaspora
98 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
100 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
101 if ($cachefile != '') {
102 if (file_exists($cachefile)) {
103 $img_str = file_get_contents($cachefile);
104 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
106 header("Content-type: $mime");
107 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
108 header('Etag: "'.md5($img_str).'"');
109 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
110 header("Cache-Control: max-age=31536000");
112 // reduce quality - if it isn't a GIF
113 if ($mime != "image/gif") {
114 $img = new Photo($img_str, $mime);
115 if($img->is_valid()) {
116 $img_str = $img->imageString();
129 if (!$direct_cache AND ($cachefile == "")) {
130 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
132 $img_str = $r[0]['data'];
133 $mime = $r[0]["desc"];
134 if ($mime == "") $mime = "image/jpeg";
140 // It shouldn't happen but it does - spaces in URL
141 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
143 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
145 $tempfile = tempnam(get_config("system","temppath"), "cache");
146 file_put_contents($tempfile, $img_str);
147 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
150 // If there is an error then return a blank image
151 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
152 $img_str = file_get_contents("images/blank.png");
154 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
156 $img = new Photo($img_str, "image/png");
157 if($img->is_valid()) {
158 $img->scaleImage(10);
159 $img_str = $img->imageString();
161 } else if (($mime != "image/jpeg") AND !$direct_cache AND ($cachefile == "")) {
162 $image = @imagecreatefromstring($img_str);
164 if($image === FALSE) die();
166 q("INSERT INTO `photo`
167 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
168 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
169 0, 0, get_guid(), dbesc($urlhash),
170 dbesc(datetime_convert()),
171 dbesc(datetime_convert()),
172 dbesc(basename(dbesc($_REQUEST["url"]))),
174 intval(imagesy($image)),
175 intval(imagesx($image)),
180 dbesc(''), dbesc(''), dbesc(''), dbesc('')
184 $img = new Photo($img_str, $mime);
185 if($img->is_valid()) {
186 if (!$direct_cache AND ($cachefile == ""))
187 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
190 $img->scaleImage(200); // Test
191 $img_str = $img->imageString();
194 //$mime = "image/jpeg";
198 // reduce quality - if it isn't a GIF
199 if ($mime != "image/gif") {
200 $img = new Photo($img_str, $mime);
201 if($img->is_valid()) {
202 $img->scaleImage(1024); // Test
203 $img_str = $img->imageString();
207 // If there is a real existing directory then put the cache file there
208 // advantage: real file access is really fast
209 // Otherwise write in cachefile
210 if ($valid AND $direct_cache)
211 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
212 elseif ($cachefile != '')
213 file_put_contents($cachefile, $img_str);
215 header("Content-type: $mime");
217 // Only output the cache headers when the file is valid
219 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
220 header('Etag: "'.md5($img_str).'"');
221 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
222 header("Cache-Control: max-age=31536000");
230 function privacy_image_cache_cachename($url, $writemode = false) {
233 $pos = strrpos($url, ".");
235 $extension = strtolower(substr($url, $pos+1));
236 $pos = strpos($extension, "?");
238 $extension = substr($extension, 0, $pos);
241 $basepath = $_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache";
243 $path = substr(hash("md5", $url), 0, 2);
245 if (is_dir($basepath) and $writemode)
246 if (!is_dir($basepath."/".$path)) {
247 mkdir($basepath."/".$path);
248 chmod($basepath."/".$path, 0777);
251 $path .= "/".strtr(base64_encode($url), '+/', '-_');
253 $extensions = array("jpg", "jpeg", "gif", "png");
255 if (in_array($extension, $extensions))
256 $path .= ".".$extension;
265 function privacy_image_cache_is_local_image($url) {
266 if ($url[0] == '/') return true;
268 if (strtolower(substr($url, 0, 5)) == "data:") return true;
270 // Check if the cached path would be longer than 255 characters - apache doesn't like it
271 if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache")) {
272 $cachedurl = get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename($url);
273 if (strlen($url) > 150)
277 // links normalised - bug #431
278 $baseurl = normalise_link(get_app()->get_baseurl());
279 $url = normalise_link($url);
280 return (substr($url, 0, strlen($baseurl)) == $baseurl);
284 * @param array $matches
287 function privacy_image_cache_img_cb($matches) {
289 // if the picture seems to be from another picture cache then take the original source
290 $queryvar = privacy_image_cache_parse_query($matches[2]);
291 if ($queryvar['url'] != "")
292 $matches[2] = urldecode($queryvar['url']);
294 // if fetching facebook pictures don't fetch the thumbnail but the big one
295 if (strpos($matches[2], ".fbcdn.net/") and (substr($matches[2], -6) == "_s.jpg"))
296 $matches[2] = substr($matches[2], 0, -6)."_n.jpg";
298 // following line changed per bug #431
299 if (privacy_image_cache_is_local_image($matches[2]))
300 return $matches[1] . $matches[2] . $matches[3];
302 //return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
304 return $matches[1].get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename(htmlspecialchars_decode($matches[2])).$matches[3];
311 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
312 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
318 * Function disabled because the plugin moved
320 function privacy_image_cache_bbcode_hook(&$a, &$o) {
321 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
329 function privacy_image_cache_display_item_hook(&$a, &$o) {
330 if (isset($o["output"])) {
331 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
332 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
333 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
334 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
335 if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
336 $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
337 if (isset($o["output"]["owner_photo"]) && !privacy_image_cache_is_local_image($o["output"]["owner_photo"]))
338 $o["output"]["owner_photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner_photo"]);
347 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
348 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
349 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["photo"]);
350 //$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
356 * @param null|object $b
358 function privacy_image_cache_cron(&$a = null, &$b = null) {
359 $cachetime = get_config('privacy_image_cache','cache_time');
360 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
362 $last = get_config('pi_cache','last_delete');
364 if ($time < ($last + 3600)) return;
366 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
367 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
369 clear_cache($a->get_basepath(), $a->get_basepath()."/privacy_image_cache");
371 set_config('pi_cache', 'last_delete', $time);
376 * @param null|object $o
378 function privacy_image_cache_plugin_admin(&$a, &$o){
381 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
383 $cachetime = get_config('privacy_image_cache','cache_time');
384 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
385 $cachetime_h = Ceil($cachetime / 3600);
387 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
388 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
390 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
392 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
394 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
395 $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;">';
396 $size = Ceil($num[0]['size'] / (1024 * 1024));
397 $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;">';
399 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
405 * @param null|object $o
407 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
408 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
410 if (isset($_REQUEST['save'])) {
411 $cachetime_h = IntVal($_REQUEST['cachetime']);
412 if ($cachetime_h < 1) $cachetime_h = 1;
413 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
415 if (isset($_REQUEST['delete_all'])) {
416 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
420 function privacy_image_cache_parse_query($var) {
422 * Use this function to parse out the query array element from
423 * the output of parse_url().
425 $var = parse_url($var, PHP_URL_QUERY);
426 $var = html_entity_decode($var);
427 $var = explode('&', $var);
430 foreach($var as $val) {
431 $x = explode('=', $val);
435 unset($val, $x, $var);