3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 * This wrapper class will call out to curl (if available) or fallback
23 * to regular PHP if necessary for handling internal HTTP requests.
25 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
26 * PHP's HTTP extension.
29 const SUPPORTS_FILE_POSTS
= false;
32 protected $timeout = 'default';
33 protected $headersOnly = null;
34 protected $postData = null;
35 protected $proxy = null;
36 protected $noProxy = false;
37 protected $sslVerifyHost = true;
38 protected $sslVerifyCert = true;
39 protected $caInfo = null;
40 protected $method = "GET";
41 protected $reqHeaders = [];
45 protected $maxRedirects = 5;
46 protected $followRedirects = false;
53 protected $headerList = [];
54 protected $respVersion = "0.9";
55 protected $respStatus = "200 Ok";
56 protected $respHeaders = [];
68 protected $profileName;
71 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
72 * @param array $options (optional) extra params to pass (see Http::request())
73 * @param string $caller The method making this request, for profiling
74 * @param Profiler $profiler An instance of the profiler for profiling, or null
76 protected function __construct(
77 $url, $options = [], $caller = __METHOD__
, $profiler = null
79 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
81 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
82 $this->parsedUrl
= wfParseUrl( $this->url
);
84 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
85 $this->status
= Status
::newFatal( 'http-invalid-url', $url );
87 $this->status
= Status
::newGood( 100 ); // continue
90 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
91 $this->timeout
= $options['timeout'];
93 $this->timeout
= $wgHTTPTimeout;
95 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
96 $this->connectTimeout
= $options['connectTimeout'];
98 $this->connectTimeout
= $wgHTTPConnectTimeout;
100 if ( isset( $options['userAgent'] ) ) {
101 $this->setUserAgent( $options['userAgent'] );
104 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
105 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
107 foreach ( $members as $o ) {
108 if ( isset( $options[$o] ) ) {
109 // ensure that MWHttpRequest::method is always
110 // uppercased. Bug 36137
111 if ( $o == 'method' ) {
112 $options[$o] = strtoupper( $options[$o] );
114 $this->$o = $options[$o];
118 if ( $this->noProxy
) {
119 $this->proxy
= ''; // noProxy takes precedence
122 // Profile based on what's calling us
123 $this->profiler
= $profiler;
124 $this->profileName
= $caller;
128 * Simple function to test if we can make any sort of requests at all, using
132 public static function canMakeRequests() {
133 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
137 * Generate a new request object
138 * @param string $url Url to use
139 * @param array $options (optional) extra params to pass (see Http::request())
140 * @param string $caller The method making this request, for profiling
141 * @throws MWException
142 * @return CurlHttpRequest|PhpHttpRequest
143 * @see MWHttpRequest::__construct
145 public static function factory( $url, $options = null, $caller = __METHOD__
) {
146 if ( !Http
::$httpEngine ) {
147 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
148 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
149 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
150 ' Http::$httpEngine is set to "curl"' );
153 switch ( Http
::$httpEngine ) {
155 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
157 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
158 throw new MWException( __METHOD__
. ': allow_url_fopen ' .
159 'needs to be enabled for pure PHP http requests to ' .
160 'work. If possible, curl should be used instead. See ' .
161 'http://php.net/curl.'
164 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
166 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
171 * Get the body, or content, of the response to the request
175 public function getContent() {
176 return $this->content
;
180 * Set the parameters of the request
183 * @todo overload the args param
185 public function setData( $args ) {
186 $this->postData
= $args;
190 * Take care of setting up the proxy (do nothing if "noProxy" is set)
194 public function proxySetup() {
195 // If there is an explicit proxy set and proxies are not disabled, then use it
196 if ( $this->proxy
&& !$this->noProxy
) {
200 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
201 // local URL and proxies are not disabled
202 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
205 $this->proxy
= Http
::getProxy();
210 * Check if the URL can be served by localhost
212 * @param string $url Full url to check
215 private static function isLocalURL( $url ) {
216 global $wgCommandLineMode, $wgLocalVirtualHosts;
218 if ( $wgCommandLineMode ) {
224 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
227 $domainParts = explode( '.', $host );
228 // Check if this domain or any superdomain is listed as a local virtual host
229 $domainParts = array_reverse( $domainParts );
232 $countParts = count( $domainParts );
233 for ( $i = 0; $i < $countParts; $i++
) {
234 $domainPart = $domainParts[$i];
236 $domain = $domainPart;
238 $domain = $domainPart . '.' . $domain;
241 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
254 public function setUserAgent( $UA ) {
255 $this->setHeader( 'User-Agent', $UA );
259 * Set an arbitrary header
260 * @param string $name
261 * @param string $value
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
272 public function getHeaderList() {
275 if ( $this->cookieJar
) {
276 $this->reqHeaders
['Cookie'] =
277 $this->cookieJar
->serializeToHttpRequest(
278 $this->parsedUrl
['path'],
279 $this->parsedUrl
['host']
283 foreach ( $this->reqHeaders
as $name => $value ) {
284 $list[] = "$name: $value";
291 * Set a read callback to accept data read from the HTTP request.
292 * By default, data is appended to an internal buffer which can be
293 * retrieved through $req->getContent().
295 * To handle data as it comes in -- especially for large files that
296 * would not fit in memory -- you can instead set your own callback,
297 * in the form function($resource, $buffer) where the first parameter
298 * is the low-level resource being read (implementation specific),
299 * and the second parameter is the data buffer.
301 * You MUST return the number of bytes handled in the buffer; if fewer
302 * bytes are reported handled than were passed to you, the HTTP fetch
305 * @param callable $callback
306 * @throws MWException
308 public function setCallback( $callback ) {
309 if ( !is_callable( $callback ) ) {
310 throw new MWException( 'Invalid MwHttpRequest callback' );
312 $this->callback
= $callback;
316 * A generic callback to read the body of the response from a remote
319 * @param resource $fh
320 * @param string $content
323 public function read( $fh, $content ) {
324 $this->content
.= $content;
325 return strlen( $content );
329 * Take care of whatever is necessary to perform the URI request.
333 public function execute() {
337 if ( strtoupper( $this->method
) == "HEAD" ) {
338 $this->headersOnly
= true;
341 $this->proxySetup(); // set up any proxy as needed
343 if ( !$this->callback
) {
344 $this->setCallback( [ $this, 'read' ] );
347 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
348 $this->setUserAgent( Http
::userAgent() );
354 * Parses the headers, including the HTTP status code and any
355 * Set-Cookie headers. This function expects the headers to be
356 * found in an array in the member variable headerList.
358 protected function parseHeader() {
362 foreach ( $this->headerList
as $header ) {
363 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
364 $this->respVersion
= $match[1];
365 $this->respStatus
= $match[2];
366 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
367 $last = count( $this->respHeaders
[$lastname] ) - 1;
368 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
369 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
370 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
371 $lastname = strtolower( $match[1] );
375 $this->parseCookies();
380 * Sets HTTPRequest status member to a fatal value with the error
381 * message if the returned integer value of the status code was
382 * not successful (< 300) or a redirect (>=300 and < 400). (see
383 * RFC2616, section 10,
384 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
385 * list of status codes.)
387 protected function setStatus() {
388 if ( !$this->respHeaders
) {
389 $this->parseHeader();
392 if ( (int)$this->respStatus
> 399 ) {
393 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
394 $this->status
->fatal( "http-bad-status", $code, $message );
399 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
400 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
401 * for a list of status codes.)
405 public function getStatus() {
406 if ( !$this->respHeaders
) {
407 $this->parseHeader();
410 return (int)$this->respStatus
;
414 * Returns true if the last status code was a redirect.
418 public function isRedirect() {
419 if ( !$this->respHeaders
) {
420 $this->parseHeader();
423 $status = (int)$this->respStatus
;
425 if ( $status >= 300 && $status <= 303 ) {
433 * Returns an associative array of response headers after the
434 * request has been executed. Because some headers
435 * (e.g. Set-Cookie) can appear more than once the, each value of
436 * the associative array is an array of the values given.
440 public function getResponseHeaders() {
441 if ( !$this->respHeaders
) {
442 $this->parseHeader();
445 return $this->respHeaders
;
449 * Returns the value of the given response header.
451 * @param string $header
452 * @return string|null
454 public function getResponseHeader( $header ) {
455 if ( !$this->respHeaders
) {
456 $this->parseHeader();
459 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
460 $v = $this->respHeaders
[strtolower( $header )];
461 return $v[count( $v ) - 1];
468 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
470 * @param CookieJar $jar
472 public function setCookieJar( $jar ) {
473 $this->cookieJar
= $jar;
477 * Returns the cookie jar in use.
481 public function getCookieJar() {
482 if ( !$this->respHeaders
) {
483 $this->parseHeader();
486 return $this->cookieJar
;
490 * Sets a cookie. Used before a request to set up any individual
491 * cookies. Used internally after a request to parse the
492 * Set-Cookie headers.
494 * @param string $name
495 * @param mixed $value
498 public function setCookie( $name, $value = null, $attr = null ) {
499 if ( !$this->cookieJar
) {
500 $this->cookieJar
= new CookieJar
;
503 $this->cookieJar
->setCookie( $name, $value, $attr );
507 * Parse the cookies in the response headers and store them in the cookie jar.
509 protected function parseCookies() {
511 if ( !$this->cookieJar
) {
512 $this->cookieJar
= new CookieJar
;
515 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
516 $url = parse_url( $this->getFinalUrl() );
517 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
518 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
525 * Returns the final URL after all redirections.
527 * Relative values of the "Location" header are incorrect as
528 * stated in RFC, however they do happen and modern browsers
529 * support them. This function loops backwards through all
530 * locations in order to build the proper absolute URI - Marooned
533 * Note that the multiple Location: headers are an artifact of
534 * CURL -- they shouldn't actually get returned this way. Rewrite
535 * this when bug 29232 is taken care of (high-level redirect
540 public function getFinalUrl() {
541 $headers = $this->getResponseHeaders();
543 // return full url (fix for incorrect but handled relative location)
544 if ( isset( $headers['location'] ) ) {
545 $locations = $headers['location'];
547 $foundRelativeURI = false;
548 $countLocations = count( $locations );
550 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
551 $url = parse_url( $locations[$i] );
553 if ( isset( $url['host'] ) ) {
554 $domain = $url['scheme'] . '://' . $url['host'];
555 break; // found correct URI (with host)
557 $foundRelativeURI = true;
561 if ( $foundRelativeURI ) {
563 return $domain . $locations[$countLocations - 1];
565 $url = parse_url( $this->url
);
566 if ( isset( $url['host'] ) ) {
567 return $url['scheme'] . '://' . $url['host'] .
568 $locations[$countLocations - 1];
572 return $locations[$countLocations - 1];
580 * Returns true if the backend can follow redirects. Overridden by the
584 public function canFollowRedirects() {