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 wfDebug( "HTTP: $method: $url" );
31 $options['method'] = strtoupper( $method );
32 if ( !isset( $options['timeout'] ) ) {
33 $options['timeout'] = 'default';
35 $req = HttpRequest
::factory( $url, $options );
36 $status = $req->execute();
37 if ( $status->isOK() ) {
38 return $req->getContent();
45 * Simple wrapper for Http::request( 'GET' )
46 * @see Http::request()
48 public static function get( $url, $timeout = 'default', $options = array() ) {
49 $options['timeout'] = $timeout;
50 return Http
::request( 'GET', $url, $options );
54 * Simple wrapper for Http::request( 'POST' )
55 * @see Http::request()
57 public static function post( $url, $options = array() ) {
58 return Http
::request( 'POST', $url, $options );
62 * Check if the URL can be served by localhost
63 * @param $url string Full url to check
66 public static function isLocalURL( $url ) {
67 global $wgCommandLineMode, $wgConf;
68 if ( $wgCommandLineMode ) {
74 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
77 $domainParts = explode( '.', $host );
78 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
79 $domainParts = array_reverse( $domainParts );
80 for ( $i = 0; $i < count( $domainParts ); $i++
) {
81 $domainPart = $domainParts[$i];
83 $domain = $domainPart;
85 $domain = $domainPart . '.' . $domain;
87 if ( $wgConf->isLocalVHost( $domain ) ) {
96 * A standard user-agent we can use for external requests.
99 public static function userAgent() {
101 return "MediaWiki/$wgVersion";
105 * Checks that the given URI is a valid one
106 * @param $uri Mixed: URI to check for validity
109 public static function isValidURI( $uri ) {
111 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
119 * This wrapper class will call out to curl (if available) or fallback
120 * to regular PHP if necessary for handling internal HTTP requests.
124 protected $timeout = 'default';
125 protected $headersOnly = null;
126 protected $postData = null;
127 protected $proxy = null;
128 protected $noProxy = false;
129 protected $sslVerifyHost = true;
130 protected $caInfo = null;
131 protected $method = "GET";
132 protected $reqHeaders = array();
134 protected $parsedUrl;
136 protected $maxRedirects = 5;
137 protected $followRedirects = true;
139 protected $cookieJar;
141 protected $headerList = array();
142 protected $respVersion = "0.9";
143 protected $respStatus = "200 Ok";
144 protected $respHeaders = array();
149 * @param $url string url to use
150 * @param $options array (optional) extra params to pass (see Http::request())
152 function __construct( $url, $options = array() ) {
153 global $wgHTTPTimeout;
156 $this->parsedUrl
= parse_url( $url );
158 if ( !Http
::isValidURI( $this->url
) ) {
159 $this->status
= Status
::newFromFatal('http-invalid-url');
161 $this->status
= Status
::newGood( 100 ); // continue
164 if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
165 $this->timeout
= $options['timeout'];
167 $this->timeout
= $wgHTTPTimeout;
170 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
171 "method", "followRedirects", "maxRedirects" );
172 foreach ( $members as $o ) {
173 if ( isset($options[$o]) ) {
174 $this->$o = $options[$o];
180 * Generate a new request object
181 * @see HttpRequest::__construct
183 public static function factory( $url, $options = null ) {
184 if ( !Http
::$httpEngine ) {
185 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
186 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
187 throw new MWException( __METHOD__
.': curl (http://php.net/curl) is not installed, but'.
188 ' Http::$httpEngine is set to "curl"' );
191 switch( Http
::$httpEngine ) {
193 return new CurlHttpRequest( $url, $options );
195 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
196 throw new MWException( __METHOD__
.': allow_url_fopen needs to be enabled for pure PHP'.
197 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
199 return new PhpHttpRequest( $url, $options );
201 throw new MWException( __METHOD__
.': The setting of Http::$httpEngine is not valid.' );
206 * Get the body, or content, of the response to the request
209 public function getContent() {
210 return $this->content
;
214 * Take care of setting up the proxy
215 * (override in subclass)
218 public function proxySetup() {
221 if ( $this->proxy
) {
224 if ( Http
::isLocalURL( $this->url
) ) {
225 $this->proxy
= 'http://localhost:80/';
226 } elseif ( $wgHTTPProxy ) {
227 $this->proxy
= $wgHTTPProxy ;
232 * Set the refererer header
234 public function setReferer( $url ) {
235 $this->setHeader('Referer', $url);
241 public function setUserAgent( $UA ) {
242 $this->setHeader('User-Agent', $UA);
246 * Set an arbitrary header
248 public function setHeader($name, $value) {
249 // I feel like I should normalize the case here...
250 $this->reqHeaders
[$name] = $value;
254 * Get an array of the headers
256 public function getHeaderList() {
259 if( $this->cookieJar
) {
260 $this->reqHeaders
['Cookie'] =
261 $this->cookieJar
->serializeToHttpRequest($this->parsedUrl
['path'],
262 $this->parsedUrl
['host']);
264 foreach($this->reqHeaders
as $name => $value) {
265 $list[] = "$name: $value";
272 * @param $callback callback
274 public function setCallback( $callback ) {
275 $this->callback
= $callback;
279 * A generic callback to read the body of the response from a remote
282 * @param $content string
284 public function read( $fh, $content ) {
285 $this->content
.= $content;
286 return strlen( $content );
290 * Take care of whatever is necessary to perform the URI request.
293 public function execute() {
296 if( strtoupper($this->method
) == "HEAD" ) {
297 $this->headersOnly
= true;
300 if ( is_array( $this->postData
) ) {
301 $this->postData
= wfArrayToCGI( $this->postData
);
304 if ( is_object( $wgTitle ) && !isset($this->reqHeaders
['Referer']) ) {
305 $this->setReferer( $wgTitle->getFullURL() );
308 if ( !$this->noProxy
) {
312 if ( !$this->callback
) {
313 $this->setCallback( array( $this, 'read' ) );
316 if ( !isset($this->reqHeaders
['User-Agent']) ) {
317 $this->setUserAgent(Http
::userAgent());
321 protected function parseHeader() {
323 foreach( $this->headerList
as $header ) {
324 if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
325 $this->respVersion
= $match[1];
326 $this->respStatus
= $match[2];
327 } elseif( preg_match( "#^[ \t]#", $header ) ) {
328 $last = count($this->respHeaders
[$lastname]) - 1;
329 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
330 } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
331 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
332 $lastname = strtolower( $match[1] );
336 if((int)$this->respStatus
!== 200) {
337 list( $code, $message ) = explode(" ", $this->respStatus
, 2);
338 $this->status
->fatal("http-bad-status", $code, $message );
341 $this->parseCookies();
345 * Returns an associative array of response headers after the
346 * request has been executed. Because some headers
347 * (e.g. Set-Cookie) can appear more than once the, each value of
348 * the associative array is an array of the values given.
351 public function getResponseHeaders() {
352 if( !$this->respHeaders
) {
353 $this->parseHeader();
355 return $this->respHeaders
;
359 * Tells the HttpRequest object to use this pre-loaded CookieJar.
360 * @param $jar CookieJar
362 public function setCookieJar( $jar ) {
363 $this->cookieJar
= $jar;
367 * Returns the cookie jar in use.
370 public function getCookieJar() {
371 if( !$this->respHeaders
) {
372 $this->parseHeader();
374 return $this->cookieJar
;
378 * Sets a cookie. Used before a request to set up any individual
379 * cookies. Used internally after a request to parse the
380 * Set-Cookie headers.
383 public function setCookie( $name, $value = null, $attr = null) {
384 if( !$this->cookieJar
) {
385 $this->cookieJar
= new CookieJar
;
387 $this->cookieJar
->setCookie($name, $value, $attr);
391 * Parse the cookies in the response headers and store them in the cookie jar.
393 protected function parseCookies() {
394 if( !$this->cookieJar
) {
395 $this->cookieJar
= new CookieJar
;
397 if( isset( $this->respHeaders
['set-cookie'] ) ) {
398 $url = parse_url( $this->getFinalUrl() );
399 foreach( $this->respHeaders
['set-cookie'] as $cookie ) {
400 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
406 * Returns the final URL after all redirections.
409 public function getFinalUrl() {
410 $finalUrl = $this->url
;
411 if ( isset( $this->respHeaders
['location'] ) ) {
412 $redir = $this->respHeaders
['location'];
413 $finalUrl = $redir[count($redir) - 1];
427 protected $isSessionKey = true;
428 // TO IMPLEMENT protected $secure
429 // TO IMPLEMENT? protected $maxAge (add onto expires)
430 // TO IMPLEMENT? protected $version
431 // TO IMPLEMENT? protected $comment
433 function __construct( $name, $value, $attr ) {
435 $this->set( $value, $attr );
439 * Sets a cookie. Used before a request to set up any individual
440 * cookies. Used internally after a request to parse the
441 * Set-Cookie headers.
442 * @param $name string the name of the cookie
443 * @param $value string the value of the cookie
444 * @param $attr array possible key/values:
445 * expires A date string
446 * path The path this cookie is used on
447 * domain Domain this cookie is used on
449 public function set( $value, $attr ) {
450 $this->value
= $value;
451 if( isset( $attr['expires'] ) ) {
452 $this->isSessionKey
= false;
453 $this->expires
= strtotime( $attr['expires'] );
455 if( isset( $attr['path'] ) ) {
456 $this->path
= $attr['path'];
460 if( isset( $attr['domain'] ) ) {
461 if( self
::validateCookieDomain( $attr['domain'] ) ) {
462 $this->domain
= $attr['domain'];
465 throw new MWException("You must specify a domain.");
470 * Return the true if the cookie is valid is valid. Otherwise,
471 * false. The uses a method similar to IE cookie security
473 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
474 * A better method might be to use a blacklist like
475 * http://publicsuffix.org/
477 * @param $domain string the domain to validate
478 * @param $originDomain string (optional) the domain the cookie originates from
481 public static function validateCookieDomain( $domain, $originDomain = null) {
482 // Don't allow a trailing dot
483 if( substr( $domain, -1 ) == "." ) return false;
485 $dc = explode(".", $domain);
487 // Don't allow cookies for "localhost", "ls" or other dot-less hosts
488 if( count($dc) < 2 ) return false;
490 // Only allow full, valid IP addresses
491 if( preg_match( '/^[0-9.]+$/', $domain ) ) {
492 if( count( $dc ) != 4 ) return false;
494 if( ip2long( $domain ) === false ) return false;
496 if( $originDomain == null ||
$originDomain == $domain ) return true;
500 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
501 if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
502 if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
503 ||
(count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
506 if( (count($dc) == 2 ||
(count($dc) == 3 && $dc[0] == "") )
507 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
512 if( $originDomain != null ) {
513 if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
516 if( substr( $domain, 0, 1 ) == "."
517 && substr_compare( $originDomain, $domain, -strlen( $domain ),
518 strlen( $domain ), TRUE ) != 0 ) {
527 * Serialize the cookie jar into a format useful for HTTP Request headers.
528 * @param $path string the path that will be used. Required.
529 * @param $domain string the domain that will be used. Required.
532 public function serializeToHttpRequest( $path, $domain ) {
535 if( $this->canServeDomain( $domain )
536 && $this->canServePath( $path )
537 && $this->isUnExpired() ) {
538 $ret = $this->name
."=". $this->value
;
544 protected function canServeDomain( $domain ) {
545 if( $domain == $this->domain
546 ||
( substr( $this->domain
, 0, 1) == "."
547 && substr_compare( $domain, $this->domain
, -strlen( $this->domain
),
548 strlen( $this->domain
), TRUE ) == 0 ) ) {
554 protected function canServePath( $path ) {
555 if( $this->path
&& substr_compare( $this->path
, $path, 0, strlen( $this->path
) ) == 0 ) {
561 protected function isUnExpired() {
562 if( $this->isSessionKey ||
$this->expires
> time() ) {
571 private $cookie = array();
574 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
577 public function setCookie ($name, $value, $attr) {
578 /* cookies: case insensitive, so this should work.
579 * We'll still send the cookies back in the same case we got them, though.
581 $index = strtoupper($name);
582 if( isset( $this->cookie
[$index] ) ) {
583 $this->cookie
[$index]->set( $value, $attr );
585 $this->cookie
[$index] = new Cookie( $name, $value, $attr );
590 * @see Cookie::serializeToHttpRequest
592 public function serializeToHttpRequest( $path, $domain ) {
595 foreach( $this->cookie
as $c ) {
596 $serialized = $c->serializeToHttpRequest( $path, $domain );
597 if ( $serialized ) $cookies[] = $serialized;
600 return implode("; ", $cookies);
604 * Parse the content of an Set-Cookie HTTP Response header.
605 * @param $cookie string
607 public function parseCookieResponseHeader ( $cookie, $domain ) {
608 $len = strlen( "Set-Cookie:" );
609 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
610 $cookie = substr( $cookie, $len );
613 $bit = array_map( 'trim', explode( ";", $cookie ) );
614 if ( count($bit) >= 1 ) {
615 list($name, $value) = explode( "=", array_shift( $bit ), 2 );
617 foreach( $bit as $piece ) {
618 $parts = explode( "=", $piece );
619 if( count( $parts ) > 1 ) {
620 $attr[strtolower( $parts[0] )] = $parts[1];
622 $attr[strtolower( $parts[0] )] = true;
626 if( !isset( $attr['domain'] ) ) {
627 $attr['domain'] = $domain;
628 } elseif ( !Cookie
::validateCookieDomain( $attr['domain'], $domain ) ) {
632 $this->setCookie( $name, $value, $attr );
639 * HttpRequest implemented using internal curl compiled into PHP
641 class CurlHttpRequest
extends HttpRequest
{
642 static $curlMessageMap = array(
643 6 => 'http-host-unreachable',
644 28 => 'http-timed-out'
647 protected $curlOptions = array();
648 protected $headerText = "";
650 protected function readHeader( $fh, $content ) {
651 $this->headerText
.= $content;
652 return strlen( $content );
655 public function execute() {
657 if ( !$this->status
->isOK() ) {
658 return $this->status
;
660 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
661 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
662 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
663 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
664 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array($this, "readHeader");
665 $this->curlOptions
[CURLOPT_FOLLOWLOCATION
] = $this->followRedirects
;
666 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
668 /* not sure these two are actually necessary */
669 if(isset($this->reqHeaders
['Referer'])) {
670 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
672 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
674 if ( $this->sslVerifyHost
) {
675 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
678 if ( $this->caInfo
) {
679 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
682 if ( $this->headersOnly
) {
683 $this->curlOptions
[CURLOPT_NOBODY
] = true;
684 $this->curlOptions
[CURLOPT_HEADER
] = true;
685 } elseif ( $this->method
== 'POST' ) {
686 $this->curlOptions
[CURLOPT_POST
] = true;
687 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
688 // Suppress 'Expect: 100-continue' header, as some servers
689 // will reject it with a 417 and Curl won't auto retry
690 // with HTTP 1.0 fallback
691 $this->reqHeaders
['Expect'] = '';
693 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
696 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
698 $curlHandle = curl_init( $this->url
);
699 curl_setopt_array( $curlHandle, $this->curlOptions
);
701 if ( false === curl_exec( $curlHandle ) ) {
702 $code = curl_error( $curlHandle );
704 if ( isset( self
::$curlMessageMap[$code] ) ) {
705 $this->status
->fatal( self
::$curlMessageMap[$code] );
707 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
710 $this->headerList
= explode("\r\n", $this->headerText
);
713 curl_close( $curlHandle );
715 $this->parseHeader();
716 return $this->status
;
720 class PhpHttpRequest
extends HttpRequest
{
721 protected function urlToTcp( $url ) {
722 $parsedUrl = parse_url( $url );
724 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
727 public function execute() {
728 if ( $this->parsedUrl
['scheme'] != 'http' ) {
729 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
733 if ( !$this->status
->isOK() ) {
734 return $this->status
;
737 $this->reqHeaders
['Accept'] = "*/*";
738 if ( $this->method
== 'POST' ) {
739 // Required for HTTP 1.0 POSTs
740 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
741 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
745 if ( $this->proxy
&& !$this->noProxy
) {
746 $options['proxy'] = $this->urlToTCP( $this->proxy
);
747 $options['request_fulluri'] = true;
750 if ( !$this->followRedirects
) {
751 $options['max_redirects'] = 0;
753 $options['max_redirects'] = $this->maxRedirects
;
756 $options['method'] = $this->method
;
757 $options['timeout'] = $this->timeout
;
758 $options['ignore_errors'] = true; /* the only way to get 404s, etc */
759 $options['header'] = implode("\r\n", $this->getHeaderList());
760 // Note that at some future point we may want to support
761 // HTTP/1.1, but we'd have to write support for chunking
762 // in version of PHP < 5.3.1
763 $options['protocol_version'] = "1.0";
765 if ( $this->postData
) {
766 $options['content'] = $this->postData
;
770 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
771 $oldTimeout = ini_set('default_socket_timeout', $this->timeout
);
774 $context = stream_context_create( array( 'http' => $options ) );
775 wfSuppressWarnings();
776 $fh = fopen( $this->url
, "r", false, $context );
778 if ( $oldTimeout !== false ) {
779 ini_set('default_socket_timeout', $oldTimeout);
781 if ( $fh === false ) {
782 $this->status
->fatal( 'http-request-error' );
783 return $this->status
;
786 $result = stream_get_meta_data( $fh );
787 if ( $result['timed_out'] ) {
788 $this->status
->fatal( 'http-timed-out', $this->url
);
789 return $this->status
;
791 $this->headerList
= $result['wrapper_data'];
793 $this->parseHeader();
794 if($this->status
->isOK()) {
795 while ( !feof( $fh ) ) {
796 $buf = fread( $fh, 8192 );
797 if ( $buf === false ) {
798 $this->status
->fatal( 'http-read-error' );
801 if ( strlen( $buf ) ) {
802 call_user_func( $this->callback
, $fh, $buf );
808 return $this->status
;