00001 <?php
00010 class Http {
00011 static $httpEngine = false;
00012
00029 public static function request( $method, $url, $options = array() ) {
00030 wfDebug( "HTTP: $method: $url" );
00031 $options['method'] = strtoupper( $method );
00032 if ( !isset( $options['timeout'] ) ) {
00033 $options['timeout'] = 'default';
00034 }
00035 $req = HttpRequest::factory( $url, $options );
00036 $status = $req->execute();
00037 if ( $status->isOK() ) {
00038 return $req->getContent();
00039 } else {
00040 return false;
00041 }
00042 }
00043
00048 public static function get( $url, $timeout = 'default', $options = array() ) {
00049 $options['timeout'] = $timeout;
00050 return Http::request( 'GET', $url, $options );
00051 }
00052
00057 public static function post( $url, $options = array() ) {
00058 return Http::request( 'POST', $url, $options );
00059 }
00060
00066 public static function isLocalURL( $url ) {
00067 global $wgCommandLineMode, $wgConf;
00068 if ( $wgCommandLineMode ) {
00069 return false;
00070 }
00071
00072
00073 $matches = array();
00074 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
00075 $host = $matches[1];
00076
00077 $domainParts = explode( '.', $host );
00078
00079 $domainParts = array_reverse( $domainParts );
00080 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
00081 $domainPart = $domainParts[$i];
00082 if ( $i == 0 ) {
00083 $domain = $domainPart;
00084 } else {
00085 $domain = $domainPart . '.' . $domain;
00086 }
00087 if ( $wgConf->isLocalVHost( $domain ) ) {
00088 return true;
00089 }
00090 }
00091 }
00092 return false;
00093 }
00094
00099 public static function userAgent() {
00100 global $wgVersion;
00101 return "MediaWiki/$wgVersion";
00102 }
00103
00109 public static function isValidURI( $uri ) {
00110 return preg_match(
00111 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
00112 $uri,
00113 $matches
00114 );
00115 }
00116 }
00117
00122 class HttpRequest {
00123 protected $content;
00124 protected $timeout = 'default';
00125 protected $headersOnly = null;
00126 protected $postData = null;
00127 protected $proxy = null;
00128 protected $noProxy = false;
00129 protected $sslVerifyHost = true;
00130 protected $caInfo = null;
00131 protected $method = "GET";
00132 protected $reqHeaders = array();
00133 protected $url;
00134 protected $parsedUrl;
00135 protected $callback;
00136 protected $maxRedirects = 5;
00137 protected $followRedirects = true;
00138
00139 protected $cookieJar;
00140
00141 protected $headerList = array();
00142 protected $respVersion = "0.9";
00143 protected $respStatus = "200 Ok";
00144 protected $respHeaders = array();
00145
00146 public $status;
00147
00152 function __construct( $url, $options = array() ) {
00153 global $wgHTTPTimeout;
00154
00155 $this->url = $url;
00156 $this->parsedUrl = parse_url( $url );
00157
00158 if ( !Http::isValidURI( $this->url ) ) {
00159 $this->status = Status::newFatal('http-invalid-url');
00160 } else {
00161 $this->status = Status::newGood( 100 );
00162 }
00163
00164 if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
00165 $this->timeout = $options['timeout'];
00166 } else {
00167 $this->timeout = $wgHTTPTimeout;
00168 }
00169
00170 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
00171 "method", "followRedirects", "maxRedirects" );
00172 foreach ( $members as $o ) {
00173 if ( isset($options[$o]) ) {
00174 $this->$o = $options[$o];
00175 }
00176 }
00177 }
00178
00183 public static function factory( $url, $options = null ) {
00184 if ( !Http::$httpEngine ) {
00185 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
00186 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
00187 throw new MWException( __METHOD__.': curl (http://php.net/curl) is not installed, but'.
00188 ' Http::$httpEngine is set to "curl"' );
00189 }
00190
00191 switch( Http::$httpEngine ) {
00192 case 'curl':
00193 return new CurlHttpRequest( $url, $options );
00194 case 'php':
00195 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
00196 throw new MWException( __METHOD__.': allow_url_fopen needs to be enabled for pure PHP'.
00197 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
00198 }
00199 return new PhpHttpRequest( $url, $options );
00200 default:
00201 throw new MWException( __METHOD__.': The setting of Http::$httpEngine is not valid.' );
00202 }
00203 }
00204
00209 public function getContent() {
00210 return $this->content;
00211 }
00212
00218 public function proxySetup() {
00219 global $wgHTTPProxy;
00220
00221 if ( $this->proxy ) {
00222 return;
00223 }
00224 if ( Http::isLocalURL( $this->url ) ) {
00225 $this->proxy = 'http://localhost:80/';
00226 } elseif ( $wgHTTPProxy ) {
00227 $this->proxy = $wgHTTPProxy ;
00228 } elseif ( getenv( "http_proxy" ) ) {
00229 $this->proxy = getenv( "http_proxy" );
00230 }
00231 }
00232
00236 public function setReferer( $url ) {
00237 $this->setHeader('Referer', $url);
00238 }
00239
00243 public function setUserAgent( $UA ) {
00244 $this->setHeader('User-Agent', $UA);
00245 }
00246
00250 public function setHeader($name, $value) {
00251
00252 $this->reqHeaders[$name] = $value;
00253 }
00254
00258 public function getHeaderList() {
00259 $list = array();
00260
00261 if( $this->cookieJar ) {
00262 $this->reqHeaders['Cookie'] =
00263 $this->cookieJar->serializeToHttpRequest($this->parsedUrl['path'],
00264 $this->parsedUrl['host']);
00265 }
00266 foreach($this->reqHeaders as $name => $value) {
00267 $list[] = "$name: $value";
00268 }
00269 return $list;
00270 }
00271
00276 public function setCallback( $callback ) {
00277 $this->callback = $callback;
00278 }
00279
00286 public function read( $fh, $content ) {
00287 $this->content .= $content;
00288 return strlen( $content );
00289 }
00290
00295 public function execute() {
00296 global $wgTitle;
00297
00298 if( strtoupper($this->method) == "HEAD" ) {
00299 $this->headersOnly = true;
00300 }
00301
00302 if ( is_array( $this->postData ) ) {
00303 $this->postData = wfArrayToCGI( $this->postData );
00304 }
00305
00306 if ( is_object( $wgTitle ) && !isset($this->reqHeaders['Referer']) ) {
00307 $this->setReferer( $wgTitle->getFullURL() );
00308 }
00309
00310 if ( !$this->noProxy ) {
00311 $this->proxySetup();
00312 }
00313
00314 if ( !$this->callback ) {
00315 $this->setCallback( array( $this, 'read' ) );
00316 }
00317
00318 if ( !isset($this->reqHeaders['User-Agent']) ) {
00319 $this->setUserAgent(Http::userAgent());
00320 }
00321 }
00322
00329 protected function parseHeader() {
00330 $lastname = "";
00331 foreach( $this->headerList as $header ) {
00332 if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
00333 $this->respVersion = $match[1];
00334 $this->respStatus = $match[2];
00335 } elseif( preg_match( "#^[ \t]#", $header ) ) {
00336 $last = count($this->respHeaders[$lastname]) - 1;
00337 $this->respHeaders[$lastname][$last] .= "\r\n$header";
00338 } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
00339 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
00340 $lastname = strtolower( $match[1] );
00341 }
00342 }
00343
00344 $this->parseCookies();
00345 }
00346
00352 protected function setStatus() {
00353 if( !$this->respHeaders ) {
00354 $this->parseHeader();
00355 }
00356
00357 if((int)$this->respStatus !== 200) {
00358 list( $code, $message ) = explode(" ", $this->respStatus, 2);
00359 $this->status->fatal("http-bad-status", $code, $message );
00360 }
00361 }
00362
00363
00368 public function isRedirect() {
00369 if( !$this->respHeaders ) {
00370 $this->parseHeader();
00371 }
00372
00373 $status = (int)$this->respStatus;
00374 if ( $status >= 300 && $status < 400 ) {
00375 return true;
00376 }
00377 return false;
00378 }
00379
00387 public function getResponseHeaders() {
00388 if( !$this->respHeaders ) {
00389 $this->parseHeader();
00390 }
00391 return $this->respHeaders;
00392 }
00393
00399 public function getResponseHeader($header) {
00400 if( !$this->respHeaders ) {
00401 $this->parseHeader();
00402 }
00403 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
00404 $v = $this->respHeaders[strtolower ( $header ) ];
00405 return $v[count( $v ) - 1];
00406 }
00407 return null;
00408 }
00409
00414 public function setCookieJar( $jar ) {
00415 $this->cookieJar = $jar;
00416 }
00417
00422 public function getCookieJar() {
00423 if( !$this->respHeaders ) {
00424 $this->parseHeader();
00425 }
00426 return $this->cookieJar;
00427 }
00428
00435 public function setCookie( $name, $value = null, $attr = null) {
00436 if( !$this->cookieJar ) {
00437 $this->cookieJar = new CookieJar;
00438 }
00439 $this->cookieJar->setCookie($name, $value, $attr);
00440 }
00441
00445 protected function parseCookies() {
00446 if( !$this->cookieJar ) {
00447 $this->cookieJar = new CookieJar;
00448 }
00449 if( isset( $this->respHeaders['set-cookie'] ) ) {
00450 $url = parse_url( $this->getFinalUrl() );
00451 foreach( $this->respHeaders['set-cookie'] as $cookie ) {
00452 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
00453 }
00454 }
00455 }
00456
00461 public function getFinalUrl() {
00462 $location = $this->getResponseHeader("Location");
00463 if ( $location ) {
00464 return $location;
00465 }
00466
00467 return $this->url;
00468 }
00469 }
00470
00471
00472 class Cookie {
00473 protected $name;
00474 protected $value;
00475 protected $expires;
00476 protected $path;
00477 protected $domain;
00478 protected $isSessionKey = true;
00479
00480
00481
00482
00483
00484 function __construct( $name, $value, $attr ) {
00485 $this->name = $name;
00486 $this->set( $value, $attr );
00487 }
00488
00500 public function set( $value, $attr ) {
00501 $this->value = $value;
00502 if( isset( $attr['expires'] ) ) {
00503 $this->isSessionKey = false;
00504 $this->expires = strtotime( $attr['expires'] );
00505 }
00506 if( isset( $attr['path'] ) ) {
00507 $this->path = $attr['path'];
00508 } else {
00509 $this->path = "/";
00510 }
00511 if( isset( $attr['domain'] ) ) {
00512 if( self::validateCookieDomain( $attr['domain'] ) ) {
00513 $this->domain = $attr['domain'];
00514 }
00515 } else {
00516 throw new MWException("You must specify a domain.");
00517 }
00518 }
00519
00532 public static function validateCookieDomain( $domain, $originDomain = null) {
00533
00534 if( substr( $domain, -1 ) == "." ) return false;
00535
00536 $dc = explode(".", $domain);
00537
00538
00539 if( count($dc) < 2 ) return false;
00540
00541
00542 if( preg_match( '/^[0-9.]+$/', $domain ) ) {
00543 if( count( $dc ) != 4 ) return false;
00544
00545 if( ip2long( $domain ) === false ) return false;
00546
00547 if( $originDomain == null || $originDomain == $domain ) return true;
00548
00549 }
00550
00551
00552 if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
00553 if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
00554 || (count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
00555 return false;
00556 }
00557 if( (count($dc) == 2 || (count($dc) == 3 && $dc[0] == "") )
00558 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
00559 return false;
00560 }
00561 }
00562
00563 if( $originDomain != null ) {
00564 if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
00565 return false;
00566 }
00567 if( substr( $domain, 0, 1 ) == "."
00568 && substr_compare( $originDomain, $domain, -strlen( $domain ),
00569 strlen( $domain ), TRUE ) != 0 ) {
00570 return false;
00571 }
00572 }
00573
00574 return true;
00575 }
00576
00583 public function serializeToHttpRequest( $path, $domain ) {
00584 $ret = "";
00585
00586 if( $this->canServeDomain( $domain )
00587 && $this->canServePath( $path )
00588 && $this->isUnExpired() ) {
00589 $ret = $this->name ."=". $this->value;
00590 }
00591
00592 return $ret;
00593 }
00594
00595 protected function canServeDomain( $domain ) {
00596 if( $domain == $this->domain
00597 || ( strlen( $domain) > strlen( $this->domain )
00598 && substr( $this->domain, 0, 1) == "."
00599 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
00600 strlen( $this->domain ), TRUE ) == 0 ) ) {
00601 return true;
00602 }
00603 return false;
00604 }
00605
00606 protected function canServePath( $path ) {
00607 if( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
00608 return true;
00609 }
00610 return false;
00611 }
00612
00613 protected function isUnExpired() {
00614 if( $this->isSessionKey || $this->expires > time() ) {
00615 return true;
00616 }
00617 return false;
00618 }
00619
00620 }
00621
00622 class CookieJar {
00623 private $cookie = array();
00624
00629 public function setCookie ($name, $value, $attr) {
00630
00631
00632
00633 $index = strtoupper($name);
00634 if( isset( $this->cookie[$index] ) ) {
00635 $this->cookie[$index]->set( $value, $attr );
00636 } else {
00637 $this->cookie[$index] = new Cookie( $name, $value, $attr );
00638 }
00639 }
00640
00644 public function serializeToHttpRequest( $path, $domain ) {
00645 $cookies = array();
00646
00647 foreach( $this->cookie as $c ) {
00648 $serialized = $c->serializeToHttpRequest( $path, $domain );
00649 if ( $serialized ) $cookies[] = $serialized;
00650 }
00651
00652 return implode("; ", $cookies);
00653 }
00654
00659 public function parseCookieResponseHeader ( $cookie, $domain ) {
00660 $len = strlen( "Set-Cookie:" );
00661 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
00662 $cookie = substr( $cookie, $len );
00663 }
00664
00665 $bit = array_map( 'trim', explode( ";", $cookie ) );
00666 if ( count($bit) >= 1 ) {
00667 list($name, $value) = explode( "=", array_shift( $bit ), 2 );
00668 $attr = array();
00669 foreach( $bit as $piece ) {
00670 $parts = explode( "=", $piece );
00671 if( count( $parts ) > 1 ) {
00672 $attr[strtolower( $parts[0] )] = $parts[1];
00673 } else {
00674 $attr[strtolower( $parts[0] )] = true;
00675 }
00676 }
00677
00678 if( !isset( $attr['domain'] ) ) {
00679 $attr['domain'] = $domain;
00680 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
00681 return null;
00682 }
00683
00684 $this->setCookie( $name, $value, $attr );
00685 }
00686 }
00687 }
00688
00689
00693 class CurlHttpRequest extends HttpRequest {
00694 static $curlMessageMap = array(
00695 6 => 'http-host-unreachable',
00696 28 => 'http-timed-out'
00697 );
00698
00699 protected $curlOptions = array();
00700 protected $headerText = "";
00701
00702 protected function readHeader( $fh, $content ) {
00703 $this->headerText .= $content;
00704 return strlen( $content );
00705 }
00706
00707 public function execute() {
00708 parent::execute();
00709 if ( !$this->status->isOK() ) {
00710 return $this->status;
00711 }
00712 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
00713 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
00714 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
00715 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
00716 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array($this, "readHeader");
00717 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
00718
00719
00720 if(isset($this->reqHeaders['Referer'])) {
00721 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
00722 }
00723 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
00724
00725 if ( $this->sslVerifyHost ) {
00726 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
00727 }
00728
00729 if ( $this->caInfo ) {
00730 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
00731 }
00732
00733 if ( $this->headersOnly ) {
00734 $this->curlOptions[CURLOPT_NOBODY] = true;
00735 $this->curlOptions[CURLOPT_HEADER] = true;
00736 } elseif ( $this->method == 'POST' ) {
00737 $this->curlOptions[CURLOPT_POST] = true;
00738 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
00739
00740
00741
00742 $this->reqHeaders['Expect'] = '';
00743 } else {
00744 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
00745 }
00746
00747 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
00748
00749 $curlHandle = curl_init( $this->url );
00750 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
00751 throw new MWException("Error setting curl options.");
00752 }
00753 if ( ! @curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, $this->followRedirects ) ) {
00754 wfDebug("Couldn't set CURLOPT_FOLLOWLOCATION. Probably safe_mode or open_basedir is set.");
00755
00756 }
00757
00758 if ( false === curl_exec( $curlHandle ) ) {
00759 $code = curl_error( $curlHandle );
00760
00761 if ( isset( self::$curlMessageMap[$code] ) ) {
00762 $this->status->fatal( self::$curlMessageMap[$code] );
00763 } else {
00764 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
00765 }
00766 } else {
00767 $this->headerList = explode("\r\n", $this->headerText);
00768 }
00769
00770 curl_close( $curlHandle );
00771
00772 $this->parseHeader();
00773 $this->setStatus();
00774 return $this->status;
00775 }
00776 }
00777
00778 class PhpHttpRequest extends HttpRequest {
00779 protected $manuallyRedirect = false;
00780
00781 protected function urlToTcp( $url ) {
00782 $parsedUrl = parse_url( $url );
00783
00784 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
00785 }
00786
00787 public function execute() {
00788 parent::execute();
00789
00790
00791
00792 if ( version_compare( '5.1.7', phpversion(), '>' ) ) {
00793 $this->manuallyRedirect = true;
00794 }
00795
00796 if ( $this->parsedUrl['scheme'] != 'http' ) {
00797 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
00798 }
00799
00800 $this->reqHeaders['Accept'] = "*/*";
00801 if ( $this->method == 'POST' ) {
00802
00803 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
00804 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
00805 }
00806
00807 $options = array();
00808 if ( $this->proxy && !$this->noProxy ) {
00809 $options['proxy'] = $this->urlToTCP( $this->proxy );
00810 $options['request_fulluri'] = true;
00811 }
00812
00813 if ( !$this->followRedirects || $this->manuallyRedirect ) {
00814 $options['max_redirects'] = 0;
00815 } else {
00816 $options['max_redirects'] = $this->maxRedirects;
00817 }
00818
00819 $options['method'] = $this->method;
00820 $options['header'] = implode("\r\n", $this->getHeaderList());
00821
00822
00823
00824 $options['protocol_version'] = "1.0";
00825
00826
00827
00828 $options['ignore_errors'] = true;
00829
00830 if ( $this->postData ) {
00831 $options['content'] = $this->postData;
00832 }
00833
00834 $oldTimeout = false;
00835 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
00836 $oldTimeout = ini_set('default_socket_timeout', $this->timeout);
00837 } else {
00838 $options['timeout'] = $this->timeout;
00839 }
00840
00841 $context = stream_context_create( array( 'http' => $options ) );
00842
00843 $this->headerList = array();
00844 $reqCount = 0;
00845 $url = $this->url;
00846 do {
00847 $again = false;
00848 $reqCount++;
00849 wfSuppressWarnings();
00850 $fh = fopen( $url, "r", false, $context );
00851 wfRestoreWarnings();
00852 if ( $fh ) {
00853 $result = stream_get_meta_data( $fh );
00854 $this->headerList = $result['wrapper_data'];
00855 $this->parseHeader();
00856 $url = $this->getResponseHeader("Location");
00857 $again = $this->manuallyRedirect && $this->followRedirects && $url
00858 && $this->isRedirect() && $this->maxRedirects > $reqCount;
00859 }
00860 } while ( $again );
00861
00862 if ( $oldTimeout !== false ) {
00863 ini_set('default_socket_timeout', $oldTimeout);
00864 }
00865 $this->setStatus();
00866
00867 if ( $fh === false ) {
00868 $this->status->fatal( 'http-request-error' );
00869 return $this->status;
00870 }
00871
00872 if ( $result['timed_out'] ) {
00873 $this->status->fatal( 'http-timed-out', $this->url );
00874 return $this->status;
00875 }
00876
00877 if($this->status->isOK()) {
00878 while ( !feof( $fh ) ) {
00879 $buf = fread( $fh, 8192 );
00880 if ( $buf === false ) {
00881 $this->status->fatal( 'http-read-error' );
00882 break;
00883 }
00884 if ( strlen( $buf ) ) {
00885 call_user_func( $this->callback, $fh, $buf );
00886 }
00887 }
00888 }
00889 fclose( $fh );
00890
00891 return $this->status;
00892 }
00893 }