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