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 * Otherwise it will use $wgHTTPProxy (if set)
24 * Otherwise it will use the environment variable "http_proxy" (if set)
25 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
26 * - sslVerifyHost (curl only) Verify hostname against certificate
27 * - sslVerifyCert (curl only) Verify SSL certificate
28 * - caInfo (curl only) Provide CA information
29 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
30 * - followRedirects Whether to follow redirects (defaults to false).
31 * Note: this should only be used when the target URL is trusted,
32 * to avoid attacks on intranet services accessible by HTTP.
33 * - userAgent A user agent, if you want to override the default
34 * MediaWiki/$wgVersion
35 * @return Mixed: (bool)false on failure or a string on success
37 public static function request( $method, $url, $options = array() ) {
38 wfDebug( "HTTP: $method: $url\n" );
39 $options['method'] = strtoupper( $method );
41 if ( !isset( $options['timeout'] ) ) {
42 $options['timeout'] = 'default';
45 $req = MWHttpRequest
::factory( $url, $options );
46 $status = $req->execute();
48 if ( $status->isOK() ) {
49 return $req->getContent();
56 * Simple wrapper for Http::request( 'GET' )
57 * @see Http::request()
60 * @param $timeout string
61 * @param $options array
64 public static function get( $url, $timeout = 'default', $options = array() ) {
65 $options['timeout'] = $timeout;
66 return Http
::request( 'GET', $url, $options );
70 * Simple wrapper for Http::request( 'POST' )
71 * @see Http::request()
74 * @param $options array
77 public static function post( $url, $options = array() ) {
78 return Http
::request( 'POST', $url, $options );
82 * Check if the URL can be served by localhost
84 * @param $url String: full url to check
87 public static function isLocalURL( $url ) {
88 global $wgCommandLineMode, $wgConf;
90 if ( $wgCommandLineMode ) {
96 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
99 $domainParts = explode( '.', $host );
100 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
101 $domainParts = array_reverse( $domainParts );
104 for ( $i = 0; $i < count( $domainParts ); $i++
) {
105 $domainPart = $domainParts[$i];
107 $domain = $domainPart;
109 $domain = $domainPart . '.' . $domain;
112 if ( $wgConf->isLocalVHost( $domain ) ) {
122 * A standard user-agent we can use for external requests.
125 public static function userAgent() {
127 return "MediaWiki/$wgVersion";
131 * Checks that the given URI is a valid one. Hardcoding the
132 * protocols, because we only want protocols that both cURL
135 * file:// should not be allowed here for security purpose (r67684)
137 * @fixme this is wildly inaccurate and fails to actually check most stuff
139 * @param $uri Mixed: URI to check for validity
142 public static function isValidURI( $uri ) {
144 '/^https?:\/\/[^\/\s]\S*$/D',
151 * This wrapper class will call out to curl (if available) or fallback
152 * to regular PHP if necessary for handling internal HTTP requests.
154 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
155 * PHP's HTTP extension.
157 class MWHttpRequest
{
158 const SUPPORTS_FILE_POSTS
= false;
161 protected $timeout = 'default';
162 protected $headersOnly = null;
163 protected $postData = null;
164 protected $proxy = null;
165 protected $noProxy = false;
166 protected $sslVerifyHost = true;
167 protected $sslVerifyCert = true;
168 protected $caInfo = null;
169 protected $method = "GET";
170 protected $reqHeaders = array();
172 protected $parsedUrl;
174 protected $maxRedirects = 5;
175 protected $followRedirects = false;
180 protected $cookieJar;
182 protected $headerList = array();
183 protected $respVersion = "0.9";
184 protected $respStatus = "200 Ok";
185 protected $respHeaders = array();
190 * @param $url String: url to use. If protocol-relative, will be expanded to an http:// URL
191 * @param $options Array: (optional) extra params to pass (see Http::request())
193 function __construct( $url, $options = array() ) {
194 global $wgHTTPTimeout;
196 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
197 $this->parsedUrl
= wfParseUrl( $this->url
);
199 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
200 $this->status
= Status
::newFatal( 'http-invalid-url' );
202 $this->status
= Status
::newGood( 100 ); // continue
205 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
206 $this->timeout
= $options['timeout'];
208 $this->timeout
= $wgHTTPTimeout;
210 if( isset( $options['userAgent'] ) ) {
211 $this->setUserAgent( $options['userAgent'] );
214 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
215 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
217 foreach ( $members as $o ) {
218 if ( isset( $options[$o] ) ) {
219 // ensure that MWHttpRequest::method is always
220 // uppercased. Bug 36137
221 if ( $o == 'method' ) {
222 $options[$o] = strtoupper( $options[$o] );
224 $this->$o = $options[$o];
228 if ( $this->noProxy
) {
229 $this->proxy
= ''; // noProxy takes precedence
234 * Simple function to test if we can make any sort of requests at all, using
238 public static function canMakeRequests() {
239 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
243 * Generate a new request object
244 * @param $url String: url to use
245 * @param $options Array: (optional) extra params to pass (see Http::request())
246 * @return CurlHttpRequest|PhpHttpRequest
247 * @see MWHttpRequest::__construct
249 public static function factory( $url, $options = null ) {
250 if ( !Http
::$httpEngine ) {
251 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
252 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
253 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
254 ' Http::$httpEngine is set to "curl"' );
257 switch( Http
::$httpEngine ) {
259 return new CurlHttpRequest( $url, $options );
261 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
262 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
263 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
265 return new PhpHttpRequest( $url, $options );
267 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
272 * Get the body, or content, of the response to the request
276 public function getContent() {
277 return $this->content
;
281 * Set the parameters of the request
284 * @todo overload the args param
286 public function setData( $args ) {
287 $this->postData
= $args;
291 * Take care of setting up the proxy (do nothing if "noProxy" is set)
295 public function proxySetup() {
298 if ( $this->proxy ||
!$this->noProxy
) {
302 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
304 } elseif ( $wgHTTPProxy ) {
305 $this->proxy
= $wgHTTPProxy ;
306 } elseif ( getenv( "http_proxy" ) ) {
307 $this->proxy
= getenv( "http_proxy" );
312 * Set the refererer header
314 public function setReferer( $url ) {
315 $this->setHeader( 'Referer', $url );
322 public function setUserAgent( $UA ) {
323 $this->setHeader( 'User-Agent', $UA );
327 * Set an arbitrary header
331 public function setHeader( $name, $value ) {
332 // I feel like I should normalize the case here...
333 $this->reqHeaders
[$name] = $value;
337 * Get an array of the headers
340 public function getHeaderList() {
343 if ( $this->cookieJar
) {
344 $this->reqHeaders
['Cookie'] =
345 $this->cookieJar
->serializeToHttpRequest(
346 $this->parsedUrl
['path'],
347 $this->parsedUrl
['host']
351 foreach ( $this->reqHeaders
as $name => $value ) {
352 $list[] = "$name: $value";
359 * Set a read callback to accept data read from the HTTP request.
360 * By default, data is appended to an internal buffer which can be
361 * retrieved through $req->getContent().
363 * To handle data as it comes in -- especially for large files that
364 * would not fit in memory -- you can instead set your own callback,
365 * in the form function($resource, $buffer) where the first parameter
366 * is the low-level resource being read (implementation specific),
367 * and the second parameter is the data buffer.
369 * You MUST return the number of bytes handled in the buffer; if fewer
370 * bytes are reported handled than were passed to you, the HTTP fetch
373 * @param $callback Callback
375 public function setCallback( $callback ) {
376 if ( !is_callable( $callback ) ) {
377 throw new MWException( 'Invalid MwHttpRequest callback' );
379 $this->callback
= $callback;
383 * A generic callback to read the body of the response from a remote
387 * @param $content String
390 public function read( $fh, $content ) {
391 $this->content
.= $content;
392 return strlen( $content );
396 * Take care of whatever is necessary to perform the URI request.
400 public function execute() {
405 if ( strtoupper( $this->method
) == "HEAD" ) {
406 $this->headersOnly
= true;
409 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
410 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
413 $this->proxySetup(); // set up any proxy as needed
415 if ( !$this->callback
) {
416 $this->setCallback( array( $this, 'read' ) );
419 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
420 $this->setUserAgent( Http
::userAgent() );
425 * Parses the headers, including the HTTP status code and any
426 * Set-Cookie headers. This function expectes the headers to be
427 * found in an array in the member variable headerList.
429 protected function parseHeader() {
432 foreach ( $this->headerList
as $header ) {
433 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
434 $this->respVersion
= $match[1];
435 $this->respStatus
= $match[2];
436 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
437 $last = count( $this->respHeaders
[$lastname] ) - 1;
438 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
439 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
440 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
441 $lastname = strtolower( $match[1] );
445 $this->parseCookies();
449 * Sets HTTPRequest status member to a fatal value with the error
450 * message if the returned integer value of the status code was
451 * not successful (< 300) or a redirect (>=300 and < 400). (see
452 * RFC2616, section 10,
453 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
454 * list of status codes.)
456 protected function setStatus() {
457 if ( !$this->respHeaders
) {
458 $this->parseHeader();
461 if ( (int)$this->respStatus
> 399 ) {
462 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
463 $this->status
->fatal( "http-bad-status", $code, $message );
468 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
469 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
470 * for a list of status codes.)
474 public function getStatus() {
475 if ( !$this->respHeaders
) {
476 $this->parseHeader();
479 return (int)$this->respStatus
;
484 * Returns true if the last status code was a redirect.
488 public function isRedirect() {
489 if ( !$this->respHeaders
) {
490 $this->parseHeader();
493 $status = (int)$this->respStatus
;
495 if ( $status >= 300 && $status <= 303 ) {
503 * Returns an associative array of response headers after the
504 * request has been executed. Because some headers
505 * (e.g. Set-Cookie) can appear more than once the, each value of
506 * the associative array is an array of the values given.
510 public function getResponseHeaders() {
511 if ( !$this->respHeaders
) {
512 $this->parseHeader();
515 return $this->respHeaders
;
519 * Returns the value of the given response header.
521 * @param $header String
524 public function getResponseHeader( $header ) {
525 if ( !$this->respHeaders
) {
526 $this->parseHeader();
529 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
530 $v = $this->respHeaders
[strtolower ( $header ) ];
531 return $v[count( $v ) - 1];
538 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
540 * @param $jar CookieJar
542 public function setCookieJar( $jar ) {
543 $this->cookieJar
= $jar;
547 * Returns the cookie jar in use.
551 public function getCookieJar() {
552 if ( !$this->respHeaders
) {
553 $this->parseHeader();
556 return $this->cookieJar
;
560 * Sets a cookie. Used before a request to set up any individual
561 * cookies. Used internally after a request to parse the
562 * Set-Cookie headers.
568 public function setCookie( $name, $value = null, $attr = null ) {
569 if ( !$this->cookieJar
) {
570 $this->cookieJar
= new CookieJar
;
573 $this->cookieJar
->setCookie( $name, $value, $attr );
577 * Parse the cookies in the response headers and store them in the cookie jar.
579 protected function parseCookies() {
580 if ( !$this->cookieJar
) {
581 $this->cookieJar
= new CookieJar
;
584 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
585 $url = parse_url( $this->getFinalUrl() );
586 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
587 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
593 * Returns the final URL after all redirections.
595 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
596 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
598 * Note that the multiple Location: headers are an artifact of CURL -- they
599 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
600 * taken care of (high-level redirect handling rewrite).
604 public function getFinalUrl() {
605 $headers = $this->getResponseHeaders();
607 //return full url (fix for incorrect but handled relative location)
608 if ( isset( $headers[ 'location' ] ) ) {
609 $locations = $headers[ 'location' ];
611 $foundRelativeURI = false;
612 $countLocations = count($locations);
614 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
615 $url = parse_url( $locations[ $i ] );
617 if ( isset($url[ 'host' ]) ) {
618 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
619 break; //found correct URI (with host)
621 $foundRelativeURI = true;
625 if ( $foundRelativeURI ) {
627 return $domain . $locations[ $countLocations - 1 ];
629 $url = parse_url( $this->url
);
630 if ( isset($url[ 'host' ]) ) {
631 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
635 return $locations[ $countLocations - 1 ];
643 * Returns true if the backend can follow redirects. Overridden by the
647 public function canFollowRedirects() {
653 * MWHttpRequest implemented using internal curl compiled into PHP
655 class CurlHttpRequest
extends MWHttpRequest
{
656 const SUPPORTS_FILE_POSTS
= true;
658 static $curlMessageMap = array(
659 6 => 'http-host-unreachable',
660 28 => 'http-timed-out'
663 protected $curlOptions = array();
664 protected $headerText = "";
671 protected function readHeader( $fh, $content ) {
672 $this->headerText
.= $content;
673 return strlen( $content );
676 public function execute() {
679 if ( !$this->status
->isOK() ) {
680 return $this->status
;
683 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
684 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
685 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
686 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
687 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
688 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
689 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
691 /* not sure these two are actually necessary */
692 if ( isset( $this->reqHeaders
['Referer'] ) ) {
693 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
695 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
697 if ( isset( $this->sslVerifyHost
) ) {
698 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
701 if ( isset( $this->sslVerifyCert
) ) {
702 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
705 if ( $this->caInfo
) {
706 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
709 if ( $this->headersOnly
) {
710 $this->curlOptions
[CURLOPT_NOBODY
] = true;
711 $this->curlOptions
[CURLOPT_HEADER
] = true;
712 } elseif ( $this->method
== 'POST' ) {
713 $this->curlOptions
[CURLOPT_POST
] = true;
714 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
715 // Suppress 'Expect: 100-continue' header, as some servers
716 // will reject it with a 417 and Curl won't auto retry
717 // with HTTP 1.0 fallback
718 $this->reqHeaders
['Expect'] = '';
720 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
723 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
725 $curlHandle = curl_init( $this->url
);
727 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
728 throw new MWException( "Error setting curl options." );
731 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
732 wfSuppressWarnings();
733 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
734 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
735 "Probably safe_mode or open_basedir is set.\n" );
736 // Continue the processing. If it were in curl_setopt_array,
737 // processing would have halted on its entry
742 if ( false === curl_exec( $curlHandle ) ) {
743 $code = curl_error( $curlHandle );
745 if ( isset( self
::$curlMessageMap[$code] ) ) {
746 $this->status
->fatal( self
::$curlMessageMap[$code] );
748 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
751 $this->headerList
= explode( "\r\n", $this->headerText
);
754 curl_close( $curlHandle );
756 $this->parseHeader();
759 return $this->status
;
765 public function canFollowRedirects() {
766 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
767 wfDebug( "Cannot follow redirects in safe mode\n" );
771 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
772 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
780 class PhpHttpRequest
extends MWHttpRequest
{
786 protected function urlToTcp( $url ) {
787 $parsedUrl = parse_url( $url );
789 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
792 public function execute() {
795 if ( is_array( $this->postData
) ) {
796 $this->postData
= wfArrayToCGI( $this->postData
);
799 if ( $this->parsedUrl
['scheme'] != 'http' &&
800 $this->parsedUrl
['scheme'] != 'https' ) {
801 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
804 $this->reqHeaders
['Accept'] = "*/*";
805 if ( $this->method
== 'POST' ) {
806 // Required for HTTP 1.0 POSTs
807 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
808 if( !isset( $this->reqHeaders
['Content-Type'] ) ) {
809 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
814 if ( $this->proxy
) {
815 $options['proxy'] = $this->urlToTCP( $this->proxy
);
816 $options['request_fulluri'] = true;
819 if ( !$this->followRedirects
) {
820 $options['max_redirects'] = 0;
822 $options['max_redirects'] = $this->maxRedirects
;
825 $options['method'] = $this->method
;
826 $options['header'] = implode( "\r\n", $this->getHeaderList() );
827 // Note that at some future point we may want to support
828 // HTTP/1.1, but we'd have to write support for chunking
829 // in version of PHP < 5.3.1
830 $options['protocol_version'] = "1.0";
832 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
833 // Only works on 5.2.10+
834 $options['ignore_errors'] = true;
836 if ( $this->postData
) {
837 $options['content'] = $this->postData
;
840 $options['timeout'] = $this->timeout
;
842 $context = stream_context_create( array( 'http' => $options ) );
844 $this->headerList
= array();
852 wfSuppressWarnings();
853 $fh = fopen( $url, "r", false, $context );
860 $result = stream_get_meta_data( $fh );
861 $this->headerList
= $result['wrapper_data'];
862 $this->parseHeader();
864 if ( !$this->followRedirects
) {
868 # Handle manual redirection
869 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
872 # Check security of URL
873 $url = $this->getResponseHeader( "Location" );
875 if ( !Http
::isValidURI( $url ) ) {
876 wfDebug( __METHOD__
. ": insecure redirection\n" );
883 if ( $fh === false ) {
884 $this->status
->fatal( 'http-request-error' );
885 return $this->status
;
888 if ( $result['timed_out'] ) {
889 $this->status
->fatal( 'http-timed-out', $this->url
);
890 return $this->status
;
893 // If everything went OK, or we recieved some error code
894 // get the response body content.
895 if ( $this->status
->isOK()
896 ||
(int)$this->respStatus
>= 300) {
897 while ( !feof( $fh ) ) {
898 $buf = fread( $fh, 8192 );
900 if ( $buf === false ) {
901 $this->status
->fatal( 'http-read-error' );
905 if ( strlen( $buf ) ) {
906 call_user_func( $this->callback
, $fh, $buf );
912 return $this->status
;