Rewrite ajaxwatch.js to use the API watch action, and JQuery. Allows it to be used...
[lhc/web/wiklou.git] / includes / HttpFunctions.php
index 9012c96..b9b1cf9 100644 (file)
@@ -15,18 +15,21 @@ class Http {
         * @param $method string HTTP method. Usually GET/POST
         * @param $url string Full URL to act on
         * @param $options options to pass to HttpRequest 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.
-        *                                      sslVerifyHost     (curl only) Verify the SSL certificate
-        *                                      caInfo                    (curl only) Provide CA information
-        *                                      maxRedirects      Maximum number of redirects to follow (defaults to 5)
-        *                                      followRedirects   Whether to follow redirects (defaults to true)
+        *      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.
+        *              sslVerifyHost   (curl only)     Verify hostname against certificate
+        *              sslVerifyCert   (curl only)     Verify SSL certificate
+        *              caInfo          (curl only)     Provide CA information
+        *              maxRedirects                    Maximum number of redirects to follow (defaults to 5)
+        *              followRedirects   Whether to follow redirects (defaults to true)
         * @returns 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" );
                $options['method'] = strtoupper( $method );
                if ( !isset( $options['timeout'] ) ) {
@@ -127,6 +130,7 @@ class HttpRequest {
        protected $proxy = null;
        protected $noProxy = false;
        protected $sslVerifyHost = true;
+       protected $sslVerifyCert = true;
        protected $caInfo = null;
        protected $method = "GET";
        protected $reqHeaders = array();
@@ -156,7 +160,7 @@ class HttpRequest {
                $this->parsedUrl = parse_url( $url );
 
                if ( !Http::isValidURI( $this->url ) ) {
-                       $this->status = Status::newFromFatal('http-invalid-url');
+                       $this->status = Status::newFatal('http-invalid-url');
                } else {
                        $this->status = Status::newGood( 100 ); // continue
                }
@@ -168,7 +172,7 @@ class HttpRequest {
                }
 
                $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
-                                                 "method", "followRedirects", "maxRedirects" );
+                                 "method", "followRedirects", "maxRedirects", "sslVerifyCert" );
                foreach ( $members as $o ) {
                        if ( isset($options[$o]) ) {
                                $this->$o = $options[$o];
@@ -210,6 +214,15 @@ class HttpRequest {
                return $this->content;
        }
 
+       /**
+        * Set the parameters of the request
+        * @param $params array
+        * @todo overload the args param
+        */
+       public function setData($args) {
+               $this->postData = $args;
+       }
+
        /**
         * Take care of setting up the proxy
         * (override in subclass)
@@ -225,6 +238,8 @@ class HttpRequest {
                        $this->proxy = 'http://localhost:80/';
                } elseif ( $wgHTTPProxy ) {
                        $this->proxy = $wgHTTPProxy ;
+               } elseif ( getenv( "http_proxy" ) ) {
+                       $this->proxy = getenv( "http_proxy" );
                }
        }
 
@@ -293,6 +308,8 @@ class HttpRequest {
        public function execute() {
                global $wgTitle;
 
+               $this->content = "";
+
                if( strtoupper($this->method) == "HEAD" ) {
                        $this->headersOnly = true;
                }
@@ -318,6 +335,12 @@ class HttpRequest {
                }
        }
 
+       /**
+        * 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.
+        * @returns nothing
+        */
        protected function parseHeader() {
                $lastname = "";
                foreach( $this->headerList as $header ) {
@@ -333,10 +356,40 @@ class HttpRequest {
                        }
                }
 
+               $this->parseCookies();
+       }
+
+       /**
+        * Sets the member variable status to a fatal status if the HTTP
+        * status code was not 200.
+        * @returns nothing
+        */
+       protected function setStatus() {
+               if( !$this->respHeaders ) {
+                       $this->parseHeader();
+               }
+
                if((int)$this->respStatus !== 200) {
-                       $this->status->fatal("http-bad-status", explode(" ", $this->respStatus, 2));
+                       list( $code, $message ) = explode(" ", $this->respStatus, 2);
+                       $this->status->fatal("http-bad-status", $code, $message );
                }
-               $this->parseCookies();
+       }
+
+
+       /**
+        * Returns true if the last status code was a redirect.
+        * @return bool
+        */
+       public function isRedirect() {
+               if( !$this->respHeaders ) {
+                       $this->parseHeader();
+               }
+
+               $status = (int)$this->respStatus;
+               if ( $status >= 300 && $status < 400 ) {
+                       return true;
+               }
+               return false;
        }
 
        /**
@@ -353,6 +406,22 @@ class HttpRequest {
                return $this->respHeaders;
        }
 
+       /**
+        * Returns the value of the given response header.
+        * @param $header string
+        * @return string
+        */
+       public function getResponseHeader($header) {
+               if( !$this->respHeaders ) {
+                       $this->parseHeader();
+               }
+               if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
+                       $v = $this->respHeaders[strtolower ( $header ) ];
+                       return $v[count( $v ) - 1];
+               }
+               return null;
+       }
+
        /**
         * Tells the HttpRequest object to use this pre-loaded CookieJar.
         * @param $jar CookieJar
@@ -405,13 +474,12 @@ class HttpRequest {
         * @returns string
         */
        public function getFinalUrl() {
-               $finalUrl = $this->url;
-               if ( isset( $this->respHeaders['location'] ) ) {
-                       $redir = $this->respHeaders['location'];
-                       $finalUrl = $redir[count($redir) - 1];
+               $location = $this->getResponseHeader("Location");
+               if ( $location ) {
+                       return $location;
                }
 
-               return $finalUrl;
+               return $this->url;
        }
 }
 
@@ -541,7 +609,8 @@ class Cookie {
 
        protected function canServeDomain( $domain ) {
                if( $domain == $this->domain
-                       || ( substr( $this->domain, 0, 1) == "."
+                       || ( strlen( $domain) > strlen( $this->domain )
+                                && substr( $this->domain, 0, 1) == "."
                                 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
                                                                        strlen( $this->domain ), TRUE ) == 0 ) ) {
                        return true;
@@ -669,9 +738,13 @@ class CurlHttpRequest extends HttpRequest {
                }
                $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
 
-               if ( $this->sslVerifyHost ) {
+               if ( isset( $this->sslVerifyHost ) ) {
                        $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
                }
+               
+               if ( isset( $this->sslVerifyCert ) ) {
+                       $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
+               }
 
                if ( $this->caInfo ) {
                        $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
@@ -711,11 +784,14 @@ class CurlHttpRequest extends HttpRequest {
                curl_close( $curlHandle );
 
                $this->parseHeader();
+               $this->setStatus();
                return $this->status;
        }
 }
 
 class PhpHttpRequest extends HttpRequest {
+       protected $manuallyRedirect = false;
+
        protected function urlToTcp( $url ) {
                $parsedUrl = parse_url( $url );
 
@@ -723,13 +799,16 @@ class PhpHttpRequest extends HttpRequest {
        }
 
        public function execute() {
-               if ( $this->parsedUrl['scheme'] != 'http' ) {
-                       $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
+               parent::execute();
+
+               // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
+               // causes a segfault
+               if ( version_compare( '5.1.7', phpversion(), '>' ) ) {
+                       $this->manuallyRedirect = true;
                }
 
-               parent::execute();
-               if ( !$this->status->isOK() ) {
-                       return $this->status;
+               if ( $this->parsedUrl['scheme'] != 'http' ) {
+                       $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
                }
 
                $this->reqHeaders['Accept'] = "*/*";
@@ -745,20 +824,23 @@ class PhpHttpRequest extends HttpRequest {
                        $options['request_fulluri'] = true;
                }
 
-               if ( !$this->followRedirects ) {
+               if ( !$this->followRedirects || $this->manuallyRedirect ) {
                        $options['max_redirects'] = 0;
                } else {
                        $options['max_redirects'] = $this->maxRedirects;
                }
 
                $options['method'] = $this->method;
-               $options['timeout'] = $this->timeout;
                $options['header'] = implode("\r\n", $this->getHeaderList());
                // Note that at some future point we may want to support
                // HTTP/1.1, but we'd have to write support for chunking
                // in version of PHP < 5.3.1
                $options['protocol_version'] = "1.0";
 
+               // This is how we tell PHP we want to deal with 404s (for example) ourselves.
+               // Only works on 5.2.10+
+               $options['ignore_errors'] = true;
+
                if ( $this->postData ) {
                        $options['content'] = $this->postData;
                }
@@ -766,40 +848,60 @@ class PhpHttpRequest extends HttpRequest {
                $oldTimeout = false;
                if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
                        $oldTimeout = ini_set('default_socket_timeout', $this->timeout);
+               } else {
+                       $options['timeout'] = $this->timeout;
                }
 
                $context = stream_context_create( array( 'http' => $options ) );
-               wfSuppressWarnings();
-               $fh = fopen( $this->url, "r", false, $context );
-               wfRestoreWarnings();
+
+               $this->headerList = array();
+               $reqCount = 0;
+               $url = $this->url;
+               do {
+                       $again = false;
+                       $reqCount++;
+                       wfSuppressWarnings();
+                       $fh = fopen( $url, "r", false, $context );
+                       wfRestoreWarnings();
+                       if ( $fh ) {
+                               $result = stream_get_meta_data( $fh );
+                               $this->headerList = $result['wrapper_data'];
+                               $this->parseHeader();
+                               $url = $this->getResponseHeader("Location");
+                               $again = $this->manuallyRedirect && $this->followRedirects && $url
+                                       && $this->isRedirect() && $this->maxRedirects > $reqCount;
+                       }
+               } while ( $again );
+
                if ( $oldTimeout !== false ) {
                        ini_set('default_socket_timeout', $oldTimeout);
                }
+               $this->setStatus();
+
                if ( $fh === false ) {
                        $this->status->fatal( 'http-request-error' );
                        return $this->status;
                }
 
-               $result = stream_get_meta_data( $fh );
                if ( $result['timed_out'] ) {
                        $this->status->fatal( 'http-timed-out', $this->url );
                        return $this->status;
                }
-               $this->headerList = $result['wrapper_data'];
 
-               while ( !feof( $fh ) ) {
-                       $buf = fread( $fh, 8192 );
-                       if ( $buf === false ) {
-                               $this->status->fatal( 'http-read-error' );
-                               break;
-                       }
-                       if ( strlen( $buf ) ) {
-                               call_user_func( $this->callback, $fh, $buf );
+               if($this->status->isOK()) {
+                       while ( !feof( $fh ) ) {
+                               $buf = fread( $fh, 8192 );
+                               if ( $buf === false ) {
+                                       $this->status->fatal( 'http-read-error' );
+                                       break;
+                               }
+                               if ( strlen( $buf ) ) {
+                                       call_user_func( $this->callback, $fh, $buf );
+                               }
                        }
                }
                fclose( $fh );
 
-               $this->parseHeader();
                return $this->status;
        }
 }