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