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