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