MediaWiki  master
HttpRequestFactory.php
Go to the documentation of this file.
1 <?php
20 namespace MediaWiki\Http;
21 
22 use GuzzleHttp\Client;
26 use MultiHttpClient;
27 use MWHttpRequest;
28 use Profiler;
29 use Psr\Log\LoggerInterface;
30 use Status;
31 
37  private $options;
39  private $logger;
40 
44  public const CONSTRUCTOR_OPTIONS = [
45  'HTTPTimeout',
46  'HTTPConnectTimeout',
47  'HTTPMaxTimeout',
48  'HTTPMaxConnectTimeout',
49  'LocalVirtualHosts',
50  'LocalHTTPProxy',
51  ];
52 
53  public function __construct( ServiceOptions $options, LoggerInterface $logger ) {
54  $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
55  $this->options = $options;
56  $this->logger = $logger;
57  }
58 
94  public function create( $url, array $options = [], $caller = __METHOD__ ) {
95  if ( !isset( $options['logger'] ) ) {
96  $options['logger'] = $this->logger;
97  }
98  $options['timeout'] = $this->normalizeTimeout(
99  $options['timeout'] ?? null,
100  $options['maxTimeout'] ?? null,
101  $this->options->get( 'HTTPTimeout' ),
102  $this->options->get( 'HTTPMaxTimeout' )
103  );
104  $options['connectTimeout'] = $this->normalizeTimeout(
105  $options['connectTimeout'] ?? null,
106  $options['maxConnectTimeout'] ?? null,
107  $this->options->get( 'HTTPConnectTimeout' ),
108  $this->options->get( 'HTTPMaxConnectTimeout' )
109  );
110 
111  return new GuzzleHttpRequest( $url, $options, $caller, Profiler::instance() );
112  }
113 
124  private function normalizeTimeout( $parameter, $maxParameter, $default, $maxConfigured ) {
125  if ( $parameter === 'default' || $parameter === null ) {
126  if ( !is_numeric( $default ) ) {
127  throw new \InvalidArgumentException(
128  '$wgHTTPTimeout and $wgHTTPConnectTimeout must be set to a number' );
129  }
130  $value = $default;
131  } else {
132  $value = $parameter;
133  }
134  if ( $maxParameter !== null ) {
135  $max = $maxParameter;
136  } else {
137  $max = $maxConfigured;
138  }
139  if ( $max && $value > $max ) {
140  return $max;
141  } else {
142  return $value;
143  }
144  }
145 
151  public function canMakeRequests() {
152  return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
153  }
154 
166  public function request( $method, $url, array $options = [], $caller = __METHOD__ ) {
168  $logger->debug( "$method: $url" );
169 
170  $options['method'] = strtoupper( $method );
171 
172  $req = $this->create( $url, $options, $caller );
173  $status = $req->execute();
174 
175  if ( $status->isOK() ) {
176  return $req->getContent();
177  } else {
178  $errors = $status->getErrorsByType( 'error' );
179  $logger->warning( Status::wrap( $status )->getWikiText( false, false, 'en' ),
180  [ 'error' => $errors, 'caller' => $caller, 'content' => $req->getContent() ] );
181  return null;
182  }
183  }
184 
194  public function get( $url, array $options = [], $caller = __METHOD__ ) {
195  return $this->request( 'GET', $url, $options, $caller );
196  }
197 
207  public function post( $url, array $options = [], $caller = __METHOD__ ) {
208  return $this->request( 'POST', $url, $options, $caller );
209  }
210 
214  public function getUserAgent() {
215  return 'MediaWiki/' . MW_VERSION;
216  }
217 
230  public function createMultiClient( $options = [] ) {
231  $options['reqTimeout'] = $this->normalizeTimeout(
232  $options['reqTimeout'] ?? $options['timeout'] ?? null,
233  $options['maxReqTimeout'] ?? $options['maxTimeout'] ?? null,
234  $this->options->get( 'HTTPTimeout' ),
235  $this->options->get( 'HTTPMaxTimeout' )
236  );
237  $options['connTimeout'] = $this->normalizeTimeout(
238  $options['connTimeout'] ?? $options['connectTimeout'] ?? null,
239  $options['maxConnTimeout'] ?? $options['maxConnectTimeout'] ?? null,
240  $this->options->get( 'HTTPConnectTimeout' ),
241  $this->options->get( 'HTTPMaxConnectTimeout' )
242  );
243  $options += [
244  'maxReqTimeout' => $this->options->get( 'HTTPMaxTimeout' ),
245  'maxConnTimeout' => $this->options->get( 'HTTPMaxConnectTimeout' ),
246  'userAgent' => $this->getUserAgent(),
247  'logger' => $this->logger,
248  'localProxy' => $this->options->get( 'LocalHTTPProxy' ),
249  'localVirtualHosts' => $this->options->get( 'LocalVirtualHosts' ),
250  ];
251  return new MultiHttpClient( $options );
252  }
253 
267  public function createGuzzleClient( array $config = [] ): Client {
268  $config['timeout'] = $this->normalizeTimeout(
269  $config['timeout'] ?? null,
270  $config['maxTimeout'] ?? null,
271  $this->options->get( 'HTTPTimeout' ),
272  $this->options->get( 'HTTPMaxTimeout' )
273  );
274 
275  $config['connect_timeout'] = $this->normalizeTimeout(
276  $config['connect_timeout'] ?? null,
277  $config['maxConnectTimeout'] ?? null,
278  $this->options->get( 'HTTPConnectTimeout' ),
279  $this->options->get( 'HTTPMaxConnectTimeout' )
280  );
281 
282  if ( !isset( $config['headers']['User-Agent'] ) ) {
283  $config['headers']['User-Agent'] = $this->getUserAgent();
284  }
285 
286  return new Client( $config );
287  }
288 }
MultiHttpClient
Class to handle multiple HTTP requests.
Definition: MultiHttpClient.php:55
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
MediaWiki\Http\HttpRequestFactory\canMakeRequests
canMakeRequests()
Simple function to test if we can make any sort of requests at all, using cURL or fopen()
Definition: HttpRequestFactory.php:151
MediaWiki\Logger\LoggerFactory\getInstance
static getInstance( $channel)
Get a named logger instance from the currently configured logger factory.
Definition: LoggerFactory.php:92
MediaWiki\Http\HttpRequestFactory
Factory creating MWHttpRequest objects.
Definition: HttpRequestFactory.php:35
MediaWiki\Http\HttpRequestFactory\createMultiClient
createMultiClient( $options=[])
Get a MultiHttpClient with MediaWiki configured defaults applied.
Definition: HttpRequestFactory.php:230
MediaWiki\Http
Definition: HttpRequestFactory.php:20
MW_VERSION
const MW_VERSION
The running version of MediaWiki.
Definition: Defines.php:36
MediaWiki\Http\HttpRequestFactory\createGuzzleClient
createGuzzleClient(array $config=[])
Get a GuzzleHttp\Client instance.
Definition: HttpRequestFactory.php:267
MediaWiki\Http\HttpRequestFactory\$logger
LoggerInterface $logger
Definition: HttpRequestFactory.php:39
MediaWiki\Http\HttpRequestFactory\__construct
__construct(ServiceOptions $options, LoggerInterface $logger)
Definition: HttpRequestFactory.php:53
MediaWiki\Http\HttpRequestFactory\getUserAgent
getUserAgent()
Definition: HttpRequestFactory.php:214
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:44
MediaWiki\Config\ServiceOptions
A class for passing options to services.
Definition: ServiceOptions.php:27
MediaWiki\Http\HttpRequestFactory\request
request( $method, $url, array $options=[], $caller=__METHOD__)
Perform an HTTP request.
Definition: HttpRequestFactory.php:166
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Status\wrap
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:62
GuzzleHttpRequest
MWHttpRequest implemented using the Guzzle library.
Definition: GuzzleHttpRequest.php:41
Profiler
Profiler base class that defines the interface and some shared functionality.
Definition: Profiler.php:36
MWHttpRequest
This wrapper class will call out to curl (if available) or fallback to regular PHP if necessary for h...
Definition: MWHttpRequest.php:33
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1844
MediaWiki\Http\HttpRequestFactory\CONSTRUCTOR_OPTIONS
const CONSTRUCTOR_OPTIONS
Definition: HttpRequestFactory.php:44
MediaWiki\Http\HttpRequestFactory\post
post( $url, array $options=[], $caller=__METHOD__)
Simple wrapper for request( 'POST' ), parameters have same meaning as for request()
Definition: HttpRequestFactory.php:207
MediaWiki\Http\HttpRequestFactory\normalizeTimeout
normalizeTimeout( $parameter, $maxParameter, $default, $maxConfigured)
Given a passed parameter value, a default and a maximum, figure out the correct timeout to pass to th...
Definition: HttpRequestFactory.php:124
MediaWiki\$config
Config $config
Definition: MediaWiki.php:42
MediaWiki\Config\ServiceOptions\get
get( $key)
Definition: ServiceOptions.php:93
MediaWiki\Http\HttpRequestFactory\$options
ServiceOptions $options
Definition: HttpRequestFactory.php:37
MediaWiki\Http\HttpRequestFactory\create
create( $url, array $options=[], $caller=__METHOD__)
Generate a new MWHttpRequest object.
Definition: HttpRequestFactory.php:94
MediaWiki\Config\ServiceOptions\assertRequiredOptions
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Definition: ServiceOptions.php:71