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