ed9250603be4a0c9545114c00858350fa01cb015
[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 - 2013 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 ? $getUrl : '') . trim($getUrl) . ' 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                 /*
413                  * Ignore empty lines because of non-blocking mode, you cannot use
414                  * empty() here as it would also see \r\n as "empty".
415                  */
416                 if (strlen($line) == 0) {
417                         // uslepp a little to avoid 100% CPU load
418                         usleep(10);
419
420                         // Skip this
421                         continue;
422                 } // END - if
423
424                 // Check for broken HTTP implementations
425                 if (substr(strtolower($line), 0, 7) == 'server:') {
426                         // Anomic (see http://anomic.de, http://yacy.net) is currently broken
427                         $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
428                 } // END - if
429
430                 // Add it to response
431                 //* DEBUG: */ print 'line(' . strlen($line) . ')='.$line.'<br />';
432                 array_push($response, $line);
433         } // END - while
434
435         // Close socket
436         fclose($resource);
437
438         // Time request if debug-mode is enabled
439         if (isDebugModeEnabled()) {
440                 // Add debug message...
441                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(TRUE) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
442         } // END - if
443
444         //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, TRUE).'</pre>');
445         //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, TRUE).'</pre>');
446
447         // Proxy agent found or something went wrong?
448         if (!isFilledArray($response)) {
449                 // No response, maybe timeout
450                 $response = array('', '', '');
451                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
452         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && (isProxyUsed() === TRUE)) {
453                 // Proxy header detected, so remove two lines
454                 array_shift($response);
455                 array_shift($response);
456         } // END - if
457
458         // Was the request successfull?
459         if ((!isHttpStatusOkay($response[0])) && ($allowOnlyHttpOkay === TRUE)) {
460                 // Not found / access forbidden
461                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
462                 $response = array('', '', '');
463         } else {
464                 // Check array for chuncked encoding
465                 $response = unchunkHttpResponse($response);
466         } // END - if
467
468         // Return response
469         return $response;
470 }
471
472 // Is HTTP status okay?
473 function isHttpStatusOkay ($header) {
474         // Determine it
475         return in_array(strtoupper(trim($header)), array('HTTP/1.1 200 OK', 'HTTP/1.0 200 OK'));
476 }
477
478 // Sets up a proxy tunnel for given hostname and through resource
479 function setupProxyTunnel ($host, $proxyHost, $port, $resource) {
480         // Initialize array
481         $response = array('', '', '');
482
483         // Generate CONNECT request header
484         $proxyTunnel  = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
485         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
486         $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . getConfig('HTTP_EOL');
487
488         // Use login data to proxy? (username at least!)
489         if (getProxyUsername() != '') {
490                 // Add it as well
491                 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
492                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
493         } // END - if
494
495         // Add last new-line
496         $proxyTunnel .= getConfig('HTTP_EOL');
497         //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
498
499         // Write request
500         fwrite($resource, $proxyTunnel);
501
502         // Got response?
503         if (feof($resource)) {
504                 // No response received
505                 return $response;
506         } // END - if
507
508         // Read the first line
509         $resp = trim(fgets($resource, 10240));
510         $respArray = explode(' ', $resp);
511         if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
512                 // Invalid response!
513                 return $response;
514         } // END - if
515
516         // All fine!
517         return $respArray;
518 }
519
520 // Check array for chuncked encoding
521 function unchunkHttpResponse ($response) {
522         // Default is not chunked
523         $isChunked = FALSE;
524
525         // Check if we have chunks
526         foreach ($response as $line) {
527                 // Make lower-case and trim it
528                 $line = trim($line);
529
530                 // Entry found?
531                 if ((isInStringIgnoreCase('transfer-encoding', $line)) && (isInStringIgnoreCase('chunked', $line))) {
532                         // Found!
533                         $isChunked = TRUE;
534                         break;
535                 } elseif (empty($line)) {
536                         // Empty line found (header->body)
537                         break;
538                 }
539         } // END - foreach
540
541         // Save whole body
542         $body = removeHttpHeaderFromResponse($response);
543
544         // Is it chunked?
545         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isChunked=' . intval($isChunked));
546         if ($isChunked === TRUE) {
547                 // Make sure, that body is an array
548                 assert(is_array($body));
549
550                 // Good, we still have the HTTP headers in there, so we need to get rid
551                 // of them temporarly
552                 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), TRUE)).'</pre>');
553                 $tempResponse = http_chunked_decode(implode('', $body));
554
555                 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
556                 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).'/'.gettype($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
557
558                 // Re-add the headers
559                 $response = mergeHttpHeadersWithBody($tempResponse);
560         } elseif (is_array($body)) {
561                 /*
562                  * Make sure the body is in one array element as many other functions
563                  * get disturbed by it.
564                  */
565
566                 // Put all array elements from body together
567                 $body = implode('', $body);
568
569                 // Now merge the extracted headers + fixed body together
570                 $response = mergeHttpHeadersWithBody($body);
571         }
572
573         // Return the unchunked array
574         return $response;
575 }
576
577 // Merges HTTP header lines with given body (string)
578 function mergeHttpHeadersWithBody ($body) {
579         // Add empty entry to mimic header->body
580         $GLOBALS['http_headers'][] = getConfig('HTTP_EOL');
581
582         // Make sure at least one header is there (which is still not valid but okay here)
583         assert(isFilledArray($GLOBALS['http_headers']));
584
585         // Merge both together
586         return merge_array($GLOBALS['http_headers'], array(count($GLOBALS['http_headers']) => $body));
587 }
588
589 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
590 function removeHttpHeaderFromResponse ($response) {
591         // Save headers for later usage
592         $GLOBALS['http_headers'] = array();
593
594         // The first array element has to contain HTTP
595         if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
596                 // Okay, we have headers, now remove them with a second array
597                 $response2 = $response;
598                 foreach ($response as $line) {
599                         // Remove line
600                         array_shift($response2);
601
602                         // Trim it for testing
603                         $lineTest = trim($line);
604
605                         // Is this line empty?
606                         if (empty($lineTest)) {
607                                 // Then stop here
608                                 break;
609                         } // END - if
610
611                         // Is the last line set and is not ending with \r\n?
612                         if ((isset($GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1])) && (substr($GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1], -2, 2) != getConfig('HTTP_EOL'))) {
613                                 // Add it to previous one
614                                 $GLOBALS['http_headers'][count($GLOBALS['http_headers']) - 1] .= $line;
615                         } else {
616                                 // Add full line to temporary global array
617                                 array_push($GLOBALS['http_headers'], $line);
618                         }
619                 } // END - foreach
620
621                 // Write back the array
622                 $response = $response2;
623         } // END - if
624
625         // Return the modified response array
626         return $response;
627 }
628
629 // Returns the flag if a broken HTTP server implementation was detected
630 function isBrokenHttpServerImplentation () {
631         // Determine it
632         $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === TRUE));
633
634         // ... and return it
635         return $isBroken;
636 }
637
638 // Extract host from script name
639 function extractHostnameFromUrl (&$script) {
640         // Use default SERVER_URL by default... ;) So?
641         $url = getServerUrl();
642
643         // Is this URL valid?
644         if (substr($script, 0, 7) == 'http://') {
645                 // Use the hostname from script URL as new hostname
646                 $url = substr($script, 7);
647                 $extract = explode('/', $url);
648                 $url = $extract[0];
649                 // Done extracting the URL :)
650         } // END - if
651
652         // Extract host name
653         $host = str_replace(array('http://', 'https://'), array('', ''), $url);
654
655         // Is there a slash at the end?
656         if (isInString('/', $host)) {
657                 $host = substr($host, 0, strpos($host, '/'));
658         } // END - if
659
660         // Is there a double-dot in? (Means port number)
661         if (strpos($host, ':') !== FALSE) {
662                 // Detected a double-dot
663                 $hostArray = explode(':', $host);
664                 $host = $hostArray[0];
665         } // END - if
666
667         // Generate relative URL
668         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
669         if (substr(strtolower($script), 0, 7) == 'http://') {
670                 // But only if http:// is in front!
671                 $script = substr($script, (strlen($url) + 7));
672         } elseif (substr(strtolower($script), 0, 8) == 'https://') {
673                 // Does this work?!
674                 $script = substr($script, (strlen($url) + 8));
675         }
676
677         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
678         if (substr($script, 0, 1) == '/') {
679                 $script = substr($script, 1);
680         } // END - if
681
682         // Return host name
683         return $host;
684 }
685
686 // Adds a HTTP header to array
687 function addHttpHeader ($header) {
688         // Send the header
689         //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
690         array_push($GLOBALS['http_header'], trim($header));
691 }
692
693 // Flushes all HTTP headers
694 function flushHttpHeaders () {
695         // Is the header already sent?
696         if (headers_sent()) {
697                 // Then abort here
698                 reportBug(__FUNCTION__, __LINE__, 'Headers already sent!');
699         } elseif ((!isset($GLOBALS['http_header'])) || (!is_array($GLOBALS['http_header']))) {
700                 // Not set or not an array
701                 reportBug(__FUNCTION__, __LINE__, 'Headers not set or not an array, isset()=' . isset($GLOBALS['http_header']) . ', please report this.');
702         }
703
704         // Flush all headers if found
705         foreach ($GLOBALS['http_header'] as $header) {
706                 // Send a single header
707                 header($header);
708         } // END - foreach
709
710         // Mark them as flushed
711         $GLOBALS['http_header'] = array();
712 }
713
714 //-----------------------------------------------------------------------------
715 // Automatically re-created functions, all taken from user comments on www.php.net
716 //-----------------------------------------------------------------------------
717
718 if (!function_exists('http_build_query')) {
719         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
720         function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
721                 $ret = array();
722                 foreach ((array) $requestData as $k => $v) {
723                         if (is_int($k) && !is_null($prefix)) {
724                                 $k = urlencode($prefix . $k);
725                         } // END - if
726
727                         if ((!empty($key)) || ($key === 0)) {
728                                 $k = $key . '[' . urlencode($k) . ']';
729                         } // END - if
730
731                         if (is_array($v) || is_object($v)) {
732                                 array_push($ret, http_build_query($v, '', $sep, $k));
733                         } else {
734                                 array_push($ret, $k . '=' . urlencode($v));
735                         }
736                 } // END - foreach
737
738                 if (empty($sep)) {
739                         $sep = ini_get('arg_separator.output');
740                 } // END - if
741
742                 return implode($sep, $ret);
743         }
744 } // END - if
745
746 if (!function_exists('http_chunked_decode')) {
747         /**
748          * dechunk an HTTP 'transfer-encoding: chunked' message.
749          *
750          * @param       $chunk          The encoded message
751          * @return      $dechunk        The decoded message. If $chunk wasn't encoded properly reportBug() is being called
752          * @author      Marques Johansson (initial author)
753          * @author      Roland Haeder (heavy modifications and simplification)
754          * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
755          */
756         function http_chunked_decode ($chunk) {
757                 // Detect multi-byte encoding
758                 $mbPrefix = detectMultiBytePrefix($chunk);
759                 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
760
761                 // Init some variables
762                 $offset = 0;
763                 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
764                 $dechunk = '';
765
766                 // Walk through all chunks
767                 while ($offset < $len) {
768                         // Where does the \r\n begin?
769                         $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
770
771                         /* DEBUG: *
772                         print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
773 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
774 len='.$len.'<br />
775 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
776                         /* DEBUG: */
777
778                         // Get next hex-coded chunk length
779                         $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
780
781                         /* DEBUG: *
782                         print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
783 ';
784                         /* DEBUG: */
785
786                         // Validation if it is hexadecimal
787                         if (!isHexadecimal($chunkLenHex)) {
788                                 // Please help debugging this
789                                 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
790                                 reportBug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
791
792                                 // This won't be reached
793                                 return $chunk;
794                         } // END - if
795
796                         // Position of next chunk is right after \r\n
797                         $offset   = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
798                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
799
800                         /* DEBUG: *
801                         print 'chunkLen='.$chunkLen.'<br />
802 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
803                         /* DEBUG: */
804
805                         // Moved out for debugging
806                         $next  = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
807                         //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
808
809                         /*
810                          * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
811                          * is currently (revision 7567 and maybe earlier) broken and does
812                          * not include the \r\n characters when it sents a "chunked" HTTP
813                          * message.
814                          */
815                         $count = 0;
816                         if (isBrokenHttpServerImplentation()) {
817                                 // Count occurrences of \r\n
818                                 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
819                         } // END - if
820
821                         /*
822                          * Correct chunk length because some broken HTTP server
823                          * implementation subtract occurrences of \r\n in their chunk
824                          * lengths.
825                          */
826                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
827
828                         // Add next chunk to $dechunk
829                         $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
830
831                         /* DEBUG: *
832                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
833 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
834 len='.$len.'<br />
835 count='.$count.'<br />
836 chunkLen='.$chunkLen.'<br />
837 chunkLenHex='.$chunkLenHex.'<br />
838 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
839 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
840                         /* DEBUG: */
841
842                         // Is $offset + $chunkLen larger than or equal $len?
843                         if (($offset + $chunkLen) >= $len) {
844                                 // Then stop processing here
845                                 break;
846                         } // END - if
847
848                         // Calculate offset of next chunk
849                         $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
850
851                         /* DEBUG: *
852                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
853 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
854 ---:---:---:---:---:---:---:---:---<br />
855 ');
856                         /* DEBUG: */
857                 } // END - while
858
859                 // Return de-chunked string
860                 return $dechunk;
861         }
862 } // END - if
863
864 // Getter for request method
865 function getHttpRequestMethod () {
866         // Console is default
867         $requestMethod = 'console';
868
869         // Is it set?
870         if (isset($_SERVER['REQUEST_METHOD'])) {
871                 // Get current request method
872                 $requestMethod = $_SERVER['REQUEST_METHOD'];
873         } // END - if
874
875         // Return it
876         return $requestMethod;
877 }
878
879 // Checks if 'content_type' is set
880 function isContentTypeSet () {
881         return isset($GLOBALS['content_type']);
882 }
883
884 // Setter for content type
885 function setContentType ($contentType) {
886         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'contentType=' . $contentType);
887         $GLOBALS['content_type'] = (string) $contentType;
888 }
889
890 // Getter for content type
891 function getContentType () {
892         // Is it there?
893         if (!isContentTypeSet()) {
894                 // Please fix this
895                 reportBug(__FUNCTION__, __LINE__, 'content_type not set in GLOBALS array.');
896         } // END - if
897
898         // Return it
899         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content_type=' . $GLOBALS['content_type']);
900         return $GLOBALS['content_type'];
901 }
902
903 // Logs wrong SERVER_NAME attempts
904 function logWrongServerNameRedirect () {
905         // Is ext-sql_patches at least version 0.9.2?
906         if (isExtensionInstalledAndNewer('sql_patches', '0.9.2')) {
907                 // Is there an entry?
908                 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'", sqlEscapeString(detectRemoteAddr(TRUE)), sqlEscapeString(detectUserAgent(TRUE)), sqlEscapeString(detectReferer(TRUE))))) == 1) {
909                         // Update counter, as all are the same
910                         sqlQueryEscaped("UPDATE
911         `{?_MYSQL_PREFIX?}_server_name_log`
912 SET
913         `server_name_counter`=`server_name_counter`+1
914 WHERE
915         `server_name`='%s' AND
916         `server_name_remote_addr`='%s' AND
917         `server_name_ua`='%s' AND
918         `server_name_referrer`='%s'
919 LIMIT 1",
920                                 array(
921                                         detectServerName(),
922                                         detectRemoteAddr(TRUE),
923                                         detectUserAgent(TRUE),
924                                         detectReferer(TRUE)
925                                 ), __FUNCTION__, __LINE__);
926                 } else {
927                         // Then log it away
928                         sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_server_name_log` (`server_name`, `server_name_remote_addr`, `server_name_ua`, `server_name_referrer`) VALUES('%s','%s', '%s', '%s')",
929                                 array(
930                                         detectServerName(),
931                                         detectRemoteAddr(TRUE),
932                                         detectUserAgent(TRUE),
933                                         detectReferer(TRUE)
934                                 ), __FUNCTION__, __LINE__);
935                 }
936         } // END - if
937 }
938
939 // Check if response status OK and array index 'response' is set
940 function isHttpResponseStatusOkay ($response) {
941         // Assertion on array
942         assert(is_array($response));
943
944         // Test it
945         $isOkay = ((isset($response['status'])) && ($response['status'] == 'OK') && (!empty($response['response'])));
946
947         // Return result
948         return $isOkay;
949 }
950
951 // [EOF]
952 ?>