Remove $timeout parameter from Http::get()
[mediawiki.git] / includes / HttpFunctions.php
blob7f0d6a216051437e07eb01541b2e17513035c9fd
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()
85 * @since 1.25 Second parameter $timeout removed. Second parameter
86 * is now $options which can be given a 'timeout'
88 * @param string $url
89 * @param array $options
90 * @return string
92 public static function get( $url, $options = array() ) {
93 $args = func_get_args();
94 if ( is_string( $args[1] ) || is_numeric( $args[1] ) ) {
95 // Second was used to be the timeout
96 // And third parameter used to be $options
97 wfWarn( "Second parameter should not be a timeout." );
98 $options = isset( $args[2] ) ? $args[2] : array();
99 $options['timeout'] = $args[1];
101 return Http::request( 'GET', $url, $options );
105 * Simple wrapper for Http::request( 'POST' )
106 * @see Http::request()
108 * @param string $url
109 * @param array $options
110 * @return string
112 public static function post( $url, $options = array() ) {
113 return Http::request( 'POST', $url, $options );
117 * Check if the URL can be served by localhost
119 * @param string $url Full url to check
120 * @return bool
122 public static function isLocalURL( $url ) {
123 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
125 if ( $wgCommandLineMode ) {
126 return false;
129 // Extract host part
130 $matches = array();
131 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
132 $host = $matches[1];
133 // Split up dotwise
134 $domainParts = explode( '.', $host );
135 // Check if this domain or any superdomain is listed as a local virtual host
136 $domainParts = array_reverse( $domainParts );
138 $domain = '';
139 $countParts = count( $domainParts );
140 for ( $i = 0; $i < $countParts; $i++ ) {
141 $domainPart = $domainParts[$i];
142 if ( $i == 0 ) {
143 $domain = $domainPart;
144 } else {
145 $domain = $domainPart . '.' . $domain;
148 if ( in_array( $domain, $wgLocalVirtualHosts )
149 || $wgConf->isLocalVHost( $domain )
151 return true;
156 return false;
160 * A standard user-agent we can use for external requests.
161 * @return string
163 public static function userAgent() {
164 global $wgVersion;
165 return "MediaWiki/$wgVersion";
169 * Checks that the given URI is a valid one. Hardcoding the
170 * protocols, because we only want protocols that both cURL
171 * and php support.
173 * file:// should not be allowed here for security purpose (r67684)
175 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
177 * @param string $uri URI to check for validity
178 * @return bool
180 public static function isValidURI( $uri ) {
181 return preg_match(
182 '/^https?:\/\/[^\/\s]\S*$/D',
183 $uri
189 * This wrapper class will call out to curl (if available) or fallback
190 * to regular PHP if necessary for handling internal HTTP requests.
192 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
193 * PHP's HTTP extension.
195 class MWHttpRequest {
196 const SUPPORTS_FILE_POSTS = false;
198 protected $content;
199 protected $timeout = 'default';
200 protected $headersOnly = null;
201 protected $postData = null;
202 protected $proxy = null;
203 protected $noProxy = false;
204 protected $sslVerifyHost = true;
205 protected $sslVerifyCert = true;
206 protected $caInfo = null;
207 protected $method = "GET";
208 protected $reqHeaders = array();
209 protected $url;
210 protected $parsedUrl;
211 protected $callback;
212 protected $maxRedirects = 5;
213 protected $followRedirects = false;
216 * @var CookieJar
218 protected $cookieJar;
220 protected $headerList = array();
221 protected $respVersion = "0.9";
222 protected $respStatus = "200 Ok";
223 protected $respHeaders = array();
225 public $status;
228 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
229 * @param array $options (optional) extra params to pass (see Http::request())
231 protected function __construct( $url, $options = array() ) {
232 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
234 $this->url = wfExpandUrl( $url, PROTO_HTTP );
235 $this->parsedUrl = wfParseUrl( $this->url );
237 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
238 $this->status = Status::newFatal( 'http-invalid-url' );
239 } else {
240 $this->status = Status::newGood( 100 ); // continue
243 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
244 $this->timeout = $options['timeout'];
245 } else {
246 $this->timeout = $wgHTTPTimeout;
248 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
249 $this->connectTimeout = $options['connectTimeout'];
250 } else {
251 $this->connectTimeout = $wgHTTPConnectTimeout;
253 if ( isset( $options['userAgent'] ) ) {
254 $this->setUserAgent( $options['userAgent'] );
257 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
258 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
260 foreach ( $members as $o ) {
261 if ( isset( $options[$o] ) ) {
262 // ensure that MWHttpRequest::method is always
263 // uppercased. Bug 36137
264 if ( $o == 'method' ) {
265 $options[$o] = strtoupper( $options[$o] );
267 $this->$o = $options[$o];
271 if ( $this->noProxy ) {
272 $this->proxy = ''; // noProxy takes precedence
277 * Simple function to test if we can make any sort of requests at all, using
278 * cURL or fopen()
279 * @return bool
281 public static function canMakeRequests() {
282 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
286 * Generate a new request object
287 * @param string $url Url to use
288 * @param array $options (optional) extra params to pass (see Http::request())
289 * @throws MWException
290 * @return CurlHttpRequest|PhpHttpRequest
291 * @see MWHttpRequest::__construct
293 public static function factory( $url, $options = null ) {
294 if ( !Http::$httpEngine ) {
295 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
296 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
297 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
298 ' Http::$httpEngine is set to "curl"' );
301 switch ( Http::$httpEngine ) {
302 case 'curl':
303 return new CurlHttpRequest( $url, $options );
304 case 'php':
305 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
306 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
307 'needs to be enabled for pure PHP http requests to ' .
308 'work. If possible, curl should be used instead. See ' .
309 'http://php.net/curl.'
312 return new PhpHttpRequest( $url, $options );
313 default:
314 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
319 * Get the body, or content, of the response to the request
321 * @return string
323 public function getContent() {
324 return $this->content;
328 * Set the parameters of the request
330 * @param array $args
331 * @todo overload the args param
333 public function setData( $args ) {
334 $this->postData = $args;
338 * Take care of setting up the proxy (do nothing if "noProxy" is set)
340 * @return void
342 public function proxySetup() {
343 global $wgHTTPProxy;
345 // If there is an explicit proxy set and proxies are not disabled, then use it
346 if ( $this->proxy && !$this->noProxy ) {
347 return;
350 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
351 // local URL and proxies are not disabled
352 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
353 $this->proxy = '';
354 } elseif ( $wgHTTPProxy ) {
355 $this->proxy = $wgHTTPProxy;
356 } elseif ( getenv( "http_proxy" ) ) {
357 $this->proxy = getenv( "http_proxy" );
362 * Set the user agent
363 * @param string $UA
365 public function setUserAgent( $UA ) {
366 $this->setHeader( 'User-Agent', $UA );
370 * Set an arbitrary header
371 * @param string $name
372 * @param string $value
374 public function setHeader( $name, $value ) {
375 // I feel like I should normalize the case here...
376 $this->reqHeaders[$name] = $value;
380 * Get an array of the headers
381 * @return array
383 public function getHeaderList() {
384 $list = array();
386 if ( $this->cookieJar ) {
387 $this->reqHeaders['Cookie'] =
388 $this->cookieJar->serializeToHttpRequest(
389 $this->parsedUrl['path'],
390 $this->parsedUrl['host']
394 foreach ( $this->reqHeaders as $name => $value ) {
395 $list[] = "$name: $value";
398 return $list;
402 * Set a read callback to accept data read from the HTTP request.
403 * By default, data is appended to an internal buffer which can be
404 * retrieved through $req->getContent().
406 * To handle data as it comes in -- especially for large files that
407 * would not fit in memory -- you can instead set your own callback,
408 * in the form function($resource, $buffer) where the first parameter
409 * is the low-level resource being read (implementation specific),
410 * and the second parameter is the data buffer.
412 * You MUST return the number of bytes handled in the buffer; if fewer
413 * bytes are reported handled than were passed to you, the HTTP fetch
414 * will be aborted.
416 * @param callable $callback
417 * @throws MWException
419 public function setCallback( $callback ) {
420 if ( !is_callable( $callback ) ) {
421 throw new MWException( 'Invalid MwHttpRequest callback' );
423 $this->callback = $callback;
427 * A generic callback to read the body of the response from a remote
428 * server.
430 * @param resource $fh
431 * @param string $content
432 * @return int
434 public function read( $fh, $content ) {
435 $this->content .= $content;
436 return strlen( $content );
440 * Take care of whatever is necessary to perform the URI request.
442 * @return Status
444 public function execute() {
446 $this->content = "";
448 if ( strtoupper( $this->method ) == "HEAD" ) {
449 $this->headersOnly = true;
452 $this->proxySetup(); // set up any proxy as needed
454 if ( !$this->callback ) {
455 $this->setCallback( array( $this, 'read' ) );
458 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
459 $this->setUserAgent( Http::userAgent() );
465 * Parses the headers, including the HTTP status code and any
466 * Set-Cookie headers. This function expects the headers to be
467 * found in an array in the member variable headerList.
469 protected function parseHeader() {
471 $lastname = "";
473 foreach ( $this->headerList as $header ) {
474 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
475 $this->respVersion = $match[1];
476 $this->respStatus = $match[2];
477 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
478 $last = count( $this->respHeaders[$lastname] ) - 1;
479 $this->respHeaders[$lastname][$last] .= "\r\n$header";
480 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
481 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
482 $lastname = strtolower( $match[1] );
486 $this->parseCookies();
491 * Sets HTTPRequest status member to a fatal value with the error
492 * message if the returned integer value of the status code was
493 * not successful (< 300) or a redirect (>=300 and < 400). (see
494 * RFC2616, section 10,
495 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
496 * list of status codes.)
498 protected function setStatus() {
499 if ( !$this->respHeaders ) {
500 $this->parseHeader();
503 if ( (int)$this->respStatus > 399 ) {
504 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
505 $this->status->fatal( "http-bad-status", $code, $message );
510 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
511 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
512 * for a list of status codes.)
514 * @return int
516 public function getStatus() {
517 if ( !$this->respHeaders ) {
518 $this->parseHeader();
521 return (int)$this->respStatus;
525 * Returns true if the last status code was a redirect.
527 * @return bool
529 public function isRedirect() {
530 if ( !$this->respHeaders ) {
531 $this->parseHeader();
534 $status = (int)$this->respStatus;
536 if ( $status >= 300 && $status <= 303 ) {
537 return true;
540 return false;
544 * Returns an associative array of response headers after the
545 * request has been executed. Because some headers
546 * (e.g. Set-Cookie) can appear more than once the, each value of
547 * the associative array is an array of the values given.
549 * @return array
551 public function getResponseHeaders() {
552 if ( !$this->respHeaders ) {
553 $this->parseHeader();
556 return $this->respHeaders;
560 * Returns the value of the given response header.
562 * @param string $header
563 * @return string
565 public function getResponseHeader( $header ) {
566 if ( !$this->respHeaders ) {
567 $this->parseHeader();
570 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
571 $v = $this->respHeaders[strtolower( $header )];
572 return $v[count( $v ) - 1];
575 return null;
579 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
581 * @param CookieJar $jar
583 public function setCookieJar( $jar ) {
584 $this->cookieJar = $jar;
588 * Returns the cookie jar in use.
590 * @return CookieJar
592 public function getCookieJar() {
593 if ( !$this->respHeaders ) {
594 $this->parseHeader();
597 return $this->cookieJar;
601 * Sets a cookie. Used before a request to set up any individual
602 * cookies. Used internally after a request to parse the
603 * Set-Cookie headers.
604 * @see Cookie::set
605 * @param string $name
606 * @param mixed $value
607 * @param array $attr
609 public function setCookie( $name, $value = null, $attr = null ) {
610 if ( !$this->cookieJar ) {
611 $this->cookieJar = new CookieJar;
614 $this->cookieJar->setCookie( $name, $value, $attr );
618 * Parse the cookies in the response headers and store them in the cookie jar.
620 protected function parseCookies() {
622 if ( !$this->cookieJar ) {
623 $this->cookieJar = new CookieJar;
626 if ( isset( $this->respHeaders['set-cookie'] ) ) {
627 $url = parse_url( $this->getFinalUrl() );
628 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
629 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
636 * Returns the final URL after all redirections.
638 * Relative values of the "Location" header are incorrect as
639 * stated in RFC, however they do happen and modern browsers
640 * support them. This function loops backwards through all
641 * locations in order to build the proper absolute URI - Marooned
642 * at wikia-inc.com
644 * Note that the multiple Location: headers are an artifact of
645 * CURL -- they shouldn't actually get returned this way. Rewrite
646 * this when bug 29232 is taken care of (high-level redirect
647 * handling rewrite).
649 * @return string
651 public function getFinalUrl() {
652 $headers = $this->getResponseHeaders();
654 //return full url (fix for incorrect but handled relative location)
655 if ( isset( $headers['location'] ) ) {
656 $locations = $headers['location'];
657 $domain = '';
658 $foundRelativeURI = false;
659 $countLocations = count( $locations );
661 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
662 $url = parse_url( $locations[$i] );
664 if ( isset( $url['host'] ) ) {
665 $domain = $url['scheme'] . '://' . $url['host'];
666 break; //found correct URI (with host)
667 } else {
668 $foundRelativeURI = true;
672 if ( $foundRelativeURI ) {
673 if ( $domain ) {
674 return $domain . $locations[$countLocations - 1];
675 } else {
676 $url = parse_url( $this->url );
677 if ( isset( $url['host'] ) ) {
678 return $url['scheme'] . '://' . $url['host'] .
679 $locations[$countLocations - 1];
682 } else {
683 return $locations[$countLocations - 1];
687 return $this->url;
691 * Returns true if the backend can follow redirects. Overridden by the
692 * child classes.
693 * @return bool
695 public function canFollowRedirects() {
696 return true;
701 * MWHttpRequest implemented using internal curl compiled into PHP
703 class CurlHttpRequest extends MWHttpRequest {
704 const SUPPORTS_FILE_POSTS = true;
706 protected $curlOptions = array();
707 protected $headerText = "";
710 * @param resource $fh
711 * @param string $content
712 * @return int
714 protected function readHeader( $fh, $content ) {
715 $this->headerText .= $content;
716 return strlen( $content );
719 public function execute() {
721 parent::execute();
723 if ( !$this->status->isOK() ) {
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 throw new MWException( "Error setting curl options." );
772 if ( $this->followRedirects && $this->canFollowRedirects() ) {
773 wfSuppressWarnings();
774 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
775 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
776 "Probably safe_mode or open_basedir is set.\n" );
777 // Continue the processing. If it were in curl_setopt_array,
778 // processing would have halted on its entry
780 wfRestoreWarnings();
783 $curlRes = curl_exec( $curlHandle );
784 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
785 $this->status->fatal( 'http-timed-out', $this->url );
786 } elseif ( $curlRes === false ) {
787 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
788 } else {
789 $this->headerList = explode( "\r\n", $this->headerText );
792 curl_close( $curlHandle );
794 $this->parseHeader();
795 $this->setStatus();
797 return $this->status;
801 * @return bool
803 public function canFollowRedirects() {
804 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
805 wfDebug( "Cannot follow redirects in safe mode\n" );
806 return false;
809 $curlVersionInfo = curl_version();
810 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
811 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
812 return false;
815 return true;
819 class PhpHttpRequest extends MWHttpRequest {
822 * @param string $url
823 * @return string
825 protected function urlToTcp( $url ) {
826 $parsedUrl = parse_url( $url );
828 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
831 public function execute() {
833 parent::execute();
835 if ( is_array( $this->postData ) ) {
836 $this->postData = wfArrayToCgi( $this->postData );
839 if ( $this->parsedUrl['scheme'] != 'http'
840 && $this->parsedUrl['scheme'] != 'https' ) {
841 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
844 $this->reqHeaders['Accept'] = "*/*";
845 $this->reqHeaders['Connection'] = 'Close';
846 if ( $this->method == 'POST' ) {
847 // Required for HTTP 1.0 POSTs
848 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
849 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
850 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
854 // Set up PHP stream context
855 $options = array(
856 'http' => array(
857 'method' => $this->method,
858 'header' => implode( "\r\n", $this->getHeaderList() ),
859 'protocol_version' => '1.1',
860 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
861 'ignore_errors' => true,
862 'timeout' => $this->timeout,
863 // Curl options in case curlwrappers are installed
864 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
865 'curl_verify_ssl_peer' => $this->sslVerifyCert,
867 'ssl' => array(
868 'verify_peer' => $this->sslVerifyCert,
869 'SNI_enabled' => true,
873 if ( $this->proxy ) {
874 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
875 $options['http']['request_fulluri'] = true;
878 if ( $this->postData ) {
879 $options['http']['content'] = $this->postData;
882 if ( $this->sslVerifyHost ) {
883 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
886 if ( is_dir( $this->caInfo ) ) {
887 $options['ssl']['capath'] = $this->caInfo;
888 } elseif ( is_file( $this->caInfo ) ) {
889 $options['ssl']['cafile'] = $this->caInfo;
890 } elseif ( $this->caInfo ) {
891 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
894 $context = stream_context_create( $options );
896 $this->headerList = array();
897 $reqCount = 0;
898 $url = $this->url;
900 $result = array();
902 do {
903 $reqCount++;
904 wfSuppressWarnings();
905 $fh = fopen( $url, "r", false, $context );
906 wfRestoreWarnings();
908 if ( !$fh ) {
909 break;
912 $result = stream_get_meta_data( $fh );
913 $this->headerList = $result['wrapper_data'];
914 $this->parseHeader();
916 if ( !$this->followRedirects ) {
917 break;
920 # Handle manual redirection
921 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
922 break;
924 # Check security of URL
925 $url = $this->getResponseHeader( "Location" );
927 if ( !Http::isValidURI( $url ) ) {
928 wfDebug( __METHOD__ . ": insecure redirection\n" );
929 break;
931 } while ( true );
933 $this->setStatus();
935 if ( $fh === false ) {
936 $this->status->fatal( 'http-request-error' );
937 return $this->status;
940 if ( $result['timed_out'] ) {
941 $this->status->fatal( 'http-timed-out', $this->url );
942 return $this->status;
945 // If everything went OK, or we received some error code
946 // get the response body content.
947 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
948 while ( !feof( $fh ) ) {
949 $buf = fread( $fh, 8192 );
951 if ( $buf === false ) {
952 $this->status->fatal( 'http-read-error' );
953 break;
956 if ( strlen( $buf ) ) {
957 call_user_func( $this->callback, $fh, $buf );
961 fclose( $fh );
963 return $this->status;