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 * - userAgent A user agent, if you want to override the default
33 * MediaWiki/$wgVersion
34 * @return Mixed: (bool)false on failure or a string on success
36 public static function request( $method, $url, $options = array() ) {
37 wfDebug( "HTTP: $method: $url\n" );
38 $options['method'] = strtoupper( $method );
40 if ( !isset( $options['timeout'] ) ) {
41 $options['timeout'] = 'default';
44 $req = MWHttpRequest
::factory( $url, $options );
45 if( isset( $options['userAgent'] ) ) {
46 $req->setUserAgent( $options['userAgent'] );
48 $status = $req->execute();
50 if ( $status->isOK() ) {
51 return $req->getContent();
58 * Simple wrapper for Http::request( 'GET' )
59 * @see Http::request()
62 * @param $timeout string
63 * @param $options array
66 public static function get( $url, $timeout = 'default', $options = array() ) {
67 $options['timeout'] = $timeout;
68 return Http
::request( 'GET', $url, $options );
72 * Simple wrapper for Http::request( 'POST' )
73 * @see Http::request()
76 * @param $options array
79 public static function post( $url, $options = array() ) {
80 return Http
::request( 'POST', $url, $options );
84 * Check if the URL can be served by localhost
86 * @param $url String: full url to check
89 public static function isLocalURL( $url ) {
90 global $wgCommandLineMode, $wgConf;
92 if ( $wgCommandLineMode ) {
98 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
101 $domainParts = explode( '.', $host );
102 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
103 $domainParts = array_reverse( $domainParts );
106 for ( $i = 0; $i < count( $domainParts ); $i++
) {
107 $domainPart = $domainParts[$i];
109 $domain = $domainPart;
111 $domain = $domainPart . '.' . $domain;
114 if ( $wgConf->isLocalVHost( $domain ) ) {
124 * A standard user-agent we can use for external requests.
127 public static function userAgent() {
129 return "MediaWiki/$wgVersion";
133 * Checks that the given URI is a valid one. Hardcoding the
134 * protocols, because we only want protocols that both cURL
137 * file:// should not be allowed here for security purpose (r67684)
139 * @fixme this is wildly inaccurate and fails to actually check most stuff
141 * @param $uri Mixed: URI to check for validity
144 public static function isValidURI( $uri ) {
146 '/^https?:\/\/[^\/\s]\S*$/D',
153 * This wrapper class will call out to curl (if available) or fallback
154 * to regular PHP if necessary for handling internal HTTP requests.
156 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
157 * PHP's HTTP extension.
159 class MWHttpRequest
{
160 const SUPPORTS_FILE_POSTS
= false;
163 protected $timeout = 'default';
164 protected $headersOnly = null;
165 protected $postData = null;
166 protected $proxy = null;
167 protected $noProxy = false;
168 protected $sslVerifyHost = true;
169 protected $sslVerifyCert = true;
170 protected $caInfo = null;
171 protected $method = "GET";
172 protected $reqHeaders = array();
174 protected $parsedUrl;
176 protected $maxRedirects = 5;
177 protected $followRedirects = false;
182 protected $cookieJar;
184 protected $headerList = array();
185 protected $respVersion = "0.9";
186 protected $respStatus = "200 Ok";
187 protected $respHeaders = array();
192 * @param $url String: url to use. If protocol-relative, will be expanded to an http:// URL
193 * @param $options Array: (optional) extra params to pass (see Http::request())
195 function __construct( $url, $options = array() ) {
196 global $wgHTTPTimeout;
198 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
199 $this->parsedUrl
= wfParseUrl( $this->url
);
201 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
202 $this->status
= Status
::newFatal( 'http-invalid-url' );
204 $this->status
= Status
::newGood( 100 ); // continue
207 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
208 $this->timeout
= $options['timeout'];
210 $this->timeout
= $wgHTTPTimeout;
213 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
214 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
216 foreach ( $members as $o ) {
217 if ( isset( $options[$o] ) ) {
218 $this->$o = $options[$o];
224 * Simple function to test if we can make any sort of requests at all, using
228 public static function canMakeRequests() {
229 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
233 * Generate a new request object
234 * @param $url String: url to use
235 * @param $options Array: (optional) extra params to pass (see Http::request())
236 * @return CurlHttpRequest|PhpHttpRequest
237 * @see MWHttpRequest::__construct
239 public static function factory( $url, $options = null ) {
240 if ( !Http
::$httpEngine ) {
241 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
242 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
243 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
244 ' Http::$httpEngine is set to "curl"' );
247 switch( Http
::$httpEngine ) {
249 return new CurlHttpRequest( $url, $options );
251 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
252 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
253 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
255 return new PhpHttpRequest( $url, $options );
257 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
262 * Get the body, or content, of the response to the request
266 public function getContent() {
267 return $this->content
;
271 * Set the parameters of the request
274 * @todo overload the args param
276 public function setData( $args ) {
277 $this->postData
= $args;
281 * Take care of setting up the proxy
282 * (override in subclass)
286 public function proxySetup() {
289 if ( $this->proxy
) {
293 if ( Http
::isLocalURL( $this->url
) ) {
295 } elseif ( $wgHTTPProxy ) {
296 $this->proxy
= $wgHTTPProxy ;
297 } elseif ( getenv( "http_proxy" ) ) {
298 $this->proxy
= getenv( "http_proxy" );
303 * Set the refererer header
305 public function setReferer( $url ) {
306 $this->setHeader( 'Referer', $url );
313 public function setUserAgent( $UA ) {
314 $this->setHeader( 'User-Agent', $UA );
318 * Set an arbitrary header
322 public function setHeader( $name, $value ) {
323 // I feel like I should normalize the case here...
324 $this->reqHeaders
[$name] = $value;
328 * Get an array of the headers
331 public function getHeaderList() {
334 if ( $this->cookieJar
) {
335 $this->reqHeaders
['Cookie'] =
336 $this->cookieJar
->serializeToHttpRequest(
337 $this->parsedUrl
['path'],
338 $this->parsedUrl
['host']
342 foreach ( $this->reqHeaders
as $name => $value ) {
343 $list[] = "$name: $value";
350 * Set a read callback to accept data read from the HTTP request.
351 * By default, data is appended to an internal buffer which can be
352 * retrieved through $req->getContent().
354 * To handle data as it comes in -- especially for large files that
355 * would not fit in memory -- you can instead set your own callback,
356 * in the form function($resource, $buffer) where the first parameter
357 * is the low-level resource being read (implementation specific),
358 * and the second parameter is the data buffer.
360 * You MUST return the number of bytes handled in the buffer; if fewer
361 * bytes are reported handled than were passed to you, the HTTP fetch
364 * @param $callback Callback
366 public function setCallback( $callback ) {
367 if ( !is_callable( $callback ) ) {
368 throw new MWException( 'Invalid MwHttpRequest callback' );
370 $this->callback
= $callback;
374 * A generic callback to read the body of the response from a remote
378 * @param $content String
381 public function read( $fh, $content ) {
382 $this->content
.= $content;
383 return strlen( $content );
387 * Take care of whatever is necessary to perform the URI request.
391 public function execute() {
396 if ( strtoupper( $this->method
) == "HEAD" ) {
397 $this->headersOnly
= true;
400 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
401 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
404 if ( !$this->noProxy
) {
408 if ( !$this->callback
) {
409 $this->setCallback( array( $this, 'read' ) );
412 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
413 $this->setUserAgent( Http
::userAgent() );
418 * Parses the headers, including the HTTP status code and any
419 * Set-Cookie headers. This function expectes the headers to be
420 * found in an array in the member variable headerList.
422 protected function parseHeader() {
425 foreach ( $this->headerList
as $header ) {
426 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
427 $this->respVersion
= $match[1];
428 $this->respStatus
= $match[2];
429 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
430 $last = count( $this->respHeaders
[$lastname] ) - 1;
431 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
432 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
433 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
434 $lastname = strtolower( $match[1] );
438 $this->parseCookies();
442 * Sets HTTPRequest status member to a fatal value with the error
443 * message if the returned integer value of the status code was
444 * not successful (< 300) or a redirect (>=300 and < 400). (see
445 * RFC2616, section 10,
446 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
447 * list of status codes.)
449 protected function setStatus() {
450 if ( !$this->respHeaders
) {
451 $this->parseHeader();
454 if ( (int)$this->respStatus
> 399 ) {
455 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
456 $this->status
->fatal( "http-bad-status", $code, $message );
461 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
462 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
463 * for a list of status codes.)
467 public function getStatus() {
468 if ( !$this->respHeaders
) {
469 $this->parseHeader();
472 return (int)$this->respStatus
;
477 * Returns true if the last status code was a redirect.
481 public function isRedirect() {
482 if ( !$this->respHeaders
) {
483 $this->parseHeader();
486 $status = (int)$this->respStatus
;
488 if ( $status >= 300 && $status <= 303 ) {
496 * Returns an associative array of response headers after the
497 * request has been executed. Because some headers
498 * (e.g. Set-Cookie) can appear more than once the, each value of
499 * the associative array is an array of the values given.
503 public function getResponseHeaders() {
504 if ( !$this->respHeaders
) {
505 $this->parseHeader();
508 return $this->respHeaders
;
512 * Returns the value of the given response header.
514 * @param $header String
517 public function getResponseHeader( $header ) {
518 if ( !$this->respHeaders
) {
519 $this->parseHeader();
522 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
523 $v = $this->respHeaders
[strtolower ( $header ) ];
524 return $v[count( $v ) - 1];
531 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
533 * @param $jar CookieJar
535 public function setCookieJar( $jar ) {
536 $this->cookieJar
= $jar;
540 * Returns the cookie jar in use.
544 public function getCookieJar() {
545 if ( !$this->respHeaders
) {
546 $this->parseHeader();
549 return $this->cookieJar
;
553 * Sets a cookie. Used before a request to set up any individual
554 * cookies. Used internally after a request to parse the
555 * Set-Cookie headers.
561 public function setCookie( $name, $value = null, $attr = null ) {
562 if ( !$this->cookieJar
) {
563 $this->cookieJar
= new CookieJar
;
566 $this->cookieJar
->setCookie( $name, $value, $attr );
570 * Parse the cookies in the response headers and store them in the cookie jar.
572 protected function parseCookies() {
573 if ( !$this->cookieJar
) {
574 $this->cookieJar
= new CookieJar
;
577 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
578 $url = parse_url( $this->getFinalUrl() );
579 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
580 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
586 * Returns the final URL after all redirections.
588 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
589 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
591 * Note that the multiple Location: headers are an artifact of CURL -- they
592 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
593 * taken care of (high-level redirect handling rewrite).
597 public function getFinalUrl() {
598 $headers = $this->getResponseHeaders();
600 //return full url (fix for incorrect but handled relative location)
601 if ( isset( $headers[ 'location' ] ) ) {
602 $locations = $headers[ 'location' ];
604 $foundRelativeURI = false;
605 $countLocations = count($locations);
607 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
608 $url = parse_url( $locations[ $i ] );
610 if ( isset($url[ 'host' ]) ) {
611 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
612 break; //found correct URI (with host)
614 $foundRelativeURI = true;
618 if ( $foundRelativeURI ) {
620 return $domain . $locations[ $countLocations - 1 ];
622 $url = parse_url( $this->url
);
623 if ( isset($url[ 'host' ]) ) {
624 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
628 return $locations[ $countLocations - 1 ];
636 * Returns true if the backend can follow redirects. Overridden by the
640 public function canFollowRedirects() {
646 * MWHttpRequest implemented using internal curl compiled into PHP
648 class CurlHttpRequest
extends MWHttpRequest
{
649 const SUPPORTS_FILE_POSTS
= true;
651 static $curlMessageMap = array(
652 6 => 'http-host-unreachable',
653 28 => 'http-timed-out'
656 protected $curlOptions = array();
657 protected $headerText = "";
664 protected function readHeader( $fh, $content ) {
665 $this->headerText
.= $content;
666 return strlen( $content );
669 public function execute() {
672 if ( !$this->status
->isOK() ) {
673 return $this->status
;
676 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
677 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
678 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
679 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
680 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
681 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
682 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
684 /* not sure these two are actually necessary */
685 if ( isset( $this->reqHeaders
['Referer'] ) ) {
686 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
688 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
690 if ( isset( $this->sslVerifyHost
) ) {
691 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
694 if ( isset( $this->sslVerifyCert
) ) {
695 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
698 if ( $this->caInfo
) {
699 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
702 if ( $this->headersOnly
) {
703 $this->curlOptions
[CURLOPT_NOBODY
] = true;
704 $this->curlOptions
[CURLOPT_HEADER
] = true;
705 } elseif ( $this->method
== 'POST' ) {
706 $this->curlOptions
[CURLOPT_POST
] = true;
707 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
708 // Suppress 'Expect: 100-continue' header, as some servers
709 // will reject it with a 417 and Curl won't auto retry
710 // with HTTP 1.0 fallback
711 $this->reqHeaders
['Expect'] = '';
713 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
716 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
718 $curlHandle = curl_init( $this->url
);
720 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
721 throw new MWException( "Error setting curl options." );
724 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
725 wfSuppressWarnings();
726 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
727 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
728 "Probably safe_mode or open_basedir is set.\n" );
729 // Continue the processing. If it were in curl_setopt_array,
730 // processing would have halted on its entry
735 if ( false === curl_exec( $curlHandle ) ) {
736 $code = curl_error( $curlHandle );
738 if ( isset( self
::$curlMessageMap[$code] ) ) {
739 $this->status
->fatal( self
::$curlMessageMap[$code] );
741 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
744 $this->headerList
= explode( "\r\n", $this->headerText
);
747 curl_close( $curlHandle );
749 $this->parseHeader();
752 return $this->status
;
758 public function canFollowRedirects() {
759 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
760 wfDebug( "Cannot follow redirects in safe mode\n" );
764 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
765 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
773 class PhpHttpRequest
extends MWHttpRequest
{
779 protected function urlToTcp( $url ) {
780 $parsedUrl = parse_url( $url );
782 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
785 public function execute() {
788 if ( is_array( $this->postData
) ) {
789 $this->postData
= wfArrayToCGI( $this->postData
);
792 if ( $this->parsedUrl
['scheme'] != 'http' &&
793 $this->parsedUrl
['scheme'] != 'https' ) {
794 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
797 $this->reqHeaders
['Accept'] = "*/*";
798 if ( $this->method
== 'POST' ) {
799 // Required for HTTP 1.0 POSTs
800 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
801 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
805 if ( $this->proxy
&& !$this->noProxy
) {
806 $options['proxy'] = $this->urlToTCP( $this->proxy
);
807 $options['request_fulluri'] = true;
810 if ( !$this->followRedirects
) {
811 $options['max_redirects'] = 0;
813 $options['max_redirects'] = $this->maxRedirects
;
816 $options['method'] = $this->method
;
817 $options['header'] = implode( "\r\n", $this->getHeaderList() );
818 // Note that at some future point we may want to support
819 // HTTP/1.1, but we'd have to write support for chunking
820 // in version of PHP < 5.3.1
821 $options['protocol_version'] = "1.0";
823 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
824 // Only works on 5.2.10+
825 $options['ignore_errors'] = true;
827 if ( $this->postData
) {
828 $options['content'] = $this->postData
;
831 $options['timeout'] = $this->timeout
;
833 $context = stream_context_create( array( 'http' => $options ) );
835 $this->headerList
= array();
843 wfSuppressWarnings();
844 $fh = fopen( $url, "r", false, $context );
851 $result = stream_get_meta_data( $fh );
852 $this->headerList
= $result['wrapper_data'];
853 $this->parseHeader();
855 if ( !$this->followRedirects
) {
859 # Handle manual redirection
860 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
863 # Check security of URL
864 $url = $this->getResponseHeader( "Location" );
866 if ( !Http
::isValidURI( $url ) ) {
867 wfDebug( __METHOD__
. ": insecure redirection\n" );
874 if ( $fh === false ) {
875 $this->status
->fatal( 'http-request-error' );
876 return $this->status
;
879 if ( $result['timed_out'] ) {
880 $this->status
->fatal( 'http-timed-out', $this->url
);
881 return $this->status
;
884 // If everything went OK, or we recieved some error code
885 // get the response body content.
886 if ( $this->status
->isOK()
887 ||
(int)$this->respStatus
>= 300) {
888 while ( !feof( $fh ) ) {
889 $buf = fread( $fh, 8192 );
891 if ( $buf === false ) {
892 $this->status
->fatal( 'http-read-error' );
896 if ( strlen( $buf ) ) {
897 call_user_func( $this->callback
, $fh, $buf );
903 return $this->status
;