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 - 2012 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 // Initialize HTTP handling
44 function initHttp () {
46 $GLOBALS['http_header'] = array();
49 // Sends out all headers required for HTTP/1.1 reply
50 function sendHttpHeaders () {
52 $now = gmdate('D, d M Y H:i:s') . ' GMT';
55 addHttpHeader('HTTP/1.1 ' . getHttpStatus());
57 // General headers for no caching
58 addHttpHeader('Expires: ' . $now); // RFC2616 - Section 14.21
59 addHttpHeader('Last-Modified: ' . $now);
60 addHttpHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
61 addHttpHeader('Pragma: no-cache'); // HTTP/1.0
62 addHttpHeader('Connection: Close');
64 // There shall be no output mode in raw output-mode
65 if (!isRawOutputMode()) {
66 // Send content-type not in raw output-mode
67 addHttpHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
71 addHttpHeader('Content-Language: ' . getLanguage());
74 // Checks whether the URL is full-qualified (http[s]:// + hostname [+ request data])
75 function isFullQualifiedUrl ($url) {
77 if (!isset($GLOBALS[__FUNCTION__][$url])) {
79 $GLOBALS[__FUNCTION__][$url] = ((substr($url, 0, 7) == 'http://') || (substr($url, 0, 8) == 'https://'));
83 return $GLOBALS[__FUNCTION__][$url];
86 // Generates the full GET URL from given base URL and data array
87 function generateGetUrlFromBaseUrlData ($baseUrl, $requestData = array()) {
91 // Is it full-qualified?
92 if (!isFullQualifiedUrl($getUrl)) {
93 // Need to prepend a slash?
94 if (substr($getUrl, 0, 1) != '/') {
96 $getUrl = '/' . $getUrl;
99 // Prepend http://hostname from mxchange.org server
100 $getUrl = getServerUrl() . $getUrl;
104 $body = http_build_query($requestData, '', '&');
106 // There should be data, else we don't need to extend $baseUrl with $body
108 // Is there a question-mark in the script?
109 if (!isInString('?', $baseUrl)) {
110 // No, so first char must be question mark
120 // Remove trailed & to make it more conform
121 if (substr($getUrl, -1, 1) == '&') {
122 $getUrl = substr($getUrl, 0, -1);
130 // Removes http[s]://<hostname> from given url
131 function removeHttpHostNameFromUrl ($url) {
133 $remove = explode(':', $url);
134 $remove = explode('/', substr($remove[1], 3));
136 // Remove the first element (should be the hostname)
139 // implode() back all other elements and prepend a slash
140 $url = '/' . implode('/', $remove);
142 // Return prepared URL
146 // Sends a HTTP request (GET, POST, HEAD are currently supported)
147 function sendHttpRequest ($requestType, $baseUrl, $requestData = array(), $removeHeader = FALSE, $allowOnlyHttpOkay = TRUE) {
151 // Start "detecting" the request type
152 switch ($requestType) {
153 case 'HEAD': // Send a HTTP/1.1 HEAD request
154 $response = sendHttpHeadRequest($baseUrl, $requestData, $allowOnlyHttpOkay);
157 case 'GET': // Send a HTTP/1.1 GET request
158 $response = sendHttpGetRequest($baseUrl, $requestData, $removeHeader, $allowOnlyHttpOkay);
161 case 'POST': // Send a HTTP/1.1 POST request
162 $response = sendHttpPostRequest($baseUrl, $requestData, $removeHeader, $allowOnlyHttpOkay);
165 default: // Unsupported HTTP request, this is really bad and needs fixing
166 reportBug(__FUNCTION__, __LINE__, 'Unsupported request detected. requestType=' . $requestType . ',baseUrl=' . $baseUrl . ',requestData()=' . count($requestData));
174 // Sends a HEAD request
175 function sendHttpHeadRequest ($baseUrl, $requestData = array(), $allowOnlyHttpOkay = TRUE) {
176 // Generate full GET URL
177 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
178 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getUrl=' . $getUrl);
180 // Is there http[s]:// in front of the URL?
181 if (isFullQualifiedUrl($getUrl)) {
182 // Remove http[s]://<hostname> from URL
183 $getUrl = removeHttpHostNameFromUrl($getUrl);
184 } elseif (substr($getUrl, 0, 1) != '/') {
186 $getUrl = '/' . $getUrl;
189 // Extract hostname and port from script
190 $host = extractHostnameFromUrl($baseUrl);
192 // Generate HEAD request header
193 $request = 'HEAD ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($getUrl) . ' HTTP/1.1' . 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: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . 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 .= 'Connection: close' . getConfig('HTTP_EOL');
205 $request .= getConfig('HTTP_EOL');
207 // Send the raw request
208 $response = sendRawRequest($host, $request, $allowOnlyHttpOkay);
210 // Return the result to the caller function
214 // Send a GET request
215 function sendHttpGetRequest ($baseUrl, $requestData = array(), $removeHeader = FALSE, $allowOnlyHttpOkay = TRUE) {
216 // Generate full GET URL
217 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
218 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getUrl=' . $getUrl);
220 // Is there http[s]:// in front of the URL?
221 if (isFullQualifiedUrl($getUrl)) {
222 // Remove http[s]://<hostname> from url
223 $getUrl = removeHttpHostNameFromUrl($getUrl);
224 } elseif (substr($getUrl, 0, 1) != '/') {
226 $getUrl = '/' . $getUrl;
229 // Extract hostname and port from script
230 $host = extractHostnameFromUrl($baseUrl);
232 // Generate GET request header
233 $request = 'GET ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
234 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
235 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
236 if (isConfigEntrySet('FULL_VERSION')) {
237 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
239 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
241 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
242 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
243 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
244 $request .= 'Connection: close' . getConfig('HTTP_EOL');
245 $request .= getConfig('HTTP_EOL');
247 // Send the raw request
248 $response = sendRawRequest($host, $request, $allowOnlyHttpOkay);
250 // Should we remove header lines?
251 if ($removeHeader === TRUE) {
253 $response = removeHttpHeaderFromResponse($response);
256 // Return the result to the caller function
260 // Send a POST request, sometimes even POST requests have no parameters
261 function sendHttpPostRequest ($baseUrl, $requestData = array(), $removeHeader = FALSE, $allowOnlyHttpOkay = TRUE) {
262 // Copy baseUrl to getUrl
265 // Is there http[s]:// in front of the URL?
266 if (isFullQualifiedUrl($getUrl)) {
267 // Remove http[s]://<hostname> from url
268 $getUrl = removeHttpHostNameFromUrl($getUrl);
269 } elseif (substr($getUrl, 0, 1) != '/') {
271 $getUrl = '/' . $getUrl;
274 // Extract host name from script
275 $host = extractHostnameFromUrl($baseUrl);
277 // Construct request body
278 $body = http_build_query($requestData, '', '&');
280 // Generate POST request header
281 $request = 'POST ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($baseUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
282 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
283 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
284 if (isConfigEntrySet('FULL_VERSION')) {
285 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
287 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
289 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
290 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
291 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
292 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
293 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
294 $request .= 'Connection: close' . getConfig('HTTP_EOL');
295 $request .= getConfig('HTTP_EOL');
300 // Send the raw request
301 $response = sendRawRequest($host, $request, $allowOnlyHttpOkay);
303 // Should we remove header lines?
304 if ($removeHeader === TRUE) {
306 $response = removeHttpHeaderFromResponse($response);
309 // Return the result to the caller function
313 // Sends a raw request (string) to given host (hostnames will be solved)
314 function sendRawRequest ($host, $request, $allowOnlyHttpOkay = TRUE) {
315 //* DEBUG: */ die('host='.$host.',request=<pre>'.$request.'</pre>');
316 // Init errno and errdesc with 'all fine' values
320 // Default port is 80
324 $response = array('', '', '');
326 // Default is non-broken HTTP server implementation
327 $GLOBALS['is_http_server_broken'] = FALSE;
330 loadIncludeOnce('inc/classes/resolver.class.php');
332 // Extract port part from host
333 $portArray = explode(':', $host);
334 if (count($portArray) == 2) {
335 // Extract host and port
336 $host = $portArray[0];
337 $port = $portArray[1];
338 } elseif (count($portArray) > 2) {
339 // This should not happen!
340 reportBug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
343 // Get resolver instance
344 $resolver = new HostnameResolver();
347 $proxyHost = compileRawCode(getProxyHost());
350 if (isProxyUsed() === TRUE) {
351 // Resolve hostname into IP address
352 $ip = $resolver->resolveHostname($proxyHost);
354 // Connect to host through proxy connection
355 $resource = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
357 // Resolve hostname into IP address
358 $ip = $resolver->resolveHostname($host);
360 // Connect to host directly
361 $resource = fsockopen($ip, $port, $errno, $errdesc, 30);
363 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ip=' . $ip . ',host=' . $host . ',isProxyUsed()=' . intval(isProxyUsed()));
366 if (!is_resource($resource)) {
368 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
369 return array('', '', '');
370 } elseif ((!stream_set_blocking($resource, 0)) || (!stream_set_timeout($resource, 1))) {
371 // Cannot set non-blocking mode or timeout
372 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
373 return array('', '', '');
376 // Shall proxy be used?
377 if (isProxyUsed() === TRUE) {
378 // Setup proxy tunnel
379 $response = setupProxyTunnel($host, $proxyHost, $port, $resource);
381 // If the response is invalid, abort
382 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
384 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
390 fwrite($resource, $request);
393 $start = microtime(TRUE);
396 while (!feof($resource)) {
397 // Get info from stream
398 $info = stream_get_meta_data($resource);
400 // Is it timed out? 15 seconds is a really patient...
401 if (($info['timed_out'] == TRUE) || (microtime(TRUE) - $start) > 15) {
403 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
409 // Get line from stream
410 $line = fgets($resource, 128);
412 // Ignore empty lines because of non-blocking mode
414 // uslepp a little to avoid 100% CPU load
421 // Check for broken HTTP implementations
422 if (substr(strtolower($line), 0, 7) == 'server:') {
423 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
424 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
427 // Add it to response
428 //* DEBUG: */ print 'line='.$line.'<br />';
429 array_push($response, $line);
435 // Time request if debug-mode is enabled
436 if (isDebugModeEnabled()) {
437 // Add debug message...
438 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(TRUE) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
441 // Skip first empty lines
443 foreach ($resp as $idx => $line) {
447 // Is this line empty?
450 array_shift($response);
452 // Abort on first non-empty line
457 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, TRUE).'</pre>');
458 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, TRUE).'</pre>');
460 // Proxy agent found or something went wrong?
461 if (count($response) == 0) {
462 // No response, maybe timeout
463 $response = array('', '', '');
464 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
465 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && (isProxyUsed() === TRUE)) {
466 // Proxy header detected, so remove two lines
467 array_shift($response);
468 array_shift($response);
471 // Was the request successfull?
472 if ((!isHttpStatusOkay($response[0])) && ($allowOnlyHttpOkay === TRUE)) {
473 // Not found / access forbidden
474 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
475 $response = array('', '', '');
477 // Check array for chuncked encoding
478 $response = unchunkHttpResponse($response);
485 // Is HTTP status okay?
486 function isHttpStatusOkay ($header) {
488 return in_array(strtoupper(trim($header)), array('HTTP/1.1 200 OK', 'HTTP/1.0 200 OK'));
491 // Sets up a proxy tunnel for given hostname and through resource
492 function setupProxyTunnel ($host, $proxyHost, $port, $resource) {
494 $response = array('', '', '');
496 // Generate CONNECT request header
497 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
498 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
499 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . getConfig('HTTP_EOL');
501 // Use login data to proxy? (username at least!)
502 if (getProxyUsername() != '') {
504 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
505 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
509 $proxyTunnel .= getConfig('HTTP_EOL');
510 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
513 fwrite($resource, $proxyTunnel);
516 if (feof($resource)) {
517 // No response received
521 // Read the first line
522 $resp = trim(fgets($resource, 10240));
523 $respArray = explode(' ', $resp);
524 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
533 // Check array for chuncked encoding
534 function unchunkHttpResponse ($response) {
535 // Default is not chunked
538 // Check if we have chunks
539 foreach ($response as $line) {
540 // Make lower-case and trim it
544 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
548 } elseif (empty($line)) {
549 // Empty line found (header->body)
555 $body = removeHttpHeaderFromResponse($response);
558 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isChunked=' . intval($isChunked));
559 if ($isChunked === TRUE) {
560 // Make sure, that body is an array
561 assert(is_array($body));
563 // Good, we still have the HTTP headers in there, so we need to get rid
564 // of them temporarly
565 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), TRUE)).'</pre>');
566 $tempResponse = http_chunked_decode(implode('', $body));
568 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
569 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).'/'.gettype($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
571 // Re-add the headers
572 $response = mergeHttpHeadersWithBody($tempResponse);
573 } elseif (is_array($body)) {
575 * Make sure the body is in one array element as many other functions
576 * get disturbed by it.
579 // Put all array elements from body together
580 $body = implode('', $body);
582 // Now merge the extracted headers + fixed body together
583 $response = mergeHttpHeadersWithBody($body);
586 // Return the unchunked array
590 // Merges HTTP header lines with given body (string)
591 function mergeHttpHeadersWithBody ($body) {
592 // Make sure at least one header is there (which is still not valid but okay here)
593 assert((is_array($GLOBALS['http_headers'])) && (count($GLOBALS['http_headers']) > 0));
595 // Merge both together
596 return merge_array($GLOBALS['http_headers'], array(count($GLOBALS['http_headers']) => $body));
599 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
600 function removeHttpHeaderFromResponse ($response) {
601 // Save headers for later usage
602 $GLOBALS['http_headers'] = array();
604 // The first array element has to contain HTTP
605 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
606 // Okay, we have headers, now remove them with a second array
607 $response2 = $response;
608 foreach ($response as $line) {
610 array_shift($response2);
612 // Trim it for testing
613 $lineTest = trim($line);
615 // Is this line empty?
616 if (empty($lineTest)) {
621 // Add full line to temporary global array
622 array_push($GLOBALS['http_headers'], $line);
625 // Write back the array
626 $response = $response2;
629 // Return the modified response array
633 // Returns the flag if a broken HTTP server implementation was detected
634 function isBrokenHttpServerImplentation () {
636 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === TRUE));
642 // Extract host from script name
643 function extractHostnameFromUrl (&$script) {
644 // Use default SERVER_URL by default... ;) So?
645 $url = getServerUrl();
647 // Is this URL valid?
648 if (substr($script, 0, 7) == 'http://') {
649 // Use the hostname from script URL as new hostname
650 $url = substr($script, 7);
651 $extract = explode('/', $url);
653 // Done extracting the URL :)
657 $host = str_replace('http://', '', $url);
658 if (isInString('/', $host)) {
659 $host = substr($host, 0, strpos($host, '/'));
662 // Generate relative URL
663 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
664 if (substr(strtolower($script), 0, 7) == 'http://') {
665 // But only if http:// is in front!
666 $script = substr($script, (strlen($url) + 7));
667 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
669 $script = substr($script, (strlen($url) + 8));
672 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
673 if (substr($script, 0, 1) == '/') {
674 $script = substr($script, 1);
681 // Adds a HTTP header to array
682 function addHttpHeader ($header) {
684 //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
685 array_push($GLOBALS['http_header'], trim($header));
688 // Flushes all HTTP headers
689 function flushHttpHeaders () {
690 // Is the header already sent?
691 if (headers_sent()) {
693 reportBug(__FUNCTION__, __LINE__, 'Headers already sent!');
694 } elseif ((!isset($GLOBALS['http_header'])) || (!is_array($GLOBALS['http_header']))) {
695 // Not set or not an array
696 reportBug(__FUNCTION__, __LINE__, 'Headers not set or not an array, isset()=' . isset($GLOBALS['http_header']) . ', please report this.');
699 // Flush all headers if found
700 foreach ($GLOBALS['http_header'] as $header) {
701 // Send a single header
705 // Mark them as flushed
706 $GLOBALS['http_header'] = array();
709 //-----------------------------------------------------------------------------
710 // Automatically re-created functions, all taken from user comments on www.php.net
711 //-----------------------------------------------------------------------------
713 if (!function_exists('http_build_query')) {
714 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
715 function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
717 foreach ((array) $requestData as $k => $v) {
718 if (is_int($k) && !is_null($prefix)) {
719 $k = urlencode($prefix . $k);
722 if ((!empty($key)) || ($key === 0)) {
723 $k = $key . '[' . urlencode($k) . ']';
726 if (is_array($v) || is_object($v)) {
727 array_push($ret, http_build_query($v, '', $sep, $k));
729 array_push($ret, $k . '=' . urlencode($v));
734 $sep = ini_get('arg_separator.output');
737 return implode($sep, $ret);
741 if (!function_exists('http_chunked_decode')) {
743 * dechunk an HTTP 'transfer-encoding: chunked' message.
745 * @param $chunk The encoded message
746 * @return $dechunk The decoded message. If $chunk wasn't encoded properly reportBug() is being called
747 * @author Marques Johansson (initial author)
748 * @author Roland Haeder (heavy modifications and simplification)
749 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
751 function http_chunked_decode ($chunk) {
752 // Detect multi-byte encoding
753 $mbPrefix = detectMultiBytePrefix($chunk);
754 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
756 // Init some variables
758 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
761 // Walk through all chunks
762 while ($offset < $len) {
763 // Where does the \r\n begin?
764 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
767 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
768 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
770 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
773 // Get next hex-coded chunk length
774 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
777 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
781 // Validation if it is hexadecimal
782 if (!isHexadecimal($chunkLenHex)) {
783 // Please help debugging this
784 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
785 reportBug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
787 // This won't be reached
791 // Position of next chunk is right after \r\n
792 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
793 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
796 print 'chunkLen='.$chunkLen.'<br />
797 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
800 // Moved out for debugging
801 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
802 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
805 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
806 * is currently (revision 7567 and maybe earlier) broken and does
807 * not include the \r\n characters when it sents a "chunked" HTTP
811 if (isBrokenHttpServerImplentation()) {
812 // Count occurrences of \r\n
813 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
817 * Correct chunk length because some broken HTTP server
818 * implementation subtract occurrences of \r\n in their chunk
821 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
823 // Add next chunk to $dechunk
824 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
827 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
828 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
830 count='.$count.'<br />
831 chunkLen='.$chunkLen.'<br />
832 chunkLenHex='.$chunkLenHex.'<br />
833 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
834 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
837 // Is $offset + $chunkLen larger than or equal $len?
838 if (($offset + $chunkLen) >= $len) {
839 // Then stop processing here
843 // Calculate offset of next chunk
844 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
847 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
848 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
849 ---:---:---:---:---:---:---:---:---<br />
854 // Return de-chunked string
859 // Getter for request method
860 function getHttpRequestMethod () {
861 // Console is default
862 $requestMethod = 'console';
865 if (isset($_SERVER['REQUEST_METHOD'])) {
866 // Get current request method
867 $requestMethod = $_SERVER['REQUEST_METHOD'];
871 return $requestMethod;
874 // Checks if 'content_type' is set
875 function isContentTypeSet () {
876 return isset($GLOBALS['content_type']);
879 // Setter for content type
880 function setContentType ($contentType) {
881 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'contentType=' . $contentType);
882 $GLOBALS['content_type'] = (string) $contentType;
885 // Getter for content type
886 function getContentType () {
888 if (!isContentTypeSet()) {
890 reportBug(__FUNCTION__, __LINE__, 'content_type not set in GLOBALS array.');
894 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content_type=' . $GLOBALS['content_type']);
895 return $GLOBALS['content_type'];
898 // Logs wrong SERVER_NAME attempts
899 function logWrongServerNameRedirect () {
900 // Is ext-sql_patches at least version 0.9.2?
901 if (isExtensionInstalledAndNewer('sql_patches', '0.9.2')) {
902 // Is there an entry?
903 if (countSumTotalData(detectServerName(), 'server_name_log', 'server_name_id', 'server_name', TRUE, str_replace('%', '{PER}', sprintf(" AND `server_name_remote_addr`='%s' AND `server_name_ua`='%s' AND `server_name_referrer`='%s'", SQL_ESCAPE(detectRemoteAddr(TRUE)), SQL_ESCAPE(detectUserAgent(TRUE)), SQL_ESCAPE(detectReferer(TRUE))))) == 1) {
904 // Update counter, as all are the same
905 SQL_QUERY_ESC("UPDATE
906 `{?_MYSQL_PREFIX?}_server_name_log`
908 `server_name_counter`=`server_name_counter`+1
910 `server_name`='%s' AND
911 `server_name_remote_addr`='%s' AND
912 `server_name_ua`='%s' AND
913 `server_name_referrer`='%s'
917 detectRemoteAddr(TRUE),
918 detectUserAgent(TRUE),
920 ), __FUNCTION__, __LINE__);
923 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_server_name_log` (`server_name`, `server_name_remote_addr`, `server_name_ua`, `server_name_referrer`) VALUES('%s','%s', '%s', '%s')",
926 detectRemoteAddr(TRUE),
927 detectUserAgent(TRUE),
929 ), __FUNCTION__, __LINE__);