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