Bug 35034 - moved autocomment-prefix between the prefix and the arrow. Follow up...
[lhc/web/wiklou.git] / includes / HttpFunctions.php
index 6d47a6b..8dd6525 100644 (file)
@@ -14,14 +14,15 @@ class Http {
         * Perform an HTTP request
         *
         * @param $method String: HTTP method. Usually GET/POST
-        * @param $url String: full URL to act on
+        * @param $url String: full URL to act on. If protocol-relative, will be expanded to an http:// URL
         * @param $options Array: options to pass to MWHttpRequest object.
         *      Possible keys for the array:
         *    - timeout             Timeout length in seconds
         *    - postData            An array of key-value pairs or a url-encoded form data
         *    - proxy               The proxy to use.
-        *                          Will use $wgHTTPProxy (if set) otherwise.
-        *    - noProxy             Override $wgHTTPProxy (if set) and don't use any proxy at all.
+        *                          Otherwise it will use $wgHTTPProxy (if set)
+        *                          Otherwise it will use the environment variable "http_proxy" (if set)
+        *    - noProxy             Don't use any proxy at all. Takes precedence over proxy value(s).
         *    - sslVerifyHost       (curl only) Verify hostname against certificate
         *    - sslVerifyCert       (curl only) Verify SSL certificate
         *    - caInfo              (curl only) Provide CA information
@@ -29,10 +30,11 @@ class Http {
         *    - followRedirects     Whether to follow redirects (defaults to false).
         *                                  Note: this should only be used when the target URL is trusted,
         *                                  to avoid attacks on intranet services accessible by HTTP.
+        *    - userAgent           A user agent, if you want to override the default
+        *                          MediaWiki/$wgVersion
         * @return Mixed: (bool)false on failure or a string on success
         */
        public static function request( $method, $url, $options = array() ) {
-               $url = wfExpandUrl( $url );
                wfDebug( "HTTP: $method: $url\n" );
                $options['method'] = strtoupper( $method );
 
@@ -53,6 +55,11 @@ class Http {
        /**
         * Simple wrapper for Http::request( 'GET' )
         * @see Http::request()
+        *
+        * @param $url
+        * @param $timeout string
+        * @param $options array
+        * @return string
         */
        public static function get( $url, $timeout = 'default', $options = array() ) {
                $options['timeout'] = $timeout;
@@ -62,6 +69,10 @@ class Http {
        /**
         * Simple wrapper for Http::request( 'POST' )
         * @see Http::request()
+        *
+        * @param $url
+        * @param $options array
+        * @return string
         */
        public static function post( $url, $options = array() ) {
                return Http::request( 'POST', $url, $options );
@@ -121,12 +132,16 @@ class Http {
         * protocols, because we only want protocols that both cURL
         * and php support.
         *
+        * file:// should not be allowed here for security purpose (r67684)
+        *
+        * @fixme this is wildly inaccurate and fails to actually check most stuff
+        *
         * @param $uri Mixed: URI to check for validity
-        * @returns Boolean
+        * @return Boolean
         */
        public static function isValidURI( $uri ) {
                return preg_match(
-                       '/^(f|ht)tps?:\/\/[^\/\s]\S*$/D',
+                       '/^https?:\/\/[^\/\s]\S*$/D',
                        $uri
                );
        }
@@ -136,12 +151,12 @@ class Http {
  * This wrapper class will call out to curl (if available) or fallback
  * to regular PHP if necessary for handling internal HTTP requests.
  *
- * Renamed from HttpRequest to MWHttpRequst to avoid conflict with
- * php's HTTP extension.
+ * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
+ * PHP's HTTP extension.
  */
 class MWHttpRequest {
        const SUPPORTS_FILE_POSTS = false;
-       
+
        protected $content;
        protected $timeout = 'default';
        protected $headersOnly = null;
@@ -172,16 +187,16 @@ class MWHttpRequest {
        public $status;
 
        /**
-        * @param $url String: url to use
+        * @param $url String: url to use. If protocol-relative, will be expanded to an http:// URL
         * @param $options Array: (optional) extra params to pass (see Http::request())
         */
        function __construct( $url, $options = array() ) {
                global $wgHTTPTimeout;
 
-               $this->url = $url;
-               $this->parsedUrl = parse_url( $url );
+               $this->url = wfExpandUrl( $url, PROTO_HTTP );
+               $this->parsedUrl = wfParseUrl( $this->url );
 
-               if ( !Http::isValidURI( $this->url ) ) {
+               if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
                        $this->status = Status::newFatal( 'http-invalid-url' );
                } else {
                        $this->status = Status::newGood( 100 ); // continue
@@ -192,6 +207,9 @@ class MWHttpRequest {
                } else {
                        $this->timeout = $wgHTTPTimeout;
                }
+               if( isset( $options['userAgent'] ) ) {
+                       $this->setUserAgent( $options['userAgent'] );
+               }
 
                $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
                                  "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
@@ -201,12 +219,26 @@ class MWHttpRequest {
                                $this->$o = $options[$o];
                        }
                }
+
+               if ( $this->noProxy ) {
+                       $this->proxy = ''; // noProxy takes precedence
+               }
+       }
+
+       /**
+        * Simple function to test if we can make any sort of requests at all, using
+        * cURL or fopen()
+        * @return bool
+        */
+       public static function canMakeRequests() {
+               return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
        }
 
        /**
         * Generate a new request object
-        * @param $url String: url to use
+        * @param $url String: url to use
         * @param $options Array: (optional) extra params to pass (see Http::request())
+        * @return CurlHttpRequest|PhpHttpRequest
         * @see MWHttpRequest::__construct
         */
        public static function factory( $url, $options = null ) {
@@ -251,20 +283,19 @@ class MWHttpRequest {
        }
 
        /**
-        * Take care of setting up the proxy
-        * (override in subclass)
+        * Take care of setting up the proxy (do nothing if "noProxy" is set)
         *
-        * @return String
+        * @return void
         */
        public function proxySetup() {
                global $wgHTTPProxy;
 
-               if ( $this->proxy ) {
+               if ( $this->proxy || !$this->noProxy ) {
                        return;
                }
 
-               if ( Http::isLocalURL( $this->url ) ) {
-                       $this->proxy = 'http://localhost:80/';
+               if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
+                       $this->proxy = '';
                } elseif ( $wgHTTPProxy ) {
                        $this->proxy = $wgHTTPProxy ;
                } elseif ( getenv( "http_proxy" ) ) {
@@ -281,6 +312,7 @@ class MWHttpRequest {
 
        /**
         * Set the user agent
+        * @param $UA string
         */
        public function setUserAgent( $UA ) {
                $this->setHeader( 'User-Agent', $UA );
@@ -288,6 +320,8 @@ class MWHttpRequest {
 
        /**
         * Set an arbitrary header
+        * @param $name
+        * @param $value
         */
        public function setHeader( $name, $value ) {
                // I feel like I should normalize the case here...
@@ -296,6 +330,7 @@ class MWHttpRequest {
 
        /**
         * Get an array of the headers
+        * @return array
         */
        public function getHeaderList() {
                $list = array();
@@ -316,11 +351,26 @@ class MWHttpRequest {
        }
 
        /**
-        * Set the callback
+        * Set a read callback to accept data read from the HTTP request.
+        * By default, data is appended to an internal buffer which can be
+        * retrieved through $req->getContent().
+        *
+        * To handle data as it comes in -- especially for large files that
+        * would not fit in memory -- you can instead set your own callback,
+        * in the form function($resource, $buffer) where the first parameter
+        * is the low-level resource being read (implementation specific),
+        * and the second parameter is the data buffer.
+        *
+        * You MUST return the number of bytes handled in the buffer; if fewer
+        * bytes are reported handled than were passed to you, the HTTP fetch
+        * will be aborted.
         *
         * @param $callback Callback
         */
        public function setCallback( $callback ) {
+               if ( !is_callable( $callback ) ) {
+                       throw new MWException( 'Invalid MwHttpRequest callback' );
+               }
                $this->callback = $callback;
        }
 
@@ -330,6 +380,7 @@ class MWHttpRequest {
         *
         * @param $fh handle
         * @param $content String
+        * @return int
         */
        public function read( $fh, $content ) {
                $this->content .= $content;
@@ -351,12 +402,10 @@ class MWHttpRequest {
                }
 
                if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
-                       $this->setReferer( $wgTitle->getFullURL() );
+                       $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
                }
 
-               if ( !$this->noProxy ) {
-                       $this->proxySetup();
-               }
+               $this->proxySetup(); // set up any proxy as needed
 
                if ( !$this->callback ) {
                        $this->setCallback( array( $this, 'read' ) );
@@ -371,8 +420,6 @@ class MWHttpRequest {
         * Parses the headers, including the HTTP status code and any
         * Set-Cookie headers.  This function expectes the headers to be
         * found in an array in the member variable headerList.
-        *
-        * @return nothing
         */
        protected function parseHeader() {
                $lastname = "";
@@ -400,8 +447,6 @@ class MWHttpRequest {
         * RFC2616, section 10,
         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
         * list of status codes.)
-        *
-        * @return nothing
         */
        protected function setStatus() {
                if ( !$this->respHeaders ) {
@@ -496,7 +541,7 @@ class MWHttpRequest {
        /**
         * Returns the cookie jar in use.
         *
-        * @returns CookieJar
+        * @return CookieJar
         */
        public function getCookieJar() {
                if ( !$this->respHeaders ) {
@@ -511,6 +556,9 @@ class MWHttpRequest {
         * cookies.      Used internally after a request to parse the
         * Set-Cookie headers.
         * @see Cookie::set
+        * @param $name
+        * @param $value null
+        * @param $attr null
         */
        public function setCookie( $name, $value = null, $attr = null ) {
                if ( !$this->cookieJar ) {
@@ -539,13 +587,48 @@ class MWHttpRequest {
        /**
         * Returns the final URL after all redirections.
         *
-        * @return String
+        * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
+        * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
+        *
+        * Note that the multiple Location: headers are an artifact of CURL -- they
+        * shouldn't actually get returned this way. Rewrite this when bug 29232 is
+        * taken care of (high-level redirect handling rewrite).
+        *
+        * @return string
         */
        public function getFinalUrl() {
-               $location = $this->getResponseHeader( "Location" );
+               $headers = $this->getResponseHeaders();
 
-               if ( $location ) {
-                       return $location;
+               //return full url (fix for incorrect but handled relative location)
+               if ( isset( $headers[ 'location' ] ) ) {
+                       $locations = $headers[ 'location' ];
+                       $domain = '';
+                       $foundRelativeURI = false;
+                       $countLocations = count($locations);
+
+                       for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
+                               $url = parse_url( $locations[ $i ] );
+
+                               if ( isset($url[ 'host' ]) ) {
+                                       $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
+                                       break;  //found correct URI (with host)
+                               } else {
+                                       $foundRelativeURI = true;
+                               }
+                       }
+
+                       if ( $foundRelativeURI ) {
+                               if ( $domain ) {
+                                       return $domain . $locations[ $countLocations - 1 ];
+                               } else {
+                                       $url = parse_url( $this->url );
+                                       if ( isset($url[ 'host' ]) ) {
+                                               return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
+                                       }
+                               }
+                       } else {
+                               return $locations[ $countLocations - 1 ];
+                       }
                }
 
                return $this->url;
@@ -554,6 +637,7 @@ class MWHttpRequest {
        /**
         * Returns true if the backend can follow redirects. Overridden by the
         * child classes.
+        * @return bool
         */
        public function canFollowRedirects() {
                return true;
@@ -565,7 +649,7 @@ class MWHttpRequest {
  */
 class CurlHttpRequest extends MWHttpRequest {
        const SUPPORTS_FILE_POSTS = true;
-       
+
        static $curlMessageMap = array(
                6 => 'http-host-unreachable',
                28 => 'http-timed-out'
@@ -574,6 +658,11 @@ class CurlHttpRequest extends MWHttpRequest {
        protected $curlOptions = array();
        protected $headerText = "";
 
+       /**
+        * @param $fh
+        * @param $content
+        * @return int
+        */
        protected function readHeader( $fh, $content ) {
                $this->headerText .= $content;
                return strlen( $content );
@@ -665,6 +754,9 @@ class CurlHttpRequest extends MWHttpRequest {
                return $this->status;
        }
 
+       /**
+        * @return bool
+        */
        public function canFollowRedirects() {
                if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
                        wfDebug( "Cannot follow redirects in safe mode\n" );
@@ -681,6 +773,11 @@ class CurlHttpRequest extends MWHttpRequest {
 }
 
 class PhpHttpRequest extends MWHttpRequest {
+
+       /**
+        * @param $url string
+        * @return string
+        */
        protected function urlToTcp( $url ) {
                $parsedUrl = parse_url( $url );
 
@@ -692,13 +789,10 @@ class PhpHttpRequest extends MWHttpRequest {
 
                if ( is_array( $this->postData ) ) {
                        $this->postData = wfArrayToCGI( $this->postData );
-               }               
-
-               // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
-               // causes a segfault
-               $manuallyRedirect = version_compare( phpversion(), '5.1.7', '<' );
+               }
 
-               if ( $this->parsedUrl['scheme'] != 'http' ) {
+               if ( $this->parsedUrl['scheme'] != 'http' &&
+                        $this->parsedUrl['scheme'] != 'https' ) {
                        $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
                }
 
@@ -710,12 +804,12 @@ class PhpHttpRequest extends MWHttpRequest {
                }
 
                $options = array();
-               if ( $this->proxy && !$this->noProxy ) {
+               if ( $this->proxy ) {
                        $options['proxy'] = $this->urlToTCP( $this->proxy );
                        $options['request_fulluri'] = true;
                }
 
-               if ( !$this->followRedirects || $manuallyRedirect ) {
+               if ( !$this->followRedirects ) {
                        $options['max_redirects'] = 0;
                } else {
                        $options['max_redirects'] = $this->maxRedirects;
@@ -736,12 +830,7 @@ class PhpHttpRequest extends MWHttpRequest {
                        $options['content'] = $this->postData;
                }
 
-               $oldTimeout = false;
-               if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
-                       $oldTimeout = ini_set( 'default_socket_timeout', $this->timeout );
-               } else {
-                       $options['timeout'] = $this->timeout;
-               }
+               $options['timeout'] = $this->timeout;
 
                $context = stream_context_create( array( 'http' => $options ) );
 
@@ -765,7 +854,7 @@ class PhpHttpRequest extends MWHttpRequest {
                        $this->headerList = $result['wrapper_data'];
                        $this->parseHeader();
 
-                       if ( !$manuallyRedirect || !$this->followRedirects ) {
+                       if ( !$this->followRedirects ) {
                                break;
                        }
 
@@ -776,16 +865,12 @@ class PhpHttpRequest extends MWHttpRequest {
                        # Check security of URL
                        $url = $this->getResponseHeader( "Location" );
 
-                       if ( substr( $url, 0, 7 ) !== 'http://' ) {
+                       if ( !Http::isValidURI( $url ) ) {
                                wfDebug( __METHOD__ . ": insecure redirection\n" );
                                break;
                        }
                } while ( true );
 
-               if ( $oldTimeout !== false ) {
-                       ini_set( 'default_socket_timeout', $oldTimeout );
-               }
-
                $this->setStatus();
 
                if ( $fh === false ) {
@@ -798,7 +883,10 @@ class PhpHttpRequest extends MWHttpRequest {
                        return $this->status;
                }
 
-               if ( $this->status->isOK() ) {
+               // If everything went OK, or we recieved some error code
+               // get the response body content.
+               if ( $this->status->isOK()
+                               || (int)$this->respStatus >= 300) {
                        while ( !feof( $fh ) ) {
                                $buf = fread( $fh, 8192 );