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 $this->logger
= $options['logger'] ??
new NullLogger();
102 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
103 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
105 $this->status
= StatusValue
::newGood( 100 ); // continue
108 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
109 $this->timeout
= $options['timeout'];
111 $this->timeout
= $wgHTTPTimeout;
113 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
114 $this->connectTimeout
= $options['connectTimeout'];
116 $this->connectTimeout
= $wgHTTPConnectTimeout;
118 if ( isset( $options['userAgent'] ) ) {
119 $this->setUserAgent( $options['userAgent'] );
121 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
124 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
127 if ( isset( $options['originalRequest'] ) ) {
128 $this->setOriginalRequest( $options['originalRequest'] );
131 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
132 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
134 foreach ( $members as $o ) {
135 if ( isset( $options[$o] ) ) {
136 // ensure that MWHttpRequest::method is always
137 // uppercased. T38137
138 if ( $o == 'method' ) {
139 $options[$o] = strtoupper( $options[$o] );
141 $this->$o = $options[$o];
145 if ( $this->noProxy
) {
146 $this->proxy
= ''; // noProxy takes precedence
149 // Profile based on what's calling us
150 $this->profiler
= $profiler;
151 $this->profileName
= $caller;
155 * @param LoggerInterface $logger
157 public function setLogger( LoggerInterface
$logger ) {
158 $this->logger
= $logger;
162 * Simple function to test if we can make any sort of requests at all, using
166 public static function canMakeRequests() {
167 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
171 * Generate a new request object
172 * Deprecated: @see HttpRequestFactory::create
173 * @param string $url Url to use
174 * @param array|null $options (optional) extra params to pass (see Http::request())
175 * @param string $caller The method making this request, for profiling
176 * @throws DomainException
177 * @return MWHttpRequest
178 * @see MWHttpRequest::__construct
180 public static function factory( $url, array $options = null, $caller = __METHOD__
) {
181 if ( $options === null ) {
184 return \MediaWiki\MediaWikiServices
::getInstance()
185 ->getHttpRequestFactory()
186 ->create( $url, $options, $caller );
190 * Get the body, or content, of the response to the request
194 public function getContent() {
195 return $this->content
;
199 * Set the parameters of the request
202 * @todo overload the args param
204 public function setData( $args ) {
205 $this->postData
= $args;
209 * Take care of setting up the proxy (do nothing if "noProxy" is set)
213 protected function proxySetup() {
214 // If there is an explicit proxy set and proxies are not disabled, then use it
215 if ( $this->proxy
&& !$this->noProxy
) {
219 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
220 // local URL and proxies are not disabled
221 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
224 $this->proxy
= Http
::getProxy();
229 * Check if the URL can be served by localhost
231 * @param string $url Full url to check
234 private static function isLocalURL( $url ) {
235 global $wgCommandLineMode, $wgLocalVirtualHosts;
237 if ( $wgCommandLineMode ) {
243 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
246 $domainParts = explode( '.', $host );
247 // Check if this domain or any superdomain is listed as a local virtual host
248 $domainParts = array_reverse( $domainParts );
251 $countParts = count( $domainParts );
252 for ( $i = 0; $i < $countParts; $i++
) {
253 $domainPart = $domainParts[$i];
255 $domain = $domainPart;
257 $domain = $domainPart . '.' . $domain;
260 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
273 public function setUserAgent( $UA ) {
274 $this->setHeader( 'User-Agent', $UA );
278 * Set an arbitrary header
279 * @param string $name
280 * @param string $value
282 public function setHeader( $name, $value ) {
283 // I feel like I should normalize the case here...
284 $this->reqHeaders
[$name] = $value;
288 * Get an array of the headers
291 protected function getHeaderList() {
294 if ( $this->cookieJar
) {
295 $this->reqHeaders
['Cookie'] =
296 $this->cookieJar
->serializeToHttpRequest(
297 $this->parsedUrl
['path'],
298 $this->parsedUrl
['host']
302 foreach ( $this->reqHeaders
as $name => $value ) {
303 $list[] = "$name: $value";
310 * Set a read callback to accept data read from the HTTP request.
311 * By default, data is appended to an internal buffer which can be
312 * retrieved through $req->getContent().
314 * To handle data as it comes in -- especially for large files that
315 * would not fit in memory -- you can instead set your own callback,
316 * in the form function($resource, $buffer) where the first parameter
317 * is the low-level resource being read (implementation specific),
318 * and the second parameter is the data buffer.
320 * You MUST return the number of bytes handled in the buffer; if fewer
321 * bytes are reported handled than were passed to you, the HTTP fetch
324 * @param callable|null $callback
325 * @throws InvalidArgumentException
327 public function setCallback( $callback ) {
328 if ( is_null( $callback ) ) {
329 $callback = [ $this, 'read' ];
330 } elseif ( !is_callable( $callback ) ) {
331 $this->status
->fatal( 'http-internal-error' );
332 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
334 $this->callback
= $callback;
338 * A generic callback to read the body of the response from a remote
341 * @param resource $fh
342 * @param string $content
346 public function read( $fh, $content ) {
347 $this->content
.= $content;
348 return strlen( $content );
352 * Take care of whatever is necessary to perform the URI request.
354 * @return StatusValue
355 * @note currently returns Status for B/C
357 public function execute() {
358 throw new LogicException( 'children must override this' );
361 protected function prepare() {
364 if ( strtoupper( $this->method
) == "HEAD" ) {
365 $this->headersOnly
= true;
368 $this->proxySetup(); // set up any proxy as needed
370 if ( !$this->callback
) {
371 $this->setCallback( null );
374 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
375 $this->setUserAgent( Http
::userAgent() );
380 * Parses the headers, including the HTTP status code and any
381 * Set-Cookie headers. This function expects the headers to be
382 * found in an array in the member variable headerList.
384 protected function parseHeader() {
387 // Failure without (valid) headers gets a response status of zero
388 if ( !$this->status
->isOK() ) {
389 $this->respStatus
= '0';
392 foreach ( $this->headerList
as $header ) {
393 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
394 $this->respVersion
= $match[1];
395 $this->respStatus
= $match[2];
396 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
397 $last = count( $this->respHeaders
[$lastname] ) - 1;
398 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
399 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
400 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
401 $lastname = strtolower( $match[1] );
405 $this->parseCookies();
409 * Sets HTTPRequest status member to a fatal value with the error
410 * message if the returned integer value of the status code was
411 * not successful (< 300) or a redirect (>=300 and < 400). (see
412 * RFC2616, section 10,
413 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
414 * list of status codes.)
416 protected function setStatus() {
417 if ( !$this->respHeaders
) {
418 $this->parseHeader();
421 if ( (int)$this->respStatus
> 399 ) {
422 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
423 $this->status
->fatal( "http-bad-status", $code, $message );
428 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
429 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
430 * for a list of status codes.)
434 public function getStatus() {
435 if ( !$this->respHeaders
) {
436 $this->parseHeader();
439 return (int)$this->respStatus
;
443 * Returns true if the last status code was a redirect.
447 public function isRedirect() {
448 if ( !$this->respHeaders
) {
449 $this->parseHeader();
452 $status = (int)$this->respStatus
;
454 if ( $status >= 300 && $status <= 303 ) {
462 * Returns an associative array of response headers after the
463 * request has been executed. Because some headers
464 * (e.g. Set-Cookie) can appear more than once the, each value of
465 * the associative array is an array of the values given.
469 public function getResponseHeaders() {
470 if ( !$this->respHeaders
) {
471 $this->parseHeader();
474 return $this->respHeaders
;
478 * Returns the value of the given response header.
480 * @param string $header
481 * @return string|null
483 public function getResponseHeader( $header ) {
484 if ( !$this->respHeaders
) {
485 $this->parseHeader();
488 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
489 $v = $this->respHeaders
[strtolower( $header )];
490 return $v[count( $v ) - 1];
497 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
499 * To read response cookies from the jar, getCookieJar must be called first.
501 * @param CookieJar $jar
503 public function setCookieJar( $jar ) {
504 $this->cookieJar
= $jar;
508 * Returns the cookie jar in use.
512 public function getCookieJar() {
513 if ( !$this->respHeaders
) {
514 $this->parseHeader();
517 return $this->cookieJar
;
521 * Sets a cookie. Used before a request to set up any individual
522 * cookies. Used internally after a request to parse the
523 * Set-Cookie headers.
525 * @param string $name
526 * @param string $value
529 public function setCookie( $name, $value, $attr = [] ) {
530 if ( !$this->cookieJar
) {
531 $this->cookieJar
= new CookieJar
;
534 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
535 $attr['domain'] = $this->parsedUrl
['host'];
538 $this->cookieJar
->setCookie( $name, $value, $attr );
542 * Parse the cookies in the response headers and store them in the cookie jar.
544 protected function parseCookies() {
545 if ( !$this->cookieJar
) {
546 $this->cookieJar
= new CookieJar
;
549 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
550 $url = parse_url( $this->getFinalUrl() );
551 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
552 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
558 * Returns the final URL after all redirections.
560 * Relative values of the "Location" header are incorrect as
561 * stated in RFC, however they do happen and modern browsers
562 * support them. This function loops backwards through all
563 * locations in order to build the proper absolute URI - Marooned
566 * Note that the multiple Location: headers are an artifact of
567 * CURL -- they shouldn't actually get returned this way. Rewrite
568 * this when T31232 is taken care of (high-level redirect
573 public function getFinalUrl() {
574 $headers = $this->getResponseHeaders();
576 // return full url (fix for incorrect but handled relative location)
577 if ( isset( $headers['location'] ) ) {
578 $locations = $headers['location'];
580 $foundRelativeURI = false;
581 $countLocations = count( $locations );
583 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
584 $url = parse_url( $locations[$i] );
586 if ( isset( $url['host'] ) ) {
587 $domain = $url['scheme'] . '://' . $url['host'];
588 break; // found correct URI (with host)
590 $foundRelativeURI = true;
594 if ( !$foundRelativeURI ) {
595 return $locations[$countLocations - 1];
598 return $domain . $locations[$countLocations - 1];
600 $url = parse_url( $this->url
);
601 if ( isset( $url['host'] ) ) {
602 return $url['scheme'] . '://' . $url['host'] .
603 $locations[$countLocations - 1];
611 * Returns true if the backend can follow redirects. Overridden by the
615 public function canFollowRedirects() {
620 * Set information about the original request. This can be useful for
621 * endpoints/API modules which act as a proxy for some service, and
622 * throttling etc. needs to happen in that service.
623 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
625 * @param WebRequest|array $originalRequest When in array form, it's
626 * expected to have the keys 'ip' and 'userAgent'.
627 * @note IP/user agent is personally identifiable information, and should
628 * only be set when the privacy policy of the request target is
629 * compatible with that of the MediaWiki installation.
631 public function setOriginalRequest( $originalRequest ) {
632 if ( $originalRequest instanceof WebRequest
) {
634 'ip' => $originalRequest->getIP(),
635 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
638 !is_array( $originalRequest )
639 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
641 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
642 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
645 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
646 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];