7 * Various HTTP related functions
11 static $httpEngine = false;
14 * Perform an HTTP request
15 * @param $method string HTTP method. Usually GET/POST
16 * @param $url string Full URL to act on
17 * @param $options options to pass to HttpRequest object
18 * Possible keys for the array:
19 * timeout Timeout length in seconds
20 * postData An array of key-value pairs or a url-encoded form data
21 * proxy The proxy to use. Will use $wgHTTPProxy (if set) otherwise.
22 * noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
23 * sslVerifyHost (curl only) Verify the SSL certificate
24 * caInfo (curl only) Provide CA information
25 * maxRedirects Maximum number of redirects to follow (defaults to 5)
26 * followRedirects Whether to follow redirects (defaults to true)
27 * @returns mixed (bool)false on failure or a string on success
29 public static function request( $method, $url, $options = array() ) {
30 $url = wfExpandUrl( $url );
31 wfDebug( "HTTP: $method: $url" );
32 $options['method'] = strtoupper( $method );
33 if ( !isset( $options['timeout'] ) ) {
34 $options['timeout'] = 'default';
36 $req = HttpRequest
::factory( $url, $options );
37 $status = $req->execute();
38 if ( $status->isOK() ) {
39 return $req->getContent();
46 * Simple wrapper for Http::request( 'GET' )
47 * @see Http::request()
49 public static function get( $url, $timeout = 'default', $options = array() ) {
50 $options['timeout'] = $timeout;
51 return Http
::request( 'GET', $url, $options );
55 * Simple wrapper for Http::request( 'POST' )
56 * @see Http::request()
58 public static function post( $url, $options = array() ) {
59 return Http
::request( 'POST', $url, $options );
63 * Check if the URL can be served by localhost
64 * @param $url string Full url to check
67 public static function isLocalURL( $url ) {
68 global $wgCommandLineMode, $wgConf;
69 if ( $wgCommandLineMode ) {
75 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
78 $domainParts = explode( '.', $host );
79 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
80 $domainParts = array_reverse( $domainParts );
81 for ( $i = 0; $i < count( $domainParts ); $i++
) {
82 $domainPart = $domainParts[$i];
84 $domain = $domainPart;
86 $domain = $domainPart . '.' . $domain;
88 if ( $wgConf->isLocalVHost( $domain ) ) {
97 * A standard user-agent we can use for external requests.
100 public static function userAgent() {
102 return "MediaWiki/$wgVersion";
106 * Checks that the given URI is a valid one
107 * @param $uri Mixed: URI to check for validity
110 public static function isValidURI( $uri ) {
112 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
120 * This wrapper class will call out to curl (if available) or fallback
121 * to regular PHP if necessary for handling internal HTTP requests.
125 protected $timeout = 'default';
126 protected $headersOnly = null;
127 protected $postData = null;
128 protected $proxy = null;
129 protected $noProxy = false;
130 protected $sslVerifyHost = true;
131 protected $caInfo = null;
132 protected $method = "GET";
133 protected $reqHeaders = array();
135 protected $parsedUrl;
137 protected $maxRedirects = 5;
138 protected $followRedirects = true;
140 protected $cookieJar;
142 protected $headerList = array();
143 protected $respVersion = "0.9";
144 protected $respStatus = "200 Ok";
145 protected $respHeaders = array();
150 * @param $url string url to use
151 * @param $options array (optional) extra params to pass (see Http::request())
153 function __construct( $url, $options = array() ) {
154 global $wgHTTPTimeout;
157 $this->parsedUrl
= parse_url( $url );
159 if ( !Http
::isValidURI( $this->url
) ) {
160 $this->status
= Status
::newFatal('http-invalid-url');
162 $this->status
= Status
::newGood( 100 ); // continue
165 if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
166 $this->timeout
= $options['timeout'];
168 $this->timeout
= $wgHTTPTimeout;
171 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
172 "method", "followRedirects", "maxRedirects" );
173 foreach ( $members as $o ) {
174 if ( isset($options[$o]) ) {
175 $this->$o = $options[$o];
181 * Generate a new request object
182 * @see HttpRequest::__construct
184 public static function factory( $url, $options = null ) {
185 if ( !Http
::$httpEngine ) {
186 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
187 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
188 throw new MWException( __METHOD__
.': curl (http://php.net/curl) is not installed, but'.
189 ' Http::$httpEngine is set to "curl"' );
192 switch( Http
::$httpEngine ) {
194 return new CurlHttpRequest( $url, $options );
196 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
197 throw new MWException( __METHOD__
.': allow_url_fopen needs to be enabled for pure PHP'.
198 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
200 return new PhpHttpRequest( $url, $options );
202 throw new MWException( __METHOD__
.': The setting of Http::$httpEngine is not valid.' );
207 * Get the body, or content, of the response to the request
210 public function getContent() {
211 return $this->content
;
215 * Set the parameters of the request
216 * @param $params array
217 * @todo overload the args param
219 public function setData($args) {
220 $this->postData
= $args;
224 * Take care of setting up the proxy
225 * (override in subclass)
228 public function proxySetup() {
231 if ( $this->proxy
) {
234 if ( Http
::isLocalURL( $this->url
) ) {
235 $this->proxy
= 'http://localhost:80/';
236 } elseif ( $wgHTTPProxy ) {
237 $this->proxy
= $wgHTTPProxy ;
238 } elseif ( getenv( "http_proxy" ) ) {
239 $this->proxy
= getenv( "http_proxy" );
244 * Set the refererer header
246 public function setReferer( $url ) {
247 $this->setHeader('Referer', $url);
253 public function setUserAgent( $UA ) {
254 $this->setHeader('User-Agent', $UA);
258 * Set an arbitrary header
260 public function setHeader($name, $value) {
261 // I feel like I should normalize the case here...
262 $this->reqHeaders
[$name] = $value;
266 * Get an array of the headers
268 public function getHeaderList() {
271 if( $this->cookieJar
) {
272 $this->reqHeaders
['Cookie'] =
273 $this->cookieJar
->serializeToHttpRequest($this->parsedUrl
['path'],
274 $this->parsedUrl
['host']);
276 foreach($this->reqHeaders
as $name => $value) {
277 $list[] = "$name: $value";
284 * @param $callback callback
286 public function setCallback( $callback ) {
287 $this->callback
= $callback;
291 * A generic callback to read the body of the response from a remote
294 * @param $content string
296 public function read( $fh, $content ) {
297 $this->content
.= $content;
298 return strlen( $content );
302 * Take care of whatever is necessary to perform the URI request.
305 public function execute() {
310 if( strtoupper($this->method
) == "HEAD" ) {
311 $this->headersOnly
= true;
314 if ( is_array( $this->postData
) ) {
315 $this->postData
= wfArrayToCGI( $this->postData
);
318 if ( is_object( $wgTitle ) && !isset($this->reqHeaders
['Referer']) ) {
319 $this->setReferer( $wgTitle->getFullURL() );
322 if ( !$this->noProxy
) {
326 if ( !$this->callback
) {
327 $this->setCallback( array( $this, 'read' ) );
330 if ( !isset($this->reqHeaders
['User-Agent']) ) {
331 $this->setUserAgent(Http
::userAgent());
336 * Parses the headers, including the HTTP status code and any
337 * Set-Cookie headers. This function expectes the headers to be
338 * found in an array in the member variable headerList.
341 protected function parseHeader() {
343 foreach( $this->headerList
as $header ) {
344 if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
345 $this->respVersion
= $match[1];
346 $this->respStatus
= $match[2];
347 } elseif( preg_match( "#^[ \t]#", $header ) ) {
348 $last = count($this->respHeaders
[$lastname]) - 1;
349 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
350 } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
351 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
352 $lastname = strtolower( $match[1] );
356 $this->parseCookies();
360 * Sets the member variable status to a fatal status if the HTTP
361 * status code was not 200.
364 protected function setStatus() {
365 if( !$this->respHeaders
) {
366 $this->parseHeader();
369 if((int)$this->respStatus
!== 200) {
370 list( $code, $message ) = explode(" ", $this->respStatus
, 2);
371 $this->status
->fatal("http-bad-status", $code, $message );
377 * Returns true if the last status code was a redirect.
380 public function isRedirect() {
381 if( !$this->respHeaders
) {
382 $this->parseHeader();
385 $status = (int)$this->respStatus
;
386 if ( $status >= 300 && $status < 400 ) {
393 * Returns an associative array of response headers after the
394 * request has been executed. Because some headers
395 * (e.g. Set-Cookie) can appear more than once the, each value of
396 * the associative array is an array of the values given.
399 public function getResponseHeaders() {
400 if( !$this->respHeaders
) {
401 $this->parseHeader();
403 return $this->respHeaders
;
407 * Returns the value of the given response header.
408 * @param $header string
411 public function getResponseHeader($header) {
412 if( !$this->respHeaders
) {
413 $this->parseHeader();
415 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
416 $v = $this->respHeaders
[strtolower ( $header ) ];
417 return $v[count( $v ) - 1];
423 * Tells the HttpRequest object to use this pre-loaded CookieJar.
424 * @param $jar CookieJar
426 public function setCookieJar( $jar ) {
427 $this->cookieJar
= $jar;
431 * Returns the cookie jar in use.
434 public function getCookieJar() {
435 if( !$this->respHeaders
) {
436 $this->parseHeader();
438 return $this->cookieJar
;
442 * Sets a cookie. Used before a request to set up any individual
443 * cookies. Used internally after a request to parse the
444 * Set-Cookie headers.
447 public function setCookie( $name, $value = null, $attr = null) {
448 if( !$this->cookieJar
) {
449 $this->cookieJar
= new CookieJar
;
451 $this->cookieJar
->setCookie($name, $value, $attr);
455 * Parse the cookies in the response headers and store them in the cookie jar.
457 protected function parseCookies() {
458 if( !$this->cookieJar
) {
459 $this->cookieJar
= new CookieJar
;
461 if( isset( $this->respHeaders
['set-cookie'] ) ) {
462 $url = parse_url( $this->getFinalUrl() );
463 foreach( $this->respHeaders
['set-cookie'] as $cookie ) {
464 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
470 * Returns the final URL after all redirections.
473 public function getFinalUrl() {
474 $location = $this->getResponseHeader("Location");
490 protected $isSessionKey = true;
491 // TO IMPLEMENT protected $secure
492 // TO IMPLEMENT? protected $maxAge (add onto expires)
493 // TO IMPLEMENT? protected $version
494 // TO IMPLEMENT? protected $comment
496 function __construct( $name, $value, $attr ) {
498 $this->set( $value, $attr );
502 * Sets a cookie. Used before a request to set up any individual
503 * cookies. Used internally after a request to parse the
504 * Set-Cookie headers.
505 * @param $name string the name of the cookie
506 * @param $value string the value of the cookie
507 * @param $attr array possible key/values:
508 * expires A date string
509 * path The path this cookie is used on
510 * domain Domain this cookie is used on
512 public function set( $value, $attr ) {
513 $this->value
= $value;
514 if( isset( $attr['expires'] ) ) {
515 $this->isSessionKey
= false;
516 $this->expires
= strtotime( $attr['expires'] );
518 if( isset( $attr['path'] ) ) {
519 $this->path
= $attr['path'];
523 if( isset( $attr['domain'] ) ) {
524 if( self
::validateCookieDomain( $attr['domain'] ) ) {
525 $this->domain
= $attr['domain'];
528 throw new MWException("You must specify a domain.");
533 * Return the true if the cookie is valid is valid. Otherwise,
534 * false. The uses a method similar to IE cookie security
536 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
537 * A better method might be to use a blacklist like
538 * http://publicsuffix.org/
540 * @param $domain string the domain to validate
541 * @param $originDomain string (optional) the domain the cookie originates from
544 public static function validateCookieDomain( $domain, $originDomain = null) {
545 // Don't allow a trailing dot
546 if( substr( $domain, -1 ) == "." ) return false;
548 $dc = explode(".", $domain);
550 // Don't allow cookies for "localhost", "ls" or other dot-less hosts
551 if( count($dc) < 2 ) return false;
553 // Only allow full, valid IP addresses
554 if( preg_match( '/^[0-9.]+$/', $domain ) ) {
555 if( count( $dc ) != 4 ) return false;
557 if( ip2long( $domain ) === false ) return false;
559 if( $originDomain == null ||
$originDomain == $domain ) return true;
563 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
564 if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
565 if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
566 ||
(count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
569 if( (count($dc) == 2 ||
(count($dc) == 3 && $dc[0] == "") )
570 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
575 if( $originDomain != null ) {
576 if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
579 if( substr( $domain, 0, 1 ) == "."
580 && substr_compare( $originDomain, $domain, -strlen( $domain ),
581 strlen( $domain ), TRUE ) != 0 ) {
590 * Serialize the cookie jar into a format useful for HTTP Request headers.
591 * @param $path string the path that will be used. Required.
592 * @param $domain string the domain that will be used. Required.
595 public function serializeToHttpRequest( $path, $domain ) {
598 if( $this->canServeDomain( $domain )
599 && $this->canServePath( $path )
600 && $this->isUnExpired() ) {
601 $ret = $this->name
."=". $this->value
;
607 protected function canServeDomain( $domain ) {
608 if( $domain == $this->domain
609 ||
( strlen( $domain) > strlen( $this->domain
)
610 && substr( $this->domain
, 0, 1) == "."
611 && substr_compare( $domain, $this->domain
, -strlen( $this->domain
),
612 strlen( $this->domain
), TRUE ) == 0 ) ) {
618 protected function canServePath( $path ) {
619 if( $this->path
&& substr_compare( $this->path
, $path, 0, strlen( $this->path
) ) == 0 ) {
625 protected function isUnExpired() {
626 if( $this->isSessionKey ||
$this->expires
> time() ) {
635 private $cookie = array();
638 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
641 public function setCookie ($name, $value, $attr) {
642 /* cookies: case insensitive, so this should work.
643 * We'll still send the cookies back in the same case we got them, though.
645 $index = strtoupper($name);
646 if( isset( $this->cookie
[$index] ) ) {
647 $this->cookie
[$index]->set( $value, $attr );
649 $this->cookie
[$index] = new Cookie( $name, $value, $attr );
654 * @see Cookie::serializeToHttpRequest
656 public function serializeToHttpRequest( $path, $domain ) {
659 foreach( $this->cookie
as $c ) {
660 $serialized = $c->serializeToHttpRequest( $path, $domain );
661 if ( $serialized ) $cookies[] = $serialized;
664 return implode("; ", $cookies);
668 * Parse the content of an Set-Cookie HTTP Response header.
669 * @param $cookie string
671 public function parseCookieResponseHeader ( $cookie, $domain ) {
672 $len = strlen( "Set-Cookie:" );
673 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
674 $cookie = substr( $cookie, $len );
677 $bit = array_map( 'trim', explode( ";", $cookie ) );
678 if ( count($bit) >= 1 ) {
679 list($name, $value) = explode( "=", array_shift( $bit ), 2 );
681 foreach( $bit as $piece ) {
682 $parts = explode( "=", $piece );
683 if( count( $parts ) > 1 ) {
684 $attr[strtolower( $parts[0] )] = $parts[1];
686 $attr[strtolower( $parts[0] )] = true;
690 if( !isset( $attr['domain'] ) ) {
691 $attr['domain'] = $domain;
692 } elseif ( !Cookie
::validateCookieDomain( $attr['domain'], $domain ) ) {
696 $this->setCookie( $name, $value, $attr );
703 * HttpRequest implemented using internal curl compiled into PHP
705 class CurlHttpRequest
extends HttpRequest
{
706 static $curlMessageMap = array(
707 6 => 'http-host-unreachable',
708 28 => 'http-timed-out'
711 protected $curlOptions = array();
712 protected $headerText = "";
714 protected function readHeader( $fh, $content ) {
715 $this->headerText
.= $content;
716 return strlen( $content );
719 public function execute() {
721 if ( !$this->status
->isOK() ) {
722 return $this->status
;
724 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
725 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
726 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
727 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
728 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array($this, "readHeader");
729 $this->curlOptions
[CURLOPT_FOLLOWLOCATION
] = $this->followRedirects
;
730 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
732 /* not sure these two are actually necessary */
733 if(isset($this->reqHeaders
['Referer'])) {
734 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
736 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
738 if ( isset( $this->sslVerifyHost
) ) {
739 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
742 if ( $this->caInfo
) {
743 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
746 if ( $this->headersOnly
) {
747 $this->curlOptions
[CURLOPT_NOBODY
] = true;
748 $this->curlOptions
[CURLOPT_HEADER
] = true;
749 } elseif ( $this->method
== 'POST' ) {
750 $this->curlOptions
[CURLOPT_POST
] = true;
751 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
752 // Suppress 'Expect: 100-continue' header, as some servers
753 // will reject it with a 417 and Curl won't auto retry
754 // with HTTP 1.0 fallback
755 $this->reqHeaders
['Expect'] = '';
757 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
760 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
762 $curlHandle = curl_init( $this->url
);
763 curl_setopt_array( $curlHandle, $this->curlOptions
);
765 if ( false === curl_exec( $curlHandle ) ) {
766 $code = curl_error( $curlHandle );
768 if ( isset( self
::$curlMessageMap[$code] ) ) {
769 $this->status
->fatal( self
::$curlMessageMap[$code] );
771 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
774 $this->headerList
= explode("\r\n", $this->headerText
);
777 curl_close( $curlHandle );
779 $this->parseHeader();
781 return $this->status
;
785 class PhpHttpRequest
extends HttpRequest
{
786 protected $manuallyRedirect = false;
788 protected function urlToTcp( $url ) {
789 $parsedUrl = parse_url( $url );
791 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
794 public function execute() {
797 // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
799 if ( version_compare( '5.1.7', phpversion(), '>' ) ) {
800 $this->manuallyRedirect
= true;
803 if ( $this->parsedUrl
['scheme'] != 'http' ) {
804 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
807 $this->reqHeaders
['Accept'] = "*/*";
808 if ( $this->method
== 'POST' ) {
809 // Required for HTTP 1.0 POSTs
810 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
811 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
815 if ( $this->proxy
&& !$this->noProxy
) {
816 $options['proxy'] = $this->urlToTCP( $this->proxy
);
817 $options['request_fulluri'] = true;
820 if ( !$this->followRedirects ||
$this->manuallyRedirect
) {
821 $options['max_redirects'] = 0;
823 $options['max_redirects'] = $this->maxRedirects
;
826 $options['method'] = $this->method
;
827 $options['header'] = implode("\r\n", $this->getHeaderList());
828 // Note that at some future point we may want to support
829 // HTTP/1.1, but we'd have to write support for chunking
830 // in version of PHP < 5.3.1
831 $options['protocol_version'] = "1.0";
833 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
834 // Only works on 5.2.10+
835 $options['ignore_errors'] = true;
837 if ( $this->postData
) {
838 $options['content'] = $this->postData
;
842 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
843 $oldTimeout = ini_set('default_socket_timeout', $this->timeout
);
845 $options['timeout'] = $this->timeout
;
848 $context = stream_context_create( array( 'http' => $options ) );
850 $this->headerList
= array();
856 wfSuppressWarnings();
857 $fh = fopen( $url, "r", false, $context );
860 $result = stream_get_meta_data( $fh );
861 $this->headerList
= $result['wrapper_data'];
862 $this->parseHeader();
863 $url = $this->getResponseHeader("Location");
864 $again = $this->manuallyRedirect
&& $this->followRedirects
&& $url
865 && $this->isRedirect() && $this->maxRedirects
> $reqCount;
869 if ( $oldTimeout !== false ) {
870 ini_set('default_socket_timeout', $oldTimeout);
874 if ( $fh === false ) {
875 $this->status
->fatal( 'http-request-error' );
876 return $this->status
;
879 if ( $result['timed_out'] ) {
880 $this->status
->fatal( 'http-timed-out', $this->url
);
881 return $this->status
;
884 if($this->status
->isOK()) {
885 while ( !feof( $fh ) ) {
886 $buf = fread( $fh, 8192 );
887 if ( $buf === false ) {
888 $this->status
->fatal( 'http-read-error' );
891 if ( strlen( $buf ) ) {
892 call_user_func( $this->callback
, $fh, $buf );
898 return $this->status
;