Relative values of the "Location" header are incorrect as stated in RFC, however...
[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 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
573 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
574 *
575 * @returns string
576 */
577 public function getFinalUrl() {
578 $headers = $this->getResponseHeaders();
579
580 //return full url (fix for incorrect but handled relative location)
581 if ( isset( $headers[ 'location' ] ) ) {
582 $locations = $headers[ 'location' ];
583 $domain = '';
584 $foundRelativeURI = false;
585 $countLocations = count($locations);
586
587 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
588 $url = parse_url( $locations[ $i ] );
589
590 if ( isset($url[ 'host' ]) ) {
591 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
592 break; //found correct URI (with host)
593 } else {
594 $foundRelativeURI = true;
595 }
596 }
597
598 if ( $foundRelativeURI ) {
599 if ( $domain ) {
600 return $domain . $locations[ $countLocations - 1 ];
601 } else {
602 $url = parse_url( $this->url );
603 if ( isset($url[ 'host' ]) ) {
604 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
605 }
606 }
607 } else {
608 return $locations[ $countLocations - 1 ];
609 }
610 }
611
612 return $this->url;
613 }
614
615 /**
616 * Returns true if the backend can follow redirects. Overridden by the
617 * child classes.
618 */
619 public function canFollowRedirects() {
620 return true;
621 }
622 }
623
624 /**
625 * MWHttpRequest implemented using internal curl compiled into PHP
626 */
627 class CurlHttpRequest extends MWHttpRequest {
628 const SUPPORTS_FILE_POSTS = true;
629
630 static $curlMessageMap = array(
631 6 => 'http-host-unreachable',
632 28 => 'http-timed-out'
633 );
634
635 protected $curlOptions = array();
636 protected $headerText = "";
637
638 protected function readHeader( $fh, $content ) {
639 $this->headerText .= $content;
640 return strlen( $content );
641 }
642
643 public function execute() {
644 parent::execute();
645
646 if ( !$this->status->isOK() ) {
647 return $this->status;
648 }
649
650 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
651 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
652 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
653 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
654 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
655 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
656 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
657
658 /* not sure these two are actually necessary */
659 if ( isset( $this->reqHeaders['Referer'] ) ) {
660 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
661 }
662 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
663
664 if ( isset( $this->sslVerifyHost ) ) {
665 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
666 }
667
668 if ( isset( $this->sslVerifyCert ) ) {
669 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
670 }
671
672 if ( $this->caInfo ) {
673 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
674 }
675
676 if ( $this->headersOnly ) {
677 $this->curlOptions[CURLOPT_NOBODY] = true;
678 $this->curlOptions[CURLOPT_HEADER] = true;
679 } elseif ( $this->method == 'POST' ) {
680 $this->curlOptions[CURLOPT_POST] = true;
681 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
682 // Suppress 'Expect: 100-continue' header, as some servers
683 // will reject it with a 417 and Curl won't auto retry
684 // with HTTP 1.0 fallback
685 $this->reqHeaders['Expect'] = '';
686 } else {
687 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
688 }
689
690 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
691
692 $curlHandle = curl_init( $this->url );
693
694 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
695 throw new MWException( "Error setting curl options." );
696 }
697
698 if ( $this->followRedirects && $this->canFollowRedirects() ) {
699 wfSuppressWarnings();
700 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
701 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
702 "Probably safe_mode or open_basedir is set.\n" );
703 // Continue the processing. If it were in curl_setopt_array,
704 // processing would have halted on its entry
705 }
706 wfRestoreWarnings();
707 }
708
709 if ( false === curl_exec( $curlHandle ) ) {
710 $code = curl_error( $curlHandle );
711
712 if ( isset( self::$curlMessageMap[$code] ) ) {
713 $this->status->fatal( self::$curlMessageMap[$code] );
714 } else {
715 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
716 }
717 } else {
718 $this->headerList = explode( "\r\n", $this->headerText );
719 }
720
721 curl_close( $curlHandle );
722
723 $this->parseHeader();
724 $this->setStatus();
725
726 return $this->status;
727 }
728
729 public function canFollowRedirects() {
730 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
731 wfDebug( "Cannot follow redirects in safe mode\n" );
732 return false;
733 }
734
735 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
736 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
737 return false;
738 }
739
740 return true;
741 }
742 }
743
744 class PhpHttpRequest extends MWHttpRequest {
745 protected function urlToTcp( $url ) {
746 $parsedUrl = parse_url( $url );
747
748 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
749 }
750
751 public function execute() {
752 parent::execute();
753
754 if ( is_array( $this->postData ) ) {
755 $this->postData = wfArrayToCGI( $this->postData );
756 }
757
758 if ( $this->parsedUrl['scheme'] != 'http' &&
759 $this->parsedUrl['scheme'] != 'https' ) {
760 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
761 }
762
763 $this->reqHeaders['Accept'] = "*/*";
764 if ( $this->method == 'POST' ) {
765 // Required for HTTP 1.0 POSTs
766 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
767 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
768 }
769
770 $options = array();
771 if ( $this->proxy && !$this->noProxy ) {
772 $options['proxy'] = $this->urlToTCP( $this->proxy );
773 $options['request_fulluri'] = true;
774 }
775
776 if ( !$this->followRedirects ) {
777 $options['max_redirects'] = 0;
778 } else {
779 $options['max_redirects'] = $this->maxRedirects;
780 }
781
782 $options['method'] = $this->method;
783 $options['header'] = implode( "\r\n", $this->getHeaderList() );
784 // Note that at some future point we may want to support
785 // HTTP/1.1, but we'd have to write support for chunking
786 // in version of PHP < 5.3.1
787 $options['protocol_version'] = "1.0";
788
789 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
790 // Only works on 5.2.10+
791 $options['ignore_errors'] = true;
792
793 if ( $this->postData ) {
794 $options['content'] = $this->postData;
795 }
796
797 $options['timeout'] = $this->timeout;
798
799 $context = stream_context_create( array( 'http' => $options ) );
800
801 $this->headerList = array();
802 $reqCount = 0;
803 $url = $this->url;
804
805 $result = array();
806
807 do {
808 $reqCount++;
809 wfSuppressWarnings();
810 $fh = fopen( $url, "r", false, $context );
811 wfRestoreWarnings();
812
813 if ( !$fh ) {
814 break;
815 }
816
817 $result = stream_get_meta_data( $fh );
818 $this->headerList = $result['wrapper_data'];
819 $this->parseHeader();
820
821 if ( !$this->followRedirects ) {
822 break;
823 }
824
825 # Handle manual redirection
826 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
827 break;
828 }
829 # Check security of URL
830 $url = $this->getResponseHeader( "Location" );
831
832 if ( substr( $url, 0, 7 ) !== 'http://' ) {
833 wfDebug( __METHOD__ . ": insecure redirection\n" );
834 break;
835 }
836 } while ( true );
837
838 $this->setStatus();
839
840 if ( $fh === false ) {
841 $this->status->fatal( 'http-request-error' );
842 return $this->status;
843 }
844
845 if ( $result['timed_out'] ) {
846 $this->status->fatal( 'http-timed-out', $this->url );
847 return $this->status;
848 }
849
850 // If everything went OK, or we recieved some error code
851 // get the response body content.
852 if ( $this->status->isOK()
853 || (int)$this->respStatus >= 300) {
854 while ( !feof( $fh ) ) {
855 $buf = fread( $fh, 8192 );
856
857 if ( $buf === false ) {
858 $this->status->fatal( 'http-read-error' );
859 break;
860 }
861
862 if ( strlen( $buf ) ) {
863 call_user_func( $this->callback, $fh, $buf );
864 }
865 }
866 }
867 fclose( $fh );
868
869 return $this->status;
870 }
871 }