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