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