MediaWiki master
HttpRequestFactory.php
Go to the documentation of this file.
1<?php
6namespace MediaWiki\Http;
7
8use GuzzleHttp\Client;
9use InvalidArgumentException;
15use Psr\Log\LoggerInterface;
18
26 public const CONSTRUCTOR_OPTIONS = [
34 ];
35
36 public function __construct(
37 private readonly ServiceOptions $options,
38 private readonly LoggerInterface $logger,
39 private readonly ?TelemetryHeadersInterface $telemetry = null,
40 ) {
41 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
42 }
43
78 public function create( $url, array $options = [], $caller = __METHOD__ ) {
79 if ( !isset( $options['logger'] ) ) {
80 $options['logger'] = $this->logger;
81 }
82 $options['timeout'] = $this->normalizeTimeout(
83 $options['timeout'] ?? null,
84 $options['maxTimeout'] ?? null,
85 $this->options->get( MainConfigNames::HTTPTimeout ),
86 $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF
87 );
88 $options['connectTimeout'] = $this->normalizeTimeout(
89 $options['connectTimeout'] ?? null,
90 $options['maxConnectTimeout'] ?? null,
91 $this->options->get( MainConfigNames::HTTPConnectTimeout ),
92 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF
93 );
94 $client = new GuzzleHttpRequest( $url, $options, $caller, Profiler::instance() );
95 if ( $this->telemetry ) {
96 $client->addTelemetry( $this->telemetry );
97 }
98 return $client;
99 }
100
111 private function normalizeTimeout( $parameter, $maxParameter, $default, $maxConfigured ) {
112 if ( $parameter === 'default' || $parameter === null ) {
113 if ( !is_numeric( $default ) ) {
114 throw new InvalidArgumentException(
115 '$wgHTTPTimeout and $wgHTTPConnectTimeout must be set to a number' );
116 }
117 $value = $default;
118 } else {
119 $value = $parameter;
120 }
121 $max = $maxParameter ?? $maxConfigured;
122 if ( $max && $value > $max ) {
123 return $max;
124 }
125
126 return $value;
127 }
128
134 public function canMakeRequests() {
135 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
136 }
137
149 public function request( $method, $url, array $options = [], $caller = __METHOD__ ) {
150 $logger = LoggerFactory::getInstance( 'http' );
151 $logger->debug( "$method: $url" );
152
153 $options['method'] = strtoupper( $method );
154
155 $req = $this->create( $url, $options, $caller );
156 $status = $req->execute();
157
158 if ( $status->isOK() ) {
159 return $req->getContent();
160 } else {
161 $errors = array_map( static fn ( $msg ) => $msg->getKey(), $status->getMessages( 'error' ) );
162 $logger->warning( Status::wrap( $status )->getWikiText( false, false, 'en' ),
163 [ 'error' => $errors, 'caller' => $caller, 'content' => $req->getContent() ] );
164 return null;
165 }
166 }
167
177 public function get( $url, array $options = [], $caller = __METHOD__ ) {
178 return $this->request( 'GET', $url, $options, $caller );
179 }
180
190 public function post( $url, array $options = [], $caller = __METHOD__ ) {
191 return $this->request( 'POST', $url, $options, $caller );
192 }
193
198 public function getUserAgent() {
199 // T245170: Also applied to MultiHttpClient.
200 // T400881, T422686: Also applied to ForeignAPIRepo, and others.
201 $contact = $this->options->get( MainConfigNames::HTTPUserAgentContact );
202 return 'MediaWiki/' . MW_VERSION . " ($contact)";
203 }
204
217 public function createMultiClient( $options = [] ) {
218 $options['reqTimeout'] = $this->normalizeTimeout(
219 $options['reqTimeout'] ?? $options['timeout'] ?? null,
220 $options['maxReqTimeout'] ?? $options['maxTimeout'] ?? null,
221 $this->options->get( MainConfigNames::HTTPTimeout ),
222 $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF
223 );
224 $options['connTimeout'] = $this->normalizeTimeout(
225 $options['connTimeout'] ?? $options['connectTimeout'] ?? null,
226 $options['maxConnTimeout'] ?? $options['maxConnectTimeout'] ?? null,
227 $this->options->get( MainConfigNames::HTTPConnectTimeout ),
228 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF
229 );
230 $options += [
231 'maxReqTimeout' => $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF,
232 'maxConnTimeout' =>
233 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF,
234 'userAgent' => $this->getUserAgent(),
235 'logger' => $this->logger,
236 'localProxy' => $this->options->get( MainConfigNames::LocalHTTPProxy ),
237 'localVirtualHosts' => $this->options->get( MainConfigNames::LocalVirtualHosts ),
238 'telemetry' => Telemetry::getInstance(),
239 ];
240 return new MultiHttpClient( $options );
241 }
242
256 public function createGuzzleClient( array $config = [] ): Client {
257 $config['timeout'] = $this->normalizeTimeout(
258 $config['timeout'] ?? null,
259 $config['maxTimeout'] ?? null,
260 $this->options->get( MainConfigNames::HTTPTimeout ),
261 $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF
262 );
263
264 $config['connect_timeout'] = $this->normalizeTimeout(
265 $config['connect_timeout'] ?? null,
266 $config['maxConnectTimeout'] ?? null,
267 $this->options->get( MainConfigNames::HTTPConnectTimeout ),
268 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF
269 );
270
271 if ( !isset( $config['headers']['User-Agent'] ) ) {
272 $config['headers']['User-Agent'] = $this->getUserAgent();
273 }
274 if ( $this->telemetry ) {
275 $config['headers'] = array_merge(
276 $this->telemetry->getRequestHeaders(), $config['headers']
277 );
278 }
279
280 return new Client( $config );
281 }
282}
const MW_VERSION
The running version of MediaWiki.
Definition Defines.php:23
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
A class for passing options to services.
MWHttpRequest implemented using the Guzzle library.
Factory creating MWHttpRequest objects.
get( $url, array $options=[], $caller=__METHOD__)
Simple wrapper for ‘request( 'GET’ ), parameters have the same meaning as forrequest()`.
createMultiClient( $options=[])
Get a MultiHttpClient with MediaWiki configured defaults applied.
post( $url, array $options=[], $caller=__METHOD__)
Simple wrapper for ‘request( 'POST’ ), parameters have the same meaning as forrequest()`.
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.
__construct(private readonly ServiceOptions $options, private readonly LoggerInterface $logger, private readonly ?TelemetryHeadersInterface $telemetry=null,)
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
const HTTPUserAgentContact
Name constant for the HTTPUserAgentContact setting, for use with Config::get()
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()
Profiler base class that defines the interface and some shared functionality.
Definition Profiler.php:26
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
Class to handle multiple HTTP requests.
Provide Request Telemetry information.