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