Fixes for ext-yoomedia to be compatible with Interface 2.0
[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                 $response[] = $line;
346         } // END - while
347
348         // Close socket
349         fclose($fp);
350
351         // Time request if debug-mode is enabled
352         if (isDebugModeEnabled()) {
353                 // Add debug message...
354                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
355         } // END - if
356
357         // Skip first empty lines
358         $resp = $response;
359         foreach ($resp as $idx => $line) {
360                 // Trim space away
361                 $line = trim($line);
362
363                 // Is this line empty?
364                 if (empty($line)) {
365                         // Then remove it
366                         array_shift($response);
367                 } else {
368                         // Abort on first non-empty line
369                         break;
370                 }
371         } // END - foreach
372
373         //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
374         //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
375
376         // Proxy agent found or something went wrong?
377         if (!isset($response[0])) {
378                 // No response, maybe timeout
379                 $response = array('', '', '');
380                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
381         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
382                 // Proxy header detected, so remove two lines
383                 array_shift($response);
384                 array_shift($response);
385         } // END - if
386
387         // Was the request successfull?
388         if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
389                 // Not found / access forbidden
390                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
391                 $response = array('', '', '');
392         } else {
393                 // Check array for chuncked encoding
394                 $response = unchunkHttpResponse($response);
395         } // END - if
396
397         // Return response
398         return $response;
399 }
400
401 // Sets up a proxy tunnel for given hostname and through resource
402 function setupProxyTunnel ($host, $port, $resource) {
403         // Initialize array
404         $response = array('', '', '');
405
406         // Generate CONNECT request header
407         $proxyTunnel  = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
408         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
409
410         // Use login data to proxy? (username at least!)
411         if (getProxyUsername() != '') {
412                 // Add it as well
413                 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
414                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
415         } // END - if
416
417         // Add last new-line
418         $proxyTunnel .= getConfig('HTTP_EOL');
419         //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
420
421         // Write request
422         fwrite($fp, $proxyTunnel);
423
424         // Got response?
425         if (feof($fp)) {
426                 // No response received
427                 return $response;
428         } // END - if
429
430         // Read the first line
431         $resp = trim(fgets($fp, 10240));
432         $respArray = explode(' ', $resp);
433         if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
434                 // Invalid response!
435                 return $response;
436         } // END - if
437
438         // All fine!
439         return $respArray;
440 }
441
442 // Check array for chuncked encoding
443 function unchunkHttpResponse ($response) {
444         // Default is not chunked
445         $isChunked = false;
446
447         // Check if we have chunks
448         foreach ($response as $line) {
449                 // Make lower-case and trim it
450                 $line = trim($line);
451
452                 // Entry found?
453                 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
454                         // Found!
455                         $isChunked = true;
456                         break;
457                 } // END - if
458         } // END - foreach
459
460         // Is it chunked?
461         if ($isChunked === true) {
462                 // Good, we still have the HTTP headers in there, so we need to get rid
463                 // of them temporarly
464                 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), true)).'</pre>');
465                 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
466
467                 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
468                 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
469
470                 // Re-add the headers
471                 $response = merge_array($GLOBALS['http_headers'], stringToArray("\n", $tempResponse));
472         } // END - if
473
474         // Return the unchunked array
475         return $response;
476 }
477
478 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
479 function removeHttpHeaderFromResponse ($response) {
480         // Save headers for later usage
481         $GLOBALS['http_headers'] = array();
482
483         // The first array element has to contain HTTP
484         if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
485                 // Okay, we have headers, now remove them with a second array
486                 $response2 = $response;
487                 foreach ($response as $line) {
488                         // Remove line
489                         array_shift($response2);
490
491                         // Add full line to temporary global array
492                         $GLOBALS['http_headers'][] = $line;
493
494                         // Trim it for testing
495                         $lineTest = trim($line);
496
497                         // Is this line empty?
498                         if (empty($lineTest)) {
499                                 // Then stop here
500                                 break;
501                         } // END - if
502                 } // END - foreach
503
504                 // Write back the array
505                 $response = $response2;
506         } // END - if
507
508         // Return the modified response array
509         return $response;
510 }
511
512 // Returns the flag if a broken HTTP server implementation was detected
513 function isBrokenHttpServerImplentation () {
514         // Determine it
515         $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === true));
516
517         // ... and return it
518         return $isBroken;
519 }
520
521 //-----------------------------------------------------------------------------
522 // Automatically re-created functions, all taken from user comments on www.php.net
523 //-----------------------------------------------------------------------------
524
525 if (!function_exists('http_build_query')) {
526         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
527         function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
528                 $ret = array();
529                 foreach ((array) $requestData as $k => $v) {
530                         if (is_int($k) && $prefix != null) {
531                                 $k = urlencode($prefix . $k);
532                         } // END - if
533
534                         if ((!empty($key)) || ($key === 0)) {
535                                 $k = $key . '[' . urlencode($k) . ']';
536                         } // END - if
537
538                         if (is_array($v) || is_object($v)) {
539                                 array_push($ret, http_build_query($v, '', $sep, $k));
540                         } else {
541                                 array_push($ret, $k . '=' . urlencode($v));
542                         }
543                 } // END - foreach
544
545                 if (empty($sep)) {
546                         $sep = ini_get('arg_separator.output');
547                 } // END - if
548
549                 return implode($sep, $ret);
550         }
551 } // END - if
552
553 if (!function_exists('http_chunked_decode')) {
554         /**
555          * dechunk an HTTP 'transfer-encoding: chunked' message.
556          *
557          * @param       $chunk          The encoded message
558          * @return      $dechunk        The decoded message. If $chunk wasn't encoded properly debug_report_bug() is being called
559          * @author      Marques Johansson (initial author)
560          * @author      Roland Haeder (heavy modifications and simplification)
561          * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
562          */
563         function http_chunked_decode ($chunk) {
564                 // Detect multi-byte encoding
565                 $mbPrefix = detectMultiBytePrefix($chunk);
566                 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
567
568                 // Init some variables
569                 $offset = 0;
570                 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
571                 $dechunk = '';
572
573                 // Walk through all chunks
574                 while ($offset < $len) {
575                         // Where does the \r\n begin?
576                         $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
577
578                         /* DEBUG: *
579                         print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
580 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
581 len='.$len.'<br />
582 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
583                         /* DEBUG: */
584
585                         // Get next hex-coded chunk length
586                         $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
587
588                         /* DEBUG: *
589                         print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
590 ';
591                         /* DEBUG: */
592
593                         // Validation if it is hexadecimal
594                         if (!isHexadecimal($chunkLenHex)) {
595                                 // Please help debugging this
596                                 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
597                                 debug_report_bug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
598
599                                 // This won't be reached
600                                 return $chunk;
601                         } // END - if
602
603                         // Position of next chunk is right after \r\n
604                         $offset   = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
605                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
606
607                         /* DEBUG: *
608                         print 'chunkLen='.$chunkLen.'<br />
609 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
610                         /* DEBUG: */
611
612                         // Moved out for debugging
613                         $next  = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
614                         //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
615
616                         /*
617                          * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
618                          * is currently (revision 7567 and maybe earlier) broken and does
619                          * not include the \r\n characters when it sents a "chunked" HTTP
620                          * message.
621                          */
622                         $count = 0;
623                         if (isBrokenHttpServerImplentation()) {
624                                 // Count occurrences of \r\n
625                                 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
626                         } // END - if
627
628                         /*
629                          * Correct chunk length because some broken HTTP server
630                          * implementation subtract occurrences of \r\n in their chunk
631                          * lengths.
632                          */
633                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
634
635                         // Add next chunk to $dechunk
636                         $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
637
638                         /* DEBUG: *
639                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
640 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
641 len='.$len.'<br />
642 count='.$count.'<br />
643 chunkLen='.$chunkLen.'<br />
644 chunkLenHex='.$chunkLenHex.'<br />
645 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
646 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
647                         /* DEBUG: */
648
649                         // Is $offset + $chunkLen larger than or equal $len?
650                         if (($offset + $chunkLen) >= $len) {
651                                 // Then stop processing here
652                                 break;
653                         } // END - if
654
655                         // Calculate offset of next chunk
656                         $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
657
658                         /* DEBUG: *
659                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
660 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
661 ---:---:---:---:---:---:---:---:---<br />
662 ');
663                         /* DEBUG: */
664                 } // END - while
665
666                 // Return de-chunked string
667                 return $dechunk;
668         }
669 } // END - if
670
671 // [EOF]
672 ?>