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