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