Pass __METHOD__ to DatabaseBase::commit() and DatabaseBase::rollback()
[mediawiki.git] / includes / HttpFunctions.php
blob23ea8df2cf1ca2e80a0d1614cad86c1a5463fe14
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];
225 * Simple function to test if we can make any sort of requests at all, using
226 * cURL or fopen()
227 * @return bool
229 public static function canMakeRequests() {
230 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
234 * Generate a new request object
235 * @param $url String: url to use
236 * @param $options Array: (optional) extra params to pass (see Http::request())
237 * @return CurlHttpRequest|PhpHttpRequest
238 * @see MWHttpRequest::__construct
240 public static function factory( $url, $options = null ) {
241 if ( !Http::$httpEngine ) {
242 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
243 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
244 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
245 ' Http::$httpEngine is set to "curl"' );
248 switch( Http::$httpEngine ) {
249 case 'curl':
250 return new CurlHttpRequest( $url, $options );
251 case 'php':
252 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
253 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
254 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
256 return new PhpHttpRequest( $url, $options );
257 default:
258 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
263 * Get the body, or content, of the response to the request
265 * @return String
267 public function getContent() {
268 return $this->content;
272 * Set the parameters of the request
274 * @param $args Array
275 * @todo overload the args param
277 public function setData( $args ) {
278 $this->postData = $args;
282 * Take care of setting up the proxy
283 * (override in subclass)
285 * @return String
287 public function proxySetup() {
288 global $wgHTTPProxy;
290 if ( $this->proxy && !$this->noProxy ) {
291 return;
294 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
295 $this->proxy = '';
296 } elseif ( $wgHTTPProxy ) {
297 $this->proxy = $wgHTTPProxy ;
298 } elseif ( getenv( "http_proxy" ) ) {
299 $this->proxy = getenv( "http_proxy" );
304 * Set the refererer header
306 public function setReferer( $url ) {
307 $this->setHeader( 'Referer', $url );
311 * Set the user agent
312 * @param $UA string
314 public function setUserAgent( $UA ) {
315 $this->setHeader( 'User-Agent', $UA );
319 * Set an arbitrary header
320 * @param $name
321 * @param $value
323 public function setHeader( $name, $value ) {
324 // I feel like I should normalize the case here...
325 $this->reqHeaders[$name] = $value;
329 * Get an array of the headers
330 * @return array
332 public function getHeaderList() {
333 $list = array();
335 if ( $this->cookieJar ) {
336 $this->reqHeaders['Cookie'] =
337 $this->cookieJar->serializeToHttpRequest(
338 $this->parsedUrl['path'],
339 $this->parsedUrl['host']
343 foreach ( $this->reqHeaders as $name => $value ) {
344 $list[] = "$name: $value";
347 return $list;
351 * Set a read callback to accept data read from the HTTP request.
352 * By default, data is appended to an internal buffer which can be
353 * retrieved through $req->getContent().
355 * To handle data as it comes in -- especially for large files that
356 * would not fit in memory -- you can instead set your own callback,
357 * in the form function($resource, $buffer) where the first parameter
358 * is the low-level resource being read (implementation specific),
359 * and the second parameter is the data buffer.
361 * You MUST return the number of bytes handled in the buffer; if fewer
362 * bytes are reported handled than were passed to you, the HTTP fetch
363 * will be aborted.
365 * @param $callback Callback
367 public function setCallback( $callback ) {
368 if ( !is_callable( $callback ) ) {
369 throw new MWException( 'Invalid MwHttpRequest callback' );
371 $this->callback = $callback;
375 * A generic callback to read the body of the response from a remote
376 * server.
378 * @param $fh handle
379 * @param $content String
380 * @return int
382 public function read( $fh, $content ) {
383 $this->content .= $content;
384 return strlen( $content );
388 * Take care of whatever is necessary to perform the URI request.
390 * @return Status
392 public function execute() {
393 global $wgTitle;
395 $this->content = "";
397 if ( strtoupper( $this->method ) == "HEAD" ) {
398 $this->headersOnly = true;
401 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
402 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
406 * Set up the proxy, but
407 * clear the proxy when $noProxy is set (takes precedence)
409 $this->proxySetup();
411 if ( !$this->callback ) {
412 $this->setCallback( array( $this, 'read' ) );
415 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
416 $this->setUserAgent( Http::userAgent() );
421 * Parses the headers, including the HTTP status code and any
422 * Set-Cookie headers. This function expectes the headers to be
423 * found in an array in the member variable headerList.
425 protected function parseHeader() {
426 $lastname = "";
428 foreach ( $this->headerList as $header ) {
429 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
430 $this->respVersion = $match[1];
431 $this->respStatus = $match[2];
432 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
433 $last = count( $this->respHeaders[$lastname] ) - 1;
434 $this->respHeaders[$lastname][$last] .= "\r\n$header";
435 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
436 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
437 $lastname = strtolower( $match[1] );
441 $this->parseCookies();
445 * Sets HTTPRequest status member to a fatal value with the error
446 * message if the returned integer value of the status code was
447 * not successful (< 300) or a redirect (>=300 and < 400). (see
448 * RFC2616, section 10,
449 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
450 * list of status codes.)
452 protected function setStatus() {
453 if ( !$this->respHeaders ) {
454 $this->parseHeader();
457 if ( (int)$this->respStatus > 399 ) {
458 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
459 $this->status->fatal( "http-bad-status", $code, $message );
464 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
465 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
466 * for a list of status codes.)
468 * @return Integer
470 public function getStatus() {
471 if ( !$this->respHeaders ) {
472 $this->parseHeader();
475 return (int)$this->respStatus;
480 * Returns true if the last status code was a redirect.
482 * @return Boolean
484 public function isRedirect() {
485 if ( !$this->respHeaders ) {
486 $this->parseHeader();
489 $status = (int)$this->respStatus;
491 if ( $status >= 300 && $status <= 303 ) {
492 return true;
495 return false;
499 * Returns an associative array of response headers after the
500 * request has been executed. Because some headers
501 * (e.g. Set-Cookie) can appear more than once the, each value of
502 * the associative array is an array of the values given.
504 * @return Array
506 public function getResponseHeaders() {
507 if ( !$this->respHeaders ) {
508 $this->parseHeader();
511 return $this->respHeaders;
515 * Returns the value of the given response header.
517 * @param $header String
518 * @return String
520 public function getResponseHeader( $header ) {
521 if ( !$this->respHeaders ) {
522 $this->parseHeader();
525 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
526 $v = $this->respHeaders[strtolower ( $header ) ];
527 return $v[count( $v ) - 1];
530 return null;
534 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
536 * @param $jar CookieJar
538 public function setCookieJar( $jar ) {
539 $this->cookieJar = $jar;
543 * Returns the cookie jar in use.
545 * @return CookieJar
547 public function getCookieJar() {
548 if ( !$this->respHeaders ) {
549 $this->parseHeader();
552 return $this->cookieJar;
556 * Sets a cookie. Used before a request to set up any individual
557 * cookies. Used internally after a request to parse the
558 * Set-Cookie headers.
559 * @see Cookie::set
560 * @param $name
561 * @param $value null
562 * @param $attr null
564 public function setCookie( $name, $value = null, $attr = null ) {
565 if ( !$this->cookieJar ) {
566 $this->cookieJar = new CookieJar;
569 $this->cookieJar->setCookie( $name, $value, $attr );
573 * Parse the cookies in the response headers and store them in the cookie jar.
575 protected function parseCookies() {
576 if ( !$this->cookieJar ) {
577 $this->cookieJar = new CookieJar;
580 if ( isset( $this->respHeaders['set-cookie'] ) ) {
581 $url = parse_url( $this->getFinalUrl() );
582 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
583 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
589 * Returns the final URL after all redirections.
591 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
592 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
594 * Note that the multiple Location: headers are an artifact of CURL -- they
595 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
596 * taken care of (high-level redirect handling rewrite).
598 * @return string
600 public function getFinalUrl() {
601 $headers = $this->getResponseHeaders();
603 //return full url (fix for incorrect but handled relative location)
604 if ( isset( $headers[ 'location' ] ) ) {
605 $locations = $headers[ 'location' ];
606 $domain = '';
607 $foundRelativeURI = false;
608 $countLocations = count($locations);
610 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
611 $url = parse_url( $locations[ $i ] );
613 if ( isset($url[ 'host' ]) ) {
614 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
615 break; //found correct URI (with host)
616 } else {
617 $foundRelativeURI = true;
621 if ( $foundRelativeURI ) {
622 if ( $domain ) {
623 return $domain . $locations[ $countLocations - 1 ];
624 } else {
625 $url = parse_url( $this->url );
626 if ( isset($url[ 'host' ]) ) {
627 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
630 } else {
631 return $locations[ $countLocations - 1 ];
635 return $this->url;
639 * Returns true if the backend can follow redirects. Overridden by the
640 * child classes.
641 * @return bool
643 public function canFollowRedirects() {
644 return true;
649 * MWHttpRequest implemented using internal curl compiled into PHP
651 class CurlHttpRequest extends MWHttpRequest {
652 const SUPPORTS_FILE_POSTS = true;
654 static $curlMessageMap = array(
655 6 => 'http-host-unreachable',
656 28 => 'http-timed-out'
659 protected $curlOptions = array();
660 protected $headerText = "";
663 * @param $fh
664 * @param $content
665 * @return int
667 protected function readHeader( $fh, $content ) {
668 $this->headerText .= $content;
669 return strlen( $content );
672 public function execute() {
673 parent::execute();
675 if ( !$this->status->isOK() ) {
676 return $this->status;
679 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
680 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
681 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
682 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
683 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
684 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
685 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
687 /* not sure these two are actually necessary */
688 if ( isset( $this->reqHeaders['Referer'] ) ) {
689 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
691 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
693 if ( isset( $this->sslVerifyHost ) ) {
694 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
697 if ( isset( $this->sslVerifyCert ) ) {
698 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
701 if ( $this->caInfo ) {
702 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
705 if ( $this->headersOnly ) {
706 $this->curlOptions[CURLOPT_NOBODY] = true;
707 $this->curlOptions[CURLOPT_HEADER] = true;
708 } elseif ( $this->method == 'POST' ) {
709 $this->curlOptions[CURLOPT_POST] = true;
710 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
711 // Suppress 'Expect: 100-continue' header, as some servers
712 // will reject it with a 417 and Curl won't auto retry
713 // with HTTP 1.0 fallback
714 $this->reqHeaders['Expect'] = '';
715 } else {
716 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
719 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
721 $curlHandle = curl_init( $this->url );
723 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
724 throw new MWException( "Error setting curl options." );
727 if ( $this->followRedirects && $this->canFollowRedirects() ) {
728 wfSuppressWarnings();
729 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
730 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
731 "Probably safe_mode or open_basedir is set.\n" );
732 // Continue the processing. If it were in curl_setopt_array,
733 // processing would have halted on its entry
735 wfRestoreWarnings();
738 if ( false === curl_exec( $curlHandle ) ) {
739 $code = curl_error( $curlHandle );
741 if ( isset( self::$curlMessageMap[$code] ) ) {
742 $this->status->fatal( self::$curlMessageMap[$code] );
743 } else {
744 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
746 } else {
747 $this->headerList = explode( "\r\n", $this->headerText );
750 curl_close( $curlHandle );
752 $this->parseHeader();
753 $this->setStatus();
755 return $this->status;
759 * @return bool
761 public function canFollowRedirects() {
762 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
763 wfDebug( "Cannot follow redirects in safe mode\n" );
764 return false;
767 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
768 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
769 return false;
772 return true;
776 class PhpHttpRequest extends MWHttpRequest {
779 * @param $url string
780 * @return string
782 protected function urlToTcp( $url ) {
783 $parsedUrl = parse_url( $url );
785 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
788 public function execute() {
789 parent::execute();
791 if ( is_array( $this->postData ) ) {
792 $this->postData = wfArrayToCGI( $this->postData );
795 if ( $this->parsedUrl['scheme'] != 'http' &&
796 $this->parsedUrl['scheme'] != 'https' ) {
797 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
800 $this->reqHeaders['Accept'] = "*/*";
801 if ( $this->method == 'POST' ) {
802 // Required for HTTP 1.0 POSTs
803 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
804 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
807 $options = array();
808 if ( $this->proxy && !$this->noProxy ) {
809 $options['proxy'] = $this->urlToTCP( $this->proxy );
810 $options['request_fulluri'] = true;
813 if ( !$this->followRedirects ) {
814 $options['max_redirects'] = 0;
815 } else {
816 $options['max_redirects'] = $this->maxRedirects;
819 $options['method'] = $this->method;
820 $options['header'] = implode( "\r\n", $this->getHeaderList() );
821 // Note that at some future point we may want to support
822 // HTTP/1.1, but we'd have to write support for chunking
823 // in version of PHP < 5.3.1
824 $options['protocol_version'] = "1.0";
826 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
827 // Only works on 5.2.10+
828 $options['ignore_errors'] = true;
830 if ( $this->postData ) {
831 $options['content'] = $this->postData;
834 $options['timeout'] = $this->timeout;
836 $context = stream_context_create( array( 'http' => $options ) );
838 $this->headerList = array();
839 $reqCount = 0;
840 $url = $this->url;
842 $result = array();
844 do {
845 $reqCount++;
846 wfSuppressWarnings();
847 $fh = fopen( $url, "r", false, $context );
848 wfRestoreWarnings();
850 if ( !$fh ) {
851 break;
854 $result = stream_get_meta_data( $fh );
855 $this->headerList = $result['wrapper_data'];
856 $this->parseHeader();
858 if ( !$this->followRedirects ) {
859 break;
862 # Handle manual redirection
863 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
864 break;
866 # Check security of URL
867 $url = $this->getResponseHeader( "Location" );
869 if ( !Http::isValidURI( $url ) ) {
870 wfDebug( __METHOD__ . ": insecure redirection\n" );
871 break;
873 } while ( true );
875 $this->setStatus();
877 if ( $fh === false ) {
878 $this->status->fatal( 'http-request-error' );
879 return $this->status;
882 if ( $result['timed_out'] ) {
883 $this->status->fatal( 'http-timed-out', $this->url );
884 return $this->status;
887 // If everything went OK, or we recieved some error code
888 // get the response body content.
889 if ( $this->status->isOK()
890 || (int)$this->respStatus >= 300) {
891 while ( !feof( $fh ) ) {
892 $buf = fread( $fh, 8192 );
894 if ( $buf === false ) {
895 $this->status->fatal( 'http-read-error' );
896 break;
899 if ( strlen( $buf ) ) {
900 call_user_func( $this->callback, $fh, $buf );
904 fclose( $fh );
906 return $this->status;