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