More return documentation
[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 * @return int
380 */
381 public function read( $fh, $content ) {
382 $this->content .= $content;
383 return strlen( $content );
384 }
385
386 /**
387 * Take care of whatever is necessary to perform the URI request.
388 *
389 * @return Status
390 */
391 public function execute() {
392 global $wgTitle;
393
394 $this->content = "";
395
396 if ( strtoupper( $this->method ) == "HEAD" ) {
397 $this->headersOnly = true;
398 }
399
400 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
401 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
402 }
403
404 if ( !$this->noProxy ) {
405 $this->proxySetup();
406 }
407
408 if ( !$this->callback ) {
409 $this->setCallback( array( $this, 'read' ) );
410 }
411
412 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
413 $this->setUserAgent( Http::userAgent() );
414 }
415 }
416
417 /**
418 * Parses the headers, including the HTTP status code and any
419 * Set-Cookie headers. This function expectes the headers to be
420 * found in an array in the member variable headerList.
421 */
422 protected function parseHeader() {
423 $lastname = "";
424
425 foreach ( $this->headerList as $header ) {
426 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
427 $this->respVersion = $match[1];
428 $this->respStatus = $match[2];
429 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
430 $last = count( $this->respHeaders[$lastname] ) - 1;
431 $this->respHeaders[$lastname][$last] .= "\r\n$header";
432 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
433 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
434 $lastname = strtolower( $match[1] );
435 }
436 }
437
438 $this->parseCookies();
439 }
440
441 /**
442 * Sets HTTPRequest status member to a fatal value with the error
443 * message if the returned integer value of the status code was
444 * not successful (< 300) or a redirect (>=300 and < 400). (see
445 * RFC2616, section 10,
446 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
447 * list of status codes.)
448 */
449 protected function setStatus() {
450 if ( !$this->respHeaders ) {
451 $this->parseHeader();
452 }
453
454 if ( (int)$this->respStatus > 399 ) {
455 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
456 $this->status->fatal( "http-bad-status", $code, $message );
457 }
458 }
459
460 /**
461 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
462 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
463 * for a list of status codes.)
464 *
465 * @return Integer
466 */
467 public function getStatus() {
468 if ( !$this->respHeaders ) {
469 $this->parseHeader();
470 }
471
472 return (int)$this->respStatus;
473 }
474
475
476 /**
477 * Returns true if the last status code was a redirect.
478 *
479 * @return Boolean
480 */
481 public function isRedirect() {
482 if ( !$this->respHeaders ) {
483 $this->parseHeader();
484 }
485
486 $status = (int)$this->respStatus;
487
488 if ( $status >= 300 && $status <= 303 ) {
489 return true;
490 }
491
492 return false;
493 }
494
495 /**
496 * Returns an associative array of response headers after the
497 * request has been executed. Because some headers
498 * (e.g. Set-Cookie) can appear more than once the, each value of
499 * the associative array is an array of the values given.
500 *
501 * @return Array
502 */
503 public function getResponseHeaders() {
504 if ( !$this->respHeaders ) {
505 $this->parseHeader();
506 }
507
508 return $this->respHeaders;
509 }
510
511 /**
512 * Returns the value of the given response header.
513 *
514 * @param $header String
515 * @return String
516 */
517 public function getResponseHeader( $header ) {
518 if ( !$this->respHeaders ) {
519 $this->parseHeader();
520 }
521
522 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
523 $v = $this->respHeaders[strtolower ( $header ) ];
524 return $v[count( $v ) - 1];
525 }
526
527 return null;
528 }
529
530 /**
531 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
532 *
533 * @param $jar CookieJar
534 */
535 public function setCookieJar( $jar ) {
536 $this->cookieJar = $jar;
537 }
538
539 /**
540 * Returns the cookie jar in use.
541 *
542 * @return CookieJar
543 */
544 public function getCookieJar() {
545 if ( !$this->respHeaders ) {
546 $this->parseHeader();
547 }
548
549 return $this->cookieJar;
550 }
551
552 /**
553 * Sets a cookie. Used before a request to set up any individual
554 * cookies. Used internally after a request to parse the
555 * Set-Cookie headers.
556 * @see Cookie::set
557 * @param $name
558 * @param $value null
559 * @param $attr null
560 */
561 public function setCookie( $name, $value = null, $attr = null ) {
562 if ( !$this->cookieJar ) {
563 $this->cookieJar = new CookieJar;
564 }
565
566 $this->cookieJar->setCookie( $name, $value, $attr );
567 }
568
569 /**
570 * Parse the cookies in the response headers and store them in the cookie jar.
571 */
572 protected function parseCookies() {
573 if ( !$this->cookieJar ) {
574 $this->cookieJar = new CookieJar;
575 }
576
577 if ( isset( $this->respHeaders['set-cookie'] ) ) {
578 $url = parse_url( $this->getFinalUrl() );
579 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
580 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
581 }
582 }
583 }
584
585 /**
586 * Returns the final URL after all redirections.
587 *
588 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
589 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
590 *
591 * Note that the multiple Location: headers are an artifact of CURL -- they
592 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
593 * taken care of (high-level redirect handling rewrite).
594 *
595 * @return string
596 */
597 public function getFinalUrl() {
598 $headers = $this->getResponseHeaders();
599
600 //return full url (fix for incorrect but handled relative location)
601 if ( isset( $headers[ 'location' ] ) ) {
602 $locations = $headers[ 'location' ];
603 $domain = '';
604 $foundRelativeURI = false;
605 $countLocations = count($locations);
606
607 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
608 $url = parse_url( $locations[ $i ] );
609
610 if ( isset($url[ 'host' ]) ) {
611 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
612 break; //found correct URI (with host)
613 } else {
614 $foundRelativeURI = true;
615 }
616 }
617
618 if ( $foundRelativeURI ) {
619 if ( $domain ) {
620 return $domain . $locations[ $countLocations - 1 ];
621 } else {
622 $url = parse_url( $this->url );
623 if ( isset($url[ 'host' ]) ) {
624 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
625 }
626 }
627 } else {
628 return $locations[ $countLocations - 1 ];
629 }
630 }
631
632 return $this->url;
633 }
634
635 /**
636 * Returns true if the backend can follow redirects. Overridden by the
637 * child classes.
638 * @return bool
639 */
640 public function canFollowRedirects() {
641 return true;
642 }
643 }
644
645 /**
646 * MWHttpRequest implemented using internal curl compiled into PHP
647 */
648 class CurlHttpRequest extends MWHttpRequest {
649 const SUPPORTS_FILE_POSTS = true;
650
651 static $curlMessageMap = array(
652 6 => 'http-host-unreachable',
653 28 => 'http-timed-out'
654 );
655
656 protected $curlOptions = array();
657 protected $headerText = "";
658
659 /**
660 * @param $fh
661 * @param $content
662 * @return int
663 */
664 protected function readHeader( $fh, $content ) {
665 $this->headerText .= $content;
666 return strlen( $content );
667 }
668
669 public function execute() {
670 parent::execute();
671
672 if ( !$this->status->isOK() ) {
673 return $this->status;
674 }
675
676 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
677 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
678 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
679 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
680 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
681 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
682 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
683
684 /* not sure these two are actually necessary */
685 if ( isset( $this->reqHeaders['Referer'] ) ) {
686 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
687 }
688 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
689
690 if ( isset( $this->sslVerifyHost ) ) {
691 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
692 }
693
694 if ( isset( $this->sslVerifyCert ) ) {
695 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
696 }
697
698 if ( $this->caInfo ) {
699 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
700 }
701
702 if ( $this->headersOnly ) {
703 $this->curlOptions[CURLOPT_NOBODY] = true;
704 $this->curlOptions[CURLOPT_HEADER] = true;
705 } elseif ( $this->method == 'POST' ) {
706 $this->curlOptions[CURLOPT_POST] = true;
707 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
708 // Suppress 'Expect: 100-continue' header, as some servers
709 // will reject it with a 417 and Curl won't auto retry
710 // with HTTP 1.0 fallback
711 $this->reqHeaders['Expect'] = '';
712 } else {
713 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
714 }
715
716 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
717
718 $curlHandle = curl_init( $this->url );
719
720 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
721 throw new MWException( "Error setting curl options." );
722 }
723
724 if ( $this->followRedirects && $this->canFollowRedirects() ) {
725 wfSuppressWarnings();
726 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
727 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
728 "Probably safe_mode or open_basedir is set.\n" );
729 // Continue the processing. If it were in curl_setopt_array,
730 // processing would have halted on its entry
731 }
732 wfRestoreWarnings();
733 }
734
735 if ( false === curl_exec( $curlHandle ) ) {
736 $code = curl_error( $curlHandle );
737
738 if ( isset( self::$curlMessageMap[$code] ) ) {
739 $this->status->fatal( self::$curlMessageMap[$code] );
740 } else {
741 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
742 }
743 } else {
744 $this->headerList = explode( "\r\n", $this->headerText );
745 }
746
747 curl_close( $curlHandle );
748
749 $this->parseHeader();
750 $this->setStatus();
751
752 return $this->status;
753 }
754
755 /**
756 * @return bool
757 */
758 public function canFollowRedirects() {
759 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
760 wfDebug( "Cannot follow redirects in safe mode\n" );
761 return false;
762 }
763
764 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
765 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
766 return false;
767 }
768
769 return true;
770 }
771 }
772
773 class PhpHttpRequest extends MWHttpRequest {
774
775 /**
776 * @param $url string
777 * @return string
778 */
779 protected function urlToTcp( $url ) {
780 $parsedUrl = parse_url( $url );
781
782 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
783 }
784
785 public function execute() {
786 parent::execute();
787
788 if ( is_array( $this->postData ) ) {
789 $this->postData = wfArrayToCGI( $this->postData );
790 }
791
792 if ( $this->parsedUrl['scheme'] != 'http' &&
793 $this->parsedUrl['scheme'] != 'https' ) {
794 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
795 }
796
797 $this->reqHeaders['Accept'] = "*/*";
798 if ( $this->method == 'POST' ) {
799 // Required for HTTP 1.0 POSTs
800 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
801 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
802 }
803
804 $options = array();
805 if ( $this->proxy && !$this->noProxy ) {
806 $options['proxy'] = $this->urlToTCP( $this->proxy );
807 $options['request_fulluri'] = true;
808 }
809
810 if ( !$this->followRedirects ) {
811 $options['max_redirects'] = 0;
812 } else {
813 $options['max_redirects'] = $this->maxRedirects;
814 }
815
816 $options['method'] = $this->method;
817 $options['header'] = implode( "\r\n", $this->getHeaderList() );
818 // Note that at some future point we may want to support
819 // HTTP/1.1, but we'd have to write support for chunking
820 // in version of PHP < 5.3.1
821 $options['protocol_version'] = "1.0";
822
823 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
824 // Only works on 5.2.10+
825 $options['ignore_errors'] = true;
826
827 if ( $this->postData ) {
828 $options['content'] = $this->postData;
829 }
830
831 $options['timeout'] = $this->timeout;
832
833 $context = stream_context_create( array( 'http' => $options ) );
834
835 $this->headerList = array();
836 $reqCount = 0;
837 $url = $this->url;
838
839 $result = array();
840
841 do {
842 $reqCount++;
843 wfSuppressWarnings();
844 $fh = fopen( $url, "r", false, $context );
845 wfRestoreWarnings();
846
847 if ( !$fh ) {
848 break;
849 }
850
851 $result = stream_get_meta_data( $fh );
852 $this->headerList = $result['wrapper_data'];
853 $this->parseHeader();
854
855 if ( !$this->followRedirects ) {
856 break;
857 }
858
859 # Handle manual redirection
860 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
861 break;
862 }
863 # Check security of URL
864 $url = $this->getResponseHeader( "Location" );
865
866 if ( !Http::isValidURI( $url ) ) {
867 wfDebug( __METHOD__ . ": insecure redirection\n" );
868 break;
869 }
870 } while ( true );
871
872 $this->setStatus();
873
874 if ( $fh === false ) {
875 $this->status->fatal( 'http-request-error' );
876 return $this->status;
877 }
878
879 if ( $result['timed_out'] ) {
880 $this->status->fatal( 'http-timed-out', $this->url );
881 return $this->status;
882 }
883
884 // If everything went OK, or we recieved some error code
885 // get the response body content.
886 if ( $this->status->isOK()
887 || (int)$this->respStatus >= 300) {
888 while ( !feof( $fh ) ) {
889 $buf = fread( $fh, 8192 );
890
891 if ( $buf === false ) {
892 $this->status->fatal( 'http-read-error' );
893 break;
894 }
895
896 if ( strlen( $buf ) ) {
897 call_user_func( $this->callback, $fh, $buf );
898 }
899 }
900 }
901 fclose( $fh );
902
903 return $this->status;
904 }
905 }