Support all extensions in link, too
[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 ? $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                 /*
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 (count($response) == 0) {
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((is_array($GLOBALS['http_headers'])) && (count($GLOBALS['http_headers']) > 0));
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('http://', '', $url);
654         if (isInString('/', $host)) {
655                 $host = substr($host, 0, strpos($host, '/'));
656         } // END - if
657
658         // Generate relative URL
659         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
660         if (substr(strtolower($script), 0, 7) == 'http://') {
661                 // But only if http:// is in front!
662                 $script = substr($script, (strlen($url) + 7));
663         } elseif (substr(strtolower($script), 0, 8) == 'https://') {
664                 // Does this work?!
665                 $script = substr($script, (strlen($url) + 8));
666         }
667
668         //* DEBUG: */ debugOutput('SCRIPT=' . $script);
669         if (substr($script, 0, 1) == '/') {
670                 $script = substr($script, 1);
671         } // END - if
672
673         // Return host name
674         return $host;
675 }
676
677 // Adds a HTTP header to array
678 function addHttpHeader ($header) {
679         // Send the header
680         //* DEBUG: */ logDebugMessage(__FUNCTION__ . ': header=' . $header);
681         array_push($GLOBALS['http_header'], trim($header));
682 }
683
684 // Flushes all HTTP headers
685 function flushHttpHeaders () {
686         // Is the header already sent?
687         if (headers_sent()) {
688                 // Then abort here
689                 reportBug(__FUNCTION__, __LINE__, 'Headers already sent!');
690         } elseif ((!isset($GLOBALS['http_header'])) || (!is_array($GLOBALS['http_header']))) {
691                 // Not set or not an array
692                 reportBug(__FUNCTION__, __LINE__, 'Headers not set or not an array, isset()=' . isset($GLOBALS['http_header']) . ', please report this.');
693         }
694
695         // Flush all headers if found
696         foreach ($GLOBALS['http_header'] as $header) {
697                 // Send a single header
698                 header($header);
699         } // END - foreach
700
701         // Mark them as flushed
702         $GLOBALS['http_header'] = array();
703 }
704
705 //-----------------------------------------------------------------------------
706 // Automatically re-created functions, all taken from user comments on www.php.net
707 //-----------------------------------------------------------------------------
708
709 if (!function_exists('http_build_query')) {
710         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
711         function http_build_query($requestData, $prefix = '', $sep = '', $key = '') {
712                 $ret = array();
713                 foreach ((array) $requestData as $k => $v) {
714                         if (is_int($k) && !is_null($prefix)) {
715                                 $k = urlencode($prefix . $k);
716                         } // END - if
717
718                         if ((!empty($key)) || ($key === 0)) {
719                                 $k = $key . '[' . urlencode($k) . ']';
720                         } // END - if
721
722                         if (is_array($v) || is_object($v)) {
723                                 array_push($ret, http_build_query($v, '', $sep, $k));
724                         } else {
725                                 array_push($ret, $k . '=' . urlencode($v));
726                         }
727                 } // END - foreach
728
729                 if (empty($sep)) {
730                         $sep = ini_get('arg_separator.output');
731                 } // END - if
732
733                 return implode($sep, $ret);
734         }
735 } // END - if
736
737 if (!function_exists('http_chunked_decode')) {
738         /**
739          * dechunk an HTTP 'transfer-encoding: chunked' message.
740          *
741          * @param       $chunk          The encoded message
742          * @return      $dechunk        The decoded message. If $chunk wasn't encoded properly reportBug() is being called
743          * @author      Marques Johansson (initial author)
744          * @author      Roland Haeder (heavy modifications and simplification)
745          * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
746          */
747         function http_chunked_decode ($chunk) {
748                 // Detect multi-byte encoding
749                 $mbPrefix = detectMultiBytePrefix($chunk);
750                 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
751
752                 // Init some variables
753                 $offset = 0;
754                 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
755                 $dechunk = '';
756
757                 // Walk through all chunks
758                 while ($offset < $len) {
759                         // Where does the \r\n begin?
760                         $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
761
762                         /* DEBUG: *
763                         print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
764 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
765 len='.$len.'<br />
766 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
767                         /* DEBUG: */
768
769                         // Get next hex-coded chunk length
770                         $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
771
772                         /* DEBUG: *
773                         print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
774 ';
775                         /* DEBUG: */
776
777                         // Validation if it is hexadecimal
778                         if (!isHexadecimal($chunkLenHex)) {
779                                 // Please help debugging this
780                                 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
781                                 reportBug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
782
783                                 // This won't be reached
784                                 return $chunk;
785                         } // END - if
786
787                         // Position of next chunk is right after \r\n
788                         $offset   = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
789                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
790
791                         /* DEBUG: *
792                         print 'chunkLen='.$chunkLen.'<br />
793 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
794                         /* DEBUG: */
795
796                         // Moved out for debugging
797                         $next  = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
798                         //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
799
800                         /*
801                          * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
802                          * is currently (revision 7567 and maybe earlier) broken and does
803                          * not include the \r\n characters when it sents a "chunked" HTTP
804                          * message.
805                          */
806                         $count = 0;
807                         if (isBrokenHttpServerImplentation()) {
808                                 // Count occurrences of \r\n
809                                 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
810                         } // END - if
811
812                         /*
813                          * Correct chunk length because some broken HTTP server
814                          * implementation subtract occurrences of \r\n in their chunk
815                          * lengths.
816                          */
817                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
818
819                         // Add next chunk to $dechunk
820                         $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
821
822                         /* DEBUG: *
823                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
824 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
825 len='.$len.'<br />
826 count='.$count.'<br />
827 chunkLen='.$chunkLen.'<br />
828 chunkLenHex='.$chunkLenHex.'<br />
829 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
830 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
831                         /* DEBUG: */
832
833                         // Is $offset + $chunkLen larger than or equal $len?
834                         if (($offset + $chunkLen) >= $len) {
835                                 // Then stop processing here
836                                 break;
837                         } // END - if
838
839                         // Calculate offset of next chunk
840                         $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
841
842                         /* DEBUG: *
843                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
844 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
845 ---:---:---:---:---:---:---:---:---<br />
846 ');
847                         /* DEBUG: */
848                 } // END - while
849
850                 // Return de-chunked string
851                 return $dechunk;
852         }
853 } // END - if
854
855 // Getter for request method
856 function getHttpRequestMethod () {
857         // Console is default
858         $requestMethod = 'console';
859
860         // Is it set?
861         if (isset($_SERVER['REQUEST_METHOD'])) {
862                 // Get current request method
863                 $requestMethod = $_SERVER['REQUEST_METHOD'];
864         } // END - if
865
866         // Return it
867         return $requestMethod;
868 }
869
870 // Checks if 'content_type' is set
871 function isContentTypeSet () {
872         return isset($GLOBALS['content_type']);
873 }
874
875 // Setter for content type
876 function setContentType ($contentType) {
877         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'contentType=' . $contentType);
878         $GLOBALS['content_type'] = (string) $contentType;
879 }
880
881 // Getter for content type
882 function getContentType () {
883         // Is it there?
884         if (!isContentTypeSet()) {
885                 // Please fix this
886                 reportBug(__FUNCTION__, __LINE__, 'content_type not set in GLOBALS array.');
887         } // END - if
888
889         // Return it
890         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'content_type=' . $GLOBALS['content_type']);
891         return $GLOBALS['content_type'];
892 }
893
894 // Logs wrong SERVER_NAME attempts
895 function logWrongServerNameRedirect () {
896         // Is ext-sql_patches at least version 0.9.2?
897         if (isExtensionInstalledAndNewer('sql_patches', '0.9.2')) {
898                 // Is there an entry?
899                 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) {
900                         // Update counter, as all are the same
901                         sqlQueryEscaped("UPDATE
902         `{?_MYSQL_PREFIX?}_server_name_log`
903 SET
904         `server_name_counter`=`server_name_counter`+1
905 WHERE
906         `server_name`='%s' AND
907         `server_name_remote_addr`='%s' AND
908         `server_name_ua`='%s' AND
909         `server_name_referrer`='%s'
910 LIMIT 1",
911                                 array(
912                                         detectServerName(),
913                                         detectRemoteAddr(TRUE),
914                                         detectUserAgent(TRUE),
915                                         detectReferer(TRUE)
916                                 ), __FUNCTION__, __LINE__);
917                 } else {
918                         // Then log it away
919                         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')",
920                                 array(
921                                         detectServerName(),
922                                         detectRemoteAddr(TRUE),
923                                         detectUserAgent(TRUE),
924                                         detectReferer(TRUE)
925                                 ), __FUNCTION__, __LINE__);
926                 }
927         } // END - if
928 }
929
930 // [EOF]
931 ?>