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