Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
47.86% covered (danger)
47.86%
56 / 117
57.14% covered (warning)
57.14%
4 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
EntryPoint
47.86% covered (danger)
47.86%
56 / 117
57.14% covered (warning)
57.14%
4 / 7
63.92
0.00% covered (danger)
0.00%
0 / 1
 createRouter
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
2
 getMainRequest
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 doSetup
60.00% covered (warning)
60.00%
12 / 20
0.00% covered (danger)
0.00%
0 / 1
2.26
 getTextFormatters
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
5
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setRouter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2
3namespace MediaWiki\Rest;
4
5use MediaWiki\Config\ServiceOptions;
6use MediaWiki\Context\IContextSource;
7use MediaWiki\Context\RequestContext;
8use MediaWiki\EntryPointEnvironment;
9use MediaWiki\Exception\MWExceptionRenderer;
10use MediaWiki\MainConfigNames;
11use MediaWiki\MediaWikiEntryPoint;
12use MediaWiki\MediaWikiServices;
13use MediaWiki\Registration\ExtensionRegistry;
14use MediaWiki\Rest\BasicAccess\CompoundAuthorizer;
15use MediaWiki\Rest\BasicAccess\MWBasicAuthorizer;
16use MediaWiki\Rest\Module\ModuleManager;
17use MediaWiki\Rest\Reporter\MWErrorReporter;
18use MediaWiki\Rest\Validator\Validator;
19use Wikimedia\Assert\Assert;
20use Wikimedia\Message\ITextFormatter;
21
22/**
23 * @internal
24 */
25class EntryPoint extends MediaWikiEntryPoint {
26
27    private ?Router $router = null;
28    private ?CorsUtils $cors  = null;
29
30    /**
31     * @internal Public for use in core tests
32     *
33     * @param MediaWikiServices $services
34     * @param IContextSource $context
35     * @param RequestInterface $request
36     * @param ITextFormatter[] $textFormatters
37     * @param bool $showExceptionDetails
38     * @param CorsUtils $cors
39     *
40     * @return Router
41     */
42    public static function createRouter(
43        MediaWikiServices $services,
44        IContextSource $context,
45        RequestInterface $request,
46        array $textFormatters,
47        bool $showExceptionDetails,
48        CorsUtils $cors
49    ): Router {
50        Assert::parameter(
51            count( $textFormatters ) > 0,
52            '$textFormatters', 'must not be empty'
53        );
54
55        $conf = $services->getMainConfig();
56
57        $authority = $context->getAuthority();
58        $authorizer = new CompoundAuthorizer();
59        $authorizer
60            ->addAuthorizer( new MWBasicAuthorizer( $authority ) )
61            ->addAuthorizer( $cors );
62
63        $objectFactory = $services->getObjectFactory();
64        $restValidator = new Validator( $objectFactory,
65            $request,
66            $authority
67        );
68
69        $stats = $services->getStatsFactory();
70
71        // NOTE: Use preferred language, see getTextFormatters().
72        $defaultTextFormatter = array_first( $textFormatters );
73        $articleUrl = $services->getUrlUtils()->expand( $conf->get( MainConfigNames::ArticlePath ) );
74        Assert::postcondition( $articleUrl !== null, 'ArticlePath setting must produce a valid URL' );
75
76        $markdownTextFormatter = new MarkdownFormatter( $defaultTextFormatter, $articleUrl );
77        $jsonLocalizer = new JsonLocalizer( $markdownTextFormatter );
78        $moduleManager = new ModuleManager(
79            new ServiceOptions( ModuleManager::CONSTRUCTOR_OPTIONS, $conf ),
80            ExtensionRegistry::getInstance()->getAttribute( 'RestModuleFiles' ),
81            $services->getLocalServerObjectCache(),
82            $jsonLocalizer
83        );
84
85        return ( new Router(
86            $moduleManager,
87            ExtensionRegistry::getInstance()->getAttribute( 'RestRoutes' ),
88            new ServiceOptions( Router::CONSTRUCTOR_OPTIONS, $conf ),
89            $services->getLocalServerObjectCache(),
90            $textFormatters,
91            $showExceptionDetails,
92            $authorizer,
93            $authority,
94            $objectFactory,
95            $restValidator,
96            new MWErrorReporter(),
97            $services->getHookContainer(),
98            $context->getRequest()->getSession(),
99            $services->getUrlUtils(),
100            $jsonLocalizer,
101        ) )
102            ->setCors( $cors )
103            ->setStats( $stats );
104    }
105
106    /**
107     * @internal
108     * @return RequestInterface The RequestInterface object used by this entry point.
109     */
110    public static function getMainRequest(): RequestInterface {
111        static $mainRequest = null;
112
113        if ( $mainRequest === null ) {
114            $conf = MediaWikiServices::getInstance()->getMainConfig();
115            $mainRequest = new RequestFromGlobals( [
116                'cookiePrefix' => $conf->get( MainConfigNames::CookiePrefix )
117            ] );
118        }
119
120        return $mainRequest;
121    }
122
123    protected function doSetup() {
124        parent::doSetup();
125
126        $context = $this->getContext();
127        $textFormatters = $this->getTextFormatters();
128        $showExceptionDetails = MWExceptionRenderer::shouldShowExceptionDetails();
129
130        $this->cors = new CorsUtils(
131            new ServiceOptions(
132                CorsUtils::CONSTRUCTOR_OPTIONS,
133                $this->getServiceContainer()->getMainConfig()
134            ),
135            $context->getUser()
136        );
137
138        if ( !$this->router ) {
139            $this->router = $this->createRouter(
140                $this->getServiceContainer(),
141                $context,
142                $this->request,
143                $textFormatters,
144                $showExceptionDetails,
145                $this->cors
146            );
147        }
148    }
149
150    /**
151     * Get a TextFormatter array from MediaWikiServices
152     *
153     * @return ITextFormatter[]
154     */
155    private function getTextFormatters() {
156        $services = $this->getServiceContainer();
157
158        $code = $services->getContentLanguageCode()->toString();
159        $langs = [];
160
161        $queryParams = $this->request->getQueryParams();
162        $requestedLang = $queryParams['lang'] ?? null;
163        if ( is_string( $requestedLang ) && $requestedLang !== '' ) {
164            $internalCode = \MediaWiki\Language\LanguageCode::bcp47ToInternal( $requestedLang );
165            if ( $services->getLanguageNameUtils()->isSupportedLanguage( $internalCode ) ) {
166                $langs = [ $internalCode ];
167            }
168        }
169
170        $langs = array_unique( array_merge( $langs, [ $code, 'en' ] ) );
171        $textFormatters = [];
172        $factory = $services->getMessageFormatterFactory();
173
174        foreach ( $langs as $lang ) {
175            // XXX: we could key on language here
176            $textFormatters[] = $factory->getTextFormatter( $lang, false );
177        }
178
179        return $textFormatters;
180    }
181
182    public function __construct(
183        private readonly RequestInterface $request,
184        RequestContext $context,
185        EntryPointEnvironment $environment,
186        MediaWikiServices $mediaWikiServices,
187    ) {
188        parent::__construct( $context, $environment, $mediaWikiServices );
189    }
190
191    /**
192     * Sets the router to use.
193     * Intended for testing.
194     */
195    public function setRouter( Router $router ): void {
196        $this->router = $router;
197    }
198
199    public function execute() {
200        $this->startOutputBuffer();
201
202        $response = $this->router->execute( $this->request );
203
204        $webResponse = $this->getResponse();
205
206        $webResponse->header(
207            'HTTP/' . $response->getProtocolVersion() . ' ' . $response->getStatusCode() . ' ' .
208            $response->getReasonPhrase()
209        );
210
211        foreach ( $response->getRawHeaderLines() as $line ) {
212            $webResponse->header( $line );
213        }
214
215        foreach ( $response->getCookies() as $cookie ) {
216            $webResponse->setCookie(
217                $cookie['name'],
218                $cookie['value'],
219                $cookie['expire'],
220                $cookie['options']
221            );
222        }
223
224        // Clear all errors that might have been displayed if display_errors=On
225        $this->discardOutputBuffer();
226
227        $stream = $response->getBody();
228        $stream->rewind();
229
230        $this->prepareForOutput();
231
232        if ( $stream instanceof CopyableStreamInterface ) {
233            $stream->copyToStream( fopen( 'php://output', 'w' ) );
234        } else {
235            while ( true ) {
236                $buffer = $stream->read( 65536 );
237                if ( $buffer === '' ) {
238                    break;
239                }
240                $this->print( $buffer );
241            }
242        }
243    }
244
245}