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