Renamed script to baseUrl to make it more clear
[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 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.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 // Sends out all headers required for HTTP/1.1 reply
44 function sendHttpHeaders () {
45         // Used later
46         $now = gmdate('D, d M Y H:i:s') . ' GMT';
47
48         // Send HTTP header
49         sendHeader('HTTP/1.1 ' . getHttpStatus());
50
51         // General headers for no caching
52         sendHeader('Expires: ' . $now); // RFC2616 - Section 14.21
53         sendHeader('Last-Modified: ' . $now);
54         sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
55         sendHeader('Pragma: no-cache'); // HTTP/1.0
56         sendHeader('Connection: Close');
57         sendHeader('Content-Type: ' . getContentType() . '; charset=UTF-8');
58         sendHeader('Content-Language: ' . getLanguage());
59 }
60
61 // Send a GET request
62 function sendGetRequest ($baseUrl, $data = array(), $removeHeader = false) {
63         // Extract hostname and port from script
64         $host = extractHostnameFromUrl($baseUrl);
65
66         // Add data
67         $body = http_build_query($data, '', '&');
68
69         // There should be data, else we don't need to extend $baseUrl with $body
70         if (!empty($body)) {
71                 // Do we have a question-mark in the script?
72                 if (strpos($baseUrl, '?') === false) {
73                         // No, so first char must be question mark
74                         $body = '?' . $body;
75                 } else {
76                         // Ok, add &
77                         $body = '&' . $body;
78                 }
79
80                 // Add script data
81                 $baseUrl .= $body;
82
83                 // Remove trailed & to make it more conform
84                 if (substr($baseUrl, -1, 1) == '&') {
85                         $baseUrl = substr($baseUrl, 0, -1);
86                 } // END - if
87         } // END - if
88
89         // Generate GET request header
90         $request  = 'GET /' . trim($baseUrl) . ' HTTP/1.1' . getConfig('HTTP_EOL');
91         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
92         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
93         if (isConfigEntrySet('FULL_VERSION')) {
94                 $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
95         } else {
96                 $request .= 'User-Agent: ' . getTitle() . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
97         }
98         $request .= 'Accept: image/png,image/*;q=0.8,text/plain,text/html,*/*;q=0.5' . getConfig('HTTP_EOL');
99         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
100         $request .= 'Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0' . getConfig('HTTP_EOL');
101         $request .= 'Connection: close' . getConfig('HTTP_EOL');
102         $request .= getConfig('HTTP_EOL');
103
104         // Send the raw request
105         $response = sendRawRequest($host, $request);
106
107         // Should we remove header lines?
108         if ($removeHeader === true) {
109                 // Okay, remove them
110                 $response = removeHttpHeaderFromResponse($response);
111         } // END - if
112
113         // Return the result to the caller function
114         return $response;
115 }
116
117 // Send a POST request
118 function sendPostRequest ($baseUrl, array $postData, $removeHeader = false) {
119         // Extract host name from script
120         $host = extractHostnameFromUrl($baseUrl);
121
122         // Construct request body
123         $body = http_build_query($postData, '', '&');
124
125         // Generate POST request header
126         $request  = 'POST /' . trim($baseUrl) . ' HTTP/1.0' . getConfig('HTTP_EOL');
127         $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
128         $request .= 'Referer: ' . getUrl() . '/admin.php' . getConfig('HTTP_EOL');
129         $request .= 'User-Agent: ' . getTitle() . '/' . getFullVersion() . getConfig('HTTP_EOL');
130         $request .= 'Accept: text/plain;q=0.8' . getConfig('HTTP_EOL');
131         $request .= 'Accept-Charset: UTF-8,*' . getConfig('HTTP_EOL');
132         $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
133         $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
134         $request .= 'Content-Length: ' . strlen($body) . getConfig('HTTP_EOL');
135         $request .= 'Connection: close' . getConfig('HTTP_EOL');
136         $request .= getConfig('HTTP_EOL');
137
138         // Add body
139         $request .= $body;
140
141         // Send the raw request
142         $response = sendRawRequest($host, $request);
143
144         // Should we remove header lines?
145         if ($removeHeader === true) {
146                 // Okay, remove them
147                 $response = removeHttpHeaderFromResponse($response);
148         } // END - if
149
150         // Return the result to the caller function
151         return $response;
152 }
153
154 // Sends a raw request to another host
155 function sendRawRequest ($host, $request) {
156         // Init errno and errdesc with 'all fine' values
157         $errno = '0';
158         $errdesc = '';
159
160         // Default port is 80
161         $port = 80;
162
163         // Initialize array
164         $response = array('', '', '');
165
166         // Default is not to use proxy
167         $useProxy = false;
168
169         // Default is non-broken HTTP server implementation
170         $GLOBALS['is_http_server_broken'] = false;
171
172         // Are proxy settins set?
173         if (isProxyUsed()) {
174                 // Then use it
175                 $useProxy = true;
176         } // END - if
177
178         // Load include
179         loadIncludeOnce('inc/classes/resolver.class.php');
180
181         // Extract port part from host
182         $portArray = explode(':', $host);
183         if (count($portArray) == 2) {
184                 // Extract host and port
185                 $host = $portArray[0];
186                 $port = $portArray[1];
187         } elseif (count($portArray) > 2) {
188                 // This should not happen!
189                 debug_report_bug(__FUNCTION__, __LINE__, 'Invalid ' . $host . '. Please report this to the Mailer-Project team.');
190         }
191
192         // Get resolver instance
193         $resolver = new HostnameResolver();
194
195         // Open connection
196         //* DEBUG: */ die('baseUrl=' . $baseUrl);
197         if ($useProxy === true) {
198                 // Resolve hostname into IP address
199                 $ip = $resolver->resolveHostname(compileRawCode(getProxyHost()));
200
201                 // Connect to host through proxy connection
202                 $fp = fsockopen($ip, bigintval(getProxyPort()), $errno, $errdesc, 30);
203         } else {
204                 // Resolve hostname into IP address
205                 $ip = $resolver->resolveHostname($host);
206
207                 // Connect to host directly
208                 $fp = fsockopen($ip, $port, $errno, $errdesc, 30);
209         }
210
211         // Is there a link?
212         if (!is_resource($fp)) {
213                 // Failed!
214                 logDebugMessage(__FUNCTION__, __LINE__, $errdesc . ' (' . $errno . ')');
215                 return $response;
216         } elseif ((!stream_set_blocking($fp, 0)) || (!stream_set_timeout($fp, 1))) {
217                 // Cannot set non-blocking mode or timeout
218                 logDebugMessage(__FUNCTION__, __LINE__, socket_strerror(socket_last_error()));
219                 return $response;
220         }
221
222         // Do we use proxy?
223         if ($useProxy === true) {
224                 // Setup proxy tunnel
225                 $response = setupProxyTunnel($host, $port, $fp);
226
227                 // If the response is invalid, abort
228                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
229                         // Invalid response!
230                         logDebugMessage(__FUNCTION__, __LINE__, 'Proxy tunnel not working?');
231                         return $response;
232                 } // END - if
233         } // END - if
234
235         // Write request
236         fwrite($fp, $request);
237
238         // Start counting
239         $start = microtime(true);
240
241         // Read response
242         while (!feof($fp)) {
243                 // Get info from stream
244                 $info = stream_get_meta_data($fp);
245
246                 // Is it timed out? 15 seconds is a really patient...
247                 if (($info['timed_out'] == true) || (microtime(true) - $start) > 15) {
248                         // Timeout
249                         logDebugMessage(__FUNCTION__, __LINE__, 'Timed out to get data from host ' . $host);
250
251                         // Abort here
252                         break;
253                 } // END - if
254
255                 // Get line from stream
256                 $line = fgets($fp, 128);
257
258                 // Ignore empty lines because of non-blocking mode
259                 if (empty($line)) {
260                         // uslepp a little to avoid 100% CPU load
261                         usleep(10);
262
263                         // Skip this
264                         continue;
265                 } // END - if
266
267                 // Check for broken HTTP implementations
268                 if (substr(strtolower($line), 0, 7) == 'server:') {
269                         // Anomic (see http://anomic.de, http://yacy.net) is currently broken
270                         $GLOBALS['is_http_server_broken'] = (count(getArrayKeysFromSubStrArray(strtolower($line), array('anomichttpd'))) > 0);
271                 } // END - if
272
273                 // Add it to response
274                 $response[] = $line;
275         } // END - while
276
277         // Close socket
278         fclose($fp);
279
280         // Time request if debug-mode is enabled
281         if (isDebugModeEnabled()) {
282                 // Add debug message...
283                 logDebugMessage(__FUNCTION__, __LINE__, 'Request took ' . (microtime(true) - $start) . ' seconds and returned ' . count($response) . ' line(s).');
284         } // END - if
285
286         // Skip first empty lines
287         $resp = $response;
288         foreach ($resp as $idx => $line) {
289                 // Trim space away
290                 $line = trim($line);
291
292                 // Is this line empty?
293                 if (empty($line)) {
294                         // Then remove it
295                         array_shift($response);
296                 } else {
297                         // Abort on first non-empty line
298                         break;
299                 }
300         } // END - foreach
301
302         //* DEBUG: */ debugOutput('<strong>Request:</strong><pre>'.print_r($request, true).'</pre>');
303         //* DEBUG: */ debugOutput('<strong>Response:</strong><pre>'.print_r($response, true).'</pre>');
304
305         // Proxy agent found or something went wrong?
306         if (!isset($response[0])) {
307                 // No response, maybe timeout
308                 $response = array('', '', '');
309                 logDebugMessage(__FUNCTION__, __LINE__, 'Invalid empty response array, maybe timed out?');
310         } elseif ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
311                 // Proxy header detected, so remove two lines
312                 array_shift($response);
313                 array_shift($response);
314         } // END - if
315
316         // Was the request successfull?
317         if ((!isInStringIgnoreCase('200 OK', $response[0])) || (empty($response[0]))) {
318                 // Not found / access forbidden
319                 logDebugMessage(__FUNCTION__, __LINE__, 'Unexpected status code ' . $response[0] . ' detected. "200 OK" was expected.');
320                 $response = array('', '', '');
321         } else {
322                 // Check array for chuncked encoding
323                 $response = unchunkHttpResponse($response);
324         } // END - if
325
326         // Return response
327         return $response;
328 }
329
330 // Sets up a proxy tunnel for given hostname and through resource
331 function setupProxyTunnel ($host, $port, $resource) {
332         // Initialize array
333         $response = array('', '', '');
334
335         // Generate CONNECT request header
336         $proxyTunnel  = 'CONNECT ' . $host . ':' . $port . ' HTTP/1.0' . getConfig('HTTP_EOL');
337         $proxyTunnel .= 'Host: ' . $host . getConfig('HTTP_EOL');
338
339         // Use login data to proxy? (username at least!)
340         if (getProxyUsername() != '') {
341                 // Add it as well
342                 $encodedAuth = base64_encode(compileRawCode(getProxyUsername()) . ':' . compileRawCode(getProxyPassword()));
343                 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . getConfig('HTTP_EOL');
344         } // END - if
345
346         // Add last new-line
347         $proxyTunnel .= getConfig('HTTP_EOL');
348         //* DEBUG: */ debugOutput('<strong>proxyTunnel=</strong><pre>' . $proxyTunnel.'</pre>');
349
350         // Write request
351         fwrite($fp, $proxyTunnel);
352
353         // Got response?
354         if (feof($fp)) {
355                 // No response received
356                 return $response;
357         } // END - if
358
359         // Read the first line
360         $resp = trim(fgets($fp, 10240));
361         $respArray = explode(' ', $resp);
362         if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
363                 // Invalid response!
364                 return $response;
365         } // END - if
366
367         // All fine!
368         return $respArray;
369 }
370
371 // Check array for chuncked encoding
372 function unchunkHttpResponse (array $response) {
373         // Default is not chunked
374         $isChunked = false;
375
376         // Check if we have chunks
377         foreach ($response as $line) {
378                 // Make lower-case and trim it
379                 $line = trim(strtolower($line));
380
381                 // Entry found?
382                 if ((strpos($line, 'transfer-encoding') !== false) && (strpos($line, 'chunked') !== false)) {
383                         // Found!
384                         $isChunked = true;
385                         break;
386                 } // END - if
387         } // END - foreach
388
389         // Is it chunked?
390         if ($isChunked === true) {
391                 // Good, we still have the HTTP headers in there, so we need to get rid
392                 // of them temporarly
393                 //* DEBUG: */ die('<pre>'.htmlentities(print_r(removeHttpHeaderFromResponse($response), true)).'</pre>');
394                 $tempResponse = http_chunked_decode(implode('', removeHttpHeaderFromResponse($response)));
395
396                 // We got a string back from http_chunked_decode(), so we need to convert it back to an array
397                 //* DEBUG: */ die('tempResponse['.strlen($tempResponse).']=<pre>'.replaceReturnNewLine(htmlentities($tempResponse)).'</pre>');
398
399                 // Re-add the headers
400                 $response = merge_array($GLOBALS['http_headers'], stringToArray("\n", $tempResponse));
401         } // END - if
402
403         // Return the unchunked array
404         return $response;
405 }
406
407 // Removes HTTP header lines from a response array (e.g. output from send<Get|Post>Request() )
408 function removeHttpHeaderFromResponse (array $response) {
409         // Save headers for later usage
410         $GLOBALS['http_headers'] = array();
411
412         // The first array element has to contain HTTP
413         if ((isset($response[0])) && (substr(strtoupper($response[0]), 0, 5) == 'HTTP/')) {
414                 // Okay, we have headers, now remove them with a second array
415                 $response2 = $response;
416                 foreach ($response as $line) {
417                         // Remove line
418                         array_shift($response2);
419
420                         // Add full line to temporary global array
421                         $GLOBALS['http_headers'][] = $line;
422
423                         // Trim it for testing
424                         $lineTest = trim($line);
425
426                         // Is this line empty?
427                         if (empty($lineTest)) {
428                                 // Then stop here
429                                 break;
430                         } // END - if
431                 } // END - foreach
432
433                 // Write back the array
434                 $response = $response2;
435         } // END - if
436
437         // Return the modified response array
438         return $response;
439 }
440
441 // Returns the flag if a broken HTTP server implementation was detected
442 function isBrokenHttpServerImplentation () {
443         // Determine it
444         $isBroken = ((isset($GLOBALS['is_http_server_broken'])) && ($GLOBALS['is_http_server_broken'] === true));
445
446         // ... and return it
447         return $isBroken;
448 }
449
450 //-----------------------------------------------------------------------------
451 // Automatically re-created functions, all taken from user comments on www.php.net
452 //-----------------------------------------------------------------------------
453
454 if (!function_exists('http_build_query')) {
455         // Taken from documentation on www.php.net, credits to Marco K. (Germany) and some light mods by R.Haeder
456         function http_build_query($data, $prefix = '', $sep = '', $key = '') {
457                 $ret = array();
458                 foreach ((array) $data as $k => $v) {
459                         if (is_int($k) && $prefix != null) {
460                                 $k = urlencode($prefix . $k);
461                         } // END - if
462
463                         if ((!empty($key)) || ($key === 0)) {
464                                 $k = $key . '[' . urlencode($k) . ']';
465                         } // END - if
466
467                         if (is_array($v) || is_object($v)) {
468                                 array_push($ret, http_build_query($v, '', $sep, $k));
469                         } else {
470                                 array_push($ret, $k . '=' . urlencode($v));
471                         }
472                 } // END - foreach
473
474                 if (empty($sep)) {
475                         $sep = ini_get('arg_separator.output');
476                 } // END - if
477
478                 return implode($sep, $ret);
479         }
480 } // END - if
481
482 if (!function_exists('http_chunked_decode')) {
483         /**
484          * dechunk an HTTP 'transfer-encoding: chunked' message.
485          *
486          * @param       $chunk          The encoded message
487          * @return      $dechunk        The decoded message. If $chunk wasn't encoded properly debug_report_bug() is being called
488          * @author      Marques Johansson (initial author)
489          * @author      Roland Haeder (heavy modifications and simplification)
490          * @link        http://php.net/manual/en/function.http-chunked-decode.php#89786
491          */
492         function http_chunked_decode ($chunk) {
493                 // Detect multi-byte encoding
494                 $mbPrefix = detectMultiBytePrefix($chunk);
495                 //* DEBUG: */ print 'mbPrefix=' . $mbPrefix . '<br />';
496
497                 // Init some variables
498                 $offset = 0;
499                 $len = call_user_func_array($mbPrefix . 'strlen', array(($chunk)));
500                 $dechunk = '';
501
502                 // Walk through all chunks
503                 while ($offset < $len) {
504                         // Where does the \r\n begin?
505                         $lineEndAt = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset));
506
507                         /* DEBUG: *
508                         print 'lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
509 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
510 len='.$len.'<br />
511 next[offset,10]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 10)))).'</pre>';
512                         /* DEBUG: */
513
514                         // Get next hex-coded chunk length
515                         $chunkLenHex = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, ($lineEndAt - $offset)));
516
517                         /* DEBUG: *
518                         print 'chunkLenHex[<em>'.__LINE__.'</em>]='.replaceReturnNewLine(htmlentities($chunkLenHex)).'<br />
519 ';
520                         /* DEBUG: */
521
522                         // Validation if it is hexadecimal
523                         if (!isHexadecimal($chunkLenHex)) {
524                                 // Please help debugging this
525                                 //* DEBUG: */ die('ABORT:chunkLenHex=<pre>'.replaceReturnNewLine(htmlentities($chunkLenHex)).'</pre>');
526                                 debug_report_bug(__FUNCTION__, __LINE__, 'Value ' . $chunkLenHex . ' is no valid hexa-decimal string.');
527
528                                 // This won't be reached
529                                 return $chunk;
530                         } // END - if
531
532                         // Position of next chunk is right after \r\n
533                         $offset   = $offset + strlen($chunkLenHex) + strlen(getConfig('HTTP_EOL'));
534                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL')));
535
536                         /* DEBUG: *
537                         print 'chunkLen='.$chunkLen.'<br />
538 offset[<em>'.__LINE__.'</em>]='.$offset.'<br />';
539                         /* DEBUG: */
540
541                         // Moved out for debugging
542                         $next  = call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
543                         //* DEBUG: */ print 'next=<pre>'.replaceReturnNewLine(htmlentities($next)).'</pre>';
544
545                         /*
546                          * Hack for e.g. YaCy HTTPDaemon (Anomic Server), this HTTP server
547                          * is currently (revision 7567 and maybe earlier) broken and does
548                          * not include the \r\n characters when it sents a "chunked" HTTP
549                          * message.
550                          */
551                         $count = 0;
552                         if (isBrokenHttpServerImplentation()) {
553                                 // Count occurrences of \r\n
554                                 $count = call_user_func_array($mbPrefix . 'substr_count', array($next, getConfig('HTTP_EOL')));
555                         } // END - if
556
557                         /*
558                          * Correct chunk length because some broken HTTP server
559                          * implementation subtract occurrences of \r\n in their chunk
560                          * lengths.
561                          */
562                         $chunkLen = hexdec(rtrim($chunkLenHex, getConfig('HTTP_EOL'))) - ($count * strlen(getConfig('HTTP_EOL')));
563
564                         // Add next chunk to $dechunk
565                         $dechunk .= call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, $chunkLen));
566
567                         /* DEBUG: *
568                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
569 lineEndAt[<em>'.__LINE__.'</em>]='.$lineEndAt.'<br />
570 len='.$len.'<br />
571 count='.$count.'<br />
572 chunkLen='.$chunkLen.'<br />
573 chunkLenHex='.$chunkLenHex.'<br />
574 dechunk=<pre>'.replaceReturnNewLine(htmlentities($dechunk)).'</pre>
575 chunk=<pre>'.replaceReturnNewLine(htmlentities($chunk)).'</pre>');
576                         /* DEBUG: */
577
578                         // Is $offset + $chunkLen larger than or equal $len?
579                         if (($offset + $chunkLen) >= $len) {
580                                 // Then stop processing here
581                                 break;
582                         } // END - if
583
584                         // Calculate offset of next chunk
585                         $offset = call_user_func_array($mbPrefix . 'strpos', array($chunk, getConfig('HTTP_EOL'), $offset + $chunkLen)) + 2;
586
587                         /* DEBUG: *
588                         print('offset[<em>'.__LINE__.'</em>]='.$offset.'<br />
589 next[100]=<pre>'.replaceReturnNewLine(htmlentities(call_user_func_array($mbPrefix . 'substr', array($chunk, $offset, 100)))).'</pre>
590 ---:---:---:---:---:---:---:---:---<br />
591 ');
592                         /* DEBUG: */
593                 } // END - while
594
595                 // Return de-chunked string
596                 return $dechunk;
597         }
598 } // END - if
599
600 // [EOF]
601 ?>