Switch some HTMLForms in special pages to OOUI
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * Various HTTP related functions.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup HTTP
22 */
23
24 /**
25 * @defgroup HTTP HTTP
26 */
27
28 /**
29 * Various HTTP related functions
30 * @ingroup HTTP
31 */
32 class Http {
33 static public $httpEngine = false;
34
35 /**
36 * Perform an HTTP request
37 *
38 * @param string $method HTTP method. Usually GET/POST
39 * @param string $url Full URL to act on. If protocol-relative, will be expanded to an http:// URL
40 * @param array $options Options to pass to MWHttpRequest object.
41 * Possible keys for the array:
42 * - timeout Timeout length in seconds
43 * - connectTimeout Timeout for connection, in seconds (curl only)
44 * - postData An array of key-value pairs or a url-encoded form data
45 * - proxy The proxy to use.
46 * Otherwise it will use $wgHTTPProxy (if set)
47 * Otherwise it will use the environment variable "http_proxy" (if set)
48 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
49 * - sslVerifyHost Verify hostname against certificate
50 * - sslVerifyCert Verify SSL certificate
51 * - caInfo Provide CA information
52 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
53 * - followRedirects Whether to follow redirects (defaults to false).
54 * Note: this should only be used when the target URL is trusted,
55 * to avoid attacks on intranet services accessible by HTTP.
56 * - userAgent A user agent, if you want to override the default
57 * MediaWiki/$wgVersion
58 * @param string $caller The method making this request, for profiling
59 * @return string|bool (bool)false on failure or a string on success
60 */
61 public static function request( $method, $url, $options = array(), $caller = __METHOD__ ) {
62 wfDebug( "HTTP: $method: $url\n" );
63
64 $options['method'] = strtoupper( $method );
65
66 if ( !isset( $options['timeout'] ) ) {
67 $options['timeout'] = 'default';
68 }
69 if ( !isset( $options['connectTimeout'] ) ) {
70 $options['connectTimeout'] = 'default';
71 }
72
73 $req = MWHttpRequest::factory( $url, $options, $caller );
74 $status = $req->execute();
75
76 $content = false;
77 if ( $status->isOK() ) {
78 $content = $req->getContent();
79 }
80 return $content;
81 }
82
83 /**
84 * Simple wrapper for Http::request( 'GET' )
85 * @see Http::request()
86 * @since 1.25 Second parameter $timeout removed. Second parameter
87 * is now $options which can be given a 'timeout'
88 *
89 * @param string $url
90 * @param array $options
91 * @param string $caller The method making this request, for profiling
92 * @return string
93 */
94 public static function get( $url, $options = array(), $caller = __METHOD__ ) {
95 $args = func_get_args();
96 if ( isset( $args[1] ) && ( is_string( $args[1] ) || is_numeric( $args[1] ) ) ) {
97 // Second was used to be the timeout
98 // And third parameter used to be $options
99 wfWarn( "Second parameter should not be a timeout.", 2 );
100 $options = isset( $args[2] ) && is_array( $args[2] ) ?
101 $args[2] : array();
102 $options['timeout'] = $args[1];
103 $caller = __METHOD__;
104 }
105 return Http::request( 'GET', $url, $options, $caller );
106 }
107
108 /**
109 * Simple wrapper for Http::request( 'POST' )
110 * @see Http::request()
111 *
112 * @param string $url
113 * @param array $options
114 * @param string $caller The method making this request, for profiling
115 * @return string
116 */
117 public static function post( $url, $options = array(), $caller = __METHOD__ ) {
118 return Http::request( 'POST', $url, $options, $caller );
119 }
120
121 /**
122 * Check if the URL can be served by localhost
123 *
124 * @param string $url Full url to check
125 * @return bool
126 */
127 public static function isLocalURL( $url ) {
128 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
129
130 if ( $wgCommandLineMode ) {
131 return false;
132 }
133
134 // Extract host part
135 $matches = array();
136 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
137 $host = $matches[1];
138 // Split up dotwise
139 $domainParts = explode( '.', $host );
140 // Check if this domain or any superdomain is listed as a local virtual host
141 $domainParts = array_reverse( $domainParts );
142
143 $domain = '';
144 $countParts = count( $domainParts );
145 for ( $i = 0; $i < $countParts; $i++ ) {
146 $domainPart = $domainParts[$i];
147 if ( $i == 0 ) {
148 $domain = $domainPart;
149 } else {
150 $domain = $domainPart . '.' . $domain;
151 }
152
153 if ( in_array( $domain, $wgLocalVirtualHosts )
154 || $wgConf->isLocalVHost( $domain )
155 ) {
156 return true;
157 }
158 }
159 }
160
161 return false;
162 }
163
164 /**
165 * A standard user-agent we can use for external requests.
166 * @return string
167 */
168 public static function userAgent() {
169 global $wgVersion;
170 return "MediaWiki/$wgVersion";
171 }
172
173 /**
174 * Checks that the given URI is a valid one. Hardcoding the
175 * protocols, because we only want protocols that both cURL
176 * and php support.
177 *
178 * file:// should not be allowed here for security purpose (r67684)
179 *
180 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
181 *
182 * @param string $uri URI to check for validity
183 * @return bool
184 */
185 public static function isValidURI( $uri ) {
186 return preg_match(
187 '/^https?:\/\/[^\/\s]\S*$/D',
188 $uri
189 );
190 }
191 }
192
193 /**
194 * This wrapper class will call out to curl (if available) or fallback
195 * to regular PHP if necessary for handling internal HTTP requests.
196 *
197 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
198 * PHP's HTTP extension.
199 */
200 class MWHttpRequest {
201 const SUPPORTS_FILE_POSTS = false;
202
203 protected $content;
204 protected $timeout = 'default';
205 protected $headersOnly = null;
206 protected $postData = null;
207 protected $proxy = null;
208 protected $noProxy = false;
209 protected $sslVerifyHost = true;
210 protected $sslVerifyCert = true;
211 protected $caInfo = null;
212 protected $method = "GET";
213 protected $reqHeaders = array();
214 protected $url;
215 protected $parsedUrl;
216 protected $callback;
217 protected $maxRedirects = 5;
218 protected $followRedirects = false;
219
220 /**
221 * @var CookieJar
222 */
223 protected $cookieJar;
224
225 protected $headerList = array();
226 protected $respVersion = "0.9";
227 protected $respStatus = "200 Ok";
228 protected $respHeaders = array();
229
230 public $status;
231
232 /**
233 * @var Profiler
234 */
235 protected $profiler;
236
237 /**
238 * @var string
239 */
240 protected $profileName;
241
242 /**
243 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
244 * @param array $options (optional) extra params to pass (see Http::request())
245 * @param string $caller The method making this request, for profiling
246 * @param Profiler $profiler An instance of the profiler for profiling, or null
247 */
248 protected function __construct( $url, $options = array(), $caller = __METHOD__, $profiler = null ) {
249 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
250
251 $this->url = wfExpandUrl( $url, PROTO_HTTP );
252 $this->parsedUrl = wfParseUrl( $this->url );
253
254 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
255 $this->status = Status::newFatal( 'http-invalid-url' );
256 } else {
257 $this->status = Status::newGood( 100 ); // continue
258 }
259
260 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
261 $this->timeout = $options['timeout'];
262 } else {
263 $this->timeout = $wgHTTPTimeout;
264 }
265 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
266 $this->connectTimeout = $options['connectTimeout'];
267 } else {
268 $this->connectTimeout = $wgHTTPConnectTimeout;
269 }
270 if ( isset( $options['userAgent'] ) ) {
271 $this->setUserAgent( $options['userAgent'] );
272 }
273
274 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
275 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
276
277 foreach ( $members as $o ) {
278 if ( isset( $options[$o] ) ) {
279 // ensure that MWHttpRequest::method is always
280 // uppercased. Bug 36137
281 if ( $o == 'method' ) {
282 $options[$o] = strtoupper( $options[$o] );
283 }
284 $this->$o = $options[$o];
285 }
286 }
287
288 if ( $this->noProxy ) {
289 $this->proxy = ''; // noProxy takes precedence
290 }
291
292 // Profile based on what's calling us
293 $this->profiler = $profiler;
294 $this->profileName = $caller;
295 }
296
297 /**
298 * Simple function to test if we can make any sort of requests at all, using
299 * cURL or fopen()
300 * @return bool
301 */
302 public static function canMakeRequests() {
303 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
304 }
305
306 /**
307 * Generate a new request object
308 * @param string $url Url to use
309 * @param array $options (optional) extra params to pass (see Http::request())
310 * @param string $caller The method making this request, for profiling
311 * @throws MWException
312 * @return CurlHttpRequest|PhpHttpRequest
313 * @see MWHttpRequest::__construct
314 */
315 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
316 if ( !Http::$httpEngine ) {
317 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
318 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
319 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
320 ' Http::$httpEngine is set to "curl"' );
321 }
322
323 switch ( Http::$httpEngine ) {
324 case 'curl':
325 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
326 case 'php':
327 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
328 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
329 'needs to be enabled for pure PHP http requests to ' .
330 'work. If possible, curl should be used instead. See ' .
331 'http://php.net/curl.'
332 );
333 }
334 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
335 default:
336 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
337 }
338 }
339
340 /**
341 * Get the body, or content, of the response to the request
342 *
343 * @return string
344 */
345 public function getContent() {
346 return $this->content;
347 }
348
349 /**
350 * Set the parameters of the request
351 *
352 * @param array $args
353 * @todo overload the args param
354 */
355 public function setData( $args ) {
356 $this->postData = $args;
357 }
358
359 /**
360 * Take care of setting up the proxy (do nothing if "noProxy" is set)
361 *
362 * @return void
363 */
364 public function proxySetup() {
365 global $wgHTTPProxy;
366
367 // If there is an explicit proxy set and proxies are not disabled, then use it
368 if ( $this->proxy && !$this->noProxy ) {
369 return;
370 }
371
372 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
373 // local URL and proxies are not disabled
374 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
375 $this->proxy = '';
376 } elseif ( $wgHTTPProxy ) {
377 $this->proxy = $wgHTTPProxy;
378 } elseif ( getenv( "http_proxy" ) ) {
379 $this->proxy = getenv( "http_proxy" );
380 }
381 }
382
383 /**
384 * Set the user agent
385 * @param string $UA
386 */
387 public function setUserAgent( $UA ) {
388 $this->setHeader( 'User-Agent', $UA );
389 }
390
391 /**
392 * Set an arbitrary header
393 * @param string $name
394 * @param string $value
395 */
396 public function setHeader( $name, $value ) {
397 // I feel like I should normalize the case here...
398 $this->reqHeaders[$name] = $value;
399 }
400
401 /**
402 * Get an array of the headers
403 * @return array
404 */
405 public function getHeaderList() {
406 $list = array();
407
408 if ( $this->cookieJar ) {
409 $this->reqHeaders['Cookie'] =
410 $this->cookieJar->serializeToHttpRequest(
411 $this->parsedUrl['path'],
412 $this->parsedUrl['host']
413 );
414 }
415
416 foreach ( $this->reqHeaders as $name => $value ) {
417 $list[] = "$name: $value";
418 }
419
420 return $list;
421 }
422
423 /**
424 * Set a read callback to accept data read from the HTTP request.
425 * By default, data is appended to an internal buffer which can be
426 * retrieved through $req->getContent().
427 *
428 * To handle data as it comes in -- especially for large files that
429 * would not fit in memory -- you can instead set your own callback,
430 * in the form function($resource, $buffer) where the first parameter
431 * is the low-level resource being read (implementation specific),
432 * and the second parameter is the data buffer.
433 *
434 * You MUST return the number of bytes handled in the buffer; if fewer
435 * bytes are reported handled than were passed to you, the HTTP fetch
436 * will be aborted.
437 *
438 * @param callable $callback
439 * @throws MWException
440 */
441 public function setCallback( $callback ) {
442 if ( !is_callable( $callback ) ) {
443 throw new MWException( 'Invalid MwHttpRequest callback' );
444 }
445 $this->callback = $callback;
446 }
447
448 /**
449 * A generic callback to read the body of the response from a remote
450 * server.
451 *
452 * @param resource $fh
453 * @param string $content
454 * @return int
455 */
456 public function read( $fh, $content ) {
457 $this->content .= $content;
458 return strlen( $content );
459 }
460
461 /**
462 * Take care of whatever is necessary to perform the URI request.
463 *
464 * @return Status
465 */
466 public function execute() {
467
468 $this->content = "";
469
470 if ( strtoupper( $this->method ) == "HEAD" ) {
471 $this->headersOnly = true;
472 }
473
474 $this->proxySetup(); // set up any proxy as needed
475
476 if ( !$this->callback ) {
477 $this->setCallback( array( $this, 'read' ) );
478 }
479
480 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
481 $this->setUserAgent( Http::userAgent() );
482 }
483
484 }
485
486 /**
487 * Parses the headers, including the HTTP status code and any
488 * Set-Cookie headers. This function expects the headers to be
489 * found in an array in the member variable headerList.
490 */
491 protected function parseHeader() {
492
493 $lastname = "";
494
495 foreach ( $this->headerList as $header ) {
496 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
497 $this->respVersion = $match[1];
498 $this->respStatus = $match[2];
499 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
500 $last = count( $this->respHeaders[$lastname] ) - 1;
501 $this->respHeaders[$lastname][$last] .= "\r\n$header";
502 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
503 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
504 $lastname = strtolower( $match[1] );
505 }
506 }
507
508 $this->parseCookies();
509
510 }
511
512 /**
513 * Sets HTTPRequest status member to a fatal value with the error
514 * message if the returned integer value of the status code was
515 * not successful (< 300) or a redirect (>=300 and < 400). (see
516 * RFC2616, section 10,
517 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
518 * list of status codes.)
519 */
520 protected function setStatus() {
521 if ( !$this->respHeaders ) {
522 $this->parseHeader();
523 }
524
525 if ( (int)$this->respStatus > 399 ) {
526 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
527 $this->status->fatal( "http-bad-status", $code, $message );
528 }
529 }
530
531 /**
532 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
533 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
534 * for a list of status codes.)
535 *
536 * @return int
537 */
538 public function getStatus() {
539 if ( !$this->respHeaders ) {
540 $this->parseHeader();
541 }
542
543 return (int)$this->respStatus;
544 }
545
546 /**
547 * Returns true if the last status code was a redirect.
548 *
549 * @return bool
550 */
551 public function isRedirect() {
552 if ( !$this->respHeaders ) {
553 $this->parseHeader();
554 }
555
556 $status = (int)$this->respStatus;
557
558 if ( $status >= 300 && $status <= 303 ) {
559 return true;
560 }
561
562 return false;
563 }
564
565 /**
566 * Returns an associative array of response headers after the
567 * request has been executed. Because some headers
568 * (e.g. Set-Cookie) can appear more than once the, each value of
569 * the associative array is an array of the values given.
570 *
571 * @return array
572 */
573 public function getResponseHeaders() {
574 if ( !$this->respHeaders ) {
575 $this->parseHeader();
576 }
577
578 return $this->respHeaders;
579 }
580
581 /**
582 * Returns the value of the given response header.
583 *
584 * @param string $header
585 * @return string
586 */
587 public function getResponseHeader( $header ) {
588 if ( !$this->respHeaders ) {
589 $this->parseHeader();
590 }
591
592 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
593 $v = $this->respHeaders[strtolower( $header )];
594 return $v[count( $v ) - 1];
595 }
596
597 return null;
598 }
599
600 /**
601 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
602 *
603 * @param CookieJar $jar
604 */
605 public function setCookieJar( $jar ) {
606 $this->cookieJar = $jar;
607 }
608
609 /**
610 * Returns the cookie jar in use.
611 *
612 * @return CookieJar
613 */
614 public function getCookieJar() {
615 if ( !$this->respHeaders ) {
616 $this->parseHeader();
617 }
618
619 return $this->cookieJar;
620 }
621
622 /**
623 * Sets a cookie. Used before a request to set up any individual
624 * cookies. Used internally after a request to parse the
625 * Set-Cookie headers.
626 * @see Cookie::set
627 * @param string $name
628 * @param mixed $value
629 * @param array $attr
630 */
631 public function setCookie( $name, $value = null, $attr = null ) {
632 if ( !$this->cookieJar ) {
633 $this->cookieJar = new CookieJar;
634 }
635
636 $this->cookieJar->setCookie( $name, $value, $attr );
637 }
638
639 /**
640 * Parse the cookies in the response headers and store them in the cookie jar.
641 */
642 protected function parseCookies() {
643
644 if ( !$this->cookieJar ) {
645 $this->cookieJar = new CookieJar;
646 }
647
648 if ( isset( $this->respHeaders['set-cookie'] ) ) {
649 $url = parse_url( $this->getFinalUrl() );
650 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
651 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
652 }
653 }
654
655 }
656
657 /**
658 * Returns the final URL after all redirections.
659 *
660 * Relative values of the "Location" header are incorrect as
661 * stated in RFC, however they do happen and modern browsers
662 * support them. This function loops backwards through all
663 * locations in order to build the proper absolute URI - Marooned
664 * at wikia-inc.com
665 *
666 * Note that the multiple Location: headers are an artifact of
667 * CURL -- they shouldn't actually get returned this way. Rewrite
668 * this when bug 29232 is taken care of (high-level redirect
669 * handling rewrite).
670 *
671 * @return string
672 */
673 public function getFinalUrl() {
674 $headers = $this->getResponseHeaders();
675
676 //return full url (fix for incorrect but handled relative location)
677 if ( isset( $headers['location'] ) ) {
678 $locations = $headers['location'];
679 $domain = '';
680 $foundRelativeURI = false;
681 $countLocations = count( $locations );
682
683 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
684 $url = parse_url( $locations[$i] );
685
686 if ( isset( $url['host'] ) ) {
687 $domain = $url['scheme'] . '://' . $url['host'];
688 break; //found correct URI (with host)
689 } else {
690 $foundRelativeURI = true;
691 }
692 }
693
694 if ( $foundRelativeURI ) {
695 if ( $domain ) {
696 return $domain . $locations[$countLocations - 1];
697 } else {
698 $url = parse_url( $this->url );
699 if ( isset( $url['host'] ) ) {
700 return $url['scheme'] . '://' . $url['host'] .
701 $locations[$countLocations - 1];
702 }
703 }
704 } else {
705 return $locations[$countLocations - 1];
706 }
707 }
708
709 return $this->url;
710 }
711
712 /**
713 * Returns true if the backend can follow redirects. Overridden by the
714 * child classes.
715 * @return bool
716 */
717 public function canFollowRedirects() {
718 return true;
719 }
720 }
721
722 /**
723 * MWHttpRequest implemented using internal curl compiled into PHP
724 */
725 class CurlHttpRequest extends MWHttpRequest {
726 const SUPPORTS_FILE_POSTS = true;
727
728 protected $curlOptions = array();
729 protected $headerText = "";
730
731 /**
732 * @param resource $fh
733 * @param string $content
734 * @return int
735 */
736 protected function readHeader( $fh, $content ) {
737 $this->headerText .= $content;
738 return strlen( $content );
739 }
740
741 public function execute() {
742
743 parent::execute();
744
745 if ( !$this->status->isOK() ) {
746 return $this->status;
747 }
748
749 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
750 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
751
752 // Only supported in curl >= 7.16.2
753 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
754 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
755 }
756
757 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
758 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
759 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
760 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
761 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
762
763 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
764
765 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
766 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
767
768 if ( $this->caInfo ) {
769 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
770 }
771
772 if ( $this->headersOnly ) {
773 $this->curlOptions[CURLOPT_NOBODY] = true;
774 $this->curlOptions[CURLOPT_HEADER] = true;
775 } elseif ( $this->method == 'POST' ) {
776 $this->curlOptions[CURLOPT_POST] = true;
777 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
778 // Suppress 'Expect: 100-continue' header, as some servers
779 // will reject it with a 417 and Curl won't auto retry
780 // with HTTP 1.0 fallback
781 $this->reqHeaders['Expect'] = '';
782 } else {
783 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
784 }
785
786 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
787
788 $curlHandle = curl_init( $this->url );
789
790 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
791 throw new MWException( "Error setting curl options." );
792 }
793
794 if ( $this->followRedirects && $this->canFollowRedirects() ) {
795 MediaWiki\suppressWarnings();
796 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
797 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
798 "Probably safe_mode or open_basedir is set.\n" );
799 // Continue the processing. If it were in curl_setopt_array,
800 // processing would have halted on its entry
801 }
802 MediaWiki\restoreWarnings();
803 }
804
805 if ( $this->profiler ) {
806 $profileSection = $this->profiler->scopedProfileIn(
807 __METHOD__ . '-' . $this->profileName
808 );
809 }
810
811 $curlRes = curl_exec( $curlHandle );
812 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
813 $this->status->fatal( 'http-timed-out', $this->url );
814 } elseif ( $curlRes === false ) {
815 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
816 } else {
817 $this->headerList = explode( "\r\n", $this->headerText );
818 }
819
820 curl_close( $curlHandle );
821
822 if ( $this->profiler ) {
823 $this->profiler->scopedProfileOut( $profileSection );
824 }
825
826 $this->parseHeader();
827 $this->setStatus();
828
829 return $this->status;
830 }
831
832 /**
833 * @return bool
834 */
835 public function canFollowRedirects() {
836 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
837 wfDebug( "Cannot follow redirects in safe mode\n" );
838 return false;
839 }
840
841 $curlVersionInfo = curl_version();
842 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
843 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
844 return false;
845 }
846
847 return true;
848 }
849 }
850
851 class PhpHttpRequest extends MWHttpRequest {
852
853 /**
854 * @param string $url
855 * @return string
856 */
857 protected function urlToTcp( $url ) {
858 $parsedUrl = parse_url( $url );
859
860 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
861 }
862
863 public function execute() {
864
865 parent::execute();
866
867 if ( is_array( $this->postData ) ) {
868 $this->postData = wfArrayToCgi( $this->postData );
869 }
870
871 if ( $this->parsedUrl['scheme'] != 'http'
872 && $this->parsedUrl['scheme'] != 'https' ) {
873 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
874 }
875
876 $this->reqHeaders['Accept'] = "*/*";
877 $this->reqHeaders['Connection'] = 'Close';
878 if ( $this->method == 'POST' ) {
879 // Required for HTTP 1.0 POSTs
880 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
881 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
882 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
883 }
884 }
885
886 // Set up PHP stream context
887 $options = array(
888 'http' => array(
889 'method' => $this->method,
890 'header' => implode( "\r\n", $this->getHeaderList() ),
891 'protocol_version' => '1.1',
892 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
893 'ignore_errors' => true,
894 'timeout' => $this->timeout,
895 // Curl options in case curlwrappers are installed
896 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
897 'curl_verify_ssl_peer' => $this->sslVerifyCert,
898 ),
899 'ssl' => array(
900 'verify_peer' => $this->sslVerifyCert,
901 'SNI_enabled' => true,
902 ),
903 );
904
905 if ( $this->proxy ) {
906 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
907 $options['http']['request_fulluri'] = true;
908 }
909
910 if ( $this->postData ) {
911 $options['http']['content'] = $this->postData;
912 }
913
914 if ( $this->sslVerifyHost ) {
915 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
916 }
917
918 if ( is_dir( $this->caInfo ) ) {
919 $options['ssl']['capath'] = $this->caInfo;
920 } elseif ( is_file( $this->caInfo ) ) {
921 $options['ssl']['cafile'] = $this->caInfo;
922 } elseif ( $this->caInfo ) {
923 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
924 }
925
926 $context = stream_context_create( $options );
927
928 $this->headerList = array();
929 $reqCount = 0;
930 $url = $this->url;
931
932 $result = array();
933
934 if ( $this->profiler ) {
935 $profileSection = $this->profiler->scopedProfileIn(
936 __METHOD__ . '-' . $this->profileName
937 );
938 }
939 do {
940 $reqCount++;
941 MediaWiki\suppressWarnings();
942 $fh = fopen( $url, "r", false, $context );
943 MediaWiki\restoreWarnings();
944
945 if ( !$fh ) {
946 break;
947 }
948
949 $result = stream_get_meta_data( $fh );
950 $this->headerList = $result['wrapper_data'];
951 $this->parseHeader();
952
953 if ( !$this->followRedirects ) {
954 break;
955 }
956
957 # Handle manual redirection
958 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
959 break;
960 }
961 # Check security of URL
962 $url = $this->getResponseHeader( "Location" );
963
964 if ( !Http::isValidURI( $url ) ) {
965 wfDebug( __METHOD__ . ": insecure redirection\n" );
966 break;
967 }
968 } while ( true );
969 if ( $this->profiler ) {
970 $this->profiler->scopedProfileOut( $profileSection );
971 }
972
973 $this->setStatus();
974
975 if ( $fh === false ) {
976 $this->status->fatal( 'http-request-error' );
977 return $this->status;
978 }
979
980 if ( $result['timed_out'] ) {
981 $this->status->fatal( 'http-timed-out', $this->url );
982 return $this->status;
983 }
984
985 // If everything went OK, or we received some error code
986 // get the response body content.
987 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
988 while ( !feof( $fh ) ) {
989 $buf = fread( $fh, 8192 );
990
991 if ( $buf === false ) {
992 $this->status->fatal( 'http-read-error' );
993 break;
994 }
995
996 if ( strlen( $buf ) ) {
997 call_user_func( $this->callback, $fh, $buf );
998 }
999 }
1000 }
1001 fclose( $fh );
1002
1003 return $this->status;
1004 }
1005 }