]> git.mxchange.org Git - mailer.git/blob - inc/http-functions.php
More fixes for ext-yoomedia (didn't handle non-error responses correctly)
[mailer.git] / inc / http-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 03/08/2011 *
4  * ===================                          Last change: 03/08/2011 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : http-functions.php                               *
8  * -------------------------------------------------------------------- *
9  * Short description : HTTP-related functions                           *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : HTTP-relevante Funktionen                        *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
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.                                  *
26  *                                                                      *
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.                         *
31  *                                                                      *
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,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Sends out all headers required for HTTP/1.1 reply
44 function sendHttpHeaders () {
45         // Used later
46         $now = gmdate('D, d M Y H:i:s') . ' GMT';
47
48         // Send HTTP header
49         sendHeader('HTTP/1.1 ' . getHttpStatus());
50
51         // General headers for no caching
52         sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
53         sendHeader('Last-Modified: ' . $now);
54         sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
55         sendHeader('Pragma: no-cache'); // HTTP/1.0
56         sendHeader('Connection: Close');
57         sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
58         sendHeader('Content-Language: ' . getLanguage());
59 }
60
61 // Generates the full GET URL from given base URL and data array
62 function generateGetUrlFromBaseUrlData ($baseUrl, $requestData = array()) {
63         // Init URL
64         $getUrl = $baseUrl;
65
66         // Add data
67         $body = http_build_query($requestData, '', '&');
68
69         // There should be data, else we don't need to extend $baseUrl with $body
70         if (!empty($body)) {
71                 // Do we have a question-mark in the script?
72                 if (!isInString('?', $baseUrl)) {
73                         // No, so first char must be question mark
74                         $body = '?' . $body;
75                 } else {
76                         // Ok, add &
77                         $body = '&' . $body;
78                 }
79
80                 // Add script data
81                 $getUrl .= $body;
82
83                 // Remove trailed & to make it more conform
84                 if (substr($getUrl, -1, 1) == '&') {
85                         $getUrl = substr($getUrl, 0, -1);
86                 } // END - if
87         } // END - if
88
89         // Return it
90         return $getUrl;
91 }
92
93 // Removes http[s]://<hostname> from given url
94 function removeHttpHostNameFromUrl ($url) {
95         // Remove http[s]://
96         $remove = explode(':', $url);
97         $remove = explode('/', substr($remove[1], 3));
98
99         // Remove the first element (should be the hostname)
100         unset($remove[0]);
101
102         // implode() back all other elements and prepend a slash
103         $url = '/' . implode('/', $remove);
104
105         // Return prepared URL
106         return $url;
107 }
108
109 // Send a HEAD request
110 function sendHeadRequest ($baseUrl, $requestData = array()) {
111         // Generate full GET URL
112         $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
113
114         // Extract hostname and port from script
115         $host = extractHostnameFromUrl($baseUrl);
116
117         // Remove http[s]://<hostname> from url
118         $getUrl = removeHttpHostNameFromUrl($getUrl);
119
120         // Generate HEAD request header
121         $request  = 'HEAD ' . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
122         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
123         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
124         if (isConfigEntrySet('FULL_VERSION')) {
125                 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
126         } else {
127                 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
128         }
129         $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
130         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
131         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
132         $request .= 'Connection: close' . getConfig('HTTP_EOL');
133         $request .= getConfig('HTTP_EOL');
134
135         // Send the raw request
136         $response = sendRawRequest($host, $request);
137
138         // Return the result to the caller function
139         return $response;
140 }
141
142 // Send a GET request
143 function sendGetRequest ($baseUrl, $requestData = array(), $removeHeader = false) {
144         // Generate full GET URL
145         $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
146
147         // Extract hostname and port from script
148         $host = extractHostnameFromUrl($baseUrl);
149
150         // Remove http[s]://<hostname> from url
151         $getUrl = removeHttpHostNameFromUrl($getUrl);
152
153         // Generate GET request header
154         $request  = 'GET ' . trim($getUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
155         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
156         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
157         if (isConfigEntrySet('FULL_VERSION')) {
158                 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
159         } else {
160                 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
161         }
162         $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
163         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
164         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
165         $request .= 'Connection: close' . getConfig('HTTP_EOL');
166         $request .= getConfig('HTTP_EOL');
167
168         // Send the raw request
169         $response = sendRawRequest($host, $request);
170
171         // Should we remove header lines?
172         if ($removeHeader === true) {
173                 // Okay, remove them
174                 $response = removeHttpHeaderFromResponse($response);
175         } // END - if
176
177         // Return the result to the caller function
178         return $response;
179 }
180
181 // Send a POST request
182 function sendPostRequest ($baseUrl, $requestData, $removeHeader = false) {
183         // Extract host name from script
184         $host = extractHostnameFromUrl($baseUrl);
185
186         // Construct request body
187         $body = http_build_query($requestData, '', '&');
188
189         // Remove http(s)://$host from base URL
190         $baseUrl = removeHttpHostNameFromUrl($baseUrl);
191
192         // Generate POST request header
193         $request  = 'POST ' . trim($baseUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
194         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
195         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
196         if (isConfigEntrySet('FULL_VERSION')) {
197                 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
198         } else {
199                 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
200         }
201         $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
202         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
203         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
204         $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
205         $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
206         $request .= 'Connection: close' . getConfig('HTTP_EOL');
207         $request .= getConfig('HTTP_EOL');
208
209         // Add body
210         $request .= $body;
211
212         // Send the raw request
213         $response = sendRawRequest($host, $request);
214
215         // Should we remove header lines?
216         if ($removeHeader === true) {
217                 // Okay, remove them
218                 $response = removeHttpHeaderFromResponse($response);
219         } // END - if
220
221         // Return the result to the caller function
222         return $response;
223 }
224
225 // Sends a raw request to another host
226 function sendRawRequest ($host, $request) {
227         //* DEBUG: */ die('host='.$host.',request=<pre>'.$request.'</pre>');
228         // Init errno and errdesc with 'all fine' values
229         $errno = '0';
230         $errdesc = '';
231
232         // Default port is 80
233         $port = 80;
234
235         // Initialize array
236         $response = array('', '', '');
237
238         // Default is not to use proxy
239         $useProxy = false;
240
241         // Default is non-broken HTTP server implementation
242         $GLOBALS['is_http_server_broken'] = false;
243
244         // Are proxy settins set?
245         if (isProxyUsed()) {
246                 // Then use it
247                 $useProxy = true;
248         } // END - if
249
250         // Load include
251         loadIncludeOnce('inc/classes/resolver.class.php');
252
253         // Extract port part from host
254         $portArray = explode(':', $host);
255         if (count($portArray) == 2) {
256                 // Extract host and port
257                 $host = $portArray[0];
258                 $port = $portArray[1];
259         } elseif (count($portArray) > 2) {
260                 // This should not happen!
261                 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
262         }
263
264         // Get resolver instance
265         $resolver = new HostnameResolver();
266
267         // Open connection
268         if ($useProxy === true) {
269                 // Resolve hostname into IP address
270                 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
271
272                 // Connect to host through proxy connection
273                 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
274         } else {
275                 // Resolve hostname into IP address
276                 $ip = $resolver->resolveHostname($host);
277
278                 // Connect to host directly
279                 $fp = fsockopen($ip, $port, $errno, $errdesc, 30);
280         }
281
282         // Is there a link?
283         if (!is_resource($fp)) {
284                 // Failed!
285                 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
286                 return $response;
287         } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
288                 // Cannot set non-blocking mode or timeout
289                 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
290                 return $response;
291         }
292
293         // Do we use proxy?
294         if ($useProxy === true) {
295                 // Setup proxy tunnel
296                 $response = setupProxyTunnel($host, $port, $fp);
297
298                 // If the response is invalid, abort
299                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
300                         // Invalid response!
301                         logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
302                         return $response;
303                 } // END - if
304         } // END - if
305
306         // Write request
307         fwrite($fp, $request);
308
309         // Start counting
310         $start = microtime(true);
311
312         // Read response
313         while (!feof($fp)) {
314                 // Get info from stream
315                 $info = stream_get_meta_data($fp);
316
317                 // Is it timed out? 15 seconds is a really patient...
318                 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
319                         // Timeout
320                         logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
321
322                         // Abort here
323                         break;
324                 } // END - if
325
326                 // Get line from stream
327                 $line = fgets($fp, 128);
328
329                 // Ignore empty lines because of non-blocking mode
330                 if (empty($line)) {
331                         // uslepp a little to avoid 100% CPU load
332                         usleep(10);
333
334                         // Skip this
335                         continue;
336                 } // END - if
337
338                 // Check for broken HTTP implementations
339                 if (substr(strtolower($line), 0, 7) == 'server:') {
340                         // Anomic (see http://anomic.de, http://yacy.net) is currently broken
341                         $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
342                 } // END - if
343
344                 // Add it to response
345                 //* DEBUG: */ print 'line='.$line.'<br />';
346                 $response[] = $line;
347         } // END - while
348
349         // Close socket
350         fclose($fp);
351
352         // Time request if debug-mode is enabled
353         if (isDebugModeEnabled()) {
354                 // Add debug message...
355                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
356         } // END - if
357
358         // Skip first empty lines
359         $resp = $response;
360         foreach ($resp as $idx => $line) {
361                 // Trim space away
362                 $line = trim($line);
363
364                 // Is this line empty?
365                 if (empty($line)) {
366                         // Then remove it
367                         array_shift($response);
368                 } else {
369                         // Abort on first non-empty line
370                         break;
371                 }
372         } // END - foreach
373
374         //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
375         //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
376
377         // Proxy agent found or something went wrong?
378         if (!isset($response[0])) {
379                 // No response, maybe timeout
380                 $response = array('', '', '');
381                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
382         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
383                 // Proxy header detected, so remove two lines
384                 array_shift($response);
385                 array_shift($response);
386         } // END - if
387
388         // Was the request successfull?
389         if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
390                 // Not found / access forbidden
391                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
392                 $response = array('', '', '');
393         } else {
394                 // Check array for chuncked encoding
395                 $response = unchunkHttpResponse($response);
396         } // END - if
397
398         // Return response
399         return $response;
400 }
401
402 // Sets up a proxy tunnel for given hostname and through resource
403 function setupProxyTunnel ($host, $port, $resource) {
404         // Initialize array
405         $response = array('', '', '');
406
407         // Generate CONNECT request header
408         $proxyTunnel  = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
409         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
410
411         // Use login data to proxy? (username at least!)
412         if (getProxyUsername() != '') {
413                 // Add it as well
414                 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
415                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
416         } // END - if
417
418         // Add last new-line
419         $proxyTunnel .= getConfig('HTTP_EOL');
420         //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
421
422         // Write request
423         fwrite($fp, $proxyTunnel);
424
425         // Got response?
426         if (feof($fp)) {
427                 // No response received
428                 return $response;
429         } // END - if
430
431         // Read the first line
432         $resp = trim(fgets($fp, 10240));
433         $respArray = explode(' ', $resp);
434         if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
435                 // Invalid response!
436                 return $response;
437         } // END - if
438
439         // All fine!
440         return $respArray;
441 }
442
443 // Check array for chuncked encoding
444 function unchunkHttpResponse ($response) {
445         // Default is not chunked
446         $isChunked = false;
447
448         // Check if we have chunks
449         foreach ($response as $line) {
450                 // Make lower-case and trim it
451                 $line = trim($line);
452
453                 // Entry found?
454                 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
455                         // Found!
456                         $isChunked = true;
457                         break;
458                 } // END - if
459         } // END - foreach
460
461         // Is it chunked?
462         if ($isChunked === true) {
463                 // Good, we still have the HTTP headers in there, so we need to get rid
464                 // of them temporarly
465                 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), true)).'</pre>');
466                 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
467
468                 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
469                 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
470
471                 // Re-add the headers
472                 $response = merge_array($GLOBALS['http_headers'], stringToArray("\n", $tempResponse));
473         } // END - if
474
475         // Return the unchunked array
476         return $response;
477 }
478
479 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
480 function removeHttpHeaderFromResponse ($response) {
481         // Save headers for later usage
482         $GLOBALS['http_headers'] = array();
483
484         // The first array element has to contain HTTP
485         if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
486                 // Okay, we have headers, now remove them with a second array
487                 $response2 = $response;
488                 foreach ($response as $line) {
489                         // Remove line
490                         array_shift($response2);
491
492                         // Add full line to temporary global array
493                         $GLOBALS['http_headers'][] = $line;
494
495                         // Trim it for testing
496                         $lineTest = trim($line);
497
498                         // Is this line empty?
499                         if (empty($lineTest)) {
500                                 // Then stop here
501                                 break;
502                         } // END - if
503                 } // END - foreach
504
505                 // Write back the array
506                 $response = $response2;
507         } // END - if
508
509         // Return the modified response array
510         return $response;
511 }
512
513 // Returns the flag if a broken HTTP server implementation was detected
514 function isBrokenHttpServerImplentation () {
515         // Determine it
516         $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === true));
517
518         // ... and return it
519         return $isBroken;
520 }
521
522 //-----------------------------------------------------------------------------
523 // Automatically re-created functions, all taken from user comments on www.php.net
524 //-----------------------------------------------------------------------------
525
526 if (!function_exists('http_build_query')) {
527         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
528         function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
529                 $ret = array();
530                 foreach ((array) $requestData as $k => $v) {
531                         if (is_int($k) && $prefix != null) {
532                                 $k = urlencode($prefix . $k);
533                         } // END - if
534
535                         if ((!empty($key)) || ($key === 0)) {
536                                 $k = $key . '[' . urlencode($k) . ']';
537                         } // END - if
538
539                         if (is_array($v) || is_object($v)) {
540                                 array_push($ret, http_build_query($v, '', $sep, $k));
541                         } else {
542                                 array_push($ret, $k . '=' . urlencode($v));
543                         }
544                 } // END - foreach
545
546                 if (empty($sep)) {
547                         $sep = ini_get('arg_separator.output');
548                 } // END - if
549
550                 return implode($sep, $ret);
551         }
552 } // END - if
553
554 if (!function_exists('http_chunked_decode')) {
555         /**
556          * dechunk an HTTP 'transfer-encoding: chunked' message.
557          *
558          * @param       $chunk          The encoded message
559          * @return      $dechunk        The decoded message. If $chunk wasn't encoded properly debug_report_bug() is being called
560          * @author      Marques Johansson (initial author)
561          * @author      Roland Haeder (heavy modifications and simplification)
562          * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
563          */
564         function http_chunked_decode ($chunk) {
565                 // Detect multi-byte encoding
566                 $mbPrefix = detectMultiBytePrefix($chunk);
567                 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
568
569                 // Init some variables
570                 $offset = 0;
571                 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
572                 $dechunk = '';
573
574                 // Walk through all chunks
575                 while ($offset < $len) {
576                         // Where does the \r\n begin?
577                         $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
578
579                         /* DEBUG: *
580                         print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
581 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
582 len='.$len.'<br />
583 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
584                         /* DEBUG: */
585
586                         // Get next hex-coded chunk length
587                         $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
588
589                         /* DEBUG: *
590                         print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
591 ';
592                         /* DEBUG: */
593
594                         // Validation if it is hexadecimal
595                         if (!isHexadecimal($chunkLenHex)) {
596                                 // Please help debugging this
597                                 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
598                                 debug_report_bug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
599
600                                 // This won't be reached
601                                 return $chunk;
602                         } // END - if
603
604                         // Position of next chunk is right after \r\n
605                         $offset   = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
606                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
607
608                         /* DEBUG: *
609                         print 'chunkLen='.$chunkLen.'<br />
610 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
611                         /* DEBUG: */
612
613                         // Moved out for debugging
614                         $next  = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
615                         //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
616
617                         /*
618                          * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
619                          * is currently (revision 7567 and maybe earlier) broken and does
620                          * not include the \r\n characters when it sents a "chunked" HTTP
621                          * message.
622                          */
623                         $count = 0;
624                         if (isBrokenHttpServerImplentation()) {
625                                 // Count occurrences of \r\n
626                                 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
627                         } // END - if
628
629                         /*
630                          * Correct chunk length because some broken HTTP server
631                          * implementation subtract occurrences of \r\n in their chunk
632                          * lengths.
633                          */
634                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
635
636                         // Add next chunk to $dechunk
637                         $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
638
639                         /* DEBUG: *
640                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
641 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
642 len='.$len.'<br />
643 count='.$count.'<br />
644 chunkLen='.$chunkLen.'<br />
645 chunkLenHex='.$chunkLenHex.'<br />
646 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
647 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
648                         /* DEBUG: */
649
650                         // Is $offset + $chunkLen larger than or equal $len?
651                         if (($offset + $chunkLen) >= $len) {
652                                 // Then stop processing here
653                                 break;
654                         } // END - if
655
656                         // Calculate offset of next chunk
657                         $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
658
659                         /* DEBUG: *
660                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
661 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
662 ---:---:---:---:---:---:---:---:---<br />
663 ');
664                         /* DEBUG: */
665                 } // END - while
666
667                 // Return de-chunked string
668                 return $dechunk;
669         }
670 } // END - if
671
672 // [EOF]
673 ?>