]> git.mxchange.org Git - friendica.git/blob - mod/proxy.php
Removed Google Maps
[friendica.git] / mod / proxy.php
1 <?php
2 // Based upon "Privacy Image Cache" by Tobias Hößl <https://github.com/CatoTH/>
3
4 define("PROXY_DEFAULT_TIME", 86400); // 1 Day
5
6 require_once('include/security.php');
7 require_once("include/Photo.php");
8
9 function proxy_init() {
10         global $a, $_SERVER;
11
12         // Pictures are stored in one of the following ways:
13         // 1. If a folder "proxy" exists and is writeable, then use this for caching
14         // 2. If a cache path is defined, use this
15         // 3. If everything else failed, cache into the database
16         //
17         // Question: Do we really need these three methods?
18
19         if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
20                 header('HTTP/1.1 304 Not Modified');
21                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
22                 header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
23                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
24                 header("Cache-Control: max-age=31536000");
25                 if(function_exists('header_remove')) {
26                         header_remove('Last-Modified');
27                         header_remove('Expires');
28                         header_remove('Cache-Control');
29                 }
30                 exit;
31         }
32
33         if(function_exists('header_remove')) {
34                 header_remove('Pragma');
35                 header_remove('pragma');
36         }
37
38         $thumb = false;
39         $size = 1024;
40
41         // If the cache path isn't there, try to create it
42         if (!is_dir($_SERVER["DOCUMENT_ROOT"]."/proxy"))
43                 if (is_writable($_SERVER["DOCUMENT_ROOT"]))
44                         mkdir($_SERVER["DOCUMENT_ROOT"]."/proxy");
45
46         // Checking if caching into a folder in the webroot is activated and working
47         $direct_cache = (is_dir($_SERVER["DOCUMENT_ROOT"]."/proxy") AND is_writable($_SERVER["DOCUMENT_ROOT"]."/proxy"));
48
49         // Look for filename in the arguments
50         if ((isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) AND !isset($_REQUEST["url"])) {
51                 if (isset($a->argv[3]))
52                         $url = $a->argv[3];
53                 elseif (isset($a->argv[2]))
54                         $url = $a->argv[2];
55                 else
56                         $url = $a->argv[1];
57
58                 if (isset($a->argv[3]) and ($a->argv[3] == "thumb"))
59                         $size = 200;
60
61                 // thumb, small, medium and large.
62                 if (substr($url, -6) == ":thumb")
63                         $size = 150;
64                 if (substr($url, -6) == ":small")
65                         $size = 340;
66                 if (substr($url, -7) == ":medium")
67                         $size = 600;
68                 if (substr($url, -6) == ":large")
69                         $size = 1024;
70
71                 $pos = strrpos($url, "=.");
72                 if ($pos)
73                         $url = substr($url, 0, $pos+1);
74
75                 $url = str_replace(array(".jpg", ".jpeg", ".gif", ".png"), array("","","",""), $url);
76
77                 $url = base64_decode(strtr($url, '-_', '+/'), true);
78
79                 if ($url)
80                         $_REQUEST['url'] = $url;
81         } else
82                 $direct_cache = false;
83
84         if (!$direct_cache) {
85                 $urlhash = 'pic:' . sha1($_REQUEST['url']);
86
87                 $cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
88                 if ($cachefile != '') {
89                         if (file_exists($cachefile)) {
90                                 $img_str = file_get_contents($cachefile);
91                                 $mime = image_type_to_mime_type(exif_imagetype($cachefile));
92
93                                 header("Content-type: $mime");
94                                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
95                                 header('Etag: "'.md5($img_str).'"');
96                                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
97                                 header("Cache-Control: max-age=31536000");
98
99                                 // reduce quality - if it isn't a GIF
100                                 if ($mime != "image/gif") {
101                                         $img = new Photo($img_str, $mime);
102                                         if($img->is_valid()) {
103                                                 $img_str = $img->imageString();
104                                         }
105                                 }
106
107                                 echo $img_str;
108                                 killme();
109                         }
110                 }
111         } else
112                 $cachefile = "";
113
114         $valid = true;
115
116         if (!$direct_cache AND ($cachefile == "")) {
117                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
118                 if (count($r)) {
119                         $img_str = $r[0]['data'];
120                         $mime = $r[0]["desc"];
121                         if ($mime == "") $mime = "image/jpeg";
122                 }
123         } else
124                 $r = array();
125
126         if (!count($r)) {
127                 // It shouldn't happen but it does - spaces in URL
128                 $_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
129                 $redirects = 0;
130                 $img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
131
132                 $tempfile = tempnam(get_temppath(), "cache");
133                 file_put_contents($tempfile, $img_str);
134                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
135                 unlink($tempfile);
136
137                 // If there is an error then return a blank image
138                 if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
139                         $img_str = file_get_contents("images/blank.png");
140                         $mime = "image/png";
141                         $cachefile = ""; // Clear the cachefile so that the dummy isn't stored
142                         $valid = false;
143                         $img = new Photo($img_str, "image/png");
144                         if($img->is_valid()) {
145                                 $img->scaleImage(10);
146                                 $img_str = $img->imageString();
147                         }
148                 } else if (($mime != "image/jpeg") AND !$direct_cache AND ($cachefile == "")) {
149                         $image = @imagecreatefromstring($img_str);
150
151                         if($image === FALSE) die();
152
153                         q("INSERT INTO `photo`
154                         ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `album`, `height`, `width`, `desc`, `data`, `scale`, `profile`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid` )
155                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' )",
156                                 0, 0, get_guid(), dbesc($urlhash),
157                                 dbesc(datetime_convert()),
158                                 dbesc(datetime_convert()),
159                                 dbesc(basename(dbesc($_REQUEST["url"]))),
160                                 dbesc(''),
161                                 intval(imagesy($image)),
162                                 intval(imagesx($image)),
163                                 $mime,
164                                 dbesc($img_str),
165                                 100,
166                                 intval(0),
167                                 dbesc(''), dbesc(''), dbesc(''), dbesc('')
168                         );
169
170                 } else {
171                         $img = new Photo($img_str, $mime);
172                         if($img->is_valid()) {
173                                 if (!$direct_cache AND ($cachefile == ""))
174                                         $img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
175                         }
176                 }
177         }
178
179         // reduce quality - if it isn't a GIF
180         if ($mime != "image/gif") {
181                 $img = new Photo($img_str, $mime);
182                 if($img->is_valid()) {
183                         $img->scaleImage($size);
184                         $img_str = $img->imageString();
185                 }
186         }
187
188         // If there is a real existing directory then put the cache file there
189         // advantage: real file access is really fast
190         // Otherwise write in cachefile
191         if ($valid AND $direct_cache)
192                 file_put_contents($_SERVER["DOCUMENT_ROOT"]."/proxy/".proxy_url($_REQUEST['url'], true), $img_str);
193         elseif ($cachefile != '')
194                 file_put_contents($cachefile, $img_str);
195
196         header("Content-type: $mime");
197
198         // Only output the cache headers when the file is valid
199         if ($valid) {
200                 header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
201                 header('Etag: "'.md5($img_str).'"');
202                 header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
203                 header("Cache-Control: max-age=31536000");
204         }
205
206         echo $img_str;
207
208         killme();
209 }
210
211 function proxy_url($url, $writemode = false) {
212         global $_SERVER;
213
214         $a = get_app();
215
216         // Only continue if it isn't a local image and the isn't deactivated
217         if (proxy_is_local_image($url)) {
218                 $url = str_replace(normalise_link($a->get_baseurl())."/", $a->get_baseurl()."/", $url);
219                 return($url);
220         }
221
222         if (get_config("system", "proxy_disabled"))
223                 return($url);
224
225         // Creating a sub directory to reduce the amount of files in the cache directory
226         $basepath = $_SERVER["DOCUMENT_ROOT"]."/proxy";
227
228         $path = substr(hash("md5", $url), 0, 2);
229
230         if (is_dir($basepath) and $writemode)
231                 if (!is_dir($basepath."/".$path)) {
232                         mkdir($basepath."/".$path);
233                         chmod($basepath."/".$path, 0777);
234                 }
235
236         $path .= "/".strtr(base64_encode($url), '+/', '-_');
237
238         // Checking for valid extensions. Only add them if they are safe
239         $pos = strrpos($url, ".");
240         if ($pos) {
241                 $extension = strtolower(substr($url, $pos+1));
242                 $pos = strpos($extension, "?");
243                 if ($pos)
244                         $extension = substr($extension, 0, $pos);
245         }
246
247         $extensions = array("jpg", "jpeg", "gif", "png");
248
249         if (in_array($extension, $extensions))
250                 $path .= ".".$extension;
251
252         $proxypath = $a->get_baseurl()."/proxy/".$path;
253
254         // Too long files aren't supported by Apache
255         // Writemode in combination with long files shouldn't be possible
256         if ((strlen($proxypath) > 250) AND $writemode)
257                 return (hash("md5", $url));
258         elseif (strlen($proxypath) > 250)
259                 return ($a->get_baseurl()."/proxy/".hash("md5", $url)."?url=".urlencode($url));
260         elseif ($writemode)
261                 return ($path);
262         else
263                 return ($proxypath);
264 }
265
266 /**
267  * @param $url string
268  * @return boolean
269  */
270 function proxy_is_local_image($url) {
271         if ($url[0] == '/') return true;
272
273         if (strtolower(substr($url, 0, 5)) == "data:") return true;
274
275         // links normalised - bug #431
276         $baseurl = normalise_link(get_app()->get_baseurl());
277         $url = normalise_link($url);
278         return (substr($url, 0, strlen($baseurl)) == $baseurl);
279 }
280
281 function proxy_parse_query($var) {
282         /**
283          *  Use this function to parse out the query array element from
284          *  the output of parse_url().
285         */
286         $var  = parse_url($var, PHP_URL_QUERY);
287         $var  = html_entity_decode($var);
288         $var  = explode('&', $var);
289         $arr  = array();
290
291         foreach($var as $val) {
292                 $x          = explode('=', $val);
293                 $arr[$x[0]] = $x[1];
294         }
295
296         unset($val, $x, $var);
297         return $arr;
298 }
299
300 function proxy_img_cb($matches) {
301
302         // if the picture seems to be from another picture cache then take the original source
303         $queryvar = proxy_parse_query($matches[2]);
304         if (($queryvar['url'] != "") AND (substr($queryvar['url'], 0, 4) == "http"))
305                 $matches[2] = urldecode($queryvar['url']);
306
307         // following line changed per bug #431
308         if (proxy_is_local_image($matches[2]))
309                 return $matches[1] . $matches[2] . $matches[3];
310
311         return $matches[1].proxy_url(htmlspecialchars_decode($matches[2])).$matches[3];
312 }
313
314 function proxy_parse_html($html) {
315         $a = get_app();
316         $html = str_replace(normalise_link($a->get_baseurl())."/", $a->get_baseurl()."/", $html);
317
318         return preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "proxy_img_cb", $html);
319 }