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