7 * Various HTTP related functions
11 static $httpEngine = false;
14 * Perform an HTTP request
16 * @param $method String: HTTP method. Usually GET/POST
17 * @param $url String: full URL to act on
18 * @param $options Array: options to pass to MWHttpRequest object.
19 * Possible keys for the array:
20 * - timeout Timeout length in seconds
21 * - postData An array of key-value pairs or a url-encoded form data
22 * - proxy The proxy to use.
23 * Will use $wgHTTPProxy (if set) otherwise.
24 * - noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
25 * - sslVerifyHost (curl only) Verify hostname against certificate
26 * - sslVerifyCert (curl only) Verify SSL certificate
27 * - caInfo (curl only) Provide CA information
28 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
29 * - followRedirects Whether to follow redirects (defaults to false).
30 * Note: this should only be used when the target URL is trusted,
31 * to avoid attacks on intranet services accessible by HTTP.
32 * @return Mixed: (bool)false on failure or a string on success
34 public static function request( $method, $url, $options = array() ) {
35 $url = wfExpandUrl( $url );
36 wfDebug( "HTTP: $method: $url\n" );
37 $options['method'] = strtoupper( $method );
39 if ( !isset( $options['timeout'] ) ) {
40 $options['timeout'] = 'default';
43 $req = MWHttpRequest
::factory( $url, $options );
44 $status = $req->execute();
46 if ( $status->isOK() ) {
47 return $req->getContent();
54 * Simple wrapper for Http::request( 'GET' )
55 * @see Http::request()
57 public static function get( $url, $timeout = 'default', $options = array() ) {
58 $options['timeout'] = $timeout;
59 return Http
::request( 'GET', $url, $options );
63 * Simple wrapper for Http::request( 'POST' )
64 * @see Http::request()
66 public static function post( $url, $options = array() ) {
67 return Http
::request( 'POST', $url, $options );
71 * Check if the URL can be served by localhost
73 * @param $url String: full url to check
76 public static function isLocalURL( $url ) {
77 global $wgCommandLineMode, $wgConf;
79 if ( $wgCommandLineMode ) {
85 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
88 $domainParts = explode( '.', $host );
89 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
90 $domainParts = array_reverse( $domainParts );
93 for ( $i = 0; $i < count( $domainParts ); $i++
) {
94 $domainPart = $domainParts[$i];
96 $domain = $domainPart;
98 $domain = $domainPart . '.' . $domain;
101 if ( $wgConf->isLocalVHost( $domain ) ) {
111 * A standard user-agent we can use for external requests.
114 public static function userAgent() {
116 return "MediaWiki/$wgVersion";
120 * Checks that the given URI is a valid one. Hardcoding the
121 * protocols, because we only want protocols that both cURL
124 * @param $uri Mixed: URI to check for validity
127 public static function isValidURI( $uri ) {
129 '/^(f|ht)tps?:\/\/[^\/\s]\S*$/D',
136 * This wrapper class will call out to curl (if available) or fallback
137 * to regular PHP if necessary for handling internal HTTP requests.
139 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
140 * PHP's HTTP extension.
142 class MWHttpRequest
{
143 const SUPPORTS_FILE_POSTS
= false;
146 protected $timeout = 'default';
147 protected $headersOnly = null;
148 protected $postData = null;
149 protected $proxy = null;
150 protected $noProxy = false;
151 protected $sslVerifyHost = true;
152 protected $sslVerifyCert = true;
153 protected $caInfo = null;
154 protected $method = "GET";
155 protected $reqHeaders = array();
157 protected $parsedUrl;
159 protected $maxRedirects = 5;
160 protected $followRedirects = false;
165 protected $cookieJar;
167 protected $headerList = array();
168 protected $respVersion = "0.9";
169 protected $respStatus = "200 Ok";
170 protected $respHeaders = array();
175 * @param $url String: url to use
176 * @param $options Array: (optional) extra params to pass (see Http::request())
178 function __construct( $url, $options = array() ) {
179 global $wgHTTPTimeout;
182 $this->parsedUrl
= parse_url( $url );
184 if ( !Http
::isValidURI( $this->url
) ) {
185 $this->status
= Status
::newFatal( 'http-invalid-url' );
187 $this->status
= Status
::newGood( 100 ); // continue
190 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
191 $this->timeout
= $options['timeout'];
193 $this->timeout
= $wgHTTPTimeout;
196 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
197 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
199 foreach ( $members as $o ) {
200 if ( isset( $options[$o] ) ) {
201 $this->$o = $options[$o];
207 * Generate a new request object
208 * @param $url String: url to use
209 * @param $options Array: (optional) extra params to pass (see Http::request())
210 * @see MWHttpRequest::__construct
212 public static function factory( $url, $options = null ) {
213 if ( !Http
::$httpEngine ) {
214 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
215 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
216 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
217 ' Http::$httpEngine is set to "curl"' );
220 switch( Http
::$httpEngine ) {
222 return new CurlHttpRequest( $url, $options );
224 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
225 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
226 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
228 return new PhpHttpRequest( $url, $options );
230 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
235 * Get the body, or content, of the response to the request
239 public function getContent() {
240 return $this->content
;
244 * Set the parameters of the request
247 * @todo overload the args param
249 public function setData( $args ) {
250 $this->postData
= $args;
254 * Take care of setting up the proxy
255 * (override in subclass)
259 public function proxySetup() {
262 if ( $this->proxy
) {
266 if ( Http
::isLocalURL( $this->url
) ) {
267 $this->proxy
= 'http://localhost:80/';
268 } elseif ( $wgHTTPProxy ) {
269 $this->proxy
= $wgHTTPProxy ;
270 } elseif ( getenv( "http_proxy" ) ) {
271 $this->proxy
= getenv( "http_proxy" );
276 * Set the refererer header
278 public function setReferer( $url ) {
279 $this->setHeader( 'Referer', $url );
285 public function setUserAgent( $UA ) {
286 $this->setHeader( 'User-Agent', $UA );
290 * Set an arbitrary header
292 public function setHeader( $name, $value ) {
293 // I feel like I should normalize the case here...
294 $this->reqHeaders
[$name] = $value;
298 * Get an array of the headers
300 public function getHeaderList() {
303 if ( $this->cookieJar
) {
304 $this->reqHeaders
['Cookie'] =
305 $this->cookieJar
->serializeToHttpRequest(
306 $this->parsedUrl
['path'],
307 $this->parsedUrl
['host']
311 foreach ( $this->reqHeaders
as $name => $value ) {
312 $list[] = "$name: $value";
321 * @param $callback Callback
323 public function setCallback( $callback ) {
324 $this->callback
= $callback;
328 * A generic callback to read the body of the response from a remote
332 * @param $content String
334 public function read( $fh, $content ) {
335 $this->content
.= $content;
336 return strlen( $content );
340 * Take care of whatever is necessary to perform the URI request.
344 public function execute() {
349 if ( strtoupper( $this->method
) == "HEAD" ) {
350 $this->headersOnly
= true;
353 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
354 $this->setReferer( $wgTitle->getFullURL() );
357 if ( !$this->noProxy
) {
361 if ( !$this->callback
) {
362 $this->setCallback( array( $this, 'read' ) );
365 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
366 $this->setUserAgent( Http
::userAgent() );
371 * Parses the headers, including the HTTP status code and any
372 * Set-Cookie headers. This function expectes the headers to be
373 * found in an array in the member variable headerList.
377 protected function parseHeader() {
380 foreach ( $this->headerList
as $header ) {
381 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
382 $this->respVersion
= $match[1];
383 $this->respStatus
= $match[2];
384 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
385 $last = count( $this->respHeaders
[$lastname] ) - 1;
386 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
387 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
388 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
389 $lastname = strtolower( $match[1] );
393 $this->parseCookies();
397 * Sets HTTPRequest status member to a fatal value with the error
398 * message if the returned integer value of the status code was
399 * not successful (< 300) or a redirect (>=300 and < 400). (see
400 * RFC2616, section 10,
401 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
402 * list of status codes.)
406 protected function setStatus() {
407 if ( !$this->respHeaders
) {
408 $this->parseHeader();
411 if ( (int)$this->respStatus
> 399 ) {
412 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
413 $this->status
->fatal( "http-bad-status", $code, $message );
418 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
419 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
420 * for a list of status codes.)
424 public function getStatus() {
425 if ( !$this->respHeaders
) {
426 $this->parseHeader();
429 return (int)$this->respStatus
;
434 * Returns true if the last status code was a redirect.
438 public function isRedirect() {
439 if ( !$this->respHeaders
) {
440 $this->parseHeader();
443 $status = (int)$this->respStatus
;
445 if ( $status >= 300 && $status <= 303 ) {
453 * Returns an associative array of response headers after the
454 * request has been executed. Because some headers
455 * (e.g. Set-Cookie) can appear more than once the, each value of
456 * the associative array is an array of the values given.
460 public function getResponseHeaders() {
461 if ( !$this->respHeaders
) {
462 $this->parseHeader();
465 return $this->respHeaders
;
469 * Returns the value of the given response header.
471 * @param $header String
474 public function getResponseHeader( $header ) {
475 if ( !$this->respHeaders
) {
476 $this->parseHeader();
479 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
480 $v = $this->respHeaders
[strtolower ( $header ) ];
481 return $v[count( $v ) - 1];
488 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
490 * @param $jar CookieJar
492 public function setCookieJar( $jar ) {
493 $this->cookieJar
= $jar;
497 * Returns the cookie jar in use.
501 public function getCookieJar() {
502 if ( !$this->respHeaders
) {
503 $this->parseHeader();
506 return $this->cookieJar
;
510 * Sets a cookie. Used before a request to set up any individual
511 * cookies. Used internally after a request to parse the
512 * Set-Cookie headers.
515 public function setCookie( $name, $value = null, $attr = null ) {
516 if ( !$this->cookieJar
) {
517 $this->cookieJar
= new CookieJar
;
520 $this->cookieJar
->setCookie( $name, $value, $attr );
524 * Parse the cookies in the response headers and store them in the cookie jar.
526 protected function parseCookies() {
527 if ( !$this->cookieJar
) {
528 $this->cookieJar
= new CookieJar
;
531 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
532 $url = parse_url( $this->getFinalUrl() );
533 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
534 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
540 * Returns the final URL after all redirections.
544 public function getFinalUrl() {
545 $location = $this->getResponseHeader( "Location" );
555 * Returns true if the backend can follow redirects. Overridden by the
558 public function canFollowRedirects() {
564 * MWHttpRequest implemented using internal curl compiled into PHP
566 class CurlHttpRequest
extends MWHttpRequest
{
567 const SUPPORTS_FILE_POSTS
= true;
569 static $curlMessageMap = array(
570 6 => 'http-host-unreachable',
571 28 => 'http-timed-out'
574 protected $curlOptions = array();
575 protected $headerText = "";
577 protected function readHeader( $fh, $content ) {
578 $this->headerText
.= $content;
579 return strlen( $content );
582 public function execute() {
585 if ( !$this->status
->isOK() ) {
586 return $this->status
;
589 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
590 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
591 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
592 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
593 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
594 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
595 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
597 /* not sure these two are actually necessary */
598 if ( isset( $this->reqHeaders
['Referer'] ) ) {
599 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
601 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
603 if ( isset( $this->sslVerifyHost
) ) {
604 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
607 if ( isset( $this->sslVerifyCert
) ) {
608 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
611 if ( $this->caInfo
) {
612 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
615 if ( $this->headersOnly
) {
616 $this->curlOptions
[CURLOPT_NOBODY
] = true;
617 $this->curlOptions
[CURLOPT_HEADER
] = true;
618 } elseif ( $this->method
== 'POST' ) {
619 $this->curlOptions
[CURLOPT_POST
] = true;
620 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
621 // Suppress 'Expect: 100-continue' header, as some servers
622 // will reject it with a 417 and Curl won't auto retry
623 // with HTTP 1.0 fallback
624 $this->reqHeaders
['Expect'] = '';
626 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
629 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
631 $curlHandle = curl_init( $this->url
);
633 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
634 throw new MWException( "Error setting curl options." );
637 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
638 wfSuppressWarnings();
639 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
640 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
641 "Probably safe_mode or open_basedir is set.\n" );
642 // Continue the processing. If it were in curl_setopt_array,
643 // processing would have halted on its entry
648 if ( false === curl_exec( $curlHandle ) ) {
649 $code = curl_error( $curlHandle );
651 if ( isset( self
::$curlMessageMap[$code] ) ) {
652 $this->status
->fatal( self
::$curlMessageMap[$code] );
654 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
657 $this->headerList
= explode( "\r\n", $this->headerText
);
660 curl_close( $curlHandle );
662 $this->parseHeader();
665 return $this->status
;
668 public function canFollowRedirects() {
669 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
670 wfDebug( "Cannot follow redirects in safe mode\n" );
674 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
675 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
683 class PhpHttpRequest
extends MWHttpRequest
{
684 protected function urlToTcp( $url ) {
685 $parsedUrl = parse_url( $url );
687 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
690 public function execute() {
693 if ( is_array( $this->postData
) ) {
694 $this->postData
= wfArrayToCGI( $this->postData
);
697 if ( $this->parsedUrl
['scheme'] != 'http' ) {
698 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
701 $this->reqHeaders
['Accept'] = "*/*";
702 if ( $this->method
== 'POST' ) {
703 // Required for HTTP 1.0 POSTs
704 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
705 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
709 if ( $this->proxy
&& !$this->noProxy
) {
710 $options['proxy'] = $this->urlToTCP( $this->proxy
);
711 $options['request_fulluri'] = true;
714 if ( !$this->followRedirects
) {
715 $options['max_redirects'] = 0;
717 $options['max_redirects'] = $this->maxRedirects
;
720 $options['method'] = $this->method
;
721 $options['header'] = implode( "\r\n", $this->getHeaderList() );
722 // Note that at some future point we may want to support
723 // HTTP/1.1, but we'd have to write support for chunking
724 // in version of PHP < 5.3.1
725 $options['protocol_version'] = "1.0";
727 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
728 // Only works on 5.2.10+
729 $options['ignore_errors'] = true;
731 if ( $this->postData
) {
732 $options['content'] = $this->postData
;
735 $options['timeout'] = $this->timeout
;
737 $context = stream_context_create( array( 'http' => $options ) );
739 $this->headerList
= array();
747 wfSuppressWarnings();
748 $fh = fopen( $url, "r", false, $context );
755 $result = stream_get_meta_data( $fh );
756 $this->headerList
= $result['wrapper_data'];
757 $this->parseHeader();
759 if ( !$this->followRedirects
) {
763 # Handle manual redirection
764 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
767 # Check security of URL
768 $url = $this->getResponseHeader( "Location" );
770 if ( substr( $url, 0, 7 ) !== 'http://' ) {
771 wfDebug( __METHOD__
. ": insecure redirection\n" );
778 if ( $fh === false ) {
779 $this->status
->fatal( 'http-request-error' );
780 return $this->status
;
783 if ( $result['timed_out'] ) {
784 $this->status
->fatal( 'http-timed-out', $this->url
);
785 return $this->status
;
788 // If everything went OK, or we recieved some error code
789 // get the response body content.
790 if ( $this->status
->isOK()
791 ||
(int)$this->respStatus
>= 300) {
792 while ( !feof( $fh ) ) {
793 $buf = fread( $fh, 8192 );
795 if ( $buf === false ) {
796 $this->status
->fatal( 'http-read-error' );
800 if ( strlen( $buf ) ) {
801 call_user_func( $this->callback
, $fh, $buf );
807 return $this->status
;