]> git.mxchange.org Git - friendica-addons.git/blob - privacy_image_cache/privacy_image_cache.php
privacy_image_cache: using another hook that only is used for displaying the page
[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;
36
37         if(function_exists('header_remove')) {
38                 header_remove('Pragma');
39                 header_remove('pragma');
40         }
41
42         $urlhash = 'pic:' . sha1($_REQUEST['url']);
43         // Double encoded url - happens with Diaspora
44         $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
45
46         $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
47         if (count($r)) {
48                 $img_str = $r[0]['data'];
49                 $mime = $r[0]["desc"];
50                 if ($mime == "") $mime = "image/jpeg";
51         } else {
52                 require_once("Photo.php");
53
54                 $img_str = fetch_url($_REQUEST['url'],true);
55
56                 $tempfile = tempnam("", "cache");
57                 file_put_contents($tempfile, $img_str);
58                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
59                 unlink($tempfile);
60
61                 // If there is an error then return a blank image
62                 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
63                         $img_str = file_get_contents("images/blank.png");
64                         $mime = "image/png";
65                 //} else if (substr($img_str, 0, 6) == "GIF89a") {
66                 } else if ($mime != "image/jpeg") {
67                         $image = @imagecreatefromstring($img_str);
68
69                         if($image === FALSE) die();
70
71                         q("INSERT INTO `photo`
72                         ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
73                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
74                                 0, 0, get_guid(), dbesc($urlhash),
75                                 dbesc(datetime_convert()),
76                                 dbesc(datetime_convert()),
77                                 dbesc(basename(dbesc($_REQUEST["url"]))),
78                                 dbesc(''),
79                                 intval(imagesy($image)),
80                                 intval(imagesx($image)),
81                                 $mime,
82                                 dbesc($img_str),
83                                 100,
84                                 intval(0),
85                                 dbesc(''), dbesc(''), dbesc(''), dbesc('')
86                         );
87
88                 } else {
89                         $img = new Photo($img_str);
90                         if($img->is_valid()) {
91                                 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
92                                 $img_str = $img->imageString();
93                         }
94                         $mime = "image/jpeg";
95                 }
96         }
97
98         header("Content-type: $mime");
99         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
100         header("Cache-Control: max-age=" . (3600*24));
101
102         echo $img_str;
103
104         killme();
105 }
106
107 /**
108  * @param $url string
109  * @return boolean
110  */
111 function privacy_image_cache_is_local_image($url) {
112     if ($url[0] == '/') return true;
113         if (strtolower(substr($url, 0, 5)) == "data:") return true;
114
115         // links normalised - bug #431
116     $baseurl = normalise_link(get_app()->get_baseurl());
117         $url = normalise_link($url);
118     return (substr($url, 0, strlen($baseurl)) == $baseurl);
119 }
120
121 /**
122  * @param array $matches
123  * @return string
124  */
125 function privacy_image_cache_img_cb($matches) {
126         // following line changed per bug #431
127         if (privacy_image_cache_is_local_image($matches[2]))
128                 return $matches[1] . $matches[2] . $matches[3];
129
130         return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($matches[2]))) . $matches[3];
131 }
132
133 /**
134  * @param App $a
135  * @param string $o
136  */
137 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
138         $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
139 }
140
141 /**
142  * @param App $a
143  * @param string $o
144  * Function disabled because the plugin moved
145  */
146 function privacy_image_cache_bbcode_hook(&$a, &$o) {
147         //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
148 }
149
150
151 /**
152  * @param App $a
153  * @param string $o
154  */
155 function privacy_image_cache_display_item_hook(&$a, &$o) {
156     if (isset($o["output"])) {
157         if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
158             $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
159         if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
160             $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
161     }
162 }
163
164
165 /**
166  * @param App $a
167  * @param string $o
168  */
169 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
170     if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
171         $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
172 }
173
174
175 /**
176  * @param App $a
177  * @param null|object $b
178  */
179 function privacy_image_cache_cron(&$a = null, &$b = null) {
180     $cachetime = get_config('privacy_image_cache','cache_time');
181     if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
182
183     $last = get_config('pi_cache','last_delete');
184     $time = time();
185     if ($time < ($last + 3600)) return;
186
187     logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
188     q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
189     set_config('pi_cache', 'last_delete', $time);
190 }
191
192
193
194
195 /**
196  * @param App $a
197  * @param null|object $o
198  */
199 function privacy_image_cache_plugin_admin(&$a, &$o){
200
201
202     $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
203
204     $cachetime = get_config('privacy_image_cache','cache_time');
205     if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
206     $cachetime_h = Ceil($cachetime / 3600);
207
208     $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
209         <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
210
211     $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
212
213     $o .= '<h4>' . t('Cache Statistics') . '</h4>';
214
215     $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
216     $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;">';
217     $size = Ceil($num[0]['size'] / (1024 * 1024));
218     $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;">';
219
220     $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
221 }
222
223
224 /**
225  * @param App $a
226  * @param null|object $o
227  */
228 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
229     check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
230
231     if (isset($_REQUEST['save'])) {
232         $cachetime_h = IntVal($_REQUEST['cachetime']);
233         if ($cachetime_h < 1) $cachetime_h = 1;
234         set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
235     }
236     if (isset($_REQUEST['delete_all'])) {
237         q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
238     }
239 }