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