* Followup r75064 — fix misleading doc comment
[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
18 * @param $options Array: options to pass to HttpRequest object.
19 * Possible keys for the array:
20 * - timeout Timeout length in seconds
21 * - postData An array of key-value pairs or a url-encoded form data
22 * - proxy The proxy to use.
23 * Will use $wgHTTPProxy (if set) otherwise.
24 * - noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
25 * - sslVerifyHost (curl only) Verify hostname against certificate
26 * - sslVerifyCert (curl only) Verify SSL certificate
27 * - caInfo (curl only) Provide CA information
28 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
29 * - followRedirects Whether to follow redirects (defaults to false).
30 * Note: this should only be used when the target URL is trusted,
31 * to avoid attacks on intranet services accessible by HTTP.
32 * @return Mixed: (bool)false on failure or a string on success
33 */
34 public static function request( $method, $url, $options = array() ) {
35 $url = wfExpandUrl( $url );
36 wfDebug( "HTTP: $method: $url\n" );
37 $options['method'] = strtoupper( $method );
38
39 if ( !isset( $options['timeout'] ) ) {
40 $options['timeout'] = 'default';
41 }
42
43 $req = HttpRequest::factory( $url, $options );
44 $status = $req->execute();
45
46 if ( $status->isOK() ) {
47 return $req->getContent();
48 } else {
49 return false;
50 }
51 }
52
53 /**
54 * Simple wrapper for Http::request( 'GET' )
55 * @see Http::request()
56 */
57 public static function get( $url, $timeout = 'default', $options = array() ) {
58 $options['timeout'] = $timeout;
59 return Http::request( 'GET', $url, $options );
60 }
61
62 /**
63 * Simple wrapper for Http::request( 'POST' )
64 * @see Http::request()
65 */
66 public static function post( $url, $options = array() ) {
67 return Http::request( 'POST', $url, $options );
68 }
69
70 /**
71 * Check if the URL can be served by localhost
72 *
73 * @param $url String: full url to check
74 * @return Boolean
75 */
76 public static function isLocalURL( $url ) {
77 global $wgCommandLineMode, $wgConf;
78
79 if ( $wgCommandLineMode ) {
80 return false;
81 }
82
83 // Extract host part
84 $matches = array();
85 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
86 $host = $matches[1];
87 // Split up dotwise
88 $domainParts = explode( '.', $host );
89 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
90 $domainParts = array_reverse( $domainParts );
91
92 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
93 $domainPart = $domainParts[$i];
94 if ( $i == 0 ) {
95 $domain = $domainPart;
96 } else {
97 $domain = $domainPart . '.' . $domain;
98 }
99
100 if ( $wgConf->isLocalVHost( $domain ) ) {
101 return true;
102 }
103 }
104 }
105
106 return false;
107 }
108
109 /**
110 * A standard user-agent we can use for external requests.
111 * @return String
112 */
113 public static function userAgent() {
114 global $wgVersion;
115 return "MediaWiki/$wgVersion";
116 }
117
118 /**
119 * Checks that the given URI is a valid one
120 *
121 * @param $uri Mixed: URI to check for validity
122 * @returns Boolean
123 */
124 public static function isValidURI( $uri ) {
125 return preg_match(
126 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
127 $uri,
128 $matches
129 );
130 }
131 }
132
133 /**
134 * This wrapper class will call out to curl (if available) or fallback
135 * to regular PHP if necessary for handling internal HTTP requests.
136 */
137 class HttpRequest {
138 protected $content;
139 protected $timeout = 'default';
140 protected $headersOnly = null;
141 protected $postData = null;
142 protected $proxy = null;
143 protected $noProxy = false;
144 protected $sslVerifyHost = true;
145 protected $sslVerifyCert = true;
146 protected $caInfo = null;
147 protected $method = "GET";
148 protected $reqHeaders = array();
149 protected $url;
150 protected $parsedUrl;
151 protected $callback;
152 protected $maxRedirects = 5;
153 protected $followRedirects = false;
154
155 protected $cookieJar;
156
157 protected $headerList = array();
158 protected $respVersion = "0.9";
159 protected $respStatus = "200 Ok";
160 protected $respHeaders = array();
161
162 public $status;
163
164 /**
165 * @param $url String: url to use
166 * @param $options Array: (optional) extra params to pass (see Http::request())
167 */
168 function __construct( $url, $options = array() ) {
169 global $wgHTTPTimeout;
170
171 $this->url = $url;
172 $this->parsedUrl = parse_url( $url );
173
174 if ( !Http::isValidURI( $this->url ) ) {
175 $this->status = Status::newFatal( 'http-invalid-url' );
176 } else {
177 $this->status = Status::newGood( 100 ); // continue
178 }
179
180 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
181 $this->timeout = $options['timeout'];
182 } else {
183 $this->timeout = $wgHTTPTimeout;
184 }
185
186 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
187 "method", "followRedirects", "maxRedirects", "sslVerifyCert" );
188
189 foreach ( $members as $o ) {
190 if ( isset( $options[$o] ) ) {
191 $this->$o = $options[$o];
192 }
193 }
194 }
195
196 /**
197 * Generate a new request object
198 * @see HttpRequest::__construct
199 */
200 public static function factory( $url, $options = null ) {
201 if ( !Http::$httpEngine ) {
202 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
203 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
204 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
205 ' Http::$httpEngine is set to "curl"' );
206 }
207
208 switch( Http::$httpEngine ) {
209 case 'curl':
210 return new CurlHttpRequest( $url, $options );
211 case 'php':
212 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
213 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
214 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
215 }
216 return new PhpHttpRequest( $url, $options );
217 default:
218 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
219 }
220 }
221
222 /**
223 * Get the body, or content, of the response to the request
224 *
225 * @return String
226 */
227 public function getContent() {
228 return $this->content;
229 }
230
231 /**
232 * Set the parameters of the request
233
234 * @param $args Array
235 * @todo overload the args param
236 */
237 public function setData( $args ) {
238 $this->postData = $args;
239 }
240
241 /**
242 * Take care of setting up the proxy
243 * (override in subclass)
244 *
245 * @return String
246 */
247 public function proxySetup() {
248 global $wgHTTPProxy;
249
250 if ( $this->proxy ) {
251 return;
252 }
253
254 if ( Http::isLocalURL( $this->url ) ) {
255 $this->proxy = 'http://localhost:80/';
256 } elseif ( $wgHTTPProxy ) {
257 $this->proxy = $wgHTTPProxy ;
258 } elseif ( getenv( "http_proxy" ) ) {
259 $this->proxy = getenv( "http_proxy" );
260 }
261 }
262
263 /**
264 * Set the refererer header
265 */
266 public function setReferer( $url ) {
267 $this->setHeader( 'Referer', $url );
268 }
269
270 /**
271 * Set the user agent
272 */
273 public function setUserAgent( $UA ) {
274 $this->setHeader( 'User-Agent', $UA );
275 }
276
277 /**
278 * Set an arbitrary header
279 */
280 public function setHeader( $name, $value ) {
281 // I feel like I should normalize the case here...
282 $this->reqHeaders[$name] = $value;
283 }
284
285 /**
286 * Get an array of the headers
287 */
288 public function getHeaderList() {
289 $list = array();
290
291 if ( $this->cookieJar ) {
292 $this->reqHeaders['Cookie'] =
293 $this->cookieJar->serializeToHttpRequest(
294 $this->parsedUrl['path'],
295 $this->parsedUrl['host']
296 );
297 }
298
299 foreach ( $this->reqHeaders as $name => $value ) {
300 $list[] = "$name: $value";
301 }
302
303 return $list;
304 }
305
306 /**
307 * Set the callback
308 *
309 * @param $callback Callback
310 */
311 public function setCallback( $callback ) {
312 $this->callback = $callback;
313 }
314
315 /**
316 * A generic callback to read the body of the response from a remote
317 * server.
318 *
319 * @param $fh handle
320 * @param $content String
321 */
322 public function read( $fh, $content ) {
323 $this->content .= $content;
324 return strlen( $content );
325 }
326
327 /**
328 * Take care of whatever is necessary to perform the URI request.
329 *
330 * @return Status
331 */
332 public function execute() {
333 global $wgTitle;
334
335 $this->content = "";
336
337 if ( strtoupper( $this->method ) == "HEAD" ) {
338 $this->headersOnly = true;
339 }
340
341 if ( is_array( $this->postData ) ) {
342 $this->postData = wfArrayToCGI( $this->postData );
343 }
344
345 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
346 $this->setReferer( $wgTitle->getFullURL() );
347 }
348
349 if ( !$this->noProxy ) {
350 $this->proxySetup();
351 }
352
353 if ( !$this->callback ) {
354 $this->setCallback( array( $this, 'read' ) );
355 }
356
357 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
358 $this->setUserAgent( Http::userAgent() );
359 }
360 }
361
362 /**
363 * Parses the headers, including the HTTP status code and any
364 * Set-Cookie headers. This function expectes the headers to be
365 * found in an array in the member variable headerList.
366 *
367 * @return nothing
368 */
369 protected function parseHeader() {
370 $lastname = "";
371
372 foreach ( $this->headerList as $header ) {
373 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
374 $this->respVersion = $match[1];
375 $this->respStatus = $match[2];
376 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
377 $last = count( $this->respHeaders[$lastname] ) - 1;
378 $this->respHeaders[$lastname][$last] .= "\r\n$header";
379 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
380 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
381 $lastname = strtolower( $match[1] );
382 }
383 }
384
385 $this->parseCookies();
386 }
387
388 /**
389 * Sets HTTPRequest status member to a fatal value with the error
390 * message if the returned integer value of the status code was
391 * not successful (< 300) or a redirect (>=300 and < 400). (see
392 * RFC2616, section 10,
393 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
394 * list of status codes.)
395 *
396 * @return nothing
397 */
398 protected function setStatus() {
399 if ( !$this->respHeaders ) {
400 $this->parseHeader();
401 }
402
403 if ( (int)$this->respStatus > 399 ) {
404 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
405 $this->status->fatal( "http-bad-status", $code, $message );
406 }
407 }
408
409 /**
410 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
411 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
412 * for a list of status codes.)
413 *
414 * @return Integer
415 */
416 public function getStatus() {
417 if ( !$this->respHeaders ) {
418 $this->parseHeader();
419 }
420
421 return (int)$this->respStatus;
422 }
423
424
425 /**
426 * Returns true if the last status code was a redirect.
427 *
428 * @return Boolean
429 */
430 public function isRedirect() {
431 if ( !$this->respHeaders ) {
432 $this->parseHeader();
433 }
434
435 $status = (int)$this->respStatus;
436
437 if ( $status >= 300 && $status <= 303 ) {
438 return true;
439 }
440
441 return false;
442 }
443
444 /**
445 * Returns an associative array of response headers after the
446 * request has been executed. Because some headers
447 * (e.g. Set-Cookie) can appear more than once the, each value of
448 * the associative array is an array of the values given.
449 *
450 * @return Array
451 */
452 public function getResponseHeaders() {
453 if ( !$this->respHeaders ) {
454 $this->parseHeader();
455 }
456
457 return $this->respHeaders;
458 }
459
460 /**
461 * Returns the value of the given response header.
462 *
463 * @param $header String
464 * @return String
465 */
466 public function getResponseHeader( $header ) {
467 if ( !$this->respHeaders ) {
468 $this->parseHeader();
469 }
470
471 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
472 $v = $this->respHeaders[strtolower ( $header ) ];
473 return $v[count( $v ) - 1];
474 }
475
476 return null;
477 }
478
479 /**
480 * Tells the HttpRequest object to use this pre-loaded CookieJar.
481 *
482 * @param $jar CookieJar
483 */
484 public function setCookieJar( $jar ) {
485 $this->cookieJar = $jar;
486 }
487
488 /**
489 * Returns the cookie jar in use.
490 *
491 * @returns CookieJar
492 */
493 public function getCookieJar() {
494 if ( !$this->respHeaders ) {
495 $this->parseHeader();
496 }
497
498 return $this->cookieJar;
499 }
500
501 /**
502 * Sets a cookie. Used before a request to set up any individual
503 * cookies. Used internally after a request to parse the
504 * Set-Cookie headers.
505 * @see Cookie::set
506 */
507 public function setCookie( $name, $value = null, $attr = null ) {
508 if ( !$this->cookieJar ) {
509 $this->cookieJar = new CookieJar;
510 }
511
512 $this->cookieJar->setCookie( $name, $value, $attr );
513 }
514
515 /**
516 * Parse the cookies in the response headers and store them in the cookie jar.
517 */
518 protected function parseCookies() {
519 if ( !$this->cookieJar ) {
520 $this->cookieJar = new CookieJar;
521 }
522
523 if ( isset( $this->respHeaders['set-cookie'] ) ) {
524 $url = parse_url( $this->getFinalUrl() );
525 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
526 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
527 }
528 }
529 }
530
531 /**
532 * Returns the final URL after all redirections.
533 *
534 * @return String
535 */
536 public function getFinalUrl() {
537 $location = $this->getResponseHeader( "Location" );
538
539 if ( $location ) {
540 return $location;
541 }
542
543 return $this->url;
544 }
545
546 /**
547 * Returns true if the backend can follow redirects. Overridden by the
548 * child classes.
549 */
550 public function canFollowRedirects() {
551 return true;
552 }
553 }
554
555
556 class Cookie {
557 protected $name;
558 protected $value;
559 protected $expires;
560 protected $path;
561 protected $domain;
562 protected $isSessionKey = true;
563 // TO IMPLEMENT protected $secure
564 // TO IMPLEMENT? protected $maxAge (add onto expires)
565 // TO IMPLEMENT? protected $version
566 // TO IMPLEMENT? protected $comment
567
568 function __construct( $name, $value, $attr ) {
569 $this->name = $name;
570 $this->set( $value, $attr );
571 }
572
573 /**
574 * Sets a cookie. Used before a request to set up any individual
575 * cookies. Used internally after a request to parse the
576 * Set-Cookie headers.
577 *
578 * @param $value String: the value of the cookie
579 * @param $attr Array: possible key/values:
580 * expires A date string
581 * path The path this cookie is used on
582 * domain Domain this cookie is used on
583 */
584 public function set( $value, $attr ) {
585 $this->value = $value;
586
587 if ( isset( $attr['expires'] ) ) {
588 $this->isSessionKey = false;
589 $this->expires = strtotime( $attr['expires'] );
590 }
591
592 if ( isset( $attr['path'] ) ) {
593 $this->path = $attr['path'];
594 } else {
595 $this->path = "/";
596 }
597
598 if ( isset( $attr['domain'] ) ) {
599 if ( self::validateCookieDomain( $attr['domain'] ) ) {
600 $this->domain = $attr['domain'];
601 }
602 } else {
603 throw new MWException( "You must specify a domain." );
604 }
605 }
606
607 /**
608 * Return the true if the cookie is valid is valid. Otherwise,
609 * false. The uses a method similar to IE cookie security
610 * described here:
611 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
612 * A better method might be to use a blacklist like
613 * http://publicsuffix.org/
614 *
615 * @param $domain String: the domain to validate
616 * @param $originDomain String: (optional) the domain the cookie originates from
617 * @return Boolean
618 */
619 public static function validateCookieDomain( $domain, $originDomain = null ) {
620 // Don't allow a trailing dot
621 if ( substr( $domain, -1 ) == "." ) {
622 return false;
623 }
624
625 $dc = explode( ".", $domain );
626
627 // Only allow full, valid IP addresses
628 if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
629 if ( count( $dc ) != 4 ) {
630 return false;
631 }
632
633 if ( ip2long( $domain ) === false ) {
634 return false;
635 }
636
637 if ( $originDomain == null || $originDomain == $domain ) {
638 return true;
639 }
640
641 }
642
643 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
644 if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
645 if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
646 || ( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
647 return false;
648 }
649 if ( ( count( $dc ) == 2 || ( count( $dc ) == 3 && $dc[0] == "" ) )
650 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
651 return false;
652 }
653 }
654
655 if ( $originDomain != null ) {
656 if ( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
657 return false;
658 }
659
660 if ( substr( $domain, 0, 1 ) == "."
661 && substr_compare( $originDomain, $domain, -strlen( $domain ),
662 strlen( $domain ), TRUE ) != 0 ) {
663 return false;
664 }
665 }
666
667 return true;
668 }
669
670 /**
671 * Serialize the cookie jar into a format useful for HTTP Request headers.
672 *
673 * @param $path String: the path that will be used. Required.
674 * @param $domain String: the domain that will be used. Required.
675 * @return String
676 */
677 public function serializeToHttpRequest( $path, $domain ) {
678 $ret = "";
679
680 if ( $this->canServeDomain( $domain )
681 && $this->canServePath( $path )
682 && $this->isUnExpired() ) {
683 $ret = $this->name . "=" . $this->value;
684 }
685
686 return $ret;
687 }
688
689 protected function canServeDomain( $domain ) {
690 if ( $domain == $this->domain
691 || ( strlen( $domain ) > strlen( $this->domain )
692 && substr( $this->domain, 0, 1 ) == "."
693 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
694 strlen( $this->domain ), TRUE ) == 0 ) ) {
695 return true;
696 }
697
698 return false;
699 }
700
701 protected function canServePath( $path ) {
702 if ( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
703 return true;
704 }
705
706 return false;
707 }
708
709 protected function isUnExpired() {
710 if ( $this->isSessionKey || $this->expires > time() ) {
711 return true;
712 }
713
714 return false;
715 }
716 }
717
718 class CookieJar {
719 private $cookie = array();
720
721 /**
722 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
723 * @see Cookie::set()
724 */
725 public function setCookie ( $name, $value, $attr ) {
726 /* cookies: case insensitive, so this should work.
727 * We'll still send the cookies back in the same case we got them, though.
728 */
729 $index = strtoupper( $name );
730
731 if ( isset( $this->cookie[$index] ) ) {
732 $this->cookie[$index]->set( $value, $attr );
733 } else {
734 $this->cookie[$index] = new Cookie( $name, $value, $attr );
735 }
736 }
737
738 /**
739 * @see Cookie::serializeToHttpRequest
740 */
741 public function serializeToHttpRequest( $path, $domain ) {
742 $cookies = array();
743
744 foreach ( $this->cookie as $c ) {
745 $serialized = $c->serializeToHttpRequest( $path, $domain );
746
747 if ( $serialized ) {
748 $cookies[] = $serialized;
749 }
750 }
751
752 return implode( "; ", $cookies );
753 }
754
755 /**
756 * Parse the content of an Set-Cookie HTTP Response header.
757 *
758 * @param $cookie String
759 * @param $domain String: cookie's domain
760 */
761 public function parseCookieResponseHeader ( $cookie, $domain ) {
762 $len = strlen( "Set-Cookie:" );
763
764 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
765 $cookie = substr( $cookie, $len );
766 }
767
768 $bit = array_map( 'trim', explode( ";", $cookie ) );
769
770 if ( count( $bit ) >= 1 ) {
771 list( $name, $value ) = explode( "=", array_shift( $bit ), 2 );
772 $attr = array();
773
774 foreach ( $bit as $piece ) {
775 $parts = explode( "=", $piece );
776 if ( count( $parts ) > 1 ) {
777 $attr[strtolower( $parts[0] )] = $parts[1];
778 } else {
779 $attr[strtolower( $parts[0] )] = true;
780 }
781 }
782
783 if ( !isset( $attr['domain'] ) ) {
784 $attr['domain'] = $domain;
785 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
786 return null;
787 }
788
789 $this->setCookie( $name, $value, $attr );
790 }
791 }
792 }
793
794 /**
795 * HttpRequest implemented using internal curl compiled into PHP
796 */
797 class CurlHttpRequest extends HttpRequest {
798 static $curlMessageMap = array(
799 6 => 'http-host-unreachable',
800 28 => 'http-timed-out'
801 );
802
803 protected $curlOptions = array();
804 protected $headerText = "";
805
806 protected function readHeader( $fh, $content ) {
807 $this->headerText .= $content;
808 return strlen( $content );
809 }
810
811 public function execute() {
812 parent::execute();
813
814 if ( !$this->status->isOK() ) {
815 return $this->status;
816 }
817
818 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
819 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
820 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
821 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
822 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
823 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
824 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
825
826 /* not sure these two are actually necessary */
827 if ( isset( $this->reqHeaders['Referer'] ) ) {
828 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
829 }
830 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
831
832 if ( isset( $this->sslVerifyHost ) ) {
833 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
834 }
835
836 if ( isset( $this->sslVerifyCert ) ) {
837 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
838 }
839
840 if ( $this->caInfo ) {
841 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
842 }
843
844 if ( $this->headersOnly ) {
845 $this->curlOptions[CURLOPT_NOBODY] = true;
846 $this->curlOptions[CURLOPT_HEADER] = true;
847 } elseif ( $this->method == 'POST' ) {
848 $this->curlOptions[CURLOPT_POST] = true;
849 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
850 // Suppress 'Expect: 100-continue' header, as some servers
851 // will reject it with a 417 and Curl won't auto retry
852 // with HTTP 1.0 fallback
853 $this->reqHeaders['Expect'] = '';
854 } else {
855 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
856 }
857
858 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
859
860 $curlHandle = curl_init( $this->url );
861
862 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
863 throw new MWException( "Error setting curl options." );
864 }
865
866 if ( $this->followRedirects && $this->canFollowRedirects() ) {
867 if ( ! @curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
868 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
869 "Probably safe_mode or open_basedir is set.\n" );
870 // Continue the processing. If it were in curl_setopt_array,
871 // processing would have halted on its entry
872 }
873 }
874
875 if ( false === curl_exec( $curlHandle ) ) {
876 $code = curl_error( $curlHandle );
877
878 if ( isset( self::$curlMessageMap[$code] ) ) {
879 $this->status->fatal( self::$curlMessageMap[$code] );
880 } else {
881 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
882 }
883 } else {
884 $this->headerList = explode( "\r\n", $this->headerText );
885 }
886
887 curl_close( $curlHandle );
888
889 $this->parseHeader();
890 $this->setStatus();
891
892 return $this->status;
893 }
894
895 public function canFollowRedirects() {
896 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
897 wfDebug( "Cannot follow redirects in safe mode\n" );
898 return false;
899 }
900
901 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
902 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
903 return false;
904 }
905
906 return true;
907 }
908 }
909
910 class PhpHttpRequest extends HttpRequest {
911 protected function urlToTcp( $url ) {
912 $parsedUrl = parse_url( $url );
913
914 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
915 }
916
917 public function execute() {
918 parent::execute();
919
920 // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
921 // causes a segfault
922 $manuallyRedirect = version_compare( phpversion(), '5.1.7', '<' );
923
924 if ( $this->parsedUrl['scheme'] != 'http' ) {
925 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
926 }
927
928 $this->reqHeaders['Accept'] = "*/*";
929 if ( $this->method == 'POST' ) {
930 // Required for HTTP 1.0 POSTs
931 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
932 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
933 }
934
935 $options = array();
936 if ( $this->proxy && !$this->noProxy ) {
937 $options['proxy'] = $this->urlToTCP( $this->proxy );
938 $options['request_fulluri'] = true;
939 }
940
941 if ( !$this->followRedirects || $manuallyRedirect ) {
942 $options['max_redirects'] = 0;
943 } else {
944 $options['max_redirects'] = $this->maxRedirects;
945 }
946
947 $options['method'] = $this->method;
948 $options['header'] = implode( "\r\n", $this->getHeaderList() );
949 // Note that at some future point we may want to support
950 // HTTP/1.1, but we'd have to write support for chunking
951 // in version of PHP < 5.3.1
952 $options['protocol_version'] = "1.0";
953
954 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
955 // Only works on 5.2.10+
956 $options['ignore_errors'] = true;
957
958 if ( $this->postData ) {
959 $options['content'] = $this->postData;
960 }
961
962 $oldTimeout = false;
963 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
964 $oldTimeout = ini_set( 'default_socket_timeout', $this->timeout );
965 } else {
966 $options['timeout'] = $this->timeout;
967 }
968
969 $context = stream_context_create( array( 'http' => $options ) );
970
971 $this->headerList = array();
972 $reqCount = 0;
973 $url = $this->url;
974
975 do {
976 $reqCount++;
977 wfSuppressWarnings();
978 $fh = fopen( $url, "r", false, $context );
979 wfRestoreWarnings();
980
981 if ( !$fh ) {
982 break;
983 }
984
985 $result = stream_get_meta_data( $fh );
986 $this->headerList = $result['wrapper_data'];
987 $this->parseHeader();
988
989 if ( !$manuallyRedirect || !$this->followRedirects ) {
990 break;
991 }
992
993 # Handle manual redirection
994 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
995 break;
996 }
997 # Check security of URL
998 $url = $this->getResponseHeader( "Location" );
999
1000 if ( substr( $url, 0, 7 ) !== 'http://' ) {
1001 wfDebug( __METHOD__ . ": insecure redirection\n" );
1002 break;
1003 }
1004 } while ( true );
1005
1006 if ( $oldTimeout !== false ) {
1007 ini_set( 'default_socket_timeout', $oldTimeout );
1008 }
1009
1010 $this->setStatus();
1011
1012 if ( $fh === false ) {
1013 $this->status->fatal( 'http-request-error' );
1014 return $this->status;
1015 }
1016
1017 if ( $result['timed_out'] ) {
1018 $this->status->fatal( 'http-timed-out', $this->url );
1019 return $this->status;
1020 }
1021
1022 if ( $this->status->isOK() ) {
1023 while ( !feof( $fh ) ) {
1024 $buf = fread( $fh, 8192 );
1025
1026 if ( $buf === false ) {
1027 $this->status->fatal( 'http-read-error' );
1028 break;
1029 }
1030
1031 if ( strlen( $buf ) ) {
1032 call_user_func( $this->callback, $fh, $buf );
1033 }
1034 }
1035 }
1036 fclose( $fh );
1037
1038 return $this->status;
1039 }
1040 }