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 $this->$o = $options[$o];
223 if ( $this->noProxy
) {
224 $this->proxy
= ''; // noProxy takes precedence
229 * Simple function to test if we can make any sort of requests at all, using
233 public static function canMakeRequests() {
234 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
238 * Generate a new request object
239 * @param $url String: url to use
240 * @param $options Array: (optional) extra params to pass (see Http::request())
241 * @return CurlHttpRequest|PhpHttpRequest
242 * @see MWHttpRequest::__construct
244 public static function factory( $url, $options = null ) {
245 if ( !Http
::$httpEngine ) {
246 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
247 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
248 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
249 ' Http::$httpEngine is set to "curl"' );
252 switch( Http
::$httpEngine ) {
254 return new CurlHttpRequest( $url, $options );
256 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
257 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
258 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
260 return new PhpHttpRequest( $url, $options );
262 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
267 * Get the body, or content, of the response to the request
271 public function getContent() {
272 return $this->content
;
276 * Set the parameters of the request
279 * @todo overload the args param
281 public function setData( $args ) {
282 $this->postData
= $args;
286 * Take care of setting up the proxy (do nothing if "noProxy" is set)
290 public function proxySetup() {
293 if ( $this->proxy ||
!$this->noProxy
) {
297 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
299 } elseif ( $wgHTTPProxy ) {
300 $this->proxy
= $wgHTTPProxy ;
301 } elseif ( getenv( "http_proxy" ) ) {
302 $this->proxy
= getenv( "http_proxy" );
307 * Set the refererer header
309 public function setReferer( $url ) {
310 $this->setHeader( 'Referer', $url );
317 public function setUserAgent( $UA ) {
318 $this->setHeader( 'User-Agent', $UA );
322 * Set an arbitrary header
326 public function setHeader( $name, $value ) {
327 // I feel like I should normalize the case here...
328 $this->reqHeaders
[$name] = $value;
332 * Get an array of the headers
335 public function getHeaderList() {
338 if ( $this->cookieJar
) {
339 $this->reqHeaders
['Cookie'] =
340 $this->cookieJar
->serializeToHttpRequest(
341 $this->parsedUrl
['path'],
342 $this->parsedUrl
['host']
346 foreach ( $this->reqHeaders
as $name => $value ) {
347 $list[] = "$name: $value";
354 * Set a read callback to accept data read from the HTTP request.
355 * By default, data is appended to an internal buffer which can be
356 * retrieved through $req->getContent().
358 * To handle data as it comes in -- especially for large files that
359 * would not fit in memory -- you can instead set your own callback,
360 * in the form function($resource, $buffer) where the first parameter
361 * is the low-level resource being read (implementation specific),
362 * and the second parameter is the data buffer.
364 * You MUST return the number of bytes handled in the buffer; if fewer
365 * bytes are reported handled than were passed to you, the HTTP fetch
368 * @param $callback Callback
370 public function setCallback( $callback ) {
371 if ( !is_callable( $callback ) ) {
372 throw new MWException( 'Invalid MwHttpRequest callback' );
374 $this->callback
= $callback;
378 * A generic callback to read the body of the response from a remote
382 * @param $content String
385 public function read( $fh, $content ) {
386 $this->content
.= $content;
387 return strlen( $content );
391 * Take care of whatever is necessary to perform the URI request.
395 public function execute() {
400 if ( strtoupper( $this->method
) == "HEAD" ) {
401 $this->headersOnly
= true;
404 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
405 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
408 $this->proxySetup(); // set up any proxy as needed
410 if ( !$this->callback
) {
411 $this->setCallback( array( $this, 'read' ) );
414 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
415 $this->setUserAgent( Http
::userAgent() );
420 * Parses the headers, including the HTTP status code and any
421 * Set-Cookie headers. This function expectes the headers to be
422 * found in an array in the member variable headerList.
424 protected function parseHeader() {
427 foreach ( $this->headerList
as $header ) {
428 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
429 $this->respVersion
= $match[1];
430 $this->respStatus
= $match[2];
431 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
432 $last = count( $this->respHeaders
[$lastname] ) - 1;
433 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
434 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
435 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
436 $lastname = strtolower( $match[1] );
440 $this->parseCookies();
444 * Sets HTTPRequest status member to a fatal value with the error
445 * message if the returned integer value of the status code was
446 * not successful (< 300) or a redirect (>=300 and < 400). (see
447 * RFC2616, section 10,
448 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
449 * list of status codes.)
451 protected function setStatus() {
452 if ( !$this->respHeaders
) {
453 $this->parseHeader();
456 if ( (int)$this->respStatus
> 399 ) {
457 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
458 $this->status
->fatal( "http-bad-status", $code, $message );
463 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
464 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
465 * for a list of status codes.)
469 public function getStatus() {
470 if ( !$this->respHeaders
) {
471 $this->parseHeader();
474 return (int)$this->respStatus
;
479 * Returns true if the last status code was a redirect.
483 public function isRedirect() {
484 if ( !$this->respHeaders
) {
485 $this->parseHeader();
488 $status = (int)$this->respStatus
;
490 if ( $status >= 300 && $status <= 303 ) {
498 * Returns an associative array of response headers after the
499 * request has been executed. Because some headers
500 * (e.g. Set-Cookie) can appear more than once the, each value of
501 * the associative array is an array of the values given.
505 public function getResponseHeaders() {
506 if ( !$this->respHeaders
) {
507 $this->parseHeader();
510 return $this->respHeaders
;
514 * Returns the value of the given response header.
516 * @param $header String
519 public function getResponseHeader( $header ) {
520 if ( !$this->respHeaders
) {
521 $this->parseHeader();
524 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
525 $v = $this->respHeaders
[strtolower ( $header ) ];
526 return $v[count( $v ) - 1];
533 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
535 * @param $jar CookieJar
537 public function setCookieJar( $jar ) {
538 $this->cookieJar
= $jar;
542 * Returns the cookie jar in use.
546 public function getCookieJar() {
547 if ( !$this->respHeaders
) {
548 $this->parseHeader();
551 return $this->cookieJar
;
555 * Sets a cookie. Used before a request to set up any individual
556 * cookies. Used internally after a request to parse the
557 * Set-Cookie headers.
563 public function setCookie( $name, $value = null, $attr = null ) {
564 if ( !$this->cookieJar
) {
565 $this->cookieJar
= new CookieJar
;
568 $this->cookieJar
->setCookie( $name, $value, $attr );
572 * Parse the cookies in the response headers and store them in the cookie jar.
574 protected function parseCookies() {
575 if ( !$this->cookieJar
) {
576 $this->cookieJar
= new CookieJar
;
579 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
580 $url = parse_url( $this->getFinalUrl() );
581 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
582 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
588 * Returns the final URL after all redirections.
590 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
591 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
593 * Note that the multiple Location: headers are an artifact of CURL -- they
594 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
595 * taken care of (high-level redirect handling rewrite).
599 public function getFinalUrl() {
600 $headers = $this->getResponseHeaders();
602 //return full url (fix for incorrect but handled relative location)
603 if ( isset( $headers[ 'location' ] ) ) {
604 $locations = $headers[ 'location' ];
606 $foundRelativeURI = false;
607 $countLocations = count($locations);
609 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
610 $url = parse_url( $locations[ $i ] );
612 if ( isset($url[ 'host' ]) ) {
613 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
614 break; //found correct URI (with host)
616 $foundRelativeURI = true;
620 if ( $foundRelativeURI ) {
622 return $domain . $locations[ $countLocations - 1 ];
624 $url = parse_url( $this->url
);
625 if ( isset($url[ 'host' ]) ) {
626 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
630 return $locations[ $countLocations - 1 ];
638 * Returns true if the backend can follow redirects. Overridden by the
642 public function canFollowRedirects() {
648 * MWHttpRequest implemented using internal curl compiled into PHP
650 class CurlHttpRequest
extends MWHttpRequest
{
651 const SUPPORTS_FILE_POSTS
= true;
653 static $curlMessageMap = array(
654 6 => 'http-host-unreachable',
655 28 => 'http-timed-out'
658 protected $curlOptions = array();
659 protected $headerText = "";
666 protected function readHeader( $fh, $content ) {
667 $this->headerText
.= $content;
668 return strlen( $content );
671 public function execute() {
674 if ( !$this->status
->isOK() ) {
675 return $this->status
;
678 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
679 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
680 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
681 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
682 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
683 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
684 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
686 /* not sure these two are actually necessary */
687 if ( isset( $this->reqHeaders
['Referer'] ) ) {
688 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
690 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
692 if ( isset( $this->sslVerifyHost
) ) {
693 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
696 if ( isset( $this->sslVerifyCert
) ) {
697 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
700 if ( $this->caInfo
) {
701 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
704 if ( $this->headersOnly
) {
705 $this->curlOptions
[CURLOPT_NOBODY
] = true;
706 $this->curlOptions
[CURLOPT_HEADER
] = true;
707 } elseif ( $this->method
== 'POST' ) {
708 $this->curlOptions
[CURLOPT_POST
] = true;
709 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
710 // Suppress 'Expect: 100-continue' header, as some servers
711 // will reject it with a 417 and Curl won't auto retry
712 // with HTTP 1.0 fallback
713 $this->reqHeaders
['Expect'] = '';
715 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
718 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
720 $curlHandle = curl_init( $this->url
);
722 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
723 throw new MWException( "Error setting curl options." );
726 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
727 wfSuppressWarnings();
728 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
729 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
730 "Probably safe_mode or open_basedir is set.\n" );
731 // Continue the processing. If it were in curl_setopt_array,
732 // processing would have halted on its entry
737 if ( false === curl_exec( $curlHandle ) ) {
738 $code = curl_error( $curlHandle );
740 if ( isset( self
::$curlMessageMap[$code] ) ) {
741 $this->status
->fatal( self
::$curlMessageMap[$code] );
743 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
746 $this->headerList
= explode( "\r\n", $this->headerText
);
749 curl_close( $curlHandle );
751 $this->parseHeader();
754 return $this->status
;
760 public function canFollowRedirects() {
761 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
762 wfDebug( "Cannot follow redirects in safe mode\n" );
766 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
767 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
775 class PhpHttpRequest
extends MWHttpRequest
{
781 protected function urlToTcp( $url ) {
782 $parsedUrl = parse_url( $url );
784 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
787 public function execute() {
790 if ( is_array( $this->postData
) ) {
791 $this->postData
= wfArrayToCGI( $this->postData
);
794 if ( $this->parsedUrl
['scheme'] != 'http' &&
795 $this->parsedUrl
['scheme'] != 'https' ) {
796 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
799 $this->reqHeaders
['Accept'] = "*/*";
800 if ( $this->method
== 'POST' ) {
801 // Required for HTTP 1.0 POSTs
802 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
803 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
807 if ( $this->proxy
) {
808 $options['proxy'] = $this->urlToTCP( $this->proxy
);
809 $options['request_fulluri'] = true;
812 if ( !$this->followRedirects
) {
813 $options['max_redirects'] = 0;
815 $options['max_redirects'] = $this->maxRedirects
;
818 $options['method'] = $this->method
;
819 $options['header'] = implode( "\r\n", $this->getHeaderList() );
820 // Note that at some future point we may want to support
821 // HTTP/1.1, but we'd have to write support for chunking
822 // in version of PHP < 5.3.1
823 $options['protocol_version'] = "1.0";
825 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
826 // Only works on 5.2.10+
827 $options['ignore_errors'] = true;
829 if ( $this->postData
) {
830 $options['content'] = $this->postData
;
833 $options['timeout'] = $this->timeout
;
835 $context = stream_context_create( array( 'http' => $options ) );
837 $this->headerList
= array();
845 wfSuppressWarnings();
846 $fh = fopen( $url, "r", false, $context );
853 $result = stream_get_meta_data( $fh );
854 $this->headerList
= $result['wrapper_data'];
855 $this->parseHeader();
857 if ( !$this->followRedirects
) {
861 # Handle manual redirection
862 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
865 # Check security of URL
866 $url = $this->getResponseHeader( "Location" );
868 if ( !Http
::isValidURI( $url ) ) {
869 wfDebug( __METHOD__
. ": insecure redirection\n" );
876 if ( $fh === false ) {
877 $this->status
->fatal( 'http-request-error' );
878 return $this->status
;
881 if ( $result['timed_out'] ) {
882 $this->status
->fatal( 'http-timed-out', $this->url
);
883 return $this->status
;
886 // If everything went OK, or we recieved some error code
887 // get the response body content.
888 if ( $this->status
->isOK()
889 ||
(int)$this->respStatus
>= 300) {
890 while ( !feof( $fh ) ) {
891 $buf = fread( $fh, 8192 );
893 if ( $buf === false ) {
894 $this->status
->fatal( 'http-read-error' );
898 if ( strlen( $buf ) ) {
899 call_user_func( $this->callback
, $fh, $buf );
905 return $this->status
;