Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / HttpFunctions.php
blobc9dd0c067fe159de33db6054d403bc81a24d33f5
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" );
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 string $url
89 * @param string $timeout
90 * @param array $options
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 string $url
103 * @param array $options
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 bool
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 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() {
437 wfProfileIn( __METHOD__ );
439 $this->content = "";
441 if ( strtoupper( $this->method ) == "HEAD" ) {
442 $this->headersOnly = true;
445 $this->proxySetup(); // set up any proxy as needed
447 if ( !$this->callback ) {
448 $this->setCallback( array( $this, 'read' ) );
451 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
452 $this->setUserAgent( Http::userAgent() );
455 wfProfileOut( __METHOD__ );
459 * Parses the headers, including the HTTP status code and any
460 * Set-Cookie headers. This function expects the headers to be
461 * found in an array in the member variable headerList.
463 protected function parseHeader() {
464 wfProfileIn( __METHOD__ );
466 $lastname = "";
468 foreach ( $this->headerList as $header ) {
469 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
470 $this->respVersion = $match[1];
471 $this->respStatus = $match[2];
472 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
473 $last = count( $this->respHeaders[$lastname] ) - 1;
474 $this->respHeaders[$lastname][$last] .= "\r\n$header";
475 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
476 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
477 $lastname = strtolower( $match[1] );
481 $this->parseCookies();
483 wfProfileOut( __METHOD__ );
487 * Sets HTTPRequest status member to a fatal value with the error
488 * message if the returned integer value of the status code was
489 * not successful (< 300) or a redirect (>=300 and < 400). (see
490 * RFC2616, section 10,
491 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
492 * list of status codes.)
494 protected function setStatus() {
495 if ( !$this->respHeaders ) {
496 $this->parseHeader();
499 if ( (int)$this->respStatus > 399 ) {
500 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
501 $this->status->fatal( "http-bad-status", $code, $message );
506 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
507 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
508 * for a list of status codes.)
510 * @return int
512 public function getStatus() {
513 if ( !$this->respHeaders ) {
514 $this->parseHeader();
517 return (int)$this->respStatus;
521 * Returns true if the last status code was a redirect.
523 * @return bool
525 public function isRedirect() {
526 if ( !$this->respHeaders ) {
527 $this->parseHeader();
530 $status = (int)$this->respStatus;
532 if ( $status >= 300 && $status <= 303 ) {
533 return true;
536 return false;
540 * Returns an associative array of response headers after the
541 * request has been executed. Because some headers
542 * (e.g. Set-Cookie) can appear more than once the, each value of
543 * the associative array is an array of the values given.
545 * @return array
547 public function getResponseHeaders() {
548 if ( !$this->respHeaders ) {
549 $this->parseHeader();
552 return $this->respHeaders;
556 * Returns the value of the given response header.
558 * @param string $header
559 * @return string
561 public function getResponseHeader( $header ) {
562 if ( !$this->respHeaders ) {
563 $this->parseHeader();
566 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
567 $v = $this->respHeaders[strtolower( $header )];
568 return $v[count( $v ) - 1];
571 return null;
575 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
577 * @param CookieJar $jar
579 public function setCookieJar( $jar ) {
580 $this->cookieJar = $jar;
584 * Returns the cookie jar in use.
586 * @return CookieJar
588 public function getCookieJar() {
589 if ( !$this->respHeaders ) {
590 $this->parseHeader();
593 return $this->cookieJar;
597 * Sets a cookie. Used before a request to set up any individual
598 * cookies. Used internally after a request to parse the
599 * Set-Cookie headers.
600 * @see Cookie::set
601 * @param string $name
602 * @param mixed $value
603 * @param array $attr
605 public function setCookie( $name, $value = null, $attr = null ) {
606 if ( !$this->cookieJar ) {
607 $this->cookieJar = new CookieJar;
610 $this->cookieJar->setCookie( $name, $value, $attr );
614 * Parse the cookies in the response headers and store them in the cookie jar.
616 protected function parseCookies() {
617 wfProfileIn( __METHOD__ );
619 if ( !$this->cookieJar ) {
620 $this->cookieJar = new CookieJar;
623 if ( isset( $this->respHeaders['set-cookie'] ) ) {
624 $url = parse_url( $this->getFinalUrl() );
625 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
626 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
630 wfProfileOut( __METHOD__ );
634 * Returns the final URL after all redirections.
636 * Relative values of the "Location" header are incorrect as
637 * stated in RFC, however they do happen and modern browsers
638 * support them. This function loops backwards through all
639 * locations in order to build the proper absolute URI - Marooned
640 * at wikia-inc.com
642 * Note that the multiple Location: headers are an artifact of
643 * CURL -- they shouldn't actually get returned this way. Rewrite
644 * this when bug 29232 is taken care of (high-level redirect
645 * handling rewrite).
647 * @return string
649 public function getFinalUrl() {
650 $headers = $this->getResponseHeaders();
652 //return full url (fix for incorrect but handled relative location)
653 if ( isset( $headers['location'] ) ) {
654 $locations = $headers['location'];
655 $domain = '';
656 $foundRelativeURI = false;
657 $countLocations = count( $locations );
659 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
660 $url = parse_url( $locations[$i] );
662 if ( isset( $url['host'] ) ) {
663 $domain = $url['scheme'] . '://' . $url['host'];
664 break; //found correct URI (with host)
665 } else {
666 $foundRelativeURI = true;
670 if ( $foundRelativeURI ) {
671 if ( $domain ) {
672 return $domain . $locations[$countLocations - 1];
673 } else {
674 $url = parse_url( $this->url );
675 if ( isset( $url['host'] ) ) {
676 return $url['scheme'] . '://' . $url['host'] .
677 $locations[$countLocations - 1];
680 } else {
681 return $locations[$countLocations - 1];
685 return $this->url;
689 * Returns true if the backend can follow redirects. Overridden by the
690 * child classes.
691 * @return bool
693 public function canFollowRedirects() {
694 return true;
699 * MWHttpRequest implemented using internal curl compiled into PHP
701 class CurlHttpRequest extends MWHttpRequest {
702 const SUPPORTS_FILE_POSTS = true;
704 protected $curlOptions = array();
705 protected $headerText = "";
708 * @param resource $fh
709 * @param string $content
710 * @return int
712 protected function readHeader( $fh, $content ) {
713 $this->headerText .= $content;
714 return strlen( $content );
717 public function execute() {
718 wfProfileIn( __METHOD__ );
720 parent::execute();
722 if ( !$this->status->isOK() ) {
723 wfProfileOut( __METHOD__ );
724 return $this->status;
727 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
728 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
730 // Only supported in curl >= 7.16.2
731 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
732 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
735 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
736 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
737 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
738 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
739 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
741 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
743 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
744 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
746 if ( $this->caInfo ) {
747 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
750 if ( $this->headersOnly ) {
751 $this->curlOptions[CURLOPT_NOBODY] = true;
752 $this->curlOptions[CURLOPT_HEADER] = true;
753 } elseif ( $this->method == 'POST' ) {
754 $this->curlOptions[CURLOPT_POST] = true;
755 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
756 // Suppress 'Expect: 100-continue' header, as some servers
757 // will reject it with a 417 and Curl won't auto retry
758 // with HTTP 1.0 fallback
759 $this->reqHeaders['Expect'] = '';
760 } else {
761 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
764 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
766 $curlHandle = curl_init( $this->url );
768 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
769 wfProfileOut( __METHOD__ );
770 throw new MWException( "Error setting curl options." );
773 if ( $this->followRedirects && $this->canFollowRedirects() ) {
774 wfSuppressWarnings();
775 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
776 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
777 "Probably safe_mode or open_basedir is set.\n" );
778 // Continue the processing. If it were in curl_setopt_array,
779 // processing would have halted on its entry
781 wfRestoreWarnings();
784 $curlRes = curl_exec( $curlHandle );
785 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
786 $this->status->fatal( 'http-timed-out', $this->url );
787 } elseif ( $curlRes === false ) {
788 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
789 } else {
790 $this->headerList = explode( "\r\n", $this->headerText );
793 curl_close( $curlHandle );
795 $this->parseHeader();
796 $this->setStatus();
798 wfProfileOut( __METHOD__ );
800 return $this->status;
804 * @return bool
806 public function canFollowRedirects() {
807 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
808 wfDebug( "Cannot follow redirects in safe mode\n" );
809 return false;
812 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
813 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
814 return false;
817 return true;
821 class PhpHttpRequest extends MWHttpRequest {
824 * @param string $url
825 * @return string
827 protected function urlToTcp( $url ) {
828 $parsedUrl = parse_url( $url );
830 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
833 public function execute() {
834 wfProfileIn( __METHOD__ );
836 parent::execute();
838 if ( is_array( $this->postData ) ) {
839 $this->postData = wfArrayToCgi( $this->postData );
842 if ( $this->parsedUrl['scheme'] != 'http'
843 && $this->parsedUrl['scheme'] != 'https' ) {
844 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
847 $this->reqHeaders['Accept'] = "*/*";
848 $this->reqHeaders['Connection'] = 'Close';
849 if ( $this->method == 'POST' ) {
850 // Required for HTTP 1.0 POSTs
851 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
852 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
853 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
857 // Set up PHP stream context
858 $options = array(
859 'http' => array(
860 'method' => $this->method,
861 'header' => implode( "\r\n", $this->getHeaderList() ),
862 'protocol_version' => '1.1',
863 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
864 'ignore_errors' => true,
865 'timeout' => $this->timeout,
866 // Curl options in case curlwrappers are installed
867 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
868 'curl_verify_ssl_peer' => $this->sslVerifyCert,
870 'ssl' => array(
871 'verify_peer' => $this->sslVerifyCert,
872 'SNI_enabled' => true,
876 if ( $this->proxy ) {
877 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
878 $options['http']['request_fulluri'] = true;
881 if ( $this->postData ) {
882 $options['http']['content'] = $this->postData;
885 if ( $this->sslVerifyHost ) {
886 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
889 if ( is_dir( $this->caInfo ) ) {
890 $options['ssl']['capath'] = $this->caInfo;
891 } elseif ( is_file( $this->caInfo ) ) {
892 $options['ssl']['cafile'] = $this->caInfo;
893 } elseif ( $this->caInfo ) {
894 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
897 $context = stream_context_create( $options );
899 $this->headerList = array();
900 $reqCount = 0;
901 $url = $this->url;
903 $result = array();
905 do {
906 $reqCount++;
907 wfSuppressWarnings();
908 $fh = fopen( $url, "r", false, $context );
909 wfRestoreWarnings();
911 if ( !$fh ) {
912 break;
915 $result = stream_get_meta_data( $fh );
916 $this->headerList = $result['wrapper_data'];
917 $this->parseHeader();
919 if ( !$this->followRedirects ) {
920 break;
923 # Handle manual redirection
924 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
925 break;
927 # Check security of URL
928 $url = $this->getResponseHeader( "Location" );
930 if ( !Http::isValidURI( $url ) ) {
931 wfDebug( __METHOD__ . ": insecure redirection\n" );
932 break;
934 } while ( true );
936 $this->setStatus();
938 if ( $fh === false ) {
939 $this->status->fatal( 'http-request-error' );
940 wfProfileOut( __METHOD__ );
941 return $this->status;
944 if ( $result['timed_out'] ) {
945 $this->status->fatal( 'http-timed-out', $this->url );
946 wfProfileOut( __METHOD__ );
947 return $this->status;
950 // If everything went OK, or we received some error code
951 // get the response body content.
952 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
953 while ( !feof( $fh ) ) {
954 $buf = fread( $fh, 8192 );
956 if ( $buf === false ) {
957 $this->status->fatal( 'http-read-error' );
958 break;
961 if ( strlen( $buf ) ) {
962 call_user_func( $this->callback, $fh, $buf );
966 fclose( $fh );
968 wfProfileOut( __METHOD__ );
970 return $this->status;