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. If protocol-relative, will be expanded to an http:// URL
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, PROTO_HTTP
);
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
130 * @param $uri Mixed: URI to check for validity
133 public static function isValidURI( $uri ) {
135 '/^https?:\/\/[^\/\s]\S*$/D',
142 * This wrapper class will call out to curl (if available) or fallback
143 * to regular PHP if necessary for handling internal HTTP requests.
145 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
146 * PHP's HTTP extension.
148 class MWHttpRequest
{
149 const SUPPORTS_FILE_POSTS
= false;
152 protected $timeout = 'default';
153 protected $headersOnly = null;
154 protected $postData = null;
155 protected $proxy = null;
156 protected $noProxy = false;
157 protected $sslVerifyHost = true;
158 protected $sslVerifyCert = true;
159 protected $caInfo = null;
160 protected $method = "GET";
161 protected $reqHeaders = array();
163 protected $parsedUrl;
165 protected $maxRedirects = 5;
166 protected $followRedirects = false;
171 protected $cookieJar;
173 protected $headerList = array();
174 protected $respVersion = "0.9";
175 protected $respStatus = "200 Ok";
176 protected $respHeaders = array();
181 * @param $url String: url to use
182 * @param $options Array: (optional) extra params to pass (see Http::request())
184 function __construct( $url, $options = array() ) {
185 global $wgHTTPTimeout;
188 $this->parsedUrl
= parse_url( $url );
190 if ( !Http
::isValidURI( $this->url
) ) {
191 $this->status
= Status
::newFatal( 'http-invalid-url' );
193 $this->status
= Status
::newGood( 100 ); // continue
196 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
197 $this->timeout
= $options['timeout'];
199 $this->timeout
= $wgHTTPTimeout;
202 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
203 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
205 foreach ( $members as $o ) {
206 if ( isset( $options[$o] ) ) {
207 $this->$o = $options[$o];
213 * Simple function to test if we can make any sort of requests at all, using
217 public static function canMakeRequests() {
218 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
222 * Generate a new request object
223 * @param $url String: url to use
224 * @param $options Array: (optional) extra params to pass (see Http::request())
225 * @see MWHttpRequest::__construct
227 public static function factory( $url, $options = null ) {
228 if ( !Http
::$httpEngine ) {
229 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
230 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
231 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
232 ' Http::$httpEngine is set to "curl"' );
235 switch( Http
::$httpEngine ) {
237 return new CurlHttpRequest( $url, $options );
239 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
240 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
241 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
243 return new PhpHttpRequest( $url, $options );
245 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
250 * Get the body, or content, of the response to the request
254 public function getContent() {
255 return $this->content
;
259 * Set the parameters of the request
262 * @todo overload the args param
264 public function setData( $args ) {
265 $this->postData
= $args;
269 * Take care of setting up the proxy
270 * (override in subclass)
274 public function proxySetup() {
277 if ( $this->proxy
) {
281 if ( Http
::isLocalURL( $this->url
) ) {
282 $this->proxy
= 'http://localhost:80/';
283 } elseif ( $wgHTTPProxy ) {
284 $this->proxy
= $wgHTTPProxy ;
285 } elseif ( getenv( "http_proxy" ) ) {
286 $this->proxy
= getenv( "http_proxy" );
291 * Set the refererer header
293 public function setReferer( $url ) {
294 $this->setHeader( 'Referer', $url );
300 public function setUserAgent( $UA ) {
301 $this->setHeader( 'User-Agent', $UA );
305 * Set an arbitrary header
307 public function setHeader( $name, $value ) {
308 // I feel like I should normalize the case here...
309 $this->reqHeaders
[$name] = $value;
313 * Get an array of the headers
315 public function getHeaderList() {
318 if ( $this->cookieJar
) {
319 $this->reqHeaders
['Cookie'] =
320 $this->cookieJar
->serializeToHttpRequest(
321 $this->parsedUrl
['path'],
322 $this->parsedUrl
['host']
326 foreach ( $this->reqHeaders
as $name => $value ) {
327 $list[] = "$name: $value";
334 * Set a read callback to accept data read from the HTTP request.
335 * By default, data is appended to an internal buffer which can be
336 * retrieved through $req->getContent().
338 * To handle data as it comes in -- especially for large files that
339 * would not fit in memory -- you can instead set your own callback,
340 * in the form function($resource, $buffer) where the first parameter
341 * is the low-level resource being read (implementation specific),
342 * and the second parameter is the data buffer.
344 * You MUST return the number of bytes handled in the buffer; if fewer
345 * bytes are reported handled than were passed to you, the HTTP fetch
348 * @param $callback Callback
350 public function setCallback( $callback ) {
351 if ( !is_callable( $callback ) ) {
352 throw new MWException( 'Invalid MwHttpRequest callback' );
354 $this->callback
= $callback;
358 * A generic callback to read the body of the response from a remote
362 * @param $content String
364 public function read( $fh, $content ) {
365 $this->content
.= $content;
366 return strlen( $content );
370 * Take care of whatever is necessary to perform the URI request.
374 public function execute() {
379 if ( strtoupper( $this->method
) == "HEAD" ) {
380 $this->headersOnly
= true;
383 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
384 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
387 if ( !$this->noProxy
) {
391 if ( !$this->callback
) {
392 $this->setCallback( array( $this, 'read' ) );
395 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
396 $this->setUserAgent( Http
::userAgent() );
401 * Parses the headers, including the HTTP status code and any
402 * Set-Cookie headers. This function expectes the headers to be
403 * found in an array in the member variable headerList.
407 protected function parseHeader() {
410 foreach ( $this->headerList
as $header ) {
411 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
412 $this->respVersion
= $match[1];
413 $this->respStatus
= $match[2];
414 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
415 $last = count( $this->respHeaders
[$lastname] ) - 1;
416 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
417 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
418 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
419 $lastname = strtolower( $match[1] );
423 $this->parseCookies();
427 * Sets HTTPRequest status member to a fatal value with the error
428 * message if the returned integer value of the status code was
429 * not successful (< 300) or a redirect (>=300 and < 400). (see
430 * RFC2616, section 10,
431 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
432 * list of status codes.)
436 protected function setStatus() {
437 if ( !$this->respHeaders
) {
438 $this->parseHeader();
441 if ( (int)$this->respStatus
> 399 ) {
442 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
443 $this->status
->fatal( "http-bad-status", $code, $message );
448 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
449 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
450 * for a list of status codes.)
454 public function getStatus() {
455 if ( !$this->respHeaders
) {
456 $this->parseHeader();
459 return (int)$this->respStatus
;
464 * Returns true if the last status code was a redirect.
468 public function isRedirect() {
469 if ( !$this->respHeaders
) {
470 $this->parseHeader();
473 $status = (int)$this->respStatus
;
475 if ( $status >= 300 && $status <= 303 ) {
483 * Returns an associative array of response headers after the
484 * request has been executed. Because some headers
485 * (e.g. Set-Cookie) can appear more than once the, each value of
486 * the associative array is an array of the values given.
490 public function getResponseHeaders() {
491 if ( !$this->respHeaders
) {
492 $this->parseHeader();
495 return $this->respHeaders
;
499 * Returns the value of the given response header.
501 * @param $header String
504 public function getResponseHeader( $header ) {
505 if ( !$this->respHeaders
) {
506 $this->parseHeader();
509 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
510 $v = $this->respHeaders
[strtolower ( $header ) ];
511 return $v[count( $v ) - 1];
518 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
520 * @param $jar CookieJar
522 public function setCookieJar( $jar ) {
523 $this->cookieJar
= $jar;
527 * Returns the cookie jar in use.
531 public function getCookieJar() {
532 if ( !$this->respHeaders
) {
533 $this->parseHeader();
536 return $this->cookieJar
;
540 * Sets a cookie. Used before a request to set up any individual
541 * cookies. Used internally after a request to parse the
542 * Set-Cookie headers.
545 public function setCookie( $name, $value = null, $attr = null ) {
546 if ( !$this->cookieJar
) {
547 $this->cookieJar
= new CookieJar
;
550 $this->cookieJar
->setCookie( $name, $value, $attr );
554 * Parse the cookies in the response headers and store them in the cookie jar.
556 protected function parseCookies() {
557 if ( !$this->cookieJar
) {
558 $this->cookieJar
= new CookieJar
;
561 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
562 $url = parse_url( $this->getFinalUrl() );
563 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
564 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
570 * Returns the final URL after all redirections.
572 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
573 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
577 public function getFinalUrl() {
578 $headers = $this->getResponseHeaders();
580 //return full url (fix for incorrect but handled relative location)
581 if ( isset( $headers[ 'location' ] ) ) {
582 $locations = $headers[ 'location' ];
584 $foundRelativeURI = false;
585 $countLocations = count($locations);
587 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
588 $url = parse_url( $locations[ $i ] );
590 if ( isset($url[ 'host' ]) ) {
591 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
592 break; //found correct URI (with host)
594 $foundRelativeURI = true;
598 if ( $foundRelativeURI ) {
600 return $domain . $locations[ $countLocations - 1 ];
602 $url = parse_url( $this->url
);
603 if ( isset($url[ 'host' ]) ) {
604 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
608 return $locations[ $countLocations - 1 ];
616 * Returns true if the backend can follow redirects. Overridden by the
619 public function canFollowRedirects() {
625 * MWHttpRequest implemented using internal curl compiled into PHP
627 class CurlHttpRequest
extends MWHttpRequest
{
628 const SUPPORTS_FILE_POSTS
= true;
630 static $curlMessageMap = array(
631 6 => 'http-host-unreachable',
632 28 => 'http-timed-out'
635 protected $curlOptions = array();
636 protected $headerText = "";
638 protected function readHeader( $fh, $content ) {
639 $this->headerText
.= $content;
640 return strlen( $content );
643 public function execute() {
646 if ( !$this->status
->isOK() ) {
647 return $this->status
;
650 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
651 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
652 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
653 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
654 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
655 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
656 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
658 /* not sure these two are actually necessary */
659 if ( isset( $this->reqHeaders
['Referer'] ) ) {
660 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
662 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
664 if ( isset( $this->sslVerifyHost
) ) {
665 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
668 if ( isset( $this->sslVerifyCert
) ) {
669 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
672 if ( $this->caInfo
) {
673 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
676 if ( $this->headersOnly
) {
677 $this->curlOptions
[CURLOPT_NOBODY
] = true;
678 $this->curlOptions
[CURLOPT_HEADER
] = true;
679 } elseif ( $this->method
== 'POST' ) {
680 $this->curlOptions
[CURLOPT_POST
] = true;
681 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
682 // Suppress 'Expect: 100-continue' header, as some servers
683 // will reject it with a 417 and Curl won't auto retry
684 // with HTTP 1.0 fallback
685 $this->reqHeaders
['Expect'] = '';
687 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
690 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
692 $curlHandle = curl_init( $this->url
);
694 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
695 throw new MWException( "Error setting curl options." );
698 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
699 wfSuppressWarnings();
700 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
701 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
702 "Probably safe_mode or open_basedir is set.\n" );
703 // Continue the processing. If it were in curl_setopt_array,
704 // processing would have halted on its entry
709 if ( false === curl_exec( $curlHandle ) ) {
710 $code = curl_error( $curlHandle );
712 if ( isset( self
::$curlMessageMap[$code] ) ) {
713 $this->status
->fatal( self
::$curlMessageMap[$code] );
715 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
718 $this->headerList
= explode( "\r\n", $this->headerText
);
721 curl_close( $curlHandle );
723 $this->parseHeader();
726 return $this->status
;
729 public function canFollowRedirects() {
730 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
731 wfDebug( "Cannot follow redirects in safe mode\n" );
735 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
736 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
744 class PhpHttpRequest
extends MWHttpRequest
{
745 protected function urlToTcp( $url ) {
746 $parsedUrl = parse_url( $url );
748 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
751 public function execute() {
754 if ( is_array( $this->postData
) ) {
755 $this->postData
= wfArrayToCGI( $this->postData
);
758 if ( $this->parsedUrl
['scheme'] != 'http' &&
759 $this->parsedUrl
['scheme'] != 'https' ) {
760 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
763 $this->reqHeaders
['Accept'] = "*/*";
764 if ( $this->method
== 'POST' ) {
765 // Required for HTTP 1.0 POSTs
766 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
767 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
771 if ( $this->proxy
&& !$this->noProxy
) {
772 $options['proxy'] = $this->urlToTCP( $this->proxy
);
773 $options['request_fulluri'] = true;
776 if ( !$this->followRedirects
) {
777 $options['max_redirects'] = 0;
779 $options['max_redirects'] = $this->maxRedirects
;
782 $options['method'] = $this->method
;
783 $options['header'] = implode( "\r\n", $this->getHeaderList() );
784 // Note that at some future point we may want to support
785 // HTTP/1.1, but we'd have to write support for chunking
786 // in version of PHP < 5.3.1
787 $options['protocol_version'] = "1.0";
789 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
790 // Only works on 5.2.10+
791 $options['ignore_errors'] = true;
793 if ( $this->postData
) {
794 $options['content'] = $this->postData
;
797 $options['timeout'] = $this->timeout
;
799 $context = stream_context_create( array( 'http' => $options ) );
801 $this->headerList
= array();
809 wfSuppressWarnings();
810 $fh = fopen( $url, "r", false, $context );
817 $result = stream_get_meta_data( $fh );
818 $this->headerList
= $result['wrapper_data'];
819 $this->parseHeader();
821 if ( !$this->followRedirects
) {
825 # Handle manual redirection
826 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
829 # Check security of URL
830 $url = $this->getResponseHeader( "Location" );
832 if ( substr( $url, 0, 7 ) !== 'http://' ) {
833 wfDebug( __METHOD__
. ": insecure redirection\n" );
840 if ( $fh === false ) {
841 $this->status
->fatal( 'http-request-error' );
842 return $this->status
;
845 if ( $result['timed_out'] ) {
846 $this->status
->fatal( 'http-timed-out', $this->url
);
847 return $this->status
;
850 // If everything went OK, or we recieved some error code
851 // get the response body content.
852 if ( $this->status
->isOK()
853 ||
(int)$this->respStatus
>= 300) {
854 while ( !feof( $fh ) ) {
855 $buf = fread( $fh, 8192 );
857 if ( $buf === false ) {
858 $this->status
->fatal( 'http-read-error' );
862 if ( strlen( $buf ) ) {
863 call_user_func( $this->callback
, $fh, $buf );
869 return $this->status
;