3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use GuzzleHttp\Client
;
22 use GuzzleHttp\Psr7\Request
;
25 * MWHttpRequest implemented using the Guzzle library
27 * Differences from the CurlHttpRequest implementation:
28 * 1) a new 'sink' option is available as an alternative to callbacks. See:
29 * http://docs.guzzlephp.org/en/stable/request-options.html#sink)
30 * The 'callback' option remains available as well. If both 'sink' and 'callback' are
31 * specified, 'sink' is used.
32 * 2) callers may set a custom handler via the 'handler' option.
33 * If this is not set, Guzzle will use curl (if available) or PHP streams (otherwise)
34 * 3) setting either sslVerifyHost or sslVerifyCert will enable both. Guzzle does not allow
35 * them to be set separately.
39 class GuzzleHttpRequest
extends MWHttpRequest
{
40 const SUPPORTS_FILE_POSTS
= true;
42 protected $handler = null;
43 protected $sink = null;
45 protected $guzzleOptions = [ 'http_errors' => false ];
48 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
49 * @param array $options (optional) extra params to pass (see HttpRequestFactory::create())
50 * @param string $caller The method making this request, for profiling
51 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
54 public function __construct(
55 $url, array $options = [], $caller = __METHOD__
, Profiler
$profiler = null
57 parent
::__construct( $url, $options, $caller, $profiler );
59 if ( isset( $options['handler'] ) ) {
60 $this->handler
= $options['handler'];
62 if ( isset( $options['sink'] ) ) {
63 $this->sink
= $options['sink'];
68 * Set a read callback to accept data read from the HTTP request.
69 * By default, data is appended to an internal buffer which can be
70 * retrieved through $req->getContent().
72 * To handle data as it comes in -- especially for large files that
73 * would not fit in memory -- you can instead set your own callback,
74 * in the form function($resource, $buffer) where the first parameter
75 * is the low-level resource being read (implementation specific),
76 * and the second parameter is the data buffer.
78 * You MUST return the number of bytes handled in the buffer; if fewer
79 * bytes are reported handled than were passed to you, the HTTP fetch
82 * This function overrides any 'sink' or 'callback' constructor option.
84 * @param callable|null $callback
85 * @throws InvalidArgumentException
87 public function setCallback( $callback ) {
89 $this->doSetCallback( $callback );
93 * Worker function for setting callbacks. Calls can originate both internally and externally
94 * via setCallback). Defaults to the internal read callback if $callback is null.
96 * If a sink is already specified, this does nothing. This causes the 'sink' constructor
97 * option to override the 'callback' constructor option.
99 * @param callable|null $callback
100 * @throws InvalidArgumentException
102 protected function doSetCallback( $callback ) {
103 if ( !$this->sink
) {
104 parent
::doSetCallback( $callback );
105 $this->sink
= new MWCallbackStream( $this->callback
);
110 * @see MWHttpRequest::execute
114 public function execute() {
117 if ( !$this->status
->isOK() ) {
118 return Status
::wrap( $this->status
); // TODO B/C; move this to callers
121 if ( $this->proxy
) {
122 $this->guzzleOptions
['proxy'] = $this->proxy
;
125 $this->guzzleOptions
['timeout'] = $this->timeout
;
126 $this->guzzleOptions
['connect_timeout'] = $this->connectTimeout
;
127 $this->guzzleOptions
['version'] = '1.1';
129 if ( !$this->followRedirects
) {
130 $this->guzzleOptions
['allow_redirects'] = false;
132 $this->guzzleOptions
['allow_redirects'] = [
133 'max' => $this->maxRedirects
137 if ( $this->method
== 'POST' ) {
138 $postData = $this->postData
;
139 if ( is_array( $postData ) ) {
140 $this->guzzleOptions
['form_params'] = $postData;
142 $this->guzzleOptions
['body'] = $postData;
145 // Suppress 'Expect: 100-continue' header, as some servers
146 // will reject it with a 417 and Curl won't auto retry
147 // with HTTP 1.0 fallback
148 $this->guzzleOptions
['expect'] = false;
151 $this->guzzleOptions
['headers'] = $this->reqHeaders
;
153 if ( $this->handler
) {
154 $this->guzzleOptions
['handler'] = $this->handler
;
158 $this->guzzleOptions
['sink'] = $this->sink
;
161 if ( $this->caInfo
) {
162 $this->guzzleOptions
['verify'] = $this->caInfo
;
163 } elseif ( !$this->sslVerifyHost
&& !$this->sslVerifyCert
) {
164 $this->guzzleOptions
['verify'] = false;
168 $client = new Client( $this->guzzleOptions
);
169 $request = new Request( $this->method
, $this->url
);
170 $response = $client->send( $request );
171 $this->headerList
= $response->getHeaders();
173 $this->respVersion
= $response->getProtocolVersion();
174 $this->respStatus
= $response->getStatusCode() . ' ' . $response->getReasonPhrase();
175 } catch ( GuzzleHttp\Exception\ConnectException
$e ) {
176 // ConnectException is thrown for several reasons besides generic "timeout":
177 // Connection refused
178 // couldn't connect to host
179 // connection attempt failed
180 // Could not resolve IPv4 address for host
181 // Could not resolve IPv6 address for host
182 if ( $this->usingCurl() ) {
183 $handlerContext = $e->getHandlerContext();
184 if ( $handlerContext['errno'] == CURLE_OPERATION_TIMEOUTED
) {
185 $this->status
->fatal( 'http-timed-out', $this->url
);
187 $this->status
->fatal( 'http-curl-error', $handlerContext['error'] );
190 $this->status
->fatal( 'http-request-error' );
192 } catch ( GuzzleHttp\Exception\RequestException
$e ) {
193 if ( $this->usingCurl() ) {
194 $handlerContext = $e->getHandlerContext();
195 $this->status
->fatal( 'http-curl-error', $handlerContext['error'] );
197 // Non-ideal, but the only way to identify connection timeout vs other conditions
198 $needle = 'Connection timed out';
199 if ( strpos( $e->getMessage(), $needle ) !== false ) {
200 $this->status
->fatal( 'http-timed-out', $this->url
);
202 $this->status
->fatal( 'http-request-error' );
205 } catch ( GuzzleHttp\Exception\GuzzleException
$e ) {
206 $this->status
->fatal( 'http-internal-error' );
209 if ( $this->profiler
) {
210 $profileSection = $this->profiler
->scopedProfileIn(
211 __METHOD__
. '-' . $this->profileName
215 if ( $this->profiler
) {
216 $this->profiler
->scopedProfileOut( $profileSection );
219 $this->parseHeader();
222 return Status
::wrap( $this->status
); // TODO B/C; move this to callers
225 protected function prepare() {
226 $this->doSetCallback( $this->callback
);
233 protected function usingCurl() {
234 return ( $this->handler
&& is_a( $this->handler
, 'GuzzleHttp\Handler\CurlHandler' ) ) ||
235 ( !$this->handler
&& extension_loaded( 'curl' ) );
239 * Guzzle provides headers as an array. Reprocess to match our expectations. Guzzle will
240 * have already parsed and removed the status line (in EasyHandle::createResponse).
242 protected function parseHeader() {
243 // Failure without (valid) headers gets a response status of zero
244 if ( !$this->status
->isOK() ) {
245 $this->respStatus
= '0 Error';
248 foreach ( $this->headerList
as $name => $values ) {
249 $this->respHeaders
[strtolower( $name )] = $values;
252 $this->parseCookies();