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 * -------------------------------------------------------------------- *
13 * Copyright (c) 2003 - 2009 by Roland Haeder *
14 * Copyright (c) 2009 - 2013 by Mailer Developer Team *
15 * For more information visit: http://mxchange.org *
17 * This program is free software; you can redistribute it and/or modify *
18 * it under the terms of the GNU General Public License as published by *
19 * the Free Software Foundation; either version 2 of the License, or *
20 * (at your option) any later version. *
22 * This program is distributed in the hope that it will be useful, *
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
25 * GNU General Public License for more details. *
27 * You should have received a copy of the GNU General Public License *
28 * along with this program; if not, write to the Free Software *
29 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
31 ************************************************************************/
33 // Some security stuff...
34 if (!defined('__SECURITY')) {
38 // Initialize HTTP handling
39 function initHttp () {
41 $GLOBALS['http_header'] = array();
44 // Sends out all headers required for HTTP/1.1 reply
45 function sendHttpHeaders () {
47 $now = gmdate('D, d M Y H:i:s') . ' GMT';
50 addHttpHeader('HTTP/1.1 ' . getHttpStatus());
52 // General headers for no caching
53 addHttpHeader('Expires: ' . $now); // RFC2616 - Section 14.21
54 addHttpHeader('Last-Modified: ' . $now);
55 addHttpHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
56 addHttpHeader('Pragma: no-cache'); // HTTP/1.0
57 addHttpHeader('Connection: Close');
59 // There shall be no output mode in raw output-mode
60 if (!isRawOutputMode()) {
61 // Send content-type not in raw output-mode
62 addHttpHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
66 addHttpHeader('Content-Language: ' . getLanguage());
69 // Checks whether the URL is full-qualified (http[s]:// + hostname [+ request data])
70 function isFullQualifiedUrl ($url) {
72 if (!isset($GLOBALS[__FUNCTION__][$url])) {
74 $GLOBALS[__FUNCTION__][$url] = ((substr($url, 0, 7) == 'http://') || (substr($url, 0, 8) == 'https://'));
78 return $GLOBALS[__FUNCTION__][$url];
81 // Generates the full GET URL from given base URL and data array
82 function generateGetUrlFromBaseUrlData ($baseUrl, $requestData = array()) {
86 // Is it full-qualified?
87 if (!isFullQualifiedUrl($getUrl)) {
88 // Need to prepend a slash?
89 if (substr($getUrl, 0, 1) != '/') {
91 $getUrl = '/' . $getUrl;
94 // Prepend http://hostname from mxchange.org server
95 $getUrl = getServerUrl() . $getUrl;
99 $body = http_build_query($requestData, '', '&');
101 // There should be data, else we don't need to extend $baseUrl with $body
103 // Is there a question-mark in the script?
104 if (!isInString('?', $baseUrl)) {
105 // No, so first char must be question mark
115 // Remove trailed & to make it more conform
116 if (substr($getUrl, -1, 1) == '&') {
117 $getUrl = substr($getUrl, 0, -1);
125 // Removes http[s]://<hostname> from given url
126 function removeHttpHostNameFromUrl ($url) {
128 $remove = explode(':', $url);
129 $remove = explode('/', substr($remove[1], 3));
131 // Remove the first element (should be the hostname)
134 // implode() back all other elements and prepend a slash
135 $url = '/' . implode('/', $remove);
137 // Return prepared URL
141 // Sends a HTTP request (GET, POST, HEAD are currently supported)
142 function sendHttpRequest ($requestType, $baseUrl, $requestData = array(), $removeHeader = FALSE, $allowOnlyHttpOkay = TRUE) {
146 // Start "detecting" the request type
147 switch ($requestType) {
148 case 'HEAD': // Send a HTTP/1.1 HEAD request
149 $response = sendHttpHeadRequest($baseUrl, $requestData, $allowOnlyHttpOkay);
152 case 'GET': // Send a HTTP/1.1 GET request
153 $response = sendHttpGetRequest($baseUrl, $requestData, $removeHeader, $allowOnlyHttpOkay);
156 case 'POST': // Send a HTTP/1.1 POST request
157 $response = sendHttpPostRequest($baseUrl, $requestData, $removeHeader, $allowOnlyHttpOkay);
160 default: // Unsupported HTTP request, this is really bad and needs fixing
161 reportBug(__FUNCTION__, __LINE__, 'Unsupported request detected. requestType=' . $requestType . ',baseUrl=' . $baseUrl . ',requestData()=' . count($requestData));
169 // Sends a HEAD request
170 function sendHttpHeadRequest ($baseUrl, $requestData = array(), $allowOnlyHttpOkay = TRUE) {
171 // Generate full GET URL
172 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
173 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getUrl=' . $getUrl);
175 // Is there http[s]:// in front of the URL?
176 if (isFullQualifiedUrl($getUrl)) {
177 // Remove http[s]://<hostname> from URL
178 $getUrl = removeHttpHostNameFromUrl($getUrl);
179 } elseif (substr($getUrl, 0, 1) != '/') {
181 $getUrl = '/' . $getUrl;
184 // Extract hostname and port from script
185 $host = extractHostnameFromUrl($baseUrl);
187 // Generate HEAD request header
188 $request = 'HEAD ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
189 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
190 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
191 if (isConfigEntrySet('FULL_VERSION')) {
192 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
194 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
196 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
197 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
198 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
199 $request .= 'Connection: close' . getConfig('HTTP_EOL');
200 $request .= getConfig('HTTP_EOL');
202 // Send the raw request
203 $response = sendRawRequest($host, $request, $allowOnlyHttpOkay);
205 // Return the result to the caller function
209 // Send a GET request
210 function sendHttpGetRequest ($baseUrl, $requestData = array(), $removeHeader = FALSE, $allowOnlyHttpOkay = TRUE) {
211 // Generate full GET URL
212 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
213 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getUrl=' . $getUrl);
215 // Is there http[s]:// in front of the URL?
216 if (isFullQualifiedUrl($getUrl)) {
217 // Remove http[s]://<hostname> from url
218 $getUrl = removeHttpHostNameFromUrl($getUrl);
219 } elseif (substr($getUrl, 0, 1) != '/') {
221 $getUrl = '/' . $getUrl;
224 // Extract hostname and port from script
225 $host = extractHostnameFromUrl($baseUrl);
227 // Generate GET request header
228 $request = 'GET ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
229 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
230 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
231 if (isConfigEntrySet('FULL_VERSION')) {
232 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
234 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
236 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
237 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
238 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
239 $request .= 'Connection: close' . getConfig('HTTP_EOL');
240 $request .= getConfig('HTTP_EOL');
242 // Send the raw request
243 $response = sendRawRequest($host, $request, $allowOnlyHttpOkay);
245 // Should we remove header lines?
246 if ($removeHeader === TRUE) {
248 $response = removeHttpHeaderFromResponse($response);
251 // Return the result to the caller function
255 // Send a POST request, sometimes even POST requests have no parameters
256 function sendHttpPostRequest ($baseUrl, $requestData = array(), $removeHeader = FALSE, $allowOnlyHttpOkay = TRUE) {
257 // Copy baseUrl to getUrl
260 // Is there http[s]:// in front of the URL?
261 if (isFullQualifiedUrl($getUrl)) {
262 // Remove http[s]://<hostname> from url
263 $getUrl = removeHttpHostNameFromUrl($getUrl);
264 } elseif (substr($getUrl, 0, 1) != '/') {
266 $getUrl = '/' . $getUrl;
269 // Extract host name from script
270 $host = extractHostnameFromUrl($baseUrl);
272 // Construct request body
273 $body = http_build_query($requestData, '', '&');
275 // Generate POST request header
276 $request = 'POST ' . (isProxyUsed() === TRUE ? $getUrl : '') . trim($getUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
277 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
278 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
279 if (isConfigEntrySet('FULL_VERSION')) {
280 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
282 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
284 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
285 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
286 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
287 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
288 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
289 $request .= 'Connection: close' . getConfig('HTTP_EOL');
290 $request .= getConfig('HTTP_EOL');
295 // Send the raw request
296 $response = sendRawRequest($host, $request, $allowOnlyHttpOkay);
298 // Should we remove header lines?
299 if ($removeHeader === TRUE) {
301 $response = removeHttpHeaderFromResponse($response);
304 // Return the result to the caller function
308 // Sends a raw request (string) to given host (hostnames will be solved)
309 function sendRawRequest ($host, $request, $allowOnlyHttpOkay = TRUE) {
310 //* DEBUG: */ die('host='.$host.',request=<pre>'.$request.'</pre>');
311 // Init errno and errdesc with 'all fine' values
315 // Default port is 80
321 // Default is non-broken HTTP server implementation
322 $GLOBALS['is_http_server_broken'] = FALSE;
325 loadIncludeOnce('inc/classes/resolver.class.php');
327 // Extract port part from host
328 $portArray = explode(':', $host);
329 if (count($portArray) == 2) {
330 // Extract host and port
331 $host = $portArray[0];
332 $port = $portArray[1];
333 } elseif (count($portArray) > 2) {
334 // This should not happen!
335 reportBug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
338 // Get resolver instance
339 $resolver = new HostnameResolver();
341 // Default is no proxy
344 // Is the configuration entry set?
345 if ((!isInstaller()) && (isConfigEntrySet('proxy_host'))) {
347 $proxyHost = compileRawCode(getProxyHost());
351 if (isProxyUsed() === TRUE) {
352 // Resolve hostname into IP address
353 $ip = $resolver->resolveHostname($proxyHost);
355 // Connect to host through proxy connection
356 $resource = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
358 // Resolve hostname into IP address
359 $ip = $resolver->resolveHostname($host);
361 // Connect to host directly
362 $resource = fsockopen($ip, $port, $errno, $errdesc, 30);
364 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ip=' . $ip . ',host=' . $host . ',isProxyUsed()=' . intval(isProxyUsed()));
367 if (!is_resource($resource)) {
369 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
370 return array('', '', '');
371 } elseif ((!stream_set_blocking($resource, 0)) || (!stream_set_timeout($resource, 1))) {
372 // Cannot set non-blocking mode or timeout
373 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
374 return array('', '', '');
377 // Shall proxy be used?
378 if (isProxyUsed() === TRUE) {
379 // Setup proxy tunnel
380 $response = setupProxyTunnel($host, $proxyHost, $port, $resource);
382 // If the response is invalid, abort
383 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
385 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
391 fwrite($resource, $request);
394 $start = microtime(TRUE);
397 while (!feof($resource)) {
398 // Get info from stream
399 $info = stream_get_meta_data($resource);
401 // Is it timed out? 15 seconds is a really patient...
402 if (($info['timed_out'] == TRUE) || (microtime(TRUE) - $start) > 15) {
404 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
410 // Get line from stream
411 $line = fgets($resource, 128);
414 * Ignore empty lines because of non-blocking mode, you cannot use
415 * empty() here as it would also see \r\n as "empty".
417 if (strlen($line) == 0) {
418 // uslepp a little to avoid 100% CPU load
425 // Check for broken HTTP implementations
426 if (substr(strtolower($line), 0, 7) == 'server:') {
427 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
428 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
431 // Add it to response
432 //* DEBUG: */ print 'line(' . strlen($line) . ')='.$line.'<br />';
433 array_push($response, $line);
439 // Time request if debug-mode is enabled
440 if (isDebugModeEnabled()) {
441 // Add debug message...
442 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(TRUE) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
445 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, TRUE).'</pre>');
446 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, TRUE).'</pre>');
448 // Proxy agent found or something went wrong?
449 if (!isFilledArray($response)) {
450 // No response, maybe timeout
451 $response = array('', '', '');
452 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
453 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && (isProxyUsed() === TRUE)) {
454 // Proxy header detected, so remove two lines
455 array_shift($response);
456 array_shift($response);
459 // Was the request successfull?
460 if ((!isHttpStatusOkay($response[0])) && ($allowOnlyHttpOkay === TRUE)) {
461 // Not found / access forbidden
462 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
463 $response = array('', '', '');
465 // Check array for chuncked encoding
466 $response = unchunkHttpResponse($response);
473 // Is HTTP status okay?
474 function isHttpStatusOkay ($header) {
476 return in_array(strtoupper(trim($header)), array('HTTP/1.1 200 OK', 'HTTP/1.0 200 OK'));
479 // Sets up a proxy tunnel for given hostname and through resource
480 function setupProxyTunnel ($host, $proxyHost, $port, $resource) {
482 $response = array('', '', '');
484 // Generate CONNECT request header
485 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
486 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
487 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . getConfig('HTTP_EOL');
489 // Use login data to proxy? (username at least!)
490 if (getProxyUsername() != '') {
492 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
493 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
497 $proxyTunnel .= getConfig('HTTP_EOL');
498 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
501 fwrite($resource, $proxyTunnel);
504 if (feof($resource)) {
505 // No response received
509 // Read the first line
510 $resp = trim(fgets($resource, 10240));
511 $respArray = explode(' ', $resp);
512 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
521 // Check array for chuncked encoding
522 function unchunkHttpResponse ($response) {
523 // Default is not chunked
526 // Check if we have chunks
527 foreach ($response as $line) {
528 // Make lower-case and trim it
532 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
536 } elseif (empty($line)) {
537 // Empty line found (header->body)
543 $body = removeHttpHeaderFromResponse($response);
546 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isChunked=' . intval($isChunked));
547 if ($isChunked === TRUE) {
548 // Make sure, that body is an array
549 assert(is_array($body));
551 // Good, we still have the HTTP headers in there, so we need to get rid
552 // of them temporarly
553 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), TRUE)).'</pre>');
554 $tempResponse = http_chunked_decode(implode('', $body));
556 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
557 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).'/'.gettype($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
559 // Re-add the headers
560 $response = mergeHttpHeadersWithBody($tempResponse);
561 } elseif (is_array($body)) {
563 * Make sure the body is in one array element as many other functions
564 * get disturbed by it.
567 // Put all array elements from body together
568 $body = implode('', $body);
570 // Now merge the extracted headers + fixed body together
571 $response = mergeHttpHeadersWithBody($body);
574 // Return the unchunked array
578 // Merges HTTP header lines with given body (string)
579 function mergeHttpHeadersWithBody ($body) {
580 // Add empty entry to mimic header->body
581 $GLOBALS['http_headers'][] = getConfig('HTTP_EOL');
583 // Make sure at least one header is there (which is still not valid but okay here)
584 assert(isFilledArray($GLOBALS['http_headers']));
586 // Merge both together
587 return merge_array($GLOBALS['http_headers'], array(count($GLOBALS['http_headers']) => $body));
590 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
591 function removeHttpHeaderFromResponse ($response) {
592 // Save headers for later usage
593 $GLOBALS['http_headers'] = array();
595 // The first array element has to contain HTTP
596 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
597 // Okay, we have headers, now remove them with a second array
598 $response2 = $response;
599 foreach ($response as $line) {
601 array_shift($response2);
603 // Trim it for testing
604 $lineTest = trim($line);
606 // Is this line empty?
607 if (empty($lineTest)) {
612 // Is the last line set and is not ending with \r\n?
613 if ((isset($GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1])) && (substr($GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1], -2, 2) != getConfig('HTTP_EOL'))) {
614 // Add it to previous one
615 $GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1] .= $line;
617 // Add full line to temporary global array
618 array_push($GLOBALS['http_headers'], $line);
622 // Write back the array
623 $response = $response2;
626 // Return the modified response array
630 // Returns the flag if a broken HTTP server implementation was detected
631 function isBrokenHttpServerImplentation () {
633 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === TRUE));
639 // Extract host from script name
640 function extractHostnameFromUrl (&$script) {
641 // Use default SERVER_URL by default... ;) So?
642 $url = getServerUrl();
644 // Is this URL valid?
645 if (substr($script, 0, 7) == 'http://') {
646 // Use the hostname from script URL as new hostname
647 $url = substr($script, 7);
648 $extract = explode('/', $url);
650 // Done extracting the URL :)
654 $host = str_replace(array('http://', 'https://'), array('', ''), $url);
656 // Is there a slash at the end?
657 if (isInString('/', $host)) {
658 $host = substr($host, 0, strpos($host, '/'));
661 // Is there a double-dot in? (Means port number)
662 if (strpos($host, ':') !== FALSE) {
663 // Detected a double-dot
664 $hostArray = explode(':', $host);
665 $host = $hostArray[0];
668 // Generate relative URL
669 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
670 if (substr(strtolower($script), 0, 7) == 'http://') {
671 // But only if http:// is in front!
672 $script = substr($script, (strlen($url) + 7));
673 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
675 $script = substr($script, (strlen($url) + 8));
678 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
679 if (substr($script, 0, 1) == '/') {
680 $script = substr($script, 1);
687 // Adds a HTTP header to array
688 function addHttpHeader ($header) {
690 //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
691 array_push($GLOBALS['http_header'], trim($header));
694 // Flushes all HTTP headers
695 function flushHttpHeaders () {
696 // Is the header already sent?
697 if (headers_sent()) {
699 reportBug(__FUNCTION__, __LINE__, 'Headers already sent!');
700 } elseif ((!isset($GLOBALS['http_header'])) || (!is_array($GLOBALS['http_header']))) {
701 // Not set or not an array
702 reportBug(__FUNCTION__, __LINE__, 'Headers not set or not an array, isset()=' . isset($GLOBALS['http_header']) . ', please report this.');
705 // Flush all headers if found
706 foreach ($GLOBALS['http_header'] as $header) {
707 // Send a single header
711 // Mark them as flushed
712 $GLOBALS['http_header'] = array();
715 //-----------------------------------------------------------------------------
716 // Automatically re-created functions, all taken from user comments on www.php.net
717 //-----------------------------------------------------------------------------
719 if (!function_exists('http_build_query')) {
720 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
721 function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
723 foreach ((array) $requestData as $k => $v) {
724 if (is_int($k) && !is_null($prefix)) {
725 $k = urlencode($prefix . $k);
728 if ((!empty($key)) || ($key === 0)) {
729 $k = $key . '[' . urlencode($k) . ']';
732 if (is_array($v) || is_object($v)) {
733 array_push($ret, http_build_query($v, '', $sep, $k));
735 array_push($ret, $k . '=' . urlencode($v));
740 $sep = ini_get('arg_separator.output');
743 return implode($sep, $ret);
747 if (!function_exists('http_chunked_decode')) {
749 * dechunk an HTTP 'transfer-encoding: chunked' message.
751 * @param $chunk The encoded message
752 * @return $dechunk The decoded message. If $chunk wasn't encoded properly reportBug() is being called
753 * @author Marques Johansson (initial author)
754 * @author Roland Haeder (heavy modifications and simplification)
755 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
757 function http_chunked_decode ($chunk) {
758 // Detect multi-byte encoding
759 $mbPrefix = detectMultiBytePrefix($chunk);
760 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
762 // Init some variables
764 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
767 // Walk through all chunks
768 while ($offset < $len) {
769 // Where does the \r\n begin?
770 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
773 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
774 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
776 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
779 // Get next hex-coded chunk length
780 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
783 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
787 // Validation if it is hexadecimal
788 if (!isHexadecimal($chunkLenHex)) {
789 // Please help debugging this
790 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
791 reportBug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
793 // This won't be reached
797 // Position of next chunk is right after \r\n
798 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
799 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
802 print 'chunkLen='.$chunkLen.'<br />
803 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
806 // Moved out for debugging
807 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
808 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
811 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
812 * is currently (revision 7567 and maybe earlier) broken and does
813 * not include the \r\n characters when it sents a "chunked" HTTP
817 if (isBrokenHttpServerImplentation()) {
818 // Count occurrences of \r\n
819 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
823 * Correct chunk length because some broken HTTP server
824 * implementation subtract occurrences of \r\n in their chunk
827 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
829 // Add next chunk to $dechunk
830 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
833 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
834 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
836 count='.$count.'<br />
837 chunkLen='.$chunkLen.'<br />
838 chunkLenHex='.$chunkLenHex.'<br />
839 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
840 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
843 // Is $offset + $chunkLen larger than or equal $len?
844 if (($offset + $chunkLen) >= $len) {
845 // Then stop processing here
849 // Calculate offset of next chunk
850 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
853 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
854 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
855 ---:---:---:---:---:---:---:---:---<br />
860 // Return de-chunked string
865 // Getter for request method
866 function getHttpRequestMethod () {
867 // Console is default
868 $requestMethod = 'console';
871 if (isset($_SERVER['REQUEST_METHOD'])) {
872 // Get current request method
873 $requestMethod = $_SERVER['REQUEST_METHOD'];
877 return $requestMethod;
880 // Checks if 'content_type' is set
881 function isContentTypeSet () {
882 return isset($GLOBALS['content_type']);
885 // Setter for content type
886 function setContentType ($contentType) {
887 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'contentType=' . $contentType);
888 $GLOBALS['content_type'] = (string) $contentType;
891 // Getter for content type
892 function getContentType () {
894 if (!isContentTypeSet()) {
896 reportBug(__FUNCTION__, __LINE__, 'content_type not set in GLOBALS array.');
900 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content_type=' . $GLOBALS['content_type']);
901 return $GLOBALS['content_type'];
904 // Logs wrong SERVER_NAME attempts
905 function logWrongServerNameRedirect () {
906 // Is ext-sql_patches at least version 0.9.2?
907 if (isExtensionInstalledAndNewer('sql_patches', '0.9.2')) {
908 // Is there an entry?
909 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) {
910 // Update counter, as all are the same
911 sqlQueryEscaped("UPDATE
912 `{?_MYSQL_PREFIX?}_server_name_log`
914 `server_name_counter`=`server_name_counter`+1
916 `server_name`='%s' AND
917 `server_name_remote_addr`='%s' AND
918 `server_name_ua`='%s' AND
919 `server_name_referrer`='%s'
923 detectRemoteAddr(TRUE),
924 detectUserAgent(TRUE),
926 ), __FUNCTION__, __LINE__);
929 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')",
932 detectRemoteAddr(TRUE),
933 detectUserAgent(TRUE),
935 ), __FUNCTION__, __LINE__);
940 // Check if response status OK and array index 'response' is set
941 function isHttpResponseStatusOkay ($response) {
942 // Assertion on array
943 assert(is_array($response));
946 $isOkay = ((isset($response['status'])) && ($response['status'] == 'OK') && (!empty($response['response'])));