http: Support HTTP Basic Authentication
[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 protected $callback;
50 protected $maxRedirects = 5;
51 protected $followRedirects = false;
52
53 /**
54 * @var CookieJar
55 */
56 protected $cookieJar;
57
58 protected $headerList = [];
59 protected $respVersion = "0.9";
60 protected $respStatus = "200 Ok";
61 protected $respHeaders = [];
62
63 public $status;
64
65 /**
66 * @var Profiler
67 */
68 protected $profiler;
69
70 /**
71 * @var string
72 */
73 protected $profileName;
74
75 /**
76 * @var LoggerInterface;
77 */
78 protected $logger;
79
80 /**
81 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
82 * @param array $options (optional) extra params to pass (see Http::request())
83 * @param string $caller The method making this request, for profiling
84 * @param Profiler $profiler An instance of the profiler for profiling, or null
85 */
86 protected function __construct(
87 $url, $options = [], $caller = __METHOD__, $profiler = null
88 ) {
89 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
90
91 $this->url = wfExpandUrl( $url, PROTO_HTTP );
92 $this->parsedUrl = wfParseUrl( $this->url );
93
94 if ( isset( $options['logger'] ) ) {
95 $this->logger = $options['logger'];
96 } else {
97 $this->logger = new NullLogger();
98 }
99
100 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
101 $this->status = Status::newFatal( 'http-invalid-url', $url );
102 } else {
103 $this->status = Status::newGood( 100 ); // continue
104 }
105
106 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
107 $this->timeout = $options['timeout'];
108 } else {
109 $this->timeout = $wgHTTPTimeout;
110 }
111 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
112 $this->connectTimeout = $options['connectTimeout'];
113 } else {
114 $this->connectTimeout = $wgHTTPConnectTimeout;
115 }
116 if ( isset( $options['userAgent'] ) ) {
117 $this->setUserAgent( $options['userAgent'] );
118 }
119 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
120 $this->setHeader(
121 'Authorization',
122 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
123 );
124 }
125
126 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
127 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
128
129 foreach ( $members as $o ) {
130 if ( isset( $options[$o] ) ) {
131 // ensure that MWHttpRequest::method is always
132 // uppercased. Bug 36137
133 if ( $o == 'method' ) {
134 $options[$o] = strtoupper( $options[$o] );
135 }
136 $this->$o = $options[$o];
137 }
138 }
139
140 if ( $this->noProxy ) {
141 $this->proxy = ''; // noProxy takes precedence
142 }
143
144 // Profile based on what's calling us
145 $this->profiler = $profiler;
146 $this->profileName = $caller;
147 }
148
149 /**
150 * @param LoggerInterface $logger
151 */
152 public function setLogger( LoggerInterface $logger ) {
153 $this->logger = $logger;
154 }
155
156 /**
157 * Simple function to test if we can make any sort of requests at all, using
158 * cURL or fopen()
159 * @return bool
160 */
161 public static function canMakeRequests() {
162 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
163 }
164
165 /**
166 * Generate a new request object
167 * @param string $url Url to use
168 * @param array $options (optional) extra params to pass (see Http::request())
169 * @param string $caller The method making this request, for profiling
170 * @throws MWException
171 * @return CurlHttpRequest|PhpHttpRequest
172 * @see MWHttpRequest::__construct
173 */
174 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
175 if ( !Http::$httpEngine ) {
176 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
177 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
178 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
179 ' Http::$httpEngine is set to "curl"' );
180 }
181
182 if ( !is_array( $options ) ) {
183 $options = [];
184 }
185
186 if ( !isset( $options['logger'] ) ) {
187 $options['logger'] = LoggerFactory::getInstance( 'http' );
188 }
189
190 switch ( Http::$httpEngine ) {
191 case 'curl':
192 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
193 case 'php':
194 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
195 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
196 'needs to be enabled for pure PHP http requests to ' .
197 'work. If possible, curl should be used instead. See ' .
198 'http://php.net/curl.'
199 );
200 }
201 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
202 default:
203 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
204 }
205 }
206
207 /**
208 * Get the body, or content, of the response to the request
209 *
210 * @return string
211 */
212 public function getContent() {
213 return $this->content;
214 }
215
216 /**
217 * Set the parameters of the request
218 *
219 * @param array $args
220 * @todo overload the args param
221 */
222 public function setData( $args ) {
223 $this->postData = $args;
224 }
225
226 /**
227 * Take care of setting up the proxy (do nothing if "noProxy" is set)
228 *
229 * @return void
230 */
231 public function proxySetup() {
232 // If there is an explicit proxy set and proxies are not disabled, then use it
233 if ( $this->proxy && !$this->noProxy ) {
234 return;
235 }
236
237 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
238 // local URL and proxies are not disabled
239 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
240 $this->proxy = '';
241 } else {
242 $this->proxy = Http::getProxy();
243 }
244 }
245
246 /**
247 * Check if the URL can be served by localhost
248 *
249 * @param string $url Full url to check
250 * @return bool
251 */
252 private static function isLocalURL( $url ) {
253 global $wgCommandLineMode, $wgLocalVirtualHosts;
254
255 if ( $wgCommandLineMode ) {
256 return false;
257 }
258
259 // Extract host part
260 $matches = [];
261 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
262 $host = $matches[1];
263 // Split up dotwise
264 $domainParts = explode( '.', $host );
265 // Check if this domain or any superdomain is listed as a local virtual host
266 $domainParts = array_reverse( $domainParts );
267
268 $domain = '';
269 $countParts = count( $domainParts );
270 for ( $i = 0; $i < $countParts; $i++ ) {
271 $domainPart = $domainParts[$i];
272 if ( $i == 0 ) {
273 $domain = $domainPart;
274 } else {
275 $domain = $domainPart . '.' . $domain;
276 }
277
278 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
279 return true;
280 }
281 }
282 }
283
284 return false;
285 }
286
287 /**
288 * Set the user agent
289 * @param string $UA
290 */
291 public function setUserAgent( $UA ) {
292 $this->setHeader( 'User-Agent', $UA );
293 }
294
295 /**
296 * Set an arbitrary header
297 * @param string $name
298 * @param string $value
299 */
300 public function setHeader( $name, $value ) {
301 // I feel like I should normalize the case here...
302 $this->reqHeaders[$name] = $value;
303 }
304
305 /**
306 * Get an array of the headers
307 * @return array
308 */
309 public function getHeaderList() {
310 $list = [];
311
312 if ( $this->cookieJar ) {
313 $this->reqHeaders['Cookie'] =
314 $this->cookieJar->serializeToHttpRequest(
315 $this->parsedUrl['path'],
316 $this->parsedUrl['host']
317 );
318 }
319
320 foreach ( $this->reqHeaders as $name => $value ) {
321 $list[] = "$name: $value";
322 }
323
324 return $list;
325 }
326
327 /**
328 * Set a read callback to accept data read from the HTTP request.
329 * By default, data is appended to an internal buffer which can be
330 * retrieved through $req->getContent().
331 *
332 * To handle data as it comes in -- especially for large files that
333 * would not fit in memory -- you can instead set your own callback,
334 * in the form function($resource, $buffer) where the first parameter
335 * is the low-level resource being read (implementation specific),
336 * and the second parameter is the data buffer.
337 *
338 * You MUST return the number of bytes handled in the buffer; if fewer
339 * bytes are reported handled than were passed to you, the HTTP fetch
340 * will be aborted.
341 *
342 * @param callable $callback
343 * @throws MWException
344 */
345 public function setCallback( $callback ) {
346 if ( !is_callable( $callback ) ) {
347 throw new MWException( 'Invalid MwHttpRequest callback' );
348 }
349 $this->callback = $callback;
350 }
351
352 /**
353 * A generic callback to read the body of the response from a remote
354 * server.
355 *
356 * @param resource $fh
357 * @param string $content
358 * @return int
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 Status
369 */
370 public function execute() {
371 $this->content = "";
372
373 if ( strtoupper( $this->method ) == "HEAD" ) {
374 $this->headersOnly = true;
375 }
376
377 $this->proxySetup(); // set up any proxy as needed
378
379 if ( !$this->callback ) {
380 $this->setCallback( [ $this, 'read' ] );
381 }
382
383 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
384 $this->setUserAgent( Http::userAgent() );
385 }
386 }
387
388 /**
389 * Parses the headers, including the HTTP status code and any
390 * Set-Cookie headers. This function expects the headers to be
391 * found in an array in the member variable headerList.
392 */
393 protected function parseHeader() {
394 $lastname = "";
395
396 foreach ( $this->headerList as $header ) {
397 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
398 $this->respVersion = $match[1];
399 $this->respStatus = $match[2];
400 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
401 $last = count( $this->respHeaders[$lastname] ) - 1;
402 $this->respHeaders[$lastname][$last] .= "\r\n$header";
403 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
404 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
405 $lastname = strtolower( $match[1] );
406 }
407 }
408
409 $this->parseCookies();
410 }
411
412 /**
413 * Sets HTTPRequest status member to a fatal value with the error
414 * message if the returned integer value of the status code was
415 * not successful (< 300) or a redirect (>=300 and < 400). (see
416 * RFC2616, section 10,
417 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
418 * list of status codes.)
419 */
420 protected function setStatus() {
421 if ( !$this->respHeaders ) {
422 $this->parseHeader();
423 }
424
425 if ( (int)$this->respStatus > 399 ) {
426 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
427 $this->status->fatal( "http-bad-status", $code, $message );
428 }
429 }
430
431 /**
432 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
433 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
434 * for a list of status codes.)
435 *
436 * @return int
437 */
438 public function getStatus() {
439 if ( !$this->respHeaders ) {
440 $this->parseHeader();
441 }
442
443 return (int)$this->respStatus;
444 }
445
446 /**
447 * Returns true if the last status code was a redirect.
448 *
449 * @return bool
450 */
451 public function isRedirect() {
452 if ( !$this->respHeaders ) {
453 $this->parseHeader();
454 }
455
456 $status = (int)$this->respStatus;
457
458 if ( $status >= 300 && $status <= 303 ) {
459 return true;
460 }
461
462 return false;
463 }
464
465 /**
466 * Returns an associative array of response headers after the
467 * request has been executed. Because some headers
468 * (e.g. Set-Cookie) can appear more than once the, each value of
469 * the associative array is an array of the values given.
470 *
471 * @return array
472 */
473 public function getResponseHeaders() {
474 if ( !$this->respHeaders ) {
475 $this->parseHeader();
476 }
477
478 return $this->respHeaders;
479 }
480
481 /**
482 * Returns the value of the given response header.
483 *
484 * @param string $header
485 * @return string|null
486 */
487 public function getResponseHeader( $header ) {
488 if ( !$this->respHeaders ) {
489 $this->parseHeader();
490 }
491
492 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
493 $v = $this->respHeaders[strtolower( $header )];
494 return $v[count( $v ) - 1];
495 }
496
497 return null;
498 }
499
500 /**
501 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
502 *
503 * @param CookieJar $jar
504 */
505 public function setCookieJar( $jar ) {
506 $this->cookieJar = $jar;
507 }
508
509 /**
510 * Returns the cookie jar in use.
511 *
512 * @return CookieJar
513 */
514 public function getCookieJar() {
515 if ( !$this->respHeaders ) {
516 $this->parseHeader();
517 }
518
519 return $this->cookieJar;
520 }
521
522 /**
523 * Sets a cookie. Used before a request to set up any individual
524 * cookies. Used internally after a request to parse the
525 * Set-Cookie headers.
526 * @see Cookie::set
527 * @param string $name
528 * @param mixed $value
529 * @param array $attr
530 */
531 public function setCookie( $name, $value = null, $attr = null ) {
532 if ( !$this->cookieJar ) {
533 $this->cookieJar = new CookieJar;
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 bug 29232 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 if ( $domain ) {
594 return $domain . $locations[$countLocations - 1];
595 } else {
596 $url = parse_url( $this->url );
597 if ( isset( $url['host'] ) ) {
598 return $url['scheme'] . '://' . $url['host'] .
599 $locations[$countLocations - 1];
600 }
601 }
602 } else {
603 return $locations[$countLocations - 1];
604 }
605 }
606
607 return $this->url;
608 }
609
610 /**
611 * Returns true if the backend can follow redirects. Overridden by the
612 * child classes.
613 * @return bool
614 */
615 public function canFollowRedirects() {
616 return true;
617 }
618 }