Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / HttpFunctions.php
blobd066df89e61ca4cb5624d4afea1afcb32cd7470b
1 <?php
2 /**
3 * Various HTTP related functions.
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.
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.
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
20 * @file
21 * @ingroup HTTP
24 /**
25 * @defgroup HTTP HTTP
28 /**
29 * Various HTTP related functions
30 * @ingroup HTTP
32 class Http {
33 static public $httpEngine = false;
35 /**
36 * Perform an HTTP request
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 * @return string|bool (bool)false on failure or a string on success
60 public static function request( $method, $url, $options = array() ) {
61 wfDebug( "HTTP: $method: $url\n" );
63 $options['method'] = strtoupper( $method );
65 if ( !isset( $options['timeout'] ) ) {
66 $options['timeout'] = 'default';
68 if ( !isset( $options['connectTimeout'] ) ) {
69 $options['connectTimeout'] = 'default';
72 $req = MWHttpRequest::factory( $url, $options );
73 $status = $req->execute();
75 $content = false;
76 if ( $status->isOK() ) {
77 $content = $req->getContent();
79 return $content;
82 /**
83 * Simple wrapper for Http::request( 'GET' )
84 * @see Http::request()
86 * @param string $url
87 * @param string $timeout
88 * @param array $options
89 * @return string
91 public static function get( $url, $timeout = 'default', $options = array() ) {
92 $options['timeout'] = $timeout;
93 return Http::request( 'GET', $url, $options );
96 /**
97 * Simple wrapper for Http::request( 'POST' )
98 * @see Http::request()
100 * @param string $url
101 * @param array $options
102 * @return string
104 public static function post( $url, $options = array() ) {
105 return Http::request( 'POST', $url, $options );
109 * Check if the URL can be served by localhost
111 * @param string $url Full url to check
112 * @return bool
114 public static function isLocalURL( $url ) {
115 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
117 if ( $wgCommandLineMode ) {
118 return false;
121 // Extract host part
122 $matches = array();
123 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
124 $host = $matches[1];
125 // Split up dotwise
126 $domainParts = explode( '.', $host );
127 // Check if this domain or any superdomain is listed as a local virtual host
128 $domainParts = array_reverse( $domainParts );
130 $domain = '';
131 $countParts = count( $domainParts );
132 for ( $i = 0; $i < $countParts; $i++ ) {
133 $domainPart = $domainParts[$i];
134 if ( $i == 0 ) {
135 $domain = $domainPart;
136 } else {
137 $domain = $domainPart . '.' . $domain;
140 if ( in_array( $domain, $wgLocalVirtualHosts )
141 || $wgConf->isLocalVHost( $domain )
143 return true;
148 return false;
152 * A standard user-agent we can use for external requests.
153 * @return string
155 public static function userAgent() {
156 global $wgVersion;
157 return "MediaWiki/$wgVersion";
161 * Checks that the given URI is a valid one. Hardcoding the
162 * protocols, because we only want protocols that both cURL
163 * and php support.
165 * file:// should not be allowed here for security purpose (r67684)
167 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
169 * @param string $uri URI to check for validity
170 * @return bool
172 public static function isValidURI( $uri ) {
173 return preg_match(
174 '/^https?:\/\/[^\/\s]\S*$/D',
175 $uri
181 * This wrapper class will call out to curl (if available) or fallback
182 * to regular PHP if necessary for handling internal HTTP requests.
184 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
185 * PHP's HTTP extension.
187 class MWHttpRequest {
188 const SUPPORTS_FILE_POSTS = false;
190 protected $content;
191 protected $timeout = 'default';
192 protected $headersOnly = null;
193 protected $postData = null;
194 protected $proxy = null;
195 protected $noProxy = false;
196 protected $sslVerifyHost = true;
197 protected $sslVerifyCert = true;
198 protected $caInfo = null;
199 protected $method = "GET";
200 protected $reqHeaders = array();
201 protected $url;
202 protected $parsedUrl;
203 protected $callback;
204 protected $maxRedirects = 5;
205 protected $followRedirects = false;
208 * @var CookieJar
210 protected $cookieJar;
212 protected $headerList = array();
213 protected $respVersion = "0.9";
214 protected $respStatus = "200 Ok";
215 protected $respHeaders = array();
217 public $status;
220 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
221 * @param array $options (optional) extra params to pass (see Http::request())
223 protected function __construct( $url, $options = array() ) {
224 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
226 $this->url = wfExpandUrl( $url, PROTO_HTTP );
227 $this->parsedUrl = wfParseUrl( $this->url );
229 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
230 $this->status = Status::newFatal( 'http-invalid-url' );
231 } else {
232 $this->status = Status::newGood( 100 ); // continue
235 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
236 $this->timeout = $options['timeout'];
237 } else {
238 $this->timeout = $wgHTTPTimeout;
240 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
241 $this->connectTimeout = $options['connectTimeout'];
242 } else {
243 $this->connectTimeout = $wgHTTPConnectTimeout;
245 if ( isset( $options['userAgent'] ) ) {
246 $this->setUserAgent( $options['userAgent'] );
249 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
250 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
252 foreach ( $members as $o ) {
253 if ( isset( $options[$o] ) ) {
254 // ensure that MWHttpRequest::method is always
255 // uppercased. Bug 36137
256 if ( $o == 'method' ) {
257 $options[$o] = strtoupper( $options[$o] );
259 $this->$o = $options[$o];
263 if ( $this->noProxy ) {
264 $this->proxy = ''; // noProxy takes precedence
269 * Simple function to test if we can make any sort of requests at all, using
270 * cURL or fopen()
271 * @return bool
273 public static function canMakeRequests() {
274 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
278 * Generate a new request object
279 * @param string $url Url to use
280 * @param array $options (optional) extra params to pass (see Http::request())
281 * @throws MWException
282 * @return CurlHttpRequest|PhpHttpRequest
283 * @see MWHttpRequest::__construct
285 public static function factory( $url, $options = null ) {
286 if ( !Http::$httpEngine ) {
287 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
288 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
289 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
290 ' Http::$httpEngine is set to "curl"' );
293 switch ( Http::$httpEngine ) {
294 case 'curl':
295 return new CurlHttpRequest( $url, $options );
296 case 'php':
297 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
298 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
299 'needs to be enabled for pure PHP http requests to ' .
300 'work. If possible, curl should be used instead. See ' .
301 'http://php.net/curl.'
304 return new PhpHttpRequest( $url, $options );
305 default:
306 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
311 * Get the body, or content, of the response to the request
313 * @return string
315 public function getContent() {
316 return $this->content;
320 * Set the parameters of the request
322 * @param array $args
323 * @todo overload the args param
325 public function setData( $args ) {
326 $this->postData = $args;
330 * Take care of setting up the proxy (do nothing if "noProxy" is set)
332 * @return void
334 public function proxySetup() {
335 global $wgHTTPProxy;
337 // If there is an explicit proxy set and proxies are not disabled, then use it
338 if ( $this->proxy && !$this->noProxy ) {
339 return;
342 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
343 // local URL and proxies are not disabled
344 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
345 $this->proxy = '';
346 } elseif ( $wgHTTPProxy ) {
347 $this->proxy = $wgHTTPProxy;
348 } elseif ( getenv( "http_proxy" ) ) {
349 $this->proxy = getenv( "http_proxy" );
354 * Set the user agent
355 * @param string $UA
357 public function setUserAgent( $UA ) {
358 $this->setHeader( 'User-Agent', $UA );
362 * Set an arbitrary header
363 * @param string $name
364 * @param string $value
366 public function setHeader( $name, $value ) {
367 // I feel like I should normalize the case here...
368 $this->reqHeaders[$name] = $value;
372 * Get an array of the headers
373 * @return array
375 public function getHeaderList() {
376 $list = array();
378 if ( $this->cookieJar ) {
379 $this->reqHeaders['Cookie'] =
380 $this->cookieJar->serializeToHttpRequest(
381 $this->parsedUrl['path'],
382 $this->parsedUrl['host']
386 foreach ( $this->reqHeaders as $name => $value ) {
387 $list[] = "$name: $value";
390 return $list;
394 * Set a read callback to accept data read from the HTTP request.
395 * By default, data is appended to an internal buffer which can be
396 * retrieved through $req->getContent().
398 * To handle data as it comes in -- especially for large files that
399 * would not fit in memory -- you can instead set your own callback,
400 * in the form function($resource, $buffer) where the first parameter
401 * is the low-level resource being read (implementation specific),
402 * and the second parameter is the data buffer.
404 * You MUST return the number of bytes handled in the buffer; if fewer
405 * bytes are reported handled than were passed to you, the HTTP fetch
406 * will be aborted.
408 * @param callable $callback
409 * @throws MWException
411 public function setCallback( $callback ) {
412 if ( !is_callable( $callback ) ) {
413 throw new MWException( 'Invalid MwHttpRequest callback' );
415 $this->callback = $callback;
419 * A generic callback to read the body of the response from a remote
420 * server.
422 * @param resource $fh
423 * @param string $content
424 * @return int
426 public function read( $fh, $content ) {
427 $this->content .= $content;
428 return strlen( $content );
432 * Take care of whatever is necessary to perform the URI request.
434 * @return Status
436 public function execute() {
438 $this->content = "";
440 if ( strtoupper( $this->method ) == "HEAD" ) {
441 $this->headersOnly = true;
444 $this->proxySetup(); // set up any proxy as needed
446 if ( !$this->callback ) {
447 $this->setCallback( array( $this, 'read' ) );
450 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
451 $this->setUserAgent( Http::userAgent() );
457 * Parses the headers, including the HTTP status code and any
458 * Set-Cookie headers. This function expects the headers to be
459 * found in an array in the member variable headerList.
461 protected function parseHeader() {
463 $lastname = "";
465 foreach ( $this->headerList as $header ) {
466 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
467 $this->respVersion = $match[1];
468 $this->respStatus = $match[2];
469 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
470 $last = count( $this->respHeaders[$lastname] ) - 1;
471 $this->respHeaders[$lastname][$last] .= "\r\n$header";
472 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
473 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
474 $lastname = strtolower( $match[1] );
478 $this->parseCookies();
483 * Sets HTTPRequest status member to a fatal value with the error
484 * message if the returned integer value of the status code was
485 * not successful (< 300) or a redirect (>=300 and < 400). (see
486 * RFC2616, section 10,
487 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
488 * list of status codes.)
490 protected function setStatus() {
491 if ( !$this->respHeaders ) {
492 $this->parseHeader();
495 if ( (int)$this->respStatus > 399 ) {
496 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
497 $this->status->fatal( "http-bad-status", $code, $message );
502 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
503 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
504 * for a list of status codes.)
506 * @return int
508 public function getStatus() {
509 if ( !$this->respHeaders ) {
510 $this->parseHeader();
513 return (int)$this->respStatus;
517 * Returns true if the last status code was a redirect.
519 * @return bool
521 public function isRedirect() {
522 if ( !$this->respHeaders ) {
523 $this->parseHeader();
526 $status = (int)$this->respStatus;
528 if ( $status >= 300 && $status <= 303 ) {
529 return true;
532 return false;
536 * Returns an associative array of response headers after the
537 * request has been executed. Because some headers
538 * (e.g. Set-Cookie) can appear more than once the, each value of
539 * the associative array is an array of the values given.
541 * @return array
543 public function getResponseHeaders() {
544 if ( !$this->respHeaders ) {
545 $this->parseHeader();
548 return $this->respHeaders;
552 * Returns the value of the given response header.
554 * @param string $header
555 * @return string
557 public function getResponseHeader( $header ) {
558 if ( !$this->respHeaders ) {
559 $this->parseHeader();
562 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
563 $v = $this->respHeaders[strtolower( $header )];
564 return $v[count( $v ) - 1];
567 return null;
571 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
573 * @param CookieJar $jar
575 public function setCookieJar( $jar ) {
576 $this->cookieJar = $jar;
580 * Returns the cookie jar in use.
582 * @return CookieJar
584 public function getCookieJar() {
585 if ( !$this->respHeaders ) {
586 $this->parseHeader();
589 return $this->cookieJar;
593 * Sets a cookie. Used before a request to set up any individual
594 * cookies. Used internally after a request to parse the
595 * Set-Cookie headers.
596 * @see Cookie::set
597 * @param string $name
598 * @param mixed $value
599 * @param array $attr
601 public function setCookie( $name, $value = null, $attr = null ) {
602 if ( !$this->cookieJar ) {
603 $this->cookieJar = new CookieJar;
606 $this->cookieJar->setCookie( $name, $value, $attr );
610 * Parse the cookies in the response headers and store them in the cookie jar.
612 protected function parseCookies() {
614 if ( !$this->cookieJar ) {
615 $this->cookieJar = new CookieJar;
618 if ( isset( $this->respHeaders['set-cookie'] ) ) {
619 $url = parse_url( $this->getFinalUrl() );
620 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
621 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
628 * Returns the final URL after all redirections.
630 * Relative values of the "Location" header are incorrect as
631 * stated in RFC, however they do happen and modern browsers
632 * support them. This function loops backwards through all
633 * locations in order to build the proper absolute URI - Marooned
634 * at wikia-inc.com
636 * Note that the multiple Location: headers are an artifact of
637 * CURL -- they shouldn't actually get returned this way. Rewrite
638 * this when bug 29232 is taken care of (high-level redirect
639 * handling rewrite).
641 * @return string
643 public function getFinalUrl() {
644 $headers = $this->getResponseHeaders();
646 //return full url (fix for incorrect but handled relative location)
647 if ( isset( $headers['location'] ) ) {
648 $locations = $headers['location'];
649 $domain = '';
650 $foundRelativeURI = false;
651 $countLocations = count( $locations );
653 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
654 $url = parse_url( $locations[$i] );
656 if ( isset( $url['host'] ) ) {
657 $domain = $url['scheme'] . '://' . $url['host'];
658 break; //found correct URI (with host)
659 } else {
660 $foundRelativeURI = true;
664 if ( $foundRelativeURI ) {
665 if ( $domain ) {
666 return $domain . $locations[$countLocations - 1];
667 } else {
668 $url = parse_url( $this->url );
669 if ( isset( $url['host'] ) ) {
670 return $url['scheme'] . '://' . $url['host'] .
671 $locations[$countLocations - 1];
674 } else {
675 return $locations[$countLocations - 1];
679 return $this->url;
683 * Returns true if the backend can follow redirects. Overridden by the
684 * child classes.
685 * @return bool
687 public function canFollowRedirects() {
688 return true;
693 * MWHttpRequest implemented using internal curl compiled into PHP
695 class CurlHttpRequest extends MWHttpRequest {
696 const SUPPORTS_FILE_POSTS = true;
698 protected $curlOptions = array();
699 protected $headerText = "";
702 * @param resource $fh
703 * @param string $content
704 * @return int
706 protected function readHeader( $fh, $content ) {
707 $this->headerText .= $content;
708 return strlen( $content );
711 public function execute() {
713 parent::execute();
715 if ( !$this->status->isOK() ) {
716 return $this->status;
719 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
720 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
722 // Only supported in curl >= 7.16.2
723 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
724 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
727 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
728 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
729 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
730 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
731 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
733 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
735 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
736 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
738 if ( $this->caInfo ) {
739 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
742 if ( $this->headersOnly ) {
743 $this->curlOptions[CURLOPT_NOBODY] = true;
744 $this->curlOptions[CURLOPT_HEADER] = true;
745 } elseif ( $this->method == 'POST' ) {
746 $this->curlOptions[CURLOPT_POST] = true;
747 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
748 // Suppress 'Expect: 100-continue' header, as some servers
749 // will reject it with a 417 and Curl won't auto retry
750 // with HTTP 1.0 fallback
751 $this->reqHeaders['Expect'] = '';
752 } else {
753 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
756 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
758 $curlHandle = curl_init( $this->url );
760 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
761 throw new MWException( "Error setting curl options." );
764 if ( $this->followRedirects && $this->canFollowRedirects() ) {
765 wfSuppressWarnings();
766 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
767 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
768 "Probably safe_mode or open_basedir is set.\n" );
769 // Continue the processing. If it were in curl_setopt_array,
770 // processing would have halted on its entry
772 wfRestoreWarnings();
775 $curlRes = curl_exec( $curlHandle );
776 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
777 $this->status->fatal( 'http-timed-out', $this->url );
778 } elseif ( $curlRes === false ) {
779 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
780 } else {
781 $this->headerList = explode( "\r\n", $this->headerText );
784 curl_close( $curlHandle );
786 $this->parseHeader();
787 $this->setStatus();
789 return $this->status;
793 * @return bool
795 public function canFollowRedirects() {
796 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
797 wfDebug( "Cannot follow redirects in safe mode\n" );
798 return false;
801 $curlVersionInfo = curl_version();
802 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
803 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
804 return false;
807 return true;
811 class PhpHttpRequest extends MWHttpRequest {
814 * @param string $url
815 * @return string
817 protected function urlToTcp( $url ) {
818 $parsedUrl = parse_url( $url );
820 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
823 public function execute() {
825 parent::execute();
827 if ( is_array( $this->postData ) ) {
828 $this->postData = wfArrayToCgi( $this->postData );
831 if ( $this->parsedUrl['scheme'] != 'http'
832 && $this->parsedUrl['scheme'] != 'https' ) {
833 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
836 $this->reqHeaders['Accept'] = "*/*";
837 $this->reqHeaders['Connection'] = 'Close';
838 if ( $this->method == 'POST' ) {
839 // Required for HTTP 1.0 POSTs
840 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
841 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
842 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
846 // Set up PHP stream context
847 $options = array(
848 'http' => array(
849 'method' => $this->method,
850 'header' => implode( "\r\n", $this->getHeaderList() ),
851 'protocol_version' => '1.1',
852 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
853 'ignore_errors' => true,
854 'timeout' => $this->timeout,
855 // Curl options in case curlwrappers are installed
856 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
857 'curl_verify_ssl_peer' => $this->sslVerifyCert,
859 'ssl' => array(
860 'verify_peer' => $this->sslVerifyCert,
861 'SNI_enabled' => true,
865 if ( $this->proxy ) {
866 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
867 $options['http']['request_fulluri'] = true;
870 if ( $this->postData ) {
871 $options['http']['content'] = $this->postData;
874 if ( $this->sslVerifyHost ) {
875 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
878 if ( is_dir( $this->caInfo ) ) {
879 $options['ssl']['capath'] = $this->caInfo;
880 } elseif ( is_file( $this->caInfo ) ) {
881 $options['ssl']['cafile'] = $this->caInfo;
882 } elseif ( $this->caInfo ) {
883 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
886 $context = stream_context_create( $options );
888 $this->headerList = array();
889 $reqCount = 0;
890 $url = $this->url;
892 $result = array();
894 do {
895 $reqCount++;
896 wfSuppressWarnings();
897 $fh = fopen( $url, "r", false, $context );
898 wfRestoreWarnings();
900 if ( !$fh ) {
901 break;
904 $result = stream_get_meta_data( $fh );
905 $this->headerList = $result['wrapper_data'];
906 $this->parseHeader();
908 if ( !$this->followRedirects ) {
909 break;
912 # Handle manual redirection
913 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
914 break;
916 # Check security of URL
917 $url = $this->getResponseHeader( "Location" );
919 if ( !Http::isValidURI( $url ) ) {
920 wfDebug( __METHOD__ . ": insecure redirection\n" );
921 break;
923 } while ( true );
925 $this->setStatus();
927 if ( $fh === false ) {
928 $this->status->fatal( 'http-request-error' );
929 return $this->status;
932 if ( $result['timed_out'] ) {
933 $this->status->fatal( 'http-timed-out', $this->url );
934 return $this->status;
937 // If everything went OK, or we received some error code
938 // get the response body content.
939 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
940 while ( !feof( $fh ) ) {
941 $buf = fread( $fh, 8192 );
943 if ( $buf === false ) {
944 $this->status->fatal( 'http-read-error' );
945 break;
948 if ( strlen( $buf ) ) {
949 call_user_func( $this->callback, $fh, $buf );
953 fclose( $fh );
955 return $this->status;