Fixed stream wrapper in PhpHttpRequest
[mediawiki.git] / includes / HttpFunctions.php
blob84d0437ae34aa06540cf1ee06cc6c9c7f8771729
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 Mixed: (bool)false on failure or a string on success
60 public static function request( $method, $url, $options = array() ) {
61 wfDebug( "HTTP: $method: $url\n" );
62 wfProfileIn( __METHOD__ . "-$method" );
64 $options['method'] = strtoupper( $method );
66 if ( !isset( $options['timeout'] ) ) {
67 $options['timeout'] = 'default';
69 if ( !isset( $options['connectTimeout'] ) ) {
70 $options['connectTimeout'] = 'default';
73 $req = MWHttpRequest::factory( $url, $options );
74 $status = $req->execute();
76 $content = false;
77 if ( $status->isOK() ) {
78 $content = $req->getContent();
80 wfProfileOut( __METHOD__ . "-$method" );
81 return $content;
84 /**
85 * Simple wrapper for Http::request( 'GET' )
86 * @see Http::request()
88 * @param $url
89 * @param $timeout string
90 * @param $options array
91 * @return string
93 public static function get( $url, $timeout = 'default', $options = array() ) {
94 $options['timeout'] = $timeout;
95 return Http::request( 'GET', $url, $options );
98 /**
99 * Simple wrapper for Http::request( 'POST' )
100 * @see Http::request()
102 * @param $url
103 * @param $options array
104 * @return string
106 public static function post( $url, $options = array() ) {
107 return Http::request( 'POST', $url, $options );
111 * Check if the URL can be served by localhost
113 * @param string $url full url to check
114 * @return Boolean
116 public static function isLocalURL( $url ) {
117 global $wgCommandLineMode, $wgConf;
119 if ( $wgCommandLineMode ) {
120 return false;
123 // Extract host part
124 $matches = array();
125 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
126 $host = $matches[1];
127 // Split up dotwise
128 $domainParts = explode( '.', $host );
129 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
130 $domainParts = array_reverse( $domainParts );
132 $domain = '';
133 $countParts = count( $domainParts );
134 for ( $i = 0; $i < $countParts; $i++ ) {
135 $domainPart = $domainParts[$i];
136 if ( $i == 0 ) {
137 $domain = $domainPart;
138 } else {
139 $domain = $domainPart . '.' . $domain;
142 if ( $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 $uri Mixed: URI to check for validity
170 * @return Boolean
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 $args Array
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 referrer header
356 public function setReferer( $url ) {
357 $this->setHeader( 'Referer', $url );
361 * Set the user agent
362 * @param $UA string
364 public function setUserAgent( $UA ) {
365 $this->setHeader( 'User-Agent', $UA );
369 * Set an arbitrary header
370 * @param $name
371 * @param $value
373 public function setHeader( $name, $value ) {
374 // I feel like I should normalize the case here...
375 $this->reqHeaders[$name] = $value;
379 * Get an array of the headers
380 * @return array
382 public function getHeaderList() {
383 $list = array();
385 if ( $this->cookieJar ) {
386 $this->reqHeaders['Cookie'] =
387 $this->cookieJar->serializeToHttpRequest(
388 $this->parsedUrl['path'],
389 $this->parsedUrl['host']
393 foreach ( $this->reqHeaders as $name => $value ) {
394 $list[] = "$name: $value";
397 return $list;
401 * Set a read callback to accept data read from the HTTP request.
402 * By default, data is appended to an internal buffer which can be
403 * retrieved through $req->getContent().
405 * To handle data as it comes in -- especially for large files that
406 * would not fit in memory -- you can instead set your own callback,
407 * in the form function($resource, $buffer) where the first parameter
408 * is the low-level resource being read (implementation specific),
409 * and the second parameter is the data buffer.
411 * You MUST return the number of bytes handled in the buffer; if fewer
412 * bytes are reported handled than were passed to you, the HTTP fetch
413 * will be aborted.
415 * @param $callback Callback
416 * @throws MWException
418 public function setCallback( $callback ) {
419 if ( !is_callable( $callback ) ) {
420 throw new MWException( 'Invalid MwHttpRequest callback' );
422 $this->callback = $callback;
426 * A generic callback to read the body of the response from a remote
427 * server.
429 * @param $fh handle
430 * @param $content String
431 * @return int
433 public function read( $fh, $content ) {
434 $this->content .= $content;
435 return strlen( $content );
439 * Take care of whatever is necessary to perform the URI request.
441 * @return Status
443 public function execute() {
444 global $wgTitle;
446 wfProfileIn( __METHOD__ );
448 $this->content = "";
450 if ( strtoupper( $this->method ) == "HEAD" ) {
451 $this->headersOnly = true;
454 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
455 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
458 $this->proxySetup(); // set up any proxy as needed
460 if ( !$this->callback ) {
461 $this->setCallback( array( $this, 'read' ) );
464 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
465 $this->setUserAgent( Http::userAgent() );
468 wfProfileOut( __METHOD__ );
472 * Parses the headers, including the HTTP status code and any
473 * Set-Cookie headers. This function expects the headers to be
474 * found in an array in the member variable headerList.
476 protected function parseHeader() {
477 wfProfileIn( __METHOD__ );
479 $lastname = "";
481 foreach ( $this->headerList as $header ) {
482 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
483 $this->respVersion = $match[1];
484 $this->respStatus = $match[2];
485 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
486 $last = count( $this->respHeaders[$lastname] ) - 1;
487 $this->respHeaders[$lastname][$last] .= "\r\n$header";
488 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
489 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
490 $lastname = strtolower( $match[1] );
494 $this->parseCookies();
496 wfProfileOut( __METHOD__ );
500 * Sets HTTPRequest status member to a fatal value with the error
501 * message if the returned integer value of the status code was
502 * not successful (< 300) or a redirect (>=300 and < 400). (see
503 * RFC2616, section 10,
504 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
505 * list of status codes.)
507 protected function setStatus() {
508 if ( !$this->respHeaders ) {
509 $this->parseHeader();
512 if ( (int)$this->respStatus > 399 ) {
513 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
514 $this->status->fatal( "http-bad-status", $code, $message );
519 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
520 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
521 * for a list of status codes.)
523 * @return Integer
525 public function getStatus() {
526 if ( !$this->respHeaders ) {
527 $this->parseHeader();
530 return (int)$this->respStatus;
534 * Returns true if the last status code was a redirect.
536 * @return Boolean
538 public function isRedirect() {
539 if ( !$this->respHeaders ) {
540 $this->parseHeader();
543 $status = (int)$this->respStatus;
545 if ( $status >= 300 && $status <= 303 ) {
546 return true;
549 return false;
553 * Returns an associative array of response headers after the
554 * request has been executed. Because some headers
555 * (e.g. Set-Cookie) can appear more than once the, each value of
556 * the associative array is an array of the values given.
558 * @return Array
560 public function getResponseHeaders() {
561 if ( !$this->respHeaders ) {
562 $this->parseHeader();
565 return $this->respHeaders;
569 * Returns the value of the given response header.
571 * @param $header String
572 * @return String
574 public function getResponseHeader( $header ) {
575 if ( !$this->respHeaders ) {
576 $this->parseHeader();
579 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
580 $v = $this->respHeaders[strtolower( $header )];
581 return $v[count( $v ) - 1];
584 return null;
588 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
590 * @param $jar CookieJar
592 public function setCookieJar( $jar ) {
593 $this->cookieJar = $jar;
597 * Returns the cookie jar in use.
599 * @return CookieJar
601 public function getCookieJar() {
602 if ( !$this->respHeaders ) {
603 $this->parseHeader();
606 return $this->cookieJar;
610 * Sets a cookie. Used before a request to set up any individual
611 * cookies. Used internally after a request to parse the
612 * Set-Cookie headers.
613 * @see Cookie::set
614 * @param $name
615 * @param $value null
616 * @param $attr null
618 public function setCookie( $name, $value = null, $attr = null ) {
619 if ( !$this->cookieJar ) {
620 $this->cookieJar = new CookieJar;
623 $this->cookieJar->setCookie( $name, $value, $attr );
627 * Parse the cookies in the response headers and store them in the cookie jar.
629 protected function parseCookies() {
630 wfProfileIn( __METHOD__ );
632 if ( !$this->cookieJar ) {
633 $this->cookieJar = new CookieJar;
636 if ( isset( $this->respHeaders['set-cookie'] ) ) {
637 $url = parse_url( $this->getFinalUrl() );
638 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
639 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
643 wfProfileOut( __METHOD__ );
647 * Returns the final URL after all redirections.
649 * Relative values of the "Location" header are incorrect as
650 * stated in RFC, however they do happen and modern browsers
651 * support them. This function loops backwards through all
652 * locations in order to build the proper absolute URI - Marooned
653 * at wikia-inc.com
655 * Note that the multiple Location: headers are an artifact of
656 * CURL -- they shouldn't actually get returned this way. Rewrite
657 * this when bug 29232 is taken care of (high-level redirect
658 * handling rewrite).
660 * @return string
662 public function getFinalUrl() {
663 $headers = $this->getResponseHeaders();
665 //return full url (fix for incorrect but handled relative location)
666 if ( isset( $headers['location'] ) ) {
667 $locations = $headers['location'];
668 $domain = '';
669 $foundRelativeURI = false;
670 $countLocations = count( $locations );
672 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
673 $url = parse_url( $locations[$i] );
675 if ( isset( $url['host'] ) ) {
676 $domain = $url['scheme'] . '://' . $url['host'];
677 break; //found correct URI (with host)
678 } else {
679 $foundRelativeURI = true;
683 if ( $foundRelativeURI ) {
684 if ( $domain ) {
685 return $domain . $locations[$countLocations - 1];
686 } else {
687 $url = parse_url( $this->url );
688 if ( isset( $url['host'] ) ) {
689 return $url['scheme'] . '://' . $url['host'] .
690 $locations[$countLocations - 1];
693 } else {
694 return $locations[$countLocations - 1];
698 return $this->url;
702 * Returns true if the backend can follow redirects. Overridden by the
703 * child classes.
704 * @return bool
706 public function canFollowRedirects() {
707 return true;
712 * MWHttpRequest implemented using internal curl compiled into PHP
714 class CurlHttpRequest extends MWHttpRequest {
715 const SUPPORTS_FILE_POSTS = true;
717 protected $curlOptions = array();
718 protected $headerText = "";
721 * @param $fh
722 * @param $content
723 * @return int
725 protected function readHeader( $fh, $content ) {
726 $this->headerText .= $content;
727 return strlen( $content );
730 public function execute() {
731 wfProfileIn( __METHOD__ );
733 parent::execute();
735 if ( !$this->status->isOK() ) {
736 wfProfileOut( __METHOD__ );
737 return $this->status;
740 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
741 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
743 // Only supported in curl >= 7.16.2
744 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
745 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
748 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
749 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
750 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
751 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
752 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
754 /* not sure these two are actually necessary */
755 if ( isset( $this->reqHeaders['Referer'] ) ) {
756 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
758 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
760 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
761 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
763 if ( $this->caInfo ) {
764 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
767 if ( $this->headersOnly ) {
768 $this->curlOptions[CURLOPT_NOBODY] = true;
769 $this->curlOptions[CURLOPT_HEADER] = true;
770 } elseif ( $this->method == 'POST' ) {
771 $this->curlOptions[CURLOPT_POST] = true;
772 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
773 // Suppress 'Expect: 100-continue' header, as some servers
774 // will reject it with a 417 and Curl won't auto retry
775 // with HTTP 1.0 fallback
776 $this->reqHeaders['Expect'] = '';
777 } else {
778 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
781 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
783 $curlHandle = curl_init( $this->url );
785 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
786 wfProfileOut( __METHOD__ );
787 throw new MWException( "Error setting curl options." );
790 if ( $this->followRedirects && $this->canFollowRedirects() ) {
791 wfSuppressWarnings();
792 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
793 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
794 "Probably safe_mode or open_basedir is set.\n" );
795 // Continue the processing. If it were in curl_setopt_array,
796 // processing would have halted on its entry
798 wfRestoreWarnings();
801 $curlRes = curl_exec( $curlHandle );
802 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
803 $this->status->fatal( 'http-timed-out', $this->url );
804 } elseif ( $curlRes === false ) {
805 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
806 } else {
807 $this->headerList = explode( "\r\n", $this->headerText );
810 curl_close( $curlHandle );
812 $this->parseHeader();
813 $this->setStatus();
815 wfProfileOut( __METHOD__ );
817 return $this->status;
821 * @return bool
823 public function canFollowRedirects() {
824 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
825 wfDebug( "Cannot follow redirects in safe mode\n" );
826 return false;
829 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
830 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
831 return false;
834 return true;
838 class PhpHttpRequest extends MWHttpRequest {
841 * @param $url string
842 * @return string
844 protected function urlToTcp( $url ) {
845 $parsedUrl = parse_url( $url );
847 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
850 public function execute() {
851 wfProfileIn( __METHOD__ );
853 parent::execute();
855 if ( is_array( $this->postData ) ) {
856 $this->postData = wfArrayToCgi( $this->postData );
859 if ( $this->parsedUrl['scheme'] != 'http'
860 && $this->parsedUrl['scheme'] != 'https' ) {
861 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
864 $this->reqHeaders['Accept'] = "*/*";
865 $this->reqHeaders['Connection'] = 'Close';
866 if ( $this->method == 'POST' ) {
867 // Required for HTTP 1.0 POSTs
868 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
869 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
870 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
874 // Set up PHP stream context
875 $options = array(
876 'http' => array(
877 'method' => $this->method,
878 'header' => implode( "\r\n", $this->getHeaderList() ),
879 'protocol_version' => '1.1',
880 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
881 'ignore_errors' => true,
882 'timeout' => $this->timeout,
883 // Curl options in case curlwrappers are installed
884 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
885 'curl_verify_ssl_peer' => $this->sslVerifyCert,
887 'ssl' => array(
888 'verify_peer' => $this->sslVerifyCert,
889 'SNI_enabled' => true,
893 if ( $this->proxy ) {
894 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
895 $options['http']['request_fulluri'] = true;
898 if ( $this->postData ) {
899 $options['http']['content'] = $this->postData;
902 if ( $this->sslVerifyHost ) {
903 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
906 if ( is_dir( $this->caInfo ) ) {
907 $options['ssl']['capath'] = $this->caInfo;
908 } elseif ( is_file( $this->caInfo ) ) {
909 $options['ssl']['cafile'] = $this->caInfo;
910 } elseif ( $this->caInfo ) {
911 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
914 $context = stream_context_create( $options );
916 $this->headerList = array();
917 $reqCount = 0;
918 $url = $this->url;
920 $result = array();
922 do {
923 $reqCount++;
924 wfSuppressWarnings();
925 $fh = fopen( $url, "r", false, $context );
926 wfRestoreWarnings();
928 if ( !$fh ) {
929 break;
932 $result = stream_get_meta_data( $fh );
933 $this->headerList = $result['wrapper_data'];
934 $this->parseHeader();
936 if ( !$this->followRedirects ) {
937 break;
940 # Handle manual redirection
941 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
942 break;
944 # Check security of URL
945 $url = $this->getResponseHeader( "Location" );
947 if ( !Http::isValidURI( $url ) ) {
948 wfDebug( __METHOD__ . ": insecure redirection\n" );
949 break;
951 } while ( true );
953 $this->setStatus();
955 if ( $fh === false ) {
956 $this->status->fatal( 'http-request-error' );
957 wfProfileOut( __METHOD__ );
958 return $this->status;
961 if ( $result['timed_out'] ) {
962 $this->status->fatal( 'http-timed-out', $this->url );
963 wfProfileOut( __METHOD__ );
964 return $this->status;
967 // If everything went OK, or we received some error code
968 // get the response body content.
969 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
970 while ( !feof( $fh ) ) {
971 $buf = fread( $fh, 8192 );
973 if ( $buf === false ) {
974 $this->status->fatal( 'http-read-error' );
975 break;
978 if ( strlen( $buf ) ) {
979 call_user_func( $this->callback, $fh, $buf );
983 fclose( $fh );
985 wfProfileOut( __METHOD__ );
987 return $this->status;