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