]> git.mxchange.org Git - friendica-addons.git/blob - privacy_image_cache/privacy_image_cache.php
New cache system (used in privacy_image_cache)
[friendica-addons.git] / privacy_image_cache / privacy_image_cache.php
1 <?php
2
3 /**
4  * Name: Privacy Image Cache
5  * Version: 0.1
6  * Author: Tobias Hößl <https://github.com/CatoTH/>
7  */
8
9 define("PRIVACY_IMAGE_CACHE_DEFAULT_TIME", 86400); // 1 Day
10
11 require_once('include/security.php');
12
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');
19 }
20
21
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');
28 }
29
30
31 function privacy_image_cache_module() {}
32
33
34 function privacy_image_cache_init() {
35         global $a, $_SERVER;
36
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');
47                 }
48                 exit;
49         }
50
51         if ($a->config["system"]["db_log"] != "")
52                 $stamp1 = microtime(true);
53
54         if(function_exists('header_remove')) {
55                 header_remove('Pragma');
56                 header_remove('pragma');
57         }
58
59         $urlhash = 'pic:' . sha1($_REQUEST['url']);
60         // Double encoded url - happens with Diaspora
61         $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
62
63         $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
64         if ($cachefile != '') {
65                 if (file_exists($cachefile)) {
66                         $img_str = file_get_contents($cachefile);
67
68                         $mime = image_type_to_mime_type(exif_imagetype($cachefile));
69
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");
75
76                         echo $img_str;
77
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);
83                         }
84
85                         killme();
86                 }
87         }
88
89         require_once("Photo.php");
90
91         $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
92         if (count($r)) {
93                 $img_str = $r[0]['data'];
94                 $mime = $r[0]["desc"];
95                 if ($mime == "") $mime = "image/jpeg";
96
97                 // Test
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();
103                 //      }
104                 //}
105         } else {
106                 // It shouldn't happen but it does - spaces in URL
107                 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
108
109                 $img_str = fetch_url($_REQUEST['url'],true);
110
111                 $tempfile = tempnam("", "cache");
112                 file_put_contents($tempfile, $img_str);
113                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
114                 unlink($tempfile);
115
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");
119                         $mime = "image/png";
120                 //} else if (substr($img_str, 0, 6) == "GIF89a") {
121                 } else if ($mime != "image/jpeg") {
122                         $image = @imagecreatefromstring($img_str);
123
124                         if($image === FALSE) die();
125
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"]))),
133                                 dbesc(''),
134                                 intval(imagesy($image)),
135                                 intval(imagesx($image)),
136                                 $mime,
137                                 dbesc($img_str),
138                                 100,
139                                 intval(0),
140                                 dbesc(''), dbesc(''), dbesc(''), dbesc('')
141                         );
142
143                 } else {
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();
149                         }
150                         $mime = "image/jpeg";
151                 }
152         }
153
154         // Writing in cachefile
155         // and (file_exists($cachefile)) and (exif_imagetype($cachefile) > 0))
156         if ($cachefile != '')
157                 file_put_contents($cachefile, $img_str);
158
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");
165
166         echo $img_str;
167
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);
173         }
174
175         killme();
176 }
177
178 /**
179  * @param $url string
180  * @return boolean
181  */
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;
185
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);
190 }
191
192 /**
193  * @param array $matches
194  * @return string
195  */
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];
200
201         return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
202 }
203
204 /**
205  * @param App $a
206  * @param string $o
207  */
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"]);
210 }
211
212 /**
213  * @param App $a
214  * @param string $o
215  * Function disabled because the plugin moved
216  */
217 function privacy_image_cache_bbcode_hook(&$a, &$o) {
218         //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
219 }
220
221
222 /**
223  * @param App $a
224  * @param string $o
225  */
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"])));
234     }
235 }
236
237
238 /**
239  * @param App $a
240  * @param string $o
241  */
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"])));
245 }
246
247
248 /**
249  * @param App $a
250  * @param null|object $b
251  */
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;
255
256     $last = get_config('pi_cache','last_delete');
257     $time = time();
258     if ($time < ($last + 3600)) return;
259
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);
263 }
264
265
266
267
268 /**
269  * @param App $a
270  * @param null|object $o
271  */
272 function privacy_image_cache_plugin_admin(&$a, &$o){
273
274
275     $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
276
277     $cachetime = get_config('privacy_image_cache','cache_time');
278     if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
279     $cachetime_h = Ceil($cachetime / 3600);
280
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;">';
283
284     $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
285
286     $o .= '<h4>' . t('Cache Statistics') . '</h4>';
287
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;">';
292
293     $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
294 }
295
296
297 /**
298  * @param App $a
299  * @param null|object $o
300  */
301 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
302     check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
303
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);
308     }
309     if (isset($_REQUEST['delete_all'])) {
310         q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
311     }
312 }