Part 1 of 2, moving ResourceLoader*Module classes to their own files - this commit...
[mediawiki.git] / includes / HttpFunctions.php
blob0dccebbd9733dda7c308d322401717868dad58e5
1 <?php
2 /**
3 * @defgroup HTTP HTTP
4 */
6 /**
7 * Various HTTP related functions
8 * @ingroup HTTP
9 */
10 class Http {
11 static $httpEngine = false;
13 /**
14 * Perform an HTTP request
16 * @param $method String: HTTP method. Usually GET/POST
17 * @param $url String: full URL to act on
18 * @param $options Array: options to pass to HttpRequest object.
19 * Possible keys for the array:
20 * - timeout Timeout length in seconds
21 * - postData An array of key-value pairs or a url-encoded form data
22 * - proxy The proxy to use.
23 * Will use $wgHTTPProxy (if set) otherwise.
24 * - noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
25 * - sslVerifyHost (curl only) Verify hostname against certificate
26 * - sslVerifyCert (curl only) Verify SSL certificate
27 * - caInfo (curl only) Provide CA information
28 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
29 * - followRedirects Whether to follow redirects (defaults to false).
30 * Note: this should only be used when the target URL is trusted,
31 * to avoid attacks on intranet services accessible by HTTP.
32 * @return Mixed: (bool)false on failure or a string on success
34 public static function request( $method, $url, $options = array() ) {
35 $url = wfExpandUrl( $url );
36 wfDebug( "HTTP: $method: $url\n" );
37 $options['method'] = strtoupper( $method );
39 if ( !isset( $options['timeout'] ) ) {
40 $options['timeout'] = 'default';
43 $req = HttpRequest::factory( $url, $options );
44 $status = $req->execute();
46 if ( $status->isOK() ) {
47 return $req->getContent();
48 } else {
49 return false;
53 /**
54 * Simple wrapper for Http::request( 'GET' )
55 * @see Http::request()
57 public static function get( $url, $timeout = 'default', $options = array() ) {
58 $options['timeout'] = $timeout;
59 return Http::request( 'GET', $url, $options );
62 /**
63 * Simple wrapper for Http::request( 'POST' )
64 * @see Http::request()
66 public static function post( $url, $options = array() ) {
67 return Http::request( 'POST', $url, $options );
70 /**
71 * Check if the URL can be served by localhost
73 * @param $url String: full url to check
74 * @return Boolean
76 public static function isLocalURL( $url ) {
77 global $wgCommandLineMode, $wgConf;
79 if ( $wgCommandLineMode ) {
80 return false;
83 // Extract host part
84 $matches = array();
85 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
86 $host = $matches[1];
87 // Split up dotwise
88 $domainParts = explode( '.', $host );
89 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
90 $domainParts = array_reverse( $domainParts );
92 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
93 $domainPart = $domainParts[$i];
94 if ( $i == 0 ) {
95 $domain = $domainPart;
96 } else {
97 $domain = $domainPart . '.' . $domain;
100 if ( $wgConf->isLocalVHost( $domain ) ) {
101 return true;
106 return false;
110 * A standard user-agent we can use for external requests.
111 * @return String
113 public static function userAgent() {
114 global $wgVersion;
115 return "MediaWiki/$wgVersion";
119 * Checks that the given URI is a valid one
121 * @param $uri Mixed: URI to check for validity
122 * @returns Boolean
124 public static function isValidURI( $uri ) {
125 return preg_match(
126 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
127 $uri,
128 $matches
134 * This wrapper class will call out to curl (if available) or fallback
135 * to regular PHP if necessary for handling internal HTTP requests.
137 class HttpRequest {
138 protected $content;
139 protected $timeout = 'default';
140 protected $headersOnly = null;
141 protected $postData = null;
142 protected $proxy = null;
143 protected $noProxy = false;
144 protected $sslVerifyHost = true;
145 protected $sslVerifyCert = true;
146 protected $caInfo = null;
147 protected $method = "GET";
148 protected $reqHeaders = array();
149 protected $url;
150 protected $parsedUrl;
151 protected $callback;
152 protected $maxRedirects = 5;
153 protected $followRedirects = false;
155 protected $cookieJar;
157 protected $headerList = array();
158 protected $respVersion = "0.9";
159 protected $respStatus = "200 Ok";
160 protected $respHeaders = array();
162 public $status;
165 * @param $url String: url to use
166 * @param $options Array: (optional) extra params to pass (see Http::request())
168 function __construct( $url, $options = array() ) {
169 global $wgHTTPTimeout;
171 $this->url = $url;
172 $this->parsedUrl = parse_url( $url );
174 if ( !Http::isValidURI( $this->url ) ) {
175 $this->status = Status::newFatal( 'http-invalid-url' );
176 } else {
177 $this->status = Status::newGood( 100 ); // continue
180 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
181 $this->timeout = $options['timeout'];
182 } else {
183 $this->timeout = $wgHTTPTimeout;
186 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
187 "method", "followRedirects", "maxRedirects", "sslVerifyCert" );
189 foreach ( $members as $o ) {
190 if ( isset( $options[$o] ) ) {
191 $this->$o = $options[$o];
197 * Generate a new request object
198 * @see HttpRequest::__construct
200 public static function factory( $url, $options = null ) {
201 if ( !Http::$httpEngine ) {
202 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
203 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
204 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
205 ' Http::$httpEngine is set to "curl"' );
208 switch( Http::$httpEngine ) {
209 case 'curl':
210 return new CurlHttpRequest( $url, $options );
211 case 'php':
212 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
213 throw new MWException( __METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' .
214 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
216 return new PhpHttpRequest( $url, $options );
217 default:
218 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
223 * Get the body, or content, of the response to the request
225 * @return String
227 public function getContent() {
228 return $this->content;
232 * Set the parameters of the request
234 * @param $args Array
235 * @todo overload the args param
237 public function setData( $args ) {
238 $this->postData = $args;
242 * Take care of setting up the proxy
243 * (override in subclass)
245 * @return String
247 public function proxySetup() {
248 global $wgHTTPProxy;
250 if ( $this->proxy ) {
251 return;
254 if ( Http::isLocalURL( $this->url ) ) {
255 $this->proxy = 'http://localhost:80/';
256 } elseif ( $wgHTTPProxy ) {
257 $this->proxy = $wgHTTPProxy ;
258 } elseif ( getenv( "http_proxy" ) ) {
259 $this->proxy = getenv( "http_proxy" );
264 * Set the refererer header
266 public function setReferer( $url ) {
267 $this->setHeader( 'Referer', $url );
271 * Set the user agent
273 public function setUserAgent( $UA ) {
274 $this->setHeader( 'User-Agent', $UA );
278 * Set an arbitrary header
280 public function setHeader( $name, $value ) {
281 // I feel like I should normalize the case here...
282 $this->reqHeaders[$name] = $value;
286 * Get an array of the headers
288 public function getHeaderList() {
289 $list = array();
291 if ( $this->cookieJar ) {
292 $this->reqHeaders['Cookie'] =
293 $this->cookieJar->serializeToHttpRequest(
294 $this->parsedUrl['path'],
295 $this->parsedUrl['host']
299 foreach ( $this->reqHeaders as $name => $value ) {
300 $list[] = "$name: $value";
303 return $list;
307 * Set the callback
309 * @param $callback Callback
311 public function setCallback( $callback ) {
312 $this->callback = $callback;
316 * A generic callback to read the body of the response from a remote
317 * server.
319 * @param $fh handle
320 * @param $content String
322 public function read( $fh, $content ) {
323 $this->content .= $content;
324 return strlen( $content );
328 * Take care of whatever is necessary to perform the URI request.
330 * @return Status
332 public function execute() {
333 global $wgTitle;
335 $this->content = "";
337 if ( strtoupper( $this->method ) == "HEAD" ) {
338 $this->headersOnly = true;
341 if ( is_array( $this->postData ) ) {
342 $this->postData = wfArrayToCGI( $this->postData );
345 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders['Referer'] ) ) {
346 $this->setReferer( $wgTitle->getFullURL() );
349 if ( !$this->noProxy ) {
350 $this->proxySetup();
353 if ( !$this->callback ) {
354 $this->setCallback( array( $this, 'read' ) );
357 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
358 $this->setUserAgent( Http::userAgent() );
363 * Parses the headers, including the HTTP status code and any
364 * Set-Cookie headers. This function expectes the headers to be
365 * found in an array in the member variable headerList.
367 * @return nothing
369 protected function parseHeader() {
370 $lastname = "";
372 foreach ( $this->headerList as $header ) {
373 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
374 $this->respVersion = $match[1];
375 $this->respStatus = $match[2];
376 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
377 $last = count( $this->respHeaders[$lastname] ) - 1;
378 $this->respHeaders[$lastname][$last] .= "\r\n$header";
379 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
380 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
381 $lastname = strtolower( $match[1] );
385 $this->parseCookies();
389 * Sets the member variable status to a fatal status if the HTTP
390 * status code was not 200.
392 * @return nothing
394 protected function setStatus() {
395 if ( !$this->respHeaders ) {
396 $this->parseHeader();
399 if ( (int)$this->respStatus !== 200 ) {
400 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
401 $this->status->fatal( "http-bad-status", $code, $message );
407 * Returns true if the last status code was a redirect.
409 * @return Boolean
411 public function isRedirect() {
412 if ( !$this->respHeaders ) {
413 $this->parseHeader();
416 $status = (int)$this->respStatus;
418 if ( $status >= 300 && $status <= 303 ) {
419 return true;
422 return false;
426 * Returns an associative array of response headers after the
427 * request has been executed. Because some headers
428 * (e.g. Set-Cookie) can appear more than once the, each value of
429 * the associative array is an array of the values given.
431 * @return Array
433 public function getResponseHeaders() {
434 if ( !$this->respHeaders ) {
435 $this->parseHeader();
438 return $this->respHeaders;
442 * Returns the value of the given response header.
444 * @param $header String
445 * @return String
447 public function getResponseHeader( $header ) {
448 if ( !$this->respHeaders ) {
449 $this->parseHeader();
452 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
453 $v = $this->respHeaders[strtolower ( $header ) ];
454 return $v[count( $v ) - 1];
457 return null;
461 * Tells the HttpRequest object to use this pre-loaded CookieJar.
463 * @param $jar CookieJar
465 public function setCookieJar( $jar ) {
466 $this->cookieJar = $jar;
470 * Returns the cookie jar in use.
472 * @returns CookieJar
474 public function getCookieJar() {
475 if ( !$this->respHeaders ) {
476 $this->parseHeader();
479 return $this->cookieJar;
483 * Sets a cookie. Used before a request to set up any individual
484 * cookies. Used internally after a request to parse the
485 * Set-Cookie headers.
486 * @see Cookie::set
488 public function setCookie( $name, $value = null, $attr = null ) {
489 if ( !$this->cookieJar ) {
490 $this->cookieJar = new CookieJar;
493 $this->cookieJar->setCookie( $name, $value, $attr );
497 * Parse the cookies in the response headers and store them in the cookie jar.
499 protected function parseCookies() {
500 if ( !$this->cookieJar ) {
501 $this->cookieJar = new CookieJar;
504 if ( isset( $this->respHeaders['set-cookie'] ) ) {
505 $url = parse_url( $this->getFinalUrl() );
506 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
507 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
513 * Returns the final URL after all redirections.
515 * @return String
517 public function getFinalUrl() {
518 $location = $this->getResponseHeader( "Location" );
520 if ( $location ) {
521 return $location;
524 return $this->url;
528 * Returns true if the backend can follow redirects. Overridden by the
529 * child classes.
531 public function canFollowRedirects() {
532 return true;
537 class Cookie {
538 protected $name;
539 protected $value;
540 protected $expires;
541 protected $path;
542 protected $domain;
543 protected $isSessionKey = true;
544 // TO IMPLEMENT protected $secure
545 // TO IMPLEMENT? protected $maxAge (add onto expires)
546 // TO IMPLEMENT? protected $version
547 // TO IMPLEMENT? protected $comment
549 function __construct( $name, $value, $attr ) {
550 $this->name = $name;
551 $this->set( $value, $attr );
555 * Sets a cookie. Used before a request to set up any individual
556 * cookies. Used internally after a request to parse the
557 * Set-Cookie headers.
559 * @param $value String: the value of the cookie
560 * @param $attr Array: possible key/values:
561 * expires A date string
562 * path The path this cookie is used on
563 * domain Domain this cookie is used on
565 public function set( $value, $attr ) {
566 $this->value = $value;
568 if ( isset( $attr['expires'] ) ) {
569 $this->isSessionKey = false;
570 $this->expires = strtotime( $attr['expires'] );
573 if ( isset( $attr['path'] ) ) {
574 $this->path = $attr['path'];
575 } else {
576 $this->path = "/";
579 if ( isset( $attr['domain'] ) ) {
580 if ( self::validateCookieDomain( $attr['domain'] ) ) {
581 $this->domain = $attr['domain'];
583 } else {
584 throw new MWException( "You must specify a domain." );
589 * Return the true if the cookie is valid is valid. Otherwise,
590 * false. The uses a method similar to IE cookie security
591 * described here:
592 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
593 * A better method might be to use a blacklist like
594 * http://publicsuffix.org/
596 * @param $domain String: the domain to validate
597 * @param $originDomain String: (optional) the domain the cookie originates from
598 * @return Boolean
600 public static function validateCookieDomain( $domain, $originDomain = null ) {
601 // Don't allow a trailing dot
602 if ( substr( $domain, -1 ) == "." ) {
603 return false;
606 $dc = explode( ".", $domain );
608 // Only allow full, valid IP addresses
609 if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
610 if ( count( $dc ) != 4 ) {
611 return false;
614 if ( ip2long( $domain ) === false ) {
615 return false;
618 if ( $originDomain == null || $originDomain == $domain ) {
619 return true;
624 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
625 if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
626 if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
627 || ( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
628 return false;
630 if ( ( count( $dc ) == 2 || ( count( $dc ) == 3 && $dc[0] == "" ) )
631 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
632 return false;
636 if ( $originDomain != null ) {
637 if ( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
638 return false;
641 if ( substr( $domain, 0, 1 ) == "."
642 && substr_compare( $originDomain, $domain, -strlen( $domain ),
643 strlen( $domain ), TRUE ) != 0 ) {
644 return false;
648 return true;
652 * Serialize the cookie jar into a format useful for HTTP Request headers.
654 * @param $path String: the path that will be used. Required.
655 * @param $domain String: the domain that will be used. Required.
656 * @return String
658 public function serializeToHttpRequest( $path, $domain ) {
659 $ret = "";
661 if ( $this->canServeDomain( $domain )
662 && $this->canServePath( $path )
663 && $this->isUnExpired() ) {
664 $ret = $this->name . "=" . $this->value;
667 return $ret;
670 protected function canServeDomain( $domain ) {
671 if ( $domain == $this->domain
672 || ( strlen( $domain ) > strlen( $this->domain )
673 && substr( $this->domain, 0, 1 ) == "."
674 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
675 strlen( $this->domain ), TRUE ) == 0 ) ) {
676 return true;
679 return false;
682 protected function canServePath( $path ) {
683 if ( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
684 return true;
687 return false;
690 protected function isUnExpired() {
691 if ( $this->isSessionKey || $this->expires > time() ) {
692 return true;
695 return false;
699 class CookieJar {
700 private $cookie = array();
703 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
704 * @see Cookie::set()
706 public function setCookie ( $name, $value, $attr ) {
707 /* cookies: case insensitive, so this should work.
708 * We'll still send the cookies back in the same case we got them, though.
710 $index = strtoupper( $name );
712 if ( isset( $this->cookie[$index] ) ) {
713 $this->cookie[$index]->set( $value, $attr );
714 } else {
715 $this->cookie[$index] = new Cookie( $name, $value, $attr );
720 * @see Cookie::serializeToHttpRequest
722 public function serializeToHttpRequest( $path, $domain ) {
723 $cookies = array();
725 foreach ( $this->cookie as $c ) {
726 $serialized = $c->serializeToHttpRequest( $path, $domain );
728 if ( $serialized ) {
729 $cookies[] = $serialized;
733 return implode( "; ", $cookies );
737 * Parse the content of an Set-Cookie HTTP Response header.
739 * @param $cookie String
740 * @param $domain String: cookie's domain
742 public function parseCookieResponseHeader ( $cookie, $domain ) {
743 $len = strlen( "Set-Cookie:" );
745 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
746 $cookie = substr( $cookie, $len );
749 $bit = array_map( 'trim', explode( ";", $cookie ) );
751 if ( count( $bit ) >= 1 ) {
752 list( $name, $value ) = explode( "=", array_shift( $bit ), 2 );
753 $attr = array();
755 foreach ( $bit as $piece ) {
756 $parts = explode( "=", $piece );
757 if ( count( $parts ) > 1 ) {
758 $attr[strtolower( $parts[0] )] = $parts[1];
759 } else {
760 $attr[strtolower( $parts[0] )] = true;
764 if ( !isset( $attr['domain'] ) ) {
765 $attr['domain'] = $domain;
766 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
767 return null;
770 $this->setCookie( $name, $value, $attr );
776 * HttpRequest implemented using internal curl compiled into PHP
778 class CurlHttpRequest extends HttpRequest {
779 static $curlMessageMap = array(
780 6 => 'http-host-unreachable',
781 28 => 'http-timed-out'
784 protected $curlOptions = array();
785 protected $headerText = "";
787 protected function readHeader( $fh, $content ) {
788 $this->headerText .= $content;
789 return strlen( $content );
792 public function execute() {
793 parent::execute();
795 if ( !$this->status->isOK() ) {
796 return $this->status;
799 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
800 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
801 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
802 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
803 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
804 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
805 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
807 /* not sure these two are actually necessary */
808 if ( isset( $this->reqHeaders['Referer'] ) ) {
809 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
811 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
813 if ( isset( $this->sslVerifyHost ) ) {
814 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
817 if ( isset( $this->sslVerifyCert ) ) {
818 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
821 if ( $this->caInfo ) {
822 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
825 if ( $this->headersOnly ) {
826 $this->curlOptions[CURLOPT_NOBODY] = true;
827 $this->curlOptions[CURLOPT_HEADER] = true;
828 } elseif ( $this->method == 'POST' ) {
829 $this->curlOptions[CURLOPT_POST] = true;
830 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
831 // Suppress 'Expect: 100-continue' header, as some servers
832 // will reject it with a 417 and Curl won't auto retry
833 // with HTTP 1.0 fallback
834 $this->reqHeaders['Expect'] = '';
835 } else {
836 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
839 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
841 $curlHandle = curl_init( $this->url );
843 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
844 throw new MWException( "Error setting curl options." );
847 if ( $this->followRedirects && $this->canFollowRedirects() ) {
848 if ( ! @curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
849 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
850 "Probably safe_mode or open_basedir is set.\n" );
851 // Continue the processing. If it were in curl_setopt_array,
852 // processing would have halted on its entry
856 if ( false === curl_exec( $curlHandle ) ) {
857 $code = curl_error( $curlHandle );
859 if ( isset( self::$curlMessageMap[$code] ) ) {
860 $this->status->fatal( self::$curlMessageMap[$code] );
861 } else {
862 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
864 } else {
865 $this->headerList = explode( "\r\n", $this->headerText );
868 curl_close( $curlHandle );
870 $this->parseHeader();
871 $this->setStatus();
873 return $this->status;
876 public function canFollowRedirects() {
877 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
878 wfDebug( "Cannot follow redirects in safe mode\n" );
879 return false;
882 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
883 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
884 return false;
887 return true;
891 class PhpHttpRequest extends HttpRequest {
892 protected function urlToTcp( $url ) {
893 $parsedUrl = parse_url( $url );
895 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
898 public function execute() {
899 parent::execute();
901 // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
902 // causes a segfault
903 $manuallyRedirect = version_compare( phpversion(), '5.1.7', '<' );
905 if ( $this->parsedUrl['scheme'] != 'http' ) {
906 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
909 $this->reqHeaders['Accept'] = "*/*";
910 if ( $this->method == 'POST' ) {
911 // Required for HTTP 1.0 POSTs
912 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
913 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
916 $options = array();
917 if ( $this->proxy && !$this->noProxy ) {
918 $options['proxy'] = $this->urlToTCP( $this->proxy );
919 $options['request_fulluri'] = true;
922 if ( !$this->followRedirects || $manuallyRedirect ) {
923 $options['max_redirects'] = 0;
924 } else {
925 $options['max_redirects'] = $this->maxRedirects;
928 $options['method'] = $this->method;
929 $options['header'] = implode( "\r\n", $this->getHeaderList() );
930 // Note that at some future point we may want to support
931 // HTTP/1.1, but we'd have to write support for chunking
932 // in version of PHP < 5.3.1
933 $options['protocol_version'] = "1.0";
935 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
936 // Only works on 5.2.10+
937 $options['ignore_errors'] = true;
939 if ( $this->postData ) {
940 $options['content'] = $this->postData;
943 $oldTimeout = false;
944 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
945 $oldTimeout = ini_set( 'default_socket_timeout', $this->timeout );
946 } else {
947 $options['timeout'] = $this->timeout;
950 $context = stream_context_create( array( 'http' => $options ) );
952 $this->headerList = array();
953 $reqCount = 0;
954 $url = $this->url;
956 do {
957 $reqCount++;
958 wfSuppressWarnings();
959 $fh = fopen( $url, "r", false, $context );
960 wfRestoreWarnings();
962 if ( !$fh ) {
963 break;
966 $result = stream_get_meta_data( $fh );
967 $this->headerList = $result['wrapper_data'];
968 $this->parseHeader();
970 if ( !$manuallyRedirect || !$this->followRedirects ) {
971 break;
974 # Handle manual redirection
975 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
976 break;
978 # Check security of URL
979 $url = $this->getResponseHeader( "Location" );
981 if ( substr( $url, 0, 7 ) !== 'http://' ) {
982 wfDebug( __METHOD__ . ": insecure redirection\n" );
983 break;
985 } while ( true );
987 if ( $oldTimeout !== false ) {
988 ini_set( 'default_socket_timeout', $oldTimeout );
991 $this->setStatus();
993 if ( $fh === false ) {
994 $this->status->fatal( 'http-request-error' );
995 return $this->status;
998 if ( $result['timed_out'] ) {
999 $this->status->fatal( 'http-timed-out', $this->url );
1000 return $this->status;
1003 if ( $this->status->isOK() ) {
1004 while ( !feof( $fh ) ) {
1005 $buf = fread( $fh, 8192 );
1007 if ( $buf === false ) {
1008 $this->status->fatal( 'http-read-error' );
1009 break;
1012 if ( strlen( $buf ) ) {
1013 call_user_func( $this->callback, $fh, $buf );
1017 fclose( $fh );
1019 return $this->status;