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 wfDebug( "HTTP: $method: $url\n" );
36 $options['method'] = strtoupper( $method );
38 if ( !isset( $options['timeout'] ) ) {
39 $options['timeout'] = 'default';
42 $req = MWHttpRequest
::factory( $url, $options );
43 $status = $req->execute();
45 if ( $status->isOK() ) {
46 return $req->getContent();
53 * Simple wrapper for Http::request( 'GET' )
54 * @see Http::request()
57 * @param $timeout string
58 * @param $options array
61 public static function get( $url, $timeout = 'default', $options = array() ) {
62 $options['timeout'] = $timeout;
63 return Http
::request( 'GET', $url, $options );
67 * Simple wrapper for Http::request( 'POST' )
68 * @see Http::request()
71 * @param $options array
74 public static function post( $url, $options = array() ) {
75 return Http
::request( 'POST', $url, $options );
79 * Check if the URL can be served by localhost
81 * @param $url String: full url to check
84 public static function isLocalURL( $url ) {
85 global $wgCommandLineMode, $wgConf;
87 if ( $wgCommandLineMode ) {
93 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
96 $domainParts = explode( '.', $host );
97 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
98 $domainParts = array_reverse( $domainParts );
101 for ( $i = 0; $i < count( $domainParts ); $i++
) {
102 $domainPart = $domainParts[$i];
104 $domain = $domainPart;
106 $domain = $domainPart . '.' . $domain;
109 if ( $wgConf->isLocalVHost( $domain ) ) {
119 * A standard user-agent we can use for external requests.
122 public static function userAgent() {
124 return "MediaWiki/$wgVersion";
128 * Checks that the given URI is a valid one. Hardcoding the
129 * protocols, because we only want protocols that both cURL
132 * @fixme this is wildly inaccurate and fails to actually check most stuff
134 * @param $uri Mixed: URI to check for validity
137 public static function isValidURI( $uri ) {
139 '/^https?:\/\/[^\/\s]\S*$/D',
146 * This wrapper class will call out to curl (if available) or fallback
147 * to regular PHP if necessary for handling internal HTTP requests.
149 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
150 * PHP's HTTP extension.
152 class MWHttpRequest
{
153 const SUPPORTS_FILE_POSTS
= false;
156 protected $timeout = 'default';
157 protected $headersOnly = null;
158 protected $postData = null;
159 protected $proxy = null;
160 protected $noProxy = false;
161 protected $sslVerifyHost = true;
162 protected $sslVerifyCert = true;
163 protected $caInfo = null;
164 protected $method = "GET";
165 protected $reqHeaders = array();
167 protected $parsedUrl;
169 protected $maxRedirects = 5;
170 protected $followRedirects = false;
175 protected $cookieJar;
177 protected $headerList = array();
178 protected $respVersion = "0.9";
179 protected $respStatus = "200 Ok";
180 protected $respHeaders = array();
185 * @param $url String: url to use. If protocol-relative, will be expanded to an http:// URL
186 * @param $options Array: (optional) extra params to pass (see Http::request())
188 function __construct( $url, $options = array() ) {
189 global $wgHTTPTimeout;
191 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
192 $this->parsedUrl
= wfParseUrl( $this->url
);
194 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
195 $this->status
= Status
::newFatal( 'http-invalid-url' );
197 $this->status
= Status
::newGood( 100 ); // continue
200 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
201 $this->timeout
= $options['timeout'];
203 $this->timeout
= $wgHTTPTimeout;
206 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
207 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
209 foreach ( $members as $o ) {
210 if ( isset( $options[$o] ) ) {
211 $this->$o = $options[$o];
217 * Simple function to test if we can make any sort of requests at all, using
221 public static function canMakeRequests() {
222 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
226 * Generate a new request object
227 * @param $url String: url to use
228 * @param $options Array: (optional) extra params to pass (see Http::request())
229 * @return \CurlHttpRequest|\PhpHttpRequest
230 * @see MWHttpRequest::__construct
232 public static function factory( $url, $options = null ) {
233 if ( !Http
::$httpEngine ) {
234 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
235 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
236 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
237 ' Http::$httpEngine is set to "curl"' );
240 switch( Http
::$httpEngine ) {
242 return new CurlHttpRequest( $url, $options );
244 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
245 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
246 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
248 return new PhpHttpRequest( $url, $options );
250 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
255 * Get the body, or content, of the response to the request
259 public function getContent() {
260 return $this->content
;
264 * Set the parameters of the request
267 * @todo overload the args param
269 public function setData( $args ) {
270 $this->postData
= $args;
274 * Take care of setting up the proxy
275 * (override in subclass)
279 public function proxySetup() {
282 if ( $this->proxy
) {
286 if ( Http
::isLocalURL( $this->url
) ) {
288 } elseif ( $wgHTTPProxy ) {
289 $this->proxy
= $wgHTTPProxy ;
290 } elseif ( getenv( "http_proxy" ) ) {
291 $this->proxy
= getenv( "http_proxy" );
296 * Set the refererer header
298 public function setReferer( $url ) {
299 $this->setHeader( 'Referer', $url );
306 public function setUserAgent( $UA ) {
307 $this->setHeader( 'User-Agent', $UA );
311 * Set an arbitrary header
315 public function setHeader( $name, $value ) {
316 // I feel like I should normalize the case here...
317 $this->reqHeaders
[$name] = $value;
321 * Get an array of the headers
324 public function getHeaderList() {
327 if ( $this->cookieJar
) {
328 $this->reqHeaders
['Cookie'] =
329 $this->cookieJar
->serializeToHttpRequest(
330 $this->parsedUrl
['path'],
331 $this->parsedUrl
['host']
335 foreach ( $this->reqHeaders
as $name => $value ) {
336 $list[] = "$name: $value";
343 * Set a read callback to accept data read from the HTTP request.
344 * By default, data is appended to an internal buffer which can be
345 * retrieved through $req->getContent().
347 * To handle data as it comes in -- especially for large files that
348 * would not fit in memory -- you can instead set your own callback,
349 * in the form function($resource, $buffer) where the first parameter
350 * is the low-level resource being read (implementation specific),
351 * and the second parameter is the data buffer.
353 * You MUST return the number of bytes handled in the buffer; if fewer
354 * bytes are reported handled than were passed to you, the HTTP fetch
357 * @param $callback Callback
359 public function setCallback( $callback ) {
360 if ( !is_callable( $callback ) ) {
361 throw new MWException( 'Invalid MwHttpRequest callback' );
363 $this->callback
= $callback;
367 * A generic callback to read the body of the response from a remote
371 * @param $content String
373 public function read( $fh, $content ) {
374 $this->content
.= $content;
375 return strlen( $content );
379 * Take care of whatever is necessary to perform the URI request.
383 public function execute() {
388 if ( strtoupper( $this->method
) == "HEAD" ) {
389 $this->headersOnly
= true;
392 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
393 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
396 if ( !$this->noProxy
) {
400 if ( !$this->callback
) {
401 $this->setCallback( array( $this, 'read' ) );
404 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
405 $this->setUserAgent( Http
::userAgent() );
410 * Parses the headers, including the HTTP status code and any
411 * Set-Cookie headers. This function expectes the headers to be
412 * found in an array in the member variable headerList.
416 protected function parseHeader() {
419 foreach ( $this->headerList
as $header ) {
420 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
421 $this->respVersion
= $match[1];
422 $this->respStatus
= $match[2];
423 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
424 $last = count( $this->respHeaders
[$lastname] ) - 1;
425 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
426 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
427 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
428 $lastname = strtolower( $match[1] );
432 $this->parseCookies();
436 * Sets HTTPRequest status member to a fatal value with the error
437 * message if the returned integer value of the status code was
438 * not successful (< 300) or a redirect (>=300 and < 400). (see
439 * RFC2616, section 10,
440 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
441 * list of status codes.)
445 protected function setStatus() {
446 if ( !$this->respHeaders
) {
447 $this->parseHeader();
450 if ( (int)$this->respStatus
> 399 ) {
451 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
452 $this->status
->fatal( "http-bad-status", $code, $message );
457 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
458 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
459 * for a list of status codes.)
463 public function getStatus() {
464 if ( !$this->respHeaders
) {
465 $this->parseHeader();
468 return (int)$this->respStatus
;
473 * Returns true if the last status code was a redirect.
477 public function isRedirect() {
478 if ( !$this->respHeaders
) {
479 $this->parseHeader();
482 $status = (int)$this->respStatus
;
484 if ( $status >= 300 && $status <= 303 ) {
492 * Returns an associative array of response headers after the
493 * request has been executed. Because some headers
494 * (e.g. Set-Cookie) can appear more than once the, each value of
495 * the associative array is an array of the values given.
499 public function getResponseHeaders() {
500 if ( !$this->respHeaders
) {
501 $this->parseHeader();
504 return $this->respHeaders
;
508 * Returns the value of the given response header.
510 * @param $header String
513 public function getResponseHeader( $header ) {
514 if ( !$this->respHeaders
) {
515 $this->parseHeader();
518 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
519 $v = $this->respHeaders
[strtolower ( $header ) ];
520 return $v[count( $v ) - 1];
527 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
529 * @param $jar CookieJar
531 public function setCookieJar( $jar ) {
532 $this->cookieJar
= $jar;
536 * Returns the cookie jar in use.
540 public function getCookieJar() {
541 if ( !$this->respHeaders
) {
542 $this->parseHeader();
545 return $this->cookieJar
;
549 * Sets a cookie. Used before a request to set up any individual
550 * cookies. Used internally after a request to parse the
551 * Set-Cookie headers.
557 public function setCookie( $name, $value = null, $attr = null ) {
558 if ( !$this->cookieJar
) {
559 $this->cookieJar
= new CookieJar
;
562 $this->cookieJar
->setCookie( $name, $value, $attr );
566 * Parse the cookies in the response headers and store them in the cookie jar.
568 protected function parseCookies() {
569 if ( !$this->cookieJar
) {
570 $this->cookieJar
= new CookieJar
;
573 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
574 $url = parse_url( $this->getFinalUrl() );
575 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
576 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
582 * Returns the final URL after all redirections.
584 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
585 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
589 public function getFinalUrl() {
590 $headers = $this->getResponseHeaders();
592 //return full url (fix for incorrect but handled relative location)
593 if ( isset( $headers[ 'location' ] ) ) {
594 $locations = $headers[ 'location' ];
596 $foundRelativeURI = false;
597 $countLocations = count($locations);
599 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
600 $url = parse_url( $locations[ $i ] );
602 if ( isset($url[ 'host' ]) ) {
603 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
604 break; //found correct URI (with host)
606 $foundRelativeURI = true;
610 if ( $foundRelativeURI ) {
612 return $domain . $locations[ $countLocations - 1 ];
614 $url = parse_url( $this->url
);
615 if ( isset($url[ 'host' ]) ) {
616 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
620 return $locations[ $countLocations - 1 ];
628 * Returns true if the backend can follow redirects. Overridden by the
632 public function canFollowRedirects() {
638 * MWHttpRequest implemented using internal curl compiled into PHP
640 class CurlHttpRequest
extends MWHttpRequest
{
641 const SUPPORTS_FILE_POSTS
= true;
643 static $curlMessageMap = array(
644 6 => 'http-host-unreachable',
645 28 => 'http-timed-out'
648 protected $curlOptions = array();
649 protected $headerText = "";
656 protected function readHeader( $fh, $content ) {
657 $this->headerText
.= $content;
658 return strlen( $content );
661 public function execute() {
664 if ( !$this->status
->isOK() ) {
665 return $this->status
;
668 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
669 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
670 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
671 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
672 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
673 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
674 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
676 /* not sure these two are actually necessary */
677 if ( isset( $this->reqHeaders
['Referer'] ) ) {
678 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
680 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
682 if ( isset( $this->sslVerifyHost
) ) {
683 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
686 if ( isset( $this->sslVerifyCert
) ) {
687 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
690 if ( $this->caInfo
) {
691 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
694 if ( $this->headersOnly
) {
695 $this->curlOptions
[CURLOPT_NOBODY
] = true;
696 $this->curlOptions
[CURLOPT_HEADER
] = true;
697 } elseif ( $this->method
== 'POST' ) {
698 $this->curlOptions
[CURLOPT_POST
] = true;
699 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
700 // Suppress 'Expect: 100-continue' header, as some servers
701 // will reject it with a 417 and Curl won't auto retry
702 // with HTTP 1.0 fallback
703 $this->reqHeaders
['Expect'] = '';
705 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
708 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
710 $curlHandle = curl_init( $this->url
);
712 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
713 throw new MWException( "Error setting curl options." );
716 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
717 wfSuppressWarnings();
718 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
719 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
720 "Probably safe_mode or open_basedir is set.\n" );
721 // Continue the processing. If it were in curl_setopt_array,
722 // processing would have halted on its entry
727 if ( false === curl_exec( $curlHandle ) ) {
728 $code = curl_error( $curlHandle );
730 if ( isset( self
::$curlMessageMap[$code] ) ) {
731 $this->status
->fatal( self
::$curlMessageMap[$code] );
733 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
736 $this->headerList
= explode( "\r\n", $this->headerText
);
739 curl_close( $curlHandle );
741 $this->parseHeader();
744 return $this->status
;
750 public function canFollowRedirects() {
751 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
752 wfDebug( "Cannot follow redirects in safe mode\n" );
756 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
757 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
765 class PhpHttpRequest
extends MWHttpRequest
{
771 protected function urlToTcp( $url ) {
772 $parsedUrl = parse_url( $url );
774 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
777 public function execute() {
780 if ( is_array( $this->postData
) ) {
781 $this->postData
= wfArrayToCGI( $this->postData
);
784 if ( $this->parsedUrl
['scheme'] != 'http' &&
785 $this->parsedUrl
['scheme'] != 'https' ) {
786 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
789 $this->reqHeaders
['Accept'] = "*/*";
790 if ( $this->method
== 'POST' ) {
791 // Required for HTTP 1.0 POSTs
792 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
793 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
797 if ( $this->proxy
&& !$this->noProxy
) {
798 $options['proxy'] = $this->urlToTCP( $this->proxy
);
799 $options['request_fulluri'] = true;
802 if ( !$this->followRedirects
) {
803 $options['max_redirects'] = 0;
805 $options['max_redirects'] = $this->maxRedirects
;
808 $options['method'] = $this->method
;
809 $options['header'] = implode( "\r\n", $this->getHeaderList() );
810 // Note that at some future point we may want to support
811 // HTTP/1.1, but we'd have to write support for chunking
812 // in version of PHP < 5.3.1
813 $options['protocol_version'] = "1.0";
815 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
816 // Only works on 5.2.10+
817 $options['ignore_errors'] = true;
819 if ( $this->postData
) {
820 $options['content'] = $this->postData
;
823 $options['timeout'] = $this->timeout
;
825 $context = stream_context_create( array( 'http' => $options ) );
827 $this->headerList
= array();
835 wfSuppressWarnings();
836 $fh = fopen( $url, "r", false, $context );
843 $result = stream_get_meta_data( $fh );
844 $this->headerList
= $result['wrapper_data'];
845 $this->parseHeader();
847 if ( !$this->followRedirects
) {
851 # Handle manual redirection
852 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
855 # Check security of URL
856 $url = $this->getResponseHeader( "Location" );
858 if ( substr( $url, 0, 7 ) !== 'http://' ) {
859 wfDebug( __METHOD__
. ": insecure redirection\n" );
866 if ( $fh === false ) {
867 $this->status
->fatal( 'http-request-error' );
868 return $this->status
;
871 if ( $result['timed_out'] ) {
872 $this->status
->fatal( 'http-timed-out', $this->url
);
873 return $this->status
;
876 // If everything went OK, or we recieved some error code
877 // get the response body content.
878 if ( $this->status
->isOK()
879 ||
(int)$this->respStatus
>= 300) {
880 while ( !feof( $fh ) ) {
881 $buf = fread( $fh, 8192 );
883 if ( $buf === false ) {
884 $this->status
->fatal( 'http-read-error' );
888 if ( strlen( $buf ) ) {
889 call_user_func( $this->callback
, $fh, $buf );
895 return $this->status
;