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) {
151 // Start "detecting" the request type
152 switch ($requestType) {
153 case 'HEAD': // Send a HTTP/1.1 HEAD request
154 $response = sendHeadRequest($baseUrl, $requestData);
157 case 'GET': // Send a HTTP/1.1 GET request
158 $response = sendGetRequest($baseUrl, $requestData, $removeHeader);
161 case 'POST': // Send a HTTP/1.1 POST request
162 $response = sendPostRequest($baseUrl, $requestData, $removeHeader);
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 sendHeadRequest ($baseUrl, $requestData = array()) {
176 // Generate full GET URL
177 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
179 // Is there http[s]:// in front of the URL?
180 if (isFullQualifiedUrl($getUrl)) {
181 // Remove http[s]://<hostname> from URL
182 $getUrl = removeHttpHostNameFromUrl($getUrl);
183 } elseif (substr($getUrl, 0, 1) != '/') {
185 $getUrl = '/' . $getUrl;
188 // Extract hostname and port from script
189 $host = extractHostnameFromUrl($baseUrl);
191 // Generate HEAD request header
192 $request = 'HEAD ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
193 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
194 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
195 if (isConfigEntrySet('FULL_VERSION')) {
196 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
198 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
200 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
201 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
202 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
203 $request .= 'Connection: close' . getConfig('HTTP_EOL');
204 $request .= getConfig('HTTP_EOL');
206 // Send the raw request
207 $response = sendRawRequest($host, $request);
209 // Return the result to the caller function
213 // Send a GET request
214 function sendGetRequest ($baseUrl, $requestData = array(), $removeHeader = FALSE) {
215 // Generate full GET URL
216 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
218 // Is there http[s]:// in front of the URL?
219 if (isFullQualifiedUrl($getUrl)) {
220 // Remove http[s]://<hostname> from url
221 $getUrl = removeHttpHostNameFromUrl($getUrl);
222 } elseif (substr($getUrl, 0, 1) != '/') {
224 $getUrl = '/' . $getUrl;
227 // Extract hostname and port from script
228 $host = extractHostnameFromUrl($baseUrl);
230 // Generate GET request header
231 $request = 'GET ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
232 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
233 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
234 if (isConfigEntrySet('FULL_VERSION')) {
235 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
237 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
239 $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
240 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
241 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
242 $request .= 'Connection: close' . getConfig('HTTP_EOL');
243 $request .= getConfig('HTTP_EOL');
245 // Send the raw request
246 $response = sendRawRequest($host, $request);
248 // Should we remove header lines?
249 if ($removeHeader === TRUE) {
251 $response = removeHttpHeaderFromResponse($response);
254 // Return the result to the caller function
258 // Send a POST request, sometimes even POST requests have no parameters
259 function sendPostRequest ($baseUrl, $requestData = array(), $removeHeader = FALSE) {
260 // Copy baseUrl to getUrl
263 // Is there http[s]:// in front of the URL?
264 if (isFullQualifiedUrl($getUrl)) {
265 // Remove http[s]://<hostname> from url
266 $getUrl = removeHttpHostNameFromUrl($getUrl);
267 } elseif (substr($getUrl, 0, 1) != '/') {
269 $getUrl = '/' . $getUrl;
272 // Extract host name from script
273 $host = extractHostnameFromUrl($baseUrl);
275 // Construct request body
276 $body = http_build_query($requestData, '', '&');
278 // Generate POST request header
279 $request = 'POST ' . (isProxyUsed() === TRUE ? $baseUrl : '') . trim($baseUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
280 $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
281 $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
282 if (isConfigEntrySet('FULL_VERSION')) {
283 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
285 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
287 $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
288 $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
289 $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
290 $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
291 $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
292 $request .= 'Connection: close' . getConfig('HTTP_EOL');
293 $request .= getConfig('HTTP_EOL');
298 // Send the raw request
299 $response = sendRawRequest($host, $request);
301 // Should we remove header lines?
302 if ($removeHeader === TRUE) {
304 $response = removeHttpHeaderFromResponse($response);
307 // Return the result to the caller function
311 // Sends a raw request (string) to given host (hostnames will be solved)
312 function sendRawRequest ($host, $request) {
313 //* DEBUG: */ die('host='.$host.',request=<pre>'.$request.'</pre>');
314 // Init errno and errdesc with 'all fine' values
318 // Default port is 80
322 $response = array('', '', '');
324 // Default is non-broken HTTP server implementation
325 $GLOBALS['is_http_server_broken'] = FALSE;
328 loadIncludeOnce('inc/classes/resolver.class.php');
330 // Extract port part from host
331 $portArray = explode(':', $host);
332 if (count($portArray) == 2) {
333 // Extract host and port
334 $host = $portArray[0];
335 $port = $portArray[1];
336 } elseif (count($portArray) > 2) {
337 // This should not happen!
338 reportBug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
341 // Get resolver instance
342 $resolver = new HostnameResolver();
345 $proxyHost = compileRawCode(getProxyHost());
348 if (isProxyUsed() === TRUE) {
349 // Resolve hostname into IP address
350 $ip = $resolver->resolveHostname($proxyHost);
352 // Connect to host through proxy connection
353 $resource = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
355 // Resolve hostname into IP address
356 $ip = $resolver->resolveHostname($host);
358 // Connect to host directly
359 $resource = fsockopen($ip, $port, $errno, $errdesc, 30);
361 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ip=' . $ip . ',host=' . $host . ',isProxyUsed()=' . intval(isProxyUsed()));
364 if (!is_resource($resource)) {
366 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
368 } elseif ((!stream_set_blocking($resource, 0)) || (!stream_set_timeout($resource, 1))) {
369 // Cannot set non-blocking mode or timeout
370 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
374 // Shall proxy be used?
375 if (isProxyUsed() === TRUE) {
376 // Setup proxy tunnel
377 $response = setupProxyTunnel($host, $proxyHost, $port, $resource);
379 // If the response is invalid, abort
380 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
382 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
388 fwrite($resource, $request);
391 $start = microtime(TRUE);
394 while (!feof($resource)) {
395 // Get info from stream
396 $info = stream_get_meta_data($resource);
398 // Is it timed out? 15 seconds is a really patient...
399 if (($info['timed_out'] == TRUE) || (microtime(TRUE) - $start) > 15) {
401 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
407 // Get line from stream
408 $line = fgets($resource, 128);
410 // Ignore empty lines because of non-blocking mode
412 // uslepp a little to avoid 100% CPU load
419 // Check for broken HTTP implementations
420 if (substr(strtolower($line), 0, 7) == 'server:') {
421 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
422 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
425 // Add it to response
426 //* DEBUG: */ print 'line='.$line.'<br />';
427 array_push($response, $line);
433 // Time request if debug-mode is enabled
434 if (isDebugModeEnabled()) {
435 // Add debug message...
436 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(TRUE) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
439 // Skip first empty lines
441 foreach ($resp as $idx => $line) {
445 // Is this line empty?
448 array_shift($response);
450 // Abort on first non-empty line
455 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, TRUE).'</pre>');
456 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, TRUE).'</pre>');
458 // Proxy agent found or something went wrong?
459 if (!isset($response[0])) {
460 // No response, maybe timeout
461 $response = array('', '', '');
462 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
463 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && (isProxyUsed() === TRUE)) {
464 // Proxy header detected, so remove two lines
465 array_shift($response);
466 array_shift($response);
469 // Was the request successfull?
470 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
471 // Not found / access forbidden
472 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
473 $response = array('', '', '');
475 // Check array for chuncked encoding
476 $response = unchunkHttpResponse($response);
483 // Sets up a proxy tunnel for given hostname and through resource
484 function setupProxyTunnel ($host, $proxyHost, $port, $resource) {
486 $response = array('', '', '');
488 // Generate CONNECT request header
489 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
490 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
491 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . getConfig('HTTP_EOL');
493 // Use login data to proxy? (username at least!)
494 if (getProxyUsername() != '') {
496 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
497 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
501 $proxyTunnel .= getConfig('HTTP_EOL');
502 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
505 fwrite($resource, $proxyTunnel);
508 if (feof($resource)) {
509 // No response received
513 // Read the first line
514 $resp = trim(fgets($resource, 10240));
515 $respArray = explode(' ', $resp);
516 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
525 // Check array for chuncked encoding
526 function unchunkHttpResponse ($response) {
527 // Default is not chunked
530 // Check if we have chunks
531 foreach ($response as $line) {
532 // Make lower-case and trim it
536 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
544 if ($isChunked === TRUE) {
545 // Good, we still have the HTTP headers in there, so we need to get rid
546 // of them temporarly
547 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), TRUE)).'</pre>');
548 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
550 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
551 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
553 // Re-add the headers
554 $response = merge_array($GLOBALS['http_headers'], stringToArray(chr(10), $tempResponse));
557 // Return the unchunked array
561 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
562 function removeHttpHeaderFromResponse ($response) {
563 // Save headers for later usage
564 $GLOBALS['http_headers'] = array();
566 // The first array element has to contain HTTP
567 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
568 // Okay, we have headers, now remove them with a second array
569 $response2 = $response;
570 foreach ($response as $line) {
572 array_shift($response2);
574 // Add full line to temporary global array
575 array_push($GLOBALS['http_headers'], $line);
577 // Trim it for testing
578 $lineTest = trim($line);
580 // Is this line empty?
581 if (empty($lineTest)) {
587 // Write back the array
588 $response = $response2;
591 // Return the modified response array
595 // Returns the flag if a broken HTTP server implementation was detected
596 function isBrokenHttpServerImplentation () {
598 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === TRUE));
604 // Extract host from script name
605 function extractHostnameFromUrl (&$script) {
606 // Use default SERVER_URL by default... ;) So?
607 $url = getServerUrl();
609 // Is this URL valid?
610 if (substr($script, 0, 7) == 'http://') {
611 // Use the hostname from script URL as new hostname
612 $url = substr($script, 7);
613 $extract = explode('/', $url);
615 // Done extracting the URL :)
619 $host = str_replace('http://', '', $url);
620 if (isInString('/', $host)) {
621 $host = substr($host, 0, strpos($host, '/'));
624 // Generate relative URL
625 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
626 if (substr(strtolower($script), 0, 7) == 'http://') {
627 // But only if http:// is in front!
628 $script = substr($script, (strlen($url) + 7));
629 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
631 $script = substr($script, (strlen($url) + 8));
634 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
635 if (substr($script, 0, 1) == '/') {
636 $script = substr($script, 1);
643 // Adds a HTTP header to array
644 function addHttpHeader ($header) {
646 //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
647 array_push($GLOBALS['http_header'], trim($header));
650 // Flushes all HTTP headers
651 function flushHttpHeaders () {
652 // Is the header already sent?
653 if (headers_sent()) {
655 reportBug(__FUNCTION__, __LINE__, 'Headers already sent!');
656 } elseif ((!isset($GLOBALS['http_header'])) || (!is_array($GLOBALS['http_header']))) {
657 // Not set or not an array
658 reportBug(__FUNCTION__, __LINE__, 'Headers not set or not an array, isset()=' . isset($GLOBALS['http_header']) . ', please report this.');
661 // Flush all headers if found
662 foreach ($GLOBALS['http_header'] as $header) {
663 // Send a single header
667 // Mark them as flushed
668 $GLOBALS['http_header'] = array();
671 //-----------------------------------------------------------------------------
672 // Automatically re-created functions, all taken from user comments on www.php.net
673 //-----------------------------------------------------------------------------
675 if (!function_exists('http_build_query')) {
676 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
677 function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
679 foreach ((array) $requestData as $k => $v) {
680 if (is_int($k) && $prefix != null) {
681 $k = urlencode($prefix . $k);
684 if ((!empty($key)) || ($key === 0)) {
685 $k = $key . '[' . urlencode($k) . ']';
688 if (is_array($v) || is_object($v)) {
689 array_push($ret, http_build_query($v, '', $sep, $k));
691 array_push($ret, $k . '=' . urlencode($v));
696 $sep = ini_get('arg_separator.output');
699 return implode($sep, $ret);
703 if (!function_exists('http_chunked_decode')) {
705 * dechunk an HTTP 'transfer-encoding: chunked' message.
707 * @param $chunk The encoded message
708 * @return $dechunk The decoded message. If $chunk wasn't encoded properly reportBug() is being called
709 * @author Marques Johansson (initial author)
710 * @author Roland Haeder (heavy modifications and simplification)
711 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
713 function http_chunked_decode ($chunk) {
714 // Detect multi-byte encoding
715 $mbPrefix = detectMultiBytePrefix($chunk);
716 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
718 // Init some variables
720 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
723 // Walk through all chunks
724 while ($offset < $len) {
725 // Where does the \r\n begin?
726 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
729 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
730 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
732 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
735 // Get next hex-coded chunk length
736 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
739 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
743 // Validation if it is hexadecimal
744 if (!isHexadecimal($chunkLenHex)) {
745 // Please help debugging this
746 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
747 reportBug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
749 // This won't be reached
753 // Position of next chunk is right after \r\n
754 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
755 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
758 print 'chunkLen='.$chunkLen.'<br />
759 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
762 // Moved out for debugging
763 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
764 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
767 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
768 * is currently (revision 7567 and maybe earlier) broken and does
769 * not include the \r\n characters when it sents a "chunked" HTTP
773 if (isBrokenHttpServerImplentation()) {
774 // Count occurrences of \r\n
775 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
779 * Correct chunk length because some broken HTTP server
780 * implementation subtract occurrences of \r\n in their chunk
783 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
785 // Add next chunk to $dechunk
786 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
789 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
790 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
792 count='.$count.'<br />
793 chunkLen='.$chunkLen.'<br />
794 chunkLenHex='.$chunkLenHex.'<br />
795 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
796 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
799 // Is $offset + $chunkLen larger than or equal $len?
800 if (($offset + $chunkLen) >= $len) {
801 // Then stop processing here
805 // Calculate offset of next chunk
806 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
809 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
810 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
811 ---:---:---:---:---:---:---:---:---<br />
816 // Return de-chunked string
821 // Getter for request method
822 function getHttpRequestMethod () {
823 // Console is default
824 $requestMethod = 'console';
827 if (isset($_SERVER['REQUEST_METHOD'])) {
828 // Get current request method
829 $requestMethod = $_SERVER['REQUEST_METHOD'];
833 return $requestMethod;
836 // Checks if 'content_type' is set
837 function isContentTypeSet () {
838 return isset($GLOBALS['content_type']);
841 // Setter for content type
842 function setContentType ($contentType) {
843 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'contentType=' . $contentType);
844 $GLOBALS['content_type'] = (string) $contentType;
847 // Getter for content type
848 function getContentType () {
850 if (!isContentTypeSet()) {
852 reportBug(__FUNCTION__, __LINE__, 'content_type not set in GLOBALS array.');
856 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content_type=' . $GLOBALS['content_type']);
857 return $GLOBALS['content_type'];
860 // Logs wrong SERVER_NAME attempts
861 function logWrongServerNameRedirect () {
862 // Is ext-sql_patches at least version 0.9.2?
863 if (isExtensionInstalledAndNewer('sql_patches', '0.9.2')) {
864 // Is there an entry?
865 if (countSumTotalData(detectServerName(), 'server_name_log', 'server_name_id', 'server_name', TRUE, 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) {
866 // Update counter, as all are the same
867 SQL_QUERY_ESC("UPDATE
868 `{?_MYSQL_PREFIX?}_server_name_log`
870 `server_name_counter`=`server_name_counter`+1
872 `server_name`='%s' AND
873 `server_name_remote_addr`='%s' AND
874 `server_name_ua`='%s' AND
875 `server_name_referrer`='%s'
879 detectRemoteAddr(TRUE),
880 detectUserAgent(TRUE),
882 ), __FUNCTION__, __LINE__);
885 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')",
888 detectRemoteAddr(TRUE),
889 detectUserAgent(TRUE),
891 ), __FUNCTION__, __LINE__);