Remove vendor prefix support for SVG embedding
[mediawiki.git] / includes / HttpFunctions.php
blob60196aba5b87725d8ea1588aa8ddc37244ae8f11
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 use MediaWiki\Logger\LoggerFactory;
30 /**
31 * Various HTTP related functions
32 * @ingroup HTTP
34 class Http {
35 static public $httpEngine = false;
37 /**
38 * Perform an HTTP request
40 * @param string $method HTTP method. Usually GET/POST
41 * @param string $url Full URL to act on. If protocol-relative, will be expanded to an http:// URL
42 * @param array $options Options to pass to MWHttpRequest object.
43 * Possible keys for the array:
44 * - timeout Timeout length in seconds
45 * - connectTimeout Timeout for connection, in seconds (curl only)
46 * - postData An array of key-value pairs or a url-encoded form data
47 * - proxy The proxy to use.
48 * Otherwise it will use $wgHTTPProxy (if set)
49 * Otherwise it will use the environment variable "http_proxy" (if set)
50 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
51 * - sslVerifyHost Verify hostname against certificate
52 * - sslVerifyCert Verify SSL certificate
53 * - caInfo Provide CA information
54 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
55 * - followRedirects Whether to follow redirects (defaults to false).
56 * Note: this should only be used when the target URL is trusted,
57 * to avoid attacks on intranet services accessible by HTTP.
58 * - userAgent A user agent, if you want to override the default
59 * MediaWiki/$wgVersion
60 * @param string $caller The method making this request, for profiling
61 * @return string|bool (bool)false on failure or a string on success
63 public static function request( $method, $url, $options = array(), $caller = __METHOD__ ) {
64 wfDebug( "HTTP: $method: $url\n" );
66 $options['method'] = strtoupper( $method );
68 if ( !isset( $options['timeout'] ) ) {
69 $options['timeout'] = 'default';
71 if ( !isset( $options['connectTimeout'] ) ) {
72 $options['connectTimeout'] = 'default';
75 $req = MWHttpRequest::factory( $url, $options, $caller );
76 $status = $req->execute();
78 if ( $status->isOK() ) {
79 return $req->getContent();
80 } else {
81 $errors = $status->getErrorsByType( 'error' );
82 $logger = LoggerFactory::getInstance( 'http' );
83 $logger->warning( $status->getWikiText(), array( 'caller' => $caller ) );
84 return false;
88 /**
89 * Simple wrapper for Http::request( 'GET' )
90 * @see Http::request()
91 * @since 1.25 Second parameter $timeout removed. Second parameter
92 * is now $options which can be given a 'timeout'
94 * @param string $url
95 * @param array $options
96 * @param string $caller The method making this request, for profiling
97 * @return string
99 public static function get( $url, $options = array(), $caller = __METHOD__ ) {
100 $args = func_get_args();
101 if ( isset( $args[1] ) && ( is_string( $args[1] ) || is_numeric( $args[1] ) ) ) {
102 // Second was used to be the timeout
103 // And third parameter used to be $options
104 wfWarn( "Second parameter should not be a timeout.", 2 );
105 $options = isset( $args[2] ) && is_array( $args[2] ) ?
106 $args[2] : array();
107 $options['timeout'] = $args[1];
108 $caller = __METHOD__;
110 return Http::request( 'GET', $url, $options, $caller );
114 * Simple wrapper for Http::request( 'POST' )
115 * @see Http::request()
117 * @param string $url
118 * @param array $options
119 * @param string $caller The method making this request, for profiling
120 * @return string
122 public static function post( $url, $options = array(), $caller = __METHOD__ ) {
123 return Http::request( 'POST', $url, $options, $caller );
127 * Check if the URL can be served by localhost
129 * @param string $url Full url to check
130 * @return bool
132 public static function isLocalURL( $url ) {
133 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
135 if ( $wgCommandLineMode ) {
136 return false;
139 // Extract host part
140 $matches = array();
141 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
142 $host = $matches[1];
143 // Split up dotwise
144 $domainParts = explode( '.', $host );
145 // Check if this domain or any superdomain is listed as a local virtual host
146 $domainParts = array_reverse( $domainParts );
148 $domain = '';
149 $countParts = count( $domainParts );
150 for ( $i = 0; $i < $countParts; $i++ ) {
151 $domainPart = $domainParts[$i];
152 if ( $i == 0 ) {
153 $domain = $domainPart;
154 } else {
155 $domain = $domainPart . '.' . $domain;
158 if ( in_array( $domain, $wgLocalVirtualHosts )
159 || $wgConf->isLocalVHost( $domain )
161 return true;
166 return false;
170 * A standard user-agent we can use for external requests.
171 * @return string
173 public static function userAgent() {
174 global $wgVersion;
175 return "MediaWiki/$wgVersion";
179 * Checks that the given URI is a valid one. Hardcoding the
180 * protocols, because we only want protocols that both cURL
181 * and php support.
183 * file:// should not be allowed here for security purpose (r67684)
185 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
187 * @param string $uri URI to check for validity
188 * @return bool
190 public static function isValidURI( $uri ) {
191 return preg_match(
192 '/^https?:\/\/[^\/\s]\S*$/D',
193 $uri
199 * This wrapper class will call out to curl (if available) or fallback
200 * to regular PHP if necessary for handling internal HTTP requests.
202 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
203 * PHP's HTTP extension.
205 class MWHttpRequest {
206 const SUPPORTS_FILE_POSTS = false;
208 protected $content;
209 protected $timeout = 'default';
210 protected $headersOnly = null;
211 protected $postData = null;
212 protected $proxy = null;
213 protected $noProxy = false;
214 protected $sslVerifyHost = true;
215 protected $sslVerifyCert = true;
216 protected $caInfo = null;
217 protected $method = "GET";
218 protected $reqHeaders = array();
219 protected $url;
220 protected $parsedUrl;
221 protected $callback;
222 protected $maxRedirects = 5;
223 protected $followRedirects = false;
226 * @var CookieJar
228 protected $cookieJar;
230 protected $headerList = array();
231 protected $respVersion = "0.9";
232 protected $respStatus = "200 Ok";
233 protected $respHeaders = array();
235 public $status;
238 * @var Profiler
240 protected $profiler;
243 * @var string
245 protected $profileName;
248 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
249 * @param array $options (optional) extra params to pass (see Http::request())
250 * @param string $caller The method making this request, for profiling
251 * @param Profiler $profiler An instance of the profiler for profiling, or null
253 protected function __construct(
254 $url, $options = array(), $caller = __METHOD__, $profiler = null
256 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
258 $this->url = wfExpandUrl( $url, PROTO_HTTP );
259 $this->parsedUrl = wfParseUrl( $this->url );
261 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
262 $this->status = Status::newFatal( 'http-invalid-url', $url );
263 } else {
264 $this->status = Status::newGood( 100 ); // continue
267 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
268 $this->timeout = $options['timeout'];
269 } else {
270 $this->timeout = $wgHTTPTimeout;
272 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
273 $this->connectTimeout = $options['connectTimeout'];
274 } else {
275 $this->connectTimeout = $wgHTTPConnectTimeout;
277 if ( isset( $options['userAgent'] ) ) {
278 $this->setUserAgent( $options['userAgent'] );
281 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
282 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
284 foreach ( $members as $o ) {
285 if ( isset( $options[$o] ) ) {
286 // ensure that MWHttpRequest::method is always
287 // uppercased. Bug 36137
288 if ( $o == 'method' ) {
289 $options[$o] = strtoupper( $options[$o] );
291 $this->$o = $options[$o];
295 if ( $this->noProxy ) {
296 $this->proxy = ''; // noProxy takes precedence
299 // Profile based on what's calling us
300 $this->profiler = $profiler;
301 $this->profileName = $caller;
305 * Simple function to test if we can make any sort of requests at all, using
306 * cURL or fopen()
307 * @return bool
309 public static function canMakeRequests() {
310 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
314 * Generate a new request object
315 * @param string $url Url to use
316 * @param array $options (optional) extra params to pass (see Http::request())
317 * @param string $caller The method making this request, for profiling
318 * @throws MWException
319 * @return CurlHttpRequest|PhpHttpRequest
320 * @see MWHttpRequest::__construct
322 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
323 if ( !Http::$httpEngine ) {
324 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
325 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
326 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
327 ' Http::$httpEngine is set to "curl"' );
330 switch ( Http::$httpEngine ) {
331 case 'curl':
332 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
333 case 'php':
334 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
335 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
336 'needs to be enabled for pure PHP http requests to ' .
337 'work. If possible, curl should be used instead. See ' .
338 'http://php.net/curl.'
341 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
342 default:
343 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
348 * Get the body, or content, of the response to the request
350 * @return string
352 public function getContent() {
353 return $this->content;
357 * Set the parameters of the request
359 * @param array $args
360 * @todo overload the args param
362 public function setData( $args ) {
363 $this->postData = $args;
367 * Take care of setting up the proxy (do nothing if "noProxy" is set)
369 * @return void
371 public function proxySetup() {
372 global $wgHTTPProxy;
374 // If there is an explicit proxy set and proxies are not disabled, then use it
375 if ( $this->proxy && !$this->noProxy ) {
376 return;
379 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
380 // local URL and proxies are not disabled
381 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
382 $this->proxy = '';
383 } elseif ( $wgHTTPProxy ) {
384 $this->proxy = $wgHTTPProxy;
385 } elseif ( getenv( "http_proxy" ) ) {
386 $this->proxy = getenv( "http_proxy" );
391 * Set the user agent
392 * @param string $UA
394 public function setUserAgent( $UA ) {
395 $this->setHeader( 'User-Agent', $UA );
399 * Set an arbitrary header
400 * @param string $name
401 * @param string $value
403 public function setHeader( $name, $value ) {
404 // I feel like I should normalize the case here...
405 $this->reqHeaders[$name] = $value;
409 * Get an array of the headers
410 * @return array
412 public function getHeaderList() {
413 $list = array();
415 if ( $this->cookieJar ) {
416 $this->reqHeaders['Cookie'] =
417 $this->cookieJar->serializeToHttpRequest(
418 $this->parsedUrl['path'],
419 $this->parsedUrl['host']
423 foreach ( $this->reqHeaders as $name => $value ) {
424 $list[] = "$name: $value";
427 return $list;
431 * Set a read callback to accept data read from the HTTP request.
432 * By default, data is appended to an internal buffer which can be
433 * retrieved through $req->getContent().
435 * To handle data as it comes in -- especially for large files that
436 * would not fit in memory -- you can instead set your own callback,
437 * in the form function($resource, $buffer) where the first parameter
438 * is the low-level resource being read (implementation specific),
439 * and the second parameter is the data buffer.
441 * You MUST return the number of bytes handled in the buffer; if fewer
442 * bytes are reported handled than were passed to you, the HTTP fetch
443 * will be aborted.
445 * @param callable $callback
446 * @throws MWException
448 public function setCallback( $callback ) {
449 if ( !is_callable( $callback ) ) {
450 throw new MWException( 'Invalid MwHttpRequest callback' );
452 $this->callback = $callback;
456 * A generic callback to read the body of the response from a remote
457 * server.
459 * @param resource $fh
460 * @param string $content
461 * @return int
463 public function read( $fh, $content ) {
464 $this->content .= $content;
465 return strlen( $content );
469 * Take care of whatever is necessary to perform the URI request.
471 * @return Status
473 public function execute() {
475 $this->content = "";
477 if ( strtoupper( $this->method ) == "HEAD" ) {
478 $this->headersOnly = true;
481 $this->proxySetup(); // set up any proxy as needed
483 if ( !$this->callback ) {
484 $this->setCallback( array( $this, 'read' ) );
487 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
488 $this->setUserAgent( Http::userAgent() );
494 * Parses the headers, including the HTTP status code and any
495 * Set-Cookie headers. This function expects the headers to be
496 * found in an array in the member variable headerList.
498 protected function parseHeader() {
500 $lastname = "";
502 foreach ( $this->headerList as $header ) {
503 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
504 $this->respVersion = $match[1];
505 $this->respStatus = $match[2];
506 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
507 $last = count( $this->respHeaders[$lastname] ) - 1;
508 $this->respHeaders[$lastname][$last] .= "\r\n$header";
509 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
510 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
511 $lastname = strtolower( $match[1] );
515 $this->parseCookies();
520 * Sets HTTPRequest status member to a fatal value with the error
521 * message if the returned integer value of the status code was
522 * not successful (< 300) or a redirect (>=300 and < 400). (see
523 * RFC2616, section 10,
524 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
525 * list of status codes.)
527 protected function setStatus() {
528 if ( !$this->respHeaders ) {
529 $this->parseHeader();
532 if ( (int)$this->respStatus > 399 ) {
533 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
534 $this->status->fatal( "http-bad-status", $code, $message );
539 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
540 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
541 * for a list of status codes.)
543 * @return int
545 public function getStatus() {
546 if ( !$this->respHeaders ) {
547 $this->parseHeader();
550 return (int)$this->respStatus;
554 * Returns true if the last status code was a redirect.
556 * @return bool
558 public function isRedirect() {
559 if ( !$this->respHeaders ) {
560 $this->parseHeader();
563 $status = (int)$this->respStatus;
565 if ( $status >= 300 && $status <= 303 ) {
566 return true;
569 return false;
573 * Returns an associative array of response headers after the
574 * request has been executed. Because some headers
575 * (e.g. Set-Cookie) can appear more than once the, each value of
576 * the associative array is an array of the values given.
578 * @return array
580 public function getResponseHeaders() {
581 if ( !$this->respHeaders ) {
582 $this->parseHeader();
585 return $this->respHeaders;
589 * Returns the value of the given response header.
591 * @param string $header
592 * @return string
594 public function getResponseHeader( $header ) {
595 if ( !$this->respHeaders ) {
596 $this->parseHeader();
599 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
600 $v = $this->respHeaders[strtolower( $header )];
601 return $v[count( $v ) - 1];
604 return null;
608 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
610 * @param CookieJar $jar
612 public function setCookieJar( $jar ) {
613 $this->cookieJar = $jar;
617 * Returns the cookie jar in use.
619 * @return CookieJar
621 public function getCookieJar() {
622 if ( !$this->respHeaders ) {
623 $this->parseHeader();
626 return $this->cookieJar;
630 * Sets a cookie. Used before a request to set up any individual
631 * cookies. Used internally after a request to parse the
632 * Set-Cookie headers.
633 * @see Cookie::set
634 * @param string $name
635 * @param mixed $value
636 * @param array $attr
638 public function setCookie( $name, $value = null, $attr = null ) {
639 if ( !$this->cookieJar ) {
640 $this->cookieJar = new CookieJar;
643 $this->cookieJar->setCookie( $name, $value, $attr );
647 * Parse the cookies in the response headers and store them in the cookie jar.
649 protected function parseCookies() {
651 if ( !$this->cookieJar ) {
652 $this->cookieJar = new CookieJar;
655 if ( isset( $this->respHeaders['set-cookie'] ) ) {
656 $url = parse_url( $this->getFinalUrl() );
657 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
658 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
665 * Returns the final URL after all redirections.
667 * Relative values of the "Location" header are incorrect as
668 * stated in RFC, however they do happen and modern browsers
669 * support them. This function loops backwards through all
670 * locations in order to build the proper absolute URI - Marooned
671 * at wikia-inc.com
673 * Note that the multiple Location: headers are an artifact of
674 * CURL -- they shouldn't actually get returned this way. Rewrite
675 * this when bug 29232 is taken care of (high-level redirect
676 * handling rewrite).
678 * @return string
680 public function getFinalUrl() {
681 $headers = $this->getResponseHeaders();
683 // return full url (fix for incorrect but handled relative location)
684 if ( isset( $headers['location'] ) ) {
685 $locations = $headers['location'];
686 $domain = '';
687 $foundRelativeURI = false;
688 $countLocations = count( $locations );
690 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
691 $url = parse_url( $locations[$i] );
693 if ( isset( $url['host'] ) ) {
694 $domain = $url['scheme'] . '://' . $url['host'];
695 break; // found correct URI (with host)
696 } else {
697 $foundRelativeURI = true;
701 if ( $foundRelativeURI ) {
702 if ( $domain ) {
703 return $domain . $locations[$countLocations - 1];
704 } else {
705 $url = parse_url( $this->url );
706 if ( isset( $url['host'] ) ) {
707 return $url['scheme'] . '://' . $url['host'] .
708 $locations[$countLocations - 1];
711 } else {
712 return $locations[$countLocations - 1];
716 return $this->url;
720 * Returns true if the backend can follow redirects. Overridden by the
721 * child classes.
722 * @return bool
724 public function canFollowRedirects() {
725 return true;
730 * MWHttpRequest implemented using internal curl compiled into PHP
732 class CurlHttpRequest extends MWHttpRequest {
733 const SUPPORTS_FILE_POSTS = true;
735 protected $curlOptions = array();
736 protected $headerText = "";
739 * @param resource $fh
740 * @param string $content
741 * @return int
743 protected function readHeader( $fh, $content ) {
744 $this->headerText .= $content;
745 return strlen( $content );
748 public function execute() {
750 parent::execute();
752 if ( !$this->status->isOK() ) {
753 return $this->status;
756 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
757 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
759 // Only supported in curl >= 7.16.2
760 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
761 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
764 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
765 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
766 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
767 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
768 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
770 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
772 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
773 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
775 if ( $this->caInfo ) {
776 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
779 if ( $this->headersOnly ) {
780 $this->curlOptions[CURLOPT_NOBODY] = true;
781 $this->curlOptions[CURLOPT_HEADER] = true;
782 } elseif ( $this->method == 'POST' ) {
783 $this->curlOptions[CURLOPT_POST] = true;
784 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
785 // Suppress 'Expect: 100-continue' header, as some servers
786 // will reject it with a 417 and Curl won't auto retry
787 // with HTTP 1.0 fallback
788 $this->reqHeaders['Expect'] = '';
789 } else {
790 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
793 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
795 $curlHandle = curl_init( $this->url );
797 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
798 throw new MWException( "Error setting curl options." );
801 if ( $this->followRedirects && $this->canFollowRedirects() ) {
802 MediaWiki\suppressWarnings();
803 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
804 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
805 "Probably safe_mode or open_basedir is set.\n" );
806 // Continue the processing. If it were in curl_setopt_array,
807 // processing would have halted on its entry
809 MediaWiki\restoreWarnings();
812 if ( $this->profiler ) {
813 $profileSection = $this->profiler->scopedProfileIn(
814 __METHOD__ . '-' . $this->profileName
818 $curlRes = curl_exec( $curlHandle );
819 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
820 $this->status->fatal( 'http-timed-out', $this->url );
821 } elseif ( $curlRes === false ) {
822 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
823 } else {
824 $this->headerList = explode( "\r\n", $this->headerText );
827 curl_close( $curlHandle );
829 if ( $this->profiler ) {
830 $this->profiler->scopedProfileOut( $profileSection );
833 $this->parseHeader();
834 $this->setStatus();
836 return $this->status;
840 * @return bool
842 public function canFollowRedirects() {
843 $curlVersionInfo = curl_version();
844 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
845 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
846 return false;
849 if ( version_compare( PHP_VERSION, '5.6.0', '<' ) ) {
850 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
851 wfDebug( "Cannot follow redirects in safe mode\n" );
852 return false;
856 return true;
860 class PhpHttpRequest extends MWHttpRequest {
862 private $fopenErrors = array();
865 * @param string $url
866 * @return string
868 protected function urlToTcp( $url ) {
869 $parsedUrl = parse_url( $url );
871 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
875 * Returns an array with a 'capath' or 'cafile' key
876 * that is suitable to be merged into the 'ssl' sub-array of
877 * a stream context options array.
878 * Uses the 'caInfo' option of the class if it is provided, otherwise uses the system
879 * default CA bundle if PHP supports that, or searches a few standard locations.
880 * @return array
881 * @throws DomainException
883 protected function getCertOptions() {
884 $certOptions = array();
885 $certLocations = array();
886 if ( $this->caInfo ) {
887 $certLocations = array( 'manual' => $this->caInfo );
888 } elseif ( version_compare( PHP_VERSION, '5.6.0', '<' ) ) {
889 // @codingStandardsIgnoreStart Generic.Files.LineLength
890 // Default locations, based on
891 // https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
892 // PHP 5.5 and older doesn't have any defaults, so we try to guess ourselves.
893 // PHP 5.6+ gets the CA location from OpenSSL as long as it is not set manually,
894 // so we should leave capath/cafile empty there.
895 // @codingStandardsIgnoreEnd
896 $certLocations = array_filter( array(
897 getenv( 'SSL_CERT_DIR' ),
898 getenv( 'SSL_CERT_PATH' ),
899 '/etc/pki/tls/certs/ca-bundle.crt', # Fedora et al
900 '/etc/ssl/certs', # Debian et al
901 '/etc/pki/tls/certs/ca-bundle.trust.crt',
902 '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem',
903 '/System/Library/OpenSSL', # OSX
904 ) );
907 foreach ( $certLocations as $key => $cert ) {
908 if ( is_dir( $cert ) ) {
909 $certOptions['capath'] = $cert;
910 break;
911 } elseif ( is_file( $cert ) ) {
912 $certOptions['cafile'] = $cert;
913 break;
914 } elseif ( $key === 'manual' ) {
915 // fail more loudly if a cert path was manually configured and it is not valid
916 throw new DomainException( "Invalid CA info passed: $cert" );
920 return $certOptions;
924 * Custom error handler for dealing with fopen() errors.
925 * fopen() tends to fire multiple errors in succession, and the last one
926 * is completely useless (something like "fopen: failed to open stream")
927 * so normal methods of handling errors programmatically
928 * like get_last_error() don't work.
930 public function errorHandler( $errno, $errstr ) {
931 $n = count( $this->fopenErrors ) + 1;
932 $this->fopenErrors += array( "errno$n" => $errno, "errstr$n" => $errstr );
935 public function execute() {
937 parent::execute();
939 if ( is_array( $this->postData ) ) {
940 $this->postData = wfArrayToCgi( $this->postData );
943 if ( $this->parsedUrl['scheme'] != 'http'
944 && $this->parsedUrl['scheme'] != 'https' ) {
945 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
948 $this->reqHeaders['Accept'] = "*/*";
949 $this->reqHeaders['Connection'] = 'Close';
950 if ( $this->method == 'POST' ) {
951 // Required for HTTP 1.0 POSTs
952 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
953 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
954 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
958 // Set up PHP stream context
959 $options = array(
960 'http' => array(
961 'method' => $this->method,
962 'header' => implode( "\r\n", $this->getHeaderList() ),
963 'protocol_version' => '1.1',
964 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
965 'ignore_errors' => true,
966 'timeout' => $this->timeout,
967 // Curl options in case curlwrappers are installed
968 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
969 'curl_verify_ssl_peer' => $this->sslVerifyCert,
971 'ssl' => array(
972 'verify_peer' => $this->sslVerifyCert,
973 'SNI_enabled' => true,
974 'ciphers' => 'HIGH:!SSLv2:!SSLv3:-ADH:-kDH:-kECDH:-DSS',
975 'disable_compression' => true,
979 if ( $this->proxy ) {
980 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
981 $options['http']['request_fulluri'] = true;
984 if ( $this->postData ) {
985 $options['http']['content'] = $this->postData;
988 if ( $this->sslVerifyHost ) {
989 // PHP 5.6.0 deprecates CN_match, in favour of peer_name which
990 // actually checks SubjectAltName properly.
991 if ( version_compare( PHP_VERSION, '5.6.0', '>=' ) ) {
992 $options['ssl']['peer_name'] = $this->parsedUrl['host'];
993 } else {
994 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
998 $options['ssl'] += $this->getCertOptions();
1000 $context = stream_context_create( $options );
1002 $this->headerList = array();
1003 $reqCount = 0;
1004 $url = $this->url;
1006 $result = array();
1008 if ( $this->profiler ) {
1009 $profileSection = $this->profiler->scopedProfileIn(
1010 __METHOD__ . '-' . $this->profileName
1013 do {
1014 $reqCount++;
1015 $this->fopenErrors = array();
1016 set_error_handler( array( $this, 'errorHandler' ) );
1017 $fh = fopen( $url, "r", false, $context );
1018 restore_error_handler();
1020 if ( !$fh ) {
1021 // HACK for instant commons.
1022 // If we are contacting (commons|upload).wikimedia.org
1023 // try again with CN_match for en.wikipedia.org
1024 // as php does not handle SubjectAltName properly
1025 // prior to "peer_name" option in php 5.6
1026 if ( isset( $options['ssl']['CN_match'] )
1027 && ( $options['ssl']['CN_match'] === 'commons.wikimedia.org'
1028 || $options['ssl']['CN_match'] === 'upload.wikimedia.org' )
1030 $options['ssl']['CN_match'] = 'en.wikipedia.org';
1031 $context = stream_context_create( $options );
1032 continue;
1034 break;
1037 $result = stream_get_meta_data( $fh );
1038 $this->headerList = $result['wrapper_data'];
1039 $this->parseHeader();
1041 if ( !$this->followRedirects ) {
1042 break;
1045 # Handle manual redirection
1046 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
1047 break;
1049 # Check security of URL
1050 $url = $this->getResponseHeader( "Location" );
1052 if ( !Http::isValidURI( $url ) ) {
1053 wfDebug( __METHOD__ . ": insecure redirection\n" );
1054 break;
1056 } while ( true );
1057 if ( $this->profiler ) {
1058 $this->profiler->scopedProfileOut( $profileSection );
1061 $this->setStatus();
1063 if ( $fh === false ) {
1064 if ( $this->fopenErrors ) {
1065 LoggerFactory::getInstance( 'http' )->warning( __CLASS__
1066 . ': error opening connection: {errstr1}', $this->fopenErrors );
1068 $this->status->fatal( 'http-request-error' );
1069 return $this->status;
1072 if ( $result['timed_out'] ) {
1073 $this->status->fatal( 'http-timed-out', $this->url );
1074 return $this->status;
1077 // If everything went OK, or we received some error code
1078 // get the response body content.
1079 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
1080 while ( !feof( $fh ) ) {
1081 $buf = fread( $fh, 8192 );
1083 if ( $buf === false ) {
1084 $this->status->fatal( 'http-read-error' );
1085 break;
1088 if ( strlen( $buf ) ) {
1089 call_user_func( $this->callback, $fh, $buf );
1093 fclose( $fh );
1095 return $this->status;