7 * Various HTTP related functions
11 static $httpEngine = false;
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 MWHttpRequest 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 = MWHttpRequest
::factory( $url, $options );
44 $status = $req->execute();
46 if ( $status->isOK() ) {
47 return $req->getContent();
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 );
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 );
71 * Check if the URL can be served by localhost
73 * @param $url String: full url to check
76 public static function isLocalURL( $url ) {
77 global $wgCommandLineMode, $wgConf;
79 if ( $wgCommandLineMode ) {
85 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
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 );
93 for ( $i = 0; $i < count( $domainParts ); $i++
) {
94 $domainPart = $domainParts[$i];
96 $domain = $domainPart;
98 $domain = $domainPart . '.' . $domain;
101 if ( $wgConf->isLocalVHost( $domain ) ) {
111 * A standard user-agent we can use for external requests.
114 public static function userAgent() {
116 return "MediaWiki/$wgVersion";
120 * Checks that the given URI is a valid one
122 * @param $uri Mixed: URI to check for validity
125 public static function isValidURI( $uri ) {
127 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
135 * This wrapper class will call out to curl (if available) or fallback
136 * to regular PHP if necessary for handling internal HTTP requests.
138 * Renamed from HttpRequest to MWHttpRequst to avoid conflict with
139 * php's HTTP extension.
141 class MWHttpRequest
{
143 protected $timeout = 'default';
144 protected $headersOnly = null;
145 protected $postData = null;
146 protected $proxy = null;
147 protected $noProxy = false;
148 protected $sslVerifyHost = true;
149 protected $sslVerifyCert = true;
150 protected $caInfo = null;
151 protected $method = "GET";
152 protected $reqHeaders = array();
154 protected $parsedUrl;
156 protected $maxRedirects = 5;
157 protected $followRedirects = false;
159 protected $cookieJar;
161 protected $headerList = array();
162 protected $respVersion = "0.9";
163 protected $respStatus = "200 Ok";
164 protected $respHeaders = array();
169 * @param $url String: url to use
170 * @param $options Array: (optional) extra params to pass (see Http::request())
172 function __construct( $url, $options = array() ) {
173 global $wgHTTPTimeout;
176 $this->parsedUrl
= parse_url( $url );
178 if ( !Http
::isValidURI( $this->url
) ) {
179 $this->status
= Status
::newFatal( 'http-invalid-url' );
181 $this->status
= Status
::newGood( 100 ); // continue
184 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
185 $this->timeout
= $options['timeout'];
187 $this->timeout
= $wgHTTPTimeout;
190 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
191 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
193 foreach ( $members as $o ) {
194 if ( isset( $options[$o] ) ) {
195 $this->$o = $options[$o];
201 * Generate a new request object
202 * @param $url String: url to use
203 * @param $options Array: (optional) extra params to pass (see Http::request())
204 * @see MWHttpRequest::__construct
206 public static function factory( $url, $options = null ) {
207 if ( !Http
::$httpEngine ) {
208 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
209 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
210 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
211 ' Http::$httpEngine is set to "curl"' );
214 switch( Http
::$httpEngine ) {
216 return new CurlHttpRequest( $url, $options );
218 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
219 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
220 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
222 return new PhpHttpRequest( $url, $options );
224 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
229 * Get the body, or content, of the response to the request
233 public function getContent() {
234 return $this->content
;
238 * Set the parameters of the request
241 * @todo overload the args param
243 public function setData( $args ) {
244 $this->postData
= $args;
248 * Take care of setting up the proxy
249 * (override in subclass)
253 public function proxySetup() {
256 if ( $this->proxy
) {
260 if ( Http
::isLocalURL( $this->url
) ) {
261 $this->proxy
= 'http://localhost:80/';
262 } elseif ( $wgHTTPProxy ) {
263 $this->proxy
= $wgHTTPProxy ;
264 } elseif ( getenv( "http_proxy" ) ) {
265 $this->proxy
= getenv( "http_proxy" );
270 * Set the refererer header
272 public function setReferer( $url ) {
273 $this->setHeader( 'Referer', $url );
279 public function setUserAgent( $UA ) {
280 $this->setHeader( 'User-Agent', $UA );
284 * Set an arbitrary header
286 public function setHeader( $name, $value ) {
287 // I feel like I should normalize the case here...
288 $this->reqHeaders
[$name] = $value;
292 * Get an array of the headers
294 public function getHeaderList() {
297 if ( $this->cookieJar
) {
298 $this->reqHeaders
['Cookie'] =
299 $this->cookieJar
->serializeToHttpRequest(
300 $this->parsedUrl
['path'],
301 $this->parsedUrl
['host']
305 foreach ( $this->reqHeaders
as $name => $value ) {
306 $list[] = "$name: $value";
315 * @param $callback Callback
317 public function setCallback( $callback ) {
318 $this->callback
= $callback;
322 * A generic callback to read the body of the response from a remote
326 * @param $content String
328 public function read( $fh, $content ) {
329 $this->content
.= $content;
330 return strlen( $content );
334 * Take care of whatever is necessary to perform the URI request.
338 public function execute() {
343 if ( strtoupper( $this->method
) == "HEAD" ) {
344 $this->headersOnly
= true;
347 if ( is_array( $this->postData
) ) {
348 $this->postData
= wfArrayToCGI( $this->postData
);
351 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
352 $this->setReferer( $wgTitle->getFullURL() );
355 if ( !$this->noProxy
) {
359 if ( !$this->callback
) {
360 $this->setCallback( array( $this, 'read' ) );
363 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
364 $this->setUserAgent( Http
::userAgent() );
369 * Parses the headers, including the HTTP status code and any
370 * Set-Cookie headers. This function expectes the headers to be
371 * found in an array in the member variable headerList.
375 protected function parseHeader() {
378 foreach ( $this->headerList
as $header ) {
379 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
380 $this->respVersion
= $match[1];
381 $this->respStatus
= $match[2];
382 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
383 $last = count( $this->respHeaders
[$lastname] ) - 1;
384 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
385 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
386 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
387 $lastname = strtolower( $match[1] );
391 $this->parseCookies();
395 * Sets HTTPRequest status member to a fatal value with the error
396 * message if the returned integer value of the status code was
397 * not successful (< 300) or a redirect (>=300 and < 400). (see
398 * RFC2616, section 10,
399 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
400 * list of status codes.)
404 protected function setStatus() {
405 if ( !$this->respHeaders
) {
406 $this->parseHeader();
409 if ( (int)$this->respStatus
> 399 ) {
410 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
411 $this->status
->fatal( "http-bad-status", $code, $message );
416 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
417 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
418 * for a list of status codes.)
422 public function getStatus() {
423 if ( !$this->respHeaders
) {
424 $this->parseHeader();
427 return (int)$this->respStatus
;
432 * Returns true if the last status code was a redirect.
436 public function isRedirect() {
437 if ( !$this->respHeaders
) {
438 $this->parseHeader();
441 $status = (int)$this->respStatus
;
443 if ( $status >= 300 && $status <= 303 ) {
451 * Returns an associative array of response headers after the
452 * request has been executed. Because some headers
453 * (e.g. Set-Cookie) can appear more than once the, each value of
454 * the associative array is an array of the values given.
458 public function getResponseHeaders() {
459 if ( !$this->respHeaders
) {
460 $this->parseHeader();
463 return $this->respHeaders
;
467 * Returns the value of the given response header.
469 * @param $header String
472 public function getResponseHeader( $header ) {
473 if ( !$this->respHeaders
) {
474 $this->parseHeader();
477 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
478 $v = $this->respHeaders
[strtolower ( $header ) ];
479 return $v[count( $v ) - 1];
486 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
488 * @param $jar CookieJar
490 public function setCookieJar( $jar ) {
491 $this->cookieJar
= $jar;
495 * Returns the cookie jar in use.
499 public function getCookieJar() {
500 if ( !$this->respHeaders
) {
501 $this->parseHeader();
504 return $this->cookieJar
;
508 * Sets a cookie. Used before a request to set up any individual
509 * cookies. Used internally after a request to parse the
510 * Set-Cookie headers.
513 public function setCookie( $name, $value = null, $attr = null ) {
514 if ( !$this->cookieJar
) {
515 $this->cookieJar
= new CookieJar
;
518 $this->cookieJar
->setCookie( $name, $value, $attr );
522 * Parse the cookies in the response headers and store them in the cookie jar.
524 protected function parseCookies() {
525 if ( !$this->cookieJar
) {
526 $this->cookieJar
= new CookieJar
;
529 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
530 $url = parse_url( $this->getFinalUrl() );
531 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
532 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
538 * Returns the final URL after all redirections.
542 public function getFinalUrl() {
543 $location = $this->getResponseHeader( "Location" );
553 * Returns true if the backend can follow redirects. Overridden by the
556 public function canFollowRedirects() {
568 protected $isSessionKey = true;
569 // TO IMPLEMENT protected $secure
570 // TO IMPLEMENT? protected $maxAge (add onto expires)
571 // TO IMPLEMENT? protected $version
572 // TO IMPLEMENT? protected $comment
574 function __construct( $name, $value, $attr ) {
576 $this->set( $value, $attr );
580 * Sets a cookie. Used before a request to set up any individual
581 * cookies. Used internally after a request to parse the
582 * Set-Cookie headers.
584 * @param $value String: the value of the cookie
585 * @param $attr Array: possible key/values:
586 * expires A date string
587 * path The path this cookie is used on
588 * domain Domain this cookie is used on
590 public function set( $value, $attr ) {
591 $this->value
= $value;
593 if ( isset( $attr['expires'] ) ) {
594 $this->isSessionKey
= false;
595 $this->expires
= strtotime( $attr['expires'] );
598 if ( isset( $attr['path'] ) ) {
599 $this->path
= $attr['path'];
604 if ( isset( $attr['domain'] ) ) {
605 if ( self
::validateCookieDomain( $attr['domain'] ) ) {
606 $this->domain
= $attr['domain'];
609 throw new MWException( "You must specify a domain." );
614 * Return the true if the cookie is valid is valid. Otherwise,
615 * false. The uses a method similar to IE cookie security
617 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
618 * A better method might be to use a blacklist like
619 * http://publicsuffix.org/
621 * @param $domain String: the domain to validate
622 * @param $originDomain String: (optional) the domain the cookie originates from
625 public static function validateCookieDomain( $domain, $originDomain = null ) {
626 // Don't allow a trailing dot
627 if ( substr( $domain, -1 ) == "." ) {
631 $dc = explode( ".", $domain );
633 // Only allow full, valid IP addresses
634 if ( preg_match( '/^[0-9.]+$/', $domain ) ) {
635 if ( count( $dc ) != 4 ) {
639 if ( ip2long( $domain ) === false ) {
643 if ( $originDomain == null ||
$originDomain == $domain ) {
649 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
650 if ( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
651 if ( ( count( $dc ) == 2 && strlen( $dc[0] ) <= 2 )
652 ||
( count( $dc ) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
655 if ( ( count( $dc ) == 2 ||
( count( $dc ) == 3 && $dc[0] == "" ) )
656 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain ) ) {
661 if ( $originDomain != null ) {
662 if ( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
666 if ( substr( $domain, 0, 1 ) == "."
667 && substr_compare( $originDomain, $domain, -strlen( $domain ),
668 strlen( $domain ), TRUE ) != 0 ) {
677 * Serialize the cookie jar into a format useful for HTTP Request headers.
679 * @param $path String: the path that will be used. Required.
680 * @param $domain String: the domain that will be used. Required.
683 public function serializeToHttpRequest( $path, $domain ) {
686 if ( $this->canServeDomain( $domain )
687 && $this->canServePath( $path )
688 && $this->isUnExpired() ) {
689 $ret = $this->name
. "=" . $this->value
;
695 protected function canServeDomain( $domain ) {
696 if ( $domain == $this->domain
697 ||
( strlen( $domain ) > strlen( $this->domain
)
698 && substr( $this->domain
, 0, 1 ) == "."
699 && substr_compare( $domain, $this->domain
, -strlen( $this->domain
),
700 strlen( $this->domain
), TRUE ) == 0 ) ) {
707 protected function canServePath( $path ) {
708 if ( $this->path
&& substr_compare( $this->path
, $path, 0, strlen( $this->path
) ) == 0 ) {
715 protected function isUnExpired() {
716 if ( $this->isSessionKey ||
$this->expires
> time() ) {
725 private $cookie = array();
728 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
731 public function setCookie ( $name, $value, $attr ) {
732 /* cookies: case insensitive, so this should work.
733 * We'll still send the cookies back in the same case we got them, though.
735 $index = strtoupper( $name );
737 if ( isset( $this->cookie
[$index] ) ) {
738 $this->cookie
[$index]->set( $value, $attr );
740 $this->cookie
[$index] = new Cookie( $name, $value, $attr );
745 * @see Cookie::serializeToHttpRequest
747 public function serializeToHttpRequest( $path, $domain ) {
750 foreach ( $this->cookie
as $c ) {
751 $serialized = $c->serializeToHttpRequest( $path, $domain );
754 $cookies[] = $serialized;
758 return implode( "; ", $cookies );
762 * Parse the content of an Set-Cookie HTTP Response header.
764 * @param $cookie String
765 * @param $domain String: cookie's domain
767 public function parseCookieResponseHeader ( $cookie, $domain ) {
768 $len = strlen( "Set-Cookie:" );
770 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
771 $cookie = substr( $cookie, $len );
774 $bit = array_map( 'trim', explode( ";", $cookie ) );
776 if ( count( $bit ) >= 1 ) {
777 list( $name, $value ) = explode( "=", array_shift( $bit ), 2 );
780 foreach ( $bit as $piece ) {
781 $parts = explode( "=", $piece );
782 if ( count( $parts ) > 1 ) {
783 $attr[strtolower( $parts[0] )] = $parts[1];
785 $attr[strtolower( $parts[0] )] = true;
789 if ( !isset( $attr['domain'] ) ) {
790 $attr['domain'] = $domain;
791 } elseif ( !Cookie
::validateCookieDomain( $attr['domain'], $domain ) ) {
795 $this->setCookie( $name, $value, $attr );
801 * MWHttpRequest implemented using internal curl compiled into PHP
803 class CurlHttpRequest
extends MWHttpRequest
{
804 static $curlMessageMap = array(
805 6 => 'http-host-unreachable',
806 28 => 'http-timed-out'
809 protected $curlOptions = array();
810 protected $headerText = "";
812 protected function readHeader( $fh, $content ) {
813 $this->headerText
.= $content;
814 return strlen( $content );
817 public function execute() {
820 if ( !$this->status
->isOK() ) {
821 return $this->status
;
824 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
825 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
826 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
827 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
828 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
829 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
830 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
832 /* not sure these two are actually necessary */
833 if ( isset( $this->reqHeaders
['Referer'] ) ) {
834 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
836 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
838 if ( isset( $this->sslVerifyHost
) ) {
839 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
842 if ( isset( $this->sslVerifyCert
) ) {
843 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
846 if ( $this->caInfo
) {
847 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
850 if ( $this->headersOnly
) {
851 $this->curlOptions
[CURLOPT_NOBODY
] = true;
852 $this->curlOptions
[CURLOPT_HEADER
] = true;
853 } elseif ( $this->method
== 'POST' ) {
854 $this->curlOptions
[CURLOPT_POST
] = true;
855 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
856 // Suppress 'Expect: 100-continue' header, as some servers
857 // will reject it with a 417 and Curl won't auto retry
858 // with HTTP 1.0 fallback
859 $this->reqHeaders
['Expect'] = '';
861 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
864 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
866 $curlHandle = curl_init( $this->url
);
868 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
869 throw new MWException( "Error setting curl options." );
872 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
873 wfSuppressWarnings();
874 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
875 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
876 "Probably safe_mode or open_basedir is set.\n" );
877 // Continue the processing. If it were in curl_setopt_array,
878 // processing would have halted on its entry
883 if ( false === curl_exec( $curlHandle ) ) {
884 $code = curl_error( $curlHandle );
886 if ( isset( self
::$curlMessageMap[$code] ) ) {
887 $this->status
->fatal( self
::$curlMessageMap[$code] );
889 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
892 $this->headerList
= explode( "\r\n", $this->headerText
);
895 curl_close( $curlHandle );
897 $this->parseHeader();
900 return $this->status
;
903 public function canFollowRedirects() {
904 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
905 wfDebug( "Cannot follow redirects in safe mode\n" );
909 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
910 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
918 class PhpHttpRequest
extends MWHttpRequest
{
919 protected function urlToTcp( $url ) {
920 $parsedUrl = parse_url( $url );
922 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
925 public function execute() {
928 // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
930 $manuallyRedirect = version_compare( phpversion(), '5.1.7', '<' );
932 if ( $this->parsedUrl
['scheme'] != 'http' ) {
933 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
936 $this->reqHeaders
['Accept'] = "*/*";
937 if ( $this->method
== 'POST' ) {
938 // Required for HTTP 1.0 POSTs
939 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
940 $this->reqHeaders
['Content-type'] = "application/x-www-form-urlencoded";
944 if ( $this->proxy
&& !$this->noProxy
) {
945 $options['proxy'] = $this->urlToTCP( $this->proxy
);
946 $options['request_fulluri'] = true;
949 if ( !$this->followRedirects ||
$manuallyRedirect ) {
950 $options['max_redirects'] = 0;
952 $options['max_redirects'] = $this->maxRedirects
;
955 $options['method'] = $this->method
;
956 $options['header'] = implode( "\r\n", $this->getHeaderList() );
957 // Note that at some future point we may want to support
958 // HTTP/1.1, but we'd have to write support for chunking
959 // in version of PHP < 5.3.1
960 $options['protocol_version'] = "1.0";
962 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
963 // Only works on 5.2.10+
964 $options['ignore_errors'] = true;
966 if ( $this->postData
) {
967 $options['content'] = $this->postData
;
971 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
972 $oldTimeout = ini_set( 'default_socket_timeout', $this->timeout
);
974 $options['timeout'] = $this->timeout
;
977 $context = stream_context_create( array( 'http' => $options ) );
979 $this->headerList
= array();
985 wfSuppressWarnings();
986 $fh = fopen( $url, "r", false, $context );
993 $result = stream_get_meta_data( $fh );
994 $this->headerList
= $result['wrapper_data'];
995 $this->parseHeader();
997 if ( !$manuallyRedirect ||
!$this->followRedirects
) {
1001 # Handle manual redirection
1002 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
1005 # Check security of URL
1006 $url = $this->getResponseHeader( "Location" );
1008 if ( substr( $url, 0, 7 ) !== 'http://' ) {
1009 wfDebug( __METHOD__
. ": insecure redirection\n" );
1014 if ( $oldTimeout !== false ) {
1015 ini_set( 'default_socket_timeout', $oldTimeout );
1020 if ( $fh === false ) {
1021 $this->status
->fatal( 'http-request-error' );
1022 return $this->status
;
1025 if ( $result['timed_out'] ) {
1026 $this->status
->fatal( 'http-timed-out', $this->url
);
1027 return $this->status
;
1030 if ( $this->status
->isOK() ) {
1031 while ( !feof( $fh ) ) {
1032 $buf = fread( $fh, 8192 );
1034 if ( $buf === false ) {
1035 $this->status
->fatal( 'http-read-error' );
1039 if ( strlen( $buf ) ) {
1040 call_user_func( $this->callback
, $fh, $buf );
1046 return $this->status
;