Check for error response codes, don't proxy via localhost in command line mode
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * Various HTTP related functions
4 */
5
6 /**
7 * Get the contents of a file by HTTP
8 *
9 * if $timeout is 'default', $wgHTTPTimeout is used
10 */
11 function wfGetHTTP( $url, $timeout = 'default' ) {
12 global $wgServer, $wgHTTPTimeout, $wgHTTPProxy;
13
14
15 # Use curl if available
16 if ( function_exists( 'curl_init' ) ) {
17 $c = curl_init( $url );
18 if ( wfIsLocalURL( $url ) ) {
19 curl_setopt( $c, CURLOPT_PROXY, 'localhost:80' );
20 } else if ($wgHTTPProxy)
21 curl_setopt($c, CURLOPT_PROXY, $wgHTTPProxy);
22
23 if ( $timeout == 'default' ) {
24 $timeout = $wgHTTPTimeout;
25 }
26 curl_setopt( $c, CURLOPT_TIMEOUT, $timeout );
27 ob_start();
28 curl_exec( $c );
29 $text = ob_get_contents();
30 ob_end_clean();
31
32 # Don't return the text of error messages, return false on error
33 if ( curl_getinfo( $c, CURLINFO_HTTP_CODE ) != 200 ) {
34 $text = false;
35 }
36 curl_close( $c );
37 } else {
38 # Otherwise use file_get_contents, or its compatibility function from GlobalFunctions.php
39 # This may take 3 minutes to time out, and doesn't have local fetch capabilities
40 $url_fopen = ini_set( 'allow_url_fopen', 1 );
41 $text = file_get_contents( $url );
42 ini_set( 'allow_url_fopen', $url_fopen );
43 }
44 return $text;
45 }
46
47 /**
48 * Check if the URL can be served by localhost
49 */
50 function wfIsLocalURL( $url ) {
51 global $wgCommandLineMode, $wgConf;
52 if ( $wgCommandLineMode ) {
53 return false;
54 }
55
56 // Extract host part
57 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
58 $host = $matches[1];
59 // Split up dotwise
60 $domainParts = explode( '.', $host );
61 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
62 $domainParts = array_reverse( $domainParts );
63 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
64 $domainPart = $domainParts[$i];
65 if ( $i == 0 ) {
66 $domain = $domainPart;
67 } else {
68 $domain = $domainPart . '.' . $domain;
69 }
70 if ( $wgConf->isLocalVHost( $domain ) ) {
71 return true;
72 }
73 }
74 }
75 return false;
76 }
77
78 ?>