Go to the documentation of this file.
22 use Psr\Log\LoggerInterface;
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\NullLogger;
92 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
100 $this->logger =
new NullLogger();
110 $this->timeout =
$options[
'timeout'];
112 $this->timeout = $wgHTTPTimeout;
114 if ( isset(
$options[
'connectTimeout'] ) &&
$options[
'connectTimeout'] !=
'default' ) {
115 $this->connectTimeout =
$options[
'connectTimeout'];
117 $this->connectTimeout = $wgHTTPConnectTimeout;
119 if ( isset(
$options[
'userAgent'] ) ) {
125 'Basic ' . base64_encode(
$options[
'username'] .
':' .
$options[
'password'] )
128 if ( isset(
$options[
'originalRequest'] ) ) {
132 $members = [
"postData",
"proxy",
"noProxy",
"sslVerifyHost",
"caInfo",
133 "method",
"followRedirects",
"maxRedirects",
"sslVerifyCert",
"callback" ];
135 foreach ( $members
as $o ) {
139 if ( $o ==
'method' ) {
146 if ( $this->noProxy ) {
152 $this->profileName = $caller;
168 return function_exists(
'curl_init' ) ||
wfIniGetBool(
'allow_url_fopen' );
184 throw new DomainException( __METHOD__ .
': curl (http://php.net/curl) is not installed, but' .
185 ' Http::$httpEngine is set to "curl"' );
192 if ( !isset(
$options[
'logger'] ) ) {
193 $options[
'logger'] = LoggerFactory::getInstance(
'http' );
201 throw new DomainException( __METHOD__ .
': allow_url_fopen ' .
202 'needs to be enabled for pure PHP http requests to ' .
203 'work. If possible, curl should be used instead. See ' .
204 'http://php.net/curl.'
209 throw new DomainException( __METHOD__ .
': The setting of Http::$httpEngine is not valid.' );
229 $this->postData =
$args;
239 if ( $this->proxy && !$this->noProxy ) {
245 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
267 if ( preg_match(
'!^https?://([\w.-]+)[/:].*$!',
$url,
$matches ) ) {
270 $domainParts = explode(
'.', $host );
272 $domainParts = array_reverse( $domainParts );
275 $countParts =
count( $domainParts );
276 for ( $i = 0; $i < $countParts; $i++ ) {
277 $domainPart = $domainParts[$i];
279 $domain = $domainPart;
281 $domain = $domainPart .
'.' . $domain;
284 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
318 if ( $this->cookieJar ) {
319 $this->reqHeaders[
'Cookie'] =
320 $this->cookieJar->serializeToHttpRequest(
321 $this->parsedUrl[
'path'],
322 $this->parsedUrl[
'host']
327 $list[] =
"$name: $value";
355 throw new InvalidArgumentException( __METHOD__ .
': invalid callback' );
381 throw new LogicException(
'children must override this' );
387 if ( strtoupper( $this->method ) ==
"HEAD" ) {
388 $this->headersOnly =
true;
393 if ( !$this->callback ) {
397 if ( !isset( $this->reqHeaders[
'User-Agent'] ) ) {
410 foreach ( $this->headerList
as $header ) {
411 if ( preg_match(
"#^HTTP/([0-9.]+) (.*)#",
$header, $match ) ) {
412 $this->respVersion = $match[1];
413 $this->respStatus = $match[2];
414 } elseif ( preg_match(
"#^[ \t]#",
$header ) ) {
415 $last =
count( $this->respHeaders[$lastname] ) - 1;
416 $this->respHeaders[$lastname][
$last] .=
"\r\n$header";
417 } elseif ( preg_match(
"#^([^:]*):[\t ]*(.*)#",
$header, $match ) ) {
418 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
419 $lastname = strtolower( $match[1] );
435 if ( !$this->respHeaders ) {
439 if ( (
int)$this->respStatus > 399 ) {
440 list(
$code, $message ) = explode(
" ", $this->respStatus, 2 );
441 $this->status->fatal(
"http-bad-status",
$code, $message );
453 if ( !$this->respHeaders ) {
466 if ( !$this->respHeaders ) {
470 $status = (int)$this->respStatus;
488 if ( !$this->respHeaders ) {
502 if ( !$this->respHeaders ) {
506 if ( isset( $this->respHeaders[strtolower(
$header )] ) ) {
507 $v = $this->respHeaders[strtolower(
$header )];
508 return $v[
count( $v ) - 1];
522 $this->cookieJar = $jar;
531 if ( !$this->respHeaders ) {
548 if ( !$this->cookieJar ) {
552 if ( $this->parsedUrl && !isset( $attr[
'domain'] ) ) {
553 $attr[
'domain'] = $this->parsedUrl[
'host'];
563 if ( !$this->cookieJar ) {
567 if ( isset( $this->respHeaders[
'set-cookie'] ) ) {
569 foreach ( $this->respHeaders[
'set-cookie']
as $cookie ) {
570 $this->cookieJar->parseCookieResponseHeader( $cookie,
$url[
'host'] );
595 if ( isset( $headers[
'location'] ) ) {
596 $locations = $headers[
'location'];
598 $foundRelativeURI =
false;
599 $countLocations =
count( $locations );
601 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
602 $url = parse_url( $locations[$i] );
604 if ( isset(
$url[
'host'] ) ) {
605 $domain =
$url[
'scheme'] .
'://' .
$url[
'host'];
608 $foundRelativeURI =
true;
612 if ( !$foundRelativeURI ) {
613 return $locations[$countLocations - 1];
616 return $domain . $locations[$countLocations - 1];
618 $url = parse_url( $this->url );
619 if ( isset(
$url[
'host'] ) ) {
620 return $url[
'scheme'] .
'://' .
$url[
'host'] .
621 $locations[$countLocations - 1];
650 if ( $originalRequest instanceof
WebRequest ) {
652 'ip' => $originalRequest->getIP(),
653 'userAgent' => $originalRequest->getHeader(
'User-Agent' ),
656 !is_array( $originalRequest )
657 || array_diff( [
'ip',
'userAgent' ], array_keys( $originalRequest ) )
659 throw new InvalidArgumentException( __METHOD__ .
': $originalRequest must be a '
660 .
"WebRequest or an array with 'ip' and 'userAgent' keys" );
663 $this->reqHeaders[
'X-Forwarded-For'] = $originalRequest[
'ip'];
664 $this->reqHeaders[
'X-Original-User-Agent'] = $originalRequest[
'userAgent'];
static factory( $url, $options=null, $caller=__METHOD__)
Generate a new request object.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
per default it will return the text for text based content
setStatus()
Sets HTTPRequest status member to a fatal value with the error message if the returned integer value ...
static instance()
Singleton.
setCookie( $name, $value, $attr=[])
Sets a cookie.
proxySetup()
Take care of setting up the proxy (do nothing if "noProxy" is set)
static userAgent()
A standard user-agent we can use for external requests.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
static newFatal( $message)
Factory function for fatal errors.
setData( $args)
Set the parameters of the request.
MWHttpRequest implemented using internal curl compiled into PHP.
Allows to change the fields on the form that will be generated $name
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
getStatus()
Get the integer value of the HTTP status code (e.g.
parseHeader()
Parses the headers, including the HTTP status code and any Set-Cookie headers.
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
getContent()
Get the body, or content, of the response to the request.
const SUPPORTS_FILE_POSTS
parseCookies()
Parse the cookies in the response headers and store them in the cookie jar.
setCookie( $name, $value, $attr)
Set a cookie in the cookie jar.
global $wgCommandLineMode
isRedirect()
Returns true if the last status code was a redirect.
static getProxy()
Gets the relevant proxy from $wgHTTPProxy.
Profiler base class that defines the interface and some trivial functionality.
getCookieJar()
Returns the cookie jar in use.
static isLocalURL( $url)
Check if the URL can be served by localhost.
setCookieJar( $jar)
Tells the MWHttpRequest object to use this pre-loaded CookieJar.
when a variable name is used in a it is silently declared as a new masking the global
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
read( $fh, $content)
A generic callback to read the body of the response from a remote server.
__construct( $url, $options=[], $caller=__METHOD__, $profiler=null)
static newGood( $value=null)
Factory function for good results.
This wrapper class will call out to curl (if available) or fallback to regular PHP if necessary for h...
setCallback( $callback)
Set a read callback to accept data read from the HTTP request.
setHeader( $name, $value)
Set an arbitrary header.
getHeaderList()
Get an array of the headers.
getResponseHeaders()
Returns an associative array of response headers after the request has been executed.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Cookie jar to use with MWHttpRequest.
static canMakeRequests()
Simple function to test if we can make any sort of requests at all, using cURL or fopen()
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
getResponseHeader( $header)
Returns the value of the given response header.
setUserAgent( $UA)
Set the user agent.
execute()
Take care of whatever is necessary to perform the URI request.
static isValidURI( $uri)
Checks that the given URI is a valid one.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
canFollowRedirects()
Returns true if the backend can follow redirects.
setLogger(LoggerInterface $logger)
getFinalUrl()
Returns the final URL after all redirections.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
setOriginalRequest( $originalRequest)
Set information about the original request.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.