Merge "Fix ParserOutput::getText 'unwrap' flag for end-of-doc comment"
[lhc/web/wiklou.git] / includes / http / MWHttpRequest.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 Psr\Log\LoggerInterface;
22 use Psr\Log\LoggerAwareInterface;
23 use Psr\Log\NullLogger;
24
25 /**
26 * This wrapper class will call out to curl (if available) or fallback
27 * to regular PHP if necessary for handling internal HTTP requests.
28 *
29 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
30 * PHP's HTTP extension.
31 */
32 abstract class MWHttpRequest implements LoggerAwareInterface {
33 const SUPPORTS_FILE_POSTS = false;
34
35 /**
36 * @var int|string
37 */
38 protected $timeout = 'default';
39
40 protected $content;
41 protected $headersOnly = null;
42 protected $postData = null;
43 protected $proxy = null;
44 protected $noProxy = false;
45 protected $sslVerifyHost = true;
46 protected $sslVerifyCert = true;
47 protected $caInfo = null;
48 protected $method = "GET";
49 protected $reqHeaders = [];
50 protected $url;
51 protected $parsedUrl;
52 /** @var callable */
53 protected $callback;
54 protected $maxRedirects = 5;
55 protected $followRedirects = false;
56 protected $connectTimeout;
57
58 /**
59 * @var CookieJar
60 */
61 protected $cookieJar;
62
63 protected $headerList = [];
64 protected $respVersion = "0.9";
65 protected $respStatus = "200 Ok";
66 protected $respHeaders = [];
67
68 /** @var StatusValue */
69 protected $status;
70
71 /**
72 * @var Profiler
73 */
74 protected $profiler;
75
76 /**
77 * @var string
78 */
79 protected $profileName;
80
81 /**
82 * @var LoggerInterface
83 */
84 protected $logger;
85
86 /**
87 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
88 * @param array $options (optional) extra params to pass (see Http::request())
89 * @param string $caller The method making this request, for profiling
90 * @param Profiler $profiler An instance of the profiler for profiling, or null
91 */
92 public function __construct(
93 $url, array $options = [], $caller = __METHOD__, $profiler = null
94 ) {
95 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
96
97 $this->url = wfExpandUrl( $url, PROTO_HTTP );
98 $this->parsedUrl = wfParseUrl( $this->url );
99
100 if ( isset( $options['logger'] ) ) {
101 $this->logger = $options['logger'];
102 } else {
103 $this->logger = new NullLogger();
104 }
105
106 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
107 $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
108 } else {
109 $this->status = StatusValue::newGood( 100 ); // continue
110 }
111
112 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
113 $this->timeout = $options['timeout'];
114 } else {
115 $this->timeout = $wgHTTPTimeout;
116 }
117 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
118 $this->connectTimeout = $options['connectTimeout'];
119 } else {
120 $this->connectTimeout = $wgHTTPConnectTimeout;
121 }
122 if ( isset( $options['userAgent'] ) ) {
123 $this->setUserAgent( $options['userAgent'] );
124 }
125 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
126 $this->setHeader(
127 'Authorization',
128 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
129 );
130 }
131 if ( isset( $options['originalRequest'] ) ) {
132 $this->setOriginalRequest( $options['originalRequest'] );
133 }
134
135 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
136 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
137
138 foreach ( $members as $o ) {
139 if ( isset( $options[$o] ) ) {
140 // ensure that MWHttpRequest::method is always
141 // uppercased. T38137
142 if ( $o == 'method' ) {
143 $options[$o] = strtoupper( $options[$o] );
144 }
145 $this->$o = $options[$o];
146 }
147 }
148
149 if ( $this->noProxy ) {
150 $this->proxy = ''; // noProxy takes precedence
151 }
152
153 // Profile based on what's calling us
154 $this->profiler = $profiler;
155 $this->profileName = $caller;
156 }
157
158 /**
159 * @param LoggerInterface $logger
160 */
161 public function setLogger( LoggerInterface $logger ) {
162 $this->logger = $logger;
163 }
164
165 /**
166 * Simple function to test if we can make any sort of requests at all, using
167 * cURL or fopen()
168 * @return bool
169 */
170 public static function canMakeRequests() {
171 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
172 }
173
174 /**
175 * Generate a new request object
176 * Deprecated: @see HttpRequestFactory::create
177 * @param string $url Url to use
178 * @param array|null $options (optional) extra params to pass (see Http::request())
179 * @param string $caller The method making this request, for profiling
180 * @throws DomainException
181 * @return MWHttpRequest
182 * @see MWHttpRequest::__construct
183 */
184 public static function factory( $url, array $options = null, $caller = __METHOD__ ) {
185 if ( $options === null ) {
186 $options = [];
187 }
188 return \MediaWiki\MediaWikiServices::getInstance()
189 ->getHttpRequestFactory()
190 ->create( $url, $options, $caller );
191 }
192
193 /**
194 * Get the body, or content, of the response to the request
195 *
196 * @return string
197 */
198 public function getContent() {
199 return $this->content;
200 }
201
202 /**
203 * Set the parameters of the request
204 *
205 * @param array $args
206 * @todo overload the args param
207 */
208 public function setData( $args ) {
209 $this->postData = $args;
210 }
211
212 /**
213 * Take care of setting up the proxy (do nothing if "noProxy" is set)
214 *
215 * @return void
216 */
217 protected function proxySetup() {
218 // If there is an explicit proxy set and proxies are not disabled, then use it
219 if ( $this->proxy && !$this->noProxy ) {
220 return;
221 }
222
223 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
224 // local URL and proxies are not disabled
225 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
226 $this->proxy = '';
227 } else {
228 $this->proxy = Http::getProxy();
229 }
230 }
231
232 /**
233 * Check if the URL can be served by localhost
234 *
235 * @param string $url Full url to check
236 * @return bool
237 */
238 private static function isLocalURL( $url ) {
239 global $wgCommandLineMode, $wgLocalVirtualHosts;
240
241 if ( $wgCommandLineMode ) {
242 return false;
243 }
244
245 // Extract host part
246 $matches = [];
247 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
248 $host = $matches[1];
249 // Split up dotwise
250 $domainParts = explode( '.', $host );
251 // Check if this domain or any superdomain is listed as a local virtual host
252 $domainParts = array_reverse( $domainParts );
253
254 $domain = '';
255 $countParts = count( $domainParts );
256 for ( $i = 0; $i < $countParts; $i++ ) {
257 $domainPart = $domainParts[$i];
258 if ( $i == 0 ) {
259 $domain = $domainPart;
260 } else {
261 $domain = $domainPart . '.' . $domain;
262 }
263
264 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
265 return true;
266 }
267 }
268 }
269
270 return false;
271 }
272
273 /**
274 * Set the user agent
275 * @param string $UA
276 */
277 public function setUserAgent( $UA ) {
278 $this->setHeader( 'User-Agent', $UA );
279 }
280
281 /**
282 * Set an arbitrary header
283 * @param string $name
284 * @param string $value
285 */
286 public function setHeader( $name, $value ) {
287 // I feel like I should normalize the case here...
288 $this->reqHeaders[$name] = $value;
289 }
290
291 /**
292 * Get an array of the headers
293 * @return array
294 */
295 protected function getHeaderList() {
296 $list = [];
297
298 if ( $this->cookieJar ) {
299 $this->reqHeaders['Cookie'] =
300 $this->cookieJar->serializeToHttpRequest(
301 $this->parsedUrl['path'],
302 $this->parsedUrl['host']
303 );
304 }
305
306 foreach ( $this->reqHeaders as $name => $value ) {
307 $list[] = "$name: $value";
308 }
309
310 return $list;
311 }
312
313 /**
314 * Set a read callback to accept data read from the HTTP request.
315 * By default, data is appended to an internal buffer which can be
316 * retrieved through $req->getContent().
317 *
318 * To handle data as it comes in -- especially for large files that
319 * would not fit in memory -- you can instead set your own callback,
320 * in the form function($resource, $buffer) where the first parameter
321 * is the low-level resource being read (implementation specific),
322 * and the second parameter is the data buffer.
323 *
324 * You MUST return the number of bytes handled in the buffer; if fewer
325 * bytes are reported handled than were passed to you, the HTTP fetch
326 * will be aborted.
327 *
328 * @param callable|null $callback
329 * @throws InvalidArgumentException
330 */
331 public function setCallback( $callback ) {
332 if ( is_null( $callback ) ) {
333 $callback = [ $this, 'read' ];
334 } elseif ( !is_callable( $callback ) ) {
335 throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
336 }
337 $this->callback = $callback;
338 }
339
340 /**
341 * A generic callback to read the body of the response from a remote
342 * server.
343 *
344 * @param resource $fh
345 * @param string $content
346 * @return int
347 * @internal
348 */
349 public function read( $fh, $content ) {
350 $this->content .= $content;
351 return strlen( $content );
352 }
353
354 /**
355 * Take care of whatever is necessary to perform the URI request.
356 *
357 * @return StatusValue
358 * @note currently returns Status for B/C
359 */
360 public function execute() {
361 throw new LogicException( 'children must override this' );
362 }
363
364 protected function prepare() {
365 $this->content = "";
366
367 if ( strtoupper( $this->method ) == "HEAD" ) {
368 $this->headersOnly = true;
369 }
370
371 $this->proxySetup(); // set up any proxy as needed
372
373 if ( !$this->callback ) {
374 $this->setCallback( null );
375 }
376
377 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
378 $this->setUserAgent( Http::userAgent() );
379 }
380 }
381
382 /**
383 * Parses the headers, including the HTTP status code and any
384 * Set-Cookie headers. This function expects the headers to be
385 * found in an array in the member variable headerList.
386 */
387 protected function parseHeader() {
388 $lastname = "";
389
390 foreach ( $this->headerList as $header ) {
391 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
392 $this->respVersion = $match[1];
393 $this->respStatus = $match[2];
394 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
395 $last = count( $this->respHeaders[$lastname] ) - 1;
396 $this->respHeaders[$lastname][$last] .= "\r\n$header";
397 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
398 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
399 $lastname = strtolower( $match[1] );
400 }
401 }
402
403 $this->parseCookies();
404 }
405
406 /**
407 * Sets HTTPRequest status member to a fatal value with the error
408 * message if the returned integer value of the status code was
409 * not successful (< 300) or a redirect (>=300 and < 400). (see
410 * RFC2616, section 10,
411 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
412 * list of status codes.)
413 */
414 protected function setStatus() {
415 if ( !$this->respHeaders ) {
416 $this->parseHeader();
417 }
418
419 if ( (int)$this->respStatus > 399 ) {
420 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
421 $this->status->fatal( "http-bad-status", $code, $message );
422 }
423 }
424
425 /**
426 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
427 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
428 * for a list of status codes.)
429 *
430 * @return int
431 */
432 public function getStatus() {
433 if ( !$this->respHeaders ) {
434 $this->parseHeader();
435 }
436
437 return (int)$this->respStatus;
438 }
439
440 /**
441 * Returns true if the last status code was a redirect.
442 *
443 * @return bool
444 */
445 public function isRedirect() {
446 if ( !$this->respHeaders ) {
447 $this->parseHeader();
448 }
449
450 $status = (int)$this->respStatus;
451
452 if ( $status >= 300 && $status <= 303 ) {
453 return true;
454 }
455
456 return false;
457 }
458
459 /**
460 * Returns an associative array of response headers after the
461 * request has been executed. Because some headers
462 * (e.g. Set-Cookie) can appear more than once the, each value of
463 * the associative array is an array of the values given.
464 *
465 * @return array
466 */
467 public function getResponseHeaders() {
468 if ( !$this->respHeaders ) {
469 $this->parseHeader();
470 }
471
472 return $this->respHeaders;
473 }
474
475 /**
476 * Returns the value of the given response header.
477 *
478 * @param string $header
479 * @return string|null
480 */
481 public function getResponseHeader( $header ) {
482 if ( !$this->respHeaders ) {
483 $this->parseHeader();
484 }
485
486 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
487 $v = $this->respHeaders[strtolower( $header )];
488 return $v[count( $v ) - 1];
489 }
490
491 return null;
492 }
493
494 /**
495 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
496 *
497 * To read response cookies from the jar, getCookieJar must be called first.
498 *
499 * @param CookieJar $jar
500 */
501 public function setCookieJar( $jar ) {
502 $this->cookieJar = $jar;
503 }
504
505 /**
506 * Returns the cookie jar in use.
507 *
508 * @return CookieJar
509 */
510 public function getCookieJar() {
511 if ( !$this->respHeaders ) {
512 $this->parseHeader();
513 }
514
515 return $this->cookieJar;
516 }
517
518 /**
519 * Sets a cookie. Used before a request to set up any individual
520 * cookies. Used internally after a request to parse the
521 * Set-Cookie headers.
522 * @see Cookie::set
523 * @param string $name
524 * @param string $value
525 * @param array $attr
526 */
527 public function setCookie( $name, $value, $attr = [] ) {
528 if ( !$this->cookieJar ) {
529 $this->cookieJar = new CookieJar;
530 }
531
532 if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
533 $attr['domain'] = $this->parsedUrl['host'];
534 }
535
536 $this->cookieJar->setCookie( $name, $value, $attr );
537 }
538
539 /**
540 * Parse the cookies in the response headers and store them in the cookie jar.
541 */
542 protected function parseCookies() {
543 if ( !$this->cookieJar ) {
544 $this->cookieJar = new CookieJar;
545 }
546
547 if ( isset( $this->respHeaders['set-cookie'] ) ) {
548 $url = parse_url( $this->getFinalUrl() );
549 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
550 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
551 }
552 }
553 }
554
555 /**
556 * Returns the final URL after all redirections.
557 *
558 * Relative values of the "Location" header are incorrect as
559 * stated in RFC, however they do happen and modern browsers
560 * support them. This function loops backwards through all
561 * locations in order to build the proper absolute URI - Marooned
562 * at wikia-inc.com
563 *
564 * Note that the multiple Location: headers are an artifact of
565 * CURL -- they shouldn't actually get returned this way. Rewrite
566 * this when T31232 is taken care of (high-level redirect
567 * handling rewrite).
568 *
569 * @return string
570 */
571 public function getFinalUrl() {
572 $headers = $this->getResponseHeaders();
573
574 // return full url (fix for incorrect but handled relative location)
575 if ( isset( $headers['location'] ) ) {
576 $locations = $headers['location'];
577 $domain = '';
578 $foundRelativeURI = false;
579 $countLocations = count( $locations );
580
581 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
582 $url = parse_url( $locations[$i] );
583
584 if ( isset( $url['host'] ) ) {
585 $domain = $url['scheme'] . '://' . $url['host'];
586 break; // found correct URI (with host)
587 } else {
588 $foundRelativeURI = true;
589 }
590 }
591
592 if ( !$foundRelativeURI ) {
593 return $locations[$countLocations - 1];
594 }
595 if ( $domain ) {
596 return $domain . $locations[$countLocations - 1];
597 }
598 $url = parse_url( $this->url );
599 if ( isset( $url['host'] ) ) {
600 return $url['scheme'] . '://' . $url['host'] .
601 $locations[$countLocations - 1];
602 }
603 }
604
605 return $this->url;
606 }
607
608 /**
609 * Returns true if the backend can follow redirects. Overridden by the
610 * child classes.
611 * @return bool
612 */
613 public function canFollowRedirects() {
614 return true;
615 }
616
617 /**
618 * Set information about the original request. This can be useful for
619 * endpoints/API modules which act as a proxy for some service, and
620 * throttling etc. needs to happen in that service.
621 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
622 * headers being set.
623 * @param WebRequest|array $originalRequest When in array form, it's
624 * expected to have the keys 'ip' and 'userAgent'.
625 * @note IP/user agent is personally identifiable information, and should
626 * only be set when the privacy policy of the request target is
627 * compatible with that of the MediaWiki installation.
628 */
629 public function setOriginalRequest( $originalRequest ) {
630 if ( $originalRequest instanceof WebRequest ) {
631 $originalRequest = [
632 'ip' => $originalRequest->getIP(),
633 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
634 ];
635 } elseif (
636 !is_array( $originalRequest )
637 || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
638 ) {
639 throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
640 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
641 }
642
643 $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
644 $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
645 }
646 }