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