2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 03/08/2011 *
4 * =================== Last change: 03/08/2011 *
6 * -------------------------------------------------------------------- *
7 * File : http-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : HTTP-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : HTTP-relevante Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Sends out all headers required for HTTP/1.1 reply
44 function sendHttpHeaders () {
46 $now = gmdate('D, d M Y H:i:s') . ' GMT';
49 sendHeader('HTTP/1.1 ' . getHttpStatus());
51 // General headers for no caching
52 sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
53 sendHeader('Last-Modified: ' . $now);
54 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
55 sendHeader('Pragma: no-cache'); // HTTP/1.0
56 sendHeader('Connection: Close');
57 sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
58 sendHeader('Content-Language: ' . getLanguage());
62 function sendGetRequest ($baseUrl, $data = array(), $removeHeader = false) {
63 // Extract hostname and port from script
64 $host = extractHostnameFromUrl($baseUrl);
67 $body = http_build_query($data, '', '&');
69 // There should be data, else we don't need to extend $baseUrl with $body
71 // Do we have a question-mark in the script?
72 if (strpos($baseUrl, '?') === false) {
73 // No, so first char must be question mark
83 // Remove trailed & to make it more conform
84 if (substr($baseUrl, -1, 1) == '&') {
85 $baseUrl = substr($baseUrl, 0, -1);
89 // Generate GET request header
90 $request = 'GET /' . trim($baseUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
91 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
92 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
93 if (isConfigEntrySet('FULL_VERSION')) {
94 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
96 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
98 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
99 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
100 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
101 $request .= 'Connection: close' . getConfig('HTTP_EOL');
102 $request .= getConfig('HTTP_EOL');
104 // Send the raw request
105 $response = sendRawRequest($host, $request);
107 // Should we remove header lines?
108 if ($removeHeader === true) {
110 $response = removeHttpHeaderFromResponse($response);
113 // Return the result to the caller function
117 // Send a POST request
118 function sendPostRequest ($baseUrl, array $postData, $removeHeader = false) {
119 // Extract host name from script
120 $host = extractHostnameFromUrl($baseUrl);
122 // Construct request body
123 $body = http_build_query($postData, '', '&');
125 // Generate POST request header
126 $request = 'POST /' . trim($baseUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
127 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
128 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
129 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
130 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
131 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
132 $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
133 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
134 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
135 $request .= 'Connection: close' . getConfig('HTTP_EOL');
136 $request .= getConfig('HTTP_EOL');
141 // Send the raw request
142 $response = sendRawRequest($host, $request);
144 // Should we remove header lines?
145 if ($removeHeader === true) {
147 $response = removeHttpHeaderFromResponse($response);
150 // Return the result to the caller function
154 // Sends a raw request to another host
155 function sendRawRequest ($host, $request) {
156 // Init errno and errdesc with 'all fine' values
160 // Default port is 80
164 $response = array('', '', '');
166 // Default is not to use proxy
169 // Default is non-broken HTTP server implementation
170 $GLOBALS['is_http_server_broken'] = false;
172 // Are proxy settins set?
179 loadIncludeOnce('inc/classes/resolver.class.php');
181 // Extract port part from host
182 $portArray = explode(':', $host);
183 if (count($portArray) == 2) {
184 // Extract host and port
185 $host = $portArray[0];
186 $port = $portArray[1];
187 } elseif (count($portArray) > 2) {
188 // This should not happen!
189 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
192 // Get resolver instance
193 $resolver = new HostnameResolver();
196 //* DEBUG: */ die('baseUrl=' . $baseUrl);
197 if ($useProxy === true) {
198 // Resolve hostname into IP address
199 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
201 // Connect to host through proxy connection
202 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
204 // Resolve hostname into IP address
205 $ip = $resolver->resolveHostname($host);
207 // Connect to host directly
208 $fp = fsockopen($ip, $port, $errno, $errdesc, 30);
212 if (!is_resource($fp)) {
214 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
216 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
217 // Cannot set non-blocking mode or timeout
218 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
223 if ($useProxy === true) {
224 // Setup proxy tunnel
225 $response = setupProxyTunnel($host, $port, $fp);
227 // If the response is invalid, abort
228 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
230 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
236 fwrite($fp, $request);
239 $start = microtime(true);
243 // Get info from stream
244 $info = stream_get_meta_data($fp);
246 // Is it timed out? 15 seconds is a really patient...
247 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
249 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
255 // Get line from stream
256 $line = fgets($fp, 128);
258 // Ignore empty lines because of non-blocking mode
260 // uslepp a little to avoid 100% CPU load
267 // Check for broken HTTP implementations
268 if (substr(strtolower($line), 0, 7) == 'server:') {
269 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
270 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
273 // Add it to response
280 // Time request if debug-mode is enabled
281 if (isDebugModeEnabled()) {
282 // Add debug message...
283 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
286 // Skip first empty lines
288 foreach ($resp as $idx => $line) {
292 // Is this line empty?
295 array_shift($response);
297 // Abort on first non-empty line
302 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
303 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
305 // Proxy agent found or something went wrong?
306 if (!isset($response[0])) {
307 // No response, maybe timeout
308 $response = array('', '', '');
309 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
310 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
311 // Proxy header detected, so remove two lines
312 array_shift($response);
313 array_shift($response);
316 // Was the request successfull?
317 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
318 // Not found / access forbidden
319 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
320 $response = array('', '', '');
322 // Check array for chuncked encoding
323 $response = unchunkHttpResponse($response);
330 // Sets up a proxy tunnel for given hostname and through resource
331 function setupProxyTunnel ($host, $port, $resource) {
333 $response = array('', '', '');
335 // Generate CONNECT request header
336 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
337 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
339 // Use login data to proxy? (username at least!)
340 if (getProxyUsername() != '') {
342 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
343 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
347 $proxyTunnel .= getConfig('HTTP_EOL');
348 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
351 fwrite($fp, $proxyTunnel);
355 // No response received
359 // Read the first line
360 $resp = trim(fgets($fp, 10240));
361 $respArray = explode(' ', $resp);
362 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
371 // Check array for chuncked encoding
372 function unchunkHttpResponse (array $response) {
373 // Default is not chunked
376 // Check if we have chunks
377 foreach ($response as $line) {
378 // Make lower-case and trim it
379 $line = trim(strtolower($line));
382 if ((strpos($line, 'transfer-encoding') !== false) && (strpos($line, 'chunked') !== false)) {
390 if ($isChunked === true) {
391 // Good, we still have the HTTP headers in there, so we need to get rid
392 // of them temporarly
393 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), true)).'</pre>');
394 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
396 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
397 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
399 // Re-add the headers
400 $response = merge_array($GLOBALS['http_headers'], stringToArray("\n", $tempResponse));
403 // Return the unchunked array
407 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
408 function removeHttpHeaderFromResponse (array $response) {
409 // Save headers for later usage
410 $GLOBALS['http_headers'] = array();
412 // The first array element has to contain HTTP
413 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
414 // Okay, we have headers, now remove them with a second array
415 $response2 = $response;
416 foreach ($response as $line) {
418 array_shift($response2);
420 // Add full line to temporary global array
421 $GLOBALS['http_headers'][] = $line;
423 // Trim it for testing
424 $lineTest = trim($line);
426 // Is this line empty?
427 if (empty($lineTest)) {
433 // Write back the array
434 $response = $response2;
437 // Return the modified response array
441 // Returns the flag if a broken HTTP server implementation was detected
442 function isBrokenHttpServerImplentation () {
444 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === true));
450 //-----------------------------------------------------------------------------
451 // Automatically re-created functions, all taken from user comments on www.php.net
452 //-----------------------------------------------------------------------------
454 if (!function_exists('http_build_query')) {
455 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
456 function http_build_query($data, $prefix = '', $sep = '', $key = '') {
458 foreach ((array) $data as $k => $v) {
459 if (is_int($k) && $prefix != null) {
460 $k = urlencode($prefix . $k);
463 if ((!empty($key)) || ($key === 0)) {
464 $k = $key . '[' . urlencode($k) . ']';
467 if (is_array($v) || is_object($v)) {
468 array_push($ret, http_build_query($v, '', $sep, $k));
470 array_push($ret, $k . '=' . urlencode($v));
475 $sep = ini_get('arg_separator.output');
478 return implode($sep, $ret);
482 if (!function_exists('http_chunked_decode')) {
484 * dechunk an HTTP 'transfer-encoding: chunked' message.
486 * @param $chunk The encoded message
487 * @return $dechunk The decoded message. If $chunk wasn't encoded properly debug_report_bug() is being called
488 * @author Marques Johansson (initial author)
489 * @author Roland Haeder (heavy modifications and simplification)
490 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
492 function http_chunked_decode ($chunk) {
493 // Detect multi-byte encoding
494 $mbPrefix = detectMultiBytePrefix($chunk);
495 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
497 // Init some variables
499 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
502 // Walk through all chunks
503 while ($offset < $len) {
504 // Where does the \r\n begin?
505 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
508 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
509 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
511 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
514 // Get next hex-coded chunk length
515 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
518 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
522 // Validation if it is hexadecimal
523 if (!isHexadecimal($chunkLenHex)) {
524 // Please help debugging this
525 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
526 debug_report_bug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
528 // This won't be reached
532 // Position of next chunk is right after \r\n
533 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
534 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
537 print 'chunkLen='.$chunkLen.'<br />
538 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
541 // Moved out for debugging
542 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
543 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
546 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
547 * is currently (revision 7567 and maybe earlier) broken and does
548 * not include the \r\n characters when it sents a "chunked" HTTP
552 if (isBrokenHttpServerImplentation()) {
553 // Count occurrences of \r\n
554 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
558 * Correct chunk length because some broken HTTP server
559 * implementation subtract occurrences of \r\n in their chunk
562 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
564 // Add next chunk to $dechunk
565 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
568 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
569 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
571 count='.$count.'<br />
572 chunkLen='.$chunkLen.'<br />
573 chunkLenHex='.$chunkLenHex.'<br />
574 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
575 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
578 // Is $offset + $chunkLen larger than or equal $len?
579 if (($offset + $chunkLen) >= $len) {
580 // Then stop processing here
584 // Calculate offset of next chunk
585 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
588 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
589 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
590 ---:---:---:---:---:---:---:---:---<br />
595 // Return de-chunked string