]> git.mxchange.org Git - friendica-addons.git/blob - privacy_image_cache/privacy_image_cache.php
6e12a043eab4cd842343f168871283ff63108bd7
[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 function privacy_image_cache_init() {
34         global $a, $_SERVER;
35
36         if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
37                 header('HTTP/1.1 304 Not Modified');
38                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
39                 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
40                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
41                 header("Cache-Control: max-age=31536000");
42                 if(function_exists('header_remove')) {
43                         header_remove('Last-Modified');
44                         header_remove('Expires');
45                         header_remove('Cache-Control');
46                 }
47                 exit;
48         }
49
50         //if ($a->config["system"]["db_log"] != "")
51         //      $stamp1 = microtime(true);
52
53         if(function_exists('header_remove')) {
54                 header_remove('Pragma');
55                 header_remove('pragma');
56         }
57
58         $thumb = false;
59
60         // Look for filename in the arguments
61         if (isset($a->argv[1]) OR isset($a->argv[2])) {
62                 if (isset($a->argv[2]))
63                         $url = $a->argv[2];
64                 else
65                         $url = $a->argv[1];
66
67                 $pos = strrpos($url, "==.");
68                 if ($pos)
69                         $url = substr($url, 0, $pos+2);
70
71                 $url = base64_decode(strtr($url, '-_', '+/'), true);
72                 if ($url)
73                         $_REQUEST['url'] = $url;
74
75                 $thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
76         }
77
78         $urlhash = 'pic:' . sha1($_REQUEST['url']);
79         // Double encoded url - happens with Diaspora
80         $urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
81
82         $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
83         if ($cachefile != '') {
84                 if (file_exists($cachefile)) {
85                         $img_str = file_get_contents($cachefile);
86
87                         $mime = image_type_to_mime_type(exif_imagetype($cachefile));
88
89                         header("Content-type: $mime");
90                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
91                         header('Etag: "'.md5($img_str).'"');
92                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
93                         header("Cache-Control: max-age=31536000");
94
95                         echo $img_str;
96
97                         //if ($a->config["system"]["db_log"] != "") {
98                         //      $stamp2 = microtime(true);
99                         //      $duration = round($stamp2-$stamp1, 3);
100                         //      if ($duration > $a->config["system"]["db_loglimit"])
101                         //              @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
102                         //}
103
104                         killme();
105                 }
106         }
107
108         require_once("Photo.php");
109
110         $valid = true;
111
112         $r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
113         if (count($r)) {
114                 $img_str = $r[0]['data'];
115                 $mime = $r[0]["desc"];
116                 if ($mime == "") $mime = "image/jpeg";
117
118         } else {
119                 // It shouldn't happen but it does - spaces in URL
120                 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
121
122                 // if the picture seems to be from another picture cache then take the original source
123                 //$queryvar = privacy_image_cache_parse_query($_REQUEST['url']);
124                 //if ($queryvar['url'] != "")
125                 //      $_REQUEST['url'] = urldecode($queryvar['url']);
126
127                 // if fetching facebook pictures don't fetch the thumbnail but the big one
128                 //if (strpos($_REQUEST['url'], ".fbcdn.net/") and (substr($_REQUEST['url'], -6) == "_s.jpg"))
129                 //      $_REQUEST['url'] = substr($_REQUEST['url'], 0, -6)."_n.jpg";
130
131                 $redirects = 0;
132                 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
133
134                 $tempfile = tempnam(get_config("system","temppath"), "cache");
135                 file_put_contents($tempfile, $img_str);
136                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
137                 unlink($tempfile);
138
139                 // If there is an error then return a blank image
140                 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
141                         $img_str = file_get_contents("images/blank.png");
142                         $mime = "image/png";
143                         $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
144                         $valid = false;
145                         $img = new Photo($img_str, "image/png");
146                         if($img->is_valid()) {
147                                 $img->scaleImage(10);
148                                 $img_str = $img->imageString();
149                         }
150                 //} else if (substr($img_str, 0, 6) == "GIF89a") {
151                 } else if ($mime != "image/jpeg") {
152                         $image = @imagecreatefromstring($img_str);
153
154                         if($image === FALSE) die();
155
156                         q("INSERT INTO `photo`
157                         ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
158                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
159                                 0, 0, get_guid(), dbesc($urlhash),
160                                 dbesc(datetime_convert()),
161                                 dbesc(datetime_convert()),
162                                 dbesc(basename(dbesc($_REQUEST["url"]))),
163                                 dbesc(''),
164                                 intval(imagesy($image)),
165                                 intval(imagesx($image)),
166                                 $mime,
167                                 dbesc($img_str),
168                                 100,
169                                 intval(0),
170                                 dbesc(''), dbesc(''), dbesc(''), dbesc('')
171                         );
172
173                 } else {
174                         $img = new Photo($img_str);
175                         if($img->is_valid()) {
176                                 $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
177                                 if ($thumb)
178                                         $img->scaleImage(200); // Test
179                                 $img_str = $img->imageString();
180                         }
181                         $mime = "image/jpeg";
182                 }
183         }
184
185
186         // If there is a real existing directory then put the cache file there
187         // advantage: real file access is really fast
188         // Otherwise write in cachefile
189         if ($valid AND is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
190                 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
191         elseif ($cachefile != '')
192                 file_put_contents($cachefile, $img_str);
193
194         header("Content-type: $mime");
195
196         // Only output the cache headers when the file is valid
197         if ($valid) {
198                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
199                 header('Etag: "'.md5($img_str).'"');
200                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
201                 header("Cache-Control: max-age=31536000");
202         }
203
204         echo $img_str;
205
206         //if ($a->config["system"]["db_log"] != "") {
207         //      $stamp2 = microtime(true);
208         //      $duration = round($stamp2-$stamp1, 3);
209         //      if ($duration > $a->config["system"]["db_loglimit"])
210         //              @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
211         //}
212
213         killme();
214 }
215
216 function privacy_image_cache_cachename($url, $writemode = false) {
217         global $_SERVER;
218
219         $basepath = $_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache";
220
221         $path = substr(hash("md5", $url), 0, 2);
222
223         if (is_dir($basepath) and $writemode)
224                 if (!is_dir($basepath."/".$path)) {
225                         mkdir($basepath."/".$path);
226                         chmod($basepath."/".$path, 0777);
227                 }
228
229         $path .= "/".strtr(base64_encode($url), '+/', '-_');
230
231         return($path);
232 }
233
234 /**
235  * @param $url string
236  * @return boolean
237  */
238 function privacy_image_cache_is_local_image($url) {
239         if ($url[0] == '/') return true;
240
241         if (strtolower(substr($url, 0, 5)) == "data:") return true;
242
243         // Check if the cached path would be longer than 255 characters - apache doesn't like it
244         if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache")) {
245                 $cachedurl = get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename($url);
246                 if (strlen($url) > 150)
247                         return true;
248         }
249
250         // links normalised - bug #431
251         $baseurl = normalise_link(get_app()->get_baseurl());
252         $url = normalise_link($url);
253         return (substr($url, 0, strlen($baseurl)) == $baseurl);
254 }
255
256 /**
257  * @param array $matches
258  * @return string
259  */
260 function privacy_image_cache_img_cb($matches) {
261
262         // if the picture seems to be from another picture cache then take the original source
263         $queryvar = privacy_image_cache_parse_query($matches[2]);
264         if ($queryvar['url'] != "")
265                 $matches[2] = urldecode($queryvar['url']);
266
267         // if fetching facebook pictures don't fetch the thumbnail but the big one
268         if (strpos($matches[2], ".fbcdn.net/") and (substr($matches[2], -6) == "_s.jpg"))
269                 $matches[2] = substr($matches[2], 0, -6)."_n.jpg";
270
271         // following line changed per bug #431
272         if (privacy_image_cache_is_local_image($matches[2]))
273                 return $matches[1] . $matches[2] . $matches[3];
274
275         //return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
276
277         return $matches[1].get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename(htmlspecialchars_decode($matches[2])).$matches[3];
278 }
279
280 /**
281  * @param App $a
282  * @param string $o
283  */
284 function privacy_image_cache_prepare_body_hook(&$a, &$o) {
285         $o["html"] = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o["html"]);
286 }
287
288 /**
289  * @param App $a
290  * @param string $o
291  * Function disabled because the plugin moved
292  */
293 function privacy_image_cache_bbcode_hook(&$a, &$o) {
294         //$o = preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "privacy_image_cache_img_cb", $o);
295 }
296
297
298 /**
299  * @param App $a
300  * @param string $o
301  */
302 function privacy_image_cache_display_item_hook(&$a, &$o) {
303     if (isset($o["output"])) {
304         if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
305             $o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
306             //$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
307         if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
308             $o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
309             //$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
310         if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
311             $o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
312             //$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
313     }
314 }
315
316
317 /**
318  * @param App $a
319  * @param string $o
320  */
321 function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
322     if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
323         $o["photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["photo"]);
324         //$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
325 }
326
327
328 /**
329  * @param App $a
330  * @param null|object $b
331  */
332 function privacy_image_cache_cron(&$a = null, &$b = null) {
333     $cachetime = get_config('privacy_image_cache','cache_time');
334     if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
335
336     $last = get_config('pi_cache','last_delete');
337     $time = time();
338     if ($time < ($last + 3600)) return;
339
340     logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
341     q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
342
343     clear_cache($a->get_basepath(), $a->get_basepath()."/privacy_image_cache");
344
345     set_config('pi_cache', 'last_delete', $time);
346 }
347
348 /**
349  * @param App $a
350  * @param null|object $o
351  */
352 function privacy_image_cache_plugin_admin(&$a, &$o){
353
354
355     $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("picsave") . '">';
356
357     $cachetime = get_config('privacy_image_cache','cache_time');
358     if (!$cachetime) $cachetime = PRIVACY_IMAGE_CACHE_DEFAULT_TIME;
359     $cachetime_h = Ceil($cachetime / 3600);
360
361     $o .= '<label for="pic_cachetime">' . t('Lifetime of the cache (in hours)') . '</label>
362         <input id="pic_cachetime" name="cachetime" type="text" value="' . escape_tags($cachetime_h) . '"><br style="clear: both;">';
363
364     $o .= '<input type="submit" name="save" value="' . t('Save') . '">';
365
366     $o .= '<h4>' . t('Cache Statistics') . '</h4>';
367
368     $num = q('SELECT COUNT(*) num, SUM(LENGTH(data)) size FROM `photo` WHERE `uid`=0 AND `contact-id`=0 AND `resource-id` LIKE "pic:%%"');
369     $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;">';
370     $size = Ceil($num[0]['size'] / (1024 * 1024));
371     $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;">';
372
373     $o .= '<input type="submit" name="delete_all" value="' . t('Delete the whole cache') . '">';
374 }
375
376
377 /**
378  * @param App $a
379  * @param null|object $o
380  */
381 function privacy_image_cache_plugin_admin_post(&$a = null, &$o = null){
382     check_form_security_token_redirectOnErr('/admin/plugins/privacy_image_cache', 'picsave');
383
384     if (isset($_REQUEST['save'])) {
385         $cachetime_h = IntVal($_REQUEST['cachetime']);
386         if ($cachetime_h < 1) $cachetime_h = 1;
387         set_config('privacy_image_cache','cache_time', $cachetime_h * 3600);
388     }
389     if (isset($_REQUEST['delete_all'])) {
390         q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%"');
391     }
392 }
393
394 function privacy_image_cache_parse_query($var) {
395         /**
396          *  Use this function to parse out the query array element from
397          *  the output of parse_url().
398         */
399         $var  = parse_url($var, PHP_URL_QUERY);
400         $var  = html_entity_decode($var);
401         $var  = explode('&', $var);
402         $arr  = array();
403
404         foreach($var as $val) {
405                 $x          = explode('=', $val);
406                 $arr[$x[0]] = $x[1];
407         }
408
409         unset($val, $x, $var);
410         return $arr;
411 }