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