db8a09b9709469d4aaad7578f8c56567702da70f
[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) the MWHttpRequest 'callback" option is unsupported. Instead, use the 'sink' option to
29 * send a filename/stream (see http://docs.guzzlephp.org/en/stable/request-options.html#sink)
30 * 2) callers may set a custom handler via the 'handler' option.
31 * If this is not set, Guzzle will use curl (if available) or PHP streams (otherwise)
32 * 3) setting either sslVerifyHost or sslVerifyCert will enable both. Guzzle does not allow
33 * them to be set separately.
34 *
35 * @since 1.33
36 */
37 class GuzzleHttpRequest extends MWHttpRequest {
38 const SUPPORTS_FILE_POSTS = true;
39
40 protected $handler = null;
41 protected $sink = null;
42 protected $guzzleOptions = [ 'http_errors' => false ];
43
44 /**
45 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
46 * @param array $options (optional) extra params to pass (see Http::request())
47 * @param string $caller The method making this request, for profiling
48 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
49 * @throws Exception
50 */
51 public function __construct(
52 $url, array $options = [], $caller = __METHOD__, $profiler = null
53 ) {
54 parent::__construct( $url, $options, $caller, $profiler );
55
56 if ( isset( $options['handler'] ) ) {
57 $this->handler = $options['handler'];
58 }
59 if ( isset( $options['sink'] ) ) {
60 $this->sink = $options['sink'];
61 }
62 }
63
64 /**
65 * @see MWHttpRequest::execute
66 *
67 * @return Status
68 */
69 public function execute() {
70 $this->prepare();
71
72 if ( !$this->status->isOK() ) {
73 return Status::wrap( $this->status ); // TODO B/C; move this to callers
74 }
75
76 if ( $this->proxy ) {
77 $this->guzzleOptions['proxy'] = $this->proxy;
78 }
79
80 $this->guzzleOptions['timeout'] = $this->timeout;
81 $this->guzzleOptions['connect_timeout'] = $this->connectTimeout;
82 $this->guzzleOptions['version'] = '1.1';
83
84 if ( !$this->followRedirects ) {
85 $this->guzzleOptions['allow_redirects'] = false;
86 } else {
87 $this->guzzleOptions['allow_redirects'] = [
88 'max' => $this->maxRedirects
89 ];
90 }
91
92 if ( $this->method == 'POST' ) {
93 $postData = $this->postData;
94 if ( is_array( $postData ) ) {
95 $this->guzzleOptions['form_params'] = $postData;
96 } else {
97 $this->guzzleOptions['body'] = $postData;
98 }
99
100 // Suppress 'Expect: 100-continue' header, as some servers
101 // will reject it with a 417 and Curl won't auto retry
102 // with HTTP 1.0 fallback
103 $this->guzzleOptions['expect'] = false;
104 }
105
106 $this->guzzleOptions['headers'] = $this->reqHeaders;
107
108 if ( $this->handler ) {
109 $this->guzzleOptions['handler'] = $this->handler;
110 }
111
112 if ( $this->sink ) {
113 $this->guzzleOptions['sink'] = $this->sink;
114 }
115
116 if ( $this->caInfo ) {
117 $this->guzzleOptions['verify'] = $this->caInfo;
118 } elseif ( !$this->sslVerifyHost && !$this->sslVerifyCert ) {
119 $this->guzzleOptions['verify'] = false;
120 }
121
122 try {
123 $client = new Client( $this->guzzleOptions );
124 $request = new Request( $this->method, $this->url );
125 $response = $client->send( $request );
126 $this->headerList = $response->getHeaders();
127 $this->content = $response->getBody()->getContents();
128
129 $this->respVersion = $response->getProtocolVersion();
130 $this->respStatus = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
131
132 } catch ( GuzzleHttp\Exception\ConnectException $e ) {
133 // ConnectException is thrown for several reasons besides generic "timeout":
134 // Connection refused
135 // couldn't connect to host
136 // connection attempt failed
137 // Could not resolve IPv4 address for host
138 // Could not resolve IPv6 address for host
139 if ( $this->usingCurl() ) {
140 $handlerContext = $e->getHandlerContext();
141 if ( $handlerContext['errno'] == CURLE_OPERATION_TIMEOUTED ) {
142 $this->status->fatal( 'http-timed-out', $this->url );
143 } else {
144 $this->status->fatal( 'http-curl-error', $handlerContext['error'] );
145 }
146 } else {
147 $this->status->fatal( 'http-request-error' );
148 }
149 } catch ( GuzzleHttp\Exception\RequestException $e ) {
150 if ( $this->usingCurl() ) {
151 $handlerContext = $e->getHandlerContext();
152 $this->status->fatal( 'http-curl-error', $handlerContext['error'] );
153 } else {
154 // Non-ideal, but the only way to identify connection timeout vs other conditions
155 $needle = 'Connection timed out';
156 if ( strpos( $e->getMessage(), $needle ) !== false ) {
157 $this->status->fatal( 'http-timed-out', $this->url );
158 } else {
159 $this->status->fatal( 'http-request-error' );
160 }
161 }
162 } catch ( GuzzleHttp\Exception\GuzzleException $e ) {
163 $this->status->fatal( 'http-internal-error' );
164 }
165
166 if ( $this->profiler ) {
167 $profileSection = $this->profiler->scopedProfileIn(
168 __METHOD__ . '-' . $this->profileName
169 );
170 }
171
172 if ( $this->profiler ) {
173 $this->profiler->scopedProfileOut( $profileSection );
174 }
175
176 $this->parseHeader();
177 $this->setStatus();
178
179 return Status::wrap( $this->status ); // TODO B/C; move this to callers
180 }
181
182 /**
183 * @return bool
184 */
185 protected function usingCurl() {
186 return ( $this->handler && is_a( $this->handler, 'GuzzleHttp\Handler\CurlHandler' ) ) ||
187 ( !$this->handler && extension_loaded( 'curl' ) );
188 }
189
190 /**
191 * Guzzle provides headers as an array. Reprocess to match our expectations. Guzzle will
192 * have already parsed and removed the status line (in EasyHandle::createResponse)z.
193 */
194 protected function parseHeader() {
195 // Failure without (valid) headers gets a response status of zero
196 if ( !$this->status->isOK() ) {
197 $this->respStatus = '0 Error';
198 }
199
200 foreach ( $this->headerList as $name => $values ) {
201 $this->respHeaders[strtolower( $name )] = $values;
202 }
203
204 $this->parseCookies();
205 }
206 }