Debian Codegraph @

includes/actions/ActionEntryPoint.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Actions;
4
5 use Action;
6 use Article;
7 use BadTitleError;
8 use ErrorPageError;
9 use HTMLFileCache;
10 use HttpError;
11 use MediaWiki\Context\RequestContext;
12 use MediaWiki\Logger\LoggerFactory;
13 use MediaWiki\MainConfigNames;
14 use MediaWiki\MediaWikiEntryPoint;
15 use MediaWiki\Output\OutputPage;
16 use MediaWiki\Permissions\PermissionStatus;
17 use MediaWiki\Profiler\ProfilingContext;
18 use MediaWiki\Request\DerivativeRequest;
19 use MediaWiki\Request\FauxRequest;
20 use MediaWiki\Request\WebRequest;
21 use MediaWiki\SpecialPage\RedirectSpecialPage;
22 use MediaWiki\SpecialPage\SpecialPage;
23 use MediaWiki\Title\MalformedTitleException;
24 use MediaWiki\Title\Title;
25 use MediaWiki\User\User;
26 use MWExceptionRenderer;
27 use PermissionsError;
28 use Profiler;
29 use Throwable;
30 use UnexpectedValueException;
31 use ViewAction;
32 use WikiFilePage;
33 use Wikimedia\Rdbms\DBConnectionError;
34
35 /**
36 * The index.php entry point for web browser navigations, usually routed to
37 * an Action or SpecialPage subclass.
38 *
39 * @internal For use in index.php
40 * @ingroup entrypoint
41 */
42 class ActionEntryPoint extends MediaWikiEntryPoint {
43
44 /**
45 * Overwritten to narrow the return type to RequestContext
46 * @return RequestContext
47 */
48 protected function getContext(): RequestContext {
49 /** @var RequestContext $context */
50 $context = parent::getContext();
51
52 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType see $context in the constructor
53 return $context;
54 }
55
56 protected function getOutput(): OutputPage {
57 return $this->getContext()->getOutput();
58 }
59
60 protected function getUser(): User {
61 return $this->getContext()->getUser();
62 }
63
64 protected function handleTopLevelError( Throwable $e ) {
65 $context = $this->getContext();
66 $action = $context->getRequest()->getRawVal( 'action' ) ?? 'view';
67 if (
68 $e instanceof DBConnectionError &&
69 $context->hasTitle() &&
70 $context->getTitle()->canExist() &&
71 in_array( $action, [ 'view', 'history' ], true ) &&
72 HTMLFileCache::useFileCache( $context, HTMLFileCache::MODE_OUTAGE )
73 ) {
74 // Try to use any (even stale) file during outages...
75 $cache = new HTMLFileCache( $context->getTitle(), $action );
76 if ( $cache->isCached() ) {
77 $cache->loadFromFileCache( $context, HTMLFileCache::MODE_OUTAGE );
78 $this->print( MWExceptionRenderer::getHTML( $e ) );
79 $this->exit();
80 }
81 }
82
83 parent::handleTopLevelError( $e );
84 }
85
86 /**
87 * Determine and send the response headers and body for this web request
88 */
89 protected function execute() {
90 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
91 global $wgTitle;
92
93 // Get title from request parameters,
94 // is set on the fly by parseTitle the first time.
95 $title = $this->getTitle();
96 $wgTitle = $title;
97
98 $request = $this->getContext()->getRequest();
99 // Set DB query expectations for this HTTP request
100 $trxLimits = $this->getConfig( MainConfigNames::TrxProfilerLimits );
101 $trxProfiler = Profiler::instance()->getTransactionProfiler();
102 $trxProfiler->setLogger( LoggerFactory::getInstance( 'rdbms' ) );
103 $trxProfiler->setStatsFactory( $this->getStatsFactory() );
104 $trxProfiler->setRequestMethod( $request->getMethod() );
105 if ( $request->hasSafeMethod() ) {
106 $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
107 } else {
108 $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
109 }
110
111 if ( $this->maybeDoHttpsRedirect() ) {
112 return;
113 }
114
115 $context = $this->getContext();
116 $output = $context->getOutput();
117
118 // NOTE: HTMLFileCache::useFileCache() is not used in WMF production but is
119 // here to provide third-party wikis with a way to enable caching for
120 // "view" and "history" actions. It's triggered by the use of $wgUseFileCache
121 // when set to true in LocalSettings.php.
122 if ( $title->canExist() && HTMLFileCache::useFileCache( $context ) ) {
123 // getAction() may trigger DB queries, so avoid eagerly initializing it if possible.
124 // This reduces the cost of requests that exit early due to tryNormaliseRedirect()
125 // or a MediaWikiPerformAction / BeforeInitialize hook handler.
126 $action = $this->getAction();
127 // Try low-level file cache hit
128 $cache = new HTMLFileCache( $title, $action );
129 if ( $cache->isCacheGood( /* Assume up to date */ ) ) {
130 // Check incoming headers to see if client has this cached
131 $timestamp = $cache->cacheTimestamp();
132 if ( !$output->checkLastModified( $timestamp ) ) {
133 $cache->loadFromFileCache( $context );
134 }
135 // Do any stats increment/watchlist stuff, assuming user is viewing the
136 // latest revision (which should always be the case for file cache)
137 $context->getWikiPage()->doViewUpdates( $context->getAuthority() );
138 // Tell OutputPage that output is taken care of
139 $output->disable();
140
141 return;
142 }
143 }
144
145 try {
146 // Actually do the work of the request and build up any output
147 $this->performRequest();
148 } catch ( ErrorPageError $e ) {
149 // TODO: Should ErrorPageError::report accept a OutputPage parameter?
150 $e->report( ErrorPageError::STAGE_OUTPUT );
151 $output->considerCacheSettingsFinal();
152 // T64091: while exceptions are convenient to bubble up GUI errors,
153 // they are not internal application faults. As with normal requests, this
154 // should commit, print the output, do deferred updates, jobs, and profiling.
155 }
156
157 $this->prepareForOutput();
158
159 // Ask OutputPage/Skin to stage the output (HTTP response body and headers).
160 // Flush the output to the client unless an exception occurred.
161 // Note that the OutputPage object in $context may have been replaced,
162 // so better fetch it again here.
163 $output = $context->getOutput();
164 $this->outputResponsePayload( $output->output( true ) );
165 }
166
167 /**
168 * If the stars are suitably aligned, do an HTTP->HTTPS redirect
169 *
170 * Note: Do this after $wgTitle is setup, otherwise the hooks run from
171 * isRegistered() will do all sorts of weird stuff.
172 *
173 * @return bool True if the redirect was done. Handling of the request
174 * should be aborted. False if no redirect was done.
175 */
176 protected function maybeDoHttpsRedirect() {
177 if ( !$this->shouldDoHttpRedirect() ) {
178 return false;
179 }
180
181 $context = $this->getContext();
182 $request = $context->getRequest();
183 $oldUrl = $request->getFullRequestURL();
184 $redirUrl = preg_replace( '#^http://#', 'https://', $oldUrl );
185
186 if ( $request->wasPosted() ) {
187 // This is weird and we'd hope it almost never happens. This
188 // means that a POST came in via HTTP and policy requires us
189 // redirecting to HTTPS. It's likely such a request is going
190 // to fail due to post data being lost, but let's try anyway
191 // and just log the instance.
192
193 // @todo FIXME: See if we could issue a 307 or 308 here, need
194 // to see how clients (automated & browser) behave when we do
195 wfDebugLog( 'RedirectedPosts', "Redirected from HTTP to HTTPS: $oldUrl" );
196 }
197 // Setup dummy Title, otherwise OutputPage::redirect will fail
198 $title = Title::newFromText( 'REDIR', NS_MAIN );
199 $context->setTitle( $title );
200 // Since we only do this redir to change proto, always send a vary header
201 $output = $context->getOutput();
202 $output->addVaryHeader( 'X-Forwarded-Proto' );
203 $output->redirect( $redirUrl );
204 $output->output();
205
206 return true;
207 }
208
209 protected function doPrepareForOutput() {
210 parent::doPrepareForOutput();
211
212 // If needed, push a deferred update to run jobs after the output is sent
213 $this->schedulePostSendJobs();
214 }
215
216 protected function schedulePostSendJobs() {
217 // Recursion guard for $wgRunJobsAsync
218 if ( $this->getTitle()->isSpecial( 'RunJobs' ) ) {
219 return;
220 }
221
222 parent::schedulePostSendJobs();
223 }
224
225 /**
226 * Parse the request to get the Title object
227 *
228 * @throws MalformedTitleException If a title has been provided by the user, but is invalid.
229 * @param WebRequest $request
230 * @return Title Title object to be $wgTitle
231 */
232 protected function parseTitle( $request ) {
233 $curid = $request->getInt( 'curid' );
234 $title = $request->getText( 'title' );
235
236 $ret = null;
237 if ( $curid ) {
238 // URLs like this are generated by RC, because rc_title isn't always accurate
239 $ret = Title::newFromID( $curid );
240 }
241 if ( $ret === null ) {
242 $ret = Title::newFromURL( $title );
243 if ( $ret !== null ) {
244 // Alias NS_MEDIA page URLs to NS_FILE...we only use NS_MEDIA
245 // in wikitext links to tell Parser to make a direct file link
246 if ( $ret->getNamespace() === NS_MEDIA ) {
247 $ret = Title::makeTitle( NS_FILE, $ret->getDBkey() );
248 }
249 // Check variant links so that interwiki links don't have to worry
250 // about the possible different language variants
251 $services = $this->getServiceContainer();
252 $languageConverter = $services
253 ->getLanguageConverterFactory()
254 ->getLanguageConverter( $services->getContentLanguage() );
255 if ( $languageConverter->hasVariants() && !$ret->exists() ) {
256 $languageConverter->findVariantLink( $title, $ret );
257 }
258 }
259 }
260
261 // If title is not provided, always allow oldid and diff to set the title.
262 // If title is provided, allow oldid and diff to override the title, unless
263 // we are talking about a special page which might use these parameters for
264 // other purposes.
265 if ( $ret === null || !$ret->isSpecialPage() ) {
266 // We can have urls with just ?diff=,?oldid= or even just ?diff=
267 $oldid = $request->getInt( 'oldid' );
268 $oldid = $oldid ?: $request->getInt( 'diff' );
269 // Allow oldid to override a changed or missing title
270 if ( $oldid ) {
271 $revRecord = $this->getServiceContainer()
272 ->getRevisionLookup()
273 ->getRevisionById( $oldid );
274 if ( $revRecord ) {
275 $ret = Title::newFromLinkTarget(
276 $revRecord->getPageAsLinkTarget()
277 );
278 }
279 }
280 }
281
282 if ( $ret === null && $request->getCheck( 'search' ) ) {
283 // Compatibility with old search URLs which didn't use Special:Search
284 // Just check for presence here, so blank requests still
285 // show the search page when using ugly URLs (T10054).
286 $ret = SpecialPage::getTitleFor( 'Search' );
287 }
288
289 if ( $ret === null || !$ret->isSpecialPage() ) {
290 // Compatibility with old URLs for Special:RevisionDelete/Special:EditTags (T323338)
291 $actionName = $request->getRawVal( 'action' );
292 if (
293 $actionName === 'revisiondelete' ||
294 ( $actionName === 'historysubmit' && $request->getBool( 'revisiondelete' ) )
295 ) {
296 $ret = SpecialPage::getTitleFor( 'Revisiondelete' );
297 } elseif (
298 $actionName === 'editchangetags' ||
299 ( $actionName === 'historysubmit' && $request->getBool( 'editchangetags' ) )
300 ) {
301 $ret = SpecialPage::getTitleFor( 'EditTags' );
302 }
303 }
304
305 // Use the main page as default title if nothing else has been provided
306 if ( $ret === null
307 && strval( $title ) === ''
308 && !$request->getCheck( 'curid' )
309 && $request->getRawVal( 'action' ) !== 'delete'
310 ) {
311 $ret = Title::newMainPage();
312 }
313
314 if ( $ret === null || ( $ret->getDBkey() == '' && !$ret->isExternal() ) ) {
315 // If we get here, we definitely don't have a valid title; throw an exception.
316 // Try to get detailed invalid title exception first, fall back to MalformedTitleException.
317 Title::newFromTextThrow( $title );
318 throw new MalformedTitleException( 'badtitletext', $title );
319 }
320
321 return $ret;
322 }
323
324 /**
325 * Get the Title object that we'll be acting on, as specified in the WebRequest
326 * @return Title
327 */
328 public function getTitle() {
329 $context = $this->getContext();
330
331 if ( !$context->hasTitle() ) {
332 try {
333 $context->setTitle( $this->parseTitle( $context->getRequest() ) );
334 } catch ( MalformedTitleException $ex ) {
335 $context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
336 }
337 }
338 return $context->getTitle();
339 }
340
341 /**
342 * Returns the name of the action that will be executed.
343 *
344 * @note This is public for the benefit of extensions that implement
345 * the BeforeInitialize or MediaWikiPerformAction hooks.
346 *
347 * @return string Action
348 */
349 public function getAction(): string {
350 return $this->getContext()->getActionName();
351 }
352
353 /**
354 * Performs the request.
355 * - bad titles
356 * - read restriction
357 * - local interwiki redirects
358 * - redirect loop
359 * - special pages
360 * - normal pages
361 *
362 * @throws PermissionsError|BadTitleError|HttpError
363 * @return void
364 */
365 protected function performRequest() {
366 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
367 global $wgTitle;
368
369 $context = $this->getContext();
370
371 $request = $context->getRequest();
372 $output = $context->getOutput();
373
374 if ( $request->getRawVal( 'printable' ) === 'yes' ) {
375 $output->setPrintable();
376 }
377
378 $user = $context->getUser();
379 $title = $context->getTitle();
380 $requestTitle = $title;
381
382 $userOptionsLookup = $this->getServiceContainer()->getUserOptionsLookup();
383 if ( $userOptionsLookup->getBoolOption( $user, 'forcesafemode' ) ) {
384 $request->setVal( 'safemode', '1' );
385 }
386
387 $this->getHookRunner()->onBeforeInitialize( $title, null, $output, $user, $request, $this );
388
389 // Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
390 if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
391 || $title->isSpecial( 'Badtitle' )
392 ) {
393 $context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
394 try {
395 $this->parseTitle( $request );
396 } catch ( MalformedTitleException $ex ) {
397 throw new BadTitleError( $ex );
398 }
399 throw new BadTitleError();
400 }
401
402 // Check user's permissions to read this page.
403 // We have to check here to catch special pages etc.
404 // We will check again in Article::view().
405 $permissionStatus = PermissionStatus::newEmpty();
406 if ( !$context->getAuthority()->authorizeRead( 'read', $title, $permissionStatus ) ) {
407 // T34276: allowing the skin to generate output with $wgTitle or
408 // $context->title set to the input title would allow anonymous users to
409 // determine whether a page exists, potentially leaking private data. In fact, the
410 // curid and oldid request parameters would allow page titles to be enumerated even
411 // when they are not guessable. So we reset the title to Special:Badtitle before the
412 // permissions error is displayed.
413
414 // The skin mostly uses $context->getTitle() these days, but some extensions
415 // still use $wgTitle.
416 $badTitle = SpecialPage::getTitleFor( 'Badtitle' );
417 $context->setTitle( $badTitle );
418 $wgTitle = $badTitle;
419
420 throw new PermissionsError( 'read', $permissionStatus );
421 }
422
423 // Interwiki redirects
424 if ( $title->isExternal() ) {
425 $rdfrom = $request->getVal( 'rdfrom' );
426 if ( $rdfrom ) {
427 $url = $title->getFullURL( [ 'rdfrom' => $rdfrom ] );
428 } else {
429 $query = $request->getValues();
430 unset( $query['title'] );
431 $url = $title->getFullURL( $query );
432 }
433 // Check for a redirect loop
434 if ( $url !== $request->getFullRequestURL() && $title->isLocal() ) {
435 // 301 so google et al report the target as the actual url.
436 $output->redirect( $url, 301 );
437 } else {
438 $context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
439 try {
440 $this->parseTitle( $request );
441 } catch ( MalformedTitleException $ex ) {
442 throw new BadTitleError( $ex );
443 }
444 throw new BadTitleError();
445 }
446 // Handle any other redirects.
447 // Redirect loops, titleless URL, $wgUsePathInfo URLs, and URLs with a variant
448 } elseif ( !$this->tryNormaliseRedirect( $title ) ) {
449 // Prevent information leak via Special:MyPage et al (T109724)
450 $spFactory = $this->getServiceContainer()->getSpecialPageFactory();
451 if ( $title->isSpecialPage() ) {
452 $specialPage = $spFactory->getPage( $title->getDBkey() );
453 if ( $specialPage instanceof RedirectSpecialPage ) {
454 $specialPage->setContext( $context );
455 if ( $this->getConfig( MainConfigNames::HideIdentifiableRedirects )
456 && $specialPage->personallyIdentifiableTarget()
457 ) {
458 [ , $subpage ] = $spFactory->resolveAlias( $title->getDBkey() );
459 $target = $specialPage->getRedirect( $subpage );
460 // Target can also be true. We let that case fall through to normal processing.
461 if ( $target instanceof Title ) {
462 if ( $target->isExternal() ) {
463 // Handle interwiki redirects
464 $target = SpecialPage::getTitleFor(
465 'GoToInterwiki',
466 'force/' . $target->getPrefixedDBkey()
467 );
468 }
469
470 $query = $specialPage->getRedirectQuery( $subpage ) ?: [];
471 $derivateRequest = new DerivativeRequest( $request, $query );
472 $derivateRequest->setRequestURL( $request->getRequestURL() );
473 $context->setRequest( $derivateRequest );
474 // Do not varnish cache these. May vary even for anons
475 $output->lowerCdnMaxage( 0 );
476 // NOTE: This also clears any action cache.
477 // Action should not have been computed yet, but if it was,
478 // we reset it because special pages only support "view".
479 $context->setTitle( $target );
480 $wgTitle = $target;
481 $title = $target;
482 $output->addJsConfigVars( [
483 'wgInternalRedirectTargetUrl' => $target->getLinkURL( $query ),
484 ] );
485 $output->addModules( 'mediawiki.action.view.redirect' );
486
487 // If the title is invalid, redirect but show the correct bad title error - T297407
488 if ( !$target->isValid() ) {
489 try {
490 $this->getServiceContainer()->getTitleParser()
491 ->parseTitle( $target->getPrefixedText() );
492 } catch ( MalformedTitleException $ex ) {
493 throw new BadTitleError( $ex );
494 }
495 throw new BadTitleError();
496 }
497 }
498 }
499 }
500 }
501
502 // Special pages ($title may have changed since if statement above)
503 if ( $title->isSpecialPage() ) {
504 // Actions that need to be made when we have a special pages
505 $spFactory->executePath( $title, $context );
506 } else {
507 // ...otherwise treat it as an article view. The article
508 // may still be a wikipage redirect to another article or URL.
509 $article = $this->initializeArticle();
510 if ( is_object( $article ) ) {
511 $this->performAction( $article, $requestTitle );
512 } elseif ( is_string( $article ) ) {
513 $output->redirect( $article );
514 } else {
515 throw new UnexpectedValueException( "Shouldn't happen: MediaWiki::initializeArticle()"
516 . " returned neither an object nor a URL" );
517 }
518 }
519
520 $contextRequest = $context->getRequest();
521 if ( $contextRequest instanceof FauxRequest ) {
522 $fauxResponse = $contextRequest->response();
523 if ( $fauxResponse->getStatusCode() ) {
524 $request->response()->statusHeader( $fauxResponse->getStatusCode() );
525 }
526
527 foreach ( $fauxResponse->getHeaders() as $key => $value ) {
528 $request->response()->header( "$key: $value" );
529 }
530 }
531
532 $output->considerCacheSettingsFinal();
533 }
534 }
535
536 /**
537 * Handle redirects for uncanonical title requests.
538 *
539 * Handles:
540 * - Redirect loops.
541 * - No title in URL.
542 * - $wgUsePathInfo URLs.
543 * - URLs with a variant.
544 * - Other non-standard URLs (as long as they have no extra query parameters).
545 *
546 * Behaviour:
547 * - Normalise title values:
548 * /wiki/Foo%20Bar -> /wiki/Foo_Bar
549 * - Normalise empty title:
550 * /wiki/ -> /wiki/Main
551 * /w/index.php?title= -> /wiki/Main
552 * - Don't redirect anything with query parameters other than 'title' or 'action=view'.
553 *
554 * @param Title $title
555 * @return bool True if a redirect was set.
556 * @throws HttpError
557 */
558 protected function tryNormaliseRedirect( Title $title ): bool {
559 $request = $this->getRequest();
560 $output = $this->getOutput();
561
562 if ( ( $request->getRawVal( 'action' ) ?? 'view' ) !== 'view'
563 || $request->wasPosted()
564 || ( $request->getCheck( 'title' )
565 && $title->getPrefixedDBkey() == $request->getText( 'title' ) )
566 || count( $request->getValueNames( [ 'action', 'title' ] ) )
567 || !$this->getHookRunner()->onTestCanonicalRedirect( $request, $title, $output )
568 ) {
569 return false;
570 }
571
572 if ( $this->getConfig( MainConfigNames::MainPageIsDomainRoot ) && $request->getRequestURL() === '/' ) {
573 return false;
574 }
575
576 $services = $this->getServiceContainer();
577
578 if ( $title->isSpecialPage() ) {
579 [ $name, $subpage ] = $services->getSpecialPageFactory()
580 ->resolveAlias( $title->getDBkey() );
581
582 if ( $name ) {
583 $title = SpecialPage::getTitleFor( $name, $subpage );
584 }
585 }
586 // Redirect to canonical url, make it a 301 to allow caching
587 $targetUrl = (string)$services->getUrlUtils()->expand( $title->getFullURL(), PROTO_CURRENT );
588 if ( $targetUrl == $request->getFullRequestURL() ) {
589 $message = "Redirect loop detected!\n\n" .
590 "This means the wiki got confused about what page was " .
591 "requested; this sometimes happens when moving a wiki " .
592 "to a new server or changing the server configuration.\n\n";
593
594 if ( $this->getConfig( MainConfigNames::UsePathInfo ) ) {
595 $message .= "The wiki is trying to interpret the page " .
596 "title from the URL path portion (PATH_INFO), which " .
597 "sometimes fails depending on the web server. Try " .
598 "setting \"\$wgUsePathInfo = false;\" in your " .
599 "LocalSettings.php, or check that \$wgArticlePath " .
600 "is correct.";
601 } else {
602 $message .= "Your web server was detected as possibly not " .
603 "supporting URL path components (PATH_INFO) correctly; " .
604 "check your LocalSettings.php for a customized " .
605 "\$wgArticlePath setting and/or toggle \$wgUsePathInfo " .
606 "to true.";
607 }
608 throw new HttpError( 500, $message );
609 }
610 $output->setCdnMaxage( 1200 );
611 $output->redirect( $targetUrl, '301' );
612 return true;
613 }
614
615 /**
616 * Initialize the main Article object for "standard" actions (view, etc)
617 * Create an Article object for the page, following redirects if needed.
618 *
619 * @return Article|string An Article, or a string to redirect to another URL
620 */
621 protected function initializeArticle() {
622 $context = $this->getContext();
623
624 $title = $context->getTitle();
625 $services = $this->getServiceContainer();
626 if ( $context->canUseWikiPage() ) {
627 // Optimization: Reuse the WikiPage instance from context, to avoid
628 // repeat fetching or computation of data already loaded.
629 $page = $context->getWikiPage();
630 } else {
631 // This case should not happen, but just in case.
632 // @TODO: remove this or use an exception
633 $page = $services->getWikiPageFactory()->newFromTitle( $title );
634 $context->setWikiPage( $page );
635 wfWarn( "RequestContext::canUseWikiPage() returned false" );
636 }
637
638 // Make GUI wrapper for the WikiPage
639 $article = Article::newFromWikiPage( $page, $context );
640
641 // Skip some unnecessary code if the content model doesn't support redirects
642 // Use the page content model rather than invoking Title::getContentModel()
643 // to avoid querying page data twice (T206498)
644 if ( !$page->getContentHandler()->supportsRedirects() ) {
645 return $article;
646 }
647
648 $request = $context->getRequest();
649
650 // Namespace might change when using redirects
651 // Check for redirects ...
652 $action = $request->getRawVal( 'action' ) ?? 'view';
653 $file = ( $page instanceof WikiFilePage ) ? $page->getFile() : null;
654 if ( ( $action == 'view' || $action == 'render' ) // ... for actions that show content
655 && !$request->getCheck( 'oldid' ) // ... and are not old revisions
656 && !$request->getCheck( 'diff' ) // ... and not when showing diff
657 && $request->getRawVal( 'redirect' ) !== 'no' // ... unless explicitly told not to
658 // ... and the article is not a non-redirect image page with associated file
659 && !( is_object( $file ) && $file->exists() && !$file->getRedirected() )
660 ) {
661 // Give extensions a change to ignore/handle redirects as needed
662 $ignoreRedirect = $target = false;
663
664 $this->getHookRunner()->onInitializeArticleMaybeRedirect( $title, $request,
665 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
666 $ignoreRedirect, $target, $article );
667 $page = $article->getPage(); // reflect any hook changes
668
669 // Follow redirects only for... redirects.
670 // If $target is set, then a hook wanted to redirect.
671 if ( !$ignoreRedirect && ( $target || $page->isRedirect() ) ) {
672 // Is the target already set by an extension?
673 $target = $target ?: $page->followRedirect();
674 if ( is_string( $target ) && !$this->getConfig( MainConfigNames::DisableHardRedirects ) ) {
675 // we'll need to redirect
676 return $target;
677 }
678 if ( is_object( $target ) ) {
679 // Rewrite environment to redirected article
680 $rpage = $services->getWikiPageFactory()->newFromTitle( $target );
681 $rpage->loadPageData();
682 if ( $rpage->exists() || ( is_object( $file ) && !$file->isLocal() ) ) {
683 $rarticle = Article::newFromWikiPage( $rpage, $context );
684 $rarticle->setRedirectedFrom( $title );
685
686 $article = $rarticle;
687 // NOTE: This also clears any action cache
688 $context->setTitle( $target );
689 $context->setWikiPage( $article->getPage() );
690 }
691 }
692 }
693 }
694
695 return $article;
696 }
697
698 /**
699 * Perform one of the "standard" actions
700 *
701 * @param Article $article
702 * @param Title $requestTitle The original title, before any redirects were applied
703 */
704 protected function performAction( Article $article, Title $requestTitle ) {
705 $request = $this->getRequest();
706 $output = $this->getOutput();
707 $title = $this->getTitle();
708 $user = $this->getUser();
709
710 if ( !$this->getHookRunner()->onMediaWikiPerformAction(
711 $output, $article, $title, $user, $request, $this )
712 ) {
713 return;
714 }
715
716 $t = microtime( true );
717 $actionName = $this->getAction();
718 $services = $this->getServiceContainer();
719
720 $action = $services->getActionFactory()->getAction( $actionName, $article, $this->getContext() );
721 if ( $action instanceof Action ) {
722 ProfilingContext::singleton()->init( MW_ENTRY_POINT, $actionName );
723
724 // Check read permissions
725 if ( $action->needsReadRights() && !$user->isAllowed( 'read' ) ) {
726 throw new PermissionsError( 'read' );
727 }
728
729 // Narrow DB query expectations for this HTTP request
730 if ( $request->wasPosted() && !$action->doesWrites() ) {
731 $trxProfiler = Profiler::instance()->getTransactionProfiler();
732 $trxLimits = $this->getConfig( MainConfigNames::TrxProfilerLimits );
733 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
734 }
735
736 // Let CDN cache things if we can purge them.
737 // Also unconditionally cache page views.
738 if ( $this->getConfig( MainConfigNames::UseCdn ) ) {
739 $htmlCacheUpdater = $services->getHtmlCacheUpdater();
740 if ( $request->matchURLForCDN( $htmlCacheUpdater->getUrls( $requestTitle ) ) ) {
741 $output->setCdnMaxage( $this->getConfig( MainConfigNames::CdnMaxAge ) );
742 } elseif ( $action instanceof ViewAction ) {
743 $output->setCdnMaxage( 3600 );
744 }
745 }
746
747 $action->show();
748
749 $runTime = microtime( true ) - $t;
750
751 $statAction = strtr( $actionName, '.', '_' );
752 $services->getStatsFactory()->getTiming( 'action_executeTiming_seconds' )
753 ->setLabel( 'action', $statAction )
754 ->copyToStatsdAt( 'action.' . $statAction . '.executeTiming' )
755 ->observe( 1000 * $runTime );
756
757 return;
758 }
759
760 // If we've not found out which action it is by now, it's unknown
761 $output->setStatusCode( 404 );
762 $output->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
763 }
764 }