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 MediaWiki\Logger\LoggerFactory
;
22 use Psr\Log\LoggerInterface
;
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\NullLogger
;
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;
39 protected $timeout = 'default';
42 protected $headersOnly = null;
43 protected $postData = null;
44 protected $proxy = null;
45 protected $noProxy = false;
46 protected $sslVerifyHost = true;
47 protected $sslVerifyCert = true;
48 protected $caInfo = null;
49 protected $method = "GET";
50 protected $reqHeaders = [];
55 protected $maxRedirects = 5;
56 protected $followRedirects = false;
57 protected $connectTimeout;
64 protected $headerList = [];
65 protected $respVersion = "0.9";
66 protected $respStatus = "200 Ok";
67 protected $respHeaders = [];
69 /** @var StatusValue */
80 protected $profileName;
83 * @var LoggerInterface;
88 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
89 * @param array $options (optional) extra params to pass (see Http::request())
90 * @param string $caller The method making this request, for profiling
91 * @param Profiler $profiler An instance of the profiler for profiling, or null
93 protected function __construct(
94 $url, $options = [], $caller = __METHOD__
, $profiler = null
96 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
98 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
99 $this->parsedUrl
= wfParseUrl( $this->url
);
101 if ( isset( $options['logger'] ) ) {
102 $this->logger
= $options['logger'];
104 $this->logger
= new NullLogger();
107 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
108 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
110 $this->status
= StatusValue
::newGood( 100 ); // continue
113 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
114 $this->timeout
= $options['timeout'];
116 $this->timeout
= $wgHTTPTimeout;
118 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
119 $this->connectTimeout
= $options['connectTimeout'];
121 $this->connectTimeout
= $wgHTTPConnectTimeout;
123 if ( isset( $options['userAgent'] ) ) {
124 $this->setUserAgent( $options['userAgent'] );
126 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
129 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
132 if ( isset( $options['originalRequest'] ) ) {
133 $this->setOriginalRequest( $options['originalRequest'] );
136 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
137 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
139 foreach ( $members as $o ) {
140 if ( isset( $options[$o] ) ) {
141 // ensure that MWHttpRequest::method is always
142 // uppercased. T38137
143 if ( $o == 'method' ) {
144 $options[$o] = strtoupper( $options[$o] );
146 $this->$o = $options[$o];
150 if ( $this->noProxy
) {
151 $this->proxy
= ''; // noProxy takes precedence
154 // Profile based on what's calling us
155 $this->profiler
= $profiler;
156 $this->profileName
= $caller;
160 * @param LoggerInterface $logger
162 public function setLogger( LoggerInterface
$logger ) {
163 $this->logger
= $logger;
167 * Simple function to test if we can make any sort of requests at all, using
171 public static function canMakeRequests() {
172 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
176 * Generate a new request object
177 * @param string $url Url to use
178 * @param array $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 CurlHttpRequest|PhpHttpRequest
182 * @see MWHttpRequest::__construct
184 public static function factory( $url, $options = null, $caller = __METHOD__
) {
185 if ( !Http
::$httpEngine ) {
186 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
187 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
188 throw new DomainException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
189 ' Http::$httpEngine is set to "curl"' );
192 if ( !is_array( $options ) ) {
196 if ( !isset( $options['logger'] ) ) {
197 $options['logger'] = LoggerFactory
::getInstance( 'http' );
200 switch ( Http
::$httpEngine ) {
202 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
204 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
205 throw new DomainException( __METHOD__
. ': allow_url_fopen ' .
206 'needs to be enabled for pure PHP http requests to ' .
207 'work. If possible, curl should be used instead. See ' .
208 'http://php.net/curl.'
211 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
213 throw new DomainException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
218 * Get the body, or content, of the response to the request
222 public function getContent() {
223 return $this->content
;
227 * Set the parameters of the request
230 * @todo overload the args param
232 public function setData( $args ) {
233 $this->postData
= $args;
237 * Take care of setting up the proxy (do nothing if "noProxy" is set)
241 protected function proxySetup() {
242 // If there is an explicit proxy set and proxies are not disabled, then use it
243 if ( $this->proxy
&& !$this->noProxy
) {
247 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
248 // local URL and proxies are not disabled
249 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
252 $this->proxy
= Http
::getProxy();
257 * Check if the URL can be served by localhost
259 * @param string $url Full url to check
262 private static function isLocalURL( $url ) {
263 global $wgCommandLineMode, $wgLocalVirtualHosts;
265 if ( $wgCommandLineMode ) {
271 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
274 $domainParts = explode( '.', $host );
275 // Check if this domain or any superdomain is listed as a local virtual host
276 $domainParts = array_reverse( $domainParts );
279 $countParts = count( $domainParts );
280 for ( $i = 0; $i < $countParts; $i++
) {
281 $domainPart = $domainParts[$i];
283 $domain = $domainPart;
285 $domain = $domainPart . '.' . $domain;
288 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
301 public function setUserAgent( $UA ) {
302 $this->setHeader( 'User-Agent', $UA );
306 * Set an arbitrary header
307 * @param string $name
308 * @param string $value
310 public function setHeader( $name, $value ) {
311 // I feel like I should normalize the case here...
312 $this->reqHeaders
[$name] = $value;
316 * Get an array of the headers
319 protected function getHeaderList() {
322 if ( $this->cookieJar
) {
323 $this->reqHeaders
['Cookie'] =
324 $this->cookieJar
->serializeToHttpRequest(
325 $this->parsedUrl
['path'],
326 $this->parsedUrl
['host']
330 foreach ( $this->reqHeaders
as $name => $value ) {
331 $list[] = "$name: $value";
338 * Set a read callback to accept data read from the HTTP request.
339 * By default, data is appended to an internal buffer which can be
340 * retrieved through $req->getContent().
342 * To handle data as it comes in -- especially for large files that
343 * would not fit in memory -- you can instead set your own callback,
344 * in the form function($resource, $buffer) where the first parameter
345 * is the low-level resource being read (implementation specific),
346 * and the second parameter is the data buffer.
348 * You MUST return the number of bytes handled in the buffer; if fewer
349 * bytes are reported handled than were passed to you, the HTTP fetch
352 * @param callable|null $callback
353 * @throws InvalidArgumentException
355 public function setCallback( $callback ) {
356 if ( is_null( $callback ) ) {
357 $callback = [ $this, 'read' ];
358 } elseif ( !is_callable( $callback ) ) {
359 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
361 $this->callback
= $callback;
365 * A generic callback to read the body of the response from a remote
368 * @param resource $fh
369 * @param string $content
373 public function read( $fh, $content ) {
374 $this->content
.= $content;
375 return strlen( $content );
379 * Take care of whatever is necessary to perform the URI request.
381 * @return StatusValue
382 * @note currently returns Status for B/C
384 public function execute() {
385 throw new LogicException( 'children must override this' );
388 protected function prepare() {
391 if ( strtoupper( $this->method
) == "HEAD" ) {
392 $this->headersOnly
= true;
395 $this->proxySetup(); // set up any proxy as needed
397 if ( !$this->callback
) {
398 $this->setCallback( null );
401 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
402 $this->setUserAgent( Http
::userAgent() );
407 * Parses the headers, including the HTTP status code and any
408 * Set-Cookie headers. This function expects the headers to be
409 * found in an array in the member variable headerList.
411 protected function parseHeader() {
414 foreach ( $this->headerList
as $header ) {
415 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
416 $this->respVersion
= $match[1];
417 $this->respStatus
= $match[2];
418 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
419 $last = count( $this->respHeaders
[$lastname] ) - 1;
420 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
421 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
422 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
423 $lastname = strtolower( $match[1] );
427 $this->parseCookies();
431 * Sets HTTPRequest status member to a fatal value with the error
432 * message if the returned integer value of the status code was
433 * not successful (< 300) or a redirect (>=300 and < 400). (see
434 * RFC2616, section 10,
435 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
436 * list of status codes.)
438 protected function setStatus() {
439 if ( !$this->respHeaders
) {
440 $this->parseHeader();
443 if ( (int)$this->respStatus
> 399 ) {
444 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
445 $this->status
->fatal( "http-bad-status", $code, $message );
450 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
451 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
452 * for a list of status codes.)
456 public function getStatus() {
457 if ( !$this->respHeaders
) {
458 $this->parseHeader();
461 return (int)$this->respStatus
;
465 * Returns true if the last status code was a redirect.
469 public function isRedirect() {
470 if ( !$this->respHeaders
) {
471 $this->parseHeader();
474 $status = (int)$this->respStatus
;
476 if ( $status >= 300 && $status <= 303 ) {
484 * Returns an associative array of response headers after the
485 * request has been executed. Because some headers
486 * (e.g. Set-Cookie) can appear more than once the, each value of
487 * the associative array is an array of the values given.
491 public function getResponseHeaders() {
492 if ( !$this->respHeaders
) {
493 $this->parseHeader();
496 return $this->respHeaders
;
500 * Returns the value of the given response header.
502 * @param string $header
503 * @return string|null
505 public function getResponseHeader( $header ) {
506 if ( !$this->respHeaders
) {
507 $this->parseHeader();
510 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
511 $v = $this->respHeaders
[strtolower( $header )];
512 return $v[count( $v ) - 1];
519 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
521 * To read response cookies from the jar, getCookieJar must be called first.
523 * @param CookieJar $jar
525 public function setCookieJar( $jar ) {
526 $this->cookieJar
= $jar;
530 * Returns the cookie jar in use.
534 public function getCookieJar() {
535 if ( !$this->respHeaders
) {
536 $this->parseHeader();
539 return $this->cookieJar
;
543 * Sets a cookie. Used before a request to set up any individual
544 * cookies. Used internally after a request to parse the
545 * Set-Cookie headers.
547 * @param string $name
548 * @param string $value
551 public function setCookie( $name, $value, $attr = [] ) {
552 if ( !$this->cookieJar
) {
553 $this->cookieJar
= new CookieJar
;
556 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
557 $attr['domain'] = $this->parsedUrl
['host'];
560 $this->cookieJar
->setCookie( $name, $value, $attr );
564 * Parse the cookies in the response headers and store them in the cookie jar.
566 protected function parseCookies() {
567 if ( !$this->cookieJar
) {
568 $this->cookieJar
= new CookieJar
;
571 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
572 $url = parse_url( $this->getFinalUrl() );
573 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
574 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
580 * Returns the final URL after all redirections.
582 * Relative values of the "Location" header are incorrect as
583 * stated in RFC, however they do happen and modern browsers
584 * support them. This function loops backwards through all
585 * locations in order to build the proper absolute URI - Marooned
588 * Note that the multiple Location: headers are an artifact of
589 * CURL -- they shouldn't actually get returned this way. Rewrite
590 * this when T31232 is taken care of (high-level redirect
595 public function getFinalUrl() {
596 $headers = $this->getResponseHeaders();
598 // return full url (fix for incorrect but handled relative location)
599 if ( isset( $headers['location'] ) ) {
600 $locations = $headers['location'];
602 $foundRelativeURI = false;
603 $countLocations = count( $locations );
605 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
606 $url = parse_url( $locations[$i] );
608 if ( isset( $url['host'] ) ) {
609 $domain = $url['scheme'] . '://' . $url['host'];
610 break; // found correct URI (with host)
612 $foundRelativeURI = true;
616 if ( !$foundRelativeURI ) {
617 return $locations[$countLocations - 1];
620 return $domain . $locations[$countLocations - 1];
622 $url = parse_url( $this->url
);
623 if ( isset( $url['host'] ) ) {
624 return $url['scheme'] . '://' . $url['host'] .
625 $locations[$countLocations - 1];
633 * Returns true if the backend can follow redirects. Overridden by the
637 public function canFollowRedirects() {
642 * Set information about the original request. This can be useful for
643 * endpoints/API modules which act as a proxy for some service, and
644 * throttling etc. needs to happen in that service.
645 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
647 * @param WebRequest|array $originalRequest When in array form, it's
648 * expected to have the keys 'ip' and 'userAgent'.
649 * @note IP/user agent is personally identifiable information, and should
650 * only be set when the privacy policy of the request target is
651 * compatible with that of the MediaWiki installation.
653 public function setOriginalRequest( $originalRequest ) {
654 if ( $originalRequest instanceof WebRequest
) {
656 'ip' => $originalRequest->getIP(),
657 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
660 !is_array( $originalRequest )
661 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
663 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
664 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
667 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
668 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];