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  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  ) {
103 
104  $this->url = wfExpandUrl( $url, PROTO_HTTP );
105  $this->parsedUrl = wfParseUrl( $this->url );
106 
107  $this->logger = $options['logger'] ?? new NullLogger();
108 
109  if ( !$this->parsedUrl || !self::isValidURI( $this->url ) ) {
110  $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
111  } else {
112  $this->status = StatusValue::newGood( 100 ); // continue
113  }
114 
115  if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
116  $this->timeout = $options['timeout'];
117  } else {
118  $this->timeout = $wgHTTPTimeout;
119  }
120  if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
121  $this->connectTimeout = $options['connectTimeout'];
122  } else {
123  $this->connectTimeout = $wgHTTPConnectTimeout;
124  }
125  if ( isset( $options['userAgent'] ) ) {
126  $this->setUserAgent( $options['userAgent'] );
127  }
128  if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
129  $this->setHeader(
130  'Authorization',
131  'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
132  );
133  }
134  if ( isset( $options['originalRequest'] ) ) {
135  $this->setOriginalRequest( $options['originalRequest'] );
136  }
137 
138  $this->setHeader( 'X-Request-Id', WebRequest::getRequestId() );
139 
140  $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
141  "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
142 
143  foreach ( $members as $o ) {
144  if ( isset( $options[$o] ) ) {
145  // ensure that MWHttpRequest::method is always
146  // uppercased. T38137
147  if ( $o == 'method' ) {
148  $options[$o] = strtoupper( $options[$o] );
149  }
150  $this->$o = $options[$o];
151  }
152  }
153 
154  if ( $this->noProxy ) {
155  $this->proxy = ''; // noProxy takes precedence
156  }
157 
158  // Profile based on what's calling us
159  $this->profiler = $profiler;
160  $this->profileName = $caller;
161  }
162 
166  public function setLogger( LoggerInterface $logger ) {
167  $this->logger = $logger;
168  }
169 
175  public static function canMakeRequests() {
176  return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
177  }
178 
189  public static function factory( $url, array $options = null, $caller = __METHOD__ ) {
190  if ( $options === null ) {
191  $options = [];
192  }
193  return MediaWikiServices::getInstance()->getHttpRequestFactory()
194  ->create( $url, $options, $caller );
195  }
196 
202  public function getContent() {
203  return $this->content;
204  }
205 
212  public function setData( array $args ) {
213  $this->postData = $args;
214  }
215 
221  protected function proxySetup() {
222  // If there is an explicit proxy set and proxies are not disabled, then use it
223  if ( $this->proxy && !$this->noProxy ) {
224  return;
225  }
226 
227  // Otherwise, fallback to $wgHTTPProxy if this is not a machine
228  // local URL and proxies are not disabled
229  if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
230  $this->proxy = '';
231  } else {
232  global $wgHTTPProxy;
233  $this->proxy = (string)$wgHTTPProxy;
234  }
235  }
236 
243  private static function isLocalURL( $url ) {
245 
246  if ( $wgCommandLineMode ) {
247  return false;
248  }
249 
250  // Extract host part
251  $matches = [];
252  if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
253  $host = $matches[1];
254  // Split up dotwise
255  $domainParts = explode( '.', $host );
256  // Check if this domain or any superdomain is listed as a local virtual host
257  $domainParts = array_reverse( $domainParts );
258 
259  $domain = '';
260  $countParts = count( $domainParts );
261  for ( $i = 0; $i < $countParts; $i++ ) {
262  $domainPart = $domainParts[$i];
263  if ( $i == 0 ) {
264  $domain = $domainPart;
265  } else {
266  $domain = $domainPart . '.' . $domain;
267  }
268 
269  if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
270  return true;
271  }
272  }
273  }
274 
275  return false;
276  }
277 
282  public function setUserAgent( $UA ) {
283  $this->setHeader( 'User-Agent', $UA );
284  }
285 
291  public function setHeader( $name, $value ) {
292  // I feel like I should normalize the case here...
293  $this->reqHeaders[$name] = $value;
294  }
295 
300  protected function getHeaderList() {
301  $list = [];
302 
303  if ( $this->cookieJar ) {
304  $this->reqHeaders['Cookie'] =
305  $this->cookieJar->serializeToHttpRequest(
306  $this->parsedUrl['path'],
307  $this->parsedUrl['host']
308  );
309  }
310 
311  foreach ( $this->reqHeaders as $name => $value ) {
312  $list[] = "$name: $value";
313  }
314 
315  return $list;
316  }
317 
336  public function setCallback( $callback ) {
337  $this->doSetCallback( $callback );
338  }
339 
347  protected function doSetCallback( $callback ) {
348  if ( $callback === null ) {
349  $callback = [ $this, 'read' ];
350  } elseif ( !is_callable( $callback ) ) {
351  $this->status->fatal( 'http-internal-error' );
352  throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
353  }
354  $this->callback = $callback;
355  }
356 
366  public function read( $fh, $content ) {
367  $this->content .= $content;
368  return strlen( $content );
369  }
370 
377  public function execute() {
378  throw new LogicException( 'children must override this' );
379  }
380 
381  protected function prepare() {
382  $this->content = "";
383 
384  if ( strtoupper( $this->method ) == "HEAD" ) {
385  $this->headersOnly = true;
386  }
387 
388  $this->proxySetup(); // set up any proxy as needed
389 
390  if ( !$this->callback ) {
391  $this->doSetCallback( null );
392  }
393 
394  if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
395  $http = MediaWikiServices::getInstance()->getHttpRequestFactory();
396  $this->setUserAgent( $http->getUserAgent() );
397  }
398  }
399 
405  protected function parseHeader() {
406  $lastname = "";
407 
408  // Failure without (valid) headers gets a response status of zero
409  if ( !$this->status->isOK() ) {
410  $this->respStatus = '0 Error';
411  }
412 
413  foreach ( $this->headerList as $header ) {
414  if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
415  $this->respVersion = $match[1];
416  $this->respStatus = $match[2];
417  } elseif ( preg_match( "#^[ \t]#", $header ) ) {
418  $last = count( $this->respHeaders[$lastname] ) - 1;
419  $this->respHeaders[$lastname][$last] .= "\r\n$header";
420  } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
421  $this->respHeaders[strtolower( $match[1] )][] = $match[2];
422  $lastname = strtolower( $match[1] );
423  }
424  }
425 
426  $this->parseCookies();
427  }
428 
436  protected function setStatus() {
437  if ( !$this->respHeaders ) {
438  $this->parseHeader();
439  }
440 
441  if ( ( (int)$this->respStatus > 0 && (int)$this->respStatus < 400 ) ) {
442  $this->status->setResult( true, (int)$this->respStatus );
443  } else {
444  list( $code, $message ) = explode( " ", $this->respStatus, 2 );
445  $this->status->setResult( false, (int)$this->respStatus );
446  $this->status->fatal( "http-bad-status", $code, $message );
447  }
448  }
449 
457  public function getStatus() {
458  if ( !$this->respHeaders ) {
459  $this->parseHeader();
460  }
461 
462  return (int)$this->respStatus;
463  }
464 
470  public function isRedirect() {
471  if ( !$this->respHeaders ) {
472  $this->parseHeader();
473  }
474 
475  $status = (int)$this->respStatus;
476 
477  if ( $status >= 300 && $status <= 303 ) {
478  return true;
479  }
480 
481  return false;
482  }
483 
493  public function getResponseHeaders() {
494  if ( !$this->respHeaders ) {
495  $this->parseHeader();
496  }
497 
498  return $this->respHeaders;
499  }
500 
507  public function getResponseHeader( $header ) {
508  if ( !$this->respHeaders ) {
509  $this->parseHeader();
510  }
511 
512  if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
513  $v = $this->respHeaders[strtolower( $header )];
514  return $v[count( $v ) - 1];
515  }
516 
517  return null;
518  }
519 
527  public function setCookieJar( CookieJar $jar ) {
528  $this->cookieJar = $jar;
529  }
530 
536  public function getCookieJar() {
537  if ( !$this->respHeaders ) {
538  $this->parseHeader();
539  }
540 
541  return $this->cookieJar;
542  }
543 
553  public function setCookie( $name, $value, array $attr = [] ) {
554  if ( !$this->cookieJar ) {
555  $this->cookieJar = new CookieJar;
556  }
557 
558  if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
559  $attr['domain'] = $this->parsedUrl['host'];
560  }
561 
562  $this->cookieJar->setCookie( $name, $value, $attr );
563  }
564 
568  protected function parseCookies() {
569  if ( !$this->cookieJar ) {
570  $this->cookieJar = new CookieJar;
571  }
572 
573  if ( isset( $this->respHeaders['set-cookie'] ) ) {
574  $url = parse_url( $this->getFinalUrl() );
575  foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
576  $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
577  }
578  }
579  }
580 
597  public function getFinalUrl() {
598  $headers = $this->getResponseHeaders();
599 
600  // return full url (fix for incorrect but handled relative location)
601  if ( isset( $headers['location'] ) ) {
602  $locations = $headers['location'];
603  $domain = '';
604  $foundRelativeURI = false;
605  $countLocations = count( $locations );
606 
607  for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
608  $url = parse_url( $locations[$i] );
609 
610  if ( isset( $url['host'] ) ) {
611  $domain = $url['scheme'] . '://' . $url['host'];
612  break; // found correct URI (with host)
613  } else {
614  $foundRelativeURI = true;
615  }
616  }
617 
618  if ( !$foundRelativeURI ) {
619  return $locations[$countLocations - 1];
620  }
621  if ( $domain ) {
622  return $domain . $locations[$countLocations - 1];
623  }
624  $url = parse_url( $this->url );
625  if ( isset( $url['host'] ) ) {
626  return $url['scheme'] . '://' . $url['host'] .
627  $locations[$countLocations - 1];
628  }
629  }
630 
631  return $this->url;
632  }
633 
639  public function canFollowRedirects() {
640  return true;
641  }
642 
655  public function setOriginalRequest( $originalRequest ) {
656  if ( $originalRequest instanceof WebRequest ) {
657  $originalRequest = [
658  'ip' => $originalRequest->getIP(),
659  'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
660  ];
661  } elseif (
662  !is_array( $originalRequest )
663  || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
664  ) {
665  throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
666  . "WebRequest or an array with 'ip' and 'userAgent' keys" );
667  }
668 
669  $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
670  $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
671  }
672 
689  public static function isValidURI( $uri ) {
690  return (bool)preg_match(
691  '/^https?:\/\/[^\/\s]\S*$/D',
692  $uri
693  );
694  }
695 }
MWHttpRequest\$headerList
$headerList
Definition: MWHttpRequest.php:65
$wgLocalVirtualHosts
$wgLocalVirtualHosts
Local virtual hosts.
Definition: DefaultSettings.php:8406
$wgHTTPConnectTimeout
$wgHTTPConnectTimeout
Timeout for connections done internally (in seconds) Only works for curl.
Definition: DefaultSettings.php:8412
MWHttpRequest\$headersOnly
$headersOnly
Definition: MWHttpRequest.php:42
StatusValue
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: StatusValue.php:42
MWHttpRequest\$logger
LoggerInterface $logger
Definition: MWHttpRequest.php:87
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
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:436
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:347
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:130
MWHttpRequest\proxySetup
proxySetup()
Take care of setting up the proxy (do nothing if "noProxy" is set)
Definition: MWHttpRequest.php:221
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
$wgHTTPTimeout
int $wgHTTPTimeout
Timeout for HTTP requests done internally, in seconds.
Definition: DefaultSettings.php:8375
MWHttpRequest\$profiler
Profiler $profiler
Definition: MWHttpRequest.php:77
MWHttpRequest\getStatus
getStatus()
Get the integer value of the HTTP status code (e.g.
Definition: MWHttpRequest.php:457
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:527
$wgHTTPProxy
$wgHTTPProxy
Proxy to use for CURL requests.
Definition: DefaultSettings.php:8391
MWHttpRequest\parseHeader
parseHeader()
Parses the headers, including the HTTP status code and any Set-Cookie headers.
Definition: MWHttpRequest.php:405
MWHttpRequest\$connectTimeout
$connectTimeout
Definition: MWHttpRequest.php:58
wfParseUrl
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
Definition: GlobalFunctions.php:793
MWHttpRequest\$postData
$postData
Definition: MWHttpRequest.php:43
MWHttpRequest\getContent
getContent()
Get the body, or content, of the response to the request.
Definition: MWHttpRequest.php:202
MWHttpRequest\SUPPORTS_FILE_POSTS
const SUPPORTS_FILE_POSTS
Definition: MWHttpRequest.php:34
MWHttpRequest\parseCookies
parseCookies()
Parse the cookies in the response headers and store them in the cookie jar.
Definition: MWHttpRequest.php:568
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:212
$wgCommandLineMode
global $wgCommandLineMode
Definition: DevelopmentSettings.php:28
$matches
$matches
Definition: NoLocalSettings.php:24
MWHttpRequest\isRedirect
isRedirect()
Returns true if the last status code was a redirect.
Definition: MWHttpRequest.php:470
Profiler
Profiler base class that defines the interface and some trivial functionality.
Definition: Profiler.php:33
MWHttpRequest\getCookieJar
getCookieJar()
Returns the cookie jar in use.
Definition: MWHttpRequest.php:536
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:243
MWHttpRequest\$cookieJar
CookieJar $cookieJar
Definition: MWHttpRequest.php:63
MWHttpRequest\read
read( $fh, $content)
A generic callback to read the body of the response from a remote server.
Definition: MWHttpRequest.php:366
$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:81
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:336
MWHttpRequest\setHeader
setHeader( $name, $value)
Set an arbitrary header.
Definition: MWHttpRequest.php:291
PROTO_HTTP
const PROTO_HTTP
Definition: Defines.php:199
MWHttpRequest\getHeaderList
getHeaderList()
Get an array of the headers.
Definition: MWHttpRequest.php:300
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:493
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:2064
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:43
MWHttpRequest\$sslVerifyHost
$sslVerifyHost
Definition: MWHttpRequest.php:46
MWHttpRequest\setCookie
setCookie( $name, $value, array $attr=[])
Sets a cookie.
Definition: MWHttpRequest.php:553
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:310
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:175
MWHttpRequest\isValidURI
static isValidURI( $uri)
Check that the given URI is a valid one.
Definition: MWHttpRequest.php:689
MWHttpRequest\getResponseHeader
getResponseHeader( $header)
Returns the value of the given response header.
Definition: MWHttpRequest.php:507
MWHttpRequest\setUserAgent
setUserAgent( $UA)
Set the user agent.
Definition: MWHttpRequest.php:282
MWHttpRequest\execute
execute()
Take care of whatever is necessary to perform the URI request.
Definition: MWHttpRequest.php:377
MWHttpRequest\canFollowRedirects
canFollowRedirects()
Returns true if the backend can follow redirects.
Definition: MWHttpRequest.php:639
MWHttpRequest\$proxy
$proxy
Definition: MWHttpRequest.php:44
MWHttpRequest\setLogger
setLogger(LoggerInterface $logger)
Definition: MWHttpRequest.php:166
MWHttpRequest\getFinalUrl
getFinalUrl()
Returns the final URL after all redirections.
Definition: MWHttpRequest.php:597
MWHttpRequest\setOriginalRequest
setOriginalRequest( $originalRequest)
Set information about the original request.
Definition: MWHttpRequest.php:655
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:189
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:491
MWHttpRequest\prepare
prepare()
Definition: MWHttpRequest.php:381