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";
319 * Set a read callback to accept data read from the HTTP request.
320 * By default, data is appended to an internal buffer which can be
321 * retrieved through $req->getContent().
323 * To handle data as it comes in -- especially for large files that
324 * would not fit in memory -- you can instead set your own callback,
325 * in the form function($resource, $buffer) where the first parameter
326 * is the low-level resource being read (implementation specific),
327 * and the second parameter is the data buffer.
329 * You MUST return the number of bytes handled in the buffer; if fewer
330 * bytes are reported handled than were passed to you, the HTTP fetch
333 * @param $callback Callback
335 public function setCallback( $callback ) {
336 if ( !is_callable( $callback ) ) {
337 throw new MWException( 'Invalid MwHttpRequest callback' );
339 $this->callback
= $callback;
343 * A generic callback to read the body of the response from a remote
347 * @param $content String
349 public function read( $fh, $content ) {
350 $this->content
.= $content;
351 return strlen( $content );
355 * Take care of whatever is necessary to perform the URI request.
359 public function execute() {
364 if ( strtoupper( $this->method
) == "HEAD" ) {
365 $this->headersOnly
= true;
368 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
369 $this->setReferer( $wgTitle->getFullURL() );
372 if ( !$this->noProxy
) {
376 if ( !$this->callback
) {
377 $this->setCallback( array( $this, 'read' ) );
380 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
381 $this->setUserAgent( Http
::userAgent() );
386 * Parses the headers, including the HTTP status code and any
387 * Set-Cookie headers. This function expectes the headers to be
388 * found in an array in the member variable headerList.
392 protected function parseHeader() {
395 foreach ( $this->headerList
as $header ) {
396 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
397 $this->respVersion
= $match[1];
398 $this->respStatus
= $match[2];
399 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
400 $last = count( $this->respHeaders
[$lastname] ) - 1;
401 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
402 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
403 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
404 $lastname = strtolower( $match[1] );
408 $this->parseCookies();
412 * Sets HTTPRequest status member to a fatal value with the error
413 * message if the returned integer value of the status code was
414 * not successful (< 300) or a redirect (>=300 and < 400). (see
415 * RFC2616, section 10,
416 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
417 * list of status codes.)
421 protected function setStatus() {
422 if ( !$this->respHeaders
) {
423 $this->parseHeader();
426 if ( (int)$this->respStatus
> 399 ) {
427 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
428 $this->status
->fatal( "http-bad-status", $code, $message );
433 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
434 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
435 * for a list of status codes.)
439 public function getStatus() {
440 if ( !$this->respHeaders
) {
441 $this->parseHeader();
444 return (int)$this->respStatus
;
449 * Returns true if the last status code was a redirect.
453 public function isRedirect() {
454 if ( !$this->respHeaders
) {
455 $this->parseHeader();
458 $status = (int)$this->respStatus
;
460 if ( $status >= 300 && $status <= 303 ) {
468 * Returns an associative array of response headers after the
469 * request has been executed. Because some headers
470 * (e.g. Set-Cookie) can appear more than once the, each value of
471 * the associative array is an array of the values given.
475 public function getResponseHeaders() {
476 if ( !$this->respHeaders
) {
477 $this->parseHeader();
480 return $this->respHeaders
;
484 * Returns the value of the given response header.
486 * @param $header String
489 public function getResponseHeader( $header ) {
490 if ( !$this->respHeaders
) {
491 $this->parseHeader();
494 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
495 $v = $this->respHeaders
[strtolower ( $header ) ];
496 return $v[count( $v ) - 1];
503 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
505 * @param $jar CookieJar
507 public function setCookieJar( $jar ) {
508 $this->cookieJar
= $jar;
512 * Returns the cookie jar in use.
516 public function getCookieJar() {
517 if ( !$this->respHeaders
) {
518 $this->parseHeader();
521 return $this->cookieJar
;
525 * Sets a cookie. Used before a request to set up any individual
526 * cookies. Used internally after a request to parse the
527 * Set-Cookie headers.
530 public function setCookie( $name, $value = null, $attr = null ) {
531 if ( !$this->cookieJar
) {
532 $this->cookieJar
= new CookieJar
;
535 $this->cookieJar
->setCookie( $name, $value, $attr );
539 * Parse the cookies in the response headers and store them in the cookie jar.
541 protected function parseCookies() {
542 if ( !$this->cookieJar
) {
543 $this->cookieJar
= new CookieJar
;
546 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
547 $url = parse_url( $this->getFinalUrl() );
548 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
549 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
555 * Returns the final URL after all redirections.
559 public function getFinalUrl() {
560 $location = $this->getResponseHeader( "Location" );
570 * Returns true if the backend can follow redirects. Overridden by the
573 public function canFollowRedirects() {
579 * MWHttpRequest implemented using internal curl compiled into PHP
581 class CurlHttpRequest
extends MWHttpRequest
{
582 const SUPPORTS_FILE_POSTS
= true;
584 static $curlMessageMap = array(
585 6 => 'http-host-unreachable',
586 28 => 'http-timed-out'
589 protected $curlOptions = array();
590 protected $headerText = "";
592 protected function readHeader( $fh, $content ) {
593 $this->headerText
.= $content;
594 return strlen( $content );
597 public function execute() {
600 if ( !$this->status
->isOK() ) {
601 return $this->status
;
604 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
605 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
606 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
607 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
608 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
609 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
610 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
612 /* not sure these two are actually necessary */
613 if ( isset( $this->reqHeaders
['Referer'] ) ) {
614 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
616 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
618 if ( isset( $this->sslVerifyHost
) ) {
619 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
622 if ( isset( $this->sslVerifyCert
) ) {
623 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
626 if ( $this->caInfo
) {
627 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
630 if ( $this->headersOnly
) {
631 $this->curlOptions
[CURLOPT_NOBODY
] = true;
632 $this->curlOptions
[CURLOPT_HEADER
] = true;
633 } elseif ( $this->method
== 'POST' ) {
634 $this->curlOptions
[CURLOPT_POST
] = true;
635 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
636 // Suppress 'Expect: 100-continue' header, as some servers
637 // will reject it with a 417 and Curl won't auto retry
638 // with HTTP 1.0 fallback
639 $this->reqHeaders
['Expect'] = '';
641 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
644 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
646 $curlHandle = curl_init( $this->url
);
648 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
649 throw new MWException( "Error setting curl options." );
652 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
653 wfSuppressWarnings();
654 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
655 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
656 "Probably safe_mode or open_basedir is set.\n" );
657 // Continue the processing. If it were in curl_setopt_array,
658 // processing would have halted on its entry
663 if ( false === curl_exec( $curlHandle ) ) {
664 $code = curl_error( $curlHandle );
666 if ( isset( self
::$curlMessageMap[$code] ) ) {
667 $this->status
->fatal( self
::$curlMessageMap[$code] );
669 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
672 $this->headerList
= explode( "\r\n", $this->headerText
);
675 curl_close( $curlHandle );
677 $this->parseHeader();
680 return $this->status
;
683 public function canFollowRedirects() {
684 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
685 wfDebug( "Cannot follow redirects in safe mode\n" );
689 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
690 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
698 class PhpHttpRequest
extends MWHttpRequest
{
699 protected function urlToTcp( $url ) {
700 $parsedUrl = parse_url( $url );
702 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
705 public function execute() {
708 if ( is_array( $this->postData
) ) {
709 $this->postData
= wfArrayToCGI( $this->postData
);
712 if ( $this->parsedUrl
['scheme'] != 'http' ) {
713 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
716 $this->reqHeaders
['Accept'] = "*/*";
717 if ( $this->method
== 'POST' ) {
718 // Required for HTTP 1.0 POSTs
719 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
720 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
724 if ( $this->proxy
&& !$this->noProxy
) {
725 $options['proxy'] = $this->urlToTCP( $this->proxy
);
726 $options['request_fulluri'] = true;
729 if ( !$this->followRedirects
) {
730 $options['max_redirects'] = 0;
732 $options['max_redirects'] = $this->maxRedirects
;
735 $options['method'] = $this->method
;
736 $options['header'] = implode( "\r\n", $this->getHeaderList() );
737 // Note that at some future point we may want to support
738 // HTTP/1.1, but we'd have to write support for chunking
739 // in version of PHP < 5.3.1
740 $options['protocol_version'] = "1.0";
742 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
743 // Only works on 5.2.10+
744 $options['ignore_errors'] = true;
746 if ( $this->postData
) {
747 $options['content'] = $this->postData
;
750 $options['timeout'] = $this->timeout
;
752 $context = stream_context_create( array( 'http' => $options ) );
754 $this->headerList
= array();
762 wfSuppressWarnings();
763 $fh = fopen( $url, "r", false, $context );
770 $result = stream_get_meta_data( $fh );
771 $this->headerList
= $result['wrapper_data'];
772 $this->parseHeader();
774 if ( !$this->followRedirects
) {
778 # Handle manual redirection
779 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
782 # Check security of URL
783 $url = $this->getResponseHeader( "Location" );
785 if ( substr( $url, 0, 7 ) !== 'http://' ) {
786 wfDebug( __METHOD__
. ": insecure redirection\n" );
793 if ( $fh === false ) {
794 $this->status
->fatal( 'http-request-error' );
795 return $this->status
;
798 if ( $result['timed_out'] ) {
799 $this->status
->fatal( 'http-timed-out', $this->url
);
800 return $this->status
;
803 // If everything went OK, or we recieved some error code
804 // get the response body content.
805 if ( $this->status
->isOK()
806 ||
(int)$this->respStatus
>= 300) {
807 while ( !feof( $fh ) ) {
808 $buf = fread( $fh, 8192 );
810 if ( $buf === false ) {
811 $this->status
->fatal( 'http-read-error' );
815 if ( strlen( $buf ) ) {
816 call_user_func( $this->callback
, $fh, $buf );
822 return $this->status
;