MediaWiki  master
MWHttpRequest.php
Go to the documentation of this file.
1 <?php
22 use Psr\Log\LoggerAwareInterface;
23 use Psr\Log\LoggerInterface;
24 use Psr\Log\NullLogger;
25 
33 abstract class MWHttpRequest implements LoggerAwareInterface {
34  public const SUPPORTS_FILE_POSTS = false;
35 
39  protected $timeout = 'default';
40 
41  protected $content;
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";
51  protected $reqHeaders = [];
52  protected $url;
53  protected $parsedUrl;
55  protected $callback;
56  protected $maxRedirects = 5;
57  protected $followRedirects = false;
58  protected $connectTimeout;
59 
63  protected $cookieJar;
64 
65  protected $headerList = [];
66  protected $respVersion = "0.9";
67  protected $respStatus = "200 Ok";
69  protected $respHeaders = [];
70 
72  protected $status;
73 
77  protected $profiler;
78 
82  protected $profileName;
83 
87  protected $logger;
88 
99  public function __construct(
100  $url, array $options = [], $caller = __METHOD__, Profiler $profiler = null
101  ) {
102  $this->url = wfExpandUrl( $url, PROTO_HTTP );
103  $this->parsedUrl = wfParseUrl( $this->url );
104 
105  $this->logger = $options['logger'] ?? new NullLogger();
106 
107  if ( !$this->parsedUrl || !self::isValidURI( $this->url ) ) {
108  $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
109  } else {
110  $this->status = StatusValue::newGood( 100 ); // continue
111  }
112 
113  if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
114  $this->timeout = $options['timeout'];
115  } else {
116  // The timeout should always be set by HttpRequestFactory, so this
117  // should only happen if the class was directly constructed
118  wfDeprecated( __METHOD__ . ' without the timeout option', '1.35' );
119  global $wgHTTPTimeout;
120  $this->timeout = $wgHTTPTimeout;
121  }
122  if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
123  $this->connectTimeout = $options['connectTimeout'];
124  } else {
125  // The timeout should always be set by HttpRequestFactory, so this
126  // should only happen if the class was directly constructed
127  wfDeprecated( __METHOD__ . ' without the connectTimeout option', '1.35' );
128  global $wgHTTPConnectTimeout;
129  $this->connectTimeout = $wgHTTPConnectTimeout;
130  }
131  if ( isset( $options['userAgent'] ) ) {
132  $this->setUserAgent( $options['userAgent'] );
133  }
134  if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
135  $this->setHeader(
136  'Authorization',
137  'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
138  );
139  }
140  if ( isset( $options['originalRequest'] ) ) {
141  $this->setOriginalRequest( $options['originalRequest'] );
142  }
143 
144  $this->setHeader( 'X-Request-Id', WebRequest::getRequestId() );
145 
146  $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
147  "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
148 
149  foreach ( $members as $o ) {
150  if ( isset( $options[$o] ) ) {
151  // ensure that MWHttpRequest::method is always
152  // uppercased. T38137
153  if ( $o == 'method' ) {
154  $options[$o] = strtoupper( $options[$o] );
155  }
156  $this->$o = $options[$o];
157  }
158  }
159 
160  if ( $this->noProxy ) {
161  $this->proxy = ''; // noProxy takes precedence
162  }
163 
164  // Profile based on what's calling us
165  $this->profiler = $profiler;
166  $this->profileName = $caller;
167  }
168 
172  public function setLogger( LoggerInterface $logger ) {
173  $this->logger = $logger;
174  }
175 
181  public static function canMakeRequests() {
182  return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
183  }
184 
195  public static function factory( $url, array $options = null, $caller = __METHOD__ ) {
196  if ( $options === null ) {
197  $options = [];
198  }
199  return MediaWikiServices::getInstance()->getHttpRequestFactory()
200  ->create( $url, $options, $caller );
201  }
202 
208  public function getContent() {
209  return $this->content;
210  }
211 
218  public function setData( array $args ) {
219  $this->postData = $args;
220  }
221 
227  protected function proxySetup() {
228  // If there is an explicit proxy set and proxies are not disabled, then use it
229  if ( $this->proxy && !$this->noProxy ) {
230  return;
231  }
232 
233  // Otherwise, fallback to $wgHTTPProxy if this is not a machine
234  // local URL and proxies are not disabled
235  if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
236  $this->proxy = '';
237  } else {
238  global $wgHTTPProxy;
239  $this->proxy = (string)$wgHTTPProxy;
240  }
241  }
242 
249  private static function isLocalURL( $url ) {
251 
252  if ( $wgCommandLineMode ) {
253  return false;
254  }
255 
256  // Extract host part
257  $matches = [];
258  if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
259  $host = $matches[1];
260  // Split up dotwise
261  $domainParts = explode( '.', $host );
262  // Check if this domain or any superdomain is listed as a local virtual host
263  $domainParts = array_reverse( $domainParts );
264 
265  $domain = '';
266  $countParts = count( $domainParts );
267  for ( $i = 0; $i < $countParts; $i++ ) {
268  $domainPart = $domainParts[$i];
269  if ( $i == 0 ) {
270  $domain = $domainPart;
271  } else {
272  $domain = $domainPart . '.' . $domain;
273  }
274 
275  if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
276  return true;
277  }
278  }
279  }
280 
281  return false;
282  }
283 
287  public function setUserAgent( $UA ) {
288  $this->setHeader( 'User-Agent', $UA );
289  }
290 
296  public function setHeader( $name, $value ) {
297  // I feel like I should normalize the case here...
298  $this->reqHeaders[$name] = $value;
299  }
300 
305  protected function getHeaderList() {
306  $list = [];
307 
308  if ( $this->cookieJar ) {
309  $this->reqHeaders['Cookie'] =
310  $this->cookieJar->serializeToHttpRequest(
311  $this->parsedUrl['path'],
312  $this->parsedUrl['host']
313  );
314  }
315 
316  foreach ( $this->reqHeaders as $name => $value ) {
317  $list[] = "$name: $value";
318  }
319 
320  return $list;
321  }
322 
341  public function setCallback( $callback ) {
342  $this->doSetCallback( $callback );
343  }
344 
352  protected function doSetCallback( $callback ) {
353  if ( $callback === null ) {
354  $callback = [ $this, 'read' ];
355  } elseif ( !is_callable( $callback ) ) {
356  $this->status->fatal( 'http-internal-error' );
357  throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
358  }
359  $this->callback = $callback;
360  }
361 
371  public function read( $fh, $content ) {
372  $this->content .= $content;
373  return strlen( $content );
374  }
375 
382  public function execute() {
383  throw new LogicException( 'children must override this' );
384  }
385 
386  protected function prepare() {
387  $this->content = "";
388 
389  if ( strtoupper( $this->method ) == "HEAD" ) {
390  $this->headersOnly = true;
391  }
392 
393  $this->proxySetup(); // set up any proxy as needed
394 
395  if ( !$this->callback ) {
396  $this->doSetCallback( null );
397  }
398 
399  if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
400  $http = MediaWikiServices::getInstance()->getHttpRequestFactory();
401  $this->setUserAgent( $http->getUserAgent() );
402  }
403  }
404 
410  protected function parseHeader() {
411  $lastname = "";
412 
413  // Failure without (valid) headers gets a response status of zero
414  if ( !$this->status->isOK() ) {
415  $this->respStatus = '0 Error';
416  }
417 
418  foreach ( $this->headerList as $header ) {
419  if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
420  $this->respVersion = $match[1];
421  $this->respStatus = $match[2];
422  } elseif ( preg_match( "#^[ \t]#", $header ) ) {
423  $last = count( $this->respHeaders[$lastname] ) - 1;
424  $this->respHeaders[$lastname][$last] .= "\r\n$header";
425  } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
426  $this->respHeaders[strtolower( $match[1] )][] = $match[2];
427  $lastname = strtolower( $match[1] );
428  }
429  }
430 
431  $this->parseCookies();
432  }
433 
441  protected function setStatus() {
442  if ( !$this->respHeaders ) {
443  $this->parseHeader();
444  }
445 
446  if ( ( (int)$this->respStatus > 0 && (int)$this->respStatus < 400 ) ) {
447  $this->status->setResult( true, (int)$this->respStatus );
448  } else {
449  list( $code, $message ) = explode( " ", $this->respStatus, 2 );
450  $this->status->setResult( false, (int)$this->respStatus );
451  $this->status->fatal( "http-bad-status", $code, $message );
452  }
453  }
454 
462  public function getStatus() {
463  if ( !$this->respHeaders ) {
464  $this->parseHeader();
465  }
466 
467  return (int)$this->respStatus;
468  }
469 
475  public function isRedirect() {
476  if ( !$this->respHeaders ) {
477  $this->parseHeader();
478  }
479 
480  $status = (int)$this->respStatus;
481 
482  if ( $status >= 300 && $status <= 303 ) {
483  return true;
484  }
485 
486  return false;
487  }
488 
498  public function getResponseHeaders() {
499  if ( !$this->respHeaders ) {
500  $this->parseHeader();
501  }
502 
503  return $this->respHeaders;
504  }
505 
512  public function getResponseHeader( $header ) {
513  if ( !$this->respHeaders ) {
514  $this->parseHeader();
515  }
516 
517  if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
518  $v = $this->respHeaders[strtolower( $header )];
519  return $v[count( $v ) - 1];
520  }
521 
522  return null;
523  }
524 
532  public function setCookieJar( CookieJar $jar ) {
533  $this->cookieJar = $jar;
534  }
535 
541  public function getCookieJar() {
542  if ( !$this->respHeaders ) {
543  $this->parseHeader();
544  }
545 
546  return $this->cookieJar;
547  }
548 
558  public function setCookie( $name, $value, array $attr = [] ) {
559  if ( !$this->cookieJar ) {
560  $this->cookieJar = new CookieJar;
561  }
562 
563  if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
564  $attr['domain'] = $this->parsedUrl['host'];
565  }
566 
567  $this->cookieJar->setCookie( $name, $value, $attr );
568  }
569 
573  protected function parseCookies() {
574  if ( !$this->cookieJar ) {
575  $this->cookieJar = new CookieJar;
576  }
577 
578  if ( isset( $this->respHeaders['set-cookie'] ) ) {
579  $url = parse_url( $this->getFinalUrl() );
580  foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
581  $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
582  }
583  }
584  }
585 
602  public function getFinalUrl() {
603  $headers = $this->getResponseHeaders();
604 
605  // return full url (fix for incorrect but handled relative location)
606  if ( isset( $headers['location'] ) ) {
607  $locations = $headers['location'];
608  $domain = '';
609  $foundRelativeURI = false;
610  $countLocations = count( $locations );
611 
612  for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
613  $url = parse_url( $locations[$i] );
614 
615  if ( isset( $url['host'] ) ) {
616  $domain = $url['scheme'] . '://' . $url['host'];
617  break; // found correct URI (with host)
618  } else {
619  $foundRelativeURI = true;
620  }
621  }
622 
623  if ( !$foundRelativeURI ) {
624  return $locations[$countLocations - 1];
625  }
626  if ( $domain ) {
627  return $domain . $locations[$countLocations - 1];
628  }
629  $url = parse_url( $this->url );
630  if ( isset( $url['host'] ) ) {
631  return $url['scheme'] . '://' . $url['host'] .
632  $locations[$countLocations - 1];
633  }
634  }
635 
636  return $this->url;
637  }
638 
644  public function canFollowRedirects() {
645  return true;
646  }
647 
660  public function setOriginalRequest( $originalRequest ) {
661  if ( $originalRequest instanceof WebRequest ) {
662  $originalRequest = [
663  'ip' => $originalRequest->getIP(),
664  'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
665  ];
666  } elseif (
667  !is_array( $originalRequest )
668  || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
669  ) {
670  throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
671  . "WebRequest or an array with 'ip' and 'userAgent' keys" );
672  }
673 
674  $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
675  $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
676  }
677 
694  public static function isValidURI( $uri ) {
695  return (bool)preg_match(
696  '/^https?:\/\/[^\/\s]\S*$/D',
697  $uri
698  );
699  }
700 }
MWHttpRequest\$headerList
$headerList
Definition: MWHttpRequest.php:65
$wgLocalVirtualHosts
$wgLocalVirtualHosts
Local virtual hosts.
Definition: DefaultSettings.php:8942
MWHttpRequest\$headersOnly
$headersOnly
Definition: MWHttpRequest.php:42
StatusValue
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: StatusValue.php:43
MWHttpRequest\$logger
LoggerInterface $logger
Definition: MWHttpRequest.php:87
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
MWHttpRequest\$callback
callable $callback
Definition: MWHttpRequest.php:55
MWHttpRequest\setStatus
setStatus()
Sets HTTPRequest status member to a fatal value with the error message if the returned integer value ...
Definition: MWHttpRequest.php:441
MWHttpRequest\$respVersion
$respVersion
Definition: MWHttpRequest.php:66
MWHttpRequest\__construct
__construct( $url, array $options=[], $caller=__METHOD__, Profiler $profiler=null)
Definition: MWHttpRequest.php:99
MWHttpRequest\doSetCallback
doSetCallback( $callback)
Worker function for setting callbacks.
Definition: MWHttpRequest.php:352
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
MWHttpRequest\proxySetup
proxySetup()
Take care of setting up the proxy (do nothing if "noProxy" is set)
Definition: MWHttpRequest.php:227
MWHttpRequest\$maxRedirects
$maxRedirects
Definition: MWHttpRequest.php:56
MWHttpRequest\$sslVerifyCert
$sslVerifyCert
Definition: MWHttpRequest.php:47
MWHttpRequest\$followRedirects
$followRedirects
Definition: MWHttpRequest.php:57
MWHttpRequest\$content
$content
Definition: MWHttpRequest.php:41
MWHttpRequest\$status
StatusValue $status
Definition: MWHttpRequest.php:72
MWHttpRequest\$profiler
Profiler $profiler
Definition: MWHttpRequest.php:77
$wgHTTPConnectTimeout
float int $wgHTTPConnectTimeout
Timeout for connections done internally (in seconds).
Definition: DefaultSettings.php:8893
MWHttpRequest\getStatus
getStatus()
Get the integer value of the HTTP status code (e.g.
Definition: MWHttpRequest.php:462
MWHttpRequest\$noProxy
$noProxy
Definition: MWHttpRequest.php:45
MWHttpRequest\setCookieJar
setCookieJar(CookieJar $jar)
Tells the MWHttpRequest object to use this pre-loaded CookieJar.
Definition: MWHttpRequest.php:532
$wgHTTPProxy
$wgHTTPProxy
Proxy to use for CURL requests.
Definition: DefaultSettings.php:8927
MWHttpRequest\parseHeader
parseHeader()
Parses the headers, including the HTTP status code and any Set-Cookie headers.
Definition: MWHttpRequest.php:410
MWHttpRequest\$connectTimeout
$connectTimeout
Definition: MWHttpRequest.php:58
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:792
MWHttpRequest\$postData
$postData
Definition: MWHttpRequest.php:43
MWHttpRequest\getContent
getContent()
Get the body, or content, of the response to the request.
Definition: MWHttpRequest.php:208
MWHttpRequest\SUPPORTS_FILE_POSTS
const SUPPORTS_FILE_POSTS
Definition: MWHttpRequest.php:34
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
MWHttpRequest\parseCookies
parseCookies()
Parse the cookies in the response headers and store them in the cookie jar.
Definition: MWHttpRequest.php:573
MWHttpRequest\$respStatus
$respStatus
Definition: MWHttpRequest.php:67
CookieJar\setCookie
setCookie( $name, $value, $attr)
Set a cookie in the cookie jar.
Definition: CookieJar.php:36
MWHttpRequest\setData
setData(array $args)
Set the parameters of the request.
Definition: MWHttpRequest.php:218
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:29
$matches
$matches
Definition: NoLocalSettings.php:24
MWHttpRequest\isRedirect
isRedirect()
Returns true if the last status code was a redirect.
Definition: MWHttpRequest.php:475
Profiler
Profiler base class that defines the interface and some shared functionality.
Definition: Profiler.php:36
MWHttpRequest\getCookieJar
getCookieJar()
Returns the cookie jar in use.
Definition: MWHttpRequest.php:541
MWHttpRequest\$timeout
int string $timeout
Definition: MWHttpRequest.php:39
$args
if( $line===false) $args
Definition: mcc.php:124
MWHttpRequest\isLocalURL
static isLocalURL( $url)
Check if the URL can be served by localhost.
Definition: MWHttpRequest.php:249
MWHttpRequest\$cookieJar
CookieJar $cookieJar
Definition: MWHttpRequest.php:63
$wgHTTPTimeout
float int $wgHTTPTimeout
Timeout for HTTP requests done internally, in seconds.
Definition: DefaultSettings.php:8883
MWHttpRequest\read
read( $fh, $content)
A generic callback to read the body of the response from a remote server.
Definition: MWHttpRequest.php:371
$header
$header
Definition: updateCredits.php:41
MWHttpRequest\$method
$method
Definition: MWHttpRequest.php:49
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
MWHttpRequest
This wrapper class will call out to curl (if available) or fallback to regular PHP if necessary for h...
Definition: MWHttpRequest.php:33
MWHttpRequest\setCallback
setCallback( $callback)
Set a read callback to accept data read from the HTTP request.
Definition: MWHttpRequest.php:341
MWHttpRequest\setHeader
setHeader( $name, $value)
Set an arbitrary header.
Definition: MWHttpRequest.php:296
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:208
MWHttpRequest\getHeaderList
getHeaderList()
Get an array of the headers.
Definition: MWHttpRequest.php:305
MWHttpRequest\$parsedUrl
$parsedUrl
Definition: MWHttpRequest.php:53
MWHttpRequest\$profileName
string $profileName
Definition: MWHttpRequest.php:82
MWHttpRequest\getResponseHeaders
getResponseHeaders()
Returns an associative array of response headers after the request has been executed.
Definition: MWHttpRequest.php:498
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1994
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
MWHttpRequest\$sslVerifyHost
$sslVerifyHost
Definition: MWHttpRequest.php:46
MWHttpRequest\setCookie
setCookie( $name, $value, array $attr=[])
Sets a cookie.
Definition: MWHttpRequest.php:558
MWHttpRequest\$respHeaders
string[][] $respHeaders
Definition: MWHttpRequest.php:69
MWHttpRequest\$reqHeaders
array $reqHeaders
Definition: MWHttpRequest.php:51
CookieJar
Cookie jar to use with MWHttpRequest.
Definition: CookieJar.php:25
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:327
MWHttpRequest\$caInfo
$caInfo
Definition: MWHttpRequest.php:48
MWHttpRequest\canMakeRequests
static canMakeRequests()
Simple function to test if we can make any sort of requests at all, using cURL or fopen()
Definition: MWHttpRequest.php:181
MWHttpRequest\isValidURI
static isValidURI( $uri)
Check that the given URI is a valid one.
Definition: MWHttpRequest.php:694
MWHttpRequest\getResponseHeader
getResponseHeader( $header)
Returns the value of the given response header.
Definition: MWHttpRequest.php:512
MWHttpRequest\setUserAgent
setUserAgent( $UA)
Definition: MWHttpRequest.php:287
MWHttpRequest\execute
execute()
Take care of whatever is necessary to perform the URI request.
Definition: MWHttpRequest.php:382
MWHttpRequest\canFollowRedirects
canFollowRedirects()
Returns true if the backend can follow redirects.
Definition: MWHttpRequest.php:644
MWHttpRequest\$proxy
$proxy
Definition: MWHttpRequest.php:44
MWHttpRequest\setLogger
setLogger(LoggerInterface $logger)
Definition: MWHttpRequest.php:172
MWHttpRequest\getFinalUrl
getFinalUrl()
Returns the final URL after all redirections.
Definition: MWHttpRequest.php:602
MWHttpRequest\setOriginalRequest
setOriginalRequest( $originalRequest)
Set information about the original request.
Definition: MWHttpRequest.php:660
MWHttpRequest\$url
$url
Definition: MWHttpRequest.php:52
MWHttpRequest\factory
static factory( $url, array $options=null, $caller=__METHOD__)
Generate a new request object.
Definition: MWHttpRequest.php:195
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:490
MWHttpRequest\prepare
prepare()
Definition: MWHttpRequest.php:386