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