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