aboutsummaryrefslogtreecommitdiffstats
path: root/includes/Rest/EntryPoint.php
blob: ec8dfa37c75119f3687e54773827ab25c9732af1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php

namespace MediaWiki\Rest;

use ExtensionRegistry;
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\Rest\BasicAccess\CompoundAuthorizer;
use MediaWiki\Rest\BasicAccess\MWBasicAuthorizer;
use MediaWiki\Rest\Reporter\MWErrorReporter;
use MediaWiki\Rest\Validator\Validator;
use MediaWiki\Title\Title;
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->getStatsdDataFactory();

		return ( new Router(
			self::getRouteFiles( $conf ),
			ExtensionRegistry::getInstance()->getAttribute( 'RestRoutes' ),
			new ServiceOptions( Router::CONSTRUCTOR_OPTIONS, $conf ),
			$services->getLocalServerObjectCache(),
			$responseFactory,
			$authorizer,
			$authority,
			$objectFactory,
			$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();

		// Set $wgTitle and the title in RequestContext, as in api.php
		global $wgTitle;
		$wgTitle = Title::makeTitle(
			NS_SPECIAL,
			'Badtitle/rest.php'
		);
		$context->setTitle( $wgTitle );

		$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();

		$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 );
			}
		}
	}

}