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
21 use Psr\Log\LoggerInterface
;
22 use Psr\Log\LoggerAwareInterface
;
23 use Psr\Log\NullLogger
;
26 * This wrapper class will call out to curl (if available) or fallback
27 * to regular PHP if necessary for handling internal HTTP requests.
29 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
30 * PHP's HTTP extension.
32 abstract class MWHttpRequest
implements LoggerAwareInterface
{
33 const SUPPORTS_FILE_POSTS
= false;
38 protected $timeout = 'default';
41 protected $headersOnly = null;
42 protected $postData = null;
43 protected $proxy = null;
44 protected $noProxy = false;
45 protected $sslVerifyHost = true;
46 protected $sslVerifyCert = true;
47 protected $caInfo = null;
48 protected $method = "GET";
49 protected $reqHeaders = [];
54 protected $maxRedirects = 5;
55 protected $followRedirects = false;
56 protected $connectTimeout;
63 protected $headerList = [];
64 protected $respVersion = "0.9";
65 protected $respStatus = "200 Ok";
66 protected $respHeaders = [];
68 /** @var StatusValue */
79 protected $profileName;
82 * @var LoggerInterface
87 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
88 * @param array $options (optional) extra params to pass (see Http::request())
89 * @param string $caller The method making this request, for profiling
90 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
92 public function __construct(
93 $url, array $options = [], $caller = __METHOD__
, $profiler = null
95 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
97 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
98 $this->parsedUrl
= wfParseUrl( $this->url
);
100 if ( isset( $options['logger'] ) ) {
101 $this->logger
= $options['logger'];
103 $this->logger
= new NullLogger();
106 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
107 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
109 $this->status
= StatusValue
::newGood( 100 ); // continue
112 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
113 $this->timeout
= $options['timeout'];
115 $this->timeout
= $wgHTTPTimeout;
117 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
118 $this->connectTimeout
= $options['connectTimeout'];
120 $this->connectTimeout
= $wgHTTPConnectTimeout;
122 if ( isset( $options['userAgent'] ) ) {
123 $this->setUserAgent( $options['userAgent'] );
125 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
128 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
131 if ( isset( $options['originalRequest'] ) ) {
132 $this->setOriginalRequest( $options['originalRequest'] );
135 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
136 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
138 foreach ( $members as $o ) {
139 if ( isset( $options[$o] ) ) {
140 // ensure that MWHttpRequest::method is always
141 // uppercased. T38137
142 if ( $o == 'method' ) {
143 $options[$o] = strtoupper( $options[$o] );
145 $this->$o = $options[$o];
149 if ( $this->noProxy
) {
150 $this->proxy
= ''; // noProxy takes precedence
153 // Profile based on what's calling us
154 $this->profiler
= $profiler;
155 $this->profileName
= $caller;
159 * @param LoggerInterface $logger
161 public function setLogger( LoggerInterface
$logger ) {
162 $this->logger
= $logger;
166 * Simple function to test if we can make any sort of requests at all, using
170 public static function canMakeRequests() {
171 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
175 * Generate a new request object
176 * Deprecated: @see HttpRequestFactory::create
177 * @param string $url Url to use
178 * @param array|null $options (optional) extra params to pass (see Http::request())
179 * @param string $caller The method making this request, for profiling
180 * @throws DomainException
181 * @return MWHttpRequest
182 * @see MWHttpRequest::__construct
184 public static function factory( $url, array $options = null, $caller = __METHOD__
) {
185 if ( $options === null ) {
188 return \MediaWiki\MediaWikiServices
::getInstance()
189 ->getHttpRequestFactory()
190 ->create( $url, $options, $caller );
194 * Get the body, or content, of the response to the request
198 public function getContent() {
199 return $this->content
;
203 * Set the parameters of the request
206 * @todo overload the args param
208 public function setData( $args ) {
209 $this->postData
= $args;
213 * Take care of setting up the proxy (do nothing if "noProxy" is set)
217 protected function proxySetup() {
218 // If there is an explicit proxy set and proxies are not disabled, then use it
219 if ( $this->proxy
&& !$this->noProxy
) {
223 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
224 // local URL and proxies are not disabled
225 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
228 $this->proxy
= Http
::getProxy();
233 * Check if the URL can be served by localhost
235 * @param string $url Full url to check
238 private static function isLocalURL( $url ) {
239 global $wgCommandLineMode, $wgLocalVirtualHosts;
241 if ( $wgCommandLineMode ) {
247 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
250 $domainParts = explode( '.', $host );
251 // Check if this domain or any superdomain is listed as a local virtual host
252 $domainParts = array_reverse( $domainParts );
255 $countParts = count( $domainParts );
256 for ( $i = 0; $i < $countParts; $i++
) {
257 $domainPart = $domainParts[$i];
259 $domain = $domainPart;
261 $domain = $domainPart . '.' . $domain;
264 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
277 public function setUserAgent( $UA ) {
278 $this->setHeader( 'User-Agent', $UA );
282 * Set an arbitrary header
283 * @param string $name
284 * @param string $value
286 public function setHeader( $name, $value ) {
287 // I feel like I should normalize the case here...
288 $this->reqHeaders
[$name] = $value;
292 * Get an array of the headers
295 protected function getHeaderList() {
298 if ( $this->cookieJar
) {
299 $this->reqHeaders
['Cookie'] =
300 $this->cookieJar
->serializeToHttpRequest(
301 $this->parsedUrl
['path'],
302 $this->parsedUrl
['host']
306 foreach ( $this->reqHeaders
as $name => $value ) {
307 $list[] = "$name: $value";
314 * Set a read callback to accept data read from the HTTP request.
315 * By default, data is appended to an internal buffer which can be
316 * retrieved through $req->getContent().
318 * To handle data as it comes in -- especially for large files that
319 * would not fit in memory -- you can instead set your own callback,
320 * in the form function($resource, $buffer) where the first parameter
321 * is the low-level resource being read (implementation specific),
322 * and the second parameter is the data buffer.
324 * You MUST return the number of bytes handled in the buffer; if fewer
325 * bytes are reported handled than were passed to you, the HTTP fetch
328 * @param callable|null $callback
329 * @throws InvalidArgumentException
331 public function setCallback( $callback ) {
332 if ( is_null( $callback ) ) {
333 $callback = [ $this, 'read' ];
334 } elseif ( !is_callable( $callback ) ) {
335 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
337 $this->callback
= $callback;
341 * A generic callback to read the body of the response from a remote
344 * @param resource $fh
345 * @param string $content
349 public function read( $fh, $content ) {
350 $this->content
.= $content;
351 return strlen( $content );
355 * Take care of whatever is necessary to perform the URI request.
357 * @return StatusValue
358 * @note currently returns Status for B/C
360 public function execute() {
361 throw new LogicException( 'children must override this' );
364 protected function prepare() {
367 if ( strtoupper( $this->method
) == "HEAD" ) {
368 $this->headersOnly
= true;
371 $this->proxySetup(); // set up any proxy as needed
373 if ( !$this->callback
) {
374 $this->setCallback( null );
377 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
378 $this->setUserAgent( Http
::userAgent() );
383 * Parses the headers, including the HTTP status code and any
384 * Set-Cookie headers. This function expects the headers to be
385 * found in an array in the member variable headerList.
387 protected function parseHeader() {
390 foreach ( $this->headerList
as $header ) {
391 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
392 $this->respVersion
= $match[1];
393 $this->respStatus
= $match[2];
394 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
395 $last = count( $this->respHeaders
[$lastname] ) - 1;
396 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
397 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
398 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
399 $lastname = strtolower( $match[1] );
403 $this->parseCookies();
407 * Sets HTTPRequest status member to a fatal value with the error
408 * message if the returned integer value of the status code was
409 * not successful (< 300) or a redirect (>=300 and < 400). (see
410 * RFC2616, section 10,
411 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
412 * list of status codes.)
414 protected function setStatus() {
415 if ( !$this->respHeaders
) {
416 $this->parseHeader();
419 if ( (int)$this->respStatus
> 399 ) {
420 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
421 $this->status
->fatal( "http-bad-status", $code, $message );
426 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
427 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
428 * for a list of status codes.)
432 public function getStatus() {
433 if ( !$this->respHeaders
) {
434 $this->parseHeader();
437 return (int)$this->respStatus
;
441 * Returns true if the last status code was a redirect.
445 public function isRedirect() {
446 if ( !$this->respHeaders
) {
447 $this->parseHeader();
450 $status = (int)$this->respStatus
;
452 if ( $status >= 300 && $status <= 303 ) {
460 * Returns an associative array of response headers after the
461 * request has been executed. Because some headers
462 * (e.g. Set-Cookie) can appear more than once the, each value of
463 * the associative array is an array of the values given.
467 public function getResponseHeaders() {
468 if ( !$this->respHeaders
) {
469 $this->parseHeader();
472 return $this->respHeaders
;
476 * Returns the value of the given response header.
478 * @param string $header
479 * @return string|null
481 public function getResponseHeader( $header ) {
482 if ( !$this->respHeaders
) {
483 $this->parseHeader();
486 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
487 $v = $this->respHeaders
[strtolower( $header )];
488 return $v[count( $v ) - 1];
495 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
497 * To read response cookies from the jar, getCookieJar must be called first.
499 * @param CookieJar $jar
501 public function setCookieJar( $jar ) {
502 $this->cookieJar
= $jar;
506 * Returns the cookie jar in use.
510 public function getCookieJar() {
511 if ( !$this->respHeaders
) {
512 $this->parseHeader();
515 return $this->cookieJar
;
519 * Sets a cookie. Used before a request to set up any individual
520 * cookies. Used internally after a request to parse the
521 * Set-Cookie headers.
523 * @param string $name
524 * @param string $value
527 public function setCookie( $name, $value, $attr = [] ) {
528 if ( !$this->cookieJar
) {
529 $this->cookieJar
= new CookieJar
;
532 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
533 $attr['domain'] = $this->parsedUrl
['host'];
536 $this->cookieJar
->setCookie( $name, $value, $attr );
540 * Parse the cookies in the response headers and store them in the cookie jar.
542 protected function parseCookies() {
543 if ( !$this->cookieJar
) {
544 $this->cookieJar
= new CookieJar
;
547 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
548 $url = parse_url( $this->getFinalUrl() );
549 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
550 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
556 * Returns the final URL after all redirections.
558 * Relative values of the "Location" header are incorrect as
559 * stated in RFC, however they do happen and modern browsers
560 * support them. This function loops backwards through all
561 * locations in order to build the proper absolute URI - Marooned
564 * Note that the multiple Location: headers are an artifact of
565 * CURL -- they shouldn't actually get returned this way. Rewrite
566 * this when T31232 is taken care of (high-level redirect
571 public function getFinalUrl() {
572 $headers = $this->getResponseHeaders();
574 // return full url (fix for incorrect but handled relative location)
575 if ( isset( $headers['location'] ) ) {
576 $locations = $headers['location'];
578 $foundRelativeURI = false;
579 $countLocations = count( $locations );
581 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
582 $url = parse_url( $locations[$i] );
584 if ( isset( $url['host'] ) ) {
585 $domain = $url['scheme'] . '://' . $url['host'];
586 break; // found correct URI (with host)
588 $foundRelativeURI = true;
592 if ( !$foundRelativeURI ) {
593 return $locations[$countLocations - 1];
596 return $domain . $locations[$countLocations - 1];
598 $url = parse_url( $this->url
);
599 if ( isset( $url['host'] ) ) {
600 return $url['scheme'] . '://' . $url['host'] .
601 $locations[$countLocations - 1];
609 * Returns true if the backend can follow redirects. Overridden by the
613 public function canFollowRedirects() {
618 * Set information about the original request. This can be useful for
619 * endpoints/API modules which act as a proxy for some service, and
620 * throttling etc. needs to happen in that service.
621 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
623 * @param WebRequest|array $originalRequest When in array form, it's
624 * expected to have the keys 'ip' and 'userAgent'.
625 * @note IP/user agent is personally identifiable information, and should
626 * only be set when the privacy policy of the request target is
627 * compatible with that of the MediaWiki installation.
629 public function setOriginalRequest( $originalRequest ) {
630 if ( $originalRequest instanceof WebRequest
) {
632 'ip' => $originalRequest->getIP(),
633 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
636 !is_array( $originalRequest )
637 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
639 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
640 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
643 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
644 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];