wiki.techinc.nl/includes/Rest/EntryPoint.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

256 lines
6 KiB
PHP
Raw Normal View History

<?php
namespace MediaWiki\Rest;
use MediaWiki\Config\Config;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\Context\IContextSource;
use MediaWiki\Context\RequestContext;
use MediaWiki\EntryPointEnvironment;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiEntryPoint;
use MediaWiki\MediaWikiServices;
use MediaWiki\Registration\ExtensionRegistry;
use MediaWiki\Rest\BasicAccess\CompoundAuthorizer;
use MediaWiki\Rest\BasicAccess\MWBasicAuthorizer;
use MediaWiki\Rest\Reporter\MWErrorReporter;
use MediaWiki\Rest\Validator\Validator;
use MWExceptionRenderer;
use Wikimedia\Message\ITextFormatter;
/**
* @internal
*/
class EntryPoint extends MediaWikiEntryPoint {
private RequestInterface $request;
private ?Router $router = null;
private ?CorsUtils $cors = null;
/**
* @internal Public for use in core tests
*
* @param MediaWikiServices $services
* @param IContextSource $context
* @param RequestInterface $request
* @param ResponseFactory $responseFactory
* @param CorsUtils $cors
*
* @return Router
*/
public static function createRouter(
MediaWikiServices $services,
IContextSource $context,
RequestInterface $request,
ResponseFactory $responseFactory,
CorsUtils $cors
): Router {
$conf = $services->getMainConfig();
$authority = $context->getAuthority();
$authorizer = new CompoundAuthorizer();
$authorizer
->addAuthorizer( new MWBasicAuthorizer( $authority ) )
->addAuthorizer( $cors );
$objectFactory = $services->getObjectFactory();
$restValidator = new Validator( $objectFactory,
$request,
$authority
);
$stats = $services->getStatsFactory();
return ( new Router(
self::getRouteFiles( $conf ),
ExtensionRegistry::getInstance()->getAttribute( 'RestRoutes' ),
new ServiceOptions( Router::CONSTRUCTOR_OPTIONS, $conf ),
$services->getLocalServerObjectCache(),
$responseFactory,
$authorizer,
$authority,
$objectFactory,
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$restValidator,
new MWErrorReporter(),
$services->getHookContainer(),
$context->getRequest()->getSession()
) )
->setCors( $cors )
->setStats( $stats );
}
/**
* @internal
* @return RequestInterface The RequestInterface object used by this entry point.
*/
public static function getMainRequest(): RequestInterface {
static $mainRequest = null;
if ( $mainRequest === null ) {
$conf = MediaWikiServices::getInstance()->getMainConfig();
$mainRequest = new RequestFromGlobals( [
'cookiePrefix' => $conf->get( MainConfigNames::CookiePrefix )
] );
}
return $mainRequest;
}
protected function doSetup() {
parent::doSetup();
$context = RequestContext::getMain();
$responseFactory = new ResponseFactory( $this->getTextFormatters() );
$responseFactory->setShowExceptionDetails(
MWExceptionRenderer::shouldShowExceptionDetails()
);
$this->cors = new CorsUtils(
new ServiceOptions(
CorsUtils::CONSTRUCTOR_OPTIONS,
$this->getServiceContainer()->getMainConfig()
),
$responseFactory,
$context->getUser()
);
if ( !$this->router ) {
$this->router = $this->createRouter(
$this->getServiceContainer(),
$context,
$this->request,
$responseFactory,
$this->cors
);
}
}
/**
* Get a TextFormatter array from MediaWikiServices
*
* @return ITextFormatter[]
*/
private function getTextFormatters() {
$services = $this->getServiceContainer();
$code = $services->getContentLanguage()->getCode();
$langs = array_unique( [ $code, 'en' ] );
$textFormatters = [];
$factory = $services->getMessageFormatterFactory();
foreach ( $langs as $lang ) {
$textFormatters[] = $factory->getTextFormatter( $lang );
}
return $textFormatters;
}
/**
* @param Config $conf
*
* @return string[]
*/
private static function getRouteFiles( $conf ) {
global $IP;
$extensionsDir = $conf->get( MainConfigNames::ExtensionDirectory );
// Always include the "official" routes. Include additional routes if specified.
$routeFiles = array_merge(
[
'includes/Rest/coreRoutes.json',
],
$conf->get( MainConfigNames::RestAPIAdditionalRouteFiles )
);
foreach ( $routeFiles as &$file ) {
if (
str_starts_with( $file, '/' )
) {
// Allow absolute paths on non-Windows
} elseif (
str_starts_with( $file, 'extensions/' )
) {
// Support hacks like Wikibase.ci.php
$file = substr_replace( $file, $extensionsDir,
0, strlen( 'extensions' ) );
} else {
$file = "$IP/$file";
}
}
return $routeFiles;
}
public function __construct(
RequestInterface $request,
RequestContext $context,
EntryPointEnvironment $environment,
MediaWikiServices $mediaWikiServices
) {
parent::__construct( $context, $environment, $mediaWikiServices );
$this->request = $request;
}
/**
* Sets the router to use.
* Intended for testing.
*
* @param Router $router
*/
public function setRouter( Router $router ): void {
$this->router = $router;
}
public function execute() {
$this->startOutputBuffer();
// IDEA: Move the call to cors->modifyResponse() into Module,
// so it's in the same class as cors->createPreflightResponse().
$response = $this->cors->modifyResponse(
$this->request,
$this->router->execute( $this->request )
);
$webResponse = $this->getResponse();
$webResponse->header(
'HTTP/' . $response->getProtocolVersion() . ' ' . $response->getStatusCode() . ' ' .
$response->getReasonPhrase()
);
foreach ( $response->getRawHeaderLines() as $line ) {
$webResponse->header( $line );
}
foreach ( $response->getCookies() as $cookie ) {
$webResponse->setCookie(
$cookie['name'],
$cookie['value'],
$cookie['expiry'],
$cookie['options']
);
}
// Clear all errors that might have been displayed if display_errors=On
$this->discardOutputBuffer();
$stream = $response->getBody();
$stream->rewind();
$this->prepareForOutput();
if ( $stream instanceof CopyableStreamInterface ) {
$stream->copyToStream( fopen( 'php://output', 'w' ) );
} else {
while ( true ) {
$buffer = $stream->read( 65536 );
if ( $buffer === '' ) {
break;
}
$this->print( $buffer );
}
}
}
}