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
29 * Various HTTP related functions
33 static public $httpEngine = false;
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();
77 if ( $status->isOK() ) {
78 $content = $req->getContent();
80 wfProfileOut( __METHOD__
. "-$method" );
85 * Simple wrapper for Http::request( 'GET' )
86 * @see Http::request()
89 * @param $timeout string
90 * @param $options array
93 public static function get( $url, $timeout = 'default', $options = array() ) {
94 $options['timeout'] = $timeout;
95 return Http
::request( 'GET', $url, $options );
99 * Simple wrapper for Http::request( 'POST' )
100 * @see Http::request()
103 * @param $options array
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
116 public static function isLocalURL( $url ) {
117 global $wgCommandLineMode, $wgConf;
119 if ( $wgCommandLineMode ) {
125 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
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 );
133 $countParts = count( $domainParts );
134 for ( $i = 0; $i < $countParts; $i++
) {
135 $domainPart = $domainParts[$i];
137 $domain = $domainPart;
139 $domain = $domainPart . '.' . $domain;
142 if ( $wgConf->isLocalVHost( $domain ) ) {
152 * A standard user-agent we can use for external requests.
155 public static function userAgent() {
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
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
172 public static function isValidURI( $uri ) {
174 '/^https?:\/\/[^\/\s]\S*$/D',
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;
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();
202 protected $parsedUrl;
204 protected $maxRedirects = 5;
205 protected $followRedirects = false;
210 protected $cookieJar;
212 protected $headerList = array();
213 protected $respVersion = "0.9";
214 protected $respStatus = "200 Ok";
215 protected $respHeaders = array();
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' );
232 $this->status
= Status
::newGood( 100 ); // continue
235 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
236 $this->timeout
= $options['timeout'];
238 $this->timeout
= $wgHTTPTimeout;
240 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
241 $this->connectTimeout
= $options['connectTimeout'];
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
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 ) {
295 return new CurlHttpRequest( $url, $options );
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.' );
303 return new PhpHttpRequest( $url, $options );
305 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
310 * Get the body, or content, of the response to the request
314 public function getContent() {
315 return $this->content
;
319 * Set the parameters of the request
322 * @todo overload the args param
324 public function setData( $args ) {
325 $this->postData
= $args;
329 * Take care of setting up the proxy (do nothing if "noProxy" is set)
333 public function proxySetup() {
336 // If there is an explicit proxy set and proxies are not disabled, then use it
337 if ( $this->proxy
&& !$this->noProxy
) {
341 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
342 // local URL and proxies are not disabled
343 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
345 } elseif ( $wgHTTPProxy ) {
346 $this->proxy
= $wgHTTPProxy;
347 } elseif ( getenv( "http_proxy" ) ) {
348 $this->proxy
= getenv( "http_proxy" );
353 * Set the referrer header
355 public function setReferer( $url ) {
356 $this->setHeader( 'Referer', $url );
363 public function setUserAgent( $UA ) {
364 $this->setHeader( 'User-Agent', $UA );
368 * Set an arbitrary header
372 public function setHeader( $name, $value ) {
373 // I feel like I should normalize the case here...
374 $this->reqHeaders
[$name] = $value;
378 * Get an array of the headers
381 public function getHeaderList() {
384 if ( $this->cookieJar
) {
385 $this->reqHeaders
['Cookie'] =
386 $this->cookieJar
->serializeToHttpRequest(
387 $this->parsedUrl
['path'],
388 $this->parsedUrl
['host']
392 foreach ( $this->reqHeaders
as $name => $value ) {
393 $list[] = "$name: $value";
400 * Set a read callback to accept data read from the HTTP request.
401 * By default, data is appended to an internal buffer which can be
402 * retrieved through $req->getContent().
404 * To handle data as it comes in -- especially for large files that
405 * would not fit in memory -- you can instead set your own callback,
406 * in the form function($resource, $buffer) where the first parameter
407 * is the low-level resource being read (implementation specific),
408 * and the second parameter is the data buffer.
410 * You MUST return the number of bytes handled in the buffer; if fewer
411 * bytes are reported handled than were passed to you, the HTTP fetch
414 * @param $callback Callback
415 * @throws MWException
417 public function setCallback( $callback ) {
418 if ( !is_callable( $callback ) ) {
419 throw new MWException( 'Invalid MwHttpRequest callback' );
421 $this->callback
= $callback;
425 * A generic callback to read the body of the response from a remote
429 * @param $content String
432 public function read( $fh, $content ) {
433 $this->content
.= $content;
434 return strlen( $content );
438 * Take care of whatever is necessary to perform the URI request.
442 public function execute() {
445 wfProfileIn( __METHOD__
);
449 if ( strtoupper( $this->method
) == "HEAD" ) {
450 $this->headersOnly
= true;
453 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
454 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
457 $this->proxySetup(); // set up any proxy as needed
459 if ( !$this->callback
) {
460 $this->setCallback( array( $this, 'read' ) );
463 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
464 $this->setUserAgent( Http
::userAgent() );
467 wfProfileOut( __METHOD__
);
471 * Parses the headers, including the HTTP status code and any
472 * Set-Cookie headers. This function expects the headers to be
473 * found in an array in the member variable headerList.
475 protected function parseHeader() {
476 wfProfileIn( __METHOD__
);
480 foreach ( $this->headerList
as $header ) {
481 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
482 $this->respVersion
= $match[1];
483 $this->respStatus
= $match[2];
484 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
485 $last = count( $this->respHeaders
[$lastname] ) - 1;
486 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
487 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
488 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
489 $lastname = strtolower( $match[1] );
493 $this->parseCookies();
495 wfProfileOut( __METHOD__
);
499 * Sets HTTPRequest status member to a fatal value with the error
500 * message if the returned integer value of the status code was
501 * not successful (< 300) or a redirect (>=300 and < 400). (see
502 * RFC2616, section 10,
503 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
504 * list of status codes.)
506 protected function setStatus() {
507 if ( !$this->respHeaders
) {
508 $this->parseHeader();
511 if ( (int)$this->respStatus
> 399 ) {
512 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
513 $this->status
->fatal( "http-bad-status", $code, $message );
518 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
519 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
520 * for a list of status codes.)
524 public function getStatus() {
525 if ( !$this->respHeaders
) {
526 $this->parseHeader();
529 return (int)$this->respStatus
;
533 * Returns true if the last status code was a redirect.
537 public function isRedirect() {
538 if ( !$this->respHeaders
) {
539 $this->parseHeader();
542 $status = (int)$this->respStatus
;
544 if ( $status >= 300 && $status <= 303 ) {
552 * Returns an associative array of response headers after the
553 * request has been executed. Because some headers
554 * (e.g. Set-Cookie) can appear more than once the, each value of
555 * the associative array is an array of the values given.
559 public function getResponseHeaders() {
560 if ( !$this->respHeaders
) {
561 $this->parseHeader();
564 return $this->respHeaders
;
568 * Returns the value of the given response header.
570 * @param $header String
573 public function getResponseHeader( $header ) {
574 if ( !$this->respHeaders
) {
575 $this->parseHeader();
578 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
579 $v = $this->respHeaders
[strtolower( $header )];
580 return $v[count( $v ) - 1];
587 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
589 * @param $jar CookieJar
591 public function setCookieJar( $jar ) {
592 $this->cookieJar
= $jar;
596 * Returns the cookie jar in use.
600 public function getCookieJar() {
601 if ( !$this->respHeaders
) {
602 $this->parseHeader();
605 return $this->cookieJar
;
609 * Sets a cookie. Used before a request to set up any individual
610 * cookies. Used internally after a request to parse the
611 * Set-Cookie headers.
617 public function setCookie( $name, $value = null, $attr = null ) {
618 if ( !$this->cookieJar
) {
619 $this->cookieJar
= new CookieJar
;
622 $this->cookieJar
->setCookie( $name, $value, $attr );
626 * Parse the cookies in the response headers and store them in the cookie jar.
628 protected function parseCookies() {
629 wfProfileIn( __METHOD__
);
631 if ( !$this->cookieJar
) {
632 $this->cookieJar
= new CookieJar
;
635 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
636 $url = parse_url( $this->getFinalUrl() );
637 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
638 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
642 wfProfileOut( __METHOD__
);
646 * Returns the final URL after all redirections.
648 * Relative values of the "Location" header are incorrect as
649 * stated in RFC, however they do happen and modern browsers
650 * support them. This function loops backwards through all
651 * locations in order to build the proper absolute URI - Marooned
654 * Note that the multiple Location: headers are an artifact of
655 * CURL -- they shouldn't actually get returned this way. Rewrite
656 * this when bug 29232 is taken care of (high-level redirect
661 public function getFinalUrl() {
662 $headers = $this->getResponseHeaders();
664 //return full url (fix for incorrect but handled relative location)
665 if ( isset( $headers['location'] ) ) {
666 $locations = $headers['location'];
668 $foundRelativeURI = false;
669 $countLocations = count( $locations );
671 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
672 $url = parse_url( $locations[$i] );
674 if ( isset( $url['host'] ) ) {
675 $domain = $url['scheme'] . '://' . $url['host'];
676 break; //found correct URI (with host)
678 $foundRelativeURI = true;
682 if ( $foundRelativeURI ) {
684 return $domain . $locations[$countLocations - 1];
686 $url = parse_url( $this->url
);
687 if ( isset( $url['host'] ) ) {
688 return $url['scheme'] . '://' . $url['host'] .
689 $locations[$countLocations - 1];
693 return $locations[$countLocations - 1];
701 * Returns true if the backend can follow redirects. Overridden by the
705 public function canFollowRedirects() {
711 * MWHttpRequest implemented using internal curl compiled into PHP
713 class CurlHttpRequest
extends MWHttpRequest
{
714 const SUPPORTS_FILE_POSTS
= true;
716 protected $curlOptions = array();
717 protected $headerText = "";
724 protected function readHeader( $fh, $content ) {
725 $this->headerText
.= $content;
726 return strlen( $content );
729 public function execute() {
730 wfProfileIn( __METHOD__
);
734 if ( !$this->status
->isOK() ) {
735 wfProfileOut( __METHOD__
);
736 return $this->status
;
739 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
740 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
742 // Only supported in curl >= 7.16.2
743 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
744 $this->curlOptions
[CURLOPT_CONNECTTIMEOUT_MS
] = $this->connectTimeout
* 1000;
747 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
748 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
749 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
750 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
751 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
753 /* not sure these two are actually necessary */
754 if ( isset( $this->reqHeaders
['Referer'] ) ) {
755 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
757 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
759 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost ?
2 : 0;
760 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
762 if ( $this->caInfo
) {
763 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
766 if ( $this->headersOnly
) {
767 $this->curlOptions
[CURLOPT_NOBODY
] = true;
768 $this->curlOptions
[CURLOPT_HEADER
] = true;
769 } elseif ( $this->method
== 'POST' ) {
770 $this->curlOptions
[CURLOPT_POST
] = true;
771 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
772 // Suppress 'Expect: 100-continue' header, as some servers
773 // will reject it with a 417 and Curl won't auto retry
774 // with HTTP 1.0 fallback
775 $this->reqHeaders
['Expect'] = '';
777 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
780 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
782 $curlHandle = curl_init( $this->url
);
784 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
785 wfProfileOut( __METHOD__
);
786 throw new MWException( "Error setting curl options." );
789 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
790 wfSuppressWarnings();
791 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
792 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
793 "Probably safe_mode or open_basedir is set.\n" );
794 // Continue the processing. If it were in curl_setopt_array,
795 // processing would have halted on its entry
800 $curlRes = curl_exec( $curlHandle );
801 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED
) {
802 $this->status
->fatal( 'http-timed-out', $this->url
);
803 } elseif ( $curlRes === false ) {
804 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
806 $this->headerList
= explode( "\r\n", $this->headerText
);
809 curl_close( $curlHandle );
811 $this->parseHeader();
814 wfProfileOut( __METHOD__
);
816 return $this->status
;
822 public function canFollowRedirects() {
823 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
824 wfDebug( "Cannot follow redirects in safe mode\n" );
828 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
829 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
837 class PhpHttpRequest
extends MWHttpRequest
{
843 protected function urlToTcp( $url ) {
844 $parsedUrl = parse_url( $url );
846 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
849 public function execute() {
850 wfProfileIn( __METHOD__
);
854 if ( is_array( $this->postData
) ) {
855 $this->postData
= wfArrayToCgi( $this->postData
);
858 if ( $this->parsedUrl
['scheme'] != 'http'
859 && $this->parsedUrl
['scheme'] != 'https' ) {
860 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
863 $this->reqHeaders
['Accept'] = "*/*";
864 if ( $this->method
== 'POST' ) {
865 // Required for HTTP 1.0 POSTs
866 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
867 if ( !isset( $this->reqHeaders
['Content-Type'] ) ) {
868 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
873 if ( $this->proxy
) {
874 $options['proxy'] = $this->urlToTCP( $this->proxy
);
875 $options['request_fulluri'] = true;
878 if ( !$this->followRedirects
) {
879 $options['max_redirects'] = 0;
881 $options['max_redirects'] = $this->maxRedirects
;
884 $options['method'] = $this->method
;
885 $options['header'] = implode( "\r\n", $this->getHeaderList() );
886 // Note that at some future point we may want to support
887 // HTTP/1.1, but we'd have to write support for chunking
888 // in version of PHP < 5.3.1
889 $options['protocol_version'] = "1.0";
891 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
892 // Only works on 5.2.10+
893 $options['ignore_errors'] = true;
895 if ( $this->postData
) {
896 $options['content'] = $this->postData
;
899 $options['timeout'] = $this->timeout
;
901 if ( $this->sslVerifyHost
) {
902 $options['CN_match'] = $this->parsedUrl
['host'];
904 if ( $this->sslVerifyCert
) {
905 $options['verify_peer'] = true;
908 if ( is_dir( $this->caInfo
) ) {
909 $options['capath'] = $this->caInfo
;
910 } elseif ( is_file( $this->caInfo
) ) {
911 $options['cafile'] = $this->caInfo
;
912 } elseif ( $this->caInfo
) {
913 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
916 $scheme = $this->parsedUrl
['scheme'];
917 $context = stream_context_create( array( "$scheme" => $options ) );
919 $this->headerList
= array();
927 wfSuppressWarnings();
928 $fh = fopen( $url, "r", false, $context );
935 $result = stream_get_meta_data( $fh );
936 $this->headerList
= $result['wrapper_data'];
937 $this->parseHeader();
939 if ( !$this->followRedirects
) {
943 # Handle manual redirection
944 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
947 # Check security of URL
948 $url = $this->getResponseHeader( "Location" );
950 if ( !Http
::isValidURI( $url ) ) {
951 wfDebug( __METHOD__
. ": insecure redirection\n" );
958 if ( $fh === false ) {
959 $this->status
->fatal( 'http-request-error' );
960 wfProfileOut( __METHOD__
);
961 return $this->status
;
964 if ( $result['timed_out'] ) {
965 $this->status
->fatal( 'http-timed-out', $this->url
);
966 wfProfileOut( __METHOD__
);
967 return $this->status
;
970 // If everything went OK, or we received some error code
971 // get the response body content.
972 if ( $this->status
->isOK() ||
(int)$this->respStatus
>= 300 ) {
973 while ( !feof( $fh ) ) {
974 $buf = fread( $fh, 8192 );
976 if ( $buf === false ) {
977 $this->status
->fatal( 'http-read-error' );
981 if ( strlen( $buf ) ) {
982 call_user_func( $this->callback
, $fh, $buf );
988 wfProfileOut( __METHOD__
);
990 return $this->status
;