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