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