4 * Name: Privacy Image Cache
6 * Author: Tobias Hößl <https://github.com/CatoTH/>
10 define("PRIVACY_IMAGE_CACHE_DEFAULT_TIME", 86400); // 1 Day
12 require_once('include/security.php');
13 require_once("include/Photo.php");
15 function privacy_image_cache_install() {
16 register_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
17 // register_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
18 register_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
19 register_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
20 register_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
24 function privacy_image_cache_uninstall() {
25 unregister_hook('prepare_body', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_prepare_body_hook');
26 unregister_hook('bbcode', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_bbcode_hook');
27 unregister_hook('display_item', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_display_item_hook');
28 unregister_hook('ping_xmlize', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_ping_xmlize_hook');
29 unregister_hook('cron', 'addon/privacy_image_cache/privacy_image_cache.php', 'privacy_image_cache_cron');
33 function privacy_image_cache_module() {}
35 function privacy_image_cache_init() {
38 // The code needs to be reworked, it is too complicated
40 // it is doing the following:
41 // 1. If a folder "privacy_image_cache" exists and is writeable, then use this for caching
42 // 2. If a cache path is defined, use this
43 // 3. If everything else failed, cache into the database
45 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
46 header('HTTP/1.1 304 Not Modified');
47 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
48 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
49 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
50 header("Cache-Control: max-age=31536000");
51 if(function_exists('header_remove')) {
52 header_remove('Last-Modified');
53 header_remove('Expires');
54 header_remove('Cache-Control');
59 if(function_exists('header_remove')) {
60 header_remove('Pragma');
61 header_remove('pragma');
67 // If the cache path isn't there, try to create it
68 if (!is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
69 if (is_writable($_SERVER["DOCUMENT_ROOT"]))
70 mkdir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache");
72 // Checking if caching into a folder in the webroot is activated and working
73 $direct_cache = (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache") AND is_writable($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"));
75 // Look for filename in the arguments
76 if (isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) {
77 if (isset($a->argv[3]))
79 elseif (isset($a->argv[2]))
84 //$thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
85 if (isset($a->argv[3]) and ($a->argv[3] == "thumb"))
88 // thumb, small, medium and large.
89 if (substr($url, -6) == ":thumb")
91 if (substr($url, -6) == ":small")
93 if (substr($url, -7) == ":medium")
95 if (substr($url, -6) == ":large")
98 $pos = strrpos($url, "=.");
100 $url = substr($url, 0, $pos+1);
102 $url = str_replace(array(".jpg", ".jpeg", ".gif", ".png"), array("","","",""), $url);
104 $url = base64_decode(strtr($url, '-_', '+/'), true);
107 $_REQUEST['url'] = $url;
110 if (!$direct_cache) {
111 $urlhash = 'pic:' . sha1($_REQUEST['url']);
112 // Double encoded url - happens with Diaspora
113 $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
115 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
116 if ($cachefile != '') {
117 if (file_exists($cachefile)) {
118 $img_str = file_get_contents($cachefile);
119 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
121 header("Content-type: $mime");
122 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
123 header('Etag: "'.md5($img_str).'"');
124 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
125 header("Cache-Control: max-age=31536000");
127 // reduce quality - if it isn't a GIF
128 if ($mime != "image/gif") {
129 $img = new Photo($img_str, $mime);
130 if($img->is_valid()) {
131 $img_str = $img->imageString();
144 if (!$direct_cache AND ($cachefile == "")) {
145 $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
147 $img_str = $r[0]['data'];
148 $mime = $r[0]["desc"];
149 if ($mime == "") $mime = "image/jpeg";
155 // It shouldn't happen but it does - spaces in URL
156 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
158 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
160 $tempfile = tempnam(get_temppath(), "cache");
161 file_put_contents($tempfile, $img_str);
162 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
165 // If there is an error then return a blank image
166 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
167 $img_str = file_get_contents("images/blank.png");
169 $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
171 $img = new Photo($img_str, "image/png");
172 if($img->is_valid()) {
173 $img->scaleImage(10);
174 $img_str = $img->imageString();
176 } else if (($mime != "image/jpeg") AND !$direct_cache AND ($cachefile == "")) {
177 $image = @imagecreatefromstring($img_str);
179 if($image === FALSE) die();
181 q("INSERT INTO `photo`
182 ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
183 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
184 0, 0, get_guid(), dbesc($urlhash),
185 dbesc(datetime_convert()),
186 dbesc(datetime_convert()),
187 dbesc(basename(dbesc($_REQUEST["url"]))),
189 intval(imagesy($image)),
190 intval(imagesx($image)),
195 dbesc(''), dbesc(''), dbesc(''), dbesc('')
199 $img = new Photo($img_str, $mime);
200 if($img->is_valid()) {
201 if (!$direct_cache AND ($cachefile == ""))
202 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
205 // $img->scaleImage(200); // Test
206 // $img_str = $img->imageString();
209 //$mime = "image/jpeg";
213 // reduce quality - if it isn't a GIF
214 if ($mime != "image/gif") {
215 $img = new Photo($img_str, $mime);
216 if($img->is_valid()) {
217 //$img->scaleImage(1024); // Test
218 $img->scaleImage($size);
219 $img_str = $img->imageString();
223 // If there is a real existing directory then put the cache file there
224 // advantage: real file access is really fast
225 // Otherwise write in cachefile
226 if ($valid AND $direct_cache)
227 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
228 elseif ($cachefile != '')
229 file_put_contents($cachefile, $img_str);
231 header("Content-type: $mime");
233 // Only output the cache headers when the file is valid
235 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
236 header('Etag: "'.md5($img_str).'"');
237 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
238 header("Cache-Control: max-age=31536000");
246 function privacy_image_cache_cachename($url, $writemode = false) {
249 $pos = strrpos($url, ".");
251 $extension = strtolower(substr($url, $pos+1));
252 $pos = strpos($extension, "?");
254 $extension = substr($extension, 0, $pos);
257 $basepath = $_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache";
259 $path = substr(hash("md5", $url), 0, 2);
261 if (is_dir($basepath) and $writemode)
262 if (!is_dir($basepath."/".$path)) {
263 mkdir($basepath."/".$path);
264 chmod($basepath."/".$path, 0777);
267 $path .= "/".strtr(base64_encode($url), '+/', '-_');
269 $extensions = array("jpg", "jpeg", "gif", "png");
271 if (in_array($extension, $extensions))
272 $path .= ".".$extension;
281 function privacy_image_cache_is_local_image($url) {
282 if ($url[0] == '/') return true;
284 if (strtolower(substr($url, 0, 5)) == "data:") return true;
286 // Check if the cached path would be longer than 255 characters - apache doesn't like it
287 if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache")) {
288 $cachedurl = get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename($url);
289 if (strlen($url) > 150)
293 // links normalised - bug #431
294 $baseurl = normalise_link(get_app()->get_baseurl());
295 $url = normalise_link($url);
296 return (substr($url, 0, strlen($baseurl)) == $baseurl);
300 * @param array $matches
303 function privacy_image_cache_img_cb($matches) {
305 // if the picture seems to be from another picture cache then take the original source
306 $queryvar = privacy_image_cache_parse_query($matches[2]);
307 if (($queryvar['url'] != "") AND (substr($queryvar['url'], 0, 4) == "http"))
308 $matches[2] = urldecode($queryvar['url']);
310 // if fetching facebook pictures don't fetch the thumbnail but the big one
311 //if (((strpos($matches[2], ".fbcdn.net/") OR strpos($matches[2], "/fbcdn-photos-"))) and (substr($matches[2], -6) == "_s.jpg"))
312 // $matches[2] = substr($matches[2], 0, -6)."_n.jpg";
314 // following line changed per bug #431
315 if (privacy_image_cache_is_local_image($matches[2]))
316 return $matches[1] . $matches[2] . $matches[3];
318 //return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
320 return $matches[1].get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename(htmlspecialchars_decode($matches[2])).$matches[3];
327 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
328 $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
334 * Function disabled because the plugin moved
336 function privacy_image_cache_bbcode_hook(&$a, &$o) {
337 //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
345 function privacy_image_cache_display_item_hook(&$a, &$o) {
346 if (isset($o["output"])) {
347 if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
348 $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
349 if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
350 $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
351 if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
352 $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
353 if (isset($o["output"]["owner_photo"]) && !privacy_image_cache_is_local_image($o["output"]["owner_photo"]))
354 $o["output"]["owner_photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner_photo"]);
363 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
364 if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
365 $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["photo"]);
366 //$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
372 * @param null|object $b
374 function privacy_image_cache_cron(&$a = null, &$b = null) {
375 $cachetime = get_config('privacy_image_cache','cache_time');
376 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
378 $last = get_config('pi_cache','last_delete');
380 if ($time < ($last + 3600)) return;
382 logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
383 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
385 clear_cache($a->get_basepath(), $a->get_basepath()."/privacy_image_cache");
387 set_config('pi_cache', 'last_delete', $time);
392 * @param null|object $o
394 function privacy_image_cache_plugin_admin(&$a, &$o){
397 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
399 $cachetime = get_config('privacy_image_cache','cache_time');
400 if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
401 $cachetime_h = Ceil($cachetime / 3600);
403 $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
404 <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
406 $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
408 $o .= '<h4>' . t('Cache Statistics') . '</h4>';
410 $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
411 $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;">';
412 $size = Ceil($num[0]['size'] / (1024 * 1024));
413 $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;">';
415 $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
421 * @param null|object $o
423 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
424 check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
426 if (isset($_REQUEST['save'])) {
427 $cachetime_h = IntVal($_REQUEST['cachetime']);
428 if ($cachetime_h < 1) $cachetime_h = 1;
429 set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
431 if (isset($_REQUEST['delete_all'])) {
432 q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
436 function privacy_image_cache_parse_query($var) {
438 * Use this function to parse out the query array element from
439 * the output of parse_url().
441 $var = parse_url($var, PHP_URL_QUERY);
442 $var = html_entity_decode($var);
443 $var = explode('&', $var);
446 foreach($var as $val) {
447 $x = explode('=', $val);
451 unset($val, $x, $var);