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