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