2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 03/08/2011 *
4 * =================== Last change: 03/08/2011 *
6 * -------------------------------------------------------------------- *
7 * File : http-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : HTTP-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : HTTP-relevante Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Sends out all headers required for HTTP/1.1 reply
44 function sendHttpHeaders () {
46 $now = gmdate('D, d M Y H:i:s') . ' GMT';
49 sendHeader('HTTP/1.1 ' . getHttpStatus());
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());
61 // Checks wether the URL is full-qualified (http[s]:// + hostname [+ request data])
62 function isFullQualifiedUrl ($url) {
64 if (!isset($GLOBALS[__FUNCTION__][$url])) {
66 $GLOBALS[__FUNCTION__][$url] = ((substr($url, 0, 7) == 'http://') || (substr($url, 0, 8) == 'https://'));
70 return $GLOBALS[__FUNCTION__][$url];
73 // Generates the full GET URL from given base URL and data array
74 function generateGetUrlFromBaseUrlData ($baseUrl, $requestData = array()) {
78 // Is it full-qualified?
79 if (!isFullQualifiedUrl($getUrl)) {
80 // Need to prepend a slash?
81 if (substr($getUrl, 0, 1) != '/') {
83 $getUrl = '/' . $getUrl;
86 // Prepend http://hostname from mxchange.org server
87 $getUrl = getServerUrl() . $getUrl;
91 $body = http_build_query($requestData, '', '&');
93 // There should be data, else we don't need to extend $baseUrl with $body
95 // Do we have a question-mark in the script?
96 if (!isInString('?', $baseUrl)) {
97 // No, so first char must be question mark
107 // Remove trailed & to make it more conform
108 if (substr($getUrl, -1, 1) == '&') {
109 $getUrl = substr($getUrl, 0, -1);
117 // Removes http[s]://<hostname> from given url
118 function removeHttpHostNameFromUrl ($url) {
120 $remove = explode(':', $url);
121 $remove = explode('/', substr($remove[1], 3));
123 // Remove the first element (should be the hostname)
126 // implode() back all other elements and prepend a slash
127 $url = '/' . implode('/', $remove);
129 // Return prepared URL
133 // Sends a HTTP request (GET, POST, HEAD are currently supported)
134 function sendHttpRequest ($requestType, $baseUrl, $requestData = array(), $removeHeader = false) {
138 // Start "detecting" the request type
139 switch ($requestType) {
140 case 'HEAD': // Send a HTTP/1.1 HEAD request
141 $response = sendHeadRequest($baseUrl, $requestData);
144 case 'GET': // Send a HTTP/1.1 GET request
145 $response = sendGetRequest($baseUrl, $requestData, $removeHeader);
148 case 'POST': // Send a HTTP/1.1 POST request
149 $response = sendPostRequest($baseUrl, $requestData, $removeHeader);
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));
161 // Sends a HEAD request
162 function sendHeadRequest ($baseUrl, $requestData = array()) {
163 // Generate full GET URL
164 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
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) != '/') {
172 $getUrl = '/' . $getUrl;
175 // Extract hostname and port from script
176 $host = extractHostnameFromUrl($baseUrl);
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');
185 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
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');
193 // Send the raw request
194 $response = sendRawRequest($host, $request);
196 // Return the result to the caller function
200 // Send a GET request
201 function sendGetRequest ($baseUrl, $requestData = array(), $removeHeader = false) {
202 // Generate full GET URL
203 $getUrl = generateGetUrlFromBaseUrlData($baseUrl, $requestData);
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) != '/') {
211 $getUrl = '/' . $getUrl;
214 // Extract hostname and port from script
215 $host = extractHostnameFromUrl($baseUrl);
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');
224 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
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');
232 // Send the raw request
233 $response = sendRawRequest($host, $request);
235 // Should we remove header lines?
236 if ($removeHeader === true) {
238 $response = removeHttpHeaderFromResponse($response);
241 // Return the result to the caller function
245 // Send a POST request
246 function sendPostRequest ($baseUrl, $requestData, $removeHeader = false) {
247 // Copy baseUrl to getUrl
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) != '/') {
256 $getUrl = '/' . $getUrl;
259 // Extract host name from script
260 $host = extractHostnameFromUrl($baseUrl);
262 // Construct request body
263 $body = http_build_query($requestData, '', '&');
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');
272 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
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');
285 // Send the raw request
286 $response = sendRawRequest($host, $request);
288 // Should we remove header lines?
289 if ($removeHeader === true) {
291 $response = removeHttpHeaderFromResponse($response);
294 // Return the result to the caller function
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
305 // Default port is 80
309 $response = array('', '', '');
311 // Default is not to use proxy
314 // Default is non-broken HTTP server implementation
315 $GLOBALS['is_http_server_broken'] = false;
317 // Are proxy settins set?
324 loadIncludeOnce('inc/classes/resolver.class.php');
326 // Extract port part from host
327 $portArray = explode(':', $host);
328 if (count($portArray) == 2) {
329 // Extract host and port
330 $host = $portArray[0];
331 $port = $portArray[1];
332 } elseif (count($portArray) > 2) {
333 // This should not happen!
334 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
337 // Get resolver instance
338 $resolver = new HostnameResolver();
341 if ($useProxy === true) {
342 // Resolve hostname into IP address
343 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
345 // Connect to host through proxy connection
346 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
348 // Resolve hostname into IP address
349 $ip = $resolver->resolveHostname($host);
351 // Connect to host directly
352 $fp = fsockopen($ip, $port, $errno, $errdesc, 30);
356 if (!is_resource($fp)) {
358 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
360 } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
361 // Cannot set non-blocking mode or timeout
362 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
367 if ($useProxy === true) {
368 // Setup proxy tunnel
369 $response = setupProxyTunnel($host, $port, $fp);
371 // If the response is invalid, abort
372 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
374 logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
380 fwrite($fp, $request);
383 $start = microtime(true);
387 // Get info from stream
388 $info = stream_get_meta_data($fp);
390 // Is it timed out? 15 seconds is a really patient...
391 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
393 logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
399 // Get line from stream
400 $line = fgets($fp, 128);
402 // Ignore empty lines because of non-blocking mode
404 // uslepp a little to avoid 100% CPU load
411 // Check for broken HTTP implementations
412 if (substr(strtolower($line), 0, 7) == 'server:') {
413 // Anomic (see http://anomic.de, http://yacy.net) is currently broken
414 $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
417 // Add it to response
418 //* DEBUG: */ print 'line='.$line.'<br />';
425 // Time request if debug-mode is enabled
426 if (isDebugModeEnabled()) {
427 // Add debug message...
428 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
431 // Skip first empty lines
433 foreach ($resp as $idx => $line) {
437 // Is this line empty?
440 array_shift($response);
442 // Abort on first non-empty line
447 //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
448 //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
450 // Proxy agent found or something went wrong?
451 if (!isset($response[0])) {
452 // No response, maybe timeout
453 $response = array('', '', '');
454 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
455 } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
456 // Proxy header detected, so remove two lines
457 array_shift($response);
458 array_shift($response);
461 // Was the request successfull?
462 if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
463 // Not found / access forbidden
464 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
465 $response = array('', '', '');
467 // Check array for chuncked encoding
468 $response = unchunkHttpResponse($response);
475 // Sets up a proxy tunnel for given hostname and through resource
476 function setupProxyTunnel ($host, $port, $resource) {
478 $response = array('', '', '');
480 // Generate CONNECT request header
481 $proxyTunnel = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
482 $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
484 // Use login data to proxy? (username at least!)
485 if (getProxyUsername() != '') {
487 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
488 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
492 $proxyTunnel .= getConfig('HTTP_EOL');
493 //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
496 fwrite($fp, $proxyTunnel);
500 // No response received
504 // Read the first line
505 $resp = trim(fgets($fp, 10240));
506 $respArray = explode(' ', $resp);
507 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
516 // Check array for chuncked encoding
517 function unchunkHttpResponse ($response) {
518 // Default is not chunked
521 // Check if we have chunks
522 foreach ($response as $line) {
523 // Make lower-case and trim it
527 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
535 if ($isChunked === true) {
536 // Good, we still have the HTTP headers in there, so we need to get rid
537 // of them temporarly
538 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), true)).'</pre>');
539 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
541 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
542 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
544 // Re-add the headers
545 $response = merge_array($GLOBALS['http_headers'], stringToArray("\n", $tempResponse));
548 // Return the unchunked array
552 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
553 function removeHttpHeaderFromResponse ($response) {
554 // Save headers for later usage
555 $GLOBALS['http_headers'] = array();
557 // The first array element has to contain HTTP
558 if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
559 // Okay, we have headers, now remove them with a second array
560 $response2 = $response;
561 foreach ($response as $line) {
563 array_shift($response2);
565 // Add full line to temporary global array
566 $GLOBALS['http_headers'][] = $line;
568 // Trim it for testing
569 $lineTest = trim($line);
571 // Is this line empty?
572 if (empty($lineTest)) {
578 // Write back the array
579 $response = $response2;
582 // Return the modified response array
586 // Returns the flag if a broken HTTP server implementation was detected
587 function isBrokenHttpServerImplentation () {
589 $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === true));
595 //-----------------------------------------------------------------------------
596 // Automatically re-created functions, all taken from user comments on www.php.net
597 //-----------------------------------------------------------------------------
599 if (!function_exists('http_build_query')) {
600 // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
601 function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
603 foreach ((array) $requestData as $k => $v) {
604 if (is_int($k) && $prefix != null) {
605 $k = urlencode($prefix . $k);
608 if ((!empty($key)) || ($key === 0)) {
609 $k = $key . '[' . urlencode($k) . ']';
612 if (is_array($v) || is_object($v)) {
613 array_push($ret, http_build_query($v, '', $sep, $k));
615 array_push($ret, $k . '=' . urlencode($v));
620 $sep = ini_get('arg_separator.output');
623 return implode($sep, $ret);
627 if (!function_exists('http_chunked_decode')) {
629 * dechunk an HTTP 'transfer-encoding: chunked' message.
631 * @param $chunk The encoded message
632 * @return $dechunk The decoded message. If $chunk wasn't encoded properly debug_report_bug() is being called
633 * @author Marques Johansson (initial author)
634 * @author Roland Haeder (heavy modifications and simplification)
635 * @link http://php.net/manual/en/function.http-chunked-decode.php#89786
637 function http_chunked_decode ($chunk) {
638 // Detect multi-byte encoding
639 $mbPrefix = detectMultiBytePrefix($chunk);
640 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
642 // Init some variables
644 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
647 // Walk through all chunks
648 while ($offset < $len) {
649 // Where does the \r\n begin?
650 $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
653 print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
654 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
656 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
659 // Get next hex-coded chunk length
660 $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
663 print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
667 // Validation if it is hexadecimal
668 if (!isHexadecimal($chunkLenHex)) {
669 // Please help debugging this
670 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
671 debug_report_bug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
673 // This won't be reached
677 // Position of next chunk is right after \r\n
678 $offset = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
679 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
682 print 'chunkLen='.$chunkLen.'<br />
683 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
686 // Moved out for debugging
687 $next = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
688 //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
691 * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
692 * is currently (revision 7567 and maybe earlier) broken and does
693 * not include the \r\n characters when it sents a "chunked" HTTP
697 if (isBrokenHttpServerImplentation()) {
698 // Count occurrences of \r\n
699 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
703 * Correct chunk length because some broken HTTP server
704 * implementation subtract occurrences of \r\n in their chunk
707 $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
709 // Add next chunk to $dechunk
710 $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
713 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
714 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
716 count='.$count.'<br />
717 chunkLen='.$chunkLen.'<br />
718 chunkLenHex='.$chunkLenHex.'<br />
719 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
720 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
723 // Is $offset + $chunkLen larger than or equal $len?
724 if (($offset + $chunkLen) >= $len) {
725 // Then stop processing here
729 // Calculate offset of next chunk
730 $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
733 print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
734 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
735 ---:---:---:---:---:---:---:---:---<br />
740 // Return de-chunked string
745 // Extract host from script name
746 function extractHostnameFromUrl (&$script) {
747 // Use default SERVER_URL by default... ;) So?
748 $url = getServerUrl();
750 // Is this URL valid?
751 if (substr($script, 0, 7) == 'http://') {
752 // Use the hostname from script URL as new hostname
753 $url = substr($script, 7);
754 $extract = explode('/', $url);
756 // Done extracting the URL :)
760 $host = str_replace('http://', '', $url);
761 if (isInString('/', $host)) {
762 $host = substr($host, 0, strpos($host, '/'));
765 // Generate relative URL
766 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
767 if (substr(strtolower($script), 0, 7) == 'http://') {
768 // But only if http:// is in front!
769 $script = substr($script, (strlen($url) + 7));
770 } elseif (substr(strtolower($script), 0, 8) == 'https://') {
772 $script = substr($script, (strlen($url) + 8));
775 //* DEBUG: */ debugOutput('SCRIPT=' . $script);
776 if (substr($script, 0, 1) == '/') {
777 $script = substr($script, 1);