MediaWiki  master
HttpRequestFactory.php
Go to the documentation of this file.
1 <?php
20 namespace MediaWiki\Http;
21 
22 use CurlHttpRequest;
23 use GuzzleHttp\Client;
25 use Http;
28 use MultiHttpClient;
29 use MWHttpRequest;
30 use PhpHttpRequest;
31 use Profiler;
32 use Psr\Log\LoggerInterface;
33 use RuntimeException;
34 use Status;
35 
41  private $options;
43  private $logger;
44 
48  public const CONSTRUCTOR_OPTIONS = [
49  'HTTPTimeout',
50  'HTTPConnectTimeout',
51  'HTTPMaxTimeout',
52  'HTTPMaxConnectTimeout',
53  ];
54 
55  public function __construct( ServiceOptions $options, LoggerInterface $logger ) {
56  $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
57  $this->options = $options;
58  $this->logger = $logger;
59  }
60 
98  public function create( $url, array $options = [], $caller = __METHOD__ ) {
99  if ( !Http::$httpEngine ) {
100  Http::$httpEngine = 'guzzle';
101  }
102 
103  if ( !isset( $options['logger'] ) ) {
104  $options['logger'] = $this->logger;
105  }
106  $options['timeout'] = $this->normalizeTimeout(
107  $options['timeout'] ?? null,
108  $options['maxTimeout'] ?? null,
109  $this->options->get( 'HTTPTimeout' ),
110  $this->options->get( 'HTTPMaxTimeout' )
111  );
112  $options['connectTimeout'] = $this->normalizeTimeout(
113  $options['connectTimeout'] ?? null,
114  $options['maxConnectTimeout'] ?? null,
115  $this->options->get( 'HTTPConnectTimeout' ),
116  $this->options->get( 'HTTPMaxConnectTimeout' )
117  );
118 
119  switch ( Http::$httpEngine ) {
120  case 'guzzle':
121  return new GuzzleHttpRequest( $url, $options, $caller, Profiler::instance() );
122  case 'curl':
123  return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
124  case 'php':
125  return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
126  default:
127  throw new RuntimeException( __METHOD__ . ': The requested engine is not valid.' );
128  }
129  }
130 
141  private function normalizeTimeout( $parameter, $maxParameter, $default, $maxConfigured ) {
142  if ( $parameter === 'default' || $parameter === null ) {
143  if ( !is_numeric( $default ) ) {
144  throw new \InvalidArgumentException(
145  '$wgHTTPTimeout and $wgHTTPConnectTimeout must be set to a number' );
146  }
147  $value = $default;
148  } else {
149  $value = $parameter;
150  }
151  if ( $maxParameter !== null ) {
152  $max = $maxParameter;
153  } else {
154  $max = $maxConfigured;
155  }
156  if ( $max && $value > $max ) {
157  return $max;
158  } else {
159  return $value;
160  }
161  }
162 
168  public function canMakeRequests() {
169  return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
170  }
171 
183  public function request( $method, $url, array $options = [], $caller = __METHOD__ ) {
185  $logger->debug( "$method: $url" );
186 
187  $options['method'] = strtoupper( $method );
188 
189  $req = $this->create( $url, $options, $caller );
190  $status = $req->execute();
191 
192  if ( $status->isOK() ) {
193  return $req->getContent();
194  } else {
195  $errors = $status->getErrorsByType( 'error' );
196  $logger->warning( Status::wrap( $status )->getWikiText( false, false, 'en' ),
197  [ 'error' => $errors, 'caller' => $caller, 'content' => $req->getContent() ] );
198  return null;
199  }
200  }
201 
211  public function get( $url, array $options = [], $caller = __METHOD__ ) {
212  return $this->request( 'GET', $url, $options, $caller );
213  }
214 
224  public function post( $url, array $options = [], $caller = __METHOD__ ) {
225  return $this->request( 'POST', $url, $options, $caller );
226  }
227 
231  public function getUserAgent() {
232  return 'MediaWiki/' . MW_VERSION;
233  }
234 
247  public function createMultiClient( $options = [] ) {
248  $options['reqTimeout'] = $this->normalizeTimeout(
249  $options['reqTimeout'] ?? $options['timeout'] ?? null,
250  $options['maxReqTimeout'] ?? $options['maxTimeout'] ?? null,
251  $this->options->get( 'HTTPTimeout' ),
252  $this->options->get( 'HTTPMaxTimeout' )
253  );
254  $options['connTimeout'] = $this->normalizeTimeout(
255  $options['connTimeout'] ?? $options['connectTimeout'] ?? null,
256  $options['maxConnTimeout'] ?? $options['maxConnectTimeout'] ?? null,
257  $this->options->get( 'HTTPConnectTimeout' ),
258  $this->options->get( 'HTTPMaxConnectTimeout' )
259  );
260  $options += [
261  'maxReqTimeout' => $this->options->get( 'HTTPMaxTimeout' ),
262  'maxConnTimeout' => $this->options->get( 'HTTPMaxConnectTimeout' ),
263  'userAgent' => $this->getUserAgent(),
264  'logger' => $this->logger
265  ];
266  return new MultiHttpClient( $options );
267  }
268 
282  public function createGuzzleClient( array $config = [] ): Client {
283  $config['timeout'] = $this->normalizeTimeout(
284  $config['timeout'] ?? null,
285  $config['maxTimeout'] ?? null,
286  $this->options->get( 'HTTPTimeout' ),
287  $this->options->get( 'HTTPMaxTimeout' )
288  );
289 
290  $config['connect_timeout'] = $this->normalizeTimeout(
291  $config['connect_timeout'] ?? null,
292  $config['maxConnectTimeout'] ?? null,
293  $this->options->get( 'HTTPConnectTimeout' ),
294  $this->options->get( 'HTTPMaxConnectTimeout' )
295  );
296 
297  if ( !isset( $config['headers']['User-Agent'] ) ) {
298  $config['headers']['User-Agent'] = $this->getUserAgent();
299  }
300 
301  return new Client( $config );
302  }
303 }
MultiHttpClient
Class to handle multiple HTTP requests.
Definition: MultiHttpClient.php:55
Http\$httpEngine
static $httpEngine
Definition: Http.php:30
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:168
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:39
MediaWiki\Http\HttpRequestFactory\createMultiClient
createMultiClient( $options=[])
Get a MultiHttpClient with MediaWiki configured defaults applied.
Definition: HttpRequestFactory.php:247
MediaWiki\Http
Definition: HttpRequestFactory.php:20
MW_VERSION
const MW_VERSION
The running version of MediaWiki.
Definition: Defines.php:35
CurlHttpRequest
MWHttpRequest implemented using internal curl compiled into PHP.
Definition: CurlHttpRequest.php:24
MediaWiki\Http\HttpRequestFactory\createGuzzleClient
createGuzzleClient(array $config=[])
Get a GuzzleHttp\Client instance.
Definition: HttpRequestFactory.php:282
MediaWiki\Http\HttpRequestFactory\$logger
LoggerInterface $logger
Definition: HttpRequestFactory.php:43
MediaWiki\Http\HttpRequestFactory\__construct
__construct(ServiceOptions $options, LoggerInterface $logger)
Definition: HttpRequestFactory.php:55
MediaWiki\Http\HttpRequestFactory\getUserAgent
getUserAgent()
Definition: HttpRequestFactory.php:231
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:183
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:42
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:2010
MediaWiki\Http\HttpRequestFactory\CONSTRUCTOR_OPTIONS
const CONSTRUCTOR_OPTIONS
Definition: HttpRequestFactory.php:48
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:224
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:141
MediaWiki\$config
Config $config
Definition: MediaWiki.php:42
MediaWiki\Config\ServiceOptions\get
get( $key)
Definition: ServiceOptions.php:88
PhpHttpRequest
Definition: PhpHttpRequest.php:21
MediaWiki\Http\HttpRequestFactory\$options
ServiceOptions $options
Definition: HttpRequestFactory.php:41
MediaWiki\Http\HttpRequestFactory\create
create( $url, array $options=[], $caller=__METHOD__)
Generate a new MWHttpRequest object.
Definition: HttpRequestFactory.php:98
Http
Various HTTP related functions.
Definition: Http.php:28
MediaWiki\Config\ServiceOptions\assertRequiredOptions
assertRequiredOptions(array $expectedKeys)
Assert that the list of options provided in this instance exactly match $expectedKeys,...
Definition: ServiceOptions.php:66