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