Update button focus and hover state according to spec
[mediawiki.git] / includes / HttpFunctions.php
blob825cd064e88c269a397d94adb0ff55d6e258a216
1 <?php
2 /**
3 * Various HTTP related functions.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup HTTP
24 /**
25 * @defgroup HTTP HTTP
28 /**
29 * Various HTTP related functions
30 * @ingroup HTTP
32 class Http {
33 static public $httpEngine = false;
35 /**
36 * Perform an HTTP request
38 * @param string $method HTTP method. Usually GET/POST
39 * @param string $url Full URL to act on. If protocol-relative, will be expanded to an http:// URL
40 * @param array $options Options to pass to MWHttpRequest object.
41 * Possible keys for the array:
42 * - timeout Timeout length in seconds
43 * - connectTimeout Timeout for connection, in seconds (curl only)
44 * - postData An array of key-value pairs or a url-encoded form data
45 * - proxy The proxy to use.
46 * Otherwise it will use $wgHTTPProxy (if set)
47 * Otherwise it will use the environment variable "http_proxy" (if set)
48 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
49 * - sslVerifyHost Verify hostname against certificate
50 * - sslVerifyCert Verify SSL certificate
51 * - caInfo Provide CA information
52 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
53 * - followRedirects Whether to follow redirects (defaults to false).
54 * Note: this should only be used when the target URL is trusted,
55 * to avoid attacks on intranet services accessible by HTTP.
56 * - userAgent A user agent, if you want to override the default
57 * MediaWiki/$wgVersion
58 * @param string $caller The method making this request, for profiling
59 * @return string|bool (bool)false on failure or a string on success
61 public static function request( $method, $url, $options = array(), $caller = __METHOD__ ) {
62 wfDebug( "HTTP: $method: $url\n" );
64 $options['method'] = strtoupper( $method );
66 if ( !isset( $options['timeout'] ) ) {
67 $options['timeout'] = 'default';
69 if ( !isset( $options['connectTimeout'] ) ) {
70 $options['connectTimeout'] = 'default';
73 $req = MWHttpRequest::factory( $url, $options, $caller );
74 $status = $req->execute();
76 $content = false;
77 if ( $status->isOK() ) {
78 $content = $req->getContent();
80 return $content;
83 /**
84 * Simple wrapper for Http::request( 'GET' )
85 * @see Http::request()
86 * @since 1.25 Second parameter $timeout removed. Second parameter
87 * is now $options which can be given a 'timeout'
89 * @param string $url
90 * @param array $options
91 * @param string $caller The method making this request, for profiling
92 * @return string
94 public static function get( $url, $options = array(), $caller = __METHOD__ ) {
95 $args = func_get_args();
96 if ( isset( $args[1] ) && ( is_string( $args[1] ) || is_numeric( $args[1] ) ) ) {
97 // Second was used to be the timeout
98 // And third parameter used to be $options
99 wfWarn( "Second parameter should not be a timeout.", 2 );
100 $options = isset( $args[2] ) && is_array( $args[2] ) ?
101 $args[2] : array();
102 $options['timeout'] = $args[1];
103 $caller = __METHOD__;
105 return Http::request( 'GET', $url, $options, $caller );
109 * Simple wrapper for Http::request( 'POST' )
110 * @see Http::request()
112 * @param string $url
113 * @param array $options
114 * @param string $caller The method making this request, for profiling
115 * @return string
117 public static function post( $url, $options = array(), $caller = __METHOD__ ) {
118 return Http::request( 'POST', $url, $options, $caller );
122 * Check if the URL can be served by localhost
124 * @param string $url Full url to check
125 * @return bool
127 public static function isLocalURL( $url ) {
128 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
130 if ( $wgCommandLineMode ) {
131 return false;
134 // Extract host part
135 $matches = array();
136 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
137 $host = $matches[1];
138 // Split up dotwise
139 $domainParts = explode( '.', $host );
140 // Check if this domain or any superdomain is listed as a local virtual host
141 $domainParts = array_reverse( $domainParts );
143 $domain = '';
144 $countParts = count( $domainParts );
145 for ( $i = 0; $i < $countParts; $i++ ) {
146 $domainPart = $domainParts[$i];
147 if ( $i == 0 ) {
148 $domain = $domainPart;
149 } else {
150 $domain = $domainPart . '.' . $domain;
153 if ( in_array( $domain, $wgLocalVirtualHosts )
154 || $wgConf->isLocalVHost( $domain )
156 return true;
161 return false;
165 * A standard user-agent we can use for external requests.
166 * @return string
168 public static function userAgent() {
169 global $wgVersion;
170 return "MediaWiki/$wgVersion";
174 * Checks that the given URI is a valid one. Hardcoding the
175 * protocols, because we only want protocols that both cURL
176 * and php support.
178 * file:// should not be allowed here for security purpose (r67684)
180 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
182 * @param string $uri URI to check for validity
183 * @return bool
185 public static function isValidURI( $uri ) {
186 return preg_match(
187 '/^https?:\/\/[^\/\s]\S*$/D',
188 $uri
194 * This wrapper class will call out to curl (if available) or fallback
195 * to regular PHP if necessary for handling internal HTTP requests.
197 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
198 * PHP's HTTP extension.
200 class MWHttpRequest {
201 const SUPPORTS_FILE_POSTS = false;
203 protected $content;
204 protected $timeout = 'default';
205 protected $headersOnly = null;
206 protected $postData = null;
207 protected $proxy = null;
208 protected $noProxy = false;
209 protected $sslVerifyHost = true;
210 protected $sslVerifyCert = true;
211 protected $caInfo = null;
212 protected $method = "GET";
213 protected $reqHeaders = array();
214 protected $url;
215 protected $parsedUrl;
216 protected $callback;
217 protected $maxRedirects = 5;
218 protected $followRedirects = false;
221 * @var CookieJar
223 protected $cookieJar;
225 protected $headerList = array();
226 protected $respVersion = "0.9";
227 protected $respStatus = "200 Ok";
228 protected $respHeaders = array();
230 public $status;
233 * @var Profiler
235 protected $profiler;
238 * @var string
240 protected $profileName;
243 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
244 * @param array $options (optional) extra params to pass (see Http::request())
245 * @param string $caller The method making this request, for profiling
246 * @param Profiler $profiler An instance of the profiler for profiling, or null
248 protected function __construct( $url, $options = array(), $caller = __METHOD__, $profiler = null ) {
249 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
251 $this->url = wfExpandUrl( $url, PROTO_HTTP );
252 $this->parsedUrl = wfParseUrl( $this->url );
254 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
255 $this->status = Status::newFatal( 'http-invalid-url' );
256 } else {
257 $this->status = Status::newGood( 100 ); // continue
260 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
261 $this->timeout = $options['timeout'];
262 } else {
263 $this->timeout = $wgHTTPTimeout;
265 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
266 $this->connectTimeout = $options['connectTimeout'];
267 } else {
268 $this->connectTimeout = $wgHTTPConnectTimeout;
270 if ( isset( $options['userAgent'] ) ) {
271 $this->setUserAgent( $options['userAgent'] );
274 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
275 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
277 foreach ( $members as $o ) {
278 if ( isset( $options[$o] ) ) {
279 // ensure that MWHttpRequest::method is always
280 // uppercased. Bug 36137
281 if ( $o == 'method' ) {
282 $options[$o] = strtoupper( $options[$o] );
284 $this->$o = $options[$o];
288 if ( $this->noProxy ) {
289 $this->proxy = ''; // noProxy takes precedence
292 // Profile based on what's calling us
293 $this->profiler = $profiler;
294 $this->profileName = $caller;
298 * Simple function to test if we can make any sort of requests at all, using
299 * cURL or fopen()
300 * @return bool
302 public static function canMakeRequests() {
303 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
307 * Generate a new request object
308 * @param string $url Url to use
309 * @param array $options (optional) extra params to pass (see Http::request())
310 * @param string $caller The method making this request, for profiling
311 * @throws MWException
312 * @return CurlHttpRequest|PhpHttpRequest
313 * @see MWHttpRequest::__construct
315 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
316 if ( !Http::$httpEngine ) {
317 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
318 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
319 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
320 ' Http::$httpEngine is set to "curl"' );
323 switch ( Http::$httpEngine ) {
324 case 'curl':
325 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
326 case 'php':
327 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
328 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
329 'needs to be enabled for pure PHP http requests to ' .
330 'work. If possible, curl should be used instead. See ' .
331 'http://php.net/curl.'
334 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
335 default:
336 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
341 * Get the body, or content, of the response to the request
343 * @return string
345 public function getContent() {
346 return $this->content;
350 * Set the parameters of the request
352 * @param array $args
353 * @todo overload the args param
355 public function setData( $args ) {
356 $this->postData = $args;
360 * Take care of setting up the proxy (do nothing if "noProxy" is set)
362 * @return void
364 public function proxySetup() {
365 global $wgHTTPProxy;
367 // If there is an explicit proxy set and proxies are not disabled, then use it
368 if ( $this->proxy && !$this->noProxy ) {
369 return;
372 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
373 // local URL and proxies are not disabled
374 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
375 $this->proxy = '';
376 } elseif ( $wgHTTPProxy ) {
377 $this->proxy = $wgHTTPProxy;
378 } elseif ( getenv( "http_proxy" ) ) {
379 $this->proxy = getenv( "http_proxy" );
384 * Set the user agent
385 * @param string $UA
387 public function setUserAgent( $UA ) {
388 $this->setHeader( 'User-Agent', $UA );
392 * Set an arbitrary header
393 * @param string $name
394 * @param string $value
396 public function setHeader( $name, $value ) {
397 // I feel like I should normalize the case here...
398 $this->reqHeaders[$name] = $value;
402 * Get an array of the headers
403 * @return array
405 public function getHeaderList() {
406 $list = array();
408 if ( $this->cookieJar ) {
409 $this->reqHeaders['Cookie'] =
410 $this->cookieJar->serializeToHttpRequest(
411 $this->parsedUrl['path'],
412 $this->parsedUrl['host']
416 foreach ( $this->reqHeaders as $name => $value ) {
417 $list[] = "$name: $value";
420 return $list;
424 * Set a read callback to accept data read from the HTTP request.
425 * By default, data is appended to an internal buffer which can be
426 * retrieved through $req->getContent().
428 * To handle data as it comes in -- especially for large files that
429 * would not fit in memory -- you can instead set your own callback,
430 * in the form function($resource, $buffer) where the first parameter
431 * is the low-level resource being read (implementation specific),
432 * and the second parameter is the data buffer.
434 * You MUST return the number of bytes handled in the buffer; if fewer
435 * bytes are reported handled than were passed to you, the HTTP fetch
436 * will be aborted.
438 * @param callable $callback
439 * @throws MWException
441 public function setCallback( $callback ) {
442 if ( !is_callable( $callback ) ) {
443 throw new MWException( 'Invalid MwHttpRequest callback' );
445 $this->callback = $callback;
449 * A generic callback to read the body of the response from a remote
450 * server.
452 * @param resource $fh
453 * @param string $content
454 * @return int
456 public function read( $fh, $content ) {
457 $this->content .= $content;
458 return strlen( $content );
462 * Take care of whatever is necessary to perform the URI request.
464 * @return Status
466 public function execute() {
468 $this->content = "";
470 if ( strtoupper( $this->method ) == "HEAD" ) {
471 $this->headersOnly = true;
474 $this->proxySetup(); // set up any proxy as needed
476 if ( !$this->callback ) {
477 $this->setCallback( array( $this, 'read' ) );
480 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
481 $this->setUserAgent( Http::userAgent() );
487 * Parses the headers, including the HTTP status code and any
488 * Set-Cookie headers. This function expects the headers to be
489 * found in an array in the member variable headerList.
491 protected function parseHeader() {
493 $lastname = "";
495 foreach ( $this->headerList as $header ) {
496 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
497 $this->respVersion = $match[1];
498 $this->respStatus = $match[2];
499 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
500 $last = count( $this->respHeaders[$lastname] ) - 1;
501 $this->respHeaders[$lastname][$last] .= "\r\n$header";
502 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
503 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
504 $lastname = strtolower( $match[1] );
508 $this->parseCookies();
513 * Sets HTTPRequest status member to a fatal value with the error
514 * message if the returned integer value of the status code was
515 * not successful (< 300) or a redirect (>=300 and < 400). (see
516 * RFC2616, section 10,
517 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
518 * list of status codes.)
520 protected function setStatus() {
521 if ( !$this->respHeaders ) {
522 $this->parseHeader();
525 if ( (int)$this->respStatus > 399 ) {
526 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
527 $this->status->fatal( "http-bad-status", $code, $message );
532 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
533 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
534 * for a list of status codes.)
536 * @return int
538 public function getStatus() {
539 if ( !$this->respHeaders ) {
540 $this->parseHeader();
543 return (int)$this->respStatus;
547 * Returns true if the last status code was a redirect.
549 * @return bool
551 public function isRedirect() {
552 if ( !$this->respHeaders ) {
553 $this->parseHeader();
556 $status = (int)$this->respStatus;
558 if ( $status >= 300 && $status <= 303 ) {
559 return true;
562 return false;
566 * Returns an associative array of response headers after the
567 * request has been executed. Because some headers
568 * (e.g. Set-Cookie) can appear more than once the, each value of
569 * the associative array is an array of the values given.
571 * @return array
573 public function getResponseHeaders() {
574 if ( !$this->respHeaders ) {
575 $this->parseHeader();
578 return $this->respHeaders;
582 * Returns the value of the given response header.
584 * @param string $header
585 * @return string
587 public function getResponseHeader( $header ) {
588 if ( !$this->respHeaders ) {
589 $this->parseHeader();
592 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
593 $v = $this->respHeaders[strtolower( $header )];
594 return $v[count( $v ) - 1];
597 return null;
601 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
603 * @param CookieJar $jar
605 public function setCookieJar( $jar ) {
606 $this->cookieJar = $jar;
610 * Returns the cookie jar in use.
612 * @return CookieJar
614 public function getCookieJar() {
615 if ( !$this->respHeaders ) {
616 $this->parseHeader();
619 return $this->cookieJar;
623 * Sets a cookie. Used before a request to set up any individual
624 * cookies. Used internally after a request to parse the
625 * Set-Cookie headers.
626 * @see Cookie::set
627 * @param string $name
628 * @param mixed $value
629 * @param array $attr
631 public function setCookie( $name, $value = null, $attr = null ) {
632 if ( !$this->cookieJar ) {
633 $this->cookieJar = new CookieJar;
636 $this->cookieJar->setCookie( $name, $value, $attr );
640 * Parse the cookies in the response headers and store them in the cookie jar.
642 protected function parseCookies() {
644 if ( !$this->cookieJar ) {
645 $this->cookieJar = new CookieJar;
648 if ( isset( $this->respHeaders['set-cookie'] ) ) {
649 $url = parse_url( $this->getFinalUrl() );
650 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
651 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
658 * Returns the final URL after all redirections.
660 * Relative values of the "Location" header are incorrect as
661 * stated in RFC, however they do happen and modern browsers
662 * support them. This function loops backwards through all
663 * locations in order to build the proper absolute URI - Marooned
664 * at wikia-inc.com
666 * Note that the multiple Location: headers are an artifact of
667 * CURL -- they shouldn't actually get returned this way. Rewrite
668 * this when bug 29232 is taken care of (high-level redirect
669 * handling rewrite).
671 * @return string
673 public function getFinalUrl() {
674 $headers = $this->getResponseHeaders();
676 //return full url (fix for incorrect but handled relative location)
677 if ( isset( $headers['location'] ) ) {
678 $locations = $headers['location'];
679 $domain = '';
680 $foundRelativeURI = false;
681 $countLocations = count( $locations );
683 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
684 $url = parse_url( $locations[$i] );
686 if ( isset( $url['host'] ) ) {
687 $domain = $url['scheme'] . '://' . $url['host'];
688 break; //found correct URI (with host)
689 } else {
690 $foundRelativeURI = true;
694 if ( $foundRelativeURI ) {
695 if ( $domain ) {
696 return $domain . $locations[$countLocations - 1];
697 } else {
698 $url = parse_url( $this->url );
699 if ( isset( $url['host'] ) ) {
700 return $url['scheme'] . '://' . $url['host'] .
701 $locations[$countLocations - 1];
704 } else {
705 return $locations[$countLocations - 1];
709 return $this->url;
713 * Returns true if the backend can follow redirects. Overridden by the
714 * child classes.
715 * @return bool
717 public function canFollowRedirects() {
718 return true;
723 * MWHttpRequest implemented using internal curl compiled into PHP
725 class CurlHttpRequest extends MWHttpRequest {
726 const SUPPORTS_FILE_POSTS = true;
728 protected $curlOptions = array();
729 protected $headerText = "";
732 * @param resource $fh
733 * @param string $content
734 * @return int
736 protected function readHeader( $fh, $content ) {
737 $this->headerText .= $content;
738 return strlen( $content );
741 public function execute() {
743 parent::execute();
745 if ( !$this->status->isOK() ) {
746 return $this->status;
749 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
750 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
752 // Only supported in curl >= 7.16.2
753 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
754 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
757 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
758 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
759 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
760 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
761 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
763 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
765 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
766 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
768 if ( $this->caInfo ) {
769 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
772 if ( $this->headersOnly ) {
773 $this->curlOptions[CURLOPT_NOBODY] = true;
774 $this->curlOptions[CURLOPT_HEADER] = true;
775 } elseif ( $this->method == 'POST' ) {
776 $this->curlOptions[CURLOPT_POST] = true;
777 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
778 // Suppress 'Expect: 100-continue' header, as some servers
779 // will reject it with a 417 and Curl won't auto retry
780 // with HTTP 1.0 fallback
781 $this->reqHeaders['Expect'] = '';
782 } else {
783 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
786 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
788 $curlHandle = curl_init( $this->url );
790 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
791 throw new MWException( "Error setting curl options." );
794 if ( $this->followRedirects && $this->canFollowRedirects() ) {
795 MediaWiki\suppressWarnings();
796 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
797 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
798 "Probably safe_mode or open_basedir is set.\n" );
799 // Continue the processing. If it were in curl_setopt_array,
800 // processing would have halted on its entry
802 MediaWiki\restoreWarnings();
805 if ( $this->profiler ) {
806 $profileSection = $this->profiler->scopedProfileIn(
807 __METHOD__ . '-' . $this->profileName
811 $curlRes = curl_exec( $curlHandle );
812 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
813 $this->status->fatal( 'http-timed-out', $this->url );
814 } elseif ( $curlRes === false ) {
815 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
816 } else {
817 $this->headerList = explode( "\r\n", $this->headerText );
820 curl_close( $curlHandle );
822 if ( $this->profiler ) {
823 $this->profiler->scopedProfileOut( $profileSection );
826 $this->parseHeader();
827 $this->setStatus();
829 return $this->status;
833 * @return bool
835 public function canFollowRedirects() {
836 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
837 wfDebug( "Cannot follow redirects in safe mode\n" );
838 return false;
841 $curlVersionInfo = curl_version();
842 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
843 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
844 return false;
847 return true;
851 class PhpHttpRequest extends MWHttpRequest {
854 * @param string $url
855 * @return string
857 protected function urlToTcp( $url ) {
858 $parsedUrl = parse_url( $url );
860 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
863 public function execute() {
865 parent::execute();
867 if ( is_array( $this->postData ) ) {
868 $this->postData = wfArrayToCgi( $this->postData );
871 if ( $this->parsedUrl['scheme'] != 'http'
872 && $this->parsedUrl['scheme'] != 'https' ) {
873 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
876 $this->reqHeaders['Accept'] = "*/*";
877 $this->reqHeaders['Connection'] = 'Close';
878 if ( $this->method == 'POST' ) {
879 // Required for HTTP 1.0 POSTs
880 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
881 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
882 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
886 // Set up PHP stream context
887 $options = array(
888 'http' => array(
889 'method' => $this->method,
890 'header' => implode( "\r\n", $this->getHeaderList() ),
891 'protocol_version' => '1.1',
892 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
893 'ignore_errors' => true,
894 'timeout' => $this->timeout,
895 // Curl options in case curlwrappers are installed
896 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
897 'curl_verify_ssl_peer' => $this->sslVerifyCert,
899 'ssl' => array(
900 'verify_peer' => $this->sslVerifyCert,
901 'SNI_enabled' => true,
905 if ( $this->proxy ) {
906 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
907 $options['http']['request_fulluri'] = true;
910 if ( $this->postData ) {
911 $options['http']['content'] = $this->postData;
914 if ( $this->sslVerifyHost ) {
915 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
918 if ( is_dir( $this->caInfo ) ) {
919 $options['ssl']['capath'] = $this->caInfo;
920 } elseif ( is_file( $this->caInfo ) ) {
921 $options['ssl']['cafile'] = $this->caInfo;
922 } elseif ( $this->caInfo ) {
923 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
926 $context = stream_context_create( $options );
928 $this->headerList = array();
929 $reqCount = 0;
930 $url = $this->url;
932 $result = array();
934 if ( $this->profiler ) {
935 $profileSection = $this->profiler->scopedProfileIn(
936 __METHOD__ . '-' . $this->profileName
939 do {
940 $reqCount++;
941 MediaWiki\suppressWarnings();
942 $fh = fopen( $url, "r", false, $context );
943 MediaWiki\restoreWarnings();
945 if ( !$fh ) {
946 break;
949 $result = stream_get_meta_data( $fh );
950 $this->headerList = $result['wrapper_data'];
951 $this->parseHeader();
953 if ( !$this->followRedirects ) {
954 break;
957 # Handle manual redirection
958 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
959 break;
961 # Check security of URL
962 $url = $this->getResponseHeader( "Location" );
964 if ( !Http::isValidURI( $url ) ) {
965 wfDebug( __METHOD__ . ": insecure redirection\n" );
966 break;
968 } while ( true );
969 if ( $this->profiler ) {
970 $this->profiler->scopedProfileOut( $profileSection );
973 $this->setStatus();
975 if ( $fh === false ) {
976 $this->status->fatal( 'http-request-error' );
977 return $this->status;
980 if ( $result['timed_out'] ) {
981 $this->status->fatal( 'http-timed-out', $this->url );
982 return $this->status;
985 // If everything went OK, or we received some error code
986 // get the response body content.
987 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
988 while ( !feof( $fh ) ) {
989 $buf = fread( $fh, 8192 );
991 if ( $buf === false ) {
992 $this->status->fatal( 'http-read-error' );
993 break;
996 if ( strlen( $buf ) ) {
997 call_user_func( $this->callback, $fh, $buf );
1001 fclose( $fh );
1003 return $this->status;