MediaWiki  master
EntryPoint.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Rest;
4 
7 use MediaWiki;
16 use RequestContext;
17 use Title;
18 use WebResponse;
20 
21 class EntryPoint {
23  private $request;
25  private $webResponse;
27  private $router;
29  private $context;
31  private $cors;
33  private static $mainRequest;
34 
42  private static function createRouter(
43  IContextSource $context, RequestInterface $request, ResponseFactory $responseFactory, CorsUtils $cors
44  ): Router {
45  $services = MediaWikiServices::getInstance();
46  $conf = $services->getMainConfig();
47 
48  $authority = $context->getAuthority();
49  $authorizer = new CompoundAuthorizer();
50  $authorizer
51  ->addAuthorizer( new MWBasicAuthorizer( $authority ) )
52  ->addAuthorizer( $cors );
53 
54  $objectFactory = $services->getObjectFactory();
55  $restValidator = new Validator( $objectFactory,
56  $request,
57  $authority
58  );
59 
60  // Always include the "official" routes. Include additional routes if specified.
61  $routeFiles = array_merge(
62  [ 'includes/Rest/coreRoutes.json' ],
64  );
65  array_walk( $routeFiles, static function ( &$val, $key ) {
66  global $IP;
67  $val = "$IP/$val";
68  } );
69 
70  return ( new Router(
71  $routeFiles,
72  ExtensionRegistry::getInstance()->getAttribute( 'RestRoutes' ),
73  new ServiceOptions( Router::CONSTRUCTOR_OPTIONS, $conf ),
74  $services->getLocalServerObjectCache(),
75  $responseFactory,
76  $authorizer,
77  $authority,
78  $objectFactory,
79  $restValidator,
80  new MWErrorReporter(),
81  $services->getHookContainer(),
82  $context->getRequest()->getSession()
83  ) )->setCors( $cors );
84  }
85 
89  public static function getMainRequest(): RequestInterface {
90  if ( self::$mainRequest === null ) {
91  $conf = MediaWikiServices::getInstance()->getMainConfig();
92  self::$mainRequest = new RequestFromGlobals( [
93  'cookiePrefix' => $conf->get( MainConfigNames::CookiePrefix )
94  ] );
95  }
96  return self::$mainRequest;
97  }
98 
99  public static function main() {
100  // URL safety checks
101  global $wgRequest;
102 
103  $context = RequestContext::getMain();
104 
105  // Set $wgTitle and the title in RequestContext, as in api.php
106  global $wgTitle;
107  $wgTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/rest.php' );
108  $context->setTitle( $wgTitle );
109 
110  $services = MediaWikiServices::getInstance();
111  $conf = $services->getMainConfig();
112 
113  $responseFactory = new ResponseFactory( self::getTextFormatters( $services ) );
114  $responseFactory->setShowExceptionDetails( MWExceptionRenderer::shouldShowExceptionDetails() );
115 
116  $cors = new CorsUtils(
117  new ServiceOptions(
118  CorsUtils::CONSTRUCTOR_OPTIONS, $conf
119  ),
120  $responseFactory,
121  $context->getUser()
122  );
123 
124  $request = self::getMainRequest();
125 
126  $router = self::createRouter( $context, $request, $responseFactory, $cors );
127 
128  $entryPoint = new self(
129  $context,
130  $request,
131  $wgRequest->response(),
132  $router,
133  $cors
134  );
135  $entryPoint->execute();
136  }
137 
144  private static function getTextFormatters( MediaWikiServices $services ) {
145  $code = $services->getContentLanguage()->getCode();
146  $langs = array_unique( [ $code, 'en' ] );
147  $textFormatters = [];
148  $factory = $services->getMessageFormatterFactory();
149 
150  foreach ( $langs as $lang ) {
151  $textFormatters[] = $factory->getTextFormatter( $lang );
152  }
153  return $textFormatters;
154  }
155 
156  public function __construct( RequestContext $context, RequestInterface $request,
157  WebResponse $webResponse, Router $router, CorsUtils $cors
158  ) {
159  $this->context = $context;
160  $this->request = $request;
161  $this->webResponse = $webResponse;
162  $this->router = $router;
163  $this->cors = $cors;
164  }
165 
166  public function execute() {
167  ob_start();
168  $response = $this->cors->modifyResponse(
169  $this->request,
170  $this->router->execute( $this->request )
171  );
172 
173  $this->webResponse->header(
174  'HTTP/' . $response->getProtocolVersion() . ' ' .
175  $response->getStatusCode() . ' ' .
176  $response->getReasonPhrase() );
177 
178  foreach ( $response->getRawHeaderLines() as $line ) {
179  $this->webResponse->header( $line );
180  }
181 
182  foreach ( $response->getCookies() as $cookie ) {
183  $this->webResponse->setCookie(
184  $cookie['name'],
185  $cookie['value'],
186  $cookie['expiry'],
187  $cookie['options'] );
188  }
189 
190  // Clear all errors that might have been displayed if display_errors=On
191  ob_end_clean();
192 
193  $stream = $response->getBody();
194  $stream->rewind();
195 
196  MediaWiki::preOutputCommit( $this->context );
197 
198  if ( $stream instanceof CopyableStreamInterface ) {
199  $stream->copyToStream( fopen( 'php://output', 'w' ) );
200  } else {
201  while ( true ) {
202  $buffer = $stream->read( 65536 );
203  if ( $buffer === '' ) {
204  break;
205  }
206  echo $buffer;
207  }
208  }
209 
210  $mw = new MediaWiki;
211  $mw->doPostOutputShutdown();
212  }
213 }
const NS_SPECIAL
Definition: Defines.php:53
if(!defined( 'MEDIAWIKI')) if(ini_get( 'mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition: Setup.php:91
global $wgRequest
Definition: Setup.php:377
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgTitle
Definition: Setup.php:497
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
Definition: WebStart.php:82
The Registry loads JSON files, and uses a Processor to extract information from them.
Class to expose exceptions to the client (API bots, users, admins using CLI scripts)
A class for passing options to services.
A class containing constants representing the names of configuration variables.
const CookiePrefix
Name constant for the CookiePrefix setting, for use with Config::get()
const RestAPIAdditionalRouteFiles
Name constant for the RestAPIAdditionalRouteFiles setting, for use with Config::get()
Service locator for MediaWiki core services.
getMainConfig()
Returns the Config object that provides configuration for MediaWiki core.
getLocalServerObjectCache()
Returns the main server-local cache, yielding EmptyBagOStuff if there is none.
getObjectFactory()
ObjectFactory is intended for instantiating "handlers" from declarative definitions,...
static getInstance()
Returns the global default instance of the top level service locator.
A factory for MWBasicRequestAuthorizer which passes through a UserIdentity.
__construct(RequestContext $context, RequestInterface $request, WebResponse $webResponse, Router $router, CorsUtils $cors)
Definition: EntryPoint.php:156
Error reporter based on MWExceptionHandler.
This is a request class that gets data directly from the superglobals and other global PHP state,...
Generates standardized response objects.
The REST router is responsible for gathering handler configuration, matching an input path and HTTP m...
Definition: Router.php:25
Wrapper for ParamValidator.
Definition: Validator.php:32
The MediaWiki class is the helper class for the index.php entry point.
Definition: MediaWiki.php:38
doPostOutputShutdown()
This function does work that can be done after the user gets the HTTP response so they don't block on...
Definition: MediaWiki.php:811
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB and session changes as needed before the client can receive a response (...
Definition: MediaWiki.php:655
Group all the pieces relevant to the context of a request into one instance.
static getMain()
Get the RequestContext object associated with the main request.
Represents a title within MediaWiki.
Definition: Title.php:49
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:638
Allow programs to request this object from WebRequest::response() and handle all outputting (or lack ...
Definition: WebResponse.php:32
Interface for objects which can provide a MediaWiki context on request.
An interface for a stream with a copyToStream() function.
A request interface similar to PSR-7's ServerRequestInterface.
$line
Definition: mcc.php:119
if(!isset( $args[0])) $lang