Mimic CURLOPT_POST in GuzzleHttpRequest
[lhc/web/wiklou.git] / includes / http / GuzzleHttpRequest.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 use GuzzleHttp\Client;
22 use GuzzleHttp\Psr7\Request;
23
24 /**
25 * MWHttpRequest implemented using the Guzzle library
26 *
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.
36 *
37 * @since 1.33
38 */
39 class GuzzleHttpRequest extends MWHttpRequest {
40 const SUPPORTS_FILE_POSTS = true;
41
42 protected $handler = null;
43 protected $sink = null;
44 /** @var array */
45 protected $guzzleOptions = [ 'http_errors' => false ];
46
47 /**
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
52 * @throws Exception
53 */
54 public function __construct(
55 $url, array $options = [], $caller = __METHOD__, Profiler $profiler = null
56 ) {
57 parent::__construct( $url, $options, $caller, $profiler );
58
59 if ( isset( $options['handler'] ) ) {
60 $this->handler = $options['handler'];
61 }
62 if ( isset( $options['sink'] ) ) {
63 $this->sink = $options['sink'];
64 }
65 }
66
67 /**
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().
71 *
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.
77 *
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
80 * will be aborted.
81 *
82 * This function overrides any 'sink' or 'callback' constructor option.
83 *
84 * @param callable|null $callback
85 * @throws InvalidArgumentException
86 */
87 public function setCallback( $callback ) {
88 $this->sink = null;
89 $this->doSetCallback( $callback );
90 }
91
92 /**
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.
95 *
96 * If a sink is already specified, this does nothing. This causes the 'sink' constructor
97 * option to override the 'callback' constructor option.
98 *
99 * @param callable|null $callback
100 * @throws InvalidArgumentException
101 */
102 protected function doSetCallback( $callback ) {
103 if ( !$this->sink ) {
104 parent::doSetCallback( $callback );
105 $this->sink = new MWCallbackStream( $this->callback );
106 }
107 }
108
109 /**
110 * @see MWHttpRequest::execute
111 *
112 * @return Status
113 */
114 public function execute() {
115 $this->prepare();
116
117 if ( !$this->status->isOK() ) {
118 return Status::wrap( $this->status ); // TODO B/C; move this to callers
119 }
120
121 if ( $this->proxy ) {
122 $this->guzzleOptions['proxy'] = $this->proxy;
123 }
124
125 $this->guzzleOptions['timeout'] = $this->timeout;
126 $this->guzzleOptions['connect_timeout'] = $this->connectTimeout;
127 $this->guzzleOptions['version'] = '1.1';
128
129 if ( !$this->followRedirects ) {
130 $this->guzzleOptions['allow_redirects'] = false;
131 } else {
132 $this->guzzleOptions['allow_redirects'] = [
133 'max' => $this->maxRedirects
134 ];
135 }
136
137 if ( $this->method == 'POST' ) {
138 $postData = $this->postData;
139 if ( is_array( $postData ) ) {
140 $this->guzzleOptions['form_params'] = $postData;
141 } else {
142 $this->guzzleOptions['body'] = $postData;
143 // mimic CURLOPT_POST option
144 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
145 $this->reqHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
146 }
147 }
148
149 // Suppress 'Expect: 100-continue' header, as some servers
150 // will reject it with a 417 and Curl won't auto retry
151 // with HTTP 1.0 fallback
152 $this->guzzleOptions['expect'] = false;
153 }
154
155 $this->guzzleOptions['headers'] = $this->reqHeaders;
156
157 if ( $this->handler ) {
158 $this->guzzleOptions['handler'] = $this->handler;
159 }
160
161 if ( $this->sink ) {
162 $this->guzzleOptions['sink'] = $this->sink;
163 }
164
165 if ( $this->caInfo ) {
166 $this->guzzleOptions['verify'] = $this->caInfo;
167 } elseif ( !$this->sslVerifyHost && !$this->sslVerifyCert ) {
168 $this->guzzleOptions['verify'] = false;
169 }
170
171 try {
172 $client = new Client( $this->guzzleOptions );
173 $request = new Request( $this->method, $this->url );
174 $response = $client->send( $request );
175 $this->headerList = $response->getHeaders();
176
177 $this->respVersion = $response->getProtocolVersion();
178 $this->respStatus = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
179 } catch ( GuzzleHttp\Exception\ConnectException $e ) {
180 // ConnectException is thrown for several reasons besides generic "timeout":
181 // Connection refused
182 // couldn't connect to host
183 // connection attempt failed
184 // Could not resolve IPv4 address for host
185 // Could not resolve IPv6 address for host
186 if ( $this->usingCurl() ) {
187 $handlerContext = $e->getHandlerContext();
188 if ( $handlerContext['errno'] == CURLE_OPERATION_TIMEOUTED ) {
189 $this->status->fatal( 'http-timed-out', $this->url );
190 } else {
191 $this->status->fatal( 'http-curl-error', $handlerContext['error'] );
192 }
193 } else {
194 $this->status->fatal( 'http-request-error' );
195 }
196 } catch ( GuzzleHttp\Exception\RequestException $e ) {
197 if ( $this->usingCurl() ) {
198 $handlerContext = $e->getHandlerContext();
199 $this->status->fatal( 'http-curl-error', $handlerContext['error'] );
200 } else {
201 // Non-ideal, but the only way to identify connection timeout vs other conditions
202 $needle = 'Connection timed out';
203 if ( strpos( $e->getMessage(), $needle ) !== false ) {
204 $this->status->fatal( 'http-timed-out', $this->url );
205 } else {
206 $this->status->fatal( 'http-request-error' );
207 }
208 }
209 } catch ( GuzzleHttp\Exception\GuzzleException $e ) {
210 $this->status->fatal( 'http-internal-error' );
211 }
212
213 if ( $this->profiler ) {
214 $profileSection = $this->profiler->scopedProfileIn(
215 __METHOD__ . '-' . $this->profileName
216 );
217 }
218
219 if ( $this->profiler ) {
220 $this->profiler->scopedProfileOut( $profileSection );
221 }
222
223 $this->parseHeader();
224 $this->setStatus();
225
226 return Status::wrap( $this->status ); // TODO B/C; move this to callers
227 }
228
229 protected function prepare() {
230 $this->doSetCallback( $this->callback );
231 parent::prepare();
232 }
233
234 /**
235 * @return bool
236 */
237 protected function usingCurl() {
238 return ( $this->handler && is_a( $this->handler, 'GuzzleHttp\Handler\CurlHandler' ) ) ||
239 ( !$this->handler && extension_loaded( 'curl' ) );
240 }
241
242 /**
243 * Guzzle provides headers as an array. Reprocess to match our expectations. Guzzle will
244 * have already parsed and removed the status line (in EasyHandle::createResponse).
245 */
246 protected function parseHeader() {
247 // Failure without (valid) headers gets a response status of zero
248 if ( !$this->status->isOK() ) {
249 $this->respStatus = '0 Error';
250 }
251
252 foreach ( $this->headerList as $name => $values ) {
253 $this->respHeaders[strtolower( $name )] = $values;
254 }
255
256 $this->parseCookies();
257 }
258 }