Merge "Migrate SpecialUndelete and Diff from tag_summary to change_tag"
[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 $this->guzzleOptions['body'] = $postData;
95
96 // Suppress 'Expect: 100-continue' header, as some servers
97 // will reject it with a 417 and Curl won't auto retry
98 // with HTTP 1.0 fallback
99 $this->guzzleOptions['expect'] = false;
100 }
101
102 $this->guzzleOptions['headers'] = $this->reqHeaders;
103
104 if ( $this->handler ) {
105 $this->guzzleOptions['handler'] = $this->handler;
106 }
107
108 if ( $this->sink ) {
109 $this->guzzleOptions['sink'] = $this->sink;
110 }
111
112 if ( $this->caInfo ) {
113 $this->guzzleOptions['verify'] = $this->caInfo;
114 } elseif ( !$this->sslVerifyHost && !$this->sslVerifyCert ) {
115 $this->guzzleOptions['verify'] = false;
116 }
117
118 try {
119 $client = new Client( $this->guzzleOptions );
120 $request = new Request( $this->method, $this->url );
121 $response = $client->send( $request );
122 $this->headerList = $response->getHeaders();
123 $this->content = $response->getBody()->getContents();
124
125 $this->respVersion = $response->getProtocolVersion();
126 $this->respStatus = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
127
128 } catch ( GuzzleHttp\Exception\ConnectException $e ) {
129 // ConnectException is thrown for several reasons besides generic "timeout":
130 // Connection refused
131 // couldn't connect to host
132 // connection attempt failed
133 // Could not resolve IPv4 address for host
134 // Could not resolve IPv6 address for host
135 if ( $this->usingCurl() ) {
136 $handlerContext = $e->getHandlerContext();
137 if ( $handlerContext['errno'] == CURLE_OPERATION_TIMEOUTED ) {
138 $this->status->fatal( 'http-timed-out', $this->url );
139 } else {
140 $this->status->fatal( 'http-curl-error', $handlerContext['error'] );
141 }
142 } else {
143 $this->status->fatal( 'http-request-error' );
144 }
145 } catch ( GuzzleHttp\Exception\RequestException $e ) {
146 if ( $this->usingCurl() ) {
147 $handlerContext = $e->getHandlerContext();
148 $this->status->fatal( 'http-curl-error', $handlerContext['error'] );
149 } else {
150 // Non-ideal, but the only way to identify connection timeout vs other conditions
151 $needle = 'Connection timed out';
152 if ( strpos( $e->getMessage(), $needle ) !== false ) {
153 $this->status->fatal( 'http-timed-out', $this->url );
154 } else {
155 $this->status->fatal( 'http-request-error' );
156 }
157 }
158 } catch ( GuzzleHttp\Exception\GuzzleException $e ) {
159 $this->status->fatal( 'http-internal-error' );
160 }
161
162 if ( $this->profiler ) {
163 $profileSection = $this->profiler->scopedProfileIn(
164 __METHOD__ . '-' . $this->profileName
165 );
166 }
167
168 if ( $this->profiler ) {
169 $this->profiler->scopedProfileOut( $profileSection );
170 }
171
172 $this->parseHeader();
173 $this->setStatus();
174
175 return Status::wrap( $this->status ); // TODO B/C; move this to callers
176 }
177
178 /**
179 * @return bool
180 */
181 protected function usingCurl() {
182 return ( $this->handler && is_a( $this->handler, 'GuzzleHttp\Handler\CurlHandler' ) ) ||
183 ( !$this->handler && extension_loaded( 'curl' ) );
184 }
185
186 /**
187 * Guzzle provides headers as an array. Reprocess to match our expectations. Guzzle will
188 * have already parsed and removed the status line (in EasyHandle::createResponse)z.
189 */
190 protected function parseHeader() {
191 // Failure without (valid) headers gets a response status of zero
192 if ( !$this->status->isOK() ) {
193 $this->respStatus = '0 Error';
194 }
195
196 foreach ( $this->headerList as $name => $values ) {
197 $this->respHeaders[strtolower( $name )] = $values;
198 }
199
200 $this->parseCookies();
201 }
202 }