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