Merge branch 'Wikidata', remote-tracking branch 'origin/Wikidata' into Wikidata
[mediawiki.git] / includes / HttpFunctions.php
bloba1d2e59e590652056ef54b2da3dce8ea91b3ff1e
1 <?php
2 /**
3 * @defgroup HTTP HTTP
4 */
6 /**
7 * Various HTTP related functions
8 * @ingroup HTTP
9 */
10 class Http {
11 static $httpEngine = false;
13 /**
14 * Perform an HTTP request
16 * @param $method String: HTTP method. Usually GET/POST
17 * @param $url String: full URL to act on. If protocol-relative, will be expanded to an http:// URL
18 * @param $options Array: options to pass to MWHttpRequest object.
19 * Possible keys for the array:
20 * - timeout Timeout length in seconds
21 * - postData An array of key-value pairs or a url-encoded form data
22 * - proxy The proxy to use.
23 * Otherwise it will use $wgHTTPProxy (if set)
24 * Otherwise it will use the environment variable "http_proxy" (if set)
25 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
26 * - sslVerifyHost (curl only) Verify hostname against certificate
27 * - sslVerifyCert (curl only) Verify SSL certificate
28 * - caInfo (curl only) Provide CA information
29 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
30 * - followRedirects Whether to follow redirects (defaults to false).
31 * Note: this should only be used when the target URL is trusted,
32 * to avoid attacks on intranet services accessible by HTTP.
33 * - userAgent A user agent, if you want to override the default
34 * MediaWiki/$wgVersion
35 * @return Mixed: (bool)false on failure or a string on success
37 public static function request( $method, $url, $options = array() ) {
38 wfDebug( "HTTP: $method: $url\n" );
39 $options['method'] = strtoupper( $method );
41 if ( !isset( $options['timeout'] ) ) {
42 $options['timeout'] = 'default';
45 $req = MWHttpRequest::factory( $url, $options );
46 $status = $req->execute();
48 if ( $status->isOK() ) {
49 return $req->getContent();
50 } else {
51 return false;
55 /**
56 * Simple wrapper for Http::request( 'GET' )
57 * @see Http::request()
59 * @param $url
60 * @param $timeout string
61 * @param $options array
62 * @return string
64 public static function get( $url, $timeout = 'default', $options = array() ) {
65 $options['timeout'] = $timeout;
66 return Http::request( 'GET', $url, $options );
69 /**
70 * Simple wrapper for Http::request( 'POST' )
71 * @see Http::request()
73 * @param $url
74 * @param $options array
75 * @return string
77 public static function post( $url, $options = array() ) {
78 return Http::request( 'POST', $url, $options );
81 /**
82 * Check if the URL can be served by localhost
84 * @param $url String: full url to check
85 * @return Boolean
87 public static function isLocalURL( $url ) {
88 global $wgCommandLineMode, $wgConf;
90 if ( $wgCommandLineMode ) {
91 return false;
94 // Extract host part
95 $matches = array();
96 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
97 $host = $matches[1];
98 // Split up dotwise
99 $domainParts = explode( '.', $host );
100 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
101 $domainParts = array_reverse( $domainParts );
103 $domain = '';
104 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
105 $domainPart = $domainParts[$i];
106 if ( $i == 0 ) {
107 $domain = $domainPart;
108 } else {
109 $domain = $domainPart . '.' . $domain;
112 if ( $wgConf->isLocalVHost( $domain ) ) {
113 return true;
118 return false;
122 * A standard user-agent we can use for external requests.
123 * @return String
125 public static function userAgent() {
126 global $wgVersion;
127 return "MediaWiki/$wgVersion";
131 * Checks that the given URI is a valid one. Hardcoding the
132 * protocols, because we only want protocols that both cURL
133 * and php support.
135 * file:// should not be allowed here for security purpose (r67684)
137 * @fixme this is wildly inaccurate and fails to actually check most stuff
139 * @param $uri Mixed: URI to check for validity
140 * @return Boolean
142 public static function isValidURI( $uri ) {
143 return preg_match(
144 '/^https?:\/\/[^\/\s]\S*$/D',
145 $uri
151 * This wrapper class will call out to curl (if available) or fallback
152 * to regular PHP if necessary for handling internal HTTP requests.
154 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
155 * PHP's HTTP extension.
157 class MWHttpRequest {
158 const SUPPORTS_FILE_POSTS = false;
160 protected $content;
161 protected $timeout = 'default';
162 protected $headersOnly = null;
163 protected $postData = null;
164 protected $proxy = null;
165 protected $noProxy = false;
166 protected $sslVerifyHost = true;
167 protected $sslVerifyCert = true;
168 protected $caInfo = null;
169 protected $method = "GET";
170 protected $reqHeaders = array();
171 protected $url;
172 protected $parsedUrl;
173 protected $callback;
174 protected $maxRedirects = 5;
175 protected $followRedirects = false;
178 * @var CookieJar
180 protected $cookieJar;
182 protected $headerList = array();
183 protected $respVersion = "0.9";
184 protected $respStatus = "200 Ok";
185 protected $respHeaders = array();
187 public $status;
190 * @param $url String: url to use. If protocol-relative, will be expanded to an http:// URL
191 * @param $options Array: (optional) extra params to pass (see Http::request())
193 function __construct( $url, $options = array() ) {
194 global $wgHTTPTimeout;
196 $this->url = wfExpandUrl( $url, PROTO_HTTP );
197 $this->parsedUrl = wfParseUrl( $this->url );
199 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
200 $this->status = Status::newFatal( 'http-invalid-url' );
201 } else {
202 $this->status = Status::newGood( 100 ); // continue
205 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
206 $this->timeout = $options['timeout'];
207 } else {
208 $this->timeout = $wgHTTPTimeout;
210 if( isset( $options['userAgent'] ) ) {
211 $this->setUserAgent( $options['userAgent'] );
214 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
215 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
217 foreach ( $members as $o ) {
218 if ( isset( $options[$o] ) ) {
219 $this->$o = $options[$o];
223 if ( $this->noProxy ) {
224 $this->proxy = ''; // noProxy takes precedence
229 * Simple function to test if we can make any sort of requests at all, using
230 * cURL or fopen()
231 * @return bool
233 public static function canMakeRequests() {
234 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
238 * Generate a new request object
239 * @param $url String: url to use
240 * @param $options Array: (optional) extra params to pass (see Http::request())
241 * @return CurlHttpRequest|PhpHttpRequest
242 * @see MWHttpRequest::__construct
244 public static function factory( $url, $options = null ) {
245 if ( !Http::$httpEngine ) {
246 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
247 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
248 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
249 ' Http::$httpEngine is set to "curl"' );
252 switch( Http::$httpEngine ) {
253 case 'curl':
254 return new CurlHttpRequest( $url, $options );
255 case 'php':
256 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
257 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
258 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
260 return new PhpHttpRequest( $url, $options );
261 default:
262 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
267 * Get the body, or content, of the response to the request
269 * @return String
271 public function getContent() {
272 return $this->content;
276 * Set the parameters of the request
278 * @param $args Array
279 * @todo overload the args param
281 public function setData( $args ) {
282 $this->postData = $args;
286 * Take care of setting up the proxy (do nothing if "noProxy" is set)
288 * @return void
290 public function proxySetup() {
291 global $wgHTTPProxy;
293 if ( $this->proxy || !$this->noProxy ) {
294 return;
297 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
298 $this->proxy = '';
299 } elseif ( $wgHTTPProxy ) {
300 $this->proxy = $wgHTTPProxy ;
301 } elseif ( getenv( "http_proxy" ) ) {
302 $this->proxy = getenv( "http_proxy" );
307 * Set the refererer header
309 public function setReferer( $url ) {
310 $this->setHeader( 'Referer', $url );
314 * Set the user agent
315 * @param $UA string
317 public function setUserAgent( $UA ) {
318 $this->setHeader( 'User-Agent', $UA );
322 * Set an arbitrary header
323 * @param $name
324 * @param $value
326 public function setHeader( $name, $value ) {
327 // I feel like I should normalize the case here...
328 $this->reqHeaders[$name] = $value;
332 * Get an array of the headers
333 * @return array
335 public function getHeaderList() {
336 $list = array();
338 if ( $this->cookieJar ) {
339 $this->reqHeaders['Cookie'] =
340 $this->cookieJar->serializeToHttpRequest(
341 $this->parsedUrl['path'],
342 $this->parsedUrl['host']
346 foreach ( $this->reqHeaders as $name => $value ) {
347 $list[] = "$name: $value";
350 return $list;
354 * Set a read callback to accept data read from the HTTP request.
355 * By default, data is appended to an internal buffer which can be
356 * retrieved through $req->getContent().
358 * To handle data as it comes in -- especially for large files that
359 * would not fit in memory -- you can instead set your own callback,
360 * in the form function($resource, $buffer) where the first parameter
361 * is the low-level resource being read (implementation specific),
362 * and the second parameter is the data buffer.
364 * You MUST return the number of bytes handled in the buffer; if fewer
365 * bytes are reported handled than were passed to you, the HTTP fetch
366 * will be aborted.
368 * @param $callback Callback
370 public function setCallback( $callback ) {
371 if ( !is_callable( $callback ) ) {
372 throw new MWException( 'Invalid MwHttpRequest callback' );
374 $this->callback = $callback;
378 * A generic callback to read the body of the response from a remote
379 * server.
381 * @param $fh handle
382 * @param $content String
383 * @return int
385 public function read( $fh, $content ) {
386 $this->content .= $content;
387 return strlen( $content );
391 * Take care of whatever is necessary to perform the URI request.
393 * @return Status
395 public function execute() {
396 global $wgTitle;
398 $this->content = "";
400 if ( strtoupper( $this->method ) == "HEAD" ) {
401 $this->headersOnly = true;
404 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
405 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
408 $this->proxySetup(); // set up any proxy as needed
410 if ( !$this->callback ) {
411 $this->setCallback( array( $this, 'read' ) );
414 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
415 $this->setUserAgent( Http::userAgent() );
420 * Parses the headers, including the HTTP status code and any
421 * Set-Cookie headers. This function expectes the headers to be
422 * found in an array in the member variable headerList.
424 protected function parseHeader() {
425 $lastname = "";
427 foreach ( $this->headerList as $header ) {
428 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
429 $this->respVersion = $match[1];
430 $this->respStatus = $match[2];
431 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
432 $last = count( $this->respHeaders[$lastname] ) - 1;
433 $this->respHeaders[$lastname][$last] .= "\r\n$header";
434 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
435 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
436 $lastname = strtolower( $match[1] );
440 $this->parseCookies();
444 * Sets HTTPRequest status member to a fatal value with the error
445 * message if the returned integer value of the status code was
446 * not successful (< 300) or a redirect (>=300 and < 400). (see
447 * RFC2616, section 10,
448 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
449 * list of status codes.)
451 protected function setStatus() {
452 if ( !$this->respHeaders ) {
453 $this->parseHeader();
456 if ( (int)$this->respStatus > 399 ) {
457 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
458 $this->status->fatal( "http-bad-status", $code, $message );
463 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
464 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
465 * for a list of status codes.)
467 * @return Integer
469 public function getStatus() {
470 if ( !$this->respHeaders ) {
471 $this->parseHeader();
474 return (int)$this->respStatus;
479 * Returns true if the last status code was a redirect.
481 * @return Boolean
483 public function isRedirect() {
484 if ( !$this->respHeaders ) {
485 $this->parseHeader();
488 $status = (int)$this->respStatus;
490 if ( $status >= 300 && $status <= 303 ) {
491 return true;
494 return false;
498 * Returns an associative array of response headers after the
499 * request has been executed. Because some headers
500 * (e.g. Set-Cookie) can appear more than once the, each value of
501 * the associative array is an array of the values given.
503 * @return Array
505 public function getResponseHeaders() {
506 if ( !$this->respHeaders ) {
507 $this->parseHeader();
510 return $this->respHeaders;
514 * Returns the value of the given response header.
516 * @param $header String
517 * @return String
519 public function getResponseHeader( $header ) {
520 if ( !$this->respHeaders ) {
521 $this->parseHeader();
524 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
525 $v = $this->respHeaders[strtolower ( $header ) ];
526 return $v[count( $v ) - 1];
529 return null;
533 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
535 * @param $jar CookieJar
537 public function setCookieJar( $jar ) {
538 $this->cookieJar = $jar;
542 * Returns the cookie jar in use.
544 * @return CookieJar
546 public function getCookieJar() {
547 if ( !$this->respHeaders ) {
548 $this->parseHeader();
551 return $this->cookieJar;
555 * Sets a cookie. Used before a request to set up any individual
556 * cookies. Used internally after a request to parse the
557 * Set-Cookie headers.
558 * @see Cookie::set
559 * @param $name
560 * @param $value null
561 * @param $attr null
563 public function setCookie( $name, $value = null, $attr = null ) {
564 if ( !$this->cookieJar ) {
565 $this->cookieJar = new CookieJar;
568 $this->cookieJar->setCookie( $name, $value, $attr );
572 * Parse the cookies in the response headers and store them in the cookie jar.
574 protected function parseCookies() {
575 if ( !$this->cookieJar ) {
576 $this->cookieJar = new CookieJar;
579 if ( isset( $this->respHeaders['set-cookie'] ) ) {
580 $url = parse_url( $this->getFinalUrl() );
581 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
582 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
588 * Returns the final URL after all redirections.
590 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
591 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
593 * Note that the multiple Location: headers are an artifact of CURL -- they
594 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
595 * taken care of (high-level redirect handling rewrite).
597 * @return string
599 public function getFinalUrl() {
600 $headers = $this->getResponseHeaders();
602 //return full url (fix for incorrect but handled relative location)
603 if ( isset( $headers[ 'location' ] ) ) {
604 $locations = $headers[ 'location' ];
605 $domain = '';
606 $foundRelativeURI = false;
607 $countLocations = count($locations);
609 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
610 $url = parse_url( $locations[ $i ] );
612 if ( isset($url[ 'host' ]) ) {
613 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
614 break; //found correct URI (with host)
615 } else {
616 $foundRelativeURI = true;
620 if ( $foundRelativeURI ) {
621 if ( $domain ) {
622 return $domain . $locations[ $countLocations - 1 ];
623 } else {
624 $url = parse_url( $this->url );
625 if ( isset($url[ 'host' ]) ) {
626 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
629 } else {
630 return $locations[ $countLocations - 1 ];
634 return $this->url;
638 * Returns true if the backend can follow redirects. Overridden by the
639 * child classes.
640 * @return bool
642 public function canFollowRedirects() {
643 return true;
648 * MWHttpRequest implemented using internal curl compiled into PHP
650 class CurlHttpRequest extends MWHttpRequest {
651 const SUPPORTS_FILE_POSTS = true;
653 static $curlMessageMap = array(
654 6 => 'http-host-unreachable',
655 28 => 'http-timed-out'
658 protected $curlOptions = array();
659 protected $headerText = "";
662 * @param $fh
663 * @param $content
664 * @return int
666 protected function readHeader( $fh, $content ) {
667 $this->headerText .= $content;
668 return strlen( $content );
671 public function execute() {
672 parent::execute();
674 if ( !$this->status->isOK() ) {
675 return $this->status;
678 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
679 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
680 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
681 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
682 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
683 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
684 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
686 /* not sure these two are actually necessary */
687 if ( isset( $this->reqHeaders['Referer'] ) ) {
688 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
690 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
692 if ( isset( $this->sslVerifyHost ) ) {
693 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
696 if ( isset( $this->sslVerifyCert ) ) {
697 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
700 if ( $this->caInfo ) {
701 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
704 if ( $this->headersOnly ) {
705 $this->curlOptions[CURLOPT_NOBODY] = true;
706 $this->curlOptions[CURLOPT_HEADER] = true;
707 } elseif ( $this->method == 'POST' ) {
708 $this->curlOptions[CURLOPT_POST] = true;
709 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
710 // Suppress 'Expect: 100-continue' header, as some servers
711 // will reject it with a 417 and Curl won't auto retry
712 // with HTTP 1.0 fallback
713 $this->reqHeaders['Expect'] = '';
714 } else {
715 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
718 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
720 $curlHandle = curl_init( $this->url );
722 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
723 throw new MWException( "Error setting curl options." );
726 if ( $this->followRedirects && $this->canFollowRedirects() ) {
727 wfSuppressWarnings();
728 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
729 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
730 "Probably safe_mode or open_basedir is set.\n" );
731 // Continue the processing. If it were in curl_setopt_array,
732 // processing would have halted on its entry
734 wfRestoreWarnings();
737 if ( false === curl_exec( $curlHandle ) ) {
738 $code = curl_error( $curlHandle );
740 if ( isset( self::$curlMessageMap[$code] ) ) {
741 $this->status->fatal( self::$curlMessageMap[$code] );
742 } else {
743 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
745 } else {
746 $this->headerList = explode( "\r\n", $this->headerText );
749 curl_close( $curlHandle );
751 $this->parseHeader();
752 $this->setStatus();
754 return $this->status;
758 * @return bool
760 public function canFollowRedirects() {
761 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
762 wfDebug( "Cannot follow redirects in safe mode\n" );
763 return false;
766 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
767 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
768 return false;
771 return true;
775 class PhpHttpRequest extends MWHttpRequest {
778 * @param $url string
779 * @return string
781 protected function urlToTcp( $url ) {
782 $parsedUrl = parse_url( $url );
784 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
787 public function execute() {
788 parent::execute();
790 if ( is_array( $this->postData ) ) {
791 $this->postData = wfArrayToCGI( $this->postData );
794 if ( $this->parsedUrl['scheme'] != 'http' &&
795 $this->parsedUrl['scheme'] != 'https' ) {
796 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
799 $this->reqHeaders['Accept'] = "*/*";
800 if ( $this->method == 'POST' ) {
801 // Required for HTTP 1.0 POSTs
802 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
803 if( !isset( $this->reqHeaders['Content-Type'] ) ) {
804 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
808 $options = array();
809 if ( $this->proxy ) {
810 $options['proxy'] = $this->urlToTCP( $this->proxy );
811 $options['request_fulluri'] = true;
814 if ( !$this->followRedirects ) {
815 $options['max_redirects'] = 0;
816 } else {
817 $options['max_redirects'] = $this->maxRedirects;
820 $options['method'] = $this->method;
821 $options['header'] = implode( "\r\n", $this->getHeaderList() );
822 // Note that at some future point we may want to support
823 // HTTP/1.1, but we'd have to write support for chunking
824 // in version of PHP < 5.3.1
825 $options['protocol_version'] = "1.0";
827 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
828 // Only works on 5.2.10+
829 $options['ignore_errors'] = true;
831 if ( $this->postData ) {
832 $options['content'] = $this->postData;
835 $options['timeout'] = $this->timeout;
837 $context = stream_context_create( array( 'http' => $options ) );
839 $this->headerList = array();
840 $reqCount = 0;
841 $url = $this->url;
843 $result = array();
845 do {
846 $reqCount++;
847 wfSuppressWarnings();
848 $fh = fopen( $url, "r", false, $context );
849 wfRestoreWarnings();
851 if ( !$fh ) {
852 break;
855 $result = stream_get_meta_data( $fh );
856 $this->headerList = $result['wrapper_data'];
857 $this->parseHeader();
859 if ( !$this->followRedirects ) {
860 break;
863 # Handle manual redirection
864 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
865 break;
867 # Check security of URL
868 $url = $this->getResponseHeader( "Location" );
870 if ( !Http::isValidURI( $url ) ) {
871 wfDebug( __METHOD__ . ": insecure redirection\n" );
872 break;
874 } while ( true );
876 $this->setStatus();
878 if ( $fh === false ) {
879 $this->status->fatal( 'http-request-error' );
880 return $this->status;
883 if ( $result['timed_out'] ) {
884 $this->status->fatal( 'http-timed-out', $this->url );
885 return $this->status;
888 // If everything went OK, or we recieved some error code
889 // get the response body content.
890 if ( $this->status->isOK()
891 || (int)$this->respStatus >= 300) {
892 while ( !feof( $fh ) ) {
893 $buf = fread( $fh, 8192 );
895 if ( $buf === false ) {
896 $this->status->fatal( 'http-read-error' );
897 break;
900 if ( strlen( $buf ) ) {
901 call_user_func( $this->callback, $fh, $buf );
905 fclose( $fh );
907 return $this->status;