]> git.mxchange.org Git - friendica.git/blob - mod/proxy.php
Merge remote-tracking branch 'upstream/develop' into develop
[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 = qu("SELECT * FROM `photo` WHERE `resource-id` = '%s' LIMIT 1", $urlhash);
139                 if (dbm::is_result($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 (!dbm::is_result($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 /**
237  * @brief Transform a remote URL into a local one
238  *
239  * This function only performs the URL replacement on http URL and if the
240  * provided URL isn't local, "the isn't deactivated" (sic) and if the config
241  * system.proxy_disabled is set to false.
242  *
243  * @param string $url       The URL to proxyfy
244  * @param bool   $writemode Returns a local path the remote URL should be saved to
245  * @param string $size      One of the PROXY_SIZE_* constants
246  *
247  * @return string The proxyfied URL or relative path
248  */
249 function proxy_url($url, $writemode = false, $size = '') {
250         $a = get_app();
251
252         if (substr($url, 0, strlen('http')) !== 'http') {
253                 return $url;
254         }
255
256         // Only continue if it isn't a local image and the isn't deactivated
257         if (proxy_is_local_image($url)) {
258                 $url = str_replace(normalise_link(App::get_baseurl()) . '/', App::get_baseurl() . '/', $url);
259                 return $url;
260         }
261
262         if (get_config('system', 'proxy_disabled')) {
263                 return $url;
264         }
265
266         // Image URL may have encoded ampersands for display which aren't desirable for proxy
267         $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
268
269         // Creating a sub directory to reduce the amount of files in the cache directory
270         $basepath = $a->get_basepath() . '/proxy';
271
272         $shortpath = hash('md5', $url);
273         $longpath = substr($shortpath, 0, 2);
274
275         if (is_dir($basepath) and $writemode) {
276                 if (!is_dir($basepath . '/' . $longpath)) {
277                         mkdir($basepath . '/' . $longpath);
278                         chmod($basepath . '/' . $longpath, 0777);
279                 }
280         }
281
282         $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
283
284         // Extract the URL extension, disregarding GET parameters starting with ?
285         $question_mark_pos = strpos($url, '?');
286         if ($question_mark_pos === false) {
287                 $question_mark_pos = strlen($url);
288         }
289         $dot_pos = strrpos($url, '.', $question_mark_pos - strlen($url));
290         if ($dot_pos !== false) {
291                 $extension = strtolower(substr($url, $dot_pos + 1, $question_mark_pos - ($dot_pos + 1)));
292         }
293
294         $extensions = array('jpg', 'jpeg', 'gif', 'png');
295         if (in_array($extension, $extensions)) {
296                 $shortpath .= '.' . $extension;
297                 $longpath .= '.' . $extension;
298         }
299
300         $proxypath = App::get_baseurl() . '/proxy/' . $longpath;
301
302         if ($size != '') {
303                 $size = ':' . $size;
304         }
305
306         // Too long files aren't supported by Apache
307         // Writemode in combination with long files shouldn't be possible
308         if ((strlen($proxypath) > 250) AND $writemode) {
309                 return $shortpath;
310         } elseif (strlen($proxypath) > 250) {
311                 return App::get_baseurl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
312         } elseif ($writemode) {
313                 return $longpath;
314         } else {
315                 return $proxypath . $size;
316         }
317 }
318
319 /**
320  * @param $url string
321  * @return boolean
322  */
323 function proxy_is_local_image($url) {
324         if ($url[0] == '/') return true;
325
326         if (strtolower(substr($url, 0, 5)) == "data:") return true;
327
328         // links normalised - bug #431
329         $baseurl = normalise_link(get_app()->get_baseurl());
330         $url = normalise_link($url);
331         return (substr($url, 0, strlen($baseurl)) == $baseurl);
332 }
333
334 function proxy_parse_query($var) {
335         /**
336          *  Use this function to parse out the query array element from
337          *  the output of parse_url().
338         */
339         $var  = parse_url($var, PHP_URL_QUERY);
340         $var  = html_entity_decode($var);
341         $var  = explode('&', $var);
342         $arr  = array();
343
344         foreach($var as $val) {
345                 $x          = explode('=', $val);
346                 $arr[$x[0]] = $x[1];
347         }
348
349         unset($val, $x, $var);
350         return $arr;
351 }
352
353 function proxy_img_cb($matches) {
354
355         // if the picture seems to be from another picture cache then take the original source
356         $queryvar = proxy_parse_query($matches[2]);
357         if (($queryvar['url'] != "") AND (substr($queryvar['url'], 0, 4) == "http"))
358                 $matches[2] = urldecode($queryvar['url']);
359
360         // following line changed per bug #431
361         if (proxy_is_local_image($matches[2]))
362                 return $matches[1] . $matches[2] . $matches[3];
363
364         return $matches[1].proxy_url(htmlspecialchars_decode($matches[2])).$matches[3];
365 }
366
367 function proxy_parse_html($html) {
368         $a = get_app();
369         $html = str_replace(normalise_link(App::get_baseurl())."/", App::get_baseurl()."/", $html);
370
371         return preg_replace_callback("/(<img [^>]*src *= *[\"'])([^\"']+)([\"'][^>]*>)/siU", "proxy_img_cb", $html);
372 }