*/
private $mPageTitle = '';
/**
* @var string The displayed title of the page. Different from page title
* if overridden by display title magic word or hooks. Can contain safe
* HTML. Different from page title which may contain messages such as
* "Editing X" which is displayed in h1. This can be used for other places
* where the page name is referred on the page.
*/
private $displayTitle;
/** @var bool See OutputPage::couldBePublicCached. */
private $cacheIsFinal = false;
/**
* @var string Contains all of the "" content. Should be private we
* got set/get accessors and the append() method.
*/
public $mBodytext = '';
/** @var string Stores contents of "" tag */
private $mHTMLtitle = '';
/**
* @var bool Is the displayed content related to the source of the
* corresponding wiki article.
*/
private $mIsArticle = false;
/** @var bool Stores "article flag" toggle. */
private $mIsArticleRelated = true;
/** @var bool Is the content subject to copyright */
private $mHasCopyright = false;
/**
* @var bool We have to set isPrintable(). Some pages should
* never be printed (ex: redirections).
*/
private $mPrintable = false;
/**
* @var ?TOCData Table of Contents information from ParserOutput, or
* null if no TOCData was ever set.
*/
private $tocData;
/**
* @var array Contains the page subtitle. Special pages usually have some
* links here. Don't confuse with site subtitle added by skins.
*/
private $mSubtitle = [];
/** @var string */
public $mRedirect = '';
/** @var int */
protected $mStatusCode;
/**
* @var string Used for sending cache control.
* The whole caching system should probably be moved into its own class.
*/
protected $mLastModified = '';
/**
* @var string[][]
* @deprecated since 1.38; will be made private (T301020)
*/
private $mCategoryLinks = [];
/**
* @var string[][]
* @deprecated since 1.38, will be made private (T301020)
*/
private $mCategories = [
'hidden' => [],
'normal' => [],
];
/**
* Internal storage for categories on the OutputPage, stored as an array:
* * sortKey: category title text as a sort key,
* * type: category type (hidden,normal)
* * title: category title,
* * link: link string, nullable to support ::setCategoryLinks()
*
* @var list
*/
private array $mCategoryData = [];
/**
* Keep track of whether mCategoryData has been
* sorted. We do this on-demand to avoid redundant sorts
* of incremental additions to the category list.
*/
private bool $mCategoriesSorted = true;
/**
* @var string[]
* @deprecated since 1.38; will be made private (T301020)
*/
private $mIndicators = [];
/**
* @var array Array mapping interwiki prefix to (non DB key) Titles (e.g. 'fr' => 'Test page')
*/
private $mLanguageLinks = [];
/**
* Used for JavaScript (predates ResourceLoader)
* @todo We should split JS / CSS.
* mScripts content is inserted as is in "" by Skin. This might
* contain either a link to a stylesheet or inline CSS.
* @var string
*/
private $mScripts = '';
/** @var string Inline CSS styles. Use addInlineStyle() sparingly */
protected $mInlineStyles = '';
/**
* Additional classes; This should be rarely modified; prefer mAdditionalBodyClasses.
* @var array
*/
protected $mAdditionalHtmlClasses = [];
/**
* @var string[] Array of elements in "". Parser might add its own headers!
* @deprecated since 1.38; will be made private (T301020)
*/
private $mHeadItems = [];
/** @var array Additional classes; there are also classes from other sources */
protected $mAdditionalBodyClasses = [];
/**
* @var array
* @deprecated since 1.38; will be made private (T301020)
*/
private $mModules = [];
/**
* @var array
* @deprecated since 1.38; will be made private (T301020)
*/
private $mModuleStyles = [];
/** @var ResourceLoader */
protected $mResourceLoader;
/** @var RL\ClientHtml */
private $rlClient;
/** @var RL\Context */
private $rlClientContext;
/** @var array */
private $rlExemptStyleModules;
/**
* @var array
* @deprecated since 1.38; will be made private (T301020)
*/
private $mJsConfigVars = [];
/**
* @var array>
* @deprecated since 1.38; will be made private (T301020)
*/
private $mTemplateIds = [];
/** @var array */
protected $mImageTimeKeys = [];
/** @var string */
public $mRedirectCode = '';
/** @var null */
protected $mFeedLinksAppendQuery = null;
/** @var array
* What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
* @see RL\Module::$origin
* RL\Module::ORIGIN_ALL is assumed unless overridden;
*/
protected $mAllowedModules = [
RL\Module::TYPE_COMBINED => RL\Module::ORIGIN_ALL,
];
/** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
protected $mDoNothing = false;
// Parser related.
/**
* lazy initialised, use parserOptions()
* @var ParserOptions
*/
protected $mParserOptions = null;
/**
* Handles the Atom / RSS links.
* We probably only support Atom in 2011.
* @see $wgAdvertisedFeedTypes
* @var array
*/
private $mFeedLinks = [];
/**
* @var bool Set to false to send no-cache headers, disabling
* client-side caching. (This variable should really be named
* in the opposite sense; see ::disableClientCache().)
* @deprecated since 1.38; will be made private (T301020)
*/
private $mEnableClientCache = true;
/** @var bool Flag if output should only contain the body of the article. */
private $mArticleBodyOnly = false;
/**
* @var bool
* @deprecated since 1.38; will be made private (T301020)
*/
private $mNewSectionLink = false;
/**
* @var bool
* @deprecated since 1.38; will be made private (T301020)
*/
private $mHideNewSectionLink = false;
/**
* @var bool Comes from the parser. This was probably made to load CSS/JS
* only if we had "". Used directly in CategoryViewer.php.
* Looks like ResourceLoader can replace this.
* @deprecated since 1.38; will be made private (T301020)
*/
private $mNoGallery = false;
/** @var int Cache stuff. Looks like mEnableClientCache */
protected $mCdnMaxage = 0;
/** @var int Upper limit on mCdnMaxage */
protected $mCdnMaxageLimit = INF;
/**
* @var bool Controls if anti-clickjacking / frame-breaking headers will
* be sent. This should be done for pages where edit actions are possible.
* Setter: $this->setPreventClickjacking()
*/
protected $mPreventClickjacking = true;
/** @var int|null To include the variable {{REVISIONID}} */
private $mRevisionId = null;
/** @var bool|null */
private $mRevisionIsCurrent = null;
/** @var string */
private $mRevisionTimestamp = null;
/** @var array */
protected $mFileVersion = null;
/**
* @var array An array of stylesheet filenames (relative from skins path),
* with options for CSS media, IE conditions, and RTL/LTR direction.
* For internal use; add settings in the skin via $this->addStyle()
*
* Style again! This seems like a code duplication since we already have
* mStyles. This is what makes Open Source amazing.
*/
protected $styles = [];
/** @var string */
private $mIndexPolicy = 'index';
/** @var string */
private $mFollowPolicy = 'follow';
/** @var array */
private $mRobotsOptions = [ 'max-image-preview' => 'standard' ];
/**
* @var array Headers that cause the cache to vary. Key is header name,
* value should always be null. (Value was an array of options for
* the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
*/
private $mVaryHeader = [
'Accept-Encoding' => null,
];
/**
* If the current page was reached through a redirect, $mRedirectedFrom contains the title
* of the redirect.
*
* @var PageReference
*/
private $mRedirectedFrom = null;
/**
* Additional key => value data
* @var array
*/
private $mProperties = [];
/**
* @var string|null ResourceLoader target for load.php links. If null, will be omitted
*/
private $mTarget = null;
/**
* @var bool Whether parser output contains a table of contents
*/
private $mEnableTOC = false;
/**
* @var array Flags set in the ParserOutput
*/
private $mOutputFlags = [];
/**
* @var string|null The URL to send in a element with rel=license
*/
private $copyrightUrl;
/**
* @var Language|null
*/
private $contentLang;
/** @var array Profiling data */
private $limitReportJSData = [];
/** @var array Map Title to Content */
private $contentOverrides = [];
/** @var callable[] */
private $contentOverrideCallbacks = [];
/**
* Link: header contents
* @var array
*/
private $mLinkHeader = [];
/**
* @var ContentSecurityPolicy
*/
private $CSP;
private string $cspOutputMode = self::CSP_HEADERS;
/**
* @var array A cache of the names of the cookies that will influence the cache
*/
private static $cacheVaryCookies = null;
/**
* Constructor for OutputPage. This should not be called directly.
* Instead a new RequestContext should be created and it will implicitly create
* a OutputPage tied to that context.
* @param IContextSource $context
*/
public function __construct( IContextSource $context ) {
$this->deprecatePublicProperty( 'mCategoryLinks', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mCategories', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mIndicators', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mHeadItems', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mModules', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mModuleStyles', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mJsConfigVars', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mTemplateIds', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mEnableClientCache', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mNewSectionLink', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mHideNewSectionLink', '1.38', __CLASS__ );
$this->deprecatePublicProperty( 'mNoGallery', '1.38', __CLASS__ );
$this->setContext( $context );
$this->CSP = new ContentSecurityPolicy(
$context->getRequest()->response(),
$context->getConfig(),
$this->getHookContainer()
);
}
/**
* Redirect to $url rather than displaying the normal page
*
* @param string $url
* @param string|int $responsecode HTTP status code
*/
public function redirect( $url, $responsecode = '302' ) {
# Strip newlines as a paranoia check for header injection in PHP<5.1.2
$this->mRedirect = str_replace( "\n", '', $url );
$this->mRedirectCode = (string)$responsecode;
}
/**
* Get the URL to redirect to, or an empty string if not redirect URL set
*
* @return string
*/
public function getRedirect() {
return $this->mRedirect;
}
/**
* Set the copyright URL to send with the output.
* Empty string to omit, null to reset.
*
* @since 1.26
*
* @param string|null $url
*/
public function setCopyrightUrl( $url ) {
$this->copyrightUrl = $url;
}
/**
* Set the HTTP status code to send with the output.
*
* @param int $statusCode
*/
public function setStatusCode( $statusCode ) {
$this->mStatusCode = $statusCode;
}
/**
* Add a new "" tag
* To add an http-equiv meta tag, precede the name with "http:"
*
* @param string $name Name of the meta tag
* @param string $val Value of the meta tag
*/
public function addMeta( $name, $val ) {
$this->mMetatags[] = [ $name, $val ];
}
/**
* Returns the current tags
*
* @since 1.25
* @return array
*/
public function getMetaTags() {
return $this->mMetatags;
}
/**
* Add a new \ tag to the page header.
*
* Note: use setCanonicalUrl() for rel=canonical.
*
* @param array $linkarr Associative array of attributes.
*/
public function addLink( array $linkarr ) {
$this->mLinktags[] = $linkarr;
}
/**
* Returns the current tags
*
* @since 1.25
* @return array
*/
public function getLinkTags() {
return $this->mLinktags;
}
/**
* Set the URL to be used for the . This should be used
* in preference to addLink(), to avoid duplicate link tags.
* @param string $url
*/
public function setCanonicalUrl( $url ) {
$this->mCanonicalUrl = $url;
}
/**
* Returns the URL to be used for the if
* one is set.
*
* @since 1.25
* @return bool|string
*/
public function getCanonicalUrl() {
return $this->mCanonicalUrl;
}
/**
* Add raw HTML to the list of scripts (including \" to "<script>foo&bar</script>"
# but leave "foobar" alone
$nameWithTags = Sanitizer::removeSomeTags( $name );
$this->mPageTitle = $nameWithTags;
# change "foo&bar" to "foo&bar"
$this->setHTMLTitle(
$this->msg( 'pagetitle' )->plaintextParams( Sanitizer::stripAllTags( $nameWithTags ) )
->inContentLanguage()
);
}
/**
* Return the "page title", i.e. the content of the \
tag.
*
* @return string
*/
public function getPageTitle() {
return $this->mPageTitle;
}
/**
* Same as page title but only contains name of the page, not any other text.
*
* @since 1.32
* @param string $html Page title text.
* @see OutputPage::setPageTitle
*/
public function setDisplayTitle( $html ) {
$this->displayTitle = $html;
}
/**
* Returns page display title.
*
* Performs some normalization, but this not as strict the magic word.
*
* @since 1.32
* @return string HTML
*/
public function getDisplayTitle() {
$html = $this->displayTitle;
if ( $html === null ) {
return htmlspecialchars( $this->getTitle()->getPrefixedText(), ENT_NOQUOTES );
}
return Sanitizer::removeSomeTags( $html );
}
/**
* Returns page display title without namespace prefix if possible.
*
* This method is unreliable and best avoided. (T314399)
*
* @since 1.32
* @return string HTML
*/
public function getUnprefixedDisplayTitle() {
$service = MediaWikiServices::getInstance();
$languageConverter = $service->getLanguageConverterFactory()
->getLanguageConverter( $service->getContentLanguage() );
$text = $this->getDisplayTitle();
// Create a regexp with matching groups as placeholders for the namespace, separator and main text
$pageTitleRegexp = '/^' . str_replace(
preg_quote( '(.+?)', '/' ),
'(.+?)',
preg_quote( Parser::formatPageTitle( '(.+?)', '(.+?)', '(.+?)' ), '/' )
) . '$/';
$matches = [];
if ( preg_match( $pageTitleRegexp, $text, $matches ) ) {
// The regexp above could be manipulated by malicious user input,
// sanitize the result just in case
return Sanitizer::removeSomeTags( $matches[3] );
}
$nsPrefix = $languageConverter->convertNamespace(
$this->getTitle()->getNamespace()
) . ':';
$prefix = preg_quote( $nsPrefix, '/' );
return preg_replace( "/^$prefix/i", '', $text );
}
/**
* Set the Title object to use
*
* @param PageReference $t
*/
public function setTitle( PageReference $t ) {
$t = Title::newFromPageReference( $t );
// @phan-suppress-next-next-line PhanUndeclaredMethod
// @fixme Not all implementations of IContextSource have this method!
$this->getContext()->setTitle( $t );
}
/**
* Replace the subtitle with $str
*
* @param string|Message $str New value of the subtitle. String should be safe HTML.
*/
public function setSubtitle( $str ) {
$this->clearSubtitle();
$this->addSubtitle( $str );
}
/**
* Add $str to the subtitle
*
* @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
* @param-taint $str exec_html
*/
public function addSubtitle( $str ) {
if ( $str instanceof Message ) {
$this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
} else {
$this->mSubtitle[] = $str;
}
}
/**
* Build message object for a subtitle containing a backlink to a page
*
* @since 1.25
* @param PageReference $page Title to link to
* @param array $query Array of additional parameters to include in the link
* @return Message
*/
public static function buildBacklinkSubtitle( PageReference $page, $query = [] ) {
if ( $page instanceof PageRecord || $page instanceof Title ) {
// Callers will typically have a PageRecord
if ( $page->isRedirect() ) {
$query['redirect'] = 'no';
}
} elseif ( $page->getNamespace() !== NS_SPECIAL ) {
// We don't know whether it's a redirect, so add the parameter, just to be sure.
$query['redirect'] = 'no';
}
$linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
return wfMessage( 'backlinksubtitle' )
->rawParams( $linkRenderer->makeLink( $page, null, [], $query ) );
}
/**
* Add a subtitle containing a backlink to a page
*
* @param PageReference $title Title to link to
* @param array $query Array of additional parameters to include in the link
*/
public function addBacklinkSubtitle( PageReference $title, $query = [] ) {
$this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
}
/**
* Clear the subtitles
*/
public function clearSubtitle() {
$this->mSubtitle = [];
}
/**
* @return string
*/
public function getSubtitle() {
return implode( " \n\t\t\t\t", $this->mSubtitle );
}
/**
* Set the page as printable, i.e. it'll be displayed with all
* print styles included
*/
public function setPrintable() {
$this->mPrintable = true;
}
/**
* Return whether the page is "printable"
*
* @return bool
*/
public function isPrintable() {
return $this->mPrintable;
}
/**
* Disable output completely, i.e. calling output() will have no effect
*/
public function disable() {
$this->mDoNothing = true;
}
/**
* Return whether the output will be completely disabled
*
* @return bool
*/
public function isDisabled() {
return $this->mDoNothing;
}
/**
* Show an "add new section" link?
*
* @return bool
*/
public function showNewSectionLink() {
return $this->mNewSectionLink;
}
/**
* Forcibly hide the new section link?
*
* @return bool
*/
public function forceHideNewSectionLink() {
return $this->mHideNewSectionLink;
}
/**
* Add or remove feed links in the page header
* This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
* for the new version
* @see addFeedLink()
*
* @param bool $show True: add default feeds, false: remove all feeds
*/
public function setSyndicated( $show = true ) {
if ( $show ) {
$this->setFeedAppendQuery( false );
} else {
$this->mFeedLinks = [];
}
}
/**
* Return effective list of advertised feed types
* @see addFeedLink()
*
* @return string[] Array of feed type names ( 'rss', 'atom' )
*/
protected function getAdvertisedFeedTypes() {
if ( $this->getConfig()->get( MainConfigNames::Feed ) ) {
return $this->getConfig()->get( MainConfigNames::AdvertisedFeedTypes );
} else {
return [];
}
}
/**
* Add default feeds to the page header
* This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
* for the new version
* @see addFeedLink()
*
* @param string|false $val Query to append to feed links or false to output
* default links
*/
public function setFeedAppendQuery( $val ) {
$this->mFeedLinks = [];
foreach ( $this->getAdvertisedFeedTypes() as $type ) {
$query = "feed=$type";
if ( is_string( $val ) ) {
$query .= '&' . $val;
}
$this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
}
}
/**
* Add a feed link to the page header
*
* @param string $format Feed type, should be a key of $wgFeedClasses
* @param string $href URL
*/
public function addFeedLink( $format, $href ) {
if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
$this->mFeedLinks[$format] = $href;
}
}
/**
* Should we output feed links for this page?
* @return bool
*/
public function isSyndicated() {
return count( $this->mFeedLinks ) > 0;
}
/**
* Return URLs for each supported syndication format for this page.
* @return array Associating format keys with URLs
*/
public function getSyndicationLinks() {
return $this->mFeedLinks;
}
/**
* Will currently always return null
*
* @return null
*/
public function getFeedAppendQuery() {
return $this->mFeedLinksAppendQuery;
}
/**
* Set whether the displayed content is related to the source of the
* corresponding article on the wiki
* Setting true will cause the change "article related" toggle to true
*
* @param bool $newVal
*/
public function setArticleFlag( $newVal ) {
$this->mIsArticle = $newVal;
if ( $newVal ) {
$this->mIsArticleRelated = $newVal;
}
}
/**
* Return whether the content displayed page is related to the source of
* the corresponding article on the wiki
*
* @return bool
*/
public function isArticle() {
return $this->mIsArticle;
}
/**
* Set whether this page is related an article on the wiki
* Setting false will cause the change of "article flag" toggle to false
*
* @param bool $newVal
*/
public function setArticleRelated( $newVal ) {
$this->mIsArticleRelated = $newVal;
if ( !$newVal ) {
$this->mIsArticle = false;
}
}
/**
* Return whether this page is related an article on the wiki
*
* @return bool
*/
public function isArticleRelated() {
return $this->mIsArticleRelated;
}
/**
* Set whether the standard copyright should be shown for the current page.
*
* @param bool $hasCopyright
*/
public function setCopyright( $hasCopyright ) {
$this->mHasCopyright = $hasCopyright;
}
/**
* Return whether the standard copyright should be shown for the current page.
* By default, it is true for all articles but other pages
* can signal it by using setCopyright( true ).
*
* Used by SkinTemplate to decided whether to show the copyright.
*
* @return bool
*/
public function showsCopyright() {
return $this->isArticle() || $this->mHasCopyright;
}
/**
* Add new language links
*
* @param string[]|ParsoidLinkTarget[] $newLinkArray Array of
* interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
*/
public function addLanguageLinks( array $newLinkArray ) {
# $newLinkArray is in order of appearance on the page;
# deduplicate so only the first for a given prefix is used
# (T26502)
foreach ( $newLinkArray as $item ) {
if ( is_string( $item ) ) {
[ $prefix, $title ] = explode( ':', $item, 2 );
# note that $title may have a fragment
} else {
$prefix = $item->getInterwiki();
$title = $item->getText();
if ( $item->getFragment() !== '' ) {
$title .= '#' . $item->getFragment();
}
}
$this->mLanguageLinks[$prefix] ??= $title;
}
}
/**
* Reset the language links and add new language links
*
* @param string[]|ParsoidLinkTarget[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
* (e.g. 'fr:Test page')
* @deprecated since 1.43, use ::addLanguageLinks() instead, or
* use the LanguageLinksHook in the rare case that you need to remove
* or replace language links from the output page.
*/
public function setLanguageLinks( array $newLinkArray ) {
$this->mLanguageLinks = [];
$this->addLanguageLinks( $newLinkArray );
}
/**
* Get the list of language links
*
* @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
*/
public function getLanguageLinks() {
$result = [];
foreach ( $this->mLanguageLinks as $prefix => $title ) {
$result[] = "$prefix:$title";
}
return $result;
}
/**
* Get the "no gallery" flag
*
* Used directly only in CategoryViewer.php
* @internal
*/
public function getNoGallery(): bool {
return $this->mNoGallery;
}
/**
* Add an array of categories, with names in the keys
*
* @param array $categories Mapping category name => sort key
*/
public function addCategoryLinks( array $categories ) {
if ( !$categories ) {
return;
}
$res = $this->addCategoryLinksToLBAndGetResult( $categories );
# Set all the values to 'normal'.
$categories = array_fill_keys( array_keys( $categories ), 'normal' );
$pageData = [];
# Mark hidden categories
foreach ( $res as $row ) {
if ( isset( $row->pp_value ) ) {
$categories[$row->page_title] = 'hidden';
}
// Page exists, cache results
if ( isset( $row->page_id ) ) {
$pageData[$row->page_title] = $row;
}
}
# Add the remaining categories to the skin
if ( $this->getHookRunner()->onOutputPageMakeCategoryLinks(
$this, $categories, $this->mCategoryLinks )
) {
$services = MediaWikiServices::getInstance();
$linkRenderer = $services->getLinkRenderer();
$languageConverter = $services->getLanguageConverterFactory()
->getLanguageConverter( $services->getContentLanguage() );
$collation = $services->getCollationFactory()->getCategoryCollation();
foreach ( $categories as $category => $type ) {
// array keys will cast numeric category names to ints, so cast back to string
$category = (string)$category;
$origcategory = $category;
if ( array_key_exists( $category, $pageData ) ) {
$title = Title::newFromRow( $pageData[$category] );
} else {
$title = Title::makeTitleSafe( NS_CATEGORY, $category );
}
if ( !$title ) {
continue;
}
$languageConverter->findVariantLink( $category, $title, true );
if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
continue;
}
$text = $languageConverter->convertHtml( $title->getText() );
$link = null;
$this->getHookRunner()->onOutputPageRenderCategoryLink( $this, $title->toPageIdentity(), $text, $link );
if ( $link === null ) {
$link = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
}
$this->mCategoryData[] = [
'sortKey' => $collation->getSortKey( $text ),
'type' => $type,
'title' => $title->getText(),
'link' => $link,
];
$this->mCategoriesSorted = false;
// Setting mCategories and mCategoryLinks is redundant here,
// but it is needed for compatibility until mCategories and
// mCategoryLinks are made private (T301020)
$this->mCategories[$type][] = $title->getText();
$this->mCategoryLinks[$type][] = $link;
}
} else {
// Conservatively assume the hook left the categories unsorted.
$this->mCategoriesSorted = false;
}
}
/**
* @param array $categories
* @return IResultWrapper
*/
protected function addCategoryLinksToLBAndGetResult( array $categories ) {
# Add the links to a LinkBatch
$arr = [ NS_CATEGORY => $categories ];
$linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
$lb = $linkBatchFactory->newLinkBatch();
$lb->setArray( $arr );
# Fetch existence plus the hiddencat property
$dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
$fields = array_merge(
LinkCache::getSelectFields(),
[ 'pp_value' ]
);
$res = $dbr->newSelectQueryBuilder()
->select( $fields )
->from( 'page' )
->leftJoin( 'page_props', null, [
'pp_propname' => 'hiddencat',
'pp_page = page_id',
] )
->where( $lb->constructSet( 'page', $dbr ) )
->caller( __METHOD__ )
->fetchResultSet();
# Add the results to the link cache
$linkCache = MediaWikiServices::getInstance()->getLinkCache();
$lb->addResultToCache( $linkCache, $res );
return $res;
}
/**
* Reset the category links (but not the category list) and add $categories
*
* @param array $categories Mapping category name => sort key
* @deprecated since 1.43, use ::addCategoryLinks()
*/
public function setCategoryLinks( array $categories ) {
wfDeprecated( __METHOD__, '1.43' );
$this->mCategoryLinks = [];
foreach ( $this->mCategoryData as &$arr ) {
// null out the 'link' entry for existing category data
$arr['link'] = null;
}
$this->addCategoryLinks( $categories );
}
/**
* Get the list of category links, in a 2-D array with the following format:
* $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
* hidden categories) and $link a HTML fragment with a link to the category
* page
*
* @return string[][]
* @return-taint none
*/
public function getCategoryLinks() {
$this->maybeSortCategories();
return $this->mCategoryLinks;
}
/**
* Get the list of category names this page belongs to.
*
* @param string $type The type of categories which should be returned. Possible values:
* * all: all categories of all types
* * hidden: only the hidden categories
* * normal: all categories, except hidden categories
* @return string[]
*/
public function getCategories( $type = 'all' ) {
$this->maybeSortCategories();
if ( $type === 'all' ) {
$allCategories = [];
foreach ( $this->mCategories as $categories ) {
$allCategories = array_merge( $allCategories, $categories );
}
return $allCategories;
}
if ( !isset( $this->mCategories[$type] ) ) {
throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
}
return $this->mCategories[$type];
}
/**
* Ensure that the category lists are sorted, so that we don't
* inadvertently depend on the exact evaluation order of various
* ParserOutput fragments.
*/
private function maybeSortCategories(): void {
if ( $this->mCategoriesSorted ) {
return;
}
// Check wiki configuration...
$sortCategories = $this->getConfig()->get( MainConfigNames::SortedCategories );
// ...but allow override with query parameter.
$sortCategories = $this->getRequest()->getFuzzyBool( 'sortcat', $sortCategories );
if ( $sortCategories ) {
// Primary sort key is the first element of category data, but
// break ties by looking at the other elements.
usort( $this->mCategoryData, static function ( $a, $b ): int {
return $a['type'] <=> $b['type'] ?:
$a['sortKey'] <=> $b['sortKey'] ?:
$a['title'] <=> $b['sortKey'] ?:
$a['link'] <=> $b['link'];
} );
}
// Rebuild mCategories and mCategoryLinks
$this->mCategories = [
'hidden' => [],
'normal' => [],
];
$this->mCategoryLinks = [];
foreach ( $this->mCategoryData as $c ) {
$this->mCategories[$c['type']][] = $c['title'];
if ( $c['link'] !== null ) {
// This test only needed because of ::setCategoryLinks()
$this->mCategoryLinks[$c['type']][] = $c['link'];
}
}
$this->mCategoriesSorted = true;
}
/**
* Add an array of indicators, with their identifiers as array
* keys and HTML contents as values.
*
* In case of duplicate keys, existing values are overwritten.
*
* @note External code which calls this method should ensure that
* any indicators sourced from parsed wikitext are wrapped with
* the appropriate class; see note in ::getIndicators().
*
* @param string[] $indicators
* @param-taint $indicators exec_html
* @since 1.25
*/
public function setIndicators( array $indicators ) {
$this->mIndicators = $indicators + $this->mIndicators;
// Keep ordered by key
ksort( $this->mIndicators );
}
/**
* Get the indicators associated with this page.
*
* The array will be internally ordered by item keys.
*
* @return string[] Keys: identifiers, values: HTML contents
* @since 1.25
*/
public function getIndicators(): array {
// Note that some -- but not all -- indicators will be wrapped
// with a class appropriate for user-generated wikitext content
// (usually .mw-parser-output). The exceptions would be an
// indicator added via ::addHelpLink() below, which adds content
// which don't come from the parser and is not user-generated;
// and any indicators added by extensions which may call
// OutputPage::setIndicators() directly. In the latter case the
// caller is responsible for wrapping any parser-generated
// indicators.
return $this->mIndicators;
}
/**
* Adds help link with an icon via page indicators.
* Link target can be overridden by a local message containing a wikilink:
* the message key is: lowercase action or special page name + '-helppage'.
* @param string $to Target MediaWiki.org page title or encoded URL.
* @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MediaWiki.org.
* @since 1.25
*/
public function addHelpLink( $to, $overrideBaseUrl = false ) {
$this->addModuleStyles( 'mediawiki.helplink' );
$text = $this->msg( 'helppage-top-gethelp' )->escaped();
if ( $overrideBaseUrl ) {
$helpUrl = $to;
} else {
$toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
$helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
}
$link = Html::rawElement(
'a',
[
'href' => $helpUrl,
'target' => '_blank',
'class' => 'mw-helplink',
],
Html::element( 'span', [ 'class' => 'mw-helplink-icon' ] ) . $text
);
// See note in ::getIndicators() above -- unlike wikitext-generated
// indicators which come from ParserOutput, this indicator will not
// be wrapped.
$this->setIndicators( [ 'mw-helplink' => $link ] );
}
/**
* Do not allow scripts which can be modified by wiki users to load on this page;
* only allow scripts bundled with, or generated by, the software.
* Site-wide styles are controlled by a config setting, since they can be
* used to create a custom skin/theme, but not user-specific ones.
*
* @todo this should be given a more accurate name
*/
public function disallowUserJs() {
$this->reduceAllowedModules(
RL\Module::TYPE_SCRIPTS,
RL\Module::ORIGIN_CORE_INDIVIDUAL
);
// Site-wide styles are controlled by a config setting, see T73621
// for background on why. User styles are never allowed.
if ( $this->getConfig()->get( MainConfigNames::AllowSiteCSSOnRestrictedPages ) ) {
$styleOrigin = RL\Module::ORIGIN_USER_SITEWIDE;
} else {
$styleOrigin = RL\Module::ORIGIN_CORE_INDIVIDUAL;
}
$this->reduceAllowedModules(
RL\Module::TYPE_STYLES,
$styleOrigin
);
}
/**
* Show what level of JavaScript / CSS untrustworthiness is allowed on this page
* @see RL\Module::$origin
* @param string $type RL\Module TYPE_ constant
* @return int Module ORIGIN_ class constant
*/
public function getAllowedModules( $type ) {
if ( $type == RL\Module::TYPE_COMBINED ) {
return min( array_values( $this->mAllowedModules ) );
} else {
return $this->mAllowedModules[$type] ?? RL\Module::ORIGIN_ALL;
}
}
/**
* Limit the highest level of CSS/JS untrustworthiness allowed.
*
* If passed the same or a higher level than the current level of untrustworthiness set, the
* level will remain unchanged.
*
* @param string $type
* @param int $level RL\Module class constant
*/
public function reduceAllowedModules( $type, $level ) {
$this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
}
/**
* Prepend $text to the body HTML
*
* @param string $text HTML
* @param-taint $text exec_html
*/
public function prependHTML( $text ) {
$this->mBodytext = $text . $this->mBodytext;
}
/**
* Append $text to the body HTML
*
* @param string $text HTML
* @param-taint $text exec_html
*/
public function addHTML( $text ) {
$this->mBodytext .= $text;
}
/**
* Shortcut for adding an Html::element via addHTML.
*
* @since 1.19
*
* @param string $element
* @param array $attribs
* @param string $contents
*/
public function addElement( $element, array $attribs = [], $contents = '' ) {
$this->addHTML( Html::element( $element, $attribs, $contents ) );
}
/**
* Clear the body HTML
*/
public function clearHTML() {
$this->mBodytext = '';
}
/**
* Get the body HTML
*
* @return string HTML
*/
public function getHTML() {
return $this->mBodytext;
}
/**
* Get/set the ParserOptions object to use for wikitext parsing
*
* @return ParserOptions
*/
public function parserOptions() {
if ( !$this->mParserOptions ) {
if ( !$this->getUser()->isSafeToLoad() ) {
// Context user isn't unstubbable yet, so don't try to get a
// ParserOptions for it. And don't cache this ParserOptions
// either.
$po = ParserOptions::newFromAnon();
$po->setAllowUnsafeRawHtml( false );
return $po;
}
$this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
$this->mParserOptions->setAllowUnsafeRawHtml( false );
}
return $this->mParserOptions;
}
/**
* Set the revision ID which will be seen by the wiki text parser
* for things such as embedded {{REVISIONID}} variable use.
*
* @param int|null $revid A positive integer, or null
* @return mixed Previous value
*/
public function setRevisionId( $revid ) {
$val = $revid === null ? null : intval( $revid );
return wfSetVar( $this->mRevisionId, $val, true );
}
/**
* Get the displayed revision ID
*
* @return int|null
*/
public function getRevisionId() {
return $this->mRevisionId;
}
/**
* Set whether the revision displayed (as set in ::setRevisionId())
* is the latest revision of the page.
*
* @param bool $isCurrent
*/
public function setRevisionIsCurrent( bool $isCurrent ): void {
$this->mRevisionIsCurrent = $isCurrent;
}
/**
* Whether the revision displayed is the latest revision of the page
*
* @since 1.34
* @return bool
*/
public function isRevisionCurrent(): bool {
return $this->mRevisionId == 0 || (
$this->mRevisionIsCurrent ?? (
$this->mRevisionId == $this->getTitle()->getLatestRevID()
)
);
}
/**
* Set the timestamp of the revision which will be displayed. This is used
* to avoid a extra DB call in SkinComponentFooter::lastModified().
*
* @param string|null $timestamp
* @return mixed Previous value
*/
public function setRevisionTimestamp( $timestamp ) {
return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
}
/**
* Get the timestamp of displayed revision.
* This will be null if not filled by setRevisionTimestamp().
*
* @return string|null
*/
public function getRevisionTimestamp() {
return $this->mRevisionTimestamp;
}
/**
* Set the displayed file version
*
* @param File|null $file
* @return mixed Previous value
*/
public function setFileVersion( $file ) {
$val = null;
if ( $file instanceof File && $file->exists() ) {
$val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
}
return wfSetVar( $this->mFileVersion, $val, true );
}
/**
* Get the displayed file version
*
* @return array|null ('time' => MW timestamp, 'sha1' => sha1)
*/
public function getFileVersion() {
return $this->mFileVersion;
}
/**
* Get the templates used on this page
*
* @return array> (namespace => dbKey => revId)
* @since 1.18
*/
public function getTemplateIds() {
return $this->mTemplateIds;
}
/**
* Get the files used on this page
*
* @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
* @since 1.18
*/
public function getFileSearchOptions() {
return $this->mImageTimeKeys;
}
/**
* Convert wikitext *in the user interface language* to HTML and
* add it to the buffer. The result will not be
* language-converted, as user interface messages are already
* localized into a specific variant. Assumes that the current
* page title will be used if optional $title is not
* provided. Output will be tidy.
*
* @param string $text Wikitext in the user interface language
* @param bool $linestart Is this the start of a line? (Defaults to true)
* @param PageReference|null $title Optional title to use; default of `null`
* means use current page title.
* @since 1.32
*/
public function addWikiTextAsInterface(
$text, $linestart = true, ?PageReference $title = null
) {
$title ??= $this->getTitle();
if ( $title === null ) {
throw new RuntimeException( 'No title in ' . __METHOD__ );
}
$this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
}
/**
* Convert wikitext *in the user interface language* to HTML and
* add it to the buffer with a `
`
* wrapper. The result will not be language-converted, as user
* interface messages as already localized into a specific
* variant. The $text will be parsed in start-of-line context.
* Output will be tidy.
*
* @param string $wrapperClass The class attribute value for the
* wrapper in the output HTML
* @param string $text Wikitext in the user interface language
* @since 1.32
*/
public function wrapWikiTextAsInterface(
$wrapperClass, $text
) {
$title = $this->getTitle();
if ( $title === null ) {
throw new RuntimeException( 'No title in ' . __METHOD__ );
}
$this->addWikiTextTitleInternal(
$text, $title,
/*linestart*/true, /*interface*/true,
$wrapperClass
);
}
/**
* Convert wikitext *in the page content language* to HTML and add
* it to the buffer. The result with be language-converted to the
* user's preferred variant. Assumes that the current page title
* will be used if optional $title is not provided. Output will be
* tidy.
*
* @param string $text Wikitext in the page content language
* @param bool $linestart Is this the start of a line? (Defaults to true)
* @param PageReference|null $title Optional title to use; default of `null`
* means use current page title.
* @since 1.32
*/
public function addWikiTextAsContent(
$text, $linestart = true, ?PageReference $title = null
) {
$title ??= $this->getTitle();
if ( !$title ) {
throw new RuntimeException( 'No title in ' . __METHOD__ );
}
$this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
}
/**
* Add wikitext with a custom Title object.
* Output is unwrapped.
*
* @param string $text Wikitext
* @param PageReference $title
* @param bool $linestart Is this the start of a line?@param
* @param bool $interface Whether it is an interface message
* (for example disables conversion)
* @param string|null $wrapperClass if not empty, wraps the output in
* a `
`
*/
private function addWikiTextTitleInternal(
string $text, PageReference $title, bool $linestart, bool $interface,
?string $wrapperClass = null
) {
$parserOutput = $this->parseInternal(
$text, $title, $linestart, $interface
);
$this->addParserOutput( $parserOutput, [
'enableSectionEditLinks' => false,
'wrapperDivClass' => $wrapperClass ?? '',
] );
}
/**
* Adds Table of Contents data to OutputPage from ParserOutput
* @param TOCData $tocData
* @internal For use by Article.php
*/
public function setTOCData( TOCData $tocData ) {
$this->tocData = $tocData;
}
/**
* @internal For usage in Skin::getTOCData() only.
* @return ?TOCData Table of Contents data, or
* null if OutputPage::setTOCData() has not been called.
*/
public function getTOCData(): ?TOCData {
return $this->tocData;
}
/**
* @internal Will be replaced by direct access to
* ParserOutput::getOutputFlag()
* @param string $name A flag name from ParserOutputFlags
* @return bool
*/
public function getOutputFlag( string $name ): bool {
return isset( $this->mOutputFlags[$name] );
}
/**
* @internal For use by ViewAction/Article only
* @since 1.42
* @param Bcp47Code $lang
*/
public function setContentLangForJS( Bcp47Code $lang ): void {
$this->contentLang = MediaWikiServices::getInstance()->getLanguageFactory()
->getLanguage( $lang );
}
/**
* Which language getJSVars should use
*
* Use of this is strongly discouraged in favour of ParserOutput::getLanguage(),
* and should not be needed in most cases given that the OutputTransform
* already takes care of 'lang' and 'dir' attributes.
*
* Consider whether RequestContext::getLanguage (e.g. OutputPage::getLanguage
* or Skin::getLanguage) or MediaWikiServices::getContentLanguage is more
* appropiate first for your use case.
*
* @since 1.42
* @return Language
*/
private function getContentLangForJS(): Language {
if ( !$this->contentLang ) {
// If this is not set, then we're likely not on in a request that renders page content
// (e.g. ViewAction or ApiParse), but rather a different Action or SpecialPage.
// In that case there isn't a main ParserOutput object to represent the page or output.
// But, the skin and frontend code mostly don't make this distinction, and so we still
// need to return something for mw.config.
//
// For historical reasons, the expectation is that:
// * on a SpecialPage, we return the language for the content area just like on a
// page view. SpecialPage content is localised, and so this is the user language.
// * on an Action about a WikiPage, we return the language that content would have
// been shown in, if this were a page view. This is generally the page language
// as stored in the database, except adapted to the current user (e.g. in case of
// translated pages or a language variant preference)
//
// This mess was centralised to here in 2023 (T341244).
$title = $this->getTitle();
if ( $title->isSpecialPage() ) {
// Special pages render in the interface language, based on request context.
// If the user's preference (or request parameter) specifies a variant,
// the content may have been converted to the user's language variant.
$pageLang = $this->getLanguage();
} else {
wfDebug( __METHOD__ . ' has to guess ParserOutput language' );
// Guess what Article::getParserOutput and ParserOptions::optionsHash() would decide
// on a page view:
//
// - Pages may have a custom page_lang set in the database,
// via Title::getPageLanguage/Title::getDbPageLanguage
//
// - Interface messages (NS_MEDIAWIKI) render based on their subpage,
// via Title::getPageLanguage/ContentHandler::getPageLanguage/MessageCache::figureMessage
//
// - Otherwise, pages are assumed to be in the wiki's default content language.
// via Title::getPageLanguage/ContentHandler::getPageLanguage/MediaWikiServices::getContentLanguage
$pageLang = $title->getPageLanguage();
}
if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
$services = MediaWikiServices::getInstance();
$langConv = $services->getLanguageConverterFactory()->getLanguageConverter( $pageLang );
// NOTE: LanguageConverter::getPreferredVariant inspects global RequestContext.
// This usually returns $pageLang unchanged.
$variant = $langConv->getPreferredVariant();
if ( $pageLang->getCode() !== $variant ) {
$pageLang = $services->getLanguageFactory()->getLanguage( $variant );
}
}
$this->contentLang = $pageLang;
}
return $this->contentLang;
}
/**
* Add all metadata associated with a ParserOutput object, but without the actual HTML. This
* includes categories, language links, ResourceLoader modules, effects of certain magic words,
* and so on. It does *not* include section information.
*
* @since 1.24
* @param ParserOutput $parserOutput
*/
public function addParserOutputMetadata( ParserOutput $parserOutput ) {
// T301020 This should eventually use the standard "merge ParserOutput"
// function between $parserOutput and $this->metadata.
$this->addLanguageLinks( $parserOutput->getLanguageLinks() );
$this->addCategoryLinks( $parserOutput->getCategoryMap() );
// Parser-generated indicators get wrapped like other parser output.
$wrapClass = $parserOutput->getWrapperDivClass();
$result = [];
foreach ( $parserOutput->getIndicators() as $name => $html ) {
if ( $html !== '' && $wrapClass !== '' ) {
$html = Html::rawElement( 'div', [ 'class' => $wrapClass ], $html );
}
$result[$name] = $html;
}
$this->setIndicators( $result );
$tocData = $parserOutput->getTOCData();
// Do not override existing TOC data if the new one is empty (T307256#8817705)
// TODO: Invent a way to merge TOCs from multiple outputs (T327429)
if ( $tocData !== null && ( $this->tocData === null || count( $tocData->getSections() ) > 0 ) ) {
$this->setTOCData( $tocData );
}
// FIXME: Best practice is for OutputPage to be an accumulator, as
// addParserOutputMetadata() may be called multiple times, but the
// following lines overwrite any previous data. These should
// be migrated to an injection pattern. (T301020, T300979)
// (Note that OutputPage::getOutputFlag() also contains this
// information, with flags from each $parserOutput all OR'ed together.)
$this->mNewSectionLink = $parserOutput->getNewSection();
$this->mHideNewSectionLink = $parserOutput->getHideNewSection();
$this->mNoGallery = $parserOutput->getNoGallery();
if ( !$parserOutput->isCacheable() ) {
$this->disableClientCache();
}
$this->addHeadItems( $parserOutput->getHeadItems() );
$this->addModules( $parserOutput->getModules() );
$this->addModuleStyles( $parserOutput->getModuleStyles() );
$this->addJsConfigVars( $parserOutput->getJsConfigVars() );
$this->mPreventClickjacking = $this->mPreventClickjacking
|| $parserOutput->getPreventClickjacking();
$scriptSrcs = $parserOutput->getExtraCSPScriptSrcs();
foreach ( $scriptSrcs as $src ) {
$this->getCSP()->addScriptSrc( $src );
}
$defaultSrcs = $parserOutput->getExtraCSPDefaultSrcs();
foreach ( $defaultSrcs as $src ) {
$this->getCSP()->addDefaultSrc( $src );
}
$styleSrcs = $parserOutput->getExtraCSPStyleSrcs();
foreach ( $styleSrcs as $src ) {
$this->getCSP()->addStyleSrc( $src );
}
// If $wgImagePreconnect is true, and if the output contains images, give the user-agent
// a hint about a remote hosts from which images may be served. Launched in T123582.
if ( $this->getConfig()->get( MainConfigNames::ImagePreconnect ) && count( $parserOutput->getImages() ) ) {
$preconnect = [];
// Optimization: Instead of processing each image, assume that wikis either serve both
// foreign and local from the same remote hostname (e.g. public wikis at WMF), or that
// foreign images are common enough to be worth the preconnect (e.g. private wikis).
$repoGroup = MediaWikiServices::getInstance()->getRepoGroup();
$repoGroup->forEachForeignRepo( static function ( $repo ) use ( &$preconnect ) {
$preconnect[] = $repo->getZoneUrl( 'thumb' );
} );
// Consider both foreign and local repos. While LocalRepo by default uses a relative
// path on the same domain, wiki farms may configure it to use a dedicated hostname.
$preconnect[] = $repoGroup->getLocalRepo()->getZoneUrl( 'thumb' );
foreach ( $preconnect as $url ) {
$host = parse_url( $url, PHP_URL_HOST );
// It is expected that file URLs are often path-only, without hostname (T317329).
if ( $host ) {
$this->addLink( [ 'rel' => 'preconnect', 'href' => '//' . $host ] );
break;
}
}
}
// Template versioning...
foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
if ( isset( $this->mTemplateIds[$ns] ) ) {
$this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
} else {
$this->mTemplateIds[$ns] = $dbks;
}
}
// File versioning...
foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
$this->mImageTimeKeys[$dbk] = $data;
}
// Enable OOUI if requested via ParserOutput
if ( $parserOutput->getEnableOOUI() ) {
$this->enableOOUI();
}
// Include parser limit report
// FIXME: This should append, rather than overwrite, or else this
// data should be injected into the OutputPage like is done for the
// other page-level things (like OutputPage::setTOCData()).
if ( !$this->limitReportJSData ) {
$this->limitReportJSData = $parserOutput->getLimitReportJSData();
}
// Link flags are ignored for now, but may in the future be
// used to mark individual language links.
$linkFlags = [];
$languageLinks = $this->getLanguageLinks();
// This hook can be used to remove/replace language links
$this->getHookRunner()->onLanguageLinks( $this->getTitle(), $languageLinks, $linkFlags );
$this->mLanguageLinks = [];
$this->addLanguageLinks( $languageLinks );
$this->getHookRunner()->onOutputPageParserOutput( $this, $parserOutput );
// This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
// so that extensions may modify ParserOutput to toggle TOC.
// This cannot be moved to addParserOutputText because that is not
// called by EditPage for Preview.
// ParserOutputFlags::SHOW_TOC is used to indicate whether the TOC
// should be shown (or hidden) in the output.
$this->mEnableTOC = $this->mEnableTOC ||
$parserOutput->getOutputFlag( ParserOutputFlags::SHOW_TOC );
// Uniform handling of all boolean flags: they are OR'ed together
// (See ParserOutput::collectMetadata())
$flags =
array_flip( $parserOutput->getAllFlags() ) +
array_flip( ParserOutputFlags::cases() );
foreach ( $flags as $name => $ignore ) {
if ( $parserOutput->getOutputFlag( $name ) ) {
$this->mOutputFlags[$name] = true;
}
}
}
private function getParserOutputText( ParserOutput $parserOutput, array $poOptions = [] ): string {
// Add default options from the skin
$skin = $this->getSkin();
$skinOptions = $skin->getOptions();
$oldText = $parserOutput->getRawText();
$poOptions += [
'allowClone' => false, // T371022
'skin' => $skin,
'injectTOC' => $skinOptions['toc'],
];
$pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
// Note: this path absolutely expects the metadata of $parserOutput to be mutated by the pipeline,
// but the raw text should not be, see T353257
// TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
$text = $pipeline->run( $parserOutput, $this->parserOptions(), $poOptions )->getContentHolderText();
$parserOutput->setRawText( $oldText );
return $text;
}
/**
* Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
* ParserOutput object, without any other metadata.
*
* @since 1.24
* @param ParserOutput $parserOutput
* @param array $poOptions Options to OutputTransformPipeline::run() (to be deprecated)
*/
public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
$text = $this->getParserOutputText( $parserOutput, $poOptions );
$this->addParserOutputText( $text, $poOptions );
$this->addModules( $parserOutput->getModules() );
$this->addModuleStyles( $parserOutput->getModuleStyles() );
$this->addJsConfigVars( $parserOutput->getJsConfigVars() );
}
/**
* Add the HTML associated with a ParserOutput object, without any metadata.
*
* @internal For local use only
* @param string|ParserOutput $text
* @param array $poOptions Options to OutputTransformPipeline::run() (to be deprecated)
*/
public function addParserOutputText( $text, $poOptions = [] ) {
if ( $text instanceof ParserOutput ) {
wfDeprecated( __METHOD__ . ' with ParserOutput as first arg', '1.42' );
$text = $this->getParserOutputText( $text, $poOptions );
}
$this->getHookRunner()->onOutputPageBeforeHTML( $this, $text );
$this->addHTML( $text );
}
/**
* Add everything from a ParserOutput object.
*
* @param ParserOutput $parserOutput
* @param array $poOptions Options to OutputTransformPipeline::run() (to be deprecated)
*/
public function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
$text = $this->getParserOutputText( $parserOutput, $poOptions );
$this->addParserOutputMetadata( $parserOutput );
$this->addParserOutputText( $text, $poOptions );
}
/**
* Add the output of a QuickTemplate to the output buffer
*
* @param \QuickTemplate &$template
*/
public function addTemplate( &$template ) {
$this->addHTML( $template->getHTML() );
}
/**
* Parse wikitext *in the page content language* and return the HTML.
* The result will be language-converted to the user's preferred variant.
* Output will be tidy.
*
* @param string $text Wikitext in the page content language
* @param bool $linestart Is this the start of a line? (Defaults to true)
* @return string HTML
* @since 1.32
*/
public function parseAsContent( $text, $linestart = true ) {
$title = $this->getTitle();
if ( $title === null ) {
throw new RuntimeException( 'No title in ' . __METHOD__ );
}
$po = $this->parseInternal(
$text, $title, $linestart, /*interface*/false
);
$pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
// TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
return $pipeline->run( $po, $this->parserOptions(), [
'allowTOC' => false,
'enableSectionEditLinks' => false,
'wrapperDivClass' => '',
'userLang' => $this->getContext()->getLanguage(),
] )->getContentHolderText();
}
/**
* Parse wikitext *in the user interface language* and return the HTML.
* The result will not be language-converted, as user interface messages
* are already localized into a specific variant.
* Output will be tidy.
*
* @param string $text Wikitext in the user interface language
* @param bool $linestart Is this the start of a line? (Defaults to true)
* @return string HTML
* @since 1.32
*/
public function parseAsInterface( $text, $linestart = true ) {
$title = $this->getTitle();
if ( $title === null ) {
throw new RuntimeException( 'No title in ' . __METHOD__ );
}
$po = $this->parseInternal(
$text, $title, $linestart, /*interface*/true
);
$pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
// TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
return $pipeline->run( $po, $this->parserOptions(), [
'allowTOC' => false,
'enableSectionEditLinks' => false,
'wrapperDivClass' => '',
'userLang' => $this->getContext()->getLanguage(),
] )->getContentHolderText();
}
/**
* Parse wikitext *in the user interface language*, strip
* paragraph wrapper, and return the HTML.
* The result will not be language-converted, as user interface messages
* are already localized into a specific variant.
* Output will be tidy. Outer paragraph wrapper will only be stripped
* if the result is a single paragraph.
*
* @param string $text Wikitext in the user interface language
* @param bool $linestart Is this the start of a line? (Defaults to true)
* @return string HTML
* @since 1.32
*/
public function parseInlineAsInterface( $text, $linestart = true ) {
return Parser::stripOuterParagraph(
$this->parseAsInterface( $text, $linestart )
);
}
/**
* Parse wikitext and return the HTML (internal implementation helper)
*
* @param string $text
* @param PageReference $title The title to use
* @param bool $linestart Is this the start of a line?
* @param bool $interface Use interface language (instead of content language) while parsing
* language sensitive magic words like GRAMMAR and PLURAL. This also disables
* LanguageConverter.
* @return ParserOutput
*/
private function parseInternal(
string $text, PageReference $title, bool $linestart, bool $interface
) {
$popts = $this->parserOptions();
$oldInterface = $popts->setInterfaceMessage( $interface );
$parserOutput = MediaWikiServices::getInstance()->getParserFactory()->getInstance()
->parse(
$text, $title, $popts,
$linestart, true, $this->mRevisionId
);
$popts->setInterfaceMessage( $oldInterface );
return $parserOutput;
}
/**
* Set the value of the "s-maxage" part of the "Cache-control" HTTP header
*
* @param int $maxage Maximum cache time on the CDN, in seconds.
*/
public function setCdnMaxage( $maxage ) {
$this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
}
/**
* Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
* lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
* that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
* $maxage.
*
* @param int $maxage Maximum cache time on the CDN, in seconds
* @since 1.27
*/
public function lowerCdnMaxage( $maxage ) {
$this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
$this->setCdnMaxage( $this->mCdnMaxage );
}
/**
* Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
*
* This sets and returns $minTTL if $mtime is false or null. Otherwise,
* the TTL is higher the older the $mtime timestamp is. Essentially, the
* TTL is 90% of the age of the object, subject to the min and max.
*
* @param string|int|float|false|null $mtime Last-Modified timestamp
* @param int $minTTL Minimum TTL in seconds [default: 1 minute]
* @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
* @since 1.28
*/
public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
$minTTL = $minTTL ?: ExpirationAwareness::TTL_MINUTE;
$maxTTL = $maxTTL ?: $this->getConfig()->get( MainConfigNames::CdnMaxAge );
if ( $mtime === null || $mtime === false ) {
return; // entity does not exist
}
$age = MWTimestamp::time() - (int)wfTimestamp( TS_UNIX, $mtime );
$adaptiveTTL = max( 0.9 * $age, $minTTL );
$adaptiveTTL = min( $adaptiveTTL, $maxTTL );
$this->lowerCdnMaxage( (int)$adaptiveTTL );
}
/**
* Do not send nocache headers
*/
public function enableClientCache(): void {
$this->mEnableClientCache = true;
}
/**
* Force the page to send nocache headers
* @since 1.38
*/
public function disableClientCache(): void {
$this->mEnableClientCache = false;
}
/**
* Whether the output might become publicly cached.
*
* @since 1.34
* @return bool
*/
public function couldBePublicCached() {
if ( !$this->cacheIsFinal ) {
// - The entry point handles its own caching and/or doesn't use OutputPage.
// (such as load.php, or MediaWiki\Rest\EntryPoint).
//
// - Or, we haven't finished processing the main part of the request yet
// (e.g. Action::show, SpecialPage::execute), and the state may still
// change via enableClientCache().
return true;
}
// e.g. various error-type pages disable all client caching
return $this->mEnableClientCache;
}
/**
* Set the expectation that cache control will not change after this point.
*
* This should be called after the main processing logic has completed
* (e.g. Action::show or SpecialPage::execute), but may be called
* before Skin output has started (OutputPage::output).
*
* @since 1.34
*/
public function considerCacheSettingsFinal() {
$this->cacheIsFinal = true;
}
/**
* Get the list of cookie names that will influence the cache
*
* @return array
*/
public function getCacheVaryCookies() {
if ( self::$cacheVaryCookies === null ) {
$config = $this->getConfig();
self::$cacheVaryCookies = array_values( array_unique( array_merge(
SessionManager::singleton()->getVaryCookies(),
[
'forceHTTPS',
],
$config->get( MainConfigNames::CacheVaryCookies )
) ) );
$this->getHookRunner()->onGetCacheVaryCookies( $this, self::$cacheVaryCookies );
}
return self::$cacheVaryCookies;
}
/**
* Check if the request has a cache-varying cookie header
* If it does, it's very important that we don't allow public caching
*
* @return bool
*/
public function haveCacheVaryCookies() {
$request = $this->getRequest();
foreach ( $this->getCacheVaryCookies() as $cookieName ) {
if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
wfDebug( __METHOD__ . ": found $cookieName" );
return true;
}
}
wfDebug( __METHOD__ . ': no cache-varying cookies found' );
return false;
}
/**
* Add an HTTP header that will have an influence on the cache
*
* @param string $header Header name
*/
public function addVaryHeader( $header ) {
if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
$this->mVaryHeader[$header] = null;
}
}
/**
* Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
* such as Accept-Encoding or Cookie
*
* @return string
*/
public function getVaryHeader() {
// If we vary on cookies, let's make sure it's always included here too.
if ( $this->getCacheVaryCookies() ) {
$this->addVaryHeader( 'Cookie' );
}
foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $_ ) {
$this->addVaryHeader( $header );
}
return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
}
/**
* Add an HTTP Link: header
*
* @param string $header Header value
*/
public function addLinkHeader( $header ) {
$this->mLinkHeader[] = $header;
}
/**
* Return a Link: header. Based on the values of $mLinkHeader.
*
* @return string|false
*/
public function getLinkHeader() {
if ( !$this->mLinkHeader ) {
return false;
}
return 'Link: ' . implode( ',', $this->mLinkHeader );
}
/**
* T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
*
* For example:
* /w/index.php?title=Main_page will vary based on Accept-Language; but
* /w/index.php?title=Main_page&variant=zh-cn will not.
*/
private function addAcceptLanguage() {
$title = $this->getTitle();
if ( !$title instanceof Title ) {
return;
}
$languageConverter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
->getLanguageConverter( $title->getPageLanguage() );
if ( !$this->getRequest()->getCheck( 'variant' ) && $languageConverter->hasVariants() ) {
$this->addVaryHeader( 'Accept-Language' );
}
}
/**
* Set the prevent-clickjacking flag.
*
* If true, will cause an X-Frame-Options header appropriate for
* edit pages to be sent. The header value is controlled by
* $wgEditPageFrameOptions. This is the default for special
* pages. If you display a CSRF-protected form on an ordinary view
* page, then you need to call this function.
*
* Setting this flag to false will turn off frame-breaking. This
* can be called from pages which do not contain any
* CSRF-protected HTML form.
*
* @param bool $enable If true, will cause an X-Frame-Options header
* appropriate for edit pages to be sent.
*
* @since 1.38
*/
public function setPreventClickjacking( bool $enable ) {
$this->mPreventClickjacking = $enable;
}
/**
* Get the prevent-clickjacking flag
*
* @since 1.24
* @return bool
*/
public function getPreventClickjacking() {
return $this->mPreventClickjacking;
}
/**
* Get the X-Frame-Options header value (without the name part), or false
* if there isn't one. This is used by Skin to determine whether to enable
* JavaScript frame-breaking, for clients that don't support X-Frame-Options.
*
* @return string|false
*/
public function getFrameOptions() {
$config = $this->getConfig();
if ( $config->get( MainConfigNames::BreakFrames ) ) {
return 'DENY';
} elseif ( $this->mPreventClickjacking && $config->get( MainConfigNames::EditPageFrameOptions ) ) {
return $config->get( MainConfigNames::EditPageFrameOptions );
}
return false;
}
private function getReportTo() {
$config = $this->getConfig();
$expiry = $config->get( MainConfigNames::ReportToExpiry );
if ( !$expiry ) {
return false;
}
$endpoints = $config->get( MainConfigNames::ReportToEndpoints );
if ( !$endpoints ) {
return false;
}
$output = [ 'max_age' => $expiry, 'endpoints' => [] ];
foreach ( $endpoints as $endpoint ) {
$output['endpoints'][] = [ 'url' => $endpoint ];
}
return json_encode( $output, JSON_UNESCAPED_SLASHES );
}
private function getFeaturePolicyReportOnly() {
$config = $this->getConfig();
$features = $config->get( MainConfigNames::FeaturePolicyReportOnly );
return implode( ';', $features );
}
/**
* Send cache control HTTP headers
*/
public function sendCacheControl() {
$response = $this->getRequest()->response();
$config = $this->getConfig();
$this->addVaryHeader( 'Cookie' );
$this->addAcceptLanguage();
# don't serve compressed data to clients who can't handle it
# maintain different caches for logged-in users and non-logged in ones
$response->header( $this->getVaryHeader() );
if ( $this->mEnableClientCache ) {
if ( !$config->get( MainConfigNames::UseCdn ) ) {
$privateReason = 'config';
} elseif ( $response->hasCookies() ) {
$privateReason = 'set-cookies';
// The client might use methods other than cookies to appear logged-in.
// E.g. HTTP headers, or query parameter tokens, OAuth, etc.
} elseif ( SessionManager::getGlobalSession()->isPersistent() ) {
$privateReason = 'session';
} elseif ( $this->isPrintable() ) {
$privateReason = 'printable';
} elseif ( $this->mCdnMaxage == 0 ) {
$privateReason = 'no-maxage';
} elseif ( $this->haveCacheVaryCookies() ) {
$privateReason = 'cache-vary-cookies';
} else {
$privateReason = false;
}
if ( $privateReason === false ) {
# We'll purge the proxy cache for anons explicitly, but require end user agents
# to revalidate against the proxy on each visit.
# IMPORTANT! The CDN needs to replace the Cache-Control header with
# Cache-Control: s-maxage=0, must-revalidate, max-age=0
wfDebug( __METHOD__ .
": local proxy caching; {$this->mLastModified} **", 'private' );
# start with a shorter timeout for initial testing
# header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
$response->header( 'Cache-Control: ' .
"s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
} else {
# We do want clients to cache if they can, but they *must* check for updates
# on revisiting the page.
wfDebug( __METHOD__ . ": private caching ($privateReason); {$this->mLastModified} **", 'private' );
$response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
$response->header( 'Cache-Control: private, must-revalidate, max-age=0' );
}
if ( $this->mLastModified ) {
$response->header( "Last-Modified: {$this->mLastModified}" );
}
} else {
wfDebug( __METHOD__ . ': no caching **', 'private' );
# In general, the absence of a last modified header should be enough to prevent
# the client from using its cache. We send a few other things just to make sure.
$response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
$response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
}
}
/**
* Transfer styles and JavaScript modules from skin.
*
* @param Skin $sk to load modules for
*/
public function loadSkinModules( $sk ) {
foreach ( $sk->getDefaultModules() as $group => $modules ) {
if ( $group === 'styles' ) {
foreach ( $modules as $moduleMembers ) {
$this->addModuleStyles( $moduleMembers );
}
} else {
$this->addModules( $modules );
}
}
}
/**
* Finally, all the text has been munged and accumulated into
* the object, let's actually output it:
*
* @param bool $return Set to true to get the result as a string rather than sending it
* @return string|null
*/
public function output( $return = false ) {
if ( $this->mDoNothing ) {
return $return ? '' : null;
}
$request = $this->getRequest();
$response = $request->response();
$config = $this->getConfig();
if ( $this->mRedirect != '' ) {
$services = MediaWikiServices::getInstance();
// Modern standards don't require redirect URLs to be absolute, but make it so just in case.
// Note that this doesn't actually guarantee an absolute URL: relative-path URLs are left intact.
$this->mRedirect = (string)$services->getUrlUtils()->expand( $this->mRedirect, PROTO_CURRENT );
$redirect = $this->mRedirect;
$code = $this->mRedirectCode;
$content = '';
if ( $this->getHookRunner()->onBeforePageRedirect( $this, $redirect, $code ) ) {
if ( $code == '301' || $code == '303' ) {
if ( !$config->get( MainConfigNames::DebugRedirects ) ) {
$response->statusHeader( (int)$code );
}
$this->mLastModified = wfTimestamp( TS_RFC2822 );
}
if ( $config->get( MainConfigNames::VaryOnXFP ) ) {
$this->addVaryHeader( 'X-Forwarded-Proto' );
}
$this->sendCacheControl();
$response->header( 'Content-Type: text/html; charset=UTF-8' );
if ( $config->get( MainConfigNames::DebugRedirects ) ) {
$url = htmlspecialchars( $redirect );
$content = "\n\n\n"
. "Redirect\n\n\n"
. "
\n"
. "\n\n";
if ( !$return ) {
print $content;
}
} else {
$response->header( 'Location: ' . $redirect );
}
}
return $return ? $content : null;
} elseif ( $this->mStatusCode ) {
$response->statusHeader( $this->mStatusCode );
}
# Buffer output; final headers may depend on later processing
ob_start();
$response->header( 'Content-language: ' .
MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
$linkHeader = $this->getLinkHeader();
if ( $linkHeader ) {
$response->header( $linkHeader );
}
// Prevent framing, if requested
$frameOptions = $this->getFrameOptions();
if ( $frameOptions ) {
$response->header( "X-Frame-Options: $frameOptions" );
}
// Get the Origin-Trial header values. This is used to enable Chrome Origin
// Trials: https://github.com/GoogleChrome/OriginTrials
$originTrials = $config->get( MainConfigNames::OriginTrials );
foreach ( $originTrials as $originTrial ) {
$response->header( "Origin-Trial: $originTrial", false );
}
$reportTo = $this->getReportTo();
if ( $reportTo ) {
$response->header( "Report-To: $reportTo" );
}
$featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
if ( $featurePolicyReportOnly ) {
$response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
}
if ( $this->mArticleBodyOnly ) {
$response->header( 'Content-type: ' . $config->get( MainConfigNames::MimeType ) . '; charset=UTF-8' );
if ( $this->cspOutputMode === self::CSP_HEADERS ) {
$this->CSP->sendHeaders();
}
echo $this->mBodytext;
} else {
// Enable safe mode if requested (T152169)
if ( $this->getRequest()->getBool( 'safemode' ) ) {
$this->disallowUserJs();
}
$sk = $this->getSkin();
$skinOptions = $sk->getOptions();
if ( $skinOptions['format'] === 'json' ) {
$response->header( 'Content-type: application/json; charset=UTF-8' );
return json_encode( [
$this->msg( 'skin-json-warning' )->escaped() => $this->msg( 'skin-json-warning-message' )->escaped()
] + $sk->getTemplateData() );
}
$response->header( 'Content-type: ' . $config->get( MainConfigNames::MimeType ) . '; charset=UTF-8' );
$this->loadSkinModules( $sk );
MWDebug::addModules( $this );
// Hook that allows last minute changes to the output page, e.g.
// adding of CSS or Javascript by extensions, adding CSP sources.
$this->getHookRunner()->onBeforePageDisplay( $this, $sk );
if ( $this->cspOutputMode === self::CSP_HEADERS ) {
$this->CSP->sendHeaders();
}
try {
$sk->outputPage();
} catch ( Exception $e ) {
ob_end_clean(); // bug T129657
throw $e;
}
}
try {
// This hook allows last minute changes to final overall output by modifying output buffer
$this->getHookRunner()->onAfterFinalPageOutput( $this );
} catch ( Exception $e ) {
ob_end_clean(); // bug T129657
throw $e;
}
$this->sendCacheControl();
if ( $return ) {
return ob_get_clean();
} else {
ob_end_flush();
return null;
}
}
/**
* Prepare this object to display an error page; disable caching and
* indexing, clear the current text and redirect, set the page's title
* and optionally a custom HTML title (content of the "" tag).
*
* @param string|Message|null $pageTitle Will be passed directly to setPageTitle()
* @param string|Message|false $htmlTitle Will be passed directly to setHTMLTitle();
* optional, if not passed the "" attribute will be
* based on $pageTitle
* @note Explicitly passing $pageTitle or $htmlTitle has been deprecated
* since 1.41; use ::setPageTitleMsg() and ::setHTMLTitle() instead.
*/
public function prepareErrorPage( $pageTitle = null, $htmlTitle = false ) {
if ( $pageTitle !== null || $htmlTitle !== false ) {
wfDeprecated( __METHOD__ . ' with explicit arguments', '1.41' );
if ( $pageTitle !== null ) {
$this->setPageTitle( $pageTitle );
}
if ( $htmlTitle !== false ) {
$this->setHTMLTitle( $htmlTitle );
}
}
$this->setRobotPolicy( 'noindex,nofollow' );
$this->setArticleRelated( false );
$this->disableClientCache();
$this->mRedirect = '';
$this->clearSubtitle();
$this->clearHTML();
}
/**
* Output a standard error page
*
* showErrorPage( 'titlemsg', 'pagetextmsg' );
* showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
* showErrorPage( 'titlemsg', $messageObject );
* showErrorPage( $titleMessageObject, $messageObject );
*
* @param string|MessageSpecifier $title Message key (string) for page title, or a MessageSpecifier
* @param string|MessageSpecifier $msg Message key (string) for page text, or a MessageSpecifier
* @param array $params Message parameters; ignored if $msg is a Message object
* @param PageReference|LinkTarget|string|null $returnto Page to show a return link to;
* defaults to the 'returnto' URL parameter
* @param string|null $returntoquery Query string for the return to link;
* defaults to the 'returntoquery' URL parameter
*/
public function showErrorPage(
$title, $msg, $params = [], $returnto = null, $returntoquery = null
) {
if ( !$title instanceof Message ) {
$title = $this->msg( $title );
}
$this->prepareErrorPage();
$this->setPageTitleMsg( $title );
if ( $msg instanceof Message ) {
if ( $params !== [] ) {
trigger_error( 'Argument ignored: $params. The message parameters argument '
. 'is discarded when the $msg argument is a Message object instead of '
. 'a string.', E_USER_NOTICE );
}
$this->addHTML( $msg->parseAsBlock() );
} else {
$this->addWikiMsgArray( $msg, $params );
}
$this->returnToMain( null, $returnto, $returntoquery );
}
/**
* Output a standard permission error page
*
* @param PermissionStatus $status
* @param string|null $action Action that was denied or null if unknown
*/
public function showPermissionStatus( PermissionStatus $status, $action = null ) {
Assert::precondition( !$status->isGood(), 'Status must have errors' );
$this->showPermissionInternal(
array_map( fn ( $msg ) => $this->msg( $msg ), $status->getMessages() ),
$action
);
}
/**
* Output a standard permission error page
*
* @deprecated since 1.43. Use ::showPermissionStatus instead
* @param array $errors Error message keys or [key, param...] arrays
* @param string|null $action Action that was denied or null if unknown
*/
public function showPermissionsErrorPage( array $errors, $action = null ) {
wfDeprecated( __METHOD__, '1.43' );
foreach ( $errors as $key => $error ) {
$errors[$key] = (array)$error;
}
$this->showPermissionInternal(
// @phan-suppress-next-line PhanParamTooFewUnpack Elements of $errors already annotated as non-empty
array_map( fn ( $err ) => $this->msg( ...$err ), $errors ),
$action
);
}
/**
* Helper for showPermissionStatus() and deprecated showPermissionsErrorMessage(),
* should be inlined when the deprecated method is removed.
*
* @param Message[] $messages
* @param string|null $action
*/
public function showPermissionInternal( array $messages, $action = null ) {
$services = MediaWikiServices::getInstance();
$groupPermissionsLookup = $services->getGroupPermissionsLookup();
// For some actions (read, edit, create and upload), display a "login to do this action"
// error if all of the following conditions are met:
// 1. the user is not logged in as a named user, and so cannot be added to groups
// 2. the only error is insufficient permissions (i.e. no block or something else)
// 3. the error can be avoided simply by logging in
if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
&& !$this->getUser()->isNamed() && count( $messages ) == 1
&& ( $messages[0]->getKey() == 'badaccess-groups' || $messages[0]->getKey() == 'badaccess-group0' )
&& ( $groupPermissionsLookup->groupHasPermission( 'user', $action )
|| $groupPermissionsLookup->groupHasPermission( 'autoconfirmed', $action ) )
) {
$displayReturnto = null;
# Due to T34276, if a user does not have read permissions,
# $this->getTitle() will just give Special:Badtitle, which is
# not especially useful as a returnto parameter. Use the title
# from the request instead, if there was one.
$request = $this->getRequest();
$returnto = Title::newFromText( $request->getText( 'title' ) );
if ( $action == 'edit' ) {
$msg = 'whitelistedittext';
$displayReturnto = $returnto;
} elseif ( $action == 'createpage' || $action == 'createtalk' ) {
$msg = 'nocreatetext';
} elseif ( $action == 'upload' ) {
$msg = 'uploadnologintext';
} else { # Read
$msg = 'loginreqpagetext';
$displayReturnto = Title::newMainPage();
}
$query = [];
if ( $returnto ) {
$query['returnto'] = $returnto->getPrefixedText();
if ( !$request->wasPosted() ) {
$returntoquery = $request->getValues();
unset( $returntoquery['title'] );
unset( $returntoquery['returnto'] );
unset( $returntoquery['returntoquery'] );
$query['returntoquery'] = wfArrayToCgi( $returntoquery );
}
}
$title = SpecialPage::getTitleFor( 'Userlogin' );
$linkRenderer = $services->getLinkRenderer();
$loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
$loginLink = $linkRenderer->makeKnownLink(
$title,
$this->msg( 'loginreqlink' )->text(),
[],
$query
);
$this->prepareErrorPage();
$this->setPageTitleMsg( $this->msg( 'loginreqtitle' ) );
$this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
# Don't return to a page the user can't read otherwise
# we'll end up in a pointless loop
if ( $displayReturnto && $this->getAuthority()->probablyCan( 'read', $displayReturnto ) ) {
$this->returnToMain( null, $displayReturnto );
}
} else {
$this->prepareErrorPage();
$this->setPageTitleMsg( $this->msg( 'permissionserrors' ) );
$this->addWikiTextAsInterface( $this->formatPermissionInternal( $messages, $action ) );
}
}
/**
* Display an error page indicating that a given version of MediaWiki is
* required to use it
*
* @param mixed $version The version of MediaWiki needed to use the page
*/
public function versionRequired( $version ) {
$this->prepareErrorPage();
$this->setPageTitleMsg(
$this->msg( 'versionrequired' )->plaintextParams( $version )
);
$this->addWikiMsg( 'versionrequiredtext', $version );
$this->returnToMain();
}
/**
* Format permission $status obtained from Authority for display.
*
* @param PermissionStatus $status
* @param-taint $status none
* @param string|null $action that was denied or null if unknown
* @return string
* @return-taint tainted
*/
public function formatPermissionStatus( PermissionStatus $status, ?string $action = null ): string {
if ( $status->isGood() ) {
return '';
}
return $this->formatPermissionInternal(
array_map( fn ( $msg ) => $this->msg( $msg ), $status->getMessages() ),
$action
);
}
/**
* Format a list of error messages
*
* @deprecated since 1.36. Use ::formatPermissionStatus instead
* @param array $errors Array of arrays returned by PermissionManager::getPermissionErrors
* @param-taint $errors none
* @phan-param non-empty-array[] $errors
* @param string|null $action Action that was denied or null if unknown
* @return string The wikitext error-messages, formatted into a list.
* @return-taint tainted
*/
public function formatPermissionsErrorMessage( array $errors, $action = null ) {
wfDeprecated( __METHOD__, '1.36' );
return $this->formatPermissionInternal(
// @phan-suppress-next-line PhanParamTooFewUnpack Elements of $errors already annotated as non-empty
array_map( fn ( $err ) => $this->msg( ...$err ), $errors ),
$action
);
}
/**
* Helper for formatPermissionStatus() and deprecated formatPermissionsErrorMessage(),
* should be inlined when the deprecated method is removed.
*
* @param Message[] $messages
* @param-taint $messages none
* @param string|null $action
* @return string
* @return-taint tainted
*
* @suppress SecurityCheck-DoubleEscaped Working with plain text, not HTML
*/
private function formatPermissionInternal( array $messages, $action = null ) {
if ( $action == null ) {
$text = $this->msg( 'permissionserrorstext', count( $messages ) )->plain() . "\n\n";
} else {
$action_desc = $this->msg( "action-$action" )->plain();
$text = $this->msg(
'permissionserrorstext-withaction',
count( $messages ),
$action_desc
)->plain() . "\n\n";
}
if ( count( $messages ) > 1 ) {
$text .= Html::openElement( 'ul', [ 'class' => 'permissions-errors' ] );
foreach ( $messages as $message ) {
$text .= Html::rawElement(
'li',
[ 'class' => 'mw-permissionerror-' . $message->getKey() ],
$message->plain()
);
}
$text .= Html::closeElement( 'ul' );
} else {
$text .= Html::openElement( 'div', [ 'class' => 'permissions-errors' ] );
$text .= Html::rawElement(
'div',
[ 'class' => 'mw-permissionerror-' . $messages[ 0 ]->getKey() ],
$messages[ 0 ]->plain()
);
$text .= Html::closeElement( 'div' );
}
return $text;
}
/**
* Show a warning about replica DB lag
*
* If the lag is higher than $wgDatabaseReplicaLagCritical seconds,
* then the warning is a bit more obvious. If the lag is
* lower than $wgDatabaseReplicaLagWarning, then no warning is shown.
*
* @param int $lag Replica lag
*/
public function showLagWarning( $lag ) {
$config = $this->getConfig();
if ( $lag >= $config->get( MainConfigNames::DatabaseReplicaLagWarning ) ) {
$lag = floor( $lag ); // floor to avoid nano seconds to display
$message = $lag < $config->get( MainConfigNames::DatabaseReplicaLagCritical )
? 'lag-warn-normal'
: 'lag-warn-high';
// For grep: mw-lag-warn-normal, mw-lag-warn-high
$wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
$this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
}
}
/**
* Output an error page
*
* @deprecated since 1.43 Use showErrorPage() instead
* @param string $message Error to output. Must be escaped for HTML.
*/
public function showFatalError( $message ) {
wfDeprecated( __METHOD__, '1.43' );
$this->prepareErrorPage();
$this->setPageTitleMsg( $this->msg( 'internalerror' ) );
$this->addHTML( $message );
}
/**
* Add a "return to" link pointing to a specified title
*
* @param LinkTarget $title Title to link
* @param array $query Query string parameters
* @param string|null $text Text of the link (input is not escaped)
* @param array $options Options array to pass to Linker
*/
public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
$linkRenderer = MediaWikiServices::getInstance()
->getLinkRendererFactory()->createFromLegacyOptions( $options );
$link = $this->msg( 'returnto' )->rawParams(
$linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
$this->addHTML( "
{$link}
\n" );
}
/**
* Add a "return to" link pointing to a specified title,
* or the title indicated in the request, or else the main page
*
* @param mixed|null $unused
* @param PageReference|LinkTarget|string|null $returnto Page to return to
* @param string|null $returntoquery Query string for the return to link
*/
public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
$returnto ??= $this->getRequest()->getText( 'returnto' );
$returntoquery ??= $this->getRequest()->getText( 'returntoquery' );
if ( $returnto === '' ) {
$returnto = Title::newMainPage();
}
if ( is_object( $returnto ) ) {
$linkTarget = TitleValue::castPageToLinkTarget( $returnto );
} else {
$linkTarget = Title::newFromText( $returnto );
}
// We don't want people to return to external interwiki. That
// might potentially be used as part of a phishing scheme
if ( !is_object( $linkTarget ) || $linkTarget->isExternal() ) {
$linkTarget = Title::newMainPage();
}
$this->addReturnTo( $linkTarget, wfCgiToArray( $returntoquery ) );
}
/**
* Output a standard "wait for takeover" warning
*
* This is useful for extensions which are hooking an action and
* suppressing its normal output so it can be taken over with JS.
*
* showPendingTakeover( 'url', 'pagetextmsg' );
* showPendingTakeover( 'url', 'pagetextmsg', [ 'param1', 'param2' ] );
* showPendingTakeover( 'url', $messageObject );
*
* @param string $fallbackUrl URL to redirect to if the user doesn't have JavaScript
* or ResourceLoader available; this should ideally be to a page that provides similar
* functionality without requiring JavaScript
* @param string|MessageSpecifier $msg Message key (string) for page text, or a MessageSpecifier
* @param mixed ...$params Message parameters; ignored if $msg is a Message object
*/
public function showPendingTakeover(
$fallbackUrl, $msg, ...$params
) {
if ( $msg instanceof Message ) {
if ( $params !== [] ) {
trigger_error( 'Argument ignored: $params. The message parameters argument '
. 'is discarded when the $msg argument is a Message object instead of '
. 'a string.', E_USER_NOTICE );
}
$this->addHTML( $msg->parseAsBlock() );
} else {
$this->addHTML( $this->msg( $msg, ...$params )->parseAsBlock() );
}
// Redirect if the user has no JS (