MediaWiki master
HttpRequestFactory.php
Go to the documentation of this file.
1<?php
6namespace MediaWiki\Http;
7
8use GuzzleHttp\Client;
10use InvalidArgumentException;
16use Profiler;
17use Psr\Log\LoggerInterface;
20
26 private $options;
28 private $logger;
30 private $telemetry;
31
35 public const CONSTRUCTOR_OPTIONS = [
42 ];
43
44 public function __construct(
45 ServiceOptions $options,
46 LoggerInterface $logger,
47 ?TelemetryHeadersInterface $telemetry = null
48 ) {
49 $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
50 $this->options = $options;
51 $this->logger = $logger;
52 $this->telemetry = $telemetry;
53 }
54
89 public function create( $url, array $options = [], $caller = __METHOD__ ) {
90 if ( !isset( $options['logger'] ) ) {
91 $options['logger'] = $this->logger;
92 }
93 $options['timeout'] = $this->normalizeTimeout(
94 $options['timeout'] ?? null,
95 $options['maxTimeout'] ?? null,
96 $this->options->get( MainConfigNames::HTTPTimeout ),
97 $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF
98 );
99 $options['connectTimeout'] = $this->normalizeTimeout(
100 $options['connectTimeout'] ?? null,
101 $options['maxConnectTimeout'] ?? null,
102 $this->options->get( MainConfigNames::HTTPConnectTimeout ),
103 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF
104 );
105 $client = new GuzzleHttpRequest( $url, $options, $caller, Profiler::instance() );
106 if ( $this->telemetry ) {
107 $client->addTelemetry( $this->telemetry );
108 }
109 return $client;
110 }
111
122 private function normalizeTimeout( $parameter, $maxParameter, $default, $maxConfigured ) {
123 if ( $parameter === 'default' || $parameter === null ) {
124 if ( !is_numeric( $default ) ) {
125 throw new InvalidArgumentException(
126 '$wgHTTPTimeout and $wgHTTPConnectTimeout must be set to a number' );
127 }
128 $value = $default;
129 } else {
130 $value = $parameter;
131 }
132 $max = $maxParameter ?? $maxConfigured;
133 if ( $max && $value > $max ) {
134 return $max;
135 }
136
137 return $value;
138 }
139
145 public function canMakeRequests() {
146 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
147 }
148
160 public function request( $method, $url, array $options = [], $caller = __METHOD__ ) {
161 $logger = LoggerFactory::getInstance( 'http' );
162 $logger->debug( "$method: $url" );
163
164 $options['method'] = strtoupper( $method );
165
166 $req = $this->create( $url, $options, $caller );
167 $status = $req->execute();
168
169 if ( $status->isOK() ) {
170 return $req->getContent();
171 } else {
172 $errors = array_map( static fn ( $msg ) => $msg->getKey(), $status->getMessages( 'error' ) );
173 $logger->warning( Status::wrap( $status )->getWikiText( false, false, 'en' ),
174 [ 'error' => $errors, 'caller' => $caller, 'content' => $req->getContent() ] );
175 return null;
176 }
177 }
178
188 public function get( $url, array $options = [], $caller = __METHOD__ ) {
189 return $this->request( 'GET', $url, $options, $caller );
190 }
191
201 public function post( $url, array $options = [], $caller = __METHOD__ ) {
202 return $this->request( 'POST', $url, $options, $caller );
203 }
204
208 public function getUserAgent() {
209 return 'MediaWiki/' . MW_VERSION;
210 }
211
224 public function createMultiClient( $options = [] ) {
225 $options['reqTimeout'] = $this->normalizeTimeout(
226 $options['reqTimeout'] ?? $options['timeout'] ?? null,
227 $options['maxReqTimeout'] ?? $options['maxTimeout'] ?? null,
228 $this->options->get( MainConfigNames::HTTPTimeout ),
229 $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF
230 );
231 $options['connTimeout'] = $this->normalizeTimeout(
232 $options['connTimeout'] ?? $options['connectTimeout'] ?? null,
233 $options['maxConnTimeout'] ?? $options['maxConnectTimeout'] ?? null,
234 $this->options->get( MainConfigNames::HTTPConnectTimeout ),
235 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF
236 );
237 $options += [
238 'maxReqTimeout' => $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF,
239 'maxConnTimeout' =>
240 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF,
241 'userAgent' => $this->getUserAgent(),
242 'logger' => $this->logger,
243 'localProxy' => $this->options->get( MainConfigNames::LocalHTTPProxy ),
244 'localVirtualHosts' => $this->options->get( MainConfigNames::LocalVirtualHosts ),
245 'telemetry' => Telemetry::getInstance(),
246 ];
247 return new MultiHttpClient( $options );
248 }
249
263 public function createGuzzleClient( array $config = [] ): Client {
264 $config['timeout'] = $this->normalizeTimeout(
265 $config['timeout'] ?? null,
266 $config['maxTimeout'] ?? null,
267 $this->options->get( MainConfigNames::HTTPTimeout ),
268 $this->options->get( MainConfigNames::HTTPMaxTimeout ) ?: INF
269 );
270
271 $config['connect_timeout'] = $this->normalizeTimeout(
272 $config['connect_timeout'] ?? null,
273 $config['maxConnectTimeout'] ?? null,
274 $this->options->get( MainConfigNames::HTTPConnectTimeout ),
275 $this->options->get( MainConfigNames::HTTPMaxConnectTimeout ) ?: INF
276 );
277
278 if ( !isset( $config['headers']['User-Agent'] ) ) {
279 $config['headers']['User-Agent'] = $this->getUserAgent();
280 }
281 if ( $this->telemetry ) {
282 $config['headers'] = array_merge(
283 $this->telemetry->getRequestHeaders(), $config['headers']
284 );
285 }
286
287 return new Client( $config );
288 }
289}
const MW_VERSION
The running version of MediaWiki.
Definition Defines.php:23
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 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.
__construct(ServiceOptions $options, LoggerInterface $logger, ?TelemetryHeadersInterface $telemetry=null)
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.
Create PSR-3 logger objects.
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()
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
Profiler base class that defines the interface and some shared functionality.
Definition Profiler.php:22
static instance()
Definition Profiler.php:90
Class to handle multiple HTTP requests.
Provide Request Telemetry information.