Move ILoadBalancer to Rdbms namespace
[mediawiki.git] / includes / http / MWHttpRequest.php
blobfac052fffc1d40481aa9b12df06a0494cf4d42ea
1 <?php
2 /**
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
18 * @file
21 use MediaWiki\Logger\LoggerFactory;
22 use Psr\Log\LoggerInterface;
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\NullLogger;
26 /**
27 * This wrapper class will call out to curl (if available) or fallback
28 * to regular PHP if necessary for handling internal HTTP requests.
30 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
31 * PHP's HTTP extension.
33 class MWHttpRequest implements LoggerAwareInterface {
34 const SUPPORTS_FILE_POSTS = false;
36 protected $content;
37 protected $timeout = 'default';
38 protected $headersOnly = null;
39 protected $postData = null;
40 protected $proxy = null;
41 protected $noProxy = false;
42 protected $sslVerifyHost = true;
43 protected $sslVerifyCert = true;
44 protected $caInfo = null;
45 protected $method = "GET";
46 protected $reqHeaders = [];
47 protected $url;
48 protected $parsedUrl;
49 /** @var callable */
50 protected $callback;
51 protected $maxRedirects = 5;
52 protected $followRedirects = false;
53 protected $connectTimeout;
55 /**
56 * @var CookieJar
58 protected $cookieJar;
60 protected $headerList = [];
61 protected $respVersion = "0.9";
62 protected $respStatus = "200 Ok";
63 protected $respHeaders = [];
65 /** @var StatusValue */
66 protected $status;
68 /**
69 * @var Profiler
71 protected $profiler;
73 /**
74 * @var string
76 protected $profileName;
78 /**
79 * @var LoggerInterface;
81 protected $logger;
83 /**
84 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
85 * @param array $options (optional) extra params to pass (see Http::request())
86 * @param string $caller The method making this request, for profiling
87 * @param Profiler $profiler An instance of the profiler for profiling, or null
89 protected function __construct(
90 $url, $options = [], $caller = __METHOD__, $profiler = null
91 ) {
92 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
94 $this->url = wfExpandUrl( $url, PROTO_HTTP );
95 $this->parsedUrl = wfParseUrl( $this->url );
97 if ( isset( $options['logger'] ) ) {
98 $this->logger = $options['logger'];
99 } else {
100 $this->logger = new NullLogger();
103 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
104 $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
105 } else {
106 $this->status = StatusValue::newGood( 100 ); // continue
109 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
110 $this->timeout = $options['timeout'];
111 } else {
112 $this->timeout = $wgHTTPTimeout;
114 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
115 $this->connectTimeout = $options['connectTimeout'];
116 } else {
117 $this->connectTimeout = $wgHTTPConnectTimeout;
119 if ( isset( $options['userAgent'] ) ) {
120 $this->setUserAgent( $options['userAgent'] );
122 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
123 $this->setHeader(
124 'Authorization',
125 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
129 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
130 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
132 foreach ( $members as $o ) {
133 if ( isset( $options[$o] ) ) {
134 // ensure that MWHttpRequest::method is always
135 // uppercased. Bug 36137
136 if ( $o == 'method' ) {
137 $options[$o] = strtoupper( $options[$o] );
139 $this->$o = $options[$o];
143 if ( $this->noProxy ) {
144 $this->proxy = ''; // noProxy takes precedence
147 // Profile based on what's calling us
148 $this->profiler = $profiler;
149 $this->profileName = $caller;
153 * @param LoggerInterface $logger
155 public function setLogger( LoggerInterface $logger ) {
156 $this->logger = $logger;
160 * Simple function to test if we can make any sort of requests at all, using
161 * cURL or fopen()
162 * @return bool
164 public static function canMakeRequests() {
165 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
169 * Generate a new request object
170 * @param string $url Url to use
171 * @param array $options (optional) extra params to pass (see Http::request())
172 * @param string $caller The method making this request, for profiling
173 * @throws DomainException
174 * @return CurlHttpRequest|PhpHttpRequest
175 * @see MWHttpRequest::__construct
177 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
178 if ( !Http::$httpEngine ) {
179 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
180 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
181 throw new DomainException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
182 ' Http::$httpEngine is set to "curl"' );
185 if ( !is_array( $options ) ) {
186 $options = [];
189 if ( !isset( $options['logger'] ) ) {
190 $options['logger'] = LoggerFactory::getInstance( 'http' );
193 switch ( Http::$httpEngine ) {
194 case 'curl':
195 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
196 case 'php':
197 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
198 throw new DomainException( __METHOD__ . ': allow_url_fopen ' .
199 'needs to be enabled for pure PHP http requests to ' .
200 'work. If possible, curl should be used instead. See ' .
201 'http://php.net/curl.'
204 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
205 default:
206 throw new DomainException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
211 * Get the body, or content, of the response to the request
213 * @return string
215 public function getContent() {
216 return $this->content;
220 * Set the parameters of the request
222 * @param array $args
223 * @todo overload the args param
225 public function setData( $args ) {
226 $this->postData = $args;
230 * Take care of setting up the proxy (do nothing if "noProxy" is set)
232 * @return void
234 protected function proxySetup() {
235 // If there is an explicit proxy set and proxies are not disabled, then use it
236 if ( $this->proxy && !$this->noProxy ) {
237 return;
240 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
241 // local URL and proxies are not disabled
242 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
243 $this->proxy = '';
244 } else {
245 $this->proxy = Http::getProxy();
250 * Check if the URL can be served by localhost
252 * @param string $url Full url to check
253 * @return bool
255 private static function isLocalURL( $url ) {
256 global $wgCommandLineMode, $wgLocalVirtualHosts;
258 if ( $wgCommandLineMode ) {
259 return false;
262 // Extract host part
263 $matches = [];
264 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
265 $host = $matches[1];
266 // Split up dotwise
267 $domainParts = explode( '.', $host );
268 // Check if this domain or any superdomain is listed as a local virtual host
269 $domainParts = array_reverse( $domainParts );
271 $domain = '';
272 $countParts = count( $domainParts );
273 for ( $i = 0; $i < $countParts; $i++ ) {
274 $domainPart = $domainParts[$i];
275 if ( $i == 0 ) {
276 $domain = $domainPart;
277 } else {
278 $domain = $domainPart . '.' . $domain;
281 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
282 return true;
287 return false;
291 * Set the user agent
292 * @param string $UA
294 public function setUserAgent( $UA ) {
295 $this->setHeader( 'User-Agent', $UA );
299 * Set an arbitrary header
300 * @param string $name
301 * @param string $value
303 public function setHeader( $name, $value ) {
304 // I feel like I should normalize the case here...
305 $this->reqHeaders[$name] = $value;
309 * Get an array of the headers
310 * @return array
312 protected function getHeaderList() {
313 $list = [];
315 if ( $this->cookieJar ) {
316 $this->reqHeaders['Cookie'] =
317 $this->cookieJar->serializeToHttpRequest(
318 $this->parsedUrl['path'],
319 $this->parsedUrl['host']
323 foreach ( $this->reqHeaders as $name => $value ) {
324 $list[] = "$name: $value";
327 return $list;
331 * Set a read callback to accept data read from the HTTP request.
332 * By default, data is appended to an internal buffer which can be
333 * retrieved through $req->getContent().
335 * To handle data as it comes in -- especially for large files that
336 * would not fit in memory -- you can instead set your own callback,
337 * in the form function($resource, $buffer) where the first parameter
338 * is the low-level resource being read (implementation specific),
339 * and the second parameter is the data buffer.
341 * You MUST return the number of bytes handled in the buffer; if fewer
342 * bytes are reported handled than were passed to you, the HTTP fetch
343 * will be aborted.
345 * @param callable|null $callback
346 * @throws InvalidArgumentException
348 public function setCallback( $callback ) {
349 if ( is_null( $callback ) ) {
350 $callback = [ $this, 'read' ];
351 } elseif ( !is_callable( $callback ) ) {
352 throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
354 $this->callback = $callback;
358 * A generic callback to read the body of the response from a remote
359 * server.
361 * @param resource $fh
362 * @param string $content
363 * @return int
364 * @internal
366 public function read( $fh, $content ) {
367 $this->content .= $content;
368 return strlen( $content );
372 * Take care of whatever is necessary to perform the URI request.
374 * @return StatusValue
375 * @note currently returns Status for B/C
377 public function execute() {
378 throw new LogicException( 'children must override this' );
381 protected function prepare() {
382 $this->content = "";
384 if ( strtoupper( $this->method ) == "HEAD" ) {
385 $this->headersOnly = true;
388 $this->proxySetup(); // set up any proxy as needed
390 if ( !$this->callback ) {
391 $this->setCallback( null );
394 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
395 $this->setUserAgent( Http::userAgent() );
400 * Parses the headers, including the HTTP status code and any
401 * Set-Cookie headers. This function expects the headers to be
402 * found in an array in the member variable headerList.
404 protected function parseHeader() {
405 $lastname = "";
407 foreach ( $this->headerList as $header ) {
408 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
409 $this->respVersion = $match[1];
410 $this->respStatus = $match[2];
411 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
412 $last = count( $this->respHeaders[$lastname] ) - 1;
413 $this->respHeaders[$lastname][$last] .= "\r\n$header";
414 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
415 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
416 $lastname = strtolower( $match[1] );
420 $this->parseCookies();
424 * Sets HTTPRequest status member to a fatal value with the error
425 * message if the returned integer value of the status code was
426 * not successful (< 300) or a redirect (>=300 and < 400). (see
427 * RFC2616, section 10,
428 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
429 * list of status codes.)
431 protected function setStatus() {
432 if ( !$this->respHeaders ) {
433 $this->parseHeader();
436 if ( (int)$this->respStatus > 399 ) {
437 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
438 $this->status->fatal( "http-bad-status", $code, $message );
443 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
444 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
445 * for a list of status codes.)
447 * @return int
449 public function getStatus() {
450 if ( !$this->respHeaders ) {
451 $this->parseHeader();
454 return (int)$this->respStatus;
458 * Returns true if the last status code was a redirect.
460 * @return bool
462 public function isRedirect() {
463 if ( !$this->respHeaders ) {
464 $this->parseHeader();
467 $status = (int)$this->respStatus;
469 if ( $status >= 300 && $status <= 303 ) {
470 return true;
473 return false;
477 * Returns an associative array of response headers after the
478 * request has been executed. Because some headers
479 * (e.g. Set-Cookie) can appear more than once the, each value of
480 * the associative array is an array of the values given.
482 * @return array
484 public function getResponseHeaders() {
485 if ( !$this->respHeaders ) {
486 $this->parseHeader();
489 return $this->respHeaders;
493 * Returns the value of the given response header.
495 * @param string $header
496 * @return string|null
498 public function getResponseHeader( $header ) {
499 if ( !$this->respHeaders ) {
500 $this->parseHeader();
503 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
504 $v = $this->respHeaders[strtolower( $header )];
505 return $v[count( $v ) - 1];
508 return null;
512 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
514 * To read response cookies from the jar, getCookieJar must be called first.
516 * @param CookieJar $jar
518 public function setCookieJar( $jar ) {
519 $this->cookieJar = $jar;
523 * Returns the cookie jar in use.
525 * @return CookieJar
527 public function getCookieJar() {
528 if ( !$this->respHeaders ) {
529 $this->parseHeader();
532 return $this->cookieJar;
536 * Sets a cookie. Used before a request to set up any individual
537 * cookies. Used internally after a request to parse the
538 * Set-Cookie headers.
539 * @see Cookie::set
540 * @param string $name
541 * @param string $value
542 * @param array $attr
544 public function setCookie( $name, $value, $attr = [] ) {
545 if ( !$this->cookieJar ) {
546 $this->cookieJar = new CookieJar;
549 if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
550 $attr['domain'] = $this->parsedUrl['host'];
553 $this->cookieJar->setCookie( $name, $value, $attr );
557 * Parse the cookies in the response headers and store them in the cookie jar.
559 protected function parseCookies() {
560 if ( !$this->cookieJar ) {
561 $this->cookieJar = new CookieJar;
564 if ( isset( $this->respHeaders['set-cookie'] ) ) {
565 $url = parse_url( $this->getFinalUrl() );
566 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
567 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
573 * Returns the final URL after all redirections.
575 * Relative values of the "Location" header are incorrect as
576 * stated in RFC, however they do happen and modern browsers
577 * support them. This function loops backwards through all
578 * locations in order to build the proper absolute URI - Marooned
579 * at wikia-inc.com
581 * Note that the multiple Location: headers are an artifact of
582 * CURL -- they shouldn't actually get returned this way. Rewrite
583 * this when bug 29232 is taken care of (high-level redirect
584 * handling rewrite).
586 * @return string
588 public function getFinalUrl() {
589 $headers = $this->getResponseHeaders();
591 // return full url (fix for incorrect but handled relative location)
592 if ( isset( $headers['location'] ) ) {
593 $locations = $headers['location'];
594 $domain = '';
595 $foundRelativeURI = false;
596 $countLocations = count( $locations );
598 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
599 $url = parse_url( $locations[$i] );
601 if ( isset( $url['host'] ) ) {
602 $domain = $url['scheme'] . '://' . $url['host'];
603 break; // found correct URI (with host)
604 } else {
605 $foundRelativeURI = true;
609 if ( $foundRelativeURI ) {
610 if ( $domain ) {
611 return $domain . $locations[$countLocations - 1];
612 } else {
613 $url = parse_url( $this->url );
614 if ( isset( $url['host'] ) ) {
615 return $url['scheme'] . '://' . $url['host'] .
616 $locations[$countLocations - 1];
619 } else {
620 return $locations[$countLocations - 1];
624 return $this->url;
628 * Returns true if the backend can follow redirects. Overridden by the
629 * child classes.
630 * @return bool
632 public function canFollowRedirects() {
633 return true;