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