]> git.mxchange.org Git - friendica-addons.git/blob - privacy_image_cache/privacy_image_cache.php
Merge pull request #82 from annando/master
[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         } else {
98                 // It shouldn't happen but it does - spaces in URL
99                 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
100
101                 $img_str = fetch_url($_REQUEST['url'],true);
102
103                 $tempfile = tempnam("", "cache");
104                 file_put_contents($tempfile, $img_str);
105                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
106                 unlink($tempfile);
107
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");
111                         $mime = "image/png";
112                         $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
113                         $img = new Photo($img_str);
114                         if($img->is_valid()) {
115                                 $img->scaleImage(1);
116                                 $img_str = $img->imageString();
117                         }
118                 //} else if (substr($img_str, 0, 6) == "GIF89a") {
119                 } else if ($mime != "image/jpeg") {
120                         $image = @imagecreatefromstring($img_str);
121
122                         if($image === FALSE) die();
123
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"]))),
131                                 dbesc(''),
132                                 intval(imagesy($image)),
133                                 intval(imagesx($image)),
134                                 $mime,
135                                 dbesc($img_str),
136                                 100,
137                                 intval(0),
138                                 dbesc(''), dbesc(''), dbesc(''), dbesc('')
139                         );
140
141                 } else {
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();
147                         }
148                         $mime = "image/jpeg";
149                 }
150         }
151
152         // Writing in cachefile
153         // and (file_exists($cachefile)) and (exif_imagetype($cachefile) > 0))
154         if ($cachefile != '')
155                 file_put_contents($cachefile, $img_str);
156
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");
162
163         echo $img_str;
164
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);
170         }
171
172         killme();
173 }
174
175 /**
176  * @param $url string
177  * @return boolean
178  */
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;
182
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);
187 }
188
189 /**
190  * @param array $matches
191  * @return string
192  */
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];
197
198         return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
199 }
200
201 /**
202  * @param App $a
203  * @param string $o
204  */
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"]);
207 }
208
209 /**
210  * @param App $a
211  * @param string $o
212  * Function disabled because the plugin moved
213  */
214 function privacy_image_cache_bbcode_hook(&$a, &$o) {
215         //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
216 }
217
218
219 /**
220  * @param App $a
221  * @param string $o
222  */
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"])));
231     }
232 }
233
234
235 /**
236  * @param App $a
237  * @param string $o
238  */
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"])));
242 }
243
244
245 /**
246  * @param App $a
247  * @param null|object $b
248  */
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;
252
253     $last = get_config('pi_cache','last_delete');
254     $time = time();
255     if ($time < ($last + 3600)) return;
256
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);
260 }
261
262
263
264
265 /**
266  * @param App $a
267  * @param null|object $o
268  */
269 function privacy_image_cache_plugin_admin(&$a, &$o){
270
271
272     $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
273
274     $cachetime = get_config('privacy_image_cache','cache_time');
275     if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
276     $cachetime_h = Ceil($cachetime / 3600);
277
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;">';
280
281     $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
282
283     $o .= '<h4>' . t('Cache Statistics') . '</h4>';
284
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;">';
289
290     $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
291 }
292
293
294 /**
295  * @param App $a
296  * @param null|object $o
297  */
298 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
299     check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
300
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);
305     }
306     if (isset($_REQUEST['delete_all'])) {
307         q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
308     }
309 }