Make userAgent also work as an option to MWHttpRequest::factory() and MWHttpRequest...
[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
224 /**
225 * Simple function to test if we can make any sort of requests at all, using
226 * cURL or fopen()
227 * @return bool
228 */
229 public static function canMakeRequests() {
230 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
231 }
232
233 /**
234 * Generate a new request object
235 * @param $url String: url to use
236 * @param $options Array: (optional) extra params to pass (see Http::request())
237 * @return CurlHttpRequest|PhpHttpRequest
238 * @see MWHttpRequest::__construct
239 */
240 public static function factory( $url, $options = null ) {
241 if ( !Http::$httpEngine ) {
242 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
243 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
244 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
245 ' Http::$httpEngine is set to "curl"' );
246 }
247
248 switch( Http::$httpEngine ) {
249 case 'curl':
250 return new CurlHttpRequest( $url, $options );
251 case 'php':
252 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
253 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
254 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
255 }
256 return new PhpHttpRequest( $url, $options );
257 default:
258 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
259 }
260 }
261
262 /**
263 * Get the body, or content, of the response to the request
264 *
265 * @return String
266 */
267 public function getContent() {
268 return $this->content;
269 }
270
271 /**
272 * Set the parameters of the request
273
274 * @param $args Array
275 * @todo overload the args param
276 */
277 public function setData( $args ) {
278 $this->postData = $args;
279 }
280
281 /**
282 * Take care of setting up the proxy
283 * (override in subclass)
284 *
285 * @return String
286 */
287 public function proxySetup() {
288 global $wgHTTPProxy;
289
290 if ( $this->proxy && !$this->noProxy ) {
291 return;
292 }
293
294 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
295 $this->proxy = '';
296 } elseif ( $wgHTTPProxy ) {
297 $this->proxy = $wgHTTPProxy ;
298 } elseif ( getenv( "http_proxy" ) ) {
299 $this->proxy = getenv( "http_proxy" );
300 }
301 }
302
303 /**
304 * Set the refererer header
305 */
306 public function setReferer( $url ) {
307 $this->setHeader( 'Referer', $url );
308 }
309
310 /**
311 * Set the user agent
312 * @param $UA string
313 */
314 public function setUserAgent( $UA ) {
315 $this->setHeader( 'User-Agent', $UA );
316 }
317
318 /**
319 * Set an arbitrary header
320 * @param $name
321 * @param $value
322 */
323 public function setHeader( $name, $value ) {
324 // I feel like I should normalize the case here...
325 $this->reqHeaders[$name] = $value;
326 }
327
328 /**
329 * Get an array of the headers
330 * @return array
331 */
332 public function getHeaderList() {
333 $list = array();
334
335 if ( $this->cookieJar ) {
336 $this->reqHeaders['Cookie'] =
337 $this->cookieJar->serializeToHttpRequest(
338 $this->parsedUrl['path'],
339 $this->parsedUrl['host']
340 );
341 }
342
343 foreach ( $this->reqHeaders as $name => $value ) {
344 $list[] = "$name: $value";
345 }
346
347 return $list;
348 }
349
350 /**
351 * Set a read callback to accept data read from the HTTP request.
352 * By default, data is appended to an internal buffer which can be
353 * retrieved through $req->getContent().
354 *
355 * To handle data as it comes in -- especially for large files that
356 * would not fit in memory -- you can instead set your own callback,
357 * in the form function($resource, $buffer) where the first parameter
358 * is the low-level resource being read (implementation specific),
359 * and the second parameter is the data buffer.
360 *
361 * You MUST return the number of bytes handled in the buffer; if fewer
362 * bytes are reported handled than were passed to you, the HTTP fetch
363 * will be aborted.
364 *
365 * @param $callback Callback
366 */
367 public function setCallback( $callback ) {
368 if ( !is_callable( $callback ) ) {
369 throw new MWException( 'Invalid MwHttpRequest callback' );
370 }
371 $this->callback = $callback;
372 }
373
374 /**
375 * A generic callback to read the body of the response from a remote
376 * server.
377 *
378 * @param $fh handle
379 * @param $content String
380 * @return int
381 */
382 public function read( $fh, $content ) {
383 $this->content .= $content;
384 return strlen( $content );
385 }
386
387 /**
388 * Take care of whatever is necessary to perform the URI request.
389 *
390 * @return Status
391 */
392 public function execute() {
393 global $wgTitle;
394
395 $this->content = "";
396
397 if ( strtoupper( $this->method ) == "HEAD" ) {
398 $this->headersOnly = true;
399 }
400
401 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
402 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT ) );
403 }
404
405 /**
406 * Set up the proxy, but
407 * clear the proxy when $noProxy is set (takes precedence)
408 */
409 $this->proxySetup();
410
411 if ( !$this->callback ) {
412 $this->setCallback( array( $this, 'read' ) );
413 }
414
415 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
416 $this->setUserAgent( Http::userAgent() );
417 }
418 }
419
420 /**
421 * Parses the headers, including the HTTP status code and any
422 * Set-Cookie headers. This function expectes the headers to be
423 * found in an array in the member variable headerList.
424 */
425 protected function parseHeader() {
426 $lastname = "";
427
428 foreach ( $this->headerList as $header ) {
429 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
430 $this->respVersion = $match[1];
431 $this->respStatus = $match[2];
432 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
433 $last = count( $this->respHeaders[$lastname] ) - 1;
434 $this->respHeaders[$lastname][$last] .= "\r\n$header";
435 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
436 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
437 $lastname = strtolower( $match[1] );
438 }
439 }
440
441 $this->parseCookies();
442 }
443
444 /**
445 * Sets HTTPRequest status member to a fatal value with the error
446 * message if the returned integer value of the status code was
447 * not successful (< 300) or a redirect (>=300 and < 400). (see
448 * RFC2616, section 10,
449 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
450 * list of status codes.)
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 * Note that the multiple Location: headers are an artifact of CURL -- they
595 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
596 * taken care of (high-level redirect handling rewrite).
597 *
598 * @return string
599 */
600 public function getFinalUrl() {
601 $headers = $this->getResponseHeaders();
602
603 //return full url (fix for incorrect but handled relative location)
604 if ( isset( $headers[ 'location' ] ) ) {
605 $locations = $headers[ 'location' ];
606 $domain = '';
607 $foundRelativeURI = false;
608 $countLocations = count($locations);
609
610 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
611 $url = parse_url( $locations[ $i ] );
612
613 if ( isset($url[ 'host' ]) ) {
614 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
615 break; //found correct URI (with host)
616 } else {
617 $foundRelativeURI = true;
618 }
619 }
620
621 if ( $foundRelativeURI ) {
622 if ( $domain ) {
623 return $domain . $locations[ $countLocations - 1 ];
624 } else {
625 $url = parse_url( $this->url );
626 if ( isset($url[ 'host' ]) ) {
627 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
628 }
629 }
630 } else {
631 return $locations[ $countLocations - 1 ];
632 }
633 }
634
635 return $this->url;
636 }
637
638 /**
639 * Returns true if the backend can follow redirects. Overridden by the
640 * child classes.
641 * @return bool
642 */
643 public function canFollowRedirects() {
644 return true;
645 }
646 }
647
648 /**
649 * MWHttpRequest implemented using internal curl compiled into PHP
650 */
651 class CurlHttpRequest extends MWHttpRequest {
652 const SUPPORTS_FILE_POSTS = true;
653
654 static $curlMessageMap = array(
655 6 => 'http-host-unreachable',
656 28 => 'http-timed-out'
657 );
658
659 protected $curlOptions = array();
660 protected $headerText = "";
661
662 /**
663 * @param $fh
664 * @param $content
665 * @return int
666 */
667 protected function readHeader( $fh, $content ) {
668 $this->headerText .= $content;
669 return strlen( $content );
670 }
671
672 public function execute() {
673 parent::execute();
674
675 if ( !$this->status->isOK() ) {
676 return $this->status;
677 }
678
679 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
680 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
681 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
682 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
683 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
684 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
685 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
686
687 /* not sure these two are actually necessary */
688 if ( isset( $this->reqHeaders['Referer'] ) ) {
689 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
690 }
691 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
692
693 if ( isset( $this->sslVerifyHost ) ) {
694 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
695 }
696
697 if ( isset( $this->sslVerifyCert ) ) {
698 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
699 }
700
701 if ( $this->caInfo ) {
702 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
703 }
704
705 if ( $this->headersOnly ) {
706 $this->curlOptions[CURLOPT_NOBODY] = true;
707 $this->curlOptions[CURLOPT_HEADER] = true;
708 } elseif ( $this->method == 'POST' ) {
709 $this->curlOptions[CURLOPT_POST] = true;
710 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
711 // Suppress 'Expect: 100-continue' header, as some servers
712 // will reject it with a 417 and Curl won't auto retry
713 // with HTTP 1.0 fallback
714 $this->reqHeaders['Expect'] = '';
715 } else {
716 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
717 }
718
719 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
720
721 $curlHandle = curl_init( $this->url );
722
723 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
724 throw new MWException( "Error setting curl options." );
725 }
726
727 if ( $this->followRedirects && $this->canFollowRedirects() ) {
728 wfSuppressWarnings();
729 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
730 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
731 "Probably safe_mode or open_basedir is set.\n" );
732 // Continue the processing. If it were in curl_setopt_array,
733 // processing would have halted on its entry
734 }
735 wfRestoreWarnings();
736 }
737
738 if ( false === curl_exec( $curlHandle ) ) {
739 $code = curl_error( $curlHandle );
740
741 if ( isset( self::$curlMessageMap[$code] ) ) {
742 $this->status->fatal( self::$curlMessageMap[$code] );
743 } else {
744 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
745 }
746 } else {
747 $this->headerList = explode( "\r\n", $this->headerText );
748 }
749
750 curl_close( $curlHandle );
751
752 $this->parseHeader();
753 $this->setStatus();
754
755 return $this->status;
756 }
757
758 /**
759 * @return bool
760 */
761 public function canFollowRedirects() {
762 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
763 wfDebug( "Cannot follow redirects in safe mode\n" );
764 return false;
765 }
766
767 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
768 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
769 return false;
770 }
771
772 return true;
773 }
774 }
775
776 class PhpHttpRequest extends MWHttpRequest {
777
778 /**
779 * @param $url string
780 * @return string
781 */
782 protected function urlToTcp( $url ) {
783 $parsedUrl = parse_url( $url );
784
785 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
786 }
787
788 public function execute() {
789 parent::execute();
790
791 if ( is_array( $this->postData ) ) {
792 $this->postData = wfArrayToCGI( $this->postData );
793 }
794
795 if ( $this->parsedUrl['scheme'] != 'http' &&
796 $this->parsedUrl['scheme'] != 'https' ) {
797 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
798 }
799
800 $this->reqHeaders['Accept'] = "*/*";
801 if ( $this->method == 'POST' ) {
802 // Required for HTTP 1.0 POSTs
803 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
804 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
805 }
806
807 $options = array();
808 if ( $this->proxy && !$this->noProxy ) {
809 $options['proxy'] = $this->urlToTCP( $this->proxy );
810 $options['request_fulluri'] = true;
811 }
812
813 if ( !$this->followRedirects ) {
814 $options['max_redirects'] = 0;
815 } else {
816 $options['max_redirects'] = $this->maxRedirects;
817 }
818
819 $options['method'] = $this->method;
820 $options['header'] = implode( "\r\n", $this->getHeaderList() );
821 // Note that at some future point we may want to support
822 // HTTP/1.1, but we'd have to write support for chunking
823 // in version of PHP < 5.3.1
824 $options['protocol_version'] = "1.0";
825
826 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
827 // Only works on 5.2.10+
828 $options['ignore_errors'] = true;
829
830 if ( $this->postData ) {
831 $options['content'] = $this->postData;
832 }
833
834 $options['timeout'] = $this->timeout;
835
836 $context = stream_context_create( array( 'http' => $options ) );
837
838 $this->headerList = array();
839 $reqCount = 0;
840 $url = $this->url;
841
842 $result = array();
843
844 do {
845 $reqCount++;
846 wfSuppressWarnings();
847 $fh = fopen( $url, "r", false, $context );
848 wfRestoreWarnings();
849
850 if ( !$fh ) {
851 break;
852 }
853
854 $result = stream_get_meta_data( $fh );
855 $this->headerList = $result['wrapper_data'];
856 $this->parseHeader();
857
858 if ( !$this->followRedirects ) {
859 break;
860 }
861
862 # Handle manual redirection
863 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
864 break;
865 }
866 # Check security of URL
867 $url = $this->getResponseHeader( "Location" );
868
869 if ( !Http::isValidURI( $url ) ) {
870 wfDebug( __METHOD__ . ": insecure redirection\n" );
871 break;
872 }
873 } while ( true );
874
875 $this->setStatus();
876
877 if ( $fh === false ) {
878 $this->status->fatal( 'http-request-error' );
879 return $this->status;
880 }
881
882 if ( $result['timed_out'] ) {
883 $this->status->fatal( 'http-timed-out', $this->url );
884 return $this->status;
885 }
886
887 // If everything went OK, or we recieved some error code
888 // get the response body content.
889 if ( $this->status->isOK()
890 || (int)$this->respStatus >= 300) {
891 while ( !feof( $fh ) ) {
892 $buf = fread( $fh, 8192 );
893
894 if ( $buf === false ) {
895 $this->status->fatal( 'http-read-error' );
896 break;
897 }
898
899 if ( strlen( $buf ) ) {
900 call_user_func( $this->callback, $fh, $buf );
901 }
902 }
903 }
904 fclose( $fh );
905
906 return $this->status;
907 }
908 }