MySqlSetup: index.php

File index.php, 32.5 kB (added by Andre <Anasonne@web.de>, 4 years ago)

anasonne

Line 
1 <?php
2
3 /* --------------------------------------------------------------------------
4
5 pici-proxy is part of the picidae-project http://www.picidae.net
6 it shall serve as a proxy to a pici-server
7 Copyright (C) 2007  picidae.net by mathias jud and christoph wachter
8
9 this script is based on PHProxy of Abdullah Arif
10
11 This program is free software; you can redistribute it and/or
12 modify it under the terms of the GNU General Public License
13 as published by the Free Software Foundation; either version 2
14 of the License, or (at your option) any later version.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24
25  ========================================================================
26  ------------------------------------------------------------------------
27  configuration section
28  ------------------------------------------------------------------------ */
29
30 $pici_server = "pici.picidae.net"// set here the URL of the pici-server
31                                     // to use
32
33 /* ----------------------------------------------------------------------
34  end configuration section
35  ------------------------------------------------------------------------
36  ======================================================================== */
37
38 /* ----------------------------------------------------------------------
39     initial section (nothing to configure anymore... you'r done :-) )
40    ---------------------------------------------------------------------- */
41
42 error_reporting(E_ALL);
43 $use_htaccess_rewrite = false;
44
45 $_config            = array
46                     (
47                         'url_var_name'             => 'p',
48                         'flags_var_name'           => 'hl',
49                         'get_form_name'            => 'p',
50                         'basic_auth_var_name'      => '____pbavn',
51                         'max_file_size'            => -1,
52                         'allow_hotlinking'         => 0,
53                         'upon_hotlink'             => 1,
54                         'compress_output'          => 0
55                     );
56 $_flags             = array
57                     (
58                         'show_referer'    => 1
59                     );
60                     
61 $_hosts             = array
62                     (
63                         '#^127\.|192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[01])\.|localhost#i'
64                     );
65 $_hotlink_domains   = array();
66 $_insert            = array();
67 $_iflags            = '';
68 $_system            = array
69                     (
70                         'ssl'          => extension_loaded('openssl') && version_compare(PHP_VERSION, '4.3.0', '>='),
71                         'uploads'      => ini_get('file_uploads'),
72                         'gzip'         => extension_loaded('zlib') && !ini_get('zlib.output_compression'),
73                         'stripslashes' => get_magic_quotes_gpc()
74                     );
75 $_proxify           = array('text/html' => 1,
76                             'application/xml+xhtml' => 1,
77                             'application/xhtml+xml' => 1,
78                             'text/css' => 1);
79
80
81
82 $_http_host         = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
83 $_script_url        = 'http' . ((isset($_ENV['HTTPS']) && $_ENV['HTTPS'] == 'on') || $_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://' . $_http_host . ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443 ? ':' . $_SERVER['SERVER_PORT'] : '') . $_SERVER['PHP_SELF'];
84 $_script_base       = substr($_script_url, 0, strrpos($_script_url, '/')+1);
85 $_url               = '';
86 $_url_parts         = array();
87 $_base              = array();
88 $_socket            = null;
89 $_request_method    = $_SERVER['REQUEST_METHOD'];
90 $_request_headers   = '';
91 $_cookie            = '';
92 $_post_body         = '';
93 $_response_headers  = array();
94 $_response_keys     = array(); 
95 $_http_version      = '';
96 $_response_code     = 0;
97 $_content_type      = 'text/html';
98 $_content_length    = false;
99 $_content_disp      = '';
100 $_set_cookie        = array();
101 $_retry             = false;
102 $_quit              = false;
103 $_basic_auth_header = '';
104 $_basic_auth_realm  = '';
105 $_auth_creds        = array();
106 $_response_body     = '';
107
108
109 /* ----------------------------------------------------
110     function section
111    ----------------------------------------------------
112    instead of show_report
113    make immediately a connection to the pici-server
114    if the piciserver fails, show an error-picture
115 */
116 function show_report($data)
117 {   
118     echo ("<h1>Hello There :-)</h1>");
119     //include $data['which'] . '.inc.php';
120     exit(0);
121 }
122
123 // ----------------------------------------------------
124 function add_cookie($name, $value, $expires = 0)
125 {
126     return rawurlencode(rawurlencode($name)) . '=' . rawurlencode(rawurlencode($value)) . (empty($expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s \G\M\T', $expires)) . '; path=/; domain=.' . $GLOBALS['_http_host'];
127 }
128
129 // ----------------------------------------------------
130 function set_post_vars($array, $parent_key = null)
131 {
132     $temp = array();
133
134     foreach ($array as $key => $value)
135     {
136         $key = isset($parent_key) ? sprintf('%s[%s]', $parent_key, urlencode($key)) : urlencode($key);
137         if (is_array($value))
138         {
139             $temp = array_merge($temp, set_post_vars($value, $key));
140         }
141         else
142         {
143             $temp[$key] = urlencode($value);
144         }
145     }
146     
147     return $temp;
148 }
149
150 // ----------------------------------------------------
151 function set_post_files($array, $parent_key = null)
152 {
153     $temp = array();
154
155     foreach ($array as $key => $value)
156     {
157         $key = isset($parent_key) ? sprintf('%s[%s]', $parent_key, urlencode($key)) : urlencode($key);
158         if (is_array($value))
159         {
160             $temp = array_merge_recursive($temp, set_post_files($value, $key));
161         }
162         else if (preg_match('#^([^\[\]]+)\[(name|type|tmp_name)\]#', $key, $m))
163         {
164             $temp[str_replace($m[0], $m[1], $key)][$m[2]] = $value;
165         }
166     }
167
168     return $temp;
169 }
170
171 // ----------------------------------------------------
172 function url_parse($url, & $container)
173 {
174     $temp = @parse_url($url);
175
176     if (!empty($temp))
177     {
178         $temp['port_ext'] = '';
179         $temp['base']     = $temp['scheme'] . '://' . $temp['host'];
180
181         if (isset($temp['port']))
182         {
183             $temp['base'] .= $temp['port_ext'] = ':' . $temp['port'];
184         }
185         else
186         {
187             $temp['port'] = $temp['scheme'] === 'https' ? 443 : 80;
188         }
189         
190         $temp['path'] = isset($temp['path']) ? $temp['path'] : '/';
191         $path         = array();
192         $temp['path'] = explode('/', $temp['path']);
193     
194         foreach ($temp['path'] as $dir)
195         {
196             if ($dir === '..')
197             {
198                 array_pop($path);
199             }
200             else if ($dir !== '.')
201             {
202                 for ($dir = rawurldecode($dir), $new_dir = '', $i = 0, $count_i = strlen($dir); $i < $count_i; $new_dir .= strspn($dir{$i}, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$-_.+!*\'(),?:@&;=') ? $dir{$i} : rawurlencode($dir{$i}), ++$i);
203                 $path[] = $new_dir;
204             }
205         }
206
207         $temp['path']     = str_replace('/%7E', '/~', '/' . ltrim(implode('/', $path), '/'));
208         $temp['file']     = substr($temp['path'], strrpos($temp['path'], '/')+1);
209         $temp['dir']      = substr($temp['path'], 0, strrpos($temp['path'], '/'));
210         $temp['base']    .= $temp['dir'];
211         $temp['prev_dir'] = substr_count($temp['path'], '/') > 1 ? substr($temp['base'], 0, strrpos($temp['base'], '/')+1) : $temp['base'] . '/';
212         $container = $temp;
213
214         return true;
215     }
216     
217     return false;
218 }
219
220 // ----------------------------------------------------
221 function complete_url($url, $proxify = true)
222 {
223     $url = trim($url);
224     
225     if ($url === '')
226     {
227         return '';
228     }
229     
230     $hash_pos = strrpos($url, '#');
231     $fragment = $hash_pos !== false ? '#' . substr($url, $hash_pos) : '';
232
233     global $use_htaccess_rewrite;
234     if ( $use_htaccess_rewrite ) $proxify = false ;
235     return $proxify ? "{$GLOBALS['_script_url']}?{$GLOBALS['_config']['url_var_name']}=" . encode_url($url) . $fragment : $url;
236 }
237
238 // ----------------------------------------------------
239 function proxify_inline_css($css)
240 {
241     preg_match_all('#url\s*\(\s*(([^)]*(\\\))*[^)]*)(\)|$)?#i', $css, $matches, PREG_SET_ORDER);
242
243     for ($i = 0, $count = count($matches); $i < $count; ++$i)
244     {
245         $css = str_replace($matches[$i][0], 'url(' . proxify_css_url($matches[$i][1]) . ')', $css);
246     }
247     
248     return $css;
249 }
250
251 // ----------------------------------------------------
252 function proxify_css($css)
253 {
254     $css = proxify_inline_css($css);
255
256     preg_match_all("#@import\s*(?:\"([^\">]*)\"?|'([^'>]*)'?)([^;]*)(;|$)#i", $css, $matches, PREG_SET_ORDER);
257
258     for ($i = 0, $count = count($matches); $i < $count; ++$i)
259     {
260         $delim = '"';
261         $url   = $matches[$i][2];
262
263         if (isset($matches[$i][3]))
264         {
265             $delim = "'";
266             $url = $matches[$i][3];
267         }
268
269         $css = str_replace($matches[$i][0], '@import ' . $delim . proxify_css_url($matches[$i][1]) . $delim . (isset($matches[$i][4]) ? $matches[$i][4] : ''), $css);
270     }
271
272     return $css;
273 }
274
275 // ----------------------------------------------------
276 function proxify_css_url($url)
277 {
278     $url   = trim($url);
279     $delim = strpos($url, '"') === 0 ? '"' : (strpos($url, "'") === 0 ? "'" : '');
280
281     return $delim . preg_replace('#([\(\),\s\'"\\\])#', '\\$1', complete_url(trim(preg_replace('#\\\(.)#', '$1', trim($url, $delim))))) . $delim;
282 }
283
284
285 // ----------------------------------------------------
286 /*
287    decode URL
288    Not neede anymore
289    URL shall look like this:
290    {proxy_path}/path/to/resource.jpg               //with .htaccess
291    {proxy_path}/index.php?q=/path/to/resource.jpg  //without .htaccess
292 */
293 function encode_url($url)
294 {
295     //@@@ better return just the relative url (the whole one is not needed)
296     return rawurlencode($url);
297 }
298
299
300 // ----------------------------------------------------
301 function decode_url($url)
302 {
303     global $pici_server;
304     return "http://" . $pici_server ."/" . str_replace(array('&amp;', '&#38;'), '&', rawurldecode($url));
305 }
306
307
308
309
310 /* ----------------------------------------------------------------------
311     run through script
312    ---------------------------------------------------------------------- */
313
314 //
315 // SET FLAGS
316 //
317
318 if (isset($_POST[$_config['url_var_name']]) && !isset($_GET[$_config['url_var_name']]) && isset($_POST[$_config['flags_var_name']]))
319 {   
320     foreach ($_flags as $flag_name => $flag_value)
321     {
322         $_iflags .= isset($_POST[$_config['flags_var_name']][$flag_name]) ? (string)(int)(bool)$_POST[$_config['flags_var_name']][$flag_name] : ($_frozen_flags[$flag_name] ? $flag_value : '0');
323     }
324     
325     $_iflags = base_convert(($_iflags != '' ? $_iflags : '0'), 2, 16);
326 }
327 else if (isset($_GET[$_config['flags_var_name']]) && !isset($_GET[$_config['get_form_name']]) && ctype_alnum($_GET[$_config['flags_var_name']]))
328 {
329     $_iflags = $_GET[$_config['flags_var_name']];
330 }
331 else if (isset($_COOKIE['flags']) && ctype_alnum($_COOKIE['flags']))
332 {
333     $_iflags = $_COOKIE['flags'];
334 }
335
336 if ($_iflags !== '')
337 {
338     $_set_cookie[] = add_cookie('flags', $_iflags, time()+2419200);
339     $_iflags = str_pad(base_convert($_iflags, 16, 2), count($_flags), '0', STR_PAD_LEFT);
340     $i = 0;
341
342     foreach ($_flags as $flag_name => $flag_value)
343     {
344         $_flags[$flag_name] = $_frozen_flags[$flag_name] ? $flag_value : (int)(bool)$_iflags{$i};
345         $i++;
346     }
347 }
348
349
350
351
352
353 //
354 // COMPRESS OUTPUT IF INSTRUCTED
355 //
356
357 if ($_config['compress_output'] && $_system['gzip'])
358 {
359     ob_start('ob_gzhandler');
360 }
361
362 //
363 // STRIP SLASHES FROM GPC IF NECESSARY
364 //
365
366 if ($_system['stripslashes'])
367 {
368     function _stripslashes($value)
369     {
370         return is_array($value) ? array_map('_stripslashes', $value) : (is_string($value) ? stripslashes($value) : $value);
371     }
372     
373     $_GET    = _stripslashes($_GET);
374     $_POST   = _stripslashes($_POST);
375     $_COOKIE = _stripslashes($_COOKIE);
376 }
377
378 //
379 // FIGURE OUT WHAT TO DO (POST URL-form submit, GET form request, regular request, basic auth, cookie manager, show URL-form)
380 //
381
382 if (isset($_POST[$_config['url_var_name']]) && !isset($_GET[$_config['url_var_name']]))
383 {   
384     header('Location: ' . $_script_url . '?' . $_config['url_var_name'] . '=' . encode_url($_POST[$_config['url_var_name']]) . '&' . $_config['flags_var_name'] . '=' . base_convert($_iflags, 2, 16));
385     exit(0);
386 }
387
388 if (isset($_GET[$_config['get_form_name']]))
389 {
390     //echo ($_GET[$_config['get_form_name']] ."<br/>");
391     
392     $_url = decode_url($_GET[$_config['get_form_name']]);
393     $qstr = strpos($_url, '?') !== false ? (strpos($_url, '?') === strlen($_url)-1 ? '' : '&') : '?';
394     $arr  = explode('&', $_SERVER['QUERY_STRING']);
395     
396     //echo ($_url ."<br/>");
397     
398     if (preg_match('#^\Q' . $_config['get_form_name'] . '\E#', $arr[0]))
399     {
400         array_shift($arr);
401     }
402     
403     $_url .= $qstr . implode('&', $arr);
404     
405     //echo ($_url ."<br/>");
406 }
407 else if (isset($_GET[$_config['url_var_name']]))
408 {
409     $_url = decode_url($_GET[$_config['url_var_name']]);
410 }
411 //???
412 else if (isset($_GET['action']) && $_GET['action'] == 'cookies')
413 {
414     show_report(array('which' => 'cookies'));
415 }
416 else
417 {
418     //show_report(array('which' => 'index', 'category' => 'entry_form'));
419     $_url = $pici_server;
420 }
421
422 if (isset($_GET[$_config['url_var_name']], $_POST[$_config['basic_auth_var_name']], $_POST['username'], $_POST['password']))
423 {
424     $_request_method    = 'GET';
425     $_basic_auth_realm  = base64_decode($_POST[$_config['basic_auth_var_name']]);
426     $_basic_auth_header = base64_encode($_POST['username'] . ':' . $_POST['password']);
427 }
428
429 /* --------------------
430     set URL
431    -------------------- */
432  
433 if (strpos($_url, '://') === false)
434 {
435     $_url = 'http://' . $_url;
436 }
437
438 if (url_parse($_url, $_url_parts))
439 {
440     $_base = $_url_parts;
441     
442     if (!empty($_hosts))
443     {
444         foreach ($_hosts as $host)
445         {
446             if (preg_match($host, $_url_parts['host']))
447             {
448                 show_report(array('which' => 'index', 'category' => 'error', 'group' => 'url', 'type' => 'external', 'error' => 1));
449             }
450         }
451     }
452 }
453 else
454 {
455     show_report(array('which' => 'index', 'category' => 'error', 'group' => 'url', 'type' => 'external', 'error' => 2));
456 }
457
458
459
460 /* -------------------------
461    hotlinking prevention
462    has something to do with
463    https and http
464    ------------------------- */
465
466 if (!$_config['allow_hotlinking'] && isset($_SERVER['HTTP_REFERER']))
467 {
468     $_hotlink_domains[] = $_http_host;
469     $is_hotlinking      = true;
470     
471     foreach ($_hotlink_domains as $host)
472     {
473         if (preg_match('#^https?\:\/\/(www)?\Q' . $host  . '\E(\/|\:|$)#i', trim($_SERVER['HTTP_REFERER'])))
474         {
475             $is_hotlinking = false;
476             break;
477         }
478     }
479     
480     if ($is_hotlinking)
481     {
482         switch ($_config['upon_hotlink'])
483         {
484             case 1:
485                 show_report(array('which' => 'index', 'category' => 'error', 'group' => 'resource', 'type' => 'hotlinking'));
486                 break;
487             case 2:
488                 header('HTTP/1.0 404 Not Found');
489                 exit(0);
490             default:
491                 header('Location: ' . $_config['upon_hotlink']);
492                 exit(0);
493         }
494     }
495 }
496
497
498 /*
499  -----------------------
500  OPEN SOCKET TO SERVER
501  -----------------------
502  */
503
504 do
505 {
506     $_retry  = false;
507     $_socket = @fsockopen(($_url_parts['scheme'] === 'https' && $_system['ssl'] ? 'ssl://' : 'tcp://') . $_url_parts['host'], $_url_parts['port'], $err_no, $err_str, 30);
508
509     if ($_socket === false)
510     {
511         show_report(array('which' => 'index', 'category' => 'error', 'group' => 'url', 'type' => 'internal', 'error' => $err_no));
512     }
513
514     //
515     // SET REQUEST HEADERS
516     //
517
518     $_request_headers  = $_request_method . ' ' . $_url_parts['path'];
519
520     if (isset($_url_parts['query']))
521     {
522         $_request_headers .= '?';
523         $query = preg_split('#([&;])#', $_url_parts['query'], -1, PREG_SPLIT_DELIM_CAPTURE);
524         for ($i = 0, $count = count($query); $i < $count; $_request_headers .= implode('=', array_map('urlencode', array_map('urldecode', explode('=', $query[$i])))) . (isset($query[++$i]) ? $query[$i] : ''), $i++);
525     }
526
527     $_request_headers .= " HTTP/1.0\r\n";
528     $_request_headers .= 'Host: ' . $_url_parts['host'] . $_url_parts['port_ext'] . "\r\n";
529
530     if (isset($_SERVER['HTTP_USER_AGENT']))
531     {
532         $_request_headers .= 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'] . "\r\n";
533     }
534     if (isset($_SERVER['HTTP_ACCEPT']))
535     {
536         $_request_headers .= 'Accept: ' . $_SERVER['HTTP_ACCEPT'] . "\r\n";
537     }
538     else
539     {
540         $_request_headers .= "Accept: */*;q=0.1\r\n";
541     }
542     if ($_flags['show_referer'] && isset($_SERVER['HTTP_REFERER']) && preg_match('#^\Q' . $_script_url . '?' . $_config['url_var_name'] . '=\E([^&]+)#', $_SERVER['HTTP_REFERER'], $matches))
543     {
544         $_request_headers .= 'Referer: ' . decode_url($matches[1]) . "\r\n";
545     }
546     if (!empty($_COOKIE))
547     {
548         $_cookie  = '';
549         $_auth_creds    = array();
550     
551         foreach ($_COOKIE as $cookie_id => $cookie_content)
552         {
553             $cookie_id      = explode(';', rawurldecode($cookie_id));
554             $cookie_content = explode(';', rawurldecode($cookie_content));
555     
556             if ($cookie_id[0] === 'COOKIE')
557             {
558                 $cookie_id[3] = str_replace('_', '.', $cookie_id[3]); //stupid PHP can't have dots in var names
559
560                 if (count($cookie_id) < 4 || ($cookie_content[1] == 'secure' && $_url_parts['scheme'] != 'https'))
561                 {
562                     continue;
563                 }
564     
565                 if ((preg_match('#\Q' . $cookie_id[3] . '\E$#i', $_url_parts['host']) || strtolower($cookie_id[3]) == strtolower('.' . $_url_parts['host'])) && preg_match('#^\Q' . $cookie_id[2] . '\E#', $_url_parts['path']))
566                 {
567                     $_cookie .= ($_cookie != '' ? '; ' : '') . (empty($cookie_id[1]) ? '' : $cookie_id[1] . '=') . $cookie_content[0];
568                 }
569             }
570             else if ($cookie_id[0] === 'AUTH' && count($cookie_id) === 3)
571             {
572                 $cookie_id[2] = str_replace('_', '.', $cookie_id[2]);
573
574                 if ($_url_parts['host'] . ':' . $_url_parts['port'] === $cookie_id[2])
575                 {
576                     $_auth_creds[$cookie_id[1]] = $cookie_content[0];
577                 }
578             }
579         }
580         
581         if ($_cookie != '')
582         {
583             $_request_headers .= "Cookie: $_cookie\r\n";
584         }
585     }
586     if (isset($_url_parts['user'], $_url_parts['pass']))
587     {
588         $_basic_auth_header = base64_encode($_url_parts['user'] . ':' . $_url_parts['pass']);
589     }
590     if (!empty($_basic_auth_header))
591     {
592         $_set_cookie[] = add_cookie("AUTH;{$_basic_auth_realm};{$_url_parts['host']}:{$_url_parts['port']}", $_basic_auth_header);
593         $_request_headers .= "Authorization: Basic {$_basic_auth_header}\r\n";
594     }
595     else if (!empty($_basic_auth_realm) && isset($_auth_creds[$_basic_auth_realm]))
596     {
597         $_request_headers  .= "Authorization: Basic {$_auth_creds[$_basic_auth_realm]}\r\n";
598     }
599     else if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
600     {
601         $_request_headers .= "Authorization: Basic {$_basic_auth_header}\r\n";
602     }
603     if ($_request_method == 'POST')
604     {   
605         if (!empty($_FILES) && $_system['uploads'])
606         {
607             $_data_boundary = '----' . md5(uniqid(rand(), true));
608             $array = set_post_vars($_POST);
609     
610             foreach ($array as $key => $value)
611             {
612                 $_post_body .= "--{$_data_boundary}\r\n";
613                 $_post_body .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
614                 $_post_body .= urldecode($value) . "\r\n";
615             }
616             
617             $array = set_post_files($_FILES);
618     
619             foreach ($array as $key => $file_info)
620             {
621                 $_post_body .= "--{$_data_boundary}\r\n";
622                 $_post_body .= "Content-Disposition: form-data; name=\"$key\"; filename=\"{$file_info['name']}\"\r\n";
623                 $_post_body .= 'Content-Type: ' . (empty($file_info['type']) ? 'application/octet-stream' : $file_info['type']) . "\r\n\r\n";
624     
625                 if (is_readable($file_info['tmp_name']))
626                 {
627                     $handle = fopen($file_info['tmp_name'], 'rb');
628                     $_post_body .= fread($handle, filesize($file_info['tmp_name']));
629                     fclose($handle);
630                 }
631                 
632                 $_post_body .= "\r\n";
633             }
634             
635             $_post_body       .= "--{$_data_boundary}--\r\n";
636             $_request_headers .= "Content-Type: multipart/form-data; boundary={$_data_boundary}\r\n";
637             $_request_headers .= "Content-Length: " . strlen($_post_body) . "\r\n\r\n";
638             $_request_headers .= $_post_body;
639         }
640         else
641         {
642             $array = set_post_vars($_POST);
643             
644             foreach ($array as $key => $value)
645             {
646                 $_post_body .= !empty($_post_body) ? '&' : '';
647                 $_post_body .= $key . '=' . $value;
648             }
649             $_request_headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
650             $_request_headers .= "Content-Length: " . strlen($_post_body) . "\r\n\r\n";
651             $_request_headers .= $_post_body;
652             $_request_headers .= "\r\n";
653         }
654         
655         $_post_body = '';
656     }
657     else
658     {
659         $_request_headers .= "\r\n";
660     }
661
662     fwrite($_socket, $_request_headers);
663     
664     //
665     // PROCESS RESPONSE HEADERS
666     //
667     
668     $_response_headers = $_response_keys = array();
669     
670     $line = fgets($_socket, 8192);
671     
672     while (strspn($line, "\r\n") !== strlen($line))
673     {
674         @list($name, $value) = explode(':', $line, 2);
675         $name = trim($name);
676         $_response_headers[strtolower($name)][] = trim($value);
677         $_response_keys[strtolower($name)] = $name;
678         $line = fgets($_socket, 8192);
679     }
680     
681     sscanf(current($_response_keys), '%s %s', $_http_version, $_response_code);
682     
683     if (isset($_response_headers['content-type']))
684     {
685         list($_content_type, ) = explode(';', str_replace(' ', '', strtolower($_response_headers['content-type'][0])), 2);
686     }
687     if (isset($_response_headers['content-length']))
688     {
689         $_content_length = $_response_headers['content-length'][0];
690         unset($_response_headers['content-length'], $_response_keys['content-length']);
691     }
692     if (isset($_response_headers['content-disposition']))
693     {
694         $_content_disp = $_response_headers['content-disposition'][0];
695         unset($_response_headers['content-disposition'], $_response_keys['content-disposition']);
696     }
697     if (isset($_response_headers['p3p']) && preg_match('#policyref\s*=\s*[\'"]?([^\'"\s]*)[\'"]?#i', $_response_headers['p3p'][0], $matches))
698     {
699         $_response_headers['p3p'][0] = str_replace($matches[0], 'policyref="' . complete_url($matches[1]) . '"', $_response_headers['p3p'][0]);
700     }
701     if (isset($_response_headers['refresh']) && preg_match('#([0-9\s]*;\s*URL\s*=)\s*(\S*)#i', $_response_headers['refresh'][0], $matches))
702     {
703         $_response_headers['refresh'][0] = $matches[1] . complete_url($matches[2]);
704     }
705     if (isset($_response_headers['location']))
706     {   
707         $_response_headers['location'][0] = complete_url($_response_headers['location'][0]);
708     }
709     if (isset($_response_headers['uri']))
710     {   
711         $_response_headers['uri'][0] = complete_url($_response_headers['uri'][0]);
712     }
713     if (isset($_response_headers['content-location']))
714     {   
715         $_response_headers['content-location'][0] = complete_url($_response_headers['content-location'][0]);
716     }
717     if (isset($_response_headers['connection']))
718     {
719         unset($_response_headers['connection'], $_response_keys['connection']);
720     }
721     if (isset($_response_headers['keep-alive']))
722     {
723         unset($_response_headers['keep-alive'], $_response_keys['keep-alive']);
724     }
725     if ($_response_code == 401 && isset($_response_headers['www-authenticate']) && preg_match('#basic\s+(?:realm="(.*?)")?#i', $_response_headers['www-authenticate'][0], $matches))
726     {
727         if (isset($_auth_creds[$matches[1]]) && !$_quit)
728         {
729             $_basic_auth_realm  = $matches[1];
730             $_basic_auth_header = '';
731             $_retry = $_quit = true;
732         }
733         else
734         {
735             show_report(array('which' => 'index', 'category' => 'auth', 'realm' => $matches[1]));
736         }
737     }
738 }
739 while ($_retry);
740
741 //
742 // OUTPUT RESPONSE IF NO PROXIFICATION IS NEEDED
743 // 
744
745 if (!isset($_proxify[$_content_type]))
746 {
747     @set_time_limit(0);
748   
749     $_response_keys['content-disposition'] = 'Content-Disposition';
750     $_response_headers['content-disposition'][0] = empty($_content_disp) ? ($_content_type == 'application/octet_stream' ? 'attachment' : 'inline') . '; filename="' . $_url_parts['file'] . '"' : $_content_disp;
751     
752     if ($_content_length !== false)
753     {
754         if ($_config['max_file_size'] != -1 && $_content_length > $_config['max_file_size'])
755         {
756             show_report(array('which' => 'index', 'category' => 'error', 'group' => 'resource', 'type' => 'file_size'));
757         }
758         
759         $_response_keys['content-length'] = 'Content-Length';
760         $_response_headers['content-length'][0] = $_content_length;
761     }
762     
763     $_response_headers   = array_filter($_response_headers);
764     $_response_keys      = array_filter($_response_keys);
765     
766     header(array_shift($_response_keys));
767     array_shift($_response_headers);
768     
769     foreach ($_response_headers as $name => $array)
770     {
771         foreach ($array as $value)
772         {
773             header($_response_keys[$name] . ': ' . $value, false);
774         }
775     }
776         
777     do
778     {
779         $data = fread($_socket, 8192);
780         echo $data;
781     }
782     while (isset($data{0}));
783         
784     fclose($_socket);
785     exit(0);
786 }
787
788 do
789 {
790     $data = @fread($_socket, 8192); // silenced to avoid the "normal" warning by a faulty SSL connection
791     $_response_body .= $data;
792 }   
793 while (isset($data{0}));
794   
795 unset($data);
796 fclose($_socket);
797
798 //
799 // MODIFY AND DUMP RESOURCE
800 //
801
802 if ($_content_type == 'text/css')
803 {
804     $_response_body = proxify_css($_response_body);
805 }
806 else
807 {
808     
809     /* rewritten html-tags */
810     
811     $tags = array
812     (
813         'a'          => array('href'),
814         'img'        => array('src', 'longdesc'),
815         'input'      => array('src', 'usemap'),
816         'form'       => array('action'),
817         'area'       => array('href'),
818         'link'       => array('href', 'src', 'urn'),
819         'script'     => array('src'),
820     );
821
822     preg_match_all('#(<\s*style[^>]*>)(.*?)(<\s*/\s*style[^>]*>)#is', $_response_body, $matches, PREG_SET_ORDER);
823
824     for ($i = 0, $count_i = count($matches); $i < $count_i; ++$i)
825     {
826         $_response_body = str_replace($matches[$i][0], $matches[$i][1]. proxify_css($matches[$i][2]) .$matches[$i][3], $_response_body);
827     }
828
829     preg_match_all("#<\s*([a-zA-Z\?-]+)([^>]+)>#S", $_response_body, $matches);
830
831     for ($i = 0, $count_i = count($matches[0]); $i < $count_i; ++$i)
832     {
833         if (!preg_match_all("#([a-zA-Z\-\/]+)\s*(?:=\s*(?:\"([^\">]*)\"?|'([^'>]*)'?|([^'\"\s]*)))?#S", $matches[2][$i], $m, PREG_SET_ORDER))
834         {
835             continue;
836         }
837         
838         $rebuild    = false;
839         $extra_html = $temp = '';
840         $attrs      = array();
841
842         for ($j = 0, $count_j = count($m); $j < $count_j; $attrs[strtolower($m[$j][1])] = (isset($m[$j][4]) ? $m[$j][4] : (isset($m[$j][3]) ? $m[$j][3] : (isset($m[$j][2]) ? $m[$j][2] : false))), ++$j);
843         
844         if (isset($attrs['style']))
845         {
846             $rebuild = true;
847             $attrs['style'] = proxify_inline_css($attrs['style']);
848         }
849         
850         $tag = strtolower($matches[1][$i]);
851
852         if (isset($tags[$tag]))
853         {
854             switch ($tag)
855             {
856                 case 'a':
857                     if (isset($attrs['href']))
858                     {
859                         $rebuild = true;
860                         $attrs['href'] = complete_url($attrs['href']);
861                     }
862                     break;
863                 case 'img':
864                     if (isset($attrs['src']))
865                     {
866                         $rebuild = true;
867                         $attrs['src'] = complete_url($attrs['src']);
868                     }
869                     if (isset($attrs['longdesc']))
870                     {
871                         $rebuild = true;
872                         $attrs['longdesc'] = complete_url($attrs['longdesc']);
873                     }
874                     break;
875                 case 'form':
876                     if (isset($attrs['action']))
877                     {
878                         $rebuild = true;
879                         
880                         if (trim($attrs['action']) === '')
881                         {
882                             $attrs['action'] = $_url_parts['path'];
883                         }
884                         if (!isset($attrs['method']) || strtolower(trim($attrs['method'])) === 'get')
885                         {
886                             //$extra_html = '<input type="hidden" name="' . $_config['get_form_name'] . '" value="' . encode_url(complete_url($attrs['action'], false)) . '" />';
887                             if ($use_htaccess_rewrite)
888                             {
889                                 $attrs['action'] = $attrs['action'];
890                             }
891                             else
892                             {
893                                 $extra_html = '<input type="hidden" name="' . $_config['get_form_name'] . '" value="' . encode_url($attrs['action']) . '" class="n" />';
894                                 $attrs['action'] = '';
895                             }
896                             break;
897                         }
898                         
899                         $attrs['action'] = complete_url($attrs['action']);
900                     }
901                     break;
902                 default:
903                     foreach ($tags[$tag] as $attr)
904                     {
905                         if (isset($attrs[$attr]))
906                         {
907                             $rebuild = true;
908                             $attrs[$attr] = complete_url($attrs[$attr]);
909                         }
910                     }
911                     break;
912             }
913         }
914     
915         if ($rebuild)
916         {
917             $new_tag = "<$tag";
918             foreach ($attrs as $name => $value)
919             {
920                 $delim = strpos($value, '"') && !strpos($value, "'") ? "'" : '"';
921                 $new_tag .= ' ' . $name . ($value !== false ? '=' . $delim . $value . $delim : '');
922             }
923
924             $_response_body = str_replace($matches[0][$i], $new_tag . '>' . $extra_html, $_response_body);
925         }
926     }
927     
928 }
929
930 $_response_keys['content-disposition'] = 'Content-Disposition';
931 $_response_headers['content-disposition'][0] = empty($_content_disp) ? ($_content_type == 'application/octet_stream' ? 'attachment' : 'inline') . '; filename="' . $_url_parts['file'] . '"' : $_content_disp;
932 $_response_keys['content-length'] = 'Content-Length';
933 $_response_headers['content-length'][0] = strlen($_response_body);   
934 $_response_headers   = array_filter($_response_headers);
935 $_response_keys      = array_filter($_response_keys);
936
937 header(array_shift($_response_keys));
938 array_shift($_response_headers);
939
940 foreach ($_response_headers as $name => $array)
941 {
942     foreach ($array as $value)
943     {
944         header($_response_keys[$name] . ': ' . $value, false);
945     }
946 }
947
948 echo $_response_body;
949
950 ?>