bd59ffe7689eb05a44885d6197fce36b5134bb16
7 * Various HTTP related functions
11 static $httpEngine = false;
14 * Perform an HTTP request
15 * @param $method string HTTP method. Usually GET/POST
16 * @param $url string Full URL to act on
17 * @param $options options to pass to HttpRequest object
18 * Possible keys for the array:
19 * timeout Timeout length in seconds
20 * postData An array of key-value pairs or a url-encoded form data
21 * proxy The proxy to use.
22 * Will use $wgHTTPProxy (if set) otherwise.
23 * noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
24 * sslVerifyHost (curl only) Verify hostname against certificate
25 * sslVerifyCert (curl only) Verify SSL certificate
26 * caInfo (curl only) Provide CA information
27 * maxRedirects Maximum number of redirects to follow (defaults to 5)
28 * followRedirects Whether to follow redirects (defaults to true)
29 * @returns mixed (bool)false on failure or a string on success
31 public static function request( $method, $url, $options = array() ) {
32 $url = wfExpandUrl( $url );
33 wfDebug( "HTTP: $method: $url" );
34 $options['method'] = strtoupper( $method );
35 if ( !isset( $options['timeout'] ) ) {
36 $options['timeout'] = 'default';
38 $req = HttpRequest
::factory( $url, $options );
39 $status = $req->execute();
40 if ( $status->isOK() ) {
41 return $req->getContent();
48 * Simple wrapper for Http::request( 'GET' )
49 * @see Http::request()
51 public static function get( $url, $timeout = 'default', $options = array() ) {
52 $options['timeout'] = $timeout;
53 return Http
::request( 'GET', $url, $options );
57 * Simple wrapper for Http::request( 'POST' )
58 * @see Http::request()
60 public static function post( $url, $options = array() ) {
61 return Http
::request( 'POST', $url, $options );
65 * Check if the URL can be served by localhost
66 * @param $url string Full url to check
69 public static function isLocalURL( $url ) {
70 global $wgCommandLineMode, $wgConf;
71 if ( $wgCommandLineMode ) {
77 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
80 $domainParts = explode( '.', $host );
81 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
82 $domainParts = array_reverse( $domainParts );
83 for ( $i = 0; $i < count( $domainParts ); $i++
) {
84 $domainPart = $domainParts[$i];
86 $domain = $domainPart;
88 $domain = $domainPart . '.' . $domain;
90 if ( $wgConf->isLocalVHost( $domain ) ) {
99 * A standard user-agent we can use for external requests.
102 public static function userAgent() {
104 return "MediaWiki/$wgVersion";
108 * Checks that the given URI is a valid one
109 * @param $uri Mixed: URI to check for validity
112 public static function isValidURI( $uri ) {
114 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
122 * This wrapper class will call out to curl (if available) or fallback
123 * to regular PHP if necessary for handling internal HTTP requests.
127 protected $timeout = 'default';
128 protected $headersOnly = null;
129 protected $postData = null;
130 protected $proxy = null;
131 protected $noProxy = false;
132 protected $sslVerifyHost = true;
133 protected $sslVerifyCert = true;
134 protected $caInfo = null;
135 protected $method = "GET";
136 protected $reqHeaders = array();
138 protected $parsedUrl;
140 protected $maxRedirects = 5;
141 protected $followRedirects = true;
143 protected $cookieJar;
145 protected $headerList = array();
146 protected $respVersion = "0.9";
147 protected $respStatus = "200 Ok";
148 protected $respHeaders = array();
153 * @param $url string url to use
154 * @param $options array (optional) extra params to pass (see Http::request())
156 function __construct( $url, $options = array() ) {
157 global $wgHTTPTimeout;
160 $this->parsedUrl
= parse_url( $url );
162 if ( !Http
::isValidURI( $this->url
) ) {
163 $this->status
= Status
::newFatal('http-invalid-url');
165 $this->status
= Status
::newGood( 100 ); // continue
168 if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
169 $this->timeout
= $options['timeout'];
171 $this->timeout
= $wgHTTPTimeout;
174 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
175 "method", "followRedirects", "maxRedirects", "sslVerifyCert" );
176 foreach ( $members as $o ) {
177 if ( isset($options[$o]) ) {
178 $this->$o = $options[$o];
184 * Generate a new request object
185 * @see HttpRequest::__construct
187 public static function factory( $url, $options = null ) {
188 if ( !Http
::$httpEngine ) {
189 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
190 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
191 throw new MWException( __METHOD__
.': curl (http://php.net/curl) is not installed, but'.
192 ' Http::$httpEngine is set to "curl"' );
195 switch( Http
::$httpEngine ) {
197 return new CurlHttpRequest( $url, $options );
199 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
200 throw new MWException( __METHOD__
.': allow_url_fopen needs to be enabled for pure PHP'.
201 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
203 return new PhpHttpRequest( $url, $options );
205 throw new MWException( __METHOD__
.': The setting of Http::$httpEngine is not valid.' );
210 * Get the body, or content, of the response to the request
213 public function getContent() {
214 return $this->content
;
218 * Set the parameters of the request
219 * @param $params array
220 * @todo overload the args param
222 public function setData($args) {
223 $this->postData
= $args;
227 * Take care of setting up the proxy
228 * (override in subclass)
231 public function proxySetup() {
234 if ( $this->proxy
) {
237 if ( Http
::isLocalURL( $this->url
) ) {
238 $this->proxy
= 'http://localhost:80/';
239 } elseif ( $wgHTTPProxy ) {
240 $this->proxy
= $wgHTTPProxy ;
241 } elseif ( getenv( "http_proxy" ) ) {
242 $this->proxy
= getenv( "http_proxy" );
247 * Set the refererer header
249 public function setReferer( $url ) {
250 $this->setHeader('Referer', $url);
256 public function setUserAgent( $UA ) {
257 $this->setHeader('User-Agent', $UA);
261 * Set an arbitrary header
263 public function setHeader($name, $value) {
264 // I feel like I should normalize the case here...
265 $this->reqHeaders
[$name] = $value;
269 * Get an array of the headers
271 public function getHeaderList() {
274 if( $this->cookieJar
) {
275 $this->reqHeaders
['Cookie'] =
276 $this->cookieJar
->serializeToHttpRequest($this->parsedUrl
['path'],
277 $this->parsedUrl
['host']);
279 foreach($this->reqHeaders
as $name => $value) {
280 $list[] = "$name: $value";
287 * @param $callback callback
289 public function setCallback( $callback ) {
290 $this->callback
= $callback;
294 * A generic callback to read the body of the response from a remote
297 * @param $content string
299 public function read( $fh, $content ) {
300 $this->content
.= $content;
301 return strlen( $content );
305 * Take care of whatever is necessary to perform the URI request.
308 public function execute() {
313 if( strtoupper($this->method
) == "HEAD" ) {
314 $this->headersOnly
= true;
317 if ( is_array( $this->postData
) ) {
318 $this->postData
= wfArrayToCGI( $this->postData
);
321 if ( is_object( $wgTitle ) && !isset($this->reqHeaders
['Referer']) ) {
322 $this->setReferer( $wgTitle->getFullURL() );
325 if ( !$this->noProxy
) {
329 if ( !$this->callback
) {
330 $this->setCallback( array( $this, 'read' ) );
333 if ( !isset($this->reqHeaders
['User-Agent']) ) {
334 $this->setUserAgent(Http
::userAgent());
339 * Parses the headers, including the HTTP status code and any
340 * Set-Cookie headers. This function expectes the headers to be
341 * found in an array in the member variable headerList.
344 protected function parseHeader() {
346 foreach( $this->headerList
as $header ) {
347 if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
348 $this->respVersion
= $match[1];
349 $this->respStatus
= $match[2];
350 } elseif( preg_match( "#^[ \t]#", $header ) ) {
351 $last = count($this->respHeaders
[$lastname]) - 1;
352 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
353 } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
354 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
355 $lastname = strtolower( $match[1] );
359 $this->parseCookies();
363 * Sets the member variable status to a fatal status if the HTTP
364 * status code was not 200.
367 protected function setStatus() {
368 if( !$this->respHeaders
) {
369 $this->parseHeader();
372 if((int)$this->respStatus
!== 200) {
373 list( $code, $message ) = explode(" ", $this->respStatus
, 2);
374 $this->status
->fatal("http-bad-status", $code, $message );
380 * Returns true if the last status code was a redirect.
383 public function isRedirect() {
384 if( !$this->respHeaders
) {
385 $this->parseHeader();
388 $status = (int)$this->respStatus
;
389 if ( $status >= 300 && $status < 400 ) {
396 * Returns an associative array of response headers after the
397 * request has been executed. Because some headers
398 * (e.g. Set-Cookie) can appear more than once the, each value of
399 * the associative array is an array of the values given.
402 public function getResponseHeaders() {
403 if( !$this->respHeaders
) {
404 $this->parseHeader();
406 return $this->respHeaders
;
410 * Returns the value of the given response header.
411 * @param $header string
414 public function getResponseHeader($header) {
415 if( !$this->respHeaders
) {
416 $this->parseHeader();
418 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
419 $v = $this->respHeaders
[strtolower ( $header ) ];
420 return $v[count( $v ) - 1];
426 * Tells the HttpRequest object to use this pre-loaded CookieJar.
427 * @param $jar CookieJar
429 public function setCookieJar( $jar ) {
430 $this->cookieJar
= $jar;
434 * Returns the cookie jar in use.
437 public function getCookieJar() {
438 if( !$this->respHeaders
) {
439 $this->parseHeader();
441 return $this->cookieJar
;
445 * Sets a cookie. Used before a request to set up any individual
446 * cookies. Used internally after a request to parse the
447 * Set-Cookie headers.
450 public function setCookie( $name, $value = null, $attr = null) {
451 if( !$this->cookieJar
) {
452 $this->cookieJar
= new CookieJar
;
454 $this->cookieJar
->setCookie($name, $value, $attr);
458 * Parse the cookies in the response headers and store them in the cookie jar.
460 protected function parseCookies() {
461 if( !$this->cookieJar
) {
462 $this->cookieJar
= new CookieJar
;
464 if( isset( $this->respHeaders
['set-cookie'] ) ) {
465 $url = parse_url( $this->getFinalUrl() );
466 foreach( $this->respHeaders
['set-cookie'] as $cookie ) {
467 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
473 * Returns the final URL after all redirections.
476 public function getFinalUrl() {
477 $location = $this->getResponseHeader("Location");
493 protected $isSessionKey = true;
494 // TO IMPLEMENT protected $secure
495 // TO IMPLEMENT? protected $maxAge (add onto expires)
496 // TO IMPLEMENT? protected $version
497 // TO IMPLEMENT? protected $comment
499 function __construct( $name, $value, $attr ) {
501 $this->set( $value, $attr );
505 * Sets a cookie. Used before a request to set up any individual
506 * cookies. Used internally after a request to parse the
507 * Set-Cookie headers.
508 * @param $name string the name of the cookie
509 * @param $value string the value of the cookie
510 * @param $attr array possible key/values:
511 * expires A date string
512 * path The path this cookie is used on
513 * domain Domain this cookie is used on
515 public function set( $value, $attr ) {
516 $this->value
= $value;
517 if( isset( $attr['expires'] ) ) {
518 $this->isSessionKey
= false;
519 $this->expires
= strtotime( $attr['expires'] );
521 if( isset( $attr['path'] ) ) {
522 $this->path
= $attr['path'];
526 if( isset( $attr['domain'] ) ) {
527 if( self
::validateCookieDomain( $attr['domain'] ) ) {
528 $this->domain
= $attr['domain'];
531 throw new MWException("You must specify a domain.");
536 * Return the true if the cookie is valid is valid. Otherwise,
537 * false. The uses a method similar to IE cookie security
539 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
540 * A better method might be to use a blacklist like
541 * http://publicsuffix.org/
543 * @param $domain string the domain to validate
544 * @param $originDomain string (optional) the domain the cookie originates from
547 public static function validateCookieDomain( $domain, $originDomain = null) {
548 // Don't allow a trailing dot
549 if( substr( $domain, -1 ) == "." ) return false;
551 $dc = explode(".", $domain);
553 // Don't allow cookies for "localhost", "ls" or other dot-less hosts
554 if( count($dc) < 2 ) return false;
556 // Only allow full, valid IP addresses
557 if( preg_match( '/^[0-9.]+$/', $domain ) ) {
558 if( count( $dc ) != 4 ) return false;
560 if( ip2long( $domain ) === false ) return false;
562 if( $originDomain == null ||
$originDomain == $domain ) return true;
566 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
567 if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
568 if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
569 ||
(count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
572 if( (count($dc) == 2 ||
(count($dc) == 3 && $dc[0] == "") )
573 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
578 if( $originDomain != null ) {
579 if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
582 if( substr( $domain, 0, 1 ) == "."
583 && substr_compare( $originDomain, $domain, -strlen( $domain ),
584 strlen( $domain ), TRUE ) != 0 ) {
593 * Serialize the cookie jar into a format useful for HTTP Request headers.
594 * @param $path string the path that will be used. Required.
595 * @param $domain string the domain that will be used. Required.
598 public function serializeToHttpRequest( $path, $domain ) {
601 if( $this->canServeDomain( $domain )
602 && $this->canServePath( $path )
603 && $this->isUnExpired() ) {
604 $ret = $this->name
."=". $this->value
;
610 protected function canServeDomain( $domain ) {
611 if( $domain == $this->domain
612 ||
( strlen( $domain) > strlen( $this->domain
)
613 && substr( $this->domain
, 0, 1) == "."
614 && substr_compare( $domain, $this->domain
, -strlen( $this->domain
),
615 strlen( $this->domain
), TRUE ) == 0 ) ) {
621 protected function canServePath( $path ) {
622 if( $this->path
&& substr_compare( $this->path
, $path, 0, strlen( $this->path
) ) == 0 ) {
628 protected function isUnExpired() {
629 if( $this->isSessionKey ||
$this->expires
> time() ) {
638 private $cookie = array();
641 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
644 public function setCookie ($name, $value, $attr) {
645 /* cookies: case insensitive, so this should work.
646 * We'll still send the cookies back in the same case we got them, though.
648 $index = strtoupper($name);
649 if( isset( $this->cookie
[$index] ) ) {
650 $this->cookie
[$index]->set( $value, $attr );
652 $this->cookie
[$index] = new Cookie( $name, $value, $attr );
657 * @see Cookie::serializeToHttpRequest
659 public function serializeToHttpRequest( $path, $domain ) {
662 foreach( $this->cookie
as $c ) {
663 $serialized = $c->serializeToHttpRequest( $path, $domain );
664 if ( $serialized ) $cookies[] = $serialized;
667 return implode("; ", $cookies);
671 * Parse the content of an Set-Cookie HTTP Response header.
672 * @param $cookie string
674 public function parseCookieResponseHeader ( $cookie, $domain ) {
675 $len = strlen( "Set-Cookie:" );
676 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
677 $cookie = substr( $cookie, $len );
680 $bit = array_map( 'trim', explode( ";", $cookie ) );
681 if ( count($bit) >= 1 ) {
682 list($name, $value) = explode( "=", array_shift( $bit ), 2 );
684 foreach( $bit as $piece ) {
685 $parts = explode( "=", $piece );
686 if( count( $parts ) > 1 ) {
687 $attr[strtolower( $parts[0] )] = $parts[1];
689 $attr[strtolower( $parts[0] )] = true;
693 if( !isset( $attr['domain'] ) ) {
694 $attr['domain'] = $domain;
695 } elseif ( !Cookie
::validateCookieDomain( $attr['domain'], $domain ) ) {
699 $this->setCookie( $name, $value, $attr );
706 * HttpRequest implemented using internal curl compiled into PHP
708 class CurlHttpRequest
extends HttpRequest
{
709 static $curlMessageMap = array(
710 6 => 'http-host-unreachable',
711 28 => 'http-timed-out'
714 protected $curlOptions = array();
715 protected $headerText = "";
717 protected function readHeader( $fh, $content ) {
718 $this->headerText
.= $content;
719 return strlen( $content );
722 public function execute() {
724 if ( !$this->status
->isOK() ) {
725 return $this->status
;
727 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
728 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
729 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
730 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
731 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array($this, "readHeader");
732 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
733 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
735 /* not sure these two are actually necessary */
736 if(isset($this->reqHeaders
['Referer'])) {
737 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
739 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
741 if ( isset( $this->sslVerifyHost
) ) {
742 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
745 if ( isset( $this->sslVerifyCert
) ) {
746 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
749 if ( $this->caInfo
) {
750 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
753 if ( $this->headersOnly
) {
754 $this->curlOptions
[CURLOPT_NOBODY
] = true;
755 $this->curlOptions
[CURLOPT_HEADER
] = true;
756 } elseif ( $this->method
== 'POST' ) {
757 $this->curlOptions
[CURLOPT_POST
] = true;
758 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
759 // Suppress 'Expect: 100-continue' header, as some servers
760 // will reject it with a 417 and Curl won't auto retry
761 // with HTTP 1.0 fallback
762 $this->reqHeaders
['Expect'] = '';
764 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
767 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
769 $curlHandle = curl_init( $this->url
);
770 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
771 throw new MWException("Error setting curl options.");
773 if ( ! @curl_setopt
( $curlHandle, CURLOPT_FOLLOWLOCATION
, $this->followRedirects
) ) {
774 wfDebug("Couldn't set CURLOPT_FOLLOWLOCATION. Probably safe_mode or open_basedir is set.");
775 /* Continue the processing. If it were in curl_setopt_array, processing would have halted on its entry */
778 if ( false === curl_exec( $curlHandle ) ) {
779 $code = curl_error( $curlHandle );
781 if ( isset( self
::$curlMessageMap[$code] ) ) {
782 $this->status
->fatal( self
::$curlMessageMap[$code] );
784 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
787 $this->headerList
= explode("\r\n", $this->headerText
);
790 curl_close( $curlHandle );
792 $this->parseHeader();
794 return $this->status
;
798 class PhpHttpRequest
extends HttpRequest
{
799 protected $manuallyRedirect = false;
801 protected function urlToTcp( $url ) {
802 $parsedUrl = parse_url( $url );
804 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
807 public function execute() {
810 // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
812 if ( version_compare( '5.1.7', phpversion(), '>' ) ) {
813 $this->manuallyRedirect
= true;
816 if ( $this->parsedUrl
['scheme'] != 'http' ) {
817 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
820 $this->reqHeaders
['Accept'] = "*/*";
821 if ( $this->method
== 'POST' ) {
822 // Required for HTTP 1.0 POSTs
823 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
824 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
828 if ( $this->proxy
&& !$this->noProxy
) {
829 $options['proxy'] = $this->urlToTCP( $this->proxy
);
830 $options['request_fulluri'] = true;
833 if ( !$this->followRedirects ||
$this->manuallyRedirect
) {
834 $options['max_redirects'] = 0;
836 $options['max_redirects'] = $this->maxRedirects
;
839 $options['method'] = $this->method
;
840 $options['header'] = implode("\r\n", $this->getHeaderList());
841 // Note that at some future point we may want to support
842 // HTTP/1.1, but we'd have to write support for chunking
843 // in version of PHP < 5.3.1
844 $options['protocol_version'] = "1.0";
846 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
847 // Only works on 5.2.10+
848 $options['ignore_errors'] = true;
850 if ( $this->postData
) {
851 $options['content'] = $this->postData
;
855 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
856 $oldTimeout = ini_set('default_socket_timeout', $this->timeout
);
858 $options['timeout'] = $this->timeout
;
861 $context = stream_context_create( array( 'http' => $options ) );
863 $this->headerList
= array();
869 wfSuppressWarnings();
870 $fh = fopen( $url, "r", false, $context );
873 $result = stream_get_meta_data( $fh );
874 $this->headerList
= $result['wrapper_data'];
875 $this->parseHeader();
876 $url = $this->getResponseHeader("Location");
877 $again = $this->manuallyRedirect
&& $this->followRedirects
&& $url
878 && $this->isRedirect() && $this->maxRedirects
> $reqCount;
882 if ( $oldTimeout !== false ) {
883 ini_set('default_socket_timeout', $oldTimeout);
887 if ( $fh === false ) {
888 $this->status
->fatal( 'http-request-error' );
889 return $this->status
;
892 if ( $result['timed_out'] ) {
893 $this->status
->fatal( 'http-timed-out', $this->url
);
894 return $this->status
;
897 if($this->status
->isOK()) {
898 while ( !feof( $fh ) ) {
899 $buf = fread( $fh, 8192 );
900 if ( $buf === false ) {
901 $this->status
->fatal( 'http-read-error' );
904 if ( strlen( $buf ) ) {
905 call_user_func( $this->callback
, $fh, $buf );
911 return $this->status
;