Add a bunch of tests and checks for cookie domain security.
[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 * @param $method string HTTP method. Usually GET/POST
16 * @param $url string Full URL to act on
17 * @param $options options to pass to HttpRequest object
18 * Possible keys for the array:
19 * timeout Timeout length in seconds
20 * postData An array of key-value pairs or a url-encoded form data
21 * proxy The proxy to use. Will use $wgHTTPProxy (if set) otherwise.
22 * noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
23 * sslVerifyHost (curl only) Verify the SSL certificate
24 * caInfo (curl only) Provide CA information
25 * maxRedirects Maximum number of redirects to follow (defaults to 5)
26 * followRedirects Whether to follow redirects (defaults to true)
27 * @returns mixed (bool)false on failure or a string on success
28 */
29 public static function request( $method, $url, $options = array() ) {
30 wfDebug( "HTTP: $method: $url" );
31 $options['method'] = strtoupper( $method );
32 if ( !isset( $options['timeout'] ) ) {
33 $options['timeout'] = 'default';
34 }
35 $req = HttpRequest::factory( $url, $options );
36 $status = $req->execute();
37 if ( $status->isOK() ) {
38 return $req->getContent();
39 } else {
40 return false;
41 }
42 }
43
44 /**
45 * Simple wrapper for Http::request( 'GET' )
46 * @see Http::request()
47 */
48 public static function get( $url, $timeout = 'default', $options = array() ) {
49 $options['timeout'] = $timeout;
50 return Http::request( 'GET', $url, $options );
51 }
52
53 /**
54 * Simple wrapper for Http::request( 'POST' )
55 * @see Http::request()
56 */
57 public static function post( $url, $options = array() ) {
58 return Http::request( 'POST', $url, $options );
59 }
60
61 /**
62 * Check if the URL can be served by localhost
63 * @param $url string Full url to check
64 * @return bool
65 */
66 public static function isLocalURL( $url ) {
67 global $wgCommandLineMode, $wgConf;
68 if ( $wgCommandLineMode ) {
69 return false;
70 }
71
72 // Extract host part
73 $matches = array();
74 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
75 $host = $matches[1];
76 // Split up dotwise
77 $domainParts = explode( '.', $host );
78 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
79 $domainParts = array_reverse( $domainParts );
80 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
81 $domainPart = $domainParts[$i];
82 if ( $i == 0 ) {
83 $domain = $domainPart;
84 } else {
85 $domain = $domainPart . '.' . $domain;
86 }
87 if ( $wgConf->isLocalVHost( $domain ) ) {
88 return true;
89 }
90 }
91 }
92 return false;
93 }
94
95 /**
96 * A standard user-agent we can use for external requests.
97 * @returns string
98 */
99 public static function userAgent() {
100 global $wgVersion;
101 return "MediaWiki/$wgVersion";
102 }
103
104 /**
105 * Checks that the given URI is a valid one
106 * @param $uri Mixed: URI to check for validity
107 * @returns bool
108 */
109 public static function isValidURI( $uri ) {
110 return preg_match(
111 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
112 $uri,
113 $matches
114 );
115 }
116 }
117
118 /**
119 * This wrapper class will call out to curl (if available) or fallback
120 * to regular PHP if necessary for handling internal HTTP requests.
121 */
122 class HttpRequest {
123 protected $content;
124 protected $timeout = 'default';
125 protected $headersOnly = null;
126 protected $postData = null;
127 protected $proxy = null;
128 protected $noProxy = false;
129 protected $sslVerifyHost = true;
130 protected $caInfo = null;
131 protected $method = "GET";
132 protected $reqHeaders = array();
133 protected $url;
134 protected $parsedUrl;
135 protected $callback;
136 protected $maxRedirects = 5;
137 protected $followRedirects = true;
138
139 protected $cookieJar;
140
141 protected $headerList = array();
142 protected $respVersion = "0.9";
143 protected $respStatus = "0.1";
144 protected $respHeaders = array();
145
146 public $status;
147
148 /**
149 * @param $url string url to use
150 * @param $options array (optional) extra params to pass (see Http::request())
151 */
152 function __construct( $url, $options = array() ) {
153 global $wgHTTPTimeout;
154
155 $this->url = $url;
156 $this->parsedUrl = parse_url( $url );
157
158 if ( !Http::isValidURI( $this->url ) ) {
159 $this->status = Status::newFromFatal('http-invalid-url');
160 } else {
161 $this->status = Status::newGood( 100 ); // continue
162 }
163
164 if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
165 $this->timeout = $options['timeout'];
166 } else {
167 $this->timeout = $wgHTTPTimeout;
168 }
169
170 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
171 "method", "followRedirects", "maxRedirects" );
172 foreach ( $members as $o ) {
173 if ( isset($options[$o]) ) {
174 $this->$o = $options[$o];
175 }
176 }
177 }
178
179 /**
180 * Generate a new request object
181 * @see HttpRequest::__construct
182 */
183 public static function factory( $url, $options = null ) {
184 if ( !Http::$httpEngine ) {
185 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
186 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
187 throw new MWException( __METHOD__.': curl (http://php.net/curl) is not installed, but'.
188 ' Http::$httpEngine is set to "curl"' );
189 }
190
191 switch( Http::$httpEngine ) {
192 case 'curl':
193 return new CurlHttpRequest( $url, $options );
194 case 'php':
195 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
196 throw new MWException( __METHOD__.': allow_url_fopen needs to be enabled for pure PHP'.
197 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
198 }
199 return new PhpHttpRequest( $url, $options );
200 default:
201 throw new MWException( __METHOD__.': The setting of Http::$httpEngine is not valid.' );
202 }
203 }
204
205 /**
206 * Get the body, or content, of the response to the request
207 * @return string
208 */
209 public function getContent() {
210 return $this->content;
211 }
212
213 /**
214 * Take care of setting up the proxy
215 * (override in subclass)
216 * @return string
217 */
218 public function proxySetup() {
219 global $wgHTTPProxy;
220
221 if ( $this->proxy ) {
222 return;
223 }
224 if ( Http::isLocalURL( $this->url ) ) {
225 $this->proxy = 'http://localhost:80/';
226 } elseif ( $wgHTTPProxy ) {
227 $this->proxy = $wgHTTPProxy ;
228 }
229 }
230
231 /**
232 * Set the refererer header
233 */
234 public function setReferer( $url ) {
235 $this->setHeader('Referer', $url);
236 }
237
238 /**
239 * Set the user agent
240 */
241 public function setUserAgent( $UA ) {
242 $this->setHeader('User-Agent', $UA);
243 }
244
245 /**
246 * Set an arbitrary header
247 */
248 public function setHeader($name, $value) {
249 // I feel like I should normalize the case here...
250 $this->reqHeaders[$name] = $value;
251 }
252
253 /**
254 * Get an array of the headers
255 */
256 public function getHeaderList() {
257 $list = array();
258
259 if( $this->cookieJar ) {
260 $this->reqHeaders['Cookie'] =
261 $this->cookieJar->serializeToHttpRequest($this->parsedURL['path'],
262 $this->parsedURL['host']);
263 }
264 foreach($this->reqHeaders as $name => $value) {
265 $list[] = "$name: $value";
266 }
267 return $list;
268 }
269
270 /**
271 * Set the callback
272 * @param $callback callback
273 */
274 public function setCallback( $callback ) {
275 $this->callback = $callback;
276 }
277
278 /**
279 * A generic callback to read the body of the response from a remote
280 * server.
281 * @param $fh handle
282 * @param $content string
283 */
284 public function read( $fh, $content ) {
285 $this->content .= $content;
286 return strlen( $content );
287 }
288
289 /**
290 * Take care of whatever is necessary to perform the URI request.
291 * @return Status
292 */
293 public function execute() {
294 global $wgTitle;
295
296 if( strtoupper($this->method) == "HEAD" ) {
297 $this->headersOnly = true;
298 }
299
300 if ( is_array( $this->postData ) ) {
301 $this->postData = wfArrayToCGI( $this->postData );
302 }
303
304 if ( is_object( $wgTitle ) && !isset($this->reqHeaders['Referer']) ) {
305 $this->setReferer( $wgTitle->getFullURL() );
306 }
307
308 if ( !$this->noProxy ) {
309 $this->proxySetup();
310 }
311
312 if ( !$this->callback ) {
313 $this->setCallback( array( $this, 'read' ) );
314 }
315
316 if ( !isset($this->reqHeaders['User-Agent']) ) {
317 $this->setUserAgent(Http::userAgent());
318 }
319 }
320
321 protected function parseHeader() {
322 $lastname = "";
323 foreach( $this->headerList as $header ) {
324 if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
325 $this->respVersion = $match[1];
326 $this->respStatus = $match[2];
327 } elseif( preg_match( "#^[ \t]#", $header ) ) {
328 $last = count($this->respHeaders[$lastname]) - 1;
329 $this->respHeaders[$lastname][$last] .= "\r\n$header";
330 } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
331 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
332 $lastname = strtolower( $match[1] );
333 }
334 }
335
336 $this->parseCookies();
337 }
338
339 /**
340 * Returns an associative array of response headers after the
341 * request has been executed. Because some headers
342 * (e.g. Set-Cookie) can appear more than once the, each value of
343 * the associative array is an array of the values given.
344 * @return array
345 */
346 public function getResponseHeaders() {
347 if( !$this->respHeaders ) {
348 $this->parseHeader();
349 }
350 return $this->respHeaders;
351 }
352
353 /**
354 * Tells the HttpRequest object to use this pre-loaded CookieJar.
355 * @param $jar CookieJar
356 */
357 public function setCookieJar( $jar ) {
358 $this->cookieJar = $jar;
359 }
360
361 /**
362 * Returns the cookie jar in use.
363 * @returns CookieJar
364 */
365 public function getCookieJar() {
366 if( !$this->respHeaders ) {
367 $this->parseHeader();
368 }
369 return $this->cookieJar;
370 }
371
372 /**
373 * Sets a cookie. Used before a request to set up any individual
374 * cookies. Used internally after a request to parse the
375 * Set-Cookie headers.
376 * @see Cookie::set
377 */
378 public function setCookie( $name, $value = null, $attr = null) {
379 if( !$this->cookieJar ) {
380 $this->cookieJar = new CookieJar;
381 }
382 $this->cookieJar->setCookie($name, $value, $attr);
383 }
384
385 /**
386 * Parse the cookies in the response headers and store them in the cookie jar.
387 */
388 protected function parseCookies() {
389 if( !$this->cookieJar ) {
390 $this->cookieJar = new CookieJar;
391 }
392 if( isset( $this->respHeaders['set-cookie'] ) ) {
393 $url = parse_url( $this->getFinalUrl() );
394 foreach( $this->respHeaders['set-cookie'] as $cookie ) {
395 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
396 }
397 }
398 }
399
400 /**
401 * Returns the final URL after all redirections.
402 * @returns string
403 */
404 public function getFinalUrl() {
405 $finalUrl = $this->url;
406 if ( isset( $this->respHeaders['location'] ) ) {
407 $redir = $this->respHeaders['location'];
408 $finalUrl = $redir[count($redir) - 1];
409 }
410
411 return $finalUrl;
412 }
413 }
414
415
416 class Cookie {
417 protected $name;
418 protected $value;
419 protected $expires;
420 protected $path;
421 protected $domain;
422 protected $isSessionKey = true;
423 // TO IMPLEMENT protected $secure
424 // TO IMPLEMENT? protected $maxAge (add onto expires)
425 // TO IMPLEMENT? protected $version
426 // TO IMPLEMENT? protected $comment
427
428 function __construct( $name, $value, $attr ) {
429 $this->name = $name;
430 $this->set( $value, $attr );
431 }
432
433 /**
434 * Sets a cookie. Used before a request to set up any individual
435 * cookies. Used internally after a request to parse the
436 * Set-Cookie headers.
437 * @param $name string the name of the cookie
438 * @param $value string the value of the cookie
439 * @param $attr array possible key/values:
440 * expires A date string
441 * path The path this cookie is used on
442 * domain Domain this cookie is used on
443 */
444 public function set( $value, $attr ) {
445 $this->value = $value;
446 if( isset( $attr['expires'] ) ) {
447 $this->isSessionKey = false;
448 $this->expires = strtotime( $attr['expires'] );
449 }
450 if( isset( $attr['path'] ) ) {
451 $this->path = $attr['path'];
452 } else {
453 $this->path = "/";
454 }
455 if( isset( $attr['domain'] ) ) {
456 if( self::validateCookieDomain( $attr['domain'] ) ) {
457 $this->domain = $attr['domain'];
458 }
459 } else {
460 throw new MWException("You must specify a domain.");
461 }
462 }
463
464 /**
465 * Return the true if the cookie is valid is valid. Otherwise,
466 * false. The uses a method similar to IE cookie security
467 * described here:
468 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
469 * A better method might be to use a blacklist like
470 * http://publicsuffix.org/
471 *
472 * @param $domain string the domain to validate
473 * @param $originDomain string (optional) the domain the cookie originates from
474 * @return bool
475 */
476 public static function validateCookieDomain( $domain, $originDomain = null) {
477 // Don't allow a trailing dot
478 if( substr( $domain, -1 ) == "." ) return false;
479
480 $dc = explode(".", $domain);
481
482 // Don't allow cookies for "localhost", "ls" or other dot-less hosts
483 if( count($dc) < 2 ) return false;
484
485 // Only allow full, valid IP addresses
486 if( preg_match( '/^[0-9.]+$/', $domain ) ) {
487 if( count( $dc ) != 4 ) return false;
488
489 if( ip2long( $domain ) === false ) return false;
490
491 if( $originDomain == null || $originDomain == $domain ) return true;
492
493 }
494
495 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
496 if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
497 if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
498 || (count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
499 return false;
500 }
501 if( (count($dc) == 2 || (count($dc) == 3 && $dc[0] == "") )
502 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
503 return false;
504 }
505 }
506
507 if( $originDomain != null ) {
508 if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
509 return false;
510 }
511 if( substr( $domain, 0, 1 ) == "."
512 && substr_compare( $originDomain, $domain, -strlen( $domain ),
513 strlen( $domain ), TRUE ) != 0 ) {
514 return false;
515 }
516 }
517
518 return true;
519 }
520
521 /**
522 * Serialize the cookie jar into a format useful for HTTP Request headers.
523 * @param $path string the path that will be used. Required.
524 * @param $domain string the domain that will be used. Required.
525 * @return string
526 */
527 public function serializeToHttpRequest( $path, $domain ) {
528 $ret = "";
529
530 if( $this->canServeDomain( $domain )
531 && $this->canServePath( $path )
532 && $this->isUnExpired() ) {
533 $ret = $this->name ."=". $this->value;
534 }
535
536 return $ret;
537 }
538
539 protected function canServeDomain( $domain ) {
540 if( $domain == $this->domain
541 || ( substr( $this->domain, 0, 1) == "."
542 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
543 strlen( $this->domain ), TRUE ) == 0 ) ) {
544 return true;
545 }
546 return false;
547 }
548
549 protected function canServePath( $path ) {
550 if( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
551 return true;
552 }
553 return false;
554 }
555
556 protected function isUnExpired() {
557 if( $this->isSessionKey || $this->expires > time() ) {
558 return true;
559 }
560 return false;
561 }
562
563 }
564
565 class CookieJar {
566 private $cookie = array();
567
568 /**
569 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
570 * @see Cookie::set()
571 */
572 public function setCookie ($name, $value, $attr) {
573 /* cookies: case insensitive, so this should work.
574 * We'll still send the cookies back in the same case we got them, though.
575 */
576 $index = strtoupper($name);
577 if( isset( $this->cookie[$index] ) ) {
578 $this->cookie[$index]->set( $value, $attr );
579 } else {
580 $this->cookie[$index] = new Cookie( $name, $value, $attr );
581 }
582 }
583
584 /**
585 * @see Cookie::serializeToHttpRequest
586 */
587 public function serializeToHttpRequest( $path, $domain ) {
588 $cookies = array();
589
590 foreach( $this->cookie as $c ) {
591 $serialized = $c->serializeToHttpRequest( $path, $domain );
592 if ( $serialized ) $cookies[] = $serialized;
593 }
594
595 return implode("; ", $cookies);
596 }
597
598 /**
599 * Parse the content of an Set-Cookie HTTP Response header.
600 * @param $cookie string
601 */
602 public function parseCookieResponseHeader ( $cookie, $domain ) {
603 $len = strlen( "Set-Cookie:" );
604 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
605 $cookie = substr( $cookie, $len );
606 }
607
608 $bit = array_map( 'trim', explode( ";", $cookie ) );
609 if ( count($bit) >= 1 ) {
610 list($name, $value) = explode( "=", array_shift( $bit ), 2 );
611 $attr = array();
612 foreach( $bit as $piece ) {
613 $parts = explode( "=", $piece );
614 if( count( $parts ) > 1 ) {
615 $attr[strtolower( $parts[0] )] = $parts[1];
616 } else {
617 $attr[strtolower( $parts[0] )] = true;
618 }
619 }
620
621 if( !isset( $attr['domain'] ) ) {
622 $attr['domain'] = $domain;
623 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
624 return null;
625 }
626
627 $this->setCookie( $name, $value, $attr );
628 }
629 }
630 }
631
632
633 /**
634 * HttpRequest implemented using internal curl compiled into PHP
635 */
636 class CurlHttpRequest extends HttpRequest {
637 static $curlMessageMap = array(
638 6 => 'http-host-unreachable',
639 28 => 'http-timed-out'
640 );
641
642 protected $curlOptions = array();
643 protected $headerText = "";
644
645 protected function readHeader( $fh, $content ) {
646 $this->headerText .= $content;
647 return strlen( $content );
648 }
649
650 public function execute() {
651 parent::execute();
652 if ( !$this->status->isOK() ) {
653 return $this->status;
654 }
655 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
656 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
657 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
658 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
659 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array($this, "readHeader");
660 $this->curlOptions[CURLOPT_FOLLOWLOCATION] = $this->followRedirects;
661 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
662
663 /* not sure these two are actually necessary */
664 if(isset($this->reqHeaders['Referer'])) {
665 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
666 }
667 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
668
669 if ( $this->sslVerifyHost ) {
670 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
671 }
672
673 if ( $this->caInfo ) {
674 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
675 }
676
677 if ( $this->headersOnly ) {
678 $this->curlOptions[CURLOPT_NOBODY] = true;
679 $this->curlOptions[CURLOPT_HEADER] = true;
680 } elseif ( $this->method == 'POST' ) {
681 $this->curlOptions[CURLOPT_POST] = true;
682 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
683 // Suppress 'Expect: 100-continue' header, as some servers
684 // will reject it with a 417 and Curl won't auto retry
685 // with HTTP 1.0 fallback
686 $this->reqHeaders['Expect'] = '';
687 } else {
688 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
689 }
690
691 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
692
693 $curlHandle = curl_init( $this->url );
694 curl_setopt_array( $curlHandle, $this->curlOptions );
695
696 if ( false === curl_exec( $curlHandle ) ) {
697 $code = curl_error( $curlHandle );
698
699 if ( isset( self::$curlMessageMap[$code] ) ) {
700 $this->status->fatal( self::$curlMessageMap[$code] );
701 } else {
702 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
703 }
704 } else {
705 $this->headerList = explode("\r\n", $this->headerText);
706 }
707
708 curl_close( $curlHandle );
709
710 return $this->status;
711 }
712 }
713
714 class PhpHttpRequest extends HttpRequest {
715 protected function urlToTcp( $url ) {
716 $parsedUrl = parse_url( $url );
717
718 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
719 }
720
721 public function execute() {
722 if ( $this->parsedUrl['scheme'] != 'http' ) {
723 $this->status->fatal( 'http-invalid-scheme', $this->parsedURL['scheme'] );
724 }
725
726 parent::execute();
727 if ( !$this->status->isOK() ) {
728 return $this->status;
729 }
730
731 $this->reqHeaders['Accept'] = "*/*";
732 if ( $this->method == 'POST' ) {
733 // Required for HTTP 1.0 POSTs
734 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
735 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
736 }
737
738 $options = array();
739 if ( $this->proxy && !$this->noProxy ) {
740 $options['proxy'] = $this->urlToTCP( $this->proxy );
741 $options['request_fulluri'] = true;
742 }
743
744 if ( !$this->followRedirects ) {
745 $options['max_redirects'] = 0;
746 } else {
747 $options['max_redirects'] = $this->maxRedirects;
748 }
749
750 $options['method'] = $this->method;
751 $options['timeout'] = $this->timeout;
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 if ( $this->postData ) {
759 $options['content'] = $this->postData;
760 }
761
762 $oldTimeout = false;
763 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
764 $oldTimeout = ini_set('default_socket_timeout', $this->timeout);
765 }
766
767 $context = stream_context_create( array( 'http' => $options ) );
768 wfSuppressWarnings();
769 $fh = fopen( $this->url, "r", false, $context );
770 wfRestoreWarnings();
771 if ( $oldTimeout !== false ) {
772 ini_set('default_socket_timeout', $oldTimeout);
773 }
774 if ( $fh === false ) {
775 $this->status->fatal( 'http-request-error' );
776 return $this->status;
777 }
778
779 $result = stream_get_meta_data( $fh );
780 if ( $result['timed_out'] ) {
781 $this->status->fatal( 'http-timed-out', $this->url );
782 return $this->status;
783 }
784 $this->headerList = $result['wrapper_data'];
785
786 while ( !feof( $fh ) ) {
787 $buf = fread( $fh, 8192 );
788 if ( $buf === false ) {
789 $this->status->fatal( 'http-read-error' );
790 break;
791 }
792 if ( strlen( $buf ) ) {
793 call_user_func( $this->callback, $fh, $buf );
794 }
795 }
796 fclose( $fh );
797
798 return $this->status;
799 }
800 }