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