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