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://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());
61 // Generates the full GET URL from given base URL and data array
62 function generateGetUrlFromBaseUrlData ($baseUrl, $requestData = array()) {
67 $body = http_build_query($requestData, '', '&');
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 (!isInString('?', $baseUrl)) {
73 // No, so first char must be question mark
83 // Remove trailed & to make it more conform
84 if (substr($getUrl, -1, 1) == '&') {
85 $getUrl = substr($getUrl, 0, -1);
93 // Removes http[s]://<hostname> from given url
94 function removeHttpHostNameFromUrl ($url) {
96 $remove = explode(':', $url);
97 $remove = explode('/', substr($remove[1], 3));
99 // Remove the first element (should be the hostname)
102 // implode() back all other elements and prepend a slash
103 $url = '/' . implode('/', $remove);
105 // Return prepared URL
109 // Send a HEAD request
110 function sendHeadRequest ($baseUrl, $requestData = array()) {
111 // Generate full GET URL
112 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
114 // Extract hostname and port from script
115 $host = extractHostnameFromUrl($baseUrl);
117 // Remove http[s]://<hostname> from url
118 $getUrl = removeHttpHostNameFromUrl($getUrl);
120 // Generate HEAD request header
121 $request = 'HEAD ' . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
122 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
123 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
124 if (isConfigEntrySet('FULL_VERSION')) {
125 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
127 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
129 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
130 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
131 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
132 $request .= 'Connection: close' . getConfig('HTTP_EOL');
133 $request .= getConfig('HTTP_EOL');
135 // Send the raw request
136 $response = sendRawRequest($host, $request);
138 // Return the result to the caller function
142 // Send a GET request
143 function sendGetRequest ($baseUrl, $requestData = array(), $removeHeader = false) {
144 // Generate full GET URL
145 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
147 // Extract hostname and port from script
148 $host = extractHostnameFromUrl($baseUrl);
150 // Remove http[s]://<hostname> from url
151 $getUrl = removeHttpHostNameFromUrl($getUrl);
153 // Generate GET request header
154 $request = 'GET ' . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
155 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
156 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
157 if (isConfigEntrySet('FULL_VERSION')) {
158 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
160 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
162 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
163 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
164 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
165 $request .= 'Connection: close' . getConfig('HTTP_EOL');
166 $request .= getConfig('HTTP_EOL');
168 // Send the raw request
169 $response = sendRawRequest($host, $request);
171 // Should we remove header lines?
172 if ($removeHeader === true) {
174 $response = removeHttpHeaderFromResponse($response);
177 // Return the result to the caller function
181 // Send a POST request
182 function sendPostRequest ($baseUrl, $requestData, $removeHeader = false) {
183 // Extract host name from script
184 $host = extractHostnameFromUrl($baseUrl);
186 // Construct request body
187 $body = http_build_query($requestData, '', '&');
189 // Remove http(s)://$host from base URL
190 $baseUrl = removeHttpHostNameFromUrl($baseUrl);
192 // Generate POST request header
193 $request = 'POST ' . trim($baseUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
194 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
195 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
196 if (isConfigEntrySet('FULL_VERSION')) {
197 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
199 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
201 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
202 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
203 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
204 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
205 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
206 $request .= 'Connection: close' . getConfig('HTTP_EOL');
207 $request .= getConfig('HTTP_EOL');
212 // Send the raw request
213 $response = sendRawRequest($host, $request);
215 // Should we remove header lines?
216 if ($removeHeader === true) {
218 $response = removeHttpHeaderFromResponse($response);
221 // Return the result to the caller function
225 // Sends a raw request to another host
226 function sendRawRequest ($host, $request) {
227 //* DEBUG: */ die('host='.$host.',request=<pre>'.$request.'</pre>');
228 // Init errno and errdesc with 'all fine' values
232 // Default port is 80
236 $response = array('', '', '');
238 // Default is not to use proxy
241 // Default is non-broken HTTP server implementation
242 $GLOBALS['is_http_server_broken'] = false;
244 // Are proxy settins set?
251 loadIncludeOnce('inc/classes/resolver.class.php');
253 // Extract port part from host
254 $portArray = explode(':', $host);
255 if (count($portArray) == 2) {
256 // Extract host and port
257 $host = $portArray[0];
258 $port = $portArray[1];
259 } elseif (count($portArray) > 2) {
260 // This should not happen!
261 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
264 // Get resolver instance
265 $resolver = new HostnameResolver();
268 if ($useProxy === true) {
269 // Resolve hostname into IP address
270 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
272 // Connect to host through proxy connection
273 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
275 // Resolve hostname into IP address
276 $ip = $resolver->resolveHostname($host);
278 // Connect to host directly
279 $fp = fsockopen($ip, $port, $errno, $errdesc, 30);
283 if (!is_resource($fp)) {
285 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
287 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
288 // Cannot set non-blocking mode or timeout
289 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
294 if ($useProxy === true) {
295 // Setup proxy tunnel
296 $response = setupProxyTunnel($host, $port, $fp);
298 // If the response is invalid, abort
299 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
301 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
307 fwrite($fp, $request);
310 $start = microtime(true);
314 // Get info from stream
315 $info = stream_get_meta_data($fp);
317 // Is it timed out? 15 seconds is a really patient...
318 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
320 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
326 // Get line from stream
327 $line = fgets($fp, 128);
329 // Ignore empty lines because of non-blocking mode
331 // uslepp a little to avoid 100% CPU load
338 // Check for broken HTTP implementations
339 if (substr(strtolower($line), 0, 7) == 'server:') {
340 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
341 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
344 // Add it to response
345 //* DEBUG: */ print 'line='.$line.'<br />';
352 // Time request if debug-mode is enabled
353 if (isDebugModeEnabled()) {
354 // Add debug message...
355 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
358 // Skip first empty lines
360 foreach ($resp as $idx => $line) {
364 // Is this line empty?
367 array_shift($response);
369 // Abort on first non-empty line
374 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
375 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
377 // Proxy agent found or something went wrong?
378 if (!isset($response[0])) {
379 // No response, maybe timeout
380 $response = array('', '', '');
381 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
382 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
383 // Proxy header detected, so remove two lines
384 array_shift($response);
385 array_shift($response);
388 // Was the request successfull?
389 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
390 // Not found / access forbidden
391 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
392 $response = array('', '', '');
394 // Check array for chuncked encoding
395 $response = unchunkHttpResponse($response);
402 // Sets up a proxy tunnel for given hostname and through resource
403 function setupProxyTunnel ($host, $port, $resource) {
405 $response = array('', '', '');
407 // Generate CONNECT request header
408 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
409 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
411 // Use login data to proxy? (username at least!)
412 if (getProxyUsername() != '') {
414 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
415 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
419 $proxyTunnel .= getConfig('HTTP_EOL');
420 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
423 fwrite($fp, $proxyTunnel);
427 // No response received
431 // Read the first line
432 $resp = trim(fgets($fp, 10240));
433 $respArray = explode(' ', $resp);
434 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
443 // Check array for chuncked encoding
444 function unchunkHttpResponse ($response) {
445 // Default is not chunked
448 // Check if we have chunks
449 foreach ($response as $line) {
450 // Make lower-case and trim it
454 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
462 if ($isChunked === true) {
463 // Good, we still have the HTTP headers in there, so we need to get rid
464 // of them temporarly
465 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), true)).'</pre>');
466 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
468 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
469 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
471 // Re-add the headers
472 $response = merge_array($GLOBALS['http_headers'], stringToArray("\n", $tempResponse));
475 // Return the unchunked array
479 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
480 function removeHttpHeaderFromResponse ($response) {
481 // Save headers for later usage
482 $GLOBALS['http_headers'] = array();
484 // The first array element has to contain HTTP
485 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
486 // Okay, we have headers, now remove them with a second array
487 $response2 = $response;
488 foreach ($response as $line) {
490 array_shift($response2);
492 // Add full line to temporary global array
493 $GLOBALS['http_headers'][] = $line;
495 // Trim it for testing
496 $lineTest = trim($line);
498 // Is this line empty?
499 if (empty($lineTest)) {
505 // Write back the array
506 $response = $response2;
509 // Return the modified response array
513 // Returns the flag if a broken HTTP server implementation was detected
514 function isBrokenHttpServerImplentation () {
516 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === true));
522 //-----------------------------------------------------------------------------
523 // Automatically re-created functions, all taken from user comments on www.php.net
524 //-----------------------------------------------------------------------------
526 if (!function_exists('http_build_query')) {
527 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
528 function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
530 foreach ((array) $requestData as $k => $v) {
531 if (is_int($k) && $prefix != null) {
532 $k = urlencode($prefix . $k);
535 if ((!empty($key)) || ($key === 0)) {
536 $k = $key . '[' . urlencode($k) . ']';
539 if (is_array($v) || is_object($v)) {
540 array_push($ret, http_build_query($v, '', $sep, $k));
542 array_push($ret, $k . '=' . urlencode($v));
547 $sep = ini_get('arg_separator.output');
550 return implode($sep, $ret);
554 if (!function_exists('http_chunked_decode')) {
556 * dechunk an HTTP 'transfer-encoding: chunked' message.
558 * @param $chunk The encoded message
559 * @return $dechunk The decoded message. If $chunk wasn't encoded properly debug_report_bug() is being called
560 * @author Marques Johansson (initial author)
561 * @author Roland Haeder (heavy modifications and simplification)
562 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
564 function http_chunked_decode ($chunk) {
565 // Detect multi-byte encoding
566 $mbPrefix = detectMultiBytePrefix($chunk);
567 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
569 // Init some variables
571 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
574 // Walk through all chunks
575 while ($offset < $len) {
576 // Where does the \r\n begin?
577 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
580 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
581 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
583 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
586 // Get next hex-coded chunk length
587 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
590 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
594 // Validation if it is hexadecimal
595 if (!isHexadecimal($chunkLenHex)) {
596 // Please help debugging this
597 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
598 debug_report_bug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
600 // This won't be reached
604 // Position of next chunk is right after \r\n
605 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
606 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
609 print 'chunkLen='.$chunkLen.'<br />
610 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
613 // Moved out for debugging
614 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
615 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
618 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
619 * is currently (revision 7567 and maybe earlier) broken and does
620 * not include the \r\n characters when it sents a "chunked" HTTP
624 if (isBrokenHttpServerImplentation()) {
625 // Count occurrences of \r\n
626 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
630 * Correct chunk length because some broken HTTP server
631 * implementation subtract occurrences of \r\n in their chunk
634 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
636 // Add next chunk to $dechunk
637 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
640 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
641 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
643 count='.$count.'<br />
644 chunkLen='.$chunkLen.'<br />
645 chunkLenHex='.$chunkLenHex.'<br />
646 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
647 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
650 // Is $offset + $chunkLen larger than or equal $len?
651 if (($offset + $chunkLen) >= $len) {
652 // Then stop processing here
656 // Calculate offset of next chunk
657 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
660 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
661 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
662 ---:---:---:---:---:---:---:---:---<br />
667 // Return de-chunked string