Add some doc comments on Cookie::validateCookieDomain() and Http::isValidUri(), which...
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * @defgroup HTTP HTTP
4 */
5
6 /**
7 * Various HTTP related functions
8 * @ingroup HTTP
9 */
10 class Http {
11 static $httpEngine = false;
12
13 /**
14 * Perform an HTTP request
15 *
16 * @param $method String: HTTP method. Usually GET/POST
17 * @param $url String: full URL to act on
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 * Will use $wgHTTPProxy (if set) otherwise.
24 * - noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
25 * - sslVerifyHost (curl only) Verify hostname against certificate
26 * - sslVerifyCert (curl only) Verify SSL certificate
27 * - caInfo (curl only) Provide CA information
28 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
29 * - followRedirects Whether to follow redirects (defaults to false).
30 * Note: this should only be used when the target URL is trusted,
31 * to avoid attacks on intranet services accessible by HTTP.
32 * @return Mixed: (bool)false on failure or a string on success
33 */
34 public static function request( $method, $url, $options = array() ) {
35 $url = wfExpandUrl( $url );
36 wfDebug( "HTTP: $method: $url\n" );
37 $options['method'] = strtoupper( $method );
38
39 if ( !isset( $options['timeout'] ) ) {
40 $options['timeout'] = 'default';
41 }
42
43 $req = MWHttpRequest::factory( $url, $options );
44 $status = $req->execute();
45
46 if ( $status->isOK() ) {
47 return $req->getContent();
48 } else {
49 return false;
50 }
51 }
52
53 /**
54 * Simple wrapper for Http::request( 'GET' )
55 * @see Http::request()
56 *
57 * @return string
58 */
59 public static function get( $url, $timeout = 'default', $options = array() ) {
60 $options['timeout'] = $timeout;
61 return Http::request( 'GET', $url, $options );
62 }
63
64 /**
65 * Simple wrapper for Http::request( 'POST' )
66 * @see Http::request()
67 *
68 * @return string
69 */
70 public static function post( $url, $options = array() ) {
71 return Http::request( 'POST', $url, $options );
72 }
73
74 /**
75 * Check if the URL can be served by localhost
76 *
77 * @param $url String: full url to check
78 * @return Boolean
79 */
80 public static function isLocalURL( $url ) {
81 global $wgCommandLineMode, $wgConf;
82
83 if ( $wgCommandLineMode ) {
84 return false;
85 }
86
87 // Extract host part
88 $matches = array();
89 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
90 $host = $matches[1];
91 // Split up dotwise
92 $domainParts = explode( '.', $host );
93 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
94 $domainParts = array_reverse( $domainParts );
95
96 $domain = '';
97 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
98 $domainPart = $domainParts[$i];
99 if ( $i == 0 ) {
100 $domain = $domainPart;
101 } else {
102 $domain = $domainPart . '.' . $domain;
103 }
104
105 if ( $wgConf->isLocalVHost( $domain ) ) {
106 return true;
107 }
108 }
109 }
110
111 return false;
112 }
113
114 /**
115 * A standard user-agent we can use for external requests.
116 * @return String
117 */
118 public static function userAgent() {
119 global $wgVersion;
120 return "MediaWiki/$wgVersion";
121 }
122
123 /**
124 * Checks that the given URI is a valid one. Hardcoding the
125 * protocols, because we only want protocols that both cURL
126 * and php support.
127 *
128 * @fixme this is wildly inaccurate and fails to actually check most stuff
129 * @fixme do we actually intend to have FTP support here? Does it work consistently?
130 *
131 * @param $uri Mixed: URI to check for validity
132 * @returns Boolean
133 */
134 public static function isValidURI( $uri ) {
135 return preg_match(
136 '/^(f|ht)tps?:\/\/[^\/\s]\S*$/D',
137 $uri
138 );
139 }
140 }
141
142 /**
143 * This wrapper class will call out to curl (if available) or fallback
144 * to regular PHP if necessary for handling internal HTTP requests.
145 *
146 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
147 * PHP's HTTP extension.
148 */
149 class MWHttpRequest {
150 const SUPPORTS_FILE_POSTS = false;
151
152 protected $content;
153 protected $timeout = 'default';
154 protected $headersOnly = null;
155 protected $postData = null;
156 protected $proxy = null;
157 protected $noProxy = false;
158 protected $sslVerifyHost = true;
159 protected $sslVerifyCert = true;
160 protected $caInfo = null;
161 protected $method = "GET";
162 protected $reqHeaders = array();
163 protected $url;
164 protected $parsedUrl;
165 protected $callback;
166 protected $maxRedirects = 5;
167 protected $followRedirects = false;
168
169 /**
170 * @var CookieJar
171 */
172 protected $cookieJar;
173
174 protected $headerList = array();
175 protected $respVersion = "0.9";
176 protected $respStatus = "200 Ok";
177 protected $respHeaders = array();
178
179 public $status;
180
181 /**
182 * @param $url String: url to use
183 * @param $options Array: (optional) extra params to pass (see Http::request())
184 */
185 function __construct( $url, $options = array() ) {
186 global $wgHTTPTimeout;
187
188 $this->url = $url;
189 $this->parsedUrl = parse_url( $url );
190
191 if ( !Http::isValidURI( $this->url ) ) {
192 $this->status = Status::newFatal( 'http-invalid-url' );
193 } else {
194 $this->status = Status::newGood( 100 ); // continue
195 }
196
197 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
198 $this->timeout = $options['timeout'];
199 } else {
200 $this->timeout = $wgHTTPTimeout;
201 }
202
203 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
204 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
205
206 foreach ( $members as $o ) {
207 if ( isset( $options[$o] ) ) {
208 $this->$o = $options[$o];
209 }
210 }
211 }
212
213 /**
214 * Generate a new request object
215 * @param $url String: url to use
216 * @param $options Array: (optional) extra params to pass (see Http::request())
217 * @see MWHttpRequest::__construct
218 */
219 public static function factory( $url, $options = null ) {
220 if ( !Http::$httpEngine ) {
221 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
222 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
223 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
224 ' Http::$httpEngine is set to "curl"' );
225 }
226
227 switch( Http::$httpEngine ) {
228 case 'curl':
229 return new CurlHttpRequest( $url, $options );
230 case 'php':
231 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
232 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
233 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
234 }
235 return new PhpHttpRequest( $url, $options );
236 default:
237 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
238 }
239 }
240
241 /**
242 * Get the body, or content, of the response to the request
243 *
244 * @return String
245 */
246 public function getContent() {
247 return $this->content;
248 }
249
250 /**
251 * Set the parameters of the request
252
253 * @param $args Array
254 * @todo overload the args param
255 */
256 public function setData( $args ) {
257 $this->postData = $args;
258 }
259
260 /**
261 * Take care of setting up the proxy
262 * (override in subclass)
263 *
264 * @return String
265 */
266 public function proxySetup() {
267 global $wgHTTPProxy;
268
269 if ( $this->proxy ) {
270 return;
271 }
272
273 if ( Http::isLocalURL( $this->url ) ) {
274 $this->proxy = 'http://localhost:80/';
275 } elseif ( $wgHTTPProxy ) {
276 $this->proxy = $wgHTTPProxy ;
277 } elseif ( getenv( "http_proxy" ) ) {
278 $this->proxy = getenv( "http_proxy" );
279 }
280 }
281
282 /**
283 * Set the refererer header
284 */
285 public function setReferer( $url ) {
286 $this->setHeader( 'Referer', $url );
287 }
288
289 /**
290 * Set the user agent
291 */
292 public function setUserAgent( $UA ) {
293 $this->setHeader( 'User-Agent', $UA );
294 }
295
296 /**
297 * Set an arbitrary header
298 */
299 public function setHeader( $name, $value ) {
300 // I feel like I should normalize the case here...
301 $this->reqHeaders[$name] = $value;
302 }
303
304 /**
305 * Get an array of the headers
306 */
307 public function getHeaderList() {
308 $list = array();
309
310 if ( $this->cookieJar ) {
311 $this->reqHeaders['Cookie'] =
312 $this->cookieJar->serializeToHttpRequest(
313 $this->parsedUrl['path'],
314 $this->parsedUrl['host']
315 );
316 }
317
318 foreach ( $this->reqHeaders as $name => $value ) {
319 $list[] = "$name: $value";
320 }
321
322 return $list;
323 }
324
325 /**
326 * Set a read callback to accept data read from the HTTP request.
327 * By default, data is appended to an internal buffer which can be
328 * retrieved through $req->getContent().
329 *
330 * To handle data as it comes in -- especially for large files that
331 * would not fit in memory -- you can instead set your own callback,
332 * in the form function($resource, $buffer) where the first parameter
333 * is the low-level resource being read (implementation specific),
334 * and the second parameter is the data buffer.
335 *
336 * You MUST return the number of bytes handled in the buffer; if fewer
337 * bytes are reported handled than were passed to you, the HTTP fetch
338 * will be aborted.
339 *
340 * @param $callback Callback
341 */
342 public function setCallback( $callback ) {
343 if ( !is_callable( $callback ) ) {
344 throw new MWException( 'Invalid MwHttpRequest callback' );
345 }
346 $this->callback = $callback;
347 }
348
349 /**
350 * A generic callback to read the body of the response from a remote
351 * server.
352 *
353 * @param $fh handle
354 * @param $content String
355 */
356 public function read( $fh, $content ) {
357 $this->content .= $content;
358 return strlen( $content );
359 }
360
361 /**
362 * Take care of whatever is necessary to perform the URI request.
363 *
364 * @return Status
365 */
366 public function execute() {
367 global $wgTitle;
368
369 $this->content = "";
370
371 if ( strtoupper( $this->method ) == "HEAD" ) {
372 $this->headersOnly = true;
373 }
374
375 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
376 $this->setReferer( $wgTitle->getFullURL() );
377 }
378
379 if ( !$this->noProxy ) {
380 $this->proxySetup();
381 }
382
383 if ( !$this->callback ) {
384 $this->setCallback( array( $this, 'read' ) );
385 }
386
387 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
388 $this->setUserAgent( Http::userAgent() );
389 }
390 }
391
392 /**
393 * Parses the headers, including the HTTP status code and any
394 * Set-Cookie headers. This function expectes the headers to be
395 * found in an array in the member variable headerList.
396 *
397 * @return nothing
398 */
399 protected function parseHeader() {
400 $lastname = "";
401
402 foreach ( $this->headerList as $header ) {
403 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
404 $this->respVersion = $match[1];
405 $this->respStatus = $match[2];
406 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
407 $last = count( $this->respHeaders[$lastname] ) - 1;
408 $this->respHeaders[$lastname][$last] .= "\r\n$header";
409 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
410 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
411 $lastname = strtolower( $match[1] );
412 }
413 }
414
415 $this->parseCookies();
416 }
417
418 /**
419 * Sets HTTPRequest status member to a fatal value with the error
420 * message if the returned integer value of the status code was
421 * not successful (< 300) or a redirect (>=300 and < 400). (see
422 * RFC2616, section 10,
423 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
424 * list of status codes.)
425 *
426 * @return nothing
427 */
428 protected function setStatus() {
429 if ( !$this->respHeaders ) {
430 $this->parseHeader();
431 }
432
433 if ( (int)$this->respStatus > 399 ) {
434 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
435 $this->status->fatal( "http-bad-status", $code, $message );
436 }
437 }
438
439 /**
440 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
441 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
442 * for a list of status codes.)
443 *
444 * @return Integer
445 */
446 public function getStatus() {
447 if ( !$this->respHeaders ) {
448 $this->parseHeader();
449 }
450
451 return (int)$this->respStatus;
452 }
453
454
455 /**
456 * Returns true if the last status code was a redirect.
457 *
458 * @return Boolean
459 */
460 public function isRedirect() {
461 if ( !$this->respHeaders ) {
462 $this->parseHeader();
463 }
464
465 $status = (int)$this->respStatus;
466
467 if ( $status >= 300 && $status <= 303 ) {
468 return true;
469 }
470
471 return false;
472 }
473
474 /**
475 * Returns an associative array of response headers after the
476 * request has been executed. Because some headers
477 * (e.g. Set-Cookie) can appear more than once the, each value of
478 * the associative array is an array of the values given.
479 *
480 * @return Array
481 */
482 public function getResponseHeaders() {
483 if ( !$this->respHeaders ) {
484 $this->parseHeader();
485 }
486
487 return $this->respHeaders;
488 }
489
490 /**
491 * Returns the value of the given response header.
492 *
493 * @param $header String
494 * @return String
495 */
496 public function getResponseHeader( $header ) {
497 if ( !$this->respHeaders ) {
498 $this->parseHeader();
499 }
500
501 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
502 $v = $this->respHeaders[strtolower ( $header ) ];
503 return $v[count( $v ) - 1];
504 }
505
506 return null;
507 }
508
509 /**
510 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
511 *
512 * @param $jar CookieJar
513 */
514 public function setCookieJar( $jar ) {
515 $this->cookieJar = $jar;
516 }
517
518 /**
519 * Returns the cookie jar in use.
520 *
521 * @returns CookieJar
522 */
523 public function getCookieJar() {
524 if ( !$this->respHeaders ) {
525 $this->parseHeader();
526 }
527
528 return $this->cookieJar;
529 }
530
531 /**
532 * Sets a cookie. Used before a request to set up any individual
533 * cookies. Used internally after a request to parse the
534 * Set-Cookie headers.
535 * @see Cookie::set
536 */
537 public function setCookie( $name, $value = null, $attr = null ) {
538 if ( !$this->cookieJar ) {
539 $this->cookieJar = new CookieJar;
540 }
541
542 $this->cookieJar->setCookie( $name, $value, $attr );
543 }
544
545 /**
546 * Parse the cookies in the response headers and store them in the cookie jar.
547 */
548 protected function parseCookies() {
549 if ( !$this->cookieJar ) {
550 $this->cookieJar = new CookieJar;
551 }
552
553 if ( isset( $this->respHeaders['set-cookie'] ) ) {
554 $url = parse_url( $this->getFinalUrl() );
555 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
556 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
557 }
558 }
559 }
560
561 /**
562 * Returns the final URL after all redirections.
563 *
564 * @return String
565 */
566 public function getFinalUrl() {
567 $location = $this->getResponseHeader( "Location" );
568
569 if ( $location ) {
570 return $location;
571 }
572
573 return $this->url;
574 }
575
576 /**
577 * Returns true if the backend can follow redirects. Overridden by the
578 * child classes.
579 */
580 public function canFollowRedirects() {
581 return true;
582 }
583 }
584
585 /**
586 * MWHttpRequest implemented using internal curl compiled into PHP
587 */
588 class CurlHttpRequest extends MWHttpRequest {
589 const SUPPORTS_FILE_POSTS = true;
590
591 static $curlMessageMap = array(
592 6 => 'http-host-unreachable',
593 28 => 'http-timed-out'
594 );
595
596 protected $curlOptions = array();
597 protected $headerText = "";
598
599 protected function readHeader( $fh, $content ) {
600 $this->headerText .= $content;
601 return strlen( $content );
602 }
603
604 public function execute() {
605 parent::execute();
606
607 if ( !$this->status->isOK() ) {
608 return $this->status;
609 }
610
611 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
612 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
613 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
614 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
615 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
616 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
617 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
618
619 /* not sure these two are actually necessary */
620 if ( isset( $this->reqHeaders['Referer'] ) ) {
621 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
622 }
623 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
624
625 if ( isset( $this->sslVerifyHost ) ) {
626 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
627 }
628
629 if ( isset( $this->sslVerifyCert ) ) {
630 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
631 }
632
633 if ( $this->caInfo ) {
634 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
635 }
636
637 if ( $this->headersOnly ) {
638 $this->curlOptions[CURLOPT_NOBODY] = true;
639 $this->curlOptions[CURLOPT_HEADER] = true;
640 } elseif ( $this->method == 'POST' ) {
641 $this->curlOptions[CURLOPT_POST] = true;
642 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
643 // Suppress 'Expect: 100-continue' header, as some servers
644 // will reject it with a 417 and Curl won't auto retry
645 // with HTTP 1.0 fallback
646 $this->reqHeaders['Expect'] = '';
647 } else {
648 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
649 }
650
651 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
652
653 $curlHandle = curl_init( $this->url );
654
655 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
656 throw new MWException( "Error setting curl options." );
657 }
658
659 if ( $this->followRedirects && $this->canFollowRedirects() ) {
660 wfSuppressWarnings();
661 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
662 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
663 "Probably safe_mode or open_basedir is set.\n" );
664 // Continue the processing. If it were in curl_setopt_array,
665 // processing would have halted on its entry
666 }
667 wfRestoreWarnings();
668 }
669
670 if ( false === curl_exec( $curlHandle ) ) {
671 $code = curl_error( $curlHandle );
672
673 if ( isset( self::$curlMessageMap[$code] ) ) {
674 $this->status->fatal( self::$curlMessageMap[$code] );
675 } else {
676 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
677 }
678 } else {
679 $this->headerList = explode( "\r\n", $this->headerText );
680 }
681
682 curl_close( $curlHandle );
683
684 $this->parseHeader();
685 $this->setStatus();
686
687 return $this->status;
688 }
689
690 public function canFollowRedirects() {
691 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
692 wfDebug( "Cannot follow redirects in safe mode\n" );
693 return false;
694 }
695
696 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
697 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
698 return false;
699 }
700
701 return true;
702 }
703 }
704
705 class PhpHttpRequest extends MWHttpRequest {
706 protected function urlToTcp( $url ) {
707 $parsedUrl = parse_url( $url );
708
709 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
710 }
711
712 public function execute() {
713 parent::execute();
714
715 if ( is_array( $this->postData ) ) {
716 $this->postData = wfArrayToCGI( $this->postData );
717 }
718
719 if ( $this->parsedUrl['scheme'] != 'http' &&
720 $this->parsedUrl['scheme'] != 'ftp' &&
721 $this->parsedUrl['scheme'] != 'https' ) {
722 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
723 }
724
725 $this->reqHeaders['Accept'] = "*/*";
726 if ( $this->method == 'POST' ) {
727 // Required for HTTP 1.0 POSTs
728 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
729 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
730 }
731
732 $options = array();
733 if ( $this->proxy && !$this->noProxy ) {
734 $options['proxy'] = $this->urlToTCP( $this->proxy );
735 $options['request_fulluri'] = true;
736 }
737
738 if ( !$this->followRedirects ) {
739 $options['max_redirects'] = 0;
740 } else {
741 $options['max_redirects'] = $this->maxRedirects;
742 }
743
744 $options['method'] = $this->method;
745 $options['header'] = implode( "\r\n", $this->getHeaderList() );
746 // Note that at some future point we may want to support
747 // HTTP/1.1, but we'd have to write support for chunking
748 // in version of PHP < 5.3.1
749 $options['protocol_version'] = "1.0";
750
751 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
752 // Only works on 5.2.10+
753 $options['ignore_errors'] = true;
754
755 if ( $this->postData ) {
756 $options['content'] = $this->postData;
757 }
758
759 $options['timeout'] = $this->timeout;
760
761 $context = stream_context_create( array( 'http' => $options ) );
762
763 $this->headerList = array();
764 $reqCount = 0;
765 $url = $this->url;
766
767 $result = array();
768
769 do {
770 $reqCount++;
771 wfSuppressWarnings();
772 $fh = fopen( $url, "r", false, $context );
773 wfRestoreWarnings();
774
775 if ( !$fh ) {
776 break;
777 }
778
779 $result = stream_get_meta_data( $fh );
780 $this->headerList = $result['wrapper_data'];
781 $this->parseHeader();
782
783 if ( !$this->followRedirects ) {
784 break;
785 }
786
787 # Handle manual redirection
788 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
789 break;
790 }
791 # Check security of URL
792 $url = $this->getResponseHeader( "Location" );
793
794 if ( substr( $url, 0, 7 ) !== 'http://' ) {
795 wfDebug( __METHOD__ . ": insecure redirection\n" );
796 break;
797 }
798 } while ( true );
799
800 $this->setStatus();
801
802 if ( $fh === false ) {
803 $this->status->fatal( 'http-request-error' );
804 return $this->status;
805 }
806
807 if ( $result['timed_out'] ) {
808 $this->status->fatal( 'http-timed-out', $this->url );
809 return $this->status;
810 }
811
812 // If everything went OK, or we recieved some error code
813 // get the response body content.
814 if ( $this->status->isOK()
815 || (int)$this->respStatus >= 300) {
816 while ( !feof( $fh ) ) {
817 $buf = fread( $fh, 8192 );
818
819 if ( $buf === false ) {
820 $this->status->fatal( 'http-read-error' );
821 break;
822 }
823
824 if ( strlen( $buf ) ) {
825 call_user_func( $this->callback, $fh, $buf );
826 }
827 }
828 }
829 fclose( $fh );
830
831 return $this->status;
832 }
833 }