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 - 2013 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
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);
413 * Ignore empty lines because of non-blocking mode, you cannot use
414 * empty() here as it would also see \r\n as "empty".
416 if (strlen($line) == 0) {
417 // uslepp a little to avoid 100% CPU load
424 // Check for broken HTTP implementations
425 if (substr(strtolower($line), 0, 7) == 'server:') {
426 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
427 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
430 // Add it to response
431 //* DEBUG: */ print 'line(' . strlen($line) . ')='.$line.'<br />';
432 array_push($response, $line);
438 // Time request if debug-mode is enabled
439 if (isDebugModeEnabled()) {
440 // Add debug message...
441 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(TRUE) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
444 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, TRUE).'</pre>');
445 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, TRUE).'</pre>');
447 // Proxy agent found or something went wrong?
448 if (!isFilledArray($response)) {
449 // No response, maybe timeout
450 $response = array('', '', '');
451 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
452 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && (isProxyUsed() === TRUE)) {
453 // Proxy header detected, so remove two lines
454 array_shift($response);
455 array_shift($response);
458 // Was the request successfull?
459 if ((!isHttpStatusOkay($response[0])) && ($allowOnlyHttpOkay === TRUE)) {
460 // Not found / access forbidden
461 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
462 $response = array('', '', '');
464 // Check array for chuncked encoding
465 $response = unchunkHttpResponse($response);
472 // Is HTTP status okay?
473 function isHttpStatusOkay ($header) {
475 return in_array(strtoupper(trim($header)), array('HTTP/1.1 200 OK', 'HTTP/1.0 200 OK'));
478 // Sets up a proxy tunnel for given hostname and through resource
479 function setupProxyTunnel ($host, $proxyHost, $port, $resource) {
481 $response = array('', '', '');
483 // Generate CONNECT request header
484 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
485 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
486 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . getConfig('HTTP_EOL');
488 // Use login data to proxy? (username at least!)
489 if (getProxyUsername() != '') {
491 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
492 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
496 $proxyTunnel .= getConfig('HTTP_EOL');
497 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
500 fwrite($resource, $proxyTunnel);
503 if (feof($resource)) {
504 // No response received
508 // Read the first line
509 $resp = trim(fgets($resource, 10240));
510 $respArray = explode(' ', $resp);
511 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
520 // Check array for chuncked encoding
521 function unchunkHttpResponse ($response) {
522 // Default is not chunked
525 // Check if we have chunks
526 foreach ($response as $line) {
527 // Make lower-case and trim it
531 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
535 } elseif (empty($line)) {
536 // Empty line found (header->body)
542 $body = removeHttpHeaderFromResponse($response);
545 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isChunked=' . intval($isChunked));
546 if ($isChunked === TRUE) {
547 // Make sure, that body is an array
548 assert(is_array($body));
550 // Good, we still have the HTTP headers in there, so we need to get rid
551 // of them temporarly
552 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), TRUE)).'</pre>');
553 $tempResponse = http_chunked_decode(implode('', $body));
555 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
556 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).'/'.gettype($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
558 // Re-add the headers
559 $response = mergeHttpHeadersWithBody($tempResponse);
560 } elseif (is_array($body)) {
562 * Make sure the body is in one array element as many other functions
563 * get disturbed by it.
566 // Put all array elements from body together
567 $body = implode('', $body);
569 // Now merge the extracted headers + fixed body together
570 $response = mergeHttpHeadersWithBody($body);
573 // Return the unchunked array
577 // Merges HTTP header lines with given body (string)
578 function mergeHttpHeadersWithBody ($body) {
579 // Add empty entry to mimic header->body
580 $GLOBALS['http_headers'][] = getConfig('HTTP_EOL');
582 // Make sure at least one header is there (which is still not valid but okay here)
583 assert(isFilledArray($GLOBALS['http_headers']));
585 // Merge both together
586 return merge_array($GLOBALS['http_headers'], array(count($GLOBALS['http_headers']) => $body));
589 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
590 function removeHttpHeaderFromResponse ($response) {
591 // Save headers for later usage
592 $GLOBALS['http_headers'] = array();
594 // The first array element has to contain HTTP
595 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
596 // Okay, we have headers, now remove them with a second array
597 $response2 = $response;
598 foreach ($response as $line) {
600 array_shift($response2);
602 // Trim it for testing
603 $lineTest = trim($line);
605 // Is this line empty?
606 if (empty($lineTest)) {
611 // Is the last line set and is not ending with \r\n?
612 if ((isset($GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1])) && (substr($GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1], -2, 2) != getConfig('HTTP_EOL'))) {
613 // Add it to previous one
614 $GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1] .= $line;
616 // Add full line to temporary global array
617 array_push($GLOBALS['http_headers'], $line);
621 // Write back the array
622 $response = $response2;
625 // Return the modified response array
629 // Returns the flag if a broken HTTP server implementation was detected
630 function isBrokenHttpServerImplentation () {
632 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === TRUE));
638 // Extract host from script name
639 function extractHostnameFromUrl (&$script) {
640 // Use default SERVER_URL by default... ;) So?
641 $url = getServerUrl();
643 // Is this URL valid?
644 if (substr($script, 0, 7) == 'http://') {
645 // Use the hostname from script URL as new hostname
646 $url = substr($script, 7);
647 $extract = explode('/', $url);
649 // Done extracting the URL :)
653 $host = str_replace(array('http://', 'https://'), array('', ''), $url);
655 // Is there a slash at the end?
656 if (isInString('/', $host)) {
657 $host = substr($host, 0, strpos($host, '/'));
660 // Is there a double-dot in? (Means port number)
661 if (strpos($host, ':') !== FALSE) {
662 // Detected a double-dot
663 $hostArray = explode(':', $host);
664 $host = $hostArray[0];
667 // Generate relative URL
668 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
669 if (substr(strtolower($script), 0, 7) == 'http://') {
670 // But only if http:// is in front!
671 $script = substr($script, (strlen($url) + 7));
672 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
674 $script = substr($script, (strlen($url) + 8));
677 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
678 if (substr($script, 0, 1) == '/') {
679 $script = substr($script, 1);
686 // Adds a HTTP header to array
687 function addHttpHeader ($header) {
689 //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
690 array_push($GLOBALS['http_header'], trim($header));
693 // Flushes all HTTP headers
694 function flushHttpHeaders () {
695 // Is the header already sent?
696 if (headers_sent()) {
698 reportBug(__FUNCTION__, __LINE__, 'Headers already sent!');
699 } elseif ((!isset($GLOBALS['http_header'])) || (!is_array($GLOBALS['http_header']))) {
700 // Not set or not an array
701 reportBug(__FUNCTION__, __LINE__, 'Headers not set or not an array, isset()=' . isset($GLOBALS['http_header']) . ', please report this.');
704 // Flush all headers if found
705 foreach ($GLOBALS['http_header'] as $header) {
706 // Send a single header
710 // Mark them as flushed
711 $GLOBALS['http_header'] = array();
714 //-----------------------------------------------------------------------------
715 // Automatically re-created functions, all taken from user comments on www.php.net
716 //-----------------------------------------------------------------------------
718 if (!function_exists('http_build_query')) {
719 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
720 function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
722 foreach ((array) $requestData as $k => $v) {
723 if (is_int($k) && !is_null($prefix)) {
724 $k = urlencode($prefix . $k);
727 if ((!empty($key)) || ($key === 0)) {
728 $k = $key . '[' . urlencode($k) . ']';
731 if (is_array($v) || is_object($v)) {
732 array_push($ret, http_build_query($v, '', $sep, $k));
734 array_push($ret, $k . '=' . urlencode($v));
739 $sep = ini_get('arg_separator.output');
742 return implode($sep, $ret);
746 if (!function_exists('http_chunked_decode')) {
748 * dechunk an HTTP 'transfer-encoding: chunked' message.
750 * @param $chunk The encoded message
751 * @return $dechunk The decoded message. If $chunk wasn't encoded properly reportBug() is being called
752 * @author Marques Johansson (initial author)
753 * @author Roland Haeder (heavy modifications and simplification)
754 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
756 function http_chunked_decode ($chunk) {
757 // Detect multi-byte encoding
758 $mbPrefix = detectMultiBytePrefix($chunk);
759 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
761 // Init some variables
763 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
766 // Walk through all chunks
767 while ($offset < $len) {
768 // Where does the \r\n begin?
769 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
772 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
773 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
775 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
778 // Get next hex-coded chunk length
779 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
782 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
786 // Validation if it is hexadecimal
787 if (!isHexadecimal($chunkLenHex)) {
788 // Please help debugging this
789 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
790 reportBug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
792 // This won't be reached
796 // Position of next chunk is right after \r\n
797 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
798 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
801 print 'chunkLen='.$chunkLen.'<br />
802 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
805 // Moved out for debugging
806 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
807 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
810 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
811 * is currently (revision 7567 and maybe earlier) broken and does
812 * not include the \r\n characters when it sents a "chunked" HTTP
816 if (isBrokenHttpServerImplentation()) {
817 // Count occurrences of \r\n
818 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
822 * Correct chunk length because some broken HTTP server
823 * implementation subtract occurrences of \r\n in their chunk
826 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
828 // Add next chunk to $dechunk
829 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
832 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
833 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
835 count='.$count.'<br />
836 chunkLen='.$chunkLen.'<br />
837 chunkLenHex='.$chunkLenHex.'<br />
838 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
839 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
842 // Is $offset + $chunkLen larger than or equal $len?
843 if (($offset + $chunkLen) >= $len) {
844 // Then stop processing here
848 // Calculate offset of next chunk
849 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
852 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
853 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
854 ---:---:---:---:---:---:---:---:---<br />
859 // Return de-chunked string
864 // Getter for request method
865 function getHttpRequestMethod () {
866 // Console is default
867 $requestMethod = 'console';
870 if (isset($_SERVER['REQUEST_METHOD'])) {
871 // Get current request method
872 $requestMethod = $_SERVER['REQUEST_METHOD'];
876 return $requestMethod;
879 // Checks if 'content_type' is set
880 function isContentTypeSet () {
881 return isset($GLOBALS['content_type']);
884 // Setter for content type
885 function setContentType ($contentType) {
886 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'contentType=' . $contentType);
887 $GLOBALS['content_type'] = (string) $contentType;
890 // Getter for content type
891 function getContentType () {
893 if (!isContentTypeSet()) {
895 reportBug(__FUNCTION__, __LINE__, 'content_type not set in GLOBALS array.');
899 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content_type=' . $GLOBALS['content_type']);
900 return $GLOBALS['content_type'];
903 // Logs wrong SERVER_NAME attempts
904 function logWrongServerNameRedirect () {
905 // Is ext-sql_patches at least version 0.9.2?
906 if (isExtensionInstalledAndNewer('sql_patches', '0.9.2')) {
907 // Is there an entry?
908 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'", sqlEscapeString(detectRemoteAddr(TRUE)), sqlEscapeString(detectUserAgent(TRUE)), sqlEscapeString(detectReferer(TRUE))))) == 1) {
909 // Update counter, as all are the same
910 sqlQueryEscaped("UPDATE
911 `{?_MYSQL_PREFIX?}_server_name_log`
913 `server_name_counter`=`server_name_counter`+1
915 `server_name`='%s' AND
916 `server_name_remote_addr`='%s' AND
917 `server_name_ua`='%s' AND
918 `server_name_referrer`='%s'
922 detectRemoteAddr(TRUE),
923 detectUserAgent(TRUE),
925 ), __FUNCTION__, __LINE__);
928 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_server_name_log` (`server_name`, `server_name_remote_addr`, `server_name_ua`, `server_name_referrer`) VALUES('%s','%s', '%s', '%s')",
931 detectRemoteAddr(TRUE),
932 detectUserAgent(TRUE),
934 ), __FUNCTION__, __LINE__);