OSDN Git Service

Remove media selector, use media query
[pukiwiki/pukiwiki.git] / lib / proxy.php
1 <?php
2 // PukiWiki - Yet another WikiWikiWeb clone
3 // proxy.php
4 // Copyright: 2003-2016 PukiWiki Development Team
5 // License: GPL v2 or (at your option) any later version
6 //
7 // HTTP-Proxy related functions
8
9 // Max number of 'track' redirection message with 301 or 302 response
10 define('PKWK_HTTP_REQUEST_URL_REDIRECT_MAX', 2);
11
12 // We also define deprecated function 'http_request' for backward compatibility
13 if (!function_exists('http_request')) {
14         // pecl_http extension also have the function named 'http_request'
15         function http_request($url, $method = 'GET', $headers = '',
16                 $post = array(), $redirect_max = PKWK_HTTP_REQUEST_URL_REDIRECT_MAX,
17                 $content_charset = '') {
18                 return pkwk_http_request($url, $method, $headers, $post,
19                         $redirect_max, $content_charset);
20         }
21 }
22
23 /*
24  * pkwk_http_request($url)
25  *     Get / Send data via HTTP request
26  * $url     : URI started with http:// (http://user:pass@host:port/path?query)
27  * $method  : GET, POST, or HEAD
28  * $headers : Additional HTTP headers, ended with "\r\n"
29  * $post    : An array of data to send via POST method ('key'=>'value')
30  * $redirect_max : Max number of HTTP redirect
31  * $content_charset : Content charset. Use '' or CONTENT_CHARSET
32 */
33 function pkwk_http_request($url, $method = 'GET', $headers = '', $post = array(),
34         $redirect_max = PKWK_HTTP_REQUEST_URL_REDIRECT_MAX, $content_charset = '')
35 {
36         global $use_proxy, $no_proxy, $proxy_host, $proxy_port;
37         global $need_proxy_auth, $proxy_auth_user, $proxy_auth_pass;
38
39         $rc  = array();
40         $arr = parse_url($url);
41
42         $via_proxy = $use_proxy ? ! in_the_net($no_proxy, $arr['host']) : FALSE;
43
44         // query
45         $arr['query'] = isset($arr['query']) ? '?' . $arr['query'] : '';
46         // port
47         $arr['port']  = isset($arr['port'])  ? $arr['port'] : 80;
48
49         $url_base = $arr['scheme'] . '://' . $arr['host'] . ':' . $arr['port'];
50         $url_path = isset($arr['path']) ? $arr['path'] : '/';
51         $url = ($via_proxy ? $url_base : '') . $url_path . $arr['query'];
52
53         $query = $method . ' ' . $url . ' HTTP/1.0' . "\r\n";
54         $query .= 'Host: ' . $arr['host'] . "\r\n";
55         $query .= 'User-Agent: PukiWiki/' . S_VERSION . "\r\n";
56
57         // Basic-auth for HTTP proxy server
58         if ($need_proxy_auth && isset($proxy_auth_user) && isset($proxy_auth_pass))
59                 $query .= 'Proxy-Authorization: Basic '.
60                         base64_encode($proxy_auth_user . ':' . $proxy_auth_pass) . "\r\n";
61
62         // (Normal) Basic-auth for remote host
63         if (isset($arr['user']) && isset($arr['pass']))
64                 $query .= 'Authorization: Basic '.
65                         base64_encode($arr['user'] . ':' . $arr['pass']) . "\r\n";
66
67         $query .= $headers;
68
69         if (strtoupper($method) == 'POST') {
70                 // 'application/x-www-form-urlencoded', especially for TrackBack ping
71                 $POST = array();
72                 foreach ($post as $name=>$val) $POST[] = $name . '=' . urlencode($val);
73                 $data = join('&', $POST);
74
75                 if (preg_match('/^[a-zA-Z0-9_-]+$/', $content_charset)) {
76                         // Legacy but simple
77                         $query .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
78                 } else {
79                         // With charset (NOTE: Some implementation may hate this)
80                         $query .= 'Content-Type: application/x-www-form-urlencoded' .
81                                 '; charset=' . strtolower($content_charset) . "\r\n";
82                 }
83
84                 $query .= 'Content-Length: ' . strlen($data) . "\r\n";
85                 $query .= "\r\n";
86                 $query .= $data;
87         } else {
88                 $query .= "\r\n";
89         }
90
91         $errno  = 0;
92         $errstr = '';
93         $fp = fsockopen(
94                 $via_proxy ? $proxy_host : $arr['host'],
95                 $via_proxy ? $proxy_port : $arr['port'],
96                 $errno, $errstr, 30);
97         if ($fp === FALSE) {
98                 return array(
99                         'query'  => $query, // Query string
100                         'rc'     => $errno, // Error number
101                         'header' => '',     // Header
102                         'data'   => $errstr // Error message
103                 );
104         }
105         fputs($fp, $query);
106         $response = '';
107         while (! feof($fp)) $response .= fread($fp, 4096);
108         fclose($fp);
109
110         $resp = explode("\r\n\r\n", $response, 2);
111         $rccd = explode(' ', $resp[0], 3); // array('HTTP/1.1', '200', 'OK\r\n...')
112         $rc   = (integer)$rccd[1];
113
114         switch ($rc) {
115         case 301: // Moved Permanently
116         case 302: // Moved Temporarily
117                 $matches = array();
118                 if (preg_match('/^Location: (.+)$/m', $resp[0], $matches)
119                         && --$redirect_max > 0)
120                 {
121                         $url = trim($matches[1]);
122                         if (! preg_match('/^https?:\//', $url)) {
123                                 // Relative path to Absolute
124                                 if ($url{0} != '/')
125                                         $url = substr($url_path, 0, strrpos($url_path, '/')) . '/' . $url;
126                                 $url = $url_base . $url; // Add sheme, host
127                         }
128                         // Redirect
129                         return pkwk_http_request($url, $method, $headers, $post, $redirect_max);
130                 }
131         }
132         return array(
133                 'query'  => $query,   // Query String
134                 'rc'     => $rc,      // Response Code
135                 'header' => $resp[0], // Header
136                 'data'   => $resp[1]  // Data
137         );
138 }
139
140 // Separate IPv4 network-address and its netmask
141 define('PKWK_CIDR_NETWORK_REGEX', '/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\/([0-9.]+))?$/');
142
143 // Check if the $host is in the specified network(s)
144 function in_the_net($networks = array(), $host = '')
145 {
146         if (empty($networks) || $host == '') return FALSE;
147         if (! is_array($networks)) $networks = array($networks);
148
149         $matches = array();
150
151         if (preg_match(PKWK_CIDR_NETWORK_REGEX, $host, $matches)) {
152                 $ip = $matches[1];
153         } else {
154                 $ip = gethostbyname($host); // May heavy
155         }
156         $l_ip = ip2long($ip);
157
158         foreach ($networks as $network) {
159                 if (preg_match(PKWK_CIDR_NETWORK_REGEX, $network, $matches) &&
160                     is_long($l_ip) && long2ip($l_ip) == $ip) {
161                         // $host seems valid IPv4 address
162                         // Sample: '10.0.0.0/8' or '10.0.0.0/255.0.0.0'
163                         $l_net = ip2long($matches[1]); // '10.0.0.0'
164                         $mask  = isset($matches[2]) ? $matches[2] : 32; // '8' or '255.0.0.0'
165                         $mask  = is_numeric($mask) ?
166                                 pow(2, 32) - pow(2, 32 - $mask) : // '8' means '8-bit mask'
167                                 ip2long($mask);                   // '255.0.0.0' (the same)
168
169                         if (($l_ip & $mask) == $l_net) return TRUE;
170                 } else {
171                         // $host seems not IPv4 address. May be a DNS name like 'foobar.example.com'?
172                         foreach ($networks as $network)
173                                 if (preg_match('/\.?\b' . preg_quote($network, '/') . '$/', $host))
174                                         return TRUE;
175                 }
176         }
177
178         return FALSE; // Not found
179 }