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