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