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()
59 public static function get( $url, $timeout = 'default', $options = array() ) {
60 $options['timeout'] = $timeout;
61 return Http
::request( 'GET', $url, $options );
65 * Simple wrapper for Http::request( 'POST' )
66 * @see Http::request()
70 public static function post( $url, $options = array() ) {
71 return Http
::request( 'POST', $url, $options );
75 * Check if the URL can be served by localhost
77 * @param $url String: full url to check
80 public static function isLocalURL( $url ) {
81 global $wgCommandLineMode, $wgConf;
83 if ( $wgCommandLineMode ) {
89 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
92 $domainParts = explode( '.', $host );
93 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
94 $domainParts = array_reverse( $domainParts );
97 for ( $i = 0; $i < count( $domainParts ); $i++
) {
98 $domainPart = $domainParts[$i];
100 $domain = $domainPart;
102 $domain = $domainPart . '.' . $domain;
105 if ( $wgConf->isLocalVHost( $domain ) ) {
115 * A standard user-agent we can use for external requests.
118 public static function userAgent() {
120 return "MediaWiki/$wgVersion";
124 * Checks that the given URI is a valid one. Hardcoding the
125 * protocols, because we only want protocols that both cURL
128 * @fixme this is wildly inaccurate and fails to actually check most stuff
129 * @fixme do we actually intend to have FTP support here? Does it work consistently?
131 * @param $uri Mixed: URI to check for validity
134 public static function isValidURI( $uri ) {
136 '/^(f|ht)tps?:\/\/[^\/\s]\S*$/D',
143 * This wrapper class will call out to curl (if available) or fallback
144 * to regular PHP if necessary for handling internal HTTP requests.
146 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
147 * PHP's HTTP extension.
149 class MWHttpRequest
{
150 const SUPPORTS_FILE_POSTS
= false;
153 protected $timeout = 'default';
154 protected $headersOnly = null;
155 protected $postData = null;
156 protected $proxy = null;
157 protected $noProxy = false;
158 protected $sslVerifyHost = true;
159 protected $sslVerifyCert = true;
160 protected $caInfo = null;
161 protected $method = "GET";
162 protected $reqHeaders = array();
164 protected $parsedUrl;
166 protected $maxRedirects = 5;
167 protected $followRedirects = false;
172 protected $cookieJar;
174 protected $headerList = array();
175 protected $respVersion = "0.9";
176 protected $respStatus = "200 Ok";
177 protected $respHeaders = array();
182 * @param $url String: url to use
183 * @param $options Array: (optional) extra params to pass (see Http::request())
185 function __construct( $url, $options = array() ) {
186 global $wgHTTPTimeout;
189 $this->parsedUrl
= parse_url( $url );
191 if ( !Http
::isValidURI( $this->url
) ) {
192 $this->status
= Status
::newFatal( 'http-invalid-url' );
194 $this->status
= Status
::newGood( 100 ); // continue
197 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
198 $this->timeout
= $options['timeout'];
200 $this->timeout
= $wgHTTPTimeout;
203 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
204 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
206 foreach ( $members as $o ) {
207 if ( isset( $options[$o] ) ) {
208 $this->$o = $options[$o];
214 * Generate a new request object
215 * @param $url String: url to use
216 * @param $options Array: (optional) extra params to pass (see Http::request())
217 * @see MWHttpRequest::__construct
219 public static function factory( $url, $options = null ) {
220 if ( !Http
::$httpEngine ) {
221 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
222 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
223 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
224 ' Http::$httpEngine is set to "curl"' );
227 switch( Http
::$httpEngine ) {
229 return new CurlHttpRequest( $url, $options );
231 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
232 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
233 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
235 return new PhpHttpRequest( $url, $options );
237 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
242 * Get the body, or content, of the response to the request
246 public function getContent() {
247 return $this->content
;
251 * Set the parameters of the request
254 * @todo overload the args param
256 public function setData( $args ) {
257 $this->postData
= $args;
261 * Take care of setting up the proxy
262 * (override in subclass)
266 public function proxySetup() {
269 if ( $this->proxy
) {
273 if ( Http
::isLocalURL( $this->url
) ) {
274 $this->proxy
= 'http://localhost:80/';
275 } elseif ( $wgHTTPProxy ) {
276 $this->proxy
= $wgHTTPProxy ;
277 } elseif ( getenv( "http_proxy" ) ) {
278 $this->proxy
= getenv( "http_proxy" );
283 * Set the refererer header
285 public function setReferer( $url ) {
286 $this->setHeader( 'Referer', $url );
292 public function setUserAgent( $UA ) {
293 $this->setHeader( 'User-Agent', $UA );
297 * Set an arbitrary header
299 public function setHeader( $name, $value ) {
300 // I feel like I should normalize the case here...
301 $this->reqHeaders
[$name] = $value;
305 * Get an array of the headers
307 public function getHeaderList() {
310 if ( $this->cookieJar
) {
311 $this->reqHeaders
['Cookie'] =
312 $this->cookieJar
->serializeToHttpRequest(
313 $this->parsedUrl
['path'],
314 $this->parsedUrl
['host']
318 foreach ( $this->reqHeaders
as $name => $value ) {
319 $list[] = "$name: $value";
326 * Set a read callback to accept data read from the HTTP request.
327 * By default, data is appended to an internal buffer which can be
328 * retrieved through $req->getContent().
330 * To handle data as it comes in -- especially for large files that
331 * would not fit in memory -- you can instead set your own callback,
332 * in the form function($resource, $buffer) where the first parameter
333 * is the low-level resource being read (implementation specific),
334 * and the second parameter is the data buffer.
336 * You MUST return the number of bytes handled in the buffer; if fewer
337 * bytes are reported handled than were passed to you, the HTTP fetch
340 * @param $callback Callback
342 public function setCallback( $callback ) {
343 if ( !is_callable( $callback ) ) {
344 throw new MWException( 'Invalid MwHttpRequest callback' );
346 $this->callback
= $callback;
350 * A generic callback to read the body of the response from a remote
354 * @param $content String
356 public function read( $fh, $content ) {
357 $this->content
.= $content;
358 return strlen( $content );
362 * Take care of whatever is necessary to perform the URI request.
366 public function execute() {
371 if ( strtoupper( $this->method
) == "HEAD" ) {
372 $this->headersOnly
= true;
375 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
376 $this->setReferer( $wgTitle->getFullURL() );
379 if ( !$this->noProxy
) {
383 if ( !$this->callback
) {
384 $this->setCallback( array( $this, 'read' ) );
387 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
388 $this->setUserAgent( Http
::userAgent() );
393 * Parses the headers, including the HTTP status code and any
394 * Set-Cookie headers. This function expectes the headers to be
395 * found in an array in the member variable headerList.
399 protected function parseHeader() {
402 foreach ( $this->headerList
as $header ) {
403 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
404 $this->respVersion
= $match[1];
405 $this->respStatus
= $match[2];
406 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
407 $last = count( $this->respHeaders
[$lastname] ) - 1;
408 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
409 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
410 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
411 $lastname = strtolower( $match[1] );
415 $this->parseCookies();
419 * Sets HTTPRequest status member to a fatal value with the error
420 * message if the returned integer value of the status code was
421 * not successful (< 300) or a redirect (>=300 and < 400). (see
422 * RFC2616, section 10,
423 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
424 * list of status codes.)
428 protected function setStatus() {
429 if ( !$this->respHeaders
) {
430 $this->parseHeader();
433 if ( (int)$this->respStatus
> 399 ) {
434 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
435 $this->status
->fatal( "http-bad-status", $code, $message );
440 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
441 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
442 * for a list of status codes.)
446 public function getStatus() {
447 if ( !$this->respHeaders
) {
448 $this->parseHeader();
451 return (int)$this->respStatus
;
456 * Returns true if the last status code was a redirect.
460 public function isRedirect() {
461 if ( !$this->respHeaders
) {
462 $this->parseHeader();
465 $status = (int)$this->respStatus
;
467 if ( $status >= 300 && $status <= 303 ) {
475 * Returns an associative array of response headers after the
476 * request has been executed. Because some headers
477 * (e.g. Set-Cookie) can appear more than once the, each value of
478 * the associative array is an array of the values given.
482 public function getResponseHeaders() {
483 if ( !$this->respHeaders
) {
484 $this->parseHeader();
487 return $this->respHeaders
;
491 * Returns the value of the given response header.
493 * @param $header String
496 public function getResponseHeader( $header ) {
497 if ( !$this->respHeaders
) {
498 $this->parseHeader();
501 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
502 $v = $this->respHeaders
[strtolower ( $header ) ];
503 return $v[count( $v ) - 1];
510 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
512 * @param $jar CookieJar
514 public function setCookieJar( $jar ) {
515 $this->cookieJar
= $jar;
519 * Returns the cookie jar in use.
523 public function getCookieJar() {
524 if ( !$this->respHeaders
) {
525 $this->parseHeader();
528 return $this->cookieJar
;
532 * Sets a cookie. Used before a request to set up any individual
533 * cookies. Used internally after a request to parse the
534 * Set-Cookie headers.
537 public function setCookie( $name, $value = null, $attr = null ) {
538 if ( !$this->cookieJar
) {
539 $this->cookieJar
= new CookieJar
;
542 $this->cookieJar
->setCookie( $name, $value, $attr );
546 * Parse the cookies in the response headers and store them in the cookie jar.
548 protected function parseCookies() {
549 if ( !$this->cookieJar
) {
550 $this->cookieJar
= new CookieJar
;
553 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
554 $url = parse_url( $this->getFinalUrl() );
555 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
556 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
562 * Returns the final URL after all redirections.
566 public function getFinalUrl() {
567 $location = $this->getResponseHeader( "Location" );
577 * Returns true if the backend can follow redirects. Overridden by the
580 public function canFollowRedirects() {
586 * MWHttpRequest implemented using internal curl compiled into PHP
588 class CurlHttpRequest
extends MWHttpRequest
{
589 const SUPPORTS_FILE_POSTS
= true;
591 static $curlMessageMap = array(
592 6 => 'http-host-unreachable',
593 28 => 'http-timed-out'
596 protected $curlOptions = array();
597 protected $headerText = "";
599 protected function readHeader( $fh, $content ) {
600 $this->headerText
.= $content;
601 return strlen( $content );
604 public function execute() {
607 if ( !$this->status
->isOK() ) {
608 return $this->status
;
611 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
612 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
613 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
614 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
615 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
616 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
617 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
619 /* not sure these two are actually necessary */
620 if ( isset( $this->reqHeaders
['Referer'] ) ) {
621 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
623 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
625 if ( isset( $this->sslVerifyHost
) ) {
626 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
629 if ( isset( $this->sslVerifyCert
) ) {
630 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
633 if ( $this->caInfo
) {
634 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
637 if ( $this->headersOnly
) {
638 $this->curlOptions
[CURLOPT_NOBODY
] = true;
639 $this->curlOptions
[CURLOPT_HEADER
] = true;
640 } elseif ( $this->method
== 'POST' ) {
641 $this->curlOptions
[CURLOPT_POST
] = true;
642 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
643 // Suppress 'Expect: 100-continue' header, as some servers
644 // will reject it with a 417 and Curl won't auto retry
645 // with HTTP 1.0 fallback
646 $this->reqHeaders
['Expect'] = '';
648 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
651 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
653 $curlHandle = curl_init( $this->url
);
655 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
656 throw new MWException( "Error setting curl options." );
659 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
660 wfSuppressWarnings();
661 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
662 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
663 "Probably safe_mode or open_basedir is set.\n" );
664 // Continue the processing. If it were in curl_setopt_array,
665 // processing would have halted on its entry
670 if ( false === curl_exec( $curlHandle ) ) {
671 $code = curl_error( $curlHandle );
673 if ( isset( self
::$curlMessageMap[$code] ) ) {
674 $this->status
->fatal( self
::$curlMessageMap[$code] );
676 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
679 $this->headerList
= explode( "\r\n", $this->headerText
);
682 curl_close( $curlHandle );
684 $this->parseHeader();
687 return $this->status
;
690 public function canFollowRedirects() {
691 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
692 wfDebug( "Cannot follow redirects in safe mode\n" );
696 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
697 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
705 class PhpHttpRequest
extends MWHttpRequest
{
706 protected function urlToTcp( $url ) {
707 $parsedUrl = parse_url( $url );
709 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
712 public function execute() {
715 if ( is_array( $this->postData
) ) {
716 $this->postData
= wfArrayToCGI( $this->postData
);
719 if ( $this->parsedUrl
['scheme'] != 'http' &&
720 $this->parsedUrl
['scheme'] != 'ftp' &&
721 $this->parsedUrl
['scheme'] != 'https' ) {
722 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
725 $this->reqHeaders
['Accept'] = "*/*";
726 if ( $this->method
== 'POST' ) {
727 // Required for HTTP 1.0 POSTs
728 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
729 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
733 if ( $this->proxy
&& !$this->noProxy
) {
734 $options['proxy'] = $this->urlToTCP( $this->proxy
);
735 $options['request_fulluri'] = true;
738 if ( !$this->followRedirects
) {
739 $options['max_redirects'] = 0;
741 $options['max_redirects'] = $this->maxRedirects
;
744 $options['method'] = $this->method
;
745 $options['header'] = implode( "\r\n", $this->getHeaderList() );
746 // Note that at some future point we may want to support
747 // HTTP/1.1, but we'd have to write support for chunking
748 // in version of PHP < 5.3.1
749 $options['protocol_version'] = "1.0";
751 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
752 // Only works on 5.2.10+
753 $options['ignore_errors'] = true;
755 if ( $this->postData
) {
756 $options['content'] = $this->postData
;
759 $options['timeout'] = $this->timeout
;
761 $context = stream_context_create( array( 'http' => $options ) );
763 $this->headerList
= array();
771 wfSuppressWarnings();
772 $fh = fopen( $url, "r", false, $context );
779 $result = stream_get_meta_data( $fh );
780 $this->headerList
= $result['wrapper_data'];
781 $this->parseHeader();
783 if ( !$this->followRedirects
) {
787 # Handle manual redirection
788 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
791 # Check security of URL
792 $url = $this->getResponseHeader( "Location" );
794 if ( substr( $url, 0, 7 ) !== 'http://' ) {
795 wfDebug( __METHOD__
. ": insecure redirection\n" );
802 if ( $fh === false ) {
803 $this->status
->fatal( 'http-request-error' );
804 return $this->status
;
807 if ( $result['timed_out'] ) {
808 $this->status
->fatal( 'http-timed-out', $this->url
);
809 return $this->status
;
812 // If everything went OK, or we recieved some error code
813 // get the response body content.
814 if ( $this->status
->isOK()
815 ||
(int)$this->respStatus
>= 300) {
816 while ( !feof( $fh ) ) {
817 $buf = fread( $fh, 8192 );
819 if ( $buf === false ) {
820 $this->status
->fatal( 'http-read-error' );
824 if ( strlen( $buf ) ) {
825 call_user_func( $this->callback
, $fh, $buf );
831 return $this->status
;