MediaWiki master
Article.php
Go to the documentation of this file.
1<?php
28use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
57use Wikimedia\IPUtils;
58use Wikimedia\NonSerializable\NonSerializableTrait;
60
70class Article implements Page {
71 use ProtectedHookAccessorTrait;
72 use NonSerializableTrait;
73
79 protected $mContext;
80
82 protected $mPage;
83
88 public $mOldId;
89
91 public $mRedirectedFrom = null;
92
94 public $mRedirectUrl = false;
95
100 private $fetchResult = null;
101
107 public $mParserOutput = null;
108
114 protected $viewIsRenderAction = false;
115
117 private RevisionStore $revisionStore;
118 private UserNameUtils $userNameUtils;
119 private UserOptionsLookup $userOptionsLookup;
120 private CommentFormatter $commentFormatter;
121 private WikiPageFactory $wikiPageFactory;
122 private JobQueueGroup $jobQueueGroup;
123 private ArchivedRevisionLookup $archivedRevisionLookup;
126
128
135 private $mRevisionRecord = null;
136
141 public function __construct( Title $title, $oldId = null ) {
142 $this->mOldId = $oldId;
143 $this->mPage = $this->newPage( $title );
144
145 $services = MediaWikiServices::getInstance();
146 $this->linkRenderer = $services->getLinkRenderer();
147 $this->revisionStore = $services->getRevisionStore();
148 $this->userNameUtils = $services->getUserNameUtils();
149 $this->userOptionsLookup = $services->getUserOptionsLookup();
150 $this->commentFormatter = $services->getCommentFormatter();
151 $this->wikiPageFactory = $services->getWikiPageFactory();
152 $this->jobQueueGroup = $services->getJobQueueGroup();
153 $this->archivedRevisionLookup = $services->getArchivedRevisionLookup();
154 $this->dbProvider = $services->getConnectionProvider();
155 $this->blockStore = $services->getDatabaseBlockStore();
156 $this->restrictionStore = $services->getRestrictionStore();
157 }
158
163 protected function newPage( Title $title ) {
164 return new WikiPage( $title );
165 }
166
172 public static function newFromID( $id ) {
173 $t = Title::newFromID( $id );
174 return $t === null ? null : new static( $t );
175 }
176
184 public static function newFromTitle( $title, IContextSource $context ): self {
185 if ( $title->getNamespace() === NS_MEDIA ) {
186 // XXX: This should not be here, but where should it go?
187 $title = Title::makeTitle( NS_FILE, $title->getDBkey() );
188 }
189
190 $page = null;
191 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
192 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
193 ->onArticleFromTitle( $title, $page, $context );
194 if ( !$page ) {
195 switch ( $title->getNamespace() ) {
196 case NS_FILE:
197 $page = new ImagePage( $title );
198 break;
199 case NS_CATEGORY:
200 $page = new CategoryPage( $title );
201 break;
202 default:
203 $page = new Article( $title );
204 }
205 }
206 $page->setContext( $context );
207
208 return $page;
209 }
210
218 public static function newFromWikiPage( WikiPage $page, IContextSource $context ) {
219 $article = self::newFromTitle( $page->getTitle(), $context );
220 $article->mPage = $page; // override to keep process cached vars
221 return $article;
222 }
223
229 public function getRedirectedFrom() {
230 return $this->mRedirectedFrom;
231 }
232
237 public function setRedirectedFrom( Title $from ) {
238 $this->mRedirectedFrom = $from;
239 }
240
246 public function getTitle() {
247 return $this->mPage->getTitle();
248 }
249
256 public function getPage() {
257 return $this->mPage;
258 }
259
260 public function clear() {
261 $this->mRedirectedFrom = null; # Title object if set
262 $this->mRedirectUrl = false;
263 $this->mRevisionRecord = null;
264 $this->fetchResult = null;
265
266 // TODO hard-deprecate direct access to public fields
267
268 $this->mPage->clear();
269 }
270
278 public function getOldID() {
279 if ( $this->mOldId === null ) {
280 $this->mOldId = $this->getOldIDFromRequest();
281 }
282
283 return $this->mOldId;
284 }
285
291 public function getOldIDFromRequest() {
292 $this->mRedirectUrl = false;
293
294 $request = $this->getContext()->getRequest();
295 $oldid = $request->getIntOrNull( 'oldid' );
296
297 if ( $oldid === null ) {
298 return 0;
299 }
300
301 if ( $oldid !== 0 ) {
302 # Load the given revision and check whether the page is another one.
303 # In that case, update this instance to reflect the change.
304 if ( $oldid === $this->mPage->getLatest() ) {
305 $this->mRevisionRecord = $this->mPage->getRevisionRecord();
306 } else {
307 $this->mRevisionRecord = $this->revisionStore->getRevisionById( $oldid );
308 if ( $this->mRevisionRecord !== null ) {
309 $revPageId = $this->mRevisionRecord->getPageId();
310 // Revision title doesn't match the page title given?
311 if ( $this->mPage->getId() !== $revPageId ) {
312 $this->mPage = $this->wikiPageFactory->newFromID( $revPageId );
313 }
314 }
315 }
316 }
317
318 $oldRev = $this->mRevisionRecord;
319 if ( $request->getRawVal( 'direction' ) === 'next' ) {
320 $nextid = 0;
321 if ( $oldRev ) {
322 $nextRev = $this->revisionStore->getNextRevision( $oldRev );
323 if ( $nextRev ) {
324 $nextid = $nextRev->getId();
325 }
326 }
327 if ( $nextid ) {
328 $oldid = $nextid;
329 $this->mRevisionRecord = null;
330 } else {
331 $this->mRedirectUrl = $this->getTitle()->getFullURL( 'redirect=no' );
332 }
333 } elseif ( $request->getRawVal( 'direction' ) === 'prev' ) {
334 $previd = 0;
335 if ( $oldRev ) {
336 $prevRev = $this->revisionStore->getPreviousRevision( $oldRev );
337 if ( $prevRev ) {
338 $previd = $prevRev->getId();
339 }
340 }
341 if ( $previd ) {
342 $oldid = $previd;
343 $this->mRevisionRecord = null;
344 }
345 }
346
347 return $oldid;
348 }
349
359 public function fetchRevisionRecord() {
360 if ( $this->fetchResult ) {
361 return $this->mRevisionRecord;
362 }
363
364 $oldid = $this->getOldID();
365
366 // $this->mRevisionRecord might already be fetched by getOldIDFromRequest()
367 if ( !$this->mRevisionRecord ) {
368 if ( !$oldid ) {
369 $this->mRevisionRecord = $this->mPage->getRevisionRecord();
370
371 if ( !$this->mRevisionRecord ) {
372 wfDebug( __METHOD__ . " failed to find page data for title " .
373 $this->getTitle()->getPrefixedText() );
374
375 // Output for this case is done by showMissingArticle().
376 $this->fetchResult = Status::newFatal( 'noarticletext' );
377 return null;
378 }
379 } else {
380 $this->mRevisionRecord = $this->revisionStore->getRevisionById( $oldid );
381
382 if ( !$this->mRevisionRecord ) {
383 wfDebug( __METHOD__ . " failed to load revision, rev_id $oldid" );
384
385 $this->fetchResult = Status::newFatal( $this->getMissingRevisionMsg( $oldid ) );
386 return null;
387 }
388 }
389 }
390
391 if ( !$this->mRevisionRecord->userCan( RevisionRecord::DELETED_TEXT, $this->getContext()->getAuthority() ) ) {
392 wfDebug( __METHOD__ . " failed to retrieve content of revision " . $this->mRevisionRecord->getId() );
393
394 // Output for this case is done by showDeletedRevisionHeader().
395 // title used in wikilinks, should not contain whitespaces
396 $this->fetchResult = new Status;
397 $title = $this->getTitle()->getPrefixedDBkey();
398
399 if ( $this->mRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) {
400 $this->fetchResult->fatal( 'rev-suppressed-text' );
401 } else {
402 $this->fetchResult->fatal( 'rev-deleted-text-permission', $title );
403 }
404
405 return null;
406 }
407
408 $this->fetchResult = Status::newGood( $this->mRevisionRecord );
409 return $this->mRevisionRecord;
410 }
411
417 public function isCurrent() {
418 # If no oldid, this is the current version.
419 if ( $this->getOldID() == 0 ) {
420 return true;
421 }
422
423 return $this->mPage->exists() &&
424 $this->mRevisionRecord &&
425 $this->mRevisionRecord->isCurrent();
426 }
427
436 public function getRevIdFetched() {
437 if ( $this->fetchResult && $this->fetchResult->isOK() ) {
439 $rev = $this->fetchResult->getValue();
440 return $rev->getId();
441 } else {
442 return $this->mPage->getLatest();
443 }
444 }
445
450 public function view() {
451 $context = $this->getContext();
452 $useFileCache = $context->getConfig()->get( MainConfigNames::UseFileCache );
453
454 # Get variables from query string
455 # As side effect this will load the revision and update the title
456 # in a revision ID is passed in the request, so this should remain
457 # the first call of this method even if $oldid is used way below.
458 $oldid = $this->getOldID();
459
460 $authority = $context->getAuthority();
461 # Another check in case getOldID() is altering the title
462 $permissionStatus = PermissionStatus::newEmpty();
463 if ( !$authority
464 ->authorizeRead( 'read', $this->getTitle(), $permissionStatus )
465 ) {
466 wfDebug( __METHOD__ . ": denied on secondary read check" );
467 throw new PermissionsError( 'read', $permissionStatus );
468 }
469
470 $outputPage = $context->getOutput();
471 # getOldID() may as well want us to redirect somewhere else
472 if ( $this->mRedirectUrl ) {
473 $outputPage->redirect( $this->mRedirectUrl );
474 wfDebug( __METHOD__ . ": redirecting due to oldid" );
475
476 return;
477 }
478
479 # If we got diff in the query, we want to see a diff page instead of the article.
480 if ( $context->getRequest()->getCheck( 'diff' ) ) {
481 wfDebug( __METHOD__ . ": showing diff page" );
482 $this->showDiffPage();
483
484 return;
485 }
486
487 $this->showProtectionIndicator();
488
489 # Set page title (may be overridden from ParserOutput if title conversion is enabled or DISPLAYTITLE is used)
490 $outputPage->setPageTitle( Parser::formatPageTitle(
491 str_replace( '_', ' ', $this->getTitle()->getNsText() ),
492 ':',
493 $this->getTitle()->getText()
494 ) );
495
496 $outputPage->setArticleFlag( true );
497 # Allow frames by default
498 $outputPage->getMetadata()->setPreventClickjacking( false );
499
500 $parserOptions = $this->getParserOptions();
501
502 $poOptions = [];
503 # Allow extensions to vary parser options used for article rendering
504 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
505 ->onArticleParserOptions( $this, $parserOptions );
506 # Render printable version, use printable version cache
507 if ( $outputPage->isPrintable() ) {
508 $parserOptions->setIsPrintable( true );
509 $poOptions['enableSectionEditLinks'] = false;
510 $this->addMessageBoxStyles( $outputPage );
511 $outputPage->prependHTML(
512 Html::warningBox(
513 $outputPage->msg( 'printableversion-deprecated-warning' )->escaped()
514 )
515 );
516 } elseif ( $this->viewIsRenderAction || !$this->isCurrent() ||
517 !$authority->probablyCan( 'edit', $this->getTitle() )
518 ) {
519 $poOptions['enableSectionEditLinks'] = false;
520 }
521
522 # Try client and file cache
523 if ( $oldid === 0 && $this->mPage->checkTouched() ) {
524 # Try to stream the output from file cache
525 if ( $useFileCache && $this->tryFileCache() ) {
526 wfDebug( __METHOD__ . ": done file cache" );
527 # tell wgOut that output is taken care of
528 $outputPage->disable();
529 $this->mPage->doViewUpdates( $authority, $oldid );
530
531 return;
532 }
533 }
534
535 $this->showRedirectedFromHeader();
536 $this->showNamespaceHeader();
537
538 if ( $this->viewIsRenderAction ) {
539 $poOptions += [ 'absoluteURLs' => true ];
540 }
541 $poOptions += [ 'includeDebugInfo' => true ];
542
543 try {
544 $continue =
545 $this->generateContentOutput( $authority, $parserOptions, $oldid, $outputPage, $poOptions );
546 } catch ( BadRevisionException $e ) {
547 $continue = false;
548 $this->showViewError( wfMessage( 'badrevision' )->text() );
549 }
550
551 if ( !$continue ) {
552 return;
553 }
554
555 # For the main page, overwrite the <title> element with the con-
556 # tents of 'pagetitle-view-mainpage' instead of the default (if
557 # that's not empty).
558 # This message always exists because it is in the i18n files
559 if ( $this->getTitle()->isMainPage() ) {
560 $msg = $context->msg( 'pagetitle-view-mainpage' )->inContentLanguage();
561 if ( !$msg->isDisabled() ) {
562 $outputPage->setHTMLTitle( $msg->text() );
563 }
564 }
565
566 // Enable 1-day CDN cache on this response
567 //
568 // To reduce impact of lost or delayed HTTP purges, the adaptive TTL will
569 // raise the TTL for pages not recently edited, upto $wgCdnMaxAge.
570 // This could use getTouched(), but that could be scary for major template edits.
571 $outputPage->adaptCdnTTL( $this->mPage->getTimestamp(), 86_400 );
572
573 $this->showViewFooter();
574 $this->mPage->doViewUpdates( $authority, $oldid, $this->fetchRevisionRecord() );
575
576 # Load the postEdit module if the user just saved this revision
577 # See also EditPage::setPostEditCookie
578 $request = $context->getRequest();
579 $cookieKey = EditPage::POST_EDIT_COOKIE_KEY_PREFIX . $this->getRevIdFetched();
580 $postEdit = $request->getCookie( $cookieKey );
581 if ( $postEdit ) {
582 # Clear the cookie. This also prevents caching of the response.
583 $request->response()->clearCookie( $cookieKey );
584 $outputPage->addJsConfigVars( 'wgPostEdit', $postEdit );
585 $outputPage->addModules( 'mediawiki.action.view.postEdit' ); // FIXME: test this
586 if ( $this->getContext()->getConfig()->get( MainConfigNames::EnableEditRecovery )
587 && $this->userOptionsLookup->getOption( $this->getContext()->getUser(), 'editrecovery' )
588 ) {
589 $outputPage->addModules( 'mediawiki.editRecovery.postEdit' );
590 }
591 }
592 }
593
597 public function showProtectionIndicator(): void {
598 $title = $this->getTitle();
599 $context = $this->getContext();
600 $outputPage = $context->getOutput();
601
602 $protectionIndicatorsAreEnabled = $context->getConfig()
603 ->get( MainConfigNames::EnableProtectionIndicators );
604
605 if ( !$protectionIndicatorsAreEnabled || $title->isMainPage() ) {
606 return;
607 }
608
609 $protection = $this->restrictionStore->getRestrictions( $title, 'edit' );
610
611 $cascadeProtection = $this->restrictionStore->getCascadeProtectionSources( $title )[1];
612
613 $isCascadeProtected = array_key_exists( 'edit', $cascadeProtection );
614
615 if ( !$protection && !$isCascadeProtected ) {
616 return;
617 }
618
619 if ( $isCascadeProtected ) {
620 // Cascade-protected pages are protected at the sysop level. So it
621 // should not matter if we take the protection level of the first
622 // or last page that is being cascaded to the current page.
623 $protectionLevel = $cascadeProtection['edit'][0];
624 } else {
625 $protectionLevel = $protection[0];
626 }
627
628 // Protection levels are stored in the database as plain text, but
629 // they are expected to be valid protection levels. So we should be able to
630 // safely use them. However phan thinks this could be a XSS problem so we
631 // are being paranoid and escaping them once more.
632 $protectionLevel = htmlspecialchars( $protectionLevel );
633
634 $protectionExpiry = $this->restrictionStore->getRestrictionExpiry( $title, 'edit' );
635 $formattedProtectionExpiry = $context->getLanguage()
636 ->formatExpiry( $protectionExpiry ?? '' );
637
638 $protectionMsg = 'protection-indicator-title';
639 if ( $protectionExpiry === 'infinity' || !$protectionExpiry ) {
640 $protectionMsg .= '-infinity';
641 }
642
643 // Potential values: 'protection-sysop', 'protection-autoconfirmed',
644 // 'protection-sysop-cascade' etc.
645 // If the wiki has more protection levels, the additional ids that get
646 // added take the form 'protection-<protectionLevel>' and
647 // 'protection-<protectionLevel>-cascade'.
648 $protectionIndicatorId = 'protection-' . $protectionLevel;
649 $protectionIndicatorId .= ( $isCascadeProtected ? '-cascade' : '' );
650
651 // Messages 'protection-indicator-title', 'protection-indicator-title-infinity'
652 $protectionMsg = $outputPage->msg( $protectionMsg, $protectionLevel, $formattedProtectionExpiry )->text();
653
654 // Use a trick similar to the one used in Action::addHelpLink() to allow wikis
655 // to customize where the help link points to.
656 $protectionHelpLink = $outputPage->msg( $protectionIndicatorId . '-helppage' );
657 if ( $protectionHelpLink->isDisabled() ) {
658 $protectionHelpLink = 'https://mediawiki.org/wiki/Special:MyLanguage/Help:Protection';
659 } else {
660 $protectionHelpLink = $protectionHelpLink->text();
661 }
662
663 $outputPage->setIndicators( [
664 $protectionIndicatorId => Html::rawElement( 'a', [
665 'class' => 'mw-protection-indicator-icon--lock',
666 'title' => $protectionMsg,
667 'href' => $protectionHelpLink
668 ],
669 // Screen reader-only text describing the same thing as
670 // was mentioned in the title attribute.
671 Html::element( 'span', [], $protectionMsg ) )
672 ] );
673
674 $outputPage->addModuleStyles( 'mediawiki.protectionIndicators.styles' );
675 }
676
689 private function generateContentOutput(
690 Authority $performer,
691 ParserOptions $parserOptions,
692 int $oldid,
693 OutputPage $outputPage,
694 array $textOptions
695 ): bool {
696 # Should the parser cache be used?
697 $useParserCache = true;
698 $pOutput = null;
699 $parserOutputAccess = MediaWikiServices::getInstance()->getParserOutputAccess();
700
701 // NOTE: $outputDone and $useParserCache may be changed by the hook
702 $this->getHookRunner()->onArticleViewHeader( $this, $outputDone, $useParserCache );
703 if ( $outputDone ) {
704 if ( $outputDone instanceof ParserOutput ) {
705 $pOutput = $outputDone;
706 }
707
708 if ( $pOutput ) {
709 $this->doOutputMetaData( $pOutput, $outputPage );
710 }
711 return true;
712 }
713
714 // Early abort if the page doesn't exist
715 if ( !$this->mPage->exists() ) {
716 wfDebug( __METHOD__ . ": showing missing article" );
717 $this->showMissingArticle();
718 $this->mPage->doViewUpdates( $performer );
719 return false; // skip all further output to OutputPage
720 }
721
722 // Try the latest parser cache
723 // NOTE: try latest-revision cache first to avoid loading revision.
724 if ( $useParserCache && !$oldid ) {
725 $pOutput = $parserOutputAccess->getCachedParserOutput(
726 $this->getPage(),
727 $parserOptions,
728 null,
729 ParserOutputAccess::OPT_NO_AUDIENCE_CHECK // we already checked
730 );
731
732 if ( $pOutput ) {
733 $this->doOutputFromParserCache( $pOutput, $outputPage, $textOptions );
734 $this->doOutputMetaData( $pOutput, $outputPage );
735 return true;
736 }
737 }
738
739 $rev = $this->fetchRevisionRecord();
740 if ( !$this->fetchResult->isOK() ) {
741 $this->showViewError( $this->fetchResult->getWikiText(
742 false, false, $this->getContext()->getLanguage()
743 ) );
744 return true;
745 }
746
747 # Are we looking at an old revision
748 if ( $oldid ) {
749 $this->setOldSubtitle( $oldid );
750
751 if ( !$this->showDeletedRevisionHeader() ) {
752 wfDebug( __METHOD__ . ": cannot view deleted revision" );
753 return false; // skip all further output to OutputPage
754 }
755
756 // Try the old revision parser cache
757 // NOTE: Repeating cache check for old revision to avoid fetching $rev
758 // before it's absolutely necessary.
759 if ( $useParserCache ) {
760 $pOutput = $parserOutputAccess->getCachedParserOutput(
761 $this->getPage(),
762 $parserOptions,
763 $rev,
764 ParserOutputAccess::OPT_NO_AUDIENCE_CHECK // we already checked in fetchRevisionRecord
765 );
766
767 if ( $pOutput ) {
768 $this->doOutputFromParserCache( $pOutput, $outputPage, $textOptions );
769 $this->doOutputMetaData( $pOutput, $outputPage );
770 return true;
771 }
772 }
773 }
774
775 # Ensure that UI elements requiring revision ID have
776 # the correct version information. (This may be overwritten after creation of ParserOutput)
777 $outputPage->setRevisionId( $this->getRevIdFetched() );
778 $outputPage->setRevisionIsCurrent( $rev->isCurrent() );
779 # Preload timestamp to avoid a DB hit
780 $outputPage->setRevisionTimestamp( $rev->getTimestamp() );
781
782 # Pages containing custom CSS or JavaScript get special treatment
783 if ( $this->getTitle()->isSiteConfigPage() || $this->getTitle()->isUserConfigPage() ) {
784 $dir = $this->getContext()->getLanguage()->getDir();
785 $lang = $this->getContext()->getLanguage()->getHtmlCode();
786
787 $outputPage->wrapWikiMsg(
788 "<div id='mw-clearyourcache' lang='$lang' dir='$dir' class='mw-content-$dir'>\n$1\n</div>",
789 'clearyourcache'
790 );
791 $outputPage->addModuleStyles( 'mediawiki.action.styles' );
792 } elseif ( !$this->getHookRunner()->onArticleRevisionViewCustom(
793 $rev,
794 $this->getTitle(),
795 $oldid,
796 $outputPage )
797 ) {
798 // NOTE: sync with hooks called in DifferenceEngine::renderNewRevision()
799 // Allow extensions do their own custom view for certain pages
800 $this->doOutputMetaData( $pOutput, $outputPage );
801 return true;
802 }
803
804 # Run the parse, protected by a pool counter
805 wfDebug( __METHOD__ . ": doing uncached parse" );
806
807 $opt = 0;
808
809 // we already checked the cache in case 2, don't check again.
810 $opt |= ParserOutputAccess::OPT_NO_CHECK_CACHE;
811
812 // we already checked in fetchRevisionRecord()
813 $opt |= ParserOutputAccess::OPT_NO_AUDIENCE_CHECK;
814
815 // enable stampede protection and allow stale content
816 $opt |= ParserOutputAccess::OPT_FOR_ARTICLE_VIEW;
817
818 // Attempt to trigger WikiPage::triggerOpportunisticLinksUpdate
819 // Ideally this should not be the responsibility of the ParserCache to control this.
820 // See https://phabricator.wikimedia.org/T329842#8816557 for more context.
821 $opt |= ParserOutputAccess::OPT_LINKS_UPDATE;
822
823 if ( !$rev->getId() || !$useParserCache ) {
824 // fake revision or uncacheable options
825 $opt |= ParserOutputAccess::OPT_NO_CACHE;
826 }
827
828 $renderStatus = $parserOutputAccess->getParserOutput(
829 $this->getPage(),
830 $parserOptions,
831 $rev,
832 $opt
833 );
834
835 // T327164: If parsoid cache warming is enabled, we want to ensure that the page
836 // the user is currently looking at has a cached parsoid rendering, in case they
837 // open visual editor. The cache entry would typically be missing if it has expired
838 // from the cache or it was invalidated by RefreshLinksJob. When "traditional"
839 // parser output has been invalidated by RefreshLinksJob, we will render it on
840 // the fly when a user requests the page, and thereby populate the cache again,
841 // per the code above.
842 // The code below is intended to do the same for parsoid output, but asynchronously
843 // in a job, so the user does not have to wait.
844 // Note that we get here if the traditional parser output was missing from the cache.
845 // We do not check if the parsoid output is present in the cache, because that check
846 // takes time. The assumption is that if we have traditional parser output
847 // cached, we probably also have parsoid output cached.
848 // So we leave it to ParsoidCachePrewarmJob to determine whether or not parsing is
849 // needed.
850 if ( $oldid === 0 || $oldid === $this->getPage()->getLatest() ) {
851 $parsoidCacheWarmingEnabled = $this->getContext()->getConfig()
852 ->get( MainConfigNames::ParsoidCacheConfig )['WarmParsoidParserCache'];
853
854 if ( $parsoidCacheWarmingEnabled ) {
855 $parsoidJobSpec = ParsoidCachePrewarmJob::newSpec(
856 $rev->getId(),
857 $this->getPage()->toPageRecord(),
858 [ 'causeAction' => 'view' ]
859 );
860 $this->jobQueueGroup->lazyPush( $parsoidJobSpec );
861 }
862 }
863
864 $this->doOutputFromRenderStatus(
865 $rev,
866 $renderStatus,
867 $outputPage,
868 $textOptions
869 );
870
871 if ( !$renderStatus->isOK() ) {
872 return true;
873 }
874
875 $pOutput = $renderStatus->getValue();
876 $this->doOutputMetaData( $pOutput, $outputPage );
877 return true;
878 }
879
880 private function doOutputMetaData( ?ParserOutput $pOutput, OutputPage $outputPage ) {
881 # Adjust title for main page & pages with displaytitle
882 if ( $pOutput ) {
883 $this->adjustDisplayTitle( $pOutput );
884
885 // It would be nice to automatically set this during the first call
886 // to OutputPage::addParserOutputMetadata, but we can't because doing
887 // so would break non-pageview actions where OutputPage::getContLangForJS
888 // has different requirements.
889 $pageLang = $pOutput->getLanguage();
890 if ( $pageLang ) {
891 $outputPage->setContentLangForJS( $pageLang );
892 }
893 }
894
895 # Check for any __NOINDEX__ tags on the page using $pOutput
896 $policy = $this->getRobotPolicy( 'view', $pOutput ?: null );
897 $outputPage->getMetadata()->setIndexPolicy( $policy['index'] );
898 $outputPage->setFollowPolicy( $policy['follow'] ); // FIXME: test this
899
900 $this->mParserOutput = $pOutput;
901 }
902
908 private function doOutputFromParserCache(
909 ParserOutput $pOutput,
910 OutputPage $outputPage,
911 array $textOptions
912 ) {
913 # Ensure that UI elements requiring revision ID have
914 # the correct version information.
915 $oldid = $pOutput->getCacheRevisionId() ?? $this->getRevIdFetched();
916 $outputPage->setRevisionId( $oldid );
917 $outputPage->setRevisionIsCurrent( $oldid === $this->mPage->getLatest() );
918 $outputPage->addParserOutput( $pOutput, $textOptions );
919 # Preload timestamp to avoid a DB hit
920 $cachedTimestamp = $pOutput->getRevisionTimestamp();
921 if ( $cachedTimestamp !== null ) {
922 $outputPage->setRevisionTimestamp( $cachedTimestamp );
923 $this->mPage->setTimestamp( $cachedTimestamp );
924 }
925 }
926
933 private function doOutputFromRenderStatus(
934 RevisionRecord $rev,
935 Status $renderStatus,
936 OutputPage $outputPage,
937 array $textOptions
938 ) {
939 $context = $this->getContext();
940 if ( !$renderStatus->isOK() ) {
941 $this->showViewError( $renderStatus->getWikiText(
942 false, 'view-pool-error', $context->getLanguage()
943 ) );
944 return;
945 }
946
947 $pOutput = $renderStatus->getValue();
948
949 // Cache stale ParserOutput object with a short expiry
950 if ( $renderStatus->hasMessage( 'view-pool-dirty-output' ) ) {
951 $outputPage->lowerCdnMaxage( $context->getConfig()->get( MainConfigNames::CdnMaxageStale ) );
952 $outputPage->setLastModified( $pOutput->getCacheTime() );
953 $staleReason = $renderStatus->hasMessage( 'view-pool-contention' )
954 ? $context->msg( 'view-pool-contention' )->escaped()
955 : $context->msg( 'view-pool-timeout' )->escaped();
956 $outputPage->addHTML( "<!-- parser cache is expired, " .
957 "sending anyway due to $staleReason-->\n" );
958
959 // Ensure OutputPage knowns the id from the dirty cache, but keep the current flag (T341013)
960 $cachedId = $pOutput->getCacheRevisionId();
961 if ( $cachedId !== null ) {
962 $outputPage->setRevisionId( $cachedId );
963 $outputPage->setRevisionTimestamp( $pOutput->getTimestamp() );
964 }
965 }
966
967 $outputPage->addParserOutput( $pOutput, $textOptions );
968
969 if ( $this->getRevisionRedirectTarget( $rev ) ) {
970 $outputPage->addSubtitle( "<span id=\"redirectsub\">" .
971 $context->msg( 'redirectpagesub' )->parse() . "</span>" );
972 }
973 }
974
979 private function getRevisionRedirectTarget( RevisionRecord $revision ) {
980 // TODO: find a *good* place for the code that determines the redirect target for
981 // a given revision!
982 // NOTE: Use main slot content. Compare code in DerivedPageDataUpdater::revisionIsRedirect.
983 $content = $revision->getContent( SlotRecord::MAIN );
984 return $content ? $content->getRedirectTarget() : null;
985 }
986
990 public function adjustDisplayTitle( ParserOutput $pOutput ) {
991 $out = $this->getContext()->getOutput();
992
993 # Adjust the title if it was set by displaytitle, -{T|}- or language conversion
994 $titleText = $pOutput->getTitleText();
995 if ( strval( $titleText ) !== '' ) {
996 $out->setPageTitle( $titleText );
997 $out->setDisplayTitle( $titleText );
998 }
999 }
1000
1005 protected function showDiffPage() {
1006 $context = $this->getContext();
1007 $outputPage = $context->getOutput();
1008 $outputPage->addBodyClasses( 'mw-article-diff' );
1009 $request = $context->getRequest();
1010 $diff = $request->getVal( 'diff' );
1011 $rcid = $request->getInt( 'rcid' );
1012 $purge = $request->getRawVal( 'action' ) === 'purge';
1013 $unhide = $request->getInt( 'unhide' ) === 1;
1014 $oldid = $this->getOldID();
1015
1016 $rev = $this->fetchRevisionRecord();
1017
1018 if ( !$rev ) {
1019 // T213621: $rev maybe null due to either lack of permission to view the
1020 // revision or actually not existing. So let's try loading it from the id
1021 $rev = $this->revisionStore->getRevisionById( $oldid );
1022 if ( $rev ) {
1023 // Revision exists but $user lacks permission to diff it.
1024 // Do nothing here.
1025 // The $rev will later be used to create standard diff elements however.
1026 } else {
1027 $outputPage->setPageTitleMsg( $context->msg( 'errorpagetitle' ) );
1028 $msg = $context->msg( 'difference-missing-revision' )
1029 ->params( $oldid )
1030 ->numParams( 1 )
1031 ->parseAsBlock();
1032 $outputPage->addHTML( $msg );
1033 return;
1034 }
1035 }
1036
1037 $services = MediaWikiServices::getInstance();
1038
1039 $contentHandler = $services
1040 ->getContentHandlerFactory()
1041 ->getContentHandler(
1042 $rev->getMainContentModel()
1043 );
1044 $de = $contentHandler->createDifferenceEngine(
1045 $context,
1046 $oldid,
1047 $diff,
1048 $rcid,
1049 $purge,
1050 $unhide
1051 );
1052
1053 $diffType = $request->getVal( 'diff-type' );
1054
1055 if ( $diffType === null ) {
1056 $diffType = $this->userOptionsLookup
1057 ->getOption( $context->getUser(), 'diff-type' );
1058 } else {
1059 $de->setExtraQueryParams( [ 'diff-type' => $diffType ] );
1060 }
1061
1062 $de->setSlotDiffOptions( [
1063 'diff-type' => $diffType,
1064 'expand-url' => $this->viewIsRenderAction,
1065 'inline-toggle' => true,
1066 ] );
1067 $de->showDiffPage( $this->isDiffOnlyView() );
1068
1069 // Run view updates for the newer revision being diffed (and shown
1070 // below the diff if not diffOnly).
1071 [ , $new ] = $de->mapDiffPrevNext( $oldid, $diff );
1072 // New can be false, convert it to 0 - this conveniently means the latest revision
1073 $this->mPage->doViewUpdates( $context->getAuthority(), (int)$new );
1074
1075 // Add link to help page; see T321569
1076 $context->getOutput()->addHelpLink( 'Help:Diff' );
1077 }
1078
1079 protected function isDiffOnlyView() {
1080 return $this->getContext()->getRequest()->getBool(
1081 'diffonly',
1082 $this->userOptionsLookup->getBoolOption( $this->getContext()->getUser(), 'diffonly' )
1083 );
1084 }
1085
1093 public function getRobotPolicy( $action, ?ParserOutput $pOutput = null ) {
1094 $context = $this->getContext();
1095 $mainConfig = $context->getConfig();
1096 $articleRobotPolicies = $mainConfig->get( MainConfigNames::ArticleRobotPolicies );
1097 $namespaceRobotPolicies = $mainConfig->get( MainConfigNames::NamespaceRobotPolicies );
1098 $defaultRobotPolicy = $mainConfig->get( MainConfigNames::DefaultRobotPolicy );
1099 $title = $this->getTitle();
1100 $ns = $title->getNamespace();
1101
1102 # Don't index user and user talk pages for blocked users (T13443)
1103 if ( $ns === NS_USER || $ns === NS_USER_TALK ) {
1104 $specificTarget = null;
1105 $vagueTarget = null;
1106 $titleText = $title->getText();
1107 if ( IPUtils::isValid( $titleText ) ) {
1108 $vagueTarget = $titleText;
1109 } else {
1110 $specificTarget = $title->getRootText();
1111 }
1112 if ( $this->blockStore->newFromTarget( $specificTarget, $vagueTarget ) instanceof DatabaseBlock ) {
1113 return [
1114 'index' => 'noindex',
1115 'follow' => 'nofollow'
1116 ];
1117 }
1118 }
1119
1120 if ( $this->mPage->getId() === 0 || $this->getOldID() ) {
1121 # Non-articles (special pages etc), and old revisions
1122 return [
1123 'index' => 'noindex',
1124 'follow' => 'nofollow'
1125 ];
1126 } elseif ( $context->getOutput()->isPrintable() ) {
1127 # Discourage indexing of printable versions, but encourage following
1128 return [
1129 'index' => 'noindex',
1130 'follow' => 'follow'
1131 ];
1132 } elseif ( $context->getRequest()->getInt( 'curid' ) ) {
1133 # For ?curid=x urls, disallow indexing
1134 return [
1135 'index' => 'noindex',
1136 'follow' => 'follow'
1137 ];
1138 }
1139
1140 # Otherwise, construct the policy based on the various config variables.
1141 $policy = self::formatRobotPolicy( $defaultRobotPolicy );
1142
1143 if ( isset( $namespaceRobotPolicies[$ns] ) ) {
1144 # Honour customised robot policies for this namespace
1145 $policy = array_merge(
1146 $policy,
1147 self::formatRobotPolicy( $namespaceRobotPolicies[$ns] )
1148 );
1149 }
1150 if ( $title->canUseNoindex() && $pOutput && $pOutput->getIndexPolicy() ) {
1151 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1152 # a final check that we have really got the parser output.
1153 $policy = array_merge(
1154 $policy,
1155 [ 'index' => $pOutput->getIndexPolicy() ]
1156 );
1157 }
1158
1159 if ( isset( $articleRobotPolicies[$title->getPrefixedText()] ) ) {
1160 # (T16900) site config can override user-defined __INDEX__ or __NOINDEX__
1161 $policy = array_merge(
1162 $policy,
1163 self::formatRobotPolicy( $articleRobotPolicies[$title->getPrefixedText()] )
1164 );
1165 }
1166
1167 return $policy;
1168 }
1169
1177 public static function formatRobotPolicy( $policy ) {
1178 if ( is_array( $policy ) ) {
1179 return $policy;
1180 } elseif ( !$policy ) {
1181 return [];
1182 }
1183
1184 $arr = [];
1185 foreach ( explode( ',', $policy ) as $var ) {
1186 $var = trim( $var );
1187 if ( $var === 'index' || $var === 'noindex' ) {
1188 $arr['index'] = $var;
1189 } elseif ( $var === 'follow' || $var === 'nofollow' ) {
1190 $arr['follow'] = $var;
1191 }
1192 }
1193
1194 return $arr;
1195 }
1196
1204 public function showRedirectedFromHeader() {
1205 $context = $this->getContext();
1206 $redirectSources = $context->getConfig()->get( MainConfigNames::RedirectSources );
1207 $outputPage = $context->getOutput();
1208 $request = $context->getRequest();
1209 $rdfrom = $request->getVal( 'rdfrom' );
1210
1211 // Construct a URL for the current page view, but with the target title
1212 $query = $request->getQueryValues();
1213 unset( $query['rdfrom'] );
1214 unset( $query['title'] );
1215 if ( $this->getTitle()->isRedirect() ) {
1216 // Prevent double redirects
1217 $query['redirect'] = 'no';
1218 }
1219 $redirectTargetUrl = $this->getTitle()->getLinkURL( $query );
1220
1221 if ( $this->mRedirectedFrom ) {
1222 // This is an internally redirected page view.
1223 // We'll need a backlink to the source page for navigation.
1224 if ( $this->getHookRunner()->onArticleViewRedirect( $this ) ) {
1225 $redir = $this->linkRenderer->makeKnownLink(
1226 $this->mRedirectedFrom,
1227 null,
1228 [],
1229 [ 'redirect' => 'no' ]
1230 );
1231
1232 $outputPage->addSubtitle( "<span class=\"mw-redirectedfrom\">" .
1233 $context->msg( 'redirectedfrom' )->rawParams( $redir )->parse()
1234 . "</span>" );
1235
1236 // Add the script to update the displayed URL and
1237 // set the fragment if one was specified in the redirect
1238 $outputPage->addJsConfigVars( [
1239 'wgInternalRedirectTargetUrl' => $redirectTargetUrl,
1240 ] );
1241 $outputPage->addModules( 'mediawiki.action.view.redirect' );
1242
1243 // Add a <link rel="canonical"> tag
1244 $outputPage->setCanonicalUrl( $this->getTitle()->getCanonicalURL() );
1245
1246 // Tell the output object that the user arrived at this article through a redirect
1247 $outputPage->setRedirectedFrom( $this->mRedirectedFrom );
1248
1249 return true;
1250 }
1251 } elseif ( $rdfrom ) {
1252 // This is an externally redirected view, from some other wiki.
1253 // If it was reported from a trusted site, supply a backlink.
1254 if ( $redirectSources && preg_match( $redirectSources, $rdfrom ) ) {
1255 $redir = $this->linkRenderer->makeExternalLink( $rdfrom, $rdfrom, $this->getTitle() );
1256 $outputPage->addSubtitle( "<span class=\"mw-redirectedfrom\">" .
1257 $context->msg( 'redirectedfrom' )->rawParams( $redir )->parse()
1258 . "</span>" );
1259
1260 // Add the script to update the displayed URL
1261 $outputPage->addJsConfigVars( [
1262 'wgInternalRedirectTargetUrl' => $redirectTargetUrl,
1263 ] );
1264 $outputPage->addModules( 'mediawiki.action.view.redirect' );
1265
1266 return true;
1267 }
1268 }
1269
1270 return false;
1271 }
1272
1277 public function showNamespaceHeader() {
1278 if ( $this->getTitle()->isTalkPage() && !$this->getContext()->msg( 'talkpageheader' )->isDisabled() ) {
1279 $this->getContext()->getOutput()->wrapWikiMsg(
1280 "<div class=\"mw-talkpageheader\">\n$1\n</div>",
1281 [ 'talkpageheader' ]
1282 );
1283 }
1284 }
1285
1289 public function showViewFooter() {
1290 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1291 if ( $this->getTitle()->getNamespace() === NS_USER_TALK
1292 && IPUtils::isValid( $this->getTitle()->getText() )
1293 ) {
1294 $this->getContext()->getOutput()->addWikiMsg( 'anontalkpagetext' );
1295 }
1296
1297 // Show a footer allowing the user to patrol the shown revision or page if possible
1298 $patrolFooterShown = $this->showPatrolFooter();
1299
1300 $this->getHookRunner()->onArticleViewFooter( $this, $patrolFooterShown );
1301 }
1302
1313 public function showPatrolFooter() {
1314 $context = $this->getContext();
1315 $mainConfig = $context->getConfig();
1316 $useNPPatrol = $mainConfig->get( MainConfigNames::UseNPPatrol );
1317 $useRCPatrol = $mainConfig->get( MainConfigNames::UseRCPatrol );
1318 $useFilePatrol = $mainConfig->get( MainConfigNames::UseFilePatrol );
1319 $fileMigrationStage = $mainConfig->get( MainConfigNames::FileSchemaMigrationStage );
1320 // Allow hooks to decide whether to not output this at all
1321 if ( !$this->getHookRunner()->onArticleShowPatrolFooter( $this ) ) {
1322 return false;
1323 }
1324
1325 $outputPage = $context->getOutput();
1326 $user = $context->getUser();
1327 $title = $this->getTitle();
1328 $rc = false;
1329
1330 if ( !$context->getAuthority()->probablyCan( 'patrol', $title )
1331 || !( $useRCPatrol || $useNPPatrol
1332 || ( $useFilePatrol && $title->inNamespace( NS_FILE ) ) )
1333 ) {
1334 // Patrolling is disabled or the user isn't allowed to
1335 return false;
1336 }
1337
1338 if ( $this->mRevisionRecord
1339 && !RecentChange::isInRCLifespan( $this->mRevisionRecord->getTimestamp(), 21600 )
1340 ) {
1341 // The current revision is already older than what could be in the RC table
1342 // 6h tolerance because the RC might not be cleaned out regularly
1343 return false;
1344 }
1345
1346 // Check for cached results
1347 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1348 $key = $cache->makeKey( 'unpatrollable-page', $title->getArticleID() );
1349 if ( $cache->get( $key ) ) {
1350 return false;
1351 }
1352
1353 $dbr = $this->dbProvider->getReplicaDatabase();
1354 $oldestRevisionRow = $dbr->newSelectQueryBuilder()
1355 ->select( [ 'rev_id', 'rev_timestamp' ] )
1356 ->from( 'revision' )
1357 ->where( [ 'rev_page' => $title->getArticleID() ] )
1358 ->orderBy( [ 'rev_timestamp', 'rev_id' ] )
1359 ->caller( __METHOD__ )->fetchRow();
1360 $oldestRevisionTimestamp = $oldestRevisionRow ? $oldestRevisionRow->rev_timestamp : false;
1361
1362 // New page patrol: Get the timestamp of the oldest revision which
1363 // the revision table holds for the given page. Then we look
1364 // whether it's within the RC lifespan and if it is, we try
1365 // to get the recentchanges row belonging to that entry.
1366 $recentPageCreation = false;
1367 if ( $oldestRevisionTimestamp
1368 && RecentChange::isInRCLifespan( $oldestRevisionTimestamp, 21600 )
1369 ) {
1370 // 6h tolerance because the RC might not be cleaned out regularly
1371 $recentPageCreation = true;
1372 $rc = RecentChange::newFromConds(
1373 [
1374 'rc_this_oldid' => intval( $oldestRevisionRow->rev_id ),
1375 // Avoid selecting a categorization entry
1376 'rc_type' => RC_NEW,
1377 ],
1378 __METHOD__
1379 );
1380 if ( $rc ) {
1381 // Use generic patrol message for new pages
1382 $markPatrolledMsg = $context->msg( 'markaspatrolledtext' );
1383 }
1384 }
1385
1386 // File patrol: Get the timestamp of the latest upload for this page,
1387 // check whether it is within the RC lifespan and if it is, we try
1388 // to get the recentchanges row belonging to that entry
1389 // (with rc_type = RC_LOG, rc_log_type = upload).
1390 $recentFileUpload = false;
1391 if ( ( !$rc || $rc->getAttribute( 'rc_patrolled' ) ) && $useFilePatrol
1392 && $title->getNamespace() === NS_FILE ) {
1393 // Retrieve timestamp from the current file (latest upload)
1394 if ( $fileMigrationStage & SCHEMA_COMPAT_READ_OLD ) {
1395 $newestUploadTimestamp = $dbr->newSelectQueryBuilder()
1396 ->select( 'img_timestamp' )
1397 ->from( 'image' )
1398 ->where( [ 'img_name' => $title->getDBkey() ] )
1399 ->caller( __METHOD__ )->fetchField();
1400 } else {
1401 $newestUploadTimestamp = $dbr->newSelectQueryBuilder()
1402 ->select( 'fr_timestamp' )
1403 ->from( 'file' )
1404 ->join( 'filerevision', null, 'file_latest = fr_id' )
1405 ->where( [ 'file_name' => $title->getDBkey() ] )
1406 ->caller( __METHOD__ )->fetchField();
1407 }
1408
1409 if ( $newestUploadTimestamp
1410 && RecentChange::isInRCLifespan( $newestUploadTimestamp, 21600 )
1411 ) {
1412 // 6h tolerance because the RC might not be cleaned out regularly
1413 $recentFileUpload = true;
1414 $rc = RecentChange::newFromConds(
1415 [
1416 'rc_type' => RC_LOG,
1417 'rc_log_type' => 'upload',
1418 'rc_timestamp' => $newestUploadTimestamp,
1419 'rc_namespace' => NS_FILE,
1420 'rc_cur_id' => $title->getArticleID()
1421 ],
1422 __METHOD__
1423 );
1424 if ( $rc ) {
1425 // Use patrol message specific to files
1426 $markPatrolledMsg = $context->msg( 'markaspatrolledtext-file' );
1427 }
1428 }
1429 }
1430
1431 if ( !$recentPageCreation && !$recentFileUpload ) {
1432 // Page creation and latest upload (for files) is too old to be in RC
1433
1434 // We definitely can't patrol so cache the information
1435 // When a new file version is uploaded, the cache is cleared
1436 $cache->set( $key, '1' );
1437
1438 return false;
1439 }
1440
1441 if ( !$rc ) {
1442 // Don't cache: This can be hit if the page gets accessed very fast after
1443 // its creation / latest upload or in case we have high replica DB lag. In case
1444 // the revision is too old, we will already return above.
1445 return false;
1446 }
1447
1448 if ( $rc->getAttribute( 'rc_patrolled' ) ) {
1449 // Patrolled RC entry around
1450
1451 // Cache the information we gathered above in case we can't patrol
1452 // Don't cache in case we can patrol as this could change
1453 $cache->set( $key, '1' );
1454
1455 return false;
1456 }
1457
1458 if ( $rc->getPerformerIdentity()->equals( $user ) ) {
1459 // Don't show a patrol link for own creations/uploads. If the user could
1460 // patrol them, they already would be patrolled
1461 return false;
1462 }
1463
1464 $outputPage->getMetadata()->setPreventClickjacking( true );
1465 $outputPage->addModules( 'mediawiki.misc-authed-curate' );
1466
1467 $link = $this->linkRenderer->makeKnownLink(
1468 $title,
1469 new HtmlArmor( '<button class="cdx-button cdx-button--action-progressive">'
1470 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $markPatrolledMsg is always set
1471 . $markPatrolledMsg->escaped() . '</button>' ),
1472 [],
1473 [
1474 'action' => 'markpatrolled',
1475 'rcid' => $rc->getAttribute( 'rc_id' ),
1476 ]
1477 );
1478
1479 $outputPage->addModuleStyles( 'mediawiki.action.styles' );
1480 $outputPage->addHTML( "<div class='patrollink' data-mw='interface'>$link</div>" );
1481
1482 return true;
1483 }
1484
1491 public static function purgePatrolFooterCache( $articleID ) {
1492 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1493 $cache->delete( $cache->makeKey( 'unpatrollable-page', $articleID ) );
1494 }
1495
1500 public function showMissingArticle() {
1501 $context = $this->getContext();
1502 $send404Code = $context->getConfig()->get( MainConfigNames::Send404Code );
1503
1504 $outputPage = $context->getOutput();
1505 // Whether the page is a root user page of an existing user (but not a subpage)
1506 $validUserPage = false;
1507
1508 $title = $this->getTitle();
1509
1510 $services = MediaWikiServices::getInstance();
1511
1512 $contextUser = $context->getUser();
1513
1514 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1515 if ( $title->getNamespace() === NS_USER
1516 || $title->getNamespace() === NS_USER_TALK
1517 ) {
1518 $rootPart = $title->getRootText();
1519 $userFactory = $services->getUserFactory();
1520 $user = $userFactory->newFromNameOrIp( $rootPart );
1521
1522 $block = $this->blockStore->newFromTarget( $user, $user );
1523
1524 if ( $user && $user->isRegistered() && $user->isHidden() &&
1525 !$context->getAuthority()->isAllowed( 'hideuser' )
1526 ) {
1527 // T120883 if the user is hidden and the viewer cannot see hidden
1528 // users, pretend like it does not exist at all.
1529 $user = false;
1530 }
1531
1532 if ( !( $user && $user->isRegistered() ) && !$this->userNameUtils->isIP( $rootPart ) ) {
1533 $this->addMessageBoxStyles( $outputPage );
1534 // User does not exist
1535 $outputPage->addHTML( Html::warningBox(
1536 $context->msg( 'userpage-userdoesnotexist-view', wfEscapeWikiText( $rootPart ) )->parse(),
1537 'mw-userpage-userdoesnotexist'
1538 ) );
1539
1540 // Show renameuser log extract
1541 LogEventsList::showLogExtract(
1542 $outputPage,
1543 'renameuser',
1544 Title::makeTitleSafe( NS_USER, $rootPart ),
1545 '',
1546 [
1547 'lim' => 10,
1548 'showIfEmpty' => false,
1549 'msgKey' => [ 'renameuser-renamed-notice', $title->getBaseText() ]
1550 ]
1551 );
1552 } elseif (
1553 $user && $block !== null &&
1554 $block->getType() != DatabaseBlock::TYPE_AUTO &&
1555 (
1556 $block->isSitewide() ||
1557 $services->getPermissionManager()->isBlockedFrom( $user, $title, true )
1558 )
1559 ) {
1560 // Show log extract if the user is sitewide blocked or is partially
1561 // blocked and not allowed to edit their user page or user talk page
1562 LogEventsList::showLogExtract(
1563 $outputPage,
1564 'block',
1565 $services->getNamespaceInfo()->getCanonicalName( NS_USER ) . ':' .
1566 $block->getTargetName(),
1567 '',
1568 [
1569 'lim' => 1,
1570 'showIfEmpty' => false,
1571 'msgKey' => [
1572 'blocked-notice-logextract',
1573 $user->getName() # Support GENDER in notice
1574 ]
1575 ]
1576 );
1577 $validUserPage = !$title->isSubpage();
1578 } else {
1579 $validUserPage = !$title->isSubpage();
1580 }
1581 }
1582
1583 $this->getHookRunner()->onShowMissingArticle( $this );
1584
1585 # Show delete and move logs if there were any such events.
1586 # The logging query can DOS the site when bots/crawlers cause 404 floods,
1587 # so be careful showing this. 404 pages must be cheap as they are hard to cache.
1588 $dbCache = MediaWikiServices::getInstance()->getMainObjectStash();
1589 $key = $dbCache->makeKey( 'page-recent-delete', md5( $title->getPrefixedText() ) );
1590 $isRegistered = $contextUser->isRegistered();
1591 $sessionExists = $context->getRequest()->getSession()->isPersistent();
1592
1593 if ( $isRegistered || $dbCache->get( $key ) || $sessionExists ) {
1594 $logTypes = [ 'delete', 'move', 'protect', 'merge' ];
1595
1596 $dbr = $this->dbProvider->getReplicaDatabase();
1597
1598 $conds = [ $dbr->expr( 'log_action', '!=', 'revision' ) ];
1599 // Give extensions a chance to hide their (unrelated) log entries
1600 $this->getHookRunner()->onArticle__MissingArticleConditions( $conds, $logTypes );
1601 LogEventsList::showLogExtract(
1602 $outputPage,
1603 $logTypes,
1604 $title,
1605 '',
1606 [
1607 'lim' => 10,
1608 'conds' => $conds,
1609 'showIfEmpty' => false,
1610 'msgKey' => [ $isRegistered || $sessionExists
1611 ? 'moveddeleted-notice'
1612 : 'moveddeleted-notice-recent'
1613 ]
1614 ]
1615 );
1616 }
1617
1618 if ( !$this->mPage->hasViewableContent() && $send404Code && !$validUserPage ) {
1619 // If there's no backing content, send a 404 Not Found
1620 // for better machine handling of broken links.
1621 $context->getRequest()->response()->statusHeader( 404 );
1622 }
1623
1624 // Also apply the robot policy for nonexisting pages (even if a 404 was used)
1625 $policy = $this->getRobotPolicy( 'view' );
1626 $outputPage->getMetadata()->setIndexPolicy( $policy['index'] );
1627 $outputPage->setFollowPolicy( $policy['follow'] );
1628
1629 $hookResult = $this->getHookRunner()->onBeforeDisplayNoArticleText( $this );
1630
1631 if ( !$hookResult ) {
1632 return;
1633 }
1634
1635 # Show error message
1636 $oldid = $this->getOldID();
1637 if ( !$oldid && $title->getNamespace() === NS_MEDIAWIKI && $title->hasSourceText() ) {
1638 $text = $this->getTitle()->getDefaultMessageText() ?? '';
1639 $outputPage->addWikiTextAsContent( $text );
1640 } else {
1641 if ( $oldid ) {
1642 $text = $this->getMissingRevisionMsg( $oldid )->plain();
1643 } elseif ( $context->getAuthority()->probablyCan( 'edit', $title ) ) {
1644 $message = $isRegistered ? 'noarticletext' : 'noarticletextanon';
1645 $text = $context->msg( $message )->plain();
1646 } else {
1647 $text = $context->msg( 'noarticletext-nopermission' )->plain();
1648 }
1649
1650 $dir = $context->getLanguage()->getDir();
1651 $lang = $context->getLanguage()->getHtmlCode();
1652 $outputPage->addWikiTextAsInterface( Xml::openElement( 'div', [
1653 'class' => "noarticletext mw-content-$dir",
1654 'dir' => $dir,
1655 'lang' => $lang,
1656 ] ) . "\n$text\n</div>" );
1657 }
1658 }
1659
1664 private function showViewError( string $errortext ) {
1665 $outputPage = $this->getContext()->getOutput();
1666 $outputPage->setPageTitleMsg( $this->getContext()->msg( 'errorpagetitle' ) );
1667 $outputPage->disableClientCache();
1668 $outputPage->setRobotPolicy( 'noindex,nofollow' );
1669 $outputPage->clearHTML();
1670 $this->addMessageBoxStyles( $outputPage );
1671 $outputPage->addHTML( Html::errorBox( $outputPage->parseAsContent( $errortext ) ) );
1672 }
1673
1680 public function showDeletedRevisionHeader() {
1681 if ( !$this->mRevisionRecord->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
1682 // Not deleted
1683 return true;
1684 }
1685 $outputPage = $this->getContext()->getOutput();
1686 // Used in wikilinks, should not contain whitespaces
1687 $titleText = $this->getTitle()->getPrefixedDBkey();
1688 $this->addMessageBoxStyles( $outputPage );
1689 // If the user is not allowed to see it...
1690 if ( !$this->mRevisionRecord->userCan(
1691 RevisionRecord::DELETED_TEXT,
1692 $this->getContext()->getAuthority()
1693 ) ) {
1694 $outputPage->addHTML(
1695 Html::warningBox(
1696 $outputPage->msg( 'rev-deleted-text-permission', $titleText )->parse(),
1697 'plainlinks'
1698 )
1699 );
1700
1701 return false;
1702 // If the user needs to confirm that they want to see it...
1703 } elseif ( $this->getContext()->getRequest()->getInt( 'unhide' ) !== 1 ) {
1704 # Give explanation and add a link to view the revision...
1705 $oldid = intval( $this->getOldID() );
1706 $link = $this->getTitle()->getFullURL( "oldid={$oldid}&unhide=1" );
1707 $msg = $this->mRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ?
1708 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1709 $outputPage->addHTML(
1710 Html::warningBox(
1711 $outputPage->msg( $msg, $link )->parse(),
1712 'plainlinks'
1713 )
1714 );
1715
1716 return false;
1717 // We are allowed to see...
1718 } else {
1719 $msg = $this->mRevisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED )
1720 ? [ 'rev-suppressed-text-view', $titleText ]
1721 : [ 'rev-deleted-text-view', $titleText ];
1722 $outputPage->addHTML(
1723 Html::warningBox(
1724 $outputPage->msg( $msg[0], $msg[1] )->parse(),
1725 'plainlinks'
1726 )
1727 );
1728
1729 return true;
1730 }
1731 }
1732
1733 private function addMessageBoxStyles( OutputPage $outputPage ) {
1734 $outputPage->addModuleStyles( [
1735 'mediawiki.codex.messagebox.styles',
1736 ] );
1737 }
1738
1747 public function setOldSubtitle( $oldid = 0 ) {
1748 if ( !$this->getHookRunner()->onDisplayOldSubtitle( $this, $oldid ) ) {
1749 return;
1750 }
1751
1752 $context = $this->getContext();
1753 $unhide = $context->getRequest()->getInt( 'unhide' ) === 1;
1754
1755 # Cascade unhide param in links for easy deletion browsing
1756 $extraParams = [];
1757 if ( $unhide ) {
1758 $extraParams['unhide'] = 1;
1759 }
1760
1761 if ( $this->mRevisionRecord && $this->mRevisionRecord->getId() === $oldid ) {
1762 $revisionRecord = $this->mRevisionRecord;
1763 } else {
1764 $revisionRecord = $this->revisionStore->getRevisionById( $oldid );
1765 }
1766 if ( !$revisionRecord ) {
1767 throw new LogicException( 'There should be a revision record at this point.' );
1768 }
1769
1770 $timestamp = $revisionRecord->getTimestamp();
1771
1772 $current = ( $oldid == $this->mPage->getLatest() );
1773 $language = $context->getLanguage();
1774 $user = $context->getUser();
1775
1776 $td = $language->userTimeAndDate( $timestamp, $user );
1777 $tddate = $language->userDate( $timestamp, $user );
1778 $tdtime = $language->userTime( $timestamp, $user );
1779
1780 # Show user links if allowed to see them. If hidden, then show them only if requested...
1781 $userlinks = Linker::revUserTools( $revisionRecord, !$unhide );
1782
1783 $infomsg = $current && !$context->msg( 'revision-info-current' )->isDisabled()
1784 ? 'revision-info-current'
1785 : 'revision-info';
1786
1787 $outputPage = $context->getOutput();
1788 $outputPage->addModuleStyles( [
1789 'mediawiki.action.styles',
1790 'mediawiki.interface.helpers.styles'
1791 ] );
1792
1793 $revisionUser = $revisionRecord->getUser();
1794 $revisionInfo = "<div id=\"mw-{$infomsg}\">" .
1795 $context->msg( $infomsg, $td )
1796 ->rawParams( $userlinks )
1797 ->params(
1798 $revisionRecord->getId(),
1799 $tddate,
1800 $tdtime,
1801 $revisionUser ? $revisionUser->getName() : ''
1802 )
1803 ->rawParams( $this->commentFormatter->formatRevision(
1804 $revisionRecord,
1805 $user,
1806 true,
1807 !$unhide
1808 ) )
1809 ->parse() .
1810 "</div>";
1811
1812 $lnk = $current
1813 ? $context->msg( 'currentrevisionlink' )->escaped()
1814 : $this->linkRenderer->makeKnownLink(
1815 $this->getTitle(),
1816 $context->msg( 'currentrevisionlink' )->text(),
1817 [],
1818 $extraParams
1819 );
1820 $curdiff = $current
1821 ? $context->msg( 'diff' )->escaped()
1822 : $this->linkRenderer->makeKnownLink(
1823 $this->getTitle(),
1824 $context->msg( 'diff' )->text(),
1825 [],
1826 [
1827 'diff' => 'cur',
1828 'oldid' => $oldid
1829 ] + $extraParams
1830 );
1831 $prevExist = (bool)$this->revisionStore->getPreviousRevision( $revisionRecord );
1832 $prevlink = $prevExist
1833 ? $this->linkRenderer->makeKnownLink(
1834 $this->getTitle(),
1835 $context->msg( 'previousrevision' )->text(),
1836 [],
1837 [
1838 'direction' => 'prev',
1839 'oldid' => $oldid
1840 ] + $extraParams
1841 )
1842 : $context->msg( 'previousrevision' )->escaped();
1843 $prevdiff = $prevExist
1844 ? $this->linkRenderer->makeKnownLink(
1845 $this->getTitle(),
1846 $context->msg( 'diff' )->text(),
1847 [],
1848 [
1849 'diff' => 'prev',
1850 'oldid' => $oldid
1851 ] + $extraParams
1852 )
1853 : $context->msg( 'diff' )->escaped();
1854 $nextlink = $current
1855 ? $context->msg( 'nextrevision' )->escaped()
1856 : $this->linkRenderer->makeKnownLink(
1857 $this->getTitle(),
1858 $context->msg( 'nextrevision' )->text(),
1859 [],
1860 [
1861 'direction' => 'next',
1862 'oldid' => $oldid
1863 ] + $extraParams
1864 );
1865 $nextdiff = $current
1866 ? $context->msg( 'diff' )->escaped()
1867 : $this->linkRenderer->makeKnownLink(
1868 $this->getTitle(),
1869 $context->msg( 'diff' )->text(),
1870 [],
1871 [
1872 'diff' => 'next',
1873 'oldid' => $oldid
1874 ] + $extraParams
1875 );
1876
1877 $cdel = Linker::getRevDeleteLink(
1878 $context->getAuthority(),
1879 $revisionRecord,
1880 $this->getTitle()
1881 );
1882 if ( $cdel !== '' ) {
1883 $cdel .= ' ';
1884 }
1885
1886 // the outer div is need for styling the revision info and nav in MobileFrontend
1887 $this->addMessageBoxStyles( $outputPage );
1888 $outputPage->addSubtitle(
1889 Html::warningBox(
1890 $revisionInfo .
1891 "<div id=\"mw-revision-nav\">" . $cdel .
1892 $context->msg( 'revision-nav' )->rawParams(
1893 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff
1894 )->escaped() . "</div>",
1895 'mw-revision'
1896 )
1897 );
1898 }
1899
1913 public static function getRedirectHeaderHtml( Language $lang, Title $target, $forceKnown = false ) {
1914 wfDeprecated( __METHOD__, '1.41' );
1915 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1916 return $linkRenderer->makeRedirectHeader( $lang, $target, $forceKnown );
1917 }
1918
1927 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1928 $out = $this->getContext()->getOutput();
1929 $msg = $out->msg( 'namespace-' . $this->getTitle()->getNamespace() . '-helppage' );
1930
1931 if ( !$msg->isDisabled() ) {
1932 $title = Title::newFromText( $msg->plain() );
1933 if ( $title instanceof Title ) {
1934 $out->addHelpLink( $title->getLocalURL(), true );
1935 }
1936 } else {
1937 $out->addHelpLink( $to, $overrideBaseUrl );
1938 }
1939 }
1940
1944 public function render() {
1945 $this->getContext()->getRequest()->response()->header( 'X-Robots-Tag: noindex' );
1946 $this->getContext()->getOutput()->setArticleBodyOnly( true );
1947 // We later set 'enableSectionEditLinks=false' based on this; also used by ImagePage
1948 $this->viewIsRenderAction = true;
1949 $this->view();
1950 }
1951
1955 public function protect() {
1956 $form = new ProtectionForm( $this );
1957 $form->execute();
1958 }
1959
1963 public function unprotect() {
1964 $this->protect();
1965 }
1966
1967 /* Caching functions */
1968
1976 protected function tryFileCache() {
1977 static $called = false;
1978
1979 if ( $called ) {
1980 wfDebug( "Article::tryFileCache(): called twice!?" );
1981 return false;
1982 }
1983
1984 $called = true;
1985 if ( $this->isFileCacheable() ) {
1986 $cache = new HTMLFileCache( $this->getTitle(), 'view' );
1987 if ( $cache->isCacheGood( $this->mPage->getTouched() ) ) {
1988 wfDebug( "Article::tryFileCache(): about to load file" );
1989 $cache->loadFromFileCache( $this->getContext() );
1990 return true;
1991 } else {
1992 wfDebug( "Article::tryFileCache(): starting buffer" );
1993 ob_start( [ &$cache, 'saveToFileCache' ] );
1994 }
1995 } else {
1996 wfDebug( "Article::tryFileCache(): not cacheable" );
1997 }
1998
1999 return false;
2000 }
2001
2007 public function isFileCacheable( $mode = HTMLFileCache::MODE_NORMAL ) {
2008 $cacheable = false;
2009
2010 if ( HTMLFileCache::useFileCache( $this->getContext(), $mode ) ) {
2011 $cacheable = $this->mPage->getId()
2012 && !$this->mRedirectedFrom && !$this->getTitle()->isRedirect();
2013 // Extension may have reason to disable file caching on some pages.
2014 if ( $cacheable ) {
2015 $cacheable = $this->getHookRunner()->onIsFileCacheable( $this ) ?? false;
2016 }
2017 }
2018
2019 return $cacheable;
2020 }
2021
2033 public function getParserOutput( $oldid = null, ?UserIdentity $user = null ) {
2034 if ( $user === null ) {
2035 $parserOptions = $this->getParserOptions();
2036 } else {
2037 $parserOptions = $this->mPage->makeParserOptions( $user );
2038 $parserOptions->setRenderReason( 'page-view' );
2039 }
2040
2041 return $this->mPage->getParserOutput( $parserOptions, $oldid );
2042 }
2043
2048 public function getParserOptions() {
2049 $parserOptions = $this->mPage->makeParserOptions( $this->getContext() );
2050 $parserOptions->setRenderReason( 'page-view' );
2051 return $parserOptions;
2052 }
2053
2060 public function setContext( $context ) {
2061 $this->mContext = $context;
2062 }
2063
2070 public function getContext(): IContextSource {
2071 if ( $this->mContext instanceof IContextSource ) {
2072 return $this->mContext;
2073 } else {
2074 wfDebug( __METHOD__ . " called and \$mContext is null. " .
2075 "Return RequestContext::getMain()" );
2076 return RequestContext::getMain();
2077 }
2078 }
2079
2085 public function getActionOverrides() {
2086 return $this->mPage->getActionOverrides();
2087 }
2088
2089 private function getMissingRevisionMsg( int $oldid ): Message {
2090 // T251066: Try loading the revision from the archive table.
2091 // Show link to view it if it exists and the user has permission to view it.
2092 // (Ignore the given title, if any; look it up from the revision instead.)
2093 $context = $this->getContext();
2094 $revRecord = $this->archivedRevisionLookup->getArchivedRevisionRecord( null, $oldid );
2095 if (
2096 $revRecord &&
2097 $revRecord->userCan(
2098 RevisionRecord::DELETED_TEXT,
2099 $context->getAuthority()
2100 ) &&
2101 $context->getAuthority()->isAllowedAny( 'deletedtext', 'undelete' )
2102 ) {
2103 return $context->msg(
2104 'missing-revision-permission',
2105 $oldid,
2106 $revRecord->getTimestamp(),
2107 Title::newFromPageIdentity( $revRecord->getPage() )->getPrefixedDBkey()
2108 );
2109 }
2110 return $context->msg( 'missing-revision', $oldid );
2111 }
2112}
const NS_USER
Definition Defines.php:67
const NS_FILE
Definition Defines.php:71
const RC_NEW
Definition Defines.php:118
const NS_MEDIAWIKI
Definition Defines.php:73
const SCHEMA_COMPAT_READ_OLD
Definition Defines.php:283
const RC_LOG
Definition Defines.php:119
const NS_MEDIA
Definition Defines.php:53
const NS_USER_TALK
Definition Defines.php:68
const NS_CATEGORY
Definition Defines.php:79
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
Legacy class representing an editable page and handling UI for some page actions.
Definition Article.php:70
static newFromWikiPage(WikiPage $page, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition Article.php:218
getContext()
Gets the context this Article is executed in.
Definition Article.php:2070
getOldIDFromRequest()
Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect.
Definition Article.php:291
getRedirectedFrom()
Get the page this view was redirected from.
Definition Article.php:229
Title null $mRedirectedFrom
Title from which we were redirected here, if any.
Definition Article.php:91
bool $viewIsRenderAction
Whether render() was called.
Definition Article.php:114
view()
This is the default action of the index.php entry point: just view the page of the given title.
Definition Article.php:450
showProtectionIndicator()
Show a lock icon above the article body if the page is protected.
Definition Article.php:597
__construct(Title $title, $oldId=null)
Definition Article.php:141
static purgePatrolFooterCache( $articleID)
Purge the cache used to check if it is worth showing the patrol footer For example,...
Definition Article.php:1491
ParserOutput null false $mParserOutput
The ParserOutput generated for viewing the page, initialized by view().
Definition Article.php:107
getOldID()
Definition Article.php:278
LinkRenderer $linkRenderer
Definition Article.php:116
getTitle()
Get the title object of the article.
Definition Article.php:246
getActionOverrides()
Call to WikiPage function for backwards compatibility.
Definition Article.php:2085
isDiffOnlyView()
Definition Article.php:1079
adjustDisplayTitle(ParserOutput $pOutput)
Adjust title for pages with displaytitle, -{T|}- or language conversion.
Definition Article.php:990
DatabaseBlockStore $blockStore
Definition Article.php:125
showDeletedRevisionHeader()
If the revision requested for view is deleted, check permissions.
Definition Article.php:1680
getParserOptions()
Get parser options suitable for rendering the primary article wikitext.
Definition Article.php:2048
IContextSource null $mContext
The context this Article is executed in.
Definition Article.php:79
static getRedirectHeaderHtml(Language $lang, Title $target, $forceKnown=false)
Return the HTML for the top of a redirect page.
Definition Article.php:1913
protect()
action=protect handler
Definition Article.php:1955
string false $mRedirectUrl
URL to redirect to or false if none.
Definition Article.php:94
isCurrent()
Returns true if the currently-referenced revision is the current edit to this page (and it exists).
Definition Article.php:417
showMissingArticle()
Show the error text for a missing article.
Definition Article.php:1500
IConnectionProvider $dbProvider
Definition Article.php:124
unprotect()
action=unprotect handler (alias)
Definition Article.php:1963
newPage(Title $title)
Definition Article.php:163
getPage()
Get the WikiPage object of this instance.
Definition Article.php:256
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition Article.php:1927
static newFromID( $id)
Constructor from a page id.
Definition Article.php:172
int null $mOldId
The oldid of the article that was requested to be shown, 0 for the current revision.
Definition Article.php:88
static formatRobotPolicy( $policy)
Converts a String robot policy into an associative array, to allow merging of several policies using ...
Definition Article.php:1177
fetchRevisionRecord()
Fetches the revision to work on.
Definition Article.php:359
getRobotPolicy( $action, ?ParserOutput $pOutput=null)
Get the robot policy to be used for the current view.
Definition Article.php:1093
showPatrolFooter()
If patrol is possible, output a patrol UI box.
Definition Article.php:1313
setOldSubtitle( $oldid=0)
Generate the navigation links when browsing through an article revisions It shows the information as:...
Definition Article.php:1747
showViewFooter()
Show the footer section of an ordinary page view.
Definition Article.php:1289
WikiPage $mPage
The WikiPage object of this instance.
Definition Article.php:82
setRedirectedFrom(Title $from)
Tell the page view functions that this view was redirected from another page on the wiki.
Definition Article.php:237
isFileCacheable( $mode=HTMLFileCache::MODE_NORMAL)
Check if the page can be cached.
Definition Article.php:2007
tryFileCache()
checkLastModified returns true if it has taken care of all output to the client that is necessary for...
Definition Article.php:1976
getRevIdFetched()
Use this to fetch the rev ID used on page views.
Definition Article.php:436
showNamespaceHeader()
Show a header specific to the namespace currently being viewed, like [[MediaWiki:Talkpagetext]].
Definition Article.php:1277
static newFromTitle( $title, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition Article.php:184
showDiffPage()
Show a diff page according to current request variables.
Definition Article.php:1005
RestrictionStore $restrictionStore
Definition Article.php:127
render()
Handle action=render.
Definition Article.php:1944
showRedirectedFromHeader()
If this request is a redirect view, send "redirected from" subtitle to the output.
Definition Article.php:1204
getParserOutput( $oldid=null, ?UserIdentity $user=null)
Lightweight method to get the parser output for a page, checking the parser cache and so on.
Definition Article.php:2033
setContext( $context)
Sets the context this Article is executed in.
Definition Article.php:2060
Special handling for category description pages.
Page view caching in the file system.
Marks HTML that shouldn't be escaped.
Definition HtmlArmor.php:30
Rendering of file description pages.
Definition ImagePage.php:39
Handle enqueueing of background jobs.
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
This is the main service interface for converting single-line comments from various DB comment fields...
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Group all the pieces relevant to the context of a request into one instance.
The HTML user interface for page editing.
Definition EditPage.php:150
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
This class is a collection of static functions that serve two purposes:
Definition Html.php:56
Base class for language-specific code.
Definition Language.php:82
Class that generates HTML for internal links.
makeRedirectHeader(Language $lang, Title $target, bool $forceKnown=false)
Return the HTML for the top of a redirect page.
Some internal bits split of from Skin.php.
Definition Linker.php:62
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:155
This is one of the Core classes and should be read at least once by any new developers.
parseAsContent( $text, $linestart=true)
Parse wikitext in the page content language and return the HTML.
disableClientCache()
Force the page to send nocache headers.
addJsConfigVars( $keys, $value=null)
Add one or more variables to be set in mw.config in JavaScript.
wrapWikiMsg( $wrap,... $msgSpecs)
This function takes a number of message/argument specifications, wraps them in some overall structure...
disable()
Disable output completely, i.e.
setRedirectedFrom(PageReference $t)
Set $mRedirectedFrom, the page which redirected us to the current page.
setRevisionTimestamp( $timestamp)
Set the timestamp of the revision which will be displayed.
adaptCdnTTL( $mtime, $minTTL=0, $maxTTL=0)
Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
addBodyClasses( $classes)
Add a class to the <body> element.
lowerCdnMaxage( $maxage)
Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is lower t...
setContentLangForJS(Bcp47Code $lang)
setIndicators(array $indicators)
Add an array of indicators, with their identifiers as array keys and HTML contents as values.
setLastModified( $timestamp)
Override the last modified timestamp.
setRevisionIsCurrent(bool $isCurrent)
Set whether the revision displayed (as set in ::setRevisionId()) is the latest revision of the page.
addWikiTextAsContent( $text, $linestart=true, ?PageReference $title=null)
Convert wikitext in the page content language to HTML and add it to the buffer.
setFollowPolicy( $policy)
Set the follow policy for the page, but leave the index policy un- touched.
clearHTML()
Clear the body HTML.
setPageTitle( $name)
"Page title" means the contents of <h1>.
setPageTitleMsg(Message $msg)
"Page title" means the contents of <h1>.
addModules( $modules)
Load one or more ResourceLoader modules on this page.
redirect( $url, $responsecode='302')
Redirect to $url rather than displaying the normal page.
setHTMLTitle( $name)
"HTML title" means the contents of "<title>".
prependHTML( $text)
Prepend $text to the body HTML.
setRobotPolicy( $policy)
Set the robot policy for the page: http://www.robotstxt.org/meta.html
setCanonicalUrl( $url)
Set the URL to be used for the <link rel=canonical>>.
addHTML( $text)
Append $text to the body HTML.
addWikiTextAsInterface( $text, $linestart=true, ?PageReference $title=null)
Convert wikitext in the user interface language to HTML and add it to the buffer.
setRevisionId( $revid)
Set the revision ID which will be seen by the wiki text parser for things such as embedded {{REVISION...
addSubtitle( $str)
Add $str to the subtitle.
addModuleStyles( $modules)
Load the styles of one or more style-only ResourceLoader modules on this page.
addParserOutput(ParserOutput $parserOutput, $poOptions=[])
Add everything from a ParserOutput object.
getMetadata()
Return a ParserOutput that can be used to set metadata properties for the current page.
isPrintable()
Return whether the page is "printable".
setArticleFlag( $newVal)
Set whether the displayed content is related to the source of the corresponding article on the wiki S...
Service for getting rendered output of a given page.
Handles the page protection UI and backend.
Service for creating WikiPage objects.
Set options of the Parser.
setIsPrintable( $x)
Parsing the printable version of the page?
setRenderReason(string $renderReason)
Sets reason for rendering the content.
ParserOutput is a rendering of a Content object or a message.
getLanguage()
Get the primary language code of the output.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:148
A StatusValue for permission errors.
Exception raised when the text of a revision is permanently missing or corrupt.
Page revision base class.
getContent( $role, $audience=self::FOR_PUBLIC, ?Authority $performer=null)
Returns the Content of the given slot of this revision.
isCurrent()
Checks whether the revision record is a stored current revision.
getTimestamp()
MCR migration note: this replaced Revision::getTimestamp.
getMainContentModel()
Returns the content model of the main slot of this revision.
getId( $wikiId=self::LOCAL)
Get revision ID.
Service for looking up page revisions.
Value object representing a content slot associated with a page revision.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
getWikiText( $shortContext=false, $longContext=false, $lang=null)
Get the error list as a wikitext formatted list.
Definition Status.php:218
Represents a title within MediaWiki.
Definition Title.php:78
Provides access to user options.
UserNameUtils service.
Module of static functions for generating XML.
Definition Xml.php:37
static newSpec(int $revisionId, PageRecord $page, array $params=[])
Show an error when a user tries to do something they do not have the necessary permissions for.
hasMessage(string $message)
Returns true if the specified message is present as a warning or error.
isOK()
Returns whether the operation completed.
fatal( $message,... $parameters)
Add an error and set OK to false, indicating that the operation as a whole was fatal.
Base representation for an editable wiki page.
Definition WikiPage.php:84
getTitle()
Get the title object of the article.
Definition WikiPage.php:252
Interface for objects which can provide a MediaWiki context on request.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:37
Interface for objects representing user identity.
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
Definition Page.php:30
Provide primary and replica IDatabase connections.