27 use Wikimedia\RelPath;
28 use Wikimedia\WrappedString;
29 use Wikimedia\WrappedStringList;
48 protected $mMetatags = [];
51 protected $mLinktags = [];
54 protected $mCanonicalUrl =
false;
58 private $mPageTitle =
'';
67 private $displayTitle;
73 public $mBodytext =
'';
76 private $mHTMLtitle =
'';
82 private $mIsArticle =
false;
85 private $mIsArticleRelated =
true;
88 private $mHasCopyright =
false;
94 private $mPrintable =
false;
100 private $mSubtitle = [];
103 public $mRedirect =
'';
106 protected $mStatusCode;
112 protected $mLastModified =
'';
115 protected $mCategoryLinks = [];
118 protected $mCategories = [
124 protected $mIndicators = [];
127 private $mLanguageLinks = [];
135 private $mScripts =
'';
138 protected $mInlineStyles =
'';
144 public $mPageLinkTitle =
'';
147 protected $mHeadItems = [];
150 protected $mAdditionalBodyClasses = [];
153 protected $mModules = [];
156 protected $mModuleStyles = [];
159 protected $mResourceLoader;
165 private $rlClientContext;
168 private $rlExemptStyleModules;
171 protected $mJsConfigVars = [];
174 protected $mTemplateIds = [];
177 protected $mImageTimeKeys = [];
180 public $mRedirectCode =
'';
182 protected $mFeedLinksAppendQuery =
null;
189 protected $mAllowedModules = [
194 protected $mDoNothing =
false;
199 protected $mContainsNewMagic = 0;
205 protected $mParserOptions =
null;
212 private $mFeedLinks = [];
215 protected $mEnableClientCache =
true;
218 private $mArticleBodyOnly =
false;
221 protected $mNewSectionLink =
false;
224 protected $mHideNewSectionLink =
false;
231 public $mNoGallery =
false;
234 protected $mCdnMaxage = 0;
236 protected $mCdnMaxageLimit = INF;
243 protected $mPreventClickjacking =
true;
246 private $mRevisionId =
null;
249 private $mRevisionTimestamp =
null;
252 protected $mFileVersion =
null;
262 protected $styles = [];
264 private $mIndexPolicy =
'index';
265 private $mFollowPolicy =
'follow';
271 private $mVaryHeader = [
272 'Accept-Encoding' => [
'match=gzip' ],
281 private $mRedirectedFrom =
null;
286 private $mProperties = [];
291 private $mTarget =
null;
296 private $mEnableTOC =
false;
301 private $copyrightUrl;
304 private $limitReportJSData = [];
307 private $contentOverrides = [];
310 private $contentOverrideCallbacks = [];
315 private $mLinkHeader = [];
325 private static $cacheVaryCookies =
null;
343 public function redirect( $url, $responsecode =
'302' ) {
344 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
345 $this->mRedirect = str_replace(
"\n",
'', $url );
346 $this->mRedirectCode = $responsecode;
354 public function getRedirect() {
355 return $this->mRedirect;
366 public function setCopyrightUrl( $url ) {
367 $this->copyrightUrl = $url;
375 public function setStatusCode( $statusCode ) {
376 $this->mStatusCode = $statusCode;
386 function addMeta(
$name, $val ) {
387 array_push( $this->mMetatags, [
$name, $val ] );
396 public function getMetaTags() {
397 return $this->mMetatags;
407 function addLink(
array $linkarr ) {
408 array_push( $this->mLinktags, $linkarr );
417 public function getLinkTags() {
418 return $this->mLinktags;
426 function setCanonicalUrl( $url ) {
427 $this->mCanonicalUrl = $url;
437 public function getCanonicalUrl() {
438 return $this->mCanonicalUrl;
448 function addScript( $script ) {
449 $this->mScripts .= $script;
460 public function addScriptFile(
$file, $unused =
null ) {
461 if ( substr(
$file, 0, 1 ) !==
'/' && !preg_match(
'#^[a-z]*://#i',
$file ) ) {
468 $this->addScript( Html::linkedScript(
$file, $this->getCSPNonce() ) );
477 public function addInlineScript( $script ) {
478 $this->mScripts .= Html::inlineScript(
"\n$script\n", $this->getCSPNonce() ) .
"\n";
489 protected function filterModules(
array $modules, $position =
null,
493 $filteredModules = [];
499 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
500 $this->warnModuleTargetFilter( $module->getName() );
503 $filteredModules[] = $val;
506 return $filteredModules;
509 private function warnModuleTargetFilter( $moduleName ) {
510 static $warnings = [];
511 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
514 $warnings[$this->mTarget][$moduleName] =
true;
515 $this->getResourceLoader()->getLogger()->debug(
516 'Module "{module}" not loadable on target "{target}".',
518 'module' => $moduleName,
519 'target' => $this->mTarget,
533 public function getModules(
$filter =
false, $position =
null, $param =
'mModules',
536 $modules = array_values( array_unique( $this->$param ) );
547 public function addModules(
$modules ) {
548 $this->mModules = array_merge( $this->mModules, (
array)
$modules );
555 public function getModuleScripts() {
567 public function getModuleStyles(
$filter =
false, $position =
null ) {
568 return $this->getModules(
$filter,
null,
'mModuleStyles',
582 public function addModuleStyles(
$modules ) {
583 $this->mModuleStyles = array_merge( $this->mModuleStyles, (
array)
$modules );
589 public function getTarget() {
590 return $this->mTarget;
598 public function setTarget( $target ) {
599 $this->mTarget = $target;
610 if ( !$this->contentOverrides ) {
612 $this->addContentOverrideCallback(
function (
LinkTarget $target ) {
614 return $this->contentOverrides[$key] ??
null;
619 $this->contentOverrides[$key] =
$content;
629 public function addContentOverrideCallback( callable $callback ) {
630 $this->contentOverrideCallbacks[] = $callback;
638 function getHeadItemsArray() {
639 return $this->mHeadItems;
664 public function addHeadItems( $values ) {
665 $this->mHeadItems = array_merge( $this->mHeadItems, (
array)$values );
674 public function hasHeadItem(
$name ) {
675 return isset( $this->mHeadItems[
$name] );
684 public function addBodyClasses( $classes ) {
685 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (
array)$classes );
695 public function setArticleBodyOnly( $only ) {
696 $this->mArticleBodyOnly = $only;
704 public function getArticleBodyOnly() {
705 return $this->mArticleBodyOnly;
726 public function getProperty(
$name ) {
727 return $this->mProperties[
$name] ??
null;
741 public function checkLastModified( $timestamp ) {
742 if ( !$timestamp || $timestamp ==
'19700101000000' ) {
743 wfDebug( __METHOD__ .
": CACHE DISABLED, NO TIMESTAMP\n" );
747 if ( !$config->
get(
'CachePages' ) ) {
748 wfDebug( __METHOD__ .
": CACHE DISABLED\n" );
754 'page' => $timestamp,
755 'user' => $this->
getUser()->getTouched(),
756 'epoch' => $config->
get(
'CacheEpoch' )
758 if ( $config->
get(
'UseSquid' ) ) {
759 $modifiedTimes[
'sepoch'] =
wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
761 $config->
get(
'SquidMaxage' )
764 Hooks::run(
'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
766 $maxModified = max( $modifiedTimes );
767 $this->mLastModified =
wfTimestamp( TS_RFC2822, $maxModified );
769 $clientHeader = $this->
getRequest()->getHeader(
'If-Modified-Since' );
770 if ( $clientHeader ===
false ) {
771 wfDebug( __METHOD__ .
": client did not send If-Modified-Since header",
'private' );
775 # IE sends sizes after the date like this:
776 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
777 # this breaks strtotime().
778 $clientHeader = preg_replace(
'/;.*$/',
'', $clientHeader );
780 Wikimedia\suppressWarnings();
781 $clientHeaderTime = strtotime( $clientHeader );
782 Wikimedia\restoreWarnings();
783 if ( !$clientHeaderTime ) {
785 .
": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
788 $clientHeaderTime =
wfTimestamp( TS_MW, $clientHeaderTime );
793 if ( $info !==
'' ) {
799 wfDebug( __METHOD__ .
": client sent If-Modified-Since: " .
800 wfTimestamp( TS_ISO_8601, $clientHeaderTime ),
'private' );
801 wfDebug( __METHOD__ .
": effective Last-Modified: " .
802 wfTimestamp( TS_ISO_8601, $maxModified ),
'private' );
803 if ( $clientHeaderTime < $maxModified ) {
804 wfDebug( __METHOD__ .
": STALE, $info",
'private' );
809 # Give a 304 Not Modified response code and disable body output
810 wfDebug( __METHOD__ .
": NOT MODIFIED, $info",
'private' );
811 ini_set(
'zlib.output_compression', 0 );
812 $this->
getRequest()->response()->statusHeader( 304 );
813 $this->sendCacheControl();
829 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
834 return $reqTime - $maxAge;
843 public function setLastModified( $timestamp ) {
844 $this->mLastModified =
wfTimestamp( TS_RFC2822, $timestamp );
855 public function setRobotPolicy( $policy ) {
858 if ( isset( $policy[
'index'] ) ) {
859 $this->setIndexPolicy( $policy[
'index'] );
861 if ( isset( $policy[
'follow'] ) ) {
862 $this->setFollowPolicy( $policy[
'follow'] );
873 public function setIndexPolicy( $policy ) {
874 $policy = trim( $policy );
875 if ( in_array( $policy, [
'index',
'noindex' ] ) ) {
876 $this->mIndexPolicy = $policy;
887 public function setFollowPolicy( $policy ) {
888 $policy = trim( $policy );
889 if ( in_array( $policy, [
'follow',
'nofollow' ] ) ) {
890 $this->mFollowPolicy = $policy;
900 public function setHTMLTitle(
$name ) {
901 if (
$name instanceof Message ) {
904 $this->mHTMLtitle =
$name;
913 public function getHTMLTitle() {
914 return $this->mHTMLtitle;
922 public function setRedirectedFrom(
$t ) {
923 $this->mRedirectedFrom =
$t;
938 public function setPageTitle(
$name ) {
939 if (
$name instanceof Message ) {
943 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
944 # but leave "<i>foobar</i>" alone
945 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
$name ) );
946 $this->mPageTitle = $nameWithTags;
948 # change "<i>foo&bar</i>" to "foo&bar"
950 $this->
msg(
'pagetitle' )->plaintextParams( Sanitizer::stripAllTags( $nameWithTags ) )
951 ->inContentLanguage()
960 public function getPageTitle() {
961 return $this->mPageTitle;
971 public function setDisplayTitle(
$html ) {
972 $this->displayTitle =
$html;
983 public function getDisplayTitle() {
984 $html = $this->displayTitle;
985 if (
$html ===
null ) {
989 return Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
$html ) );
998 public function getUnprefixedDisplayTitle() {
999 $text = $this->getDisplayTitle();
1000 $nsPrefix = $this->
getTitle()->getNsText() .
':';
1001 $prefix = preg_quote( $nsPrefix,
'/' );
1003 return preg_replace(
"/^$prefix/i",
'', $text );
1011 public function setTitle(
Title $t ) {
1020 public function setSubtitle( $str ) {
1021 $this->clearSubtitle();
1022 $this->addSubtitle( $str );
1030 public function addSubtitle( $str ) {
1031 if ( $str instanceof Message ) {
1032 $this->mSubtitle[] = $str->setContext( $this->
getContext() )->parse();
1034 $this->mSubtitle[] = $str;
1047 if (
$title->isRedirect() ) {
1048 $query[
'redirect'] =
'no';
1050 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1062 $this->addSubtitle( self::buildBacklinkSubtitle(
$title,
$query ) );
1068 public function clearSubtitle() {
1069 $this->mSubtitle = [];
1077 public function getSubtitle() {
1078 return implode(
"<br />\n\t\t\t\t", $this->mSubtitle );
1085 public function setPrintable() {
1086 $this->mPrintable =
true;
1094 public function isPrintable() {
1095 return $this->mPrintable;
1101 public function disable() {
1102 $this->mDoNothing =
true;
1110 public function isDisabled() {
1111 return $this->mDoNothing;
1119 public function showNewSectionLink() {
1120 return $this->mNewSectionLink;
1128 public function forceHideNewSectionLink() {
1129 return $this->mHideNewSectionLink;
1140 public function setSyndicated( $show =
true ) {
1142 $this->setFeedAppendQuery(
false );
1144 $this->mFeedLinks = [];
1154 protected function getAdvertisedFeedTypes() {
1155 if ( $this->
getConfig()->
get(
'Feed' ) ) {
1156 return $this->
getConfig()->get(
'AdvertisedFeedTypes' );
1171 public function setFeedAppendQuery( $val ) {
1172 $this->mFeedLinks = [];
1174 foreach ( $this->getAdvertisedFeedTypes()
as $type ) {
1176 if ( is_string( $val ) ) {
1189 public function addFeedLink( $format, $href ) {
1190 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1191 $this->mFeedLinks[$format] = $href;
1199 public function isSyndicated() {
1200 return count( $this->mFeedLinks ) > 0;
1207 public function getSyndicationLinks() {
1208 return $this->mFeedLinks;
1216 public function getFeedAppendQuery() {
1217 return $this->mFeedLinksAppendQuery;
1227 public function setArticleFlag( $newVal ) {
1228 $this->mIsArticle = $newVal;
1230 $this->mIsArticleRelated = $newVal;
1240 public function isArticle() {
1241 return $this->mIsArticle;
1250 public function setArticleRelated( $newVal ) {
1251 $this->mIsArticleRelated = $newVal;
1253 $this->mIsArticle =
false;
1262 public function isArticleRelated() {
1263 return $this->mIsArticleRelated;
1271 public function setCopyright( $hasCopyright ) {
1272 $this->mHasCopyright = $hasCopyright;
1284 public function showsCopyright() {
1285 return $this->isArticle() || $this->mHasCopyright;
1294 public function addLanguageLinks(
array $newLinkArray ) {
1295 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1304 public function setLanguageLinks(
array $newLinkArray ) {
1305 $this->mLanguageLinks = $newLinkArray;
1313 public function getLanguageLinks() {
1314 return $this->mLanguageLinks;
1322 public function addCategoryLinks(
array $categories ) {
1323 if ( !$categories ) {
1327 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1329 # Set all the values to 'normal'.
1330 $categories = array_fill_keys( array_keys( $categories ),
'normal' );
1332 # Mark hidden categories
1333 foreach (
$res as $row ) {
1334 if ( isset( $row->pp_value ) ) {
1335 $categories[$row->page_title] =
'hidden';
1340 $outputPage = $this;
1341 # Add the remaining categories to the skin
1343 'OutputPageMakeCategoryLinks',
1344 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1346 $services = MediaWikiServices::getInstance();
1348 foreach ( $categories
as $category =>
$type ) {
1350 $category = (
string)$category;
1351 $origcategory = $category;
1356 $services->getContentLanguage()->findVariantLink( $category,
$title,
true );
1357 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1360 $text =
$services->getContentLanguage()->convertHtml(
$title->getText() );
1371 protected function addCategoryLinksToLBAndGetResult(
array $categories ) {
1372 # Add the links to a LinkBatch
1377 # Fetch existence plus the hiddencat property
1379 $fields = array_merge(
1381 [
'page_namespace',
'page_title',
'pp_value' ]
1384 $res =
$dbr->select( [
'page',
'page_props' ],
1386 $lb->constructSet(
'page',
$dbr ),
1389 [
'page_props' => [
'LEFT JOIN', [
1390 'pp_propname' =>
'hiddencat',
1395 # Add the results to the link cache
1396 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1397 $lb->addResultToCache( $linkCache,
$res );
1407 public function setCategoryLinks(
array $categories ) {
1408 $this->mCategoryLinks = [];
1409 $this->addCategoryLinks( $categories );
1420 public function getCategoryLinks() {
1421 return $this->mCategoryLinks;
1433 public function getCategories(
$type =
'all' ) {
1434 if (
$type ===
'all' ) {
1435 $allCategories = [];
1436 foreach ( $this->mCategories
as $categories ) {
1437 $allCategories = array_merge( $allCategories, $categories );
1439 return $allCategories;
1441 if ( !isset( $this->mCategories[
$type] ) ) {
1442 throw new InvalidArgumentException(
'Invalid category type given: ' .
$type );
1444 return $this->mCategories[
$type];
1456 public function setIndicators(
array $indicators ) {
1457 $this->mIndicators = $indicators + $this->mIndicators;
1459 ksort( $this->mIndicators );
1470 public function getIndicators() {
1471 return $this->mIndicators;
1482 public function addHelpLink( $to, $overrideBaseUrl =
false ) {
1483 $this->addModuleStyles(
'mediawiki.helplink' );
1484 $text = $this->
msg(
'helppage-top-gethelp' )->escaped();
1486 if ( $overrideBaseUrl ) {
1489 $toUrlencoded =
wfUrlencode( str_replace(
' ',
'_', $to ) );
1490 $helpUrl =
"//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1493 $link = Html::rawElement(
1497 'target' =>
'_blank',
1498 'class' =>
'mw-helplink',
1503 $this->setIndicators( [
'mw-helplink' =>
$link ] );
1514 public function disallowUserJs() {
1515 $this->reduceAllowedModules(
1522 if ( $this->
getConfig()->
get(
'AllowSiteCSSOnRestrictedPages' ) ) {
1527 $this->reduceAllowedModules(
1539 public function getAllowedModules(
$type ) {
1541 return min( array_values( $this->mAllowedModules ) );
1556 public function reduceAllowedModules(
$type, $level ) {
1557 $this->mAllowedModules[
$type] = min( $this->getAllowedModules(
$type ), $level );
1565 public function prependHTML( $text ) {
1566 $this->mBodytext = $text . $this->mBodytext;
1574 public function addHTML( $text ) {
1575 $this->mBodytext .= $text;
1587 public function addElement( $element,
array $attribs = [], $contents =
'' ) {
1588 $this->addHTML( Html::element( $element,
$attribs, $contents ) );
1594 public function clearHTML() {
1595 $this->mBodytext =
'';
1603 public function getHTML() {
1604 return $this->mBodytext;
1614 public function parserOptions(
$options =
null ) {
1616 wfDeprecated( __METHOD__ .
' with non-null $options',
'1.31' );
1623 $anonPO->setAllowUnsafeRawHtml(
false );
1624 if ( !
$options->matches( $anonPO ) ) {
1630 if ( !$this->mParserOptions ) {
1631 if ( !$this->
getUser()->isSafeToLoad() ) {
1636 $po->setAllowUnsafeRawHtml(
false );
1637 $po->isBogus =
true;
1645 $this->mParserOptions->setAllowUnsafeRawHtml(
false );
1651 return wfSetVar( $this->mParserOptions,
null,
true );
1664 public function setRevisionId( $revid ) {
1665 $val = is_null( $revid ) ?
null : intval( $revid );
1666 return wfSetVar( $this->mRevisionId, $val,
true );
1674 public function getRevisionId() {
1675 return $this->mRevisionId;
1685 public function setRevisionTimestamp( $timestamp ) {
1686 return wfSetVar( $this->mRevisionTimestamp, $timestamp,
true );
1695 public function getRevisionTimestamp() {
1696 return $this->mRevisionTimestamp;
1705 public function setFileVersion(
$file ) {
1708 $val = [
'time' =>
$file->getTimestamp(),
'sha1' =>
$file->getSha1() ];
1710 return wfSetVar( $this->mFileVersion, $val,
true );
1718 public function getFileVersion() {
1719 return $this->mFileVersion;
1728 public function getTemplateIds() {
1729 return $this->mTemplateIds;
1738 public function getFileSearchOptions() {
1739 return $this->mImageTimeKeys;
1754 public function addWikiText( $text, $linestart =
true, $interface =
true ) {
1760 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
false, $interface );
1779 public function addWikiTextAsInterface(
1788 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
true );
1804 public function wrapWikiTextAsInterface(
1805 $wrapperClass, $text
1807 $this->addWikiTextTitleInternal(
1829 public function addWikiTextAsContent(
1838 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
false );
1850 public function addWikiTextWithTitle( $text,
Title $title, $linestart =
true ) {
1852 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
false,
false );
1865 function addWikiTextTitleTidy( $text,
Title $title, $linestart =
true ) {
1867 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
false );
1878 public function addWikiTextTidy( $text, $linestart =
true ) {
1884 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
false );
1906 public function addWikiTextTitle( $text,
Title $title, $linestart,
1907 $tidy =
false, $interface =
false
1910 return $this->addWikiTextTitleInternal( $text,
$title, $linestart, $tidy, $interface );
1929 private function addWikiTextTitleInternal(
1930 $text,
Title $title, $linestart, $tidy, $interface, $wrapperClass =
null
1936 $parserOutput = $this->parseInternal(
1937 $text,
$title, $linestart, $tidy, $interface,
null
1940 $this->addParserOutput( $parserOutput, [
1941 'enableSectionEditLinks' =>
false,
1942 'wrapperDivClass' => $wrapperClass ??
'',
1954 public function addParserOutputMetadata(
ParserOutput $parserOutput ) {
1955 $this->mLanguageLinks =
1963 $this->enableClientCache(
false );
1966 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->
getHeadItems() );
1967 $this->addModules( $parserOutput->
getModules() );
1970 $this->mPreventClickjacking = $this->mPreventClickjacking
1975 if ( isset( $this->mTemplateIds[$ns] ) ) {
1976 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1978 $this->mTemplateIds[$ns] = $dbks;
1983 $this->mImageTimeKeys[$dbk] =
$data;
1987 $parserOutputHooks = $this->
getConfig()->get(
'ParserOutputHooks' );
1990 if ( isset( $parserOutputHooks[$hookName] ) ) {
1991 $parserOutputHooks[$hookName]( $this, $parserOutput,
$data );
1997 $this->enableOOUI();
2001 if ( !$this->limitReportJSData ) {
2009 $outputPage = $this;
2010 Hooks::run(
'LanguageLinks', [ $this->
getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
2018 $this->mEnableTOC =
true;
2030 public function addParserOutputContent(
ParserOutput $parserOutput, $poOptions = [] ) {
2031 $this->addParserOutputText( $parserOutput, $poOptions );
2033 $this->addModules( $parserOutput->
getModules() );
2046 public function addParserOutputText(
ParserOutput $parserOutput, $poOptions = [] ) {
2047 $text = $parserOutput->
getText( $poOptions );
2049 $outputPage = $this;
2051 $this->addHTML( $text );
2060 function addParserOutput(
ParserOutput $parserOutput, $poOptions = [] ) {
2061 $this->addParserOutputMetadata( $parserOutput );
2062 $this->addParserOutputText( $parserOutput, $poOptions );
2070 public function addTemplate( &
$template ) {
2092 public function parse( $text, $linestart =
true, $interface =
false, $language =
null ) {
2094 return $this->parseInternal(
2095 $text, $this->
getTitle(), $linestart,
false, $interface, $language
2097 'enableSectionEditLinks' =>
false,
2112 public function parseAsContent( $text, $linestart =
true ) {
2113 return $this->parseInternal(
2114 $text, $this->
getTitle(), $linestart,
true,
false,
null
2116 'enableSectionEditLinks' =>
false,
2117 'wrapperDivClass' =>
''
2133 public function parseAsInterface( $text, $linestart =
true ) {
2134 return $this->parseInternal(
2135 $text, $this->
getTitle(), $linestart,
true,
true,
null
2137 'enableSectionEditLinks' =>
false,
2138 'wrapperDivClass' =>
''
2156 public function parseInlineAsInterface( $text, $linestart =
true ) {
2157 return Parser::stripOuterParagraph(
2158 $this->parseAsInterface( $text, $linestart )
2175 public function parseInline( $text, $linestart =
true, $interface =
false ) {
2177 $parsed = $this->parseInternal(
2178 $text, $this->
getTitle(), $linestart,
false, $interface,
null
2180 'enableSectionEditLinks' =>
false,
2181 'wrapperDivClass' =>
'',
2183 return Parser::stripOuterParagraph( $parsed );
2200 private function parseInternal( $text,
$title, $linestart, $tidy, $interface, $language ) {
2203 if ( is_null(
$title ) ) {
2204 throw new MWException(
'Empty $mTitle in ' . __METHOD__ );
2207 $popts = $this->parserOptions();
2208 $oldTidy = $popts->setTidy( $tidy );
2209 $oldInterface = $popts->setInterfaceMessage( (
bool)$interface );
2211 if ( $language !==
null ) {
2212 $oldLang = $popts->setTargetLanguage( $language );
2215 $parserOutput =
$wgParser->getFreshParser()->parse(
2217 $linestart,
true, $this->mRevisionId
2220 $popts->setTidy( $oldTidy );
2221 $popts->setInterfaceMessage( $oldInterface );
2223 if ( $language !==
null ) {
2224 $popts->setTargetLanguage( $oldLang );
2227 return $parserOutput;
2235 public function setCdnMaxage( $maxage ) {
2236 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2248 public function lowerCdnMaxage( $maxage ) {
2249 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2250 $this->setCdnMaxage( $this->mCdnMaxage );
2265 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2267 $maxTTL = $maxTTL ?: $this->
getConfig()->get(
'SquidMaxage' );
2269 if ( $mtime ===
null || $mtime ===
false ) {
2273 $age = MWTimestamp::time() -
wfTimestamp( TS_UNIX, $mtime );
2274 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2275 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2277 $this->lowerCdnMaxage( (
int)$adaptiveTTL );
2287 public function enableClientCache( $state ) {
2288 return wfSetVar( $this->mEnableClientCache, $state );
2296 function getCacheVaryCookies() {
2297 if ( self::$cacheVaryCookies ===
null ) {
2299 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2300 SessionManager::singleton()->getVaryCookies(),
2304 $config->
get(
'CacheVaryCookies' )
2306 Hooks::run(
'GetCacheVaryCookies', [ $this, &self::$cacheVaryCookies ] );
2308 return self::$cacheVaryCookies;
2317 function haveCacheVaryCookies() {
2319 foreach ( $this->getCacheVaryCookies()
as $cookieName ) {
2320 if (
$request->getCookie( $cookieName,
'',
'' ) !==
'' ) {
2321 wfDebug( __METHOD__ .
": found $cookieName\n" );
2325 wfDebug( __METHOD__ .
": no cache-varying cookies found\n" );
2337 public function addVaryHeader(
$header,
array $option =
null ) {
2338 if ( !array_key_exists(
$header, $this->mVaryHeader ) ) {
2339 $this->mVaryHeader[
$header] = [];
2341 if ( !is_array( $option ) ) {
2345 array_unique( array_merge( $this->mVaryHeader[
$header], $option ) );
2354 public function getVaryHeader() {
2356 if ( $this->getCacheVaryCookies() ) {
2357 $this->addVaryHeader(
'Cookie' );
2360 foreach ( SessionManager::singleton()->getVaryHeaders()
as $header =>
$options ) {
2363 return 'Vary: ' . implode(
', ', array_keys( $this->mVaryHeader ) );
2371 public function addLinkHeader(
$header ) {
2372 $this->mLinkHeader[] =
$header;
2380 public function getLinkHeader() {
2381 if ( !$this->mLinkHeader ) {
2385 return 'Link: ' . implode(
',', $this->mLinkHeader );
2395 public function getKeyHeader() {
2398 $cvCookies = $this->getCacheVaryCookies();
2400 $cookiesOption = [];
2401 foreach ( $cvCookies
as $cookieName ) {
2402 $cookiesOption[] =
'param=' . $cookieName;
2404 $this->addVaryHeader(
'Cookie', $cookiesOption );
2406 foreach ( SessionManager::singleton()->getVaryHeaders()
as $header =>
$options ) {
2411 foreach ( $this->mVaryHeader
as $header => $option ) {
2413 if ( is_array( $option ) &&
count( $option ) > 0 ) {
2414 $newheader .=
';' . implode(
';', $option );
2416 $headers[] = $newheader;
2418 $key =
'Key: ' . implode(
',', $headers );
2430 private function addAcceptLanguage() {
2432 if ( !$title instanceof
Title ) {
2437 if ( !$this->
getRequest()->getCheck(
'variant' ) &&
$lang->hasVariants() ) {
2438 $variants =
$lang->getVariants();
2440 foreach ( $variants
as $variant ) {
2441 if ( $variant ===
$lang->getCode() ) {
2455 $aloption[] =
"substr=$variant";
2460 if ( $variantBCP47 !== $variant ) {
2461 $aloption[] =
"substr=$variantBCP47";
2464 $this->addVaryHeader(
'Accept-Language', $aloption );
2478 public function preventClickjacking( $enable =
true ) {
2479 $this->mPreventClickjacking = $enable;
2487 public function allowClickjacking() {
2488 $this->mPreventClickjacking =
false;
2497 public function getPreventClickjacking() {
2498 return $this->mPreventClickjacking;
2508 public function getFrameOptions() {
2510 if ( $config->
get(
'BreakFrames' ) ) {
2512 } elseif ( $this->mPreventClickjacking && $config->
get(
'EditPageFrameOptions' ) ) {
2513 return $config->
get(
'EditPageFrameOptions' );
2524 private function getOriginTrials() {
2527 return $config->
get(
'OriginTrials' );
2533 public function sendCacheControl() {
2537 $this->addVaryHeader(
'Cookie' );
2538 $this->addAcceptLanguage();
2540 # don't serve compressed data to clients who can't handle it
2541 # maintain different caches for logged-in users and non-logged in ones
2542 $response->header( $this->getVaryHeader() );
2544 if ( $config->
get(
'UseKeyHeader' ) ) {
2545 $response->header( $this->getKeyHeader() );
2548 if ( $this->mEnableClientCache ) {
2550 $config->
get(
'UseSquid' ) &&
2552 !SessionManager::getGlobalSession()->isPersistent() &&
2553 !$this->isPrintable() &&
2554 $this->mCdnMaxage != 0 &&
2555 !$this->haveCacheVaryCookies()
2557 if ( $config->
get(
'UseESI' ) ) {
2559 # We'll purge the proxy cache explicitly, but require end user agents
2560 # to revalidate against the proxy on each visit.
2561 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2563 ": proxy caching with ESI; {$this->mLastModified} **",
'private' );
2564 # start with a shorter timeout for initial testing
2565 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2567 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2568 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2570 $response->header(
'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2572 # We'll purge the proxy cache for anons explicitly, but require end user agents
2573 # to revalidate against the proxy on each visit.
2574 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2575 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2577 ": local proxy caching; {$this->mLastModified} **",
'private' );
2578 # start with a shorter timeout for initial testing
2579 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2581 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2584 # We do want clients to cache if they can, but they *must* check for updates
2585 # on revisiting the page.
2586 wfDebug( __METHOD__ .
": private caching; {$this->mLastModified} **",
'private' );
2587 $response->header(
'Expires: ' . gmdate(
'D, d M Y H:i:s', 0 ) .
' GMT' );
2588 $response->header(
"Cache-Control: private, must-revalidate, max-age=0" );
2590 if ( $this->mLastModified ) {
2591 $response->header(
"Last-Modified: {$this->mLastModified}" );
2594 wfDebug( __METHOD__ .
": no caching **",
'private' );
2596 # In general, the absence of a last modified header should be enough to prevent
2597 # the client from using its cache. We send a few other things just to make sure.
2598 $response->header(
'Expires: ' . gmdate(
'D, d M Y H:i:s', 0 ) .
' GMT' );
2599 $response->header(
'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2600 $response->header(
'Pragma: no-cache' );
2609 public function loadSkinModules( $sk ) {
2611 if ( $group ===
'styles' ) {
2612 foreach (
$modules as $key => $moduleMembers ) {
2613 $this->addModuleStyles( $moduleMembers );
2631 public function output( $return =
false ) {
2632 if ( $this->mDoNothing ) {
2633 return $return ?
'' :
null;
2639 if ( $this->mRedirect !=
'' ) {
2640 # Standards require redirect URLs to be absolute
2643 $redirect = $this->mRedirect;
2644 $code = $this->mRedirectCode;
2646 if (
Hooks::run(
"BeforePageRedirect", [ $this, &$redirect, &
$code ] ) ) {
2648 if ( !$config->
get(
'DebugRedirects' ) ) {
2653 if ( $config->
get(
'VaryOnXFP' ) ) {
2654 $this->addVaryHeader(
'X-Forwarded-Proto' );
2656 $this->sendCacheControl();
2658 $response->header(
"Content-Type: text/html; charset=utf-8" );
2659 if ( $config->
get(
'DebugRedirects' ) ) {
2660 $url = htmlspecialchars( $redirect );
2661 print
"<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2662 print
"<p>Location: <a href=\"$url\">$url</a></p>\n";
2663 print
"</body>\n</html>\n";
2665 $response->header(
'Location: ' . $redirect );
2669 return $return ?
'' :
null;
2670 } elseif ( $this->mStatusCode ) {
2671 $response->statusHeader( $this->mStatusCode );
2674 # Buffer output; final headers may depend on later processing
2677 $response->header(
'Content-type: ' . $config->
get(
'MimeType' ) .
'; charset=UTF-8' );
2678 $response->header(
'Content-language: ' .
2679 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2681 if ( !$this->mArticleBodyOnly ) {
2685 $linkHeader = $this->getLinkHeader();
2686 if ( $linkHeader ) {
2691 $frameOptions = $this->getFrameOptions();
2692 if ( $frameOptions ) {
2693 $response->header(
"X-Frame-Options: $frameOptions" );
2696 $originTrials = $this->getOriginTrials();
2697 foreach ( $originTrials
as $originTrial ) {
2698 $response->header(
"Origin-Trial: $originTrial",
false );
2703 if ( $this->mArticleBodyOnly ) {
2704 echo $this->mBodytext;
2707 if ( $this->
getRequest()->getBool(
'safemode' ) ) {
2708 $this->disallowUserJs();
2712 $this->loadSkinModules( $sk );
2717 $outputPage = $this;
2724 }
catch ( Exception
$e ) {
2733 }
catch ( Exception
$e ) {
2738 $this->sendCacheControl();
2741 return ob_get_clean();
2758 public function prepareErrorPage( $pageTitle, $htmlTitle =
false ) {
2759 $this->setPageTitle( $pageTitle );
2760 if ( $htmlTitle !==
false ) {
2761 $this->setHTMLTitle( $htmlTitle );
2763 $this->setRobotPolicy(
'noindex,nofollow' );
2764 $this->setArticleRelated(
false );
2765 $this->enableClientCache(
false );
2766 $this->mRedirect =
'';
2767 $this->clearSubtitle();
2783 public function showErrorPage(
$title, $msg,
$params = [] ) {
2784 if ( !
$title instanceof Message ) {
2788 $this->prepareErrorPage(
$title );
2790 if ( $msg instanceof Message ) {
2792 trigger_error(
'Argument ignored: $params. The message parameters argument '
2793 .
'is discarded when the $msg argument is a Message object instead of '
2794 .
'a string.', E_USER_NOTICE );
2796 $this->addHTML( $msg->parseAsBlock() );
2798 $this->addWikiMsgArray( $msg,
$params );
2801 $this->returnToMain();
2810 public function showPermissionsErrorPage(
array $errors, $action =
null ) {
2811 foreach ( $errors
as $key => $error ) {
2812 $errors[$key] = (
array)$error;
2820 if ( in_array( $action, [
'read',
'edit',
'createpage',
'createtalk',
'upload' ] )
2821 && $this->
getUser()->isAnon() &&
count( $errors ) == 1 && isset( $errors[0][0] )
2822 && ( $errors[0][0] ==
'badaccess-groups' || $errors[0][0] ==
'badaccess-group0' )
2826 $displayReturnto =
null;
2828 # Due to T34276, if a user does not have read permissions,
2829 # $this->getTitle() will just give Special:Badtitle, which is
2830 # not especially useful as a returnto parameter. Use the title
2831 # from the request instead, if there was one.
2834 if ( $action ==
'edit' ) {
2835 $msg =
'whitelistedittext';
2836 $displayReturnto = $returnto;
2837 } elseif ( $action ==
'createpage' || $action ==
'createtalk' ) {
2838 $msg =
'nocreatetext';
2839 } elseif ( $action ==
'upload' ) {
2840 $msg =
'uploadnologintext';
2842 $msg =
'loginreqpagetext';
2849 $query[
'returnto'] = $returnto->getPrefixedText();
2852 $returntoquery =
$request->getValues();
2853 unset( $returntoquery[
'title'] );
2854 unset( $returntoquery[
'returnto'] );
2855 unset( $returntoquery[
'returntoquery'] );
2860 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2864 $this->
msg(
'loginreqlink' )->
text(),
2869 $this->prepareErrorPage( $this->
msg(
'loginreqtitle' ) );
2870 $this->addHTML( $this->
msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2872 # Don't return to a page the user can't read otherwise
2873 # we'll end up in a pointless loop
2874 if ( $displayReturnto && $displayReturnto->userCan(
'read', $this->getUser() ) ) {
2875 $this->returnToMain(
null, $displayReturnto );
2878 $this->prepareErrorPage( $this->
msg(
'permissionserrors' ) );
2879 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2889 public function versionRequired( $version ) {
2890 $this->prepareErrorPage( $this->
msg(
'versionrequired', $version ) );
2892 $this->addWikiMsg(
'versionrequiredtext', $version );
2893 $this->returnToMain();
2903 public function formatPermissionsErrorMessage(
array $errors, $action =
null ) {
2904 if ( $action ==
null ) {
2905 $text = $this->
msg(
'permissionserrorstext',
count( $errors ) )->plain() .
"\n\n";
2907 $action_desc = $this->
msg(
"action-$action" )->plain();
2909 'permissionserrorstext-withaction',
2912 )->plain() .
"\n\n";
2915 if (
count( $errors ) > 1 ) {
2916 $text .=
'<ul class="permissions-errors">' .
"\n";
2918 foreach ( $errors
as $error ) {
2920 $text .= $this->
msg( ...$error )->plain();
2925 $text .=
"<div class=\"permissions-errors\">\n" .
2926 $this->
msg( ...reset( $errors ) )->plain() .
2942 public function showLagWarning( $lag ) {
2944 if ( $lag >= $config->
get(
'SlaveLagWarning' ) ) {
2945 $lag = floor( $lag );
2946 $message = $lag < $config->
get(
'SlaveLagCritical' )
2949 $wrap = Html::rawElement(
'div', [
'class' =>
"mw-{$message}" ],
"\n$1\n" );
2950 $this->wrapWikiMsg(
"$wrap\n", [ $message, $this->
getLanguage()->formatNum( $lag ) ] );
2960 public function showFatalError( $message ) {
2961 $this->prepareErrorPage( $this->
msg(
'internalerror' ) );
2963 $this->addHTML( $message );
2969 public function showUnexpectedValueError(
$name, $val ) {
2971 $this->showFatalError( $this->
msg(
'unexpected',
$name, $val )->escaped() );
2977 public function showFileCopyError( $old, $new ) {
2979 $this->showFatalError( $this->
msg(
'filecopyerror', $old, $new )->escaped() );
2985 public function showFileRenameError( $old, $new ) {
2987 $this->showFatalError( $this->
msg(
'filerenameerror', $old, $new )->escaped() );
2993 public function showFileDeleteError(
$name ) {
2995 $this->showFatalError( $this->
msg(
'filedeleteerror',
$name )->escaped() );
3001 public function showFileNotFoundError(
$name ) {
3003 $this->showFatalError( $this->
msg(
'filenotfound',
$name )->escaped() );
3016 ->getLinkRendererFactory()->createFromLegacyOptions(
$options );
3017 $link = $this->
msg(
'returnto' )->rawParams(
3019 $this->addHTML(
"<p id=\"mw-returnto\">{$link}</p>\n" );
3030 public function returnToMain( $unused =
null, $returnto =
null, $returntoquery =
null ) {
3031 if ( $returnto ==
null ) {
3032 $returnto = $this->
getRequest()->getText(
'returnto' );
3035 if ( $returntoquery ==
null ) {
3036 $returntoquery = $this->
getRequest()->getText(
'returntoquery' );
3039 if ( $returnto ===
'' ) {
3043 if ( is_object( $returnto ) ) {
3044 $titleObj = $returnto;
3050 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
3054 $this->addReturnTo( $titleObj,
wfCgiToArray( $returntoquery ) );
3057 private function getRlClientContext() {
3058 if ( !$this->rlClientContext ) {
3059 $query = ResourceLoader::makeLoaderQuery(
3062 $this->
getSkin()->getSkinName(),
3063 $this->
getUser()->isLoggedIn() ? $this->
getUser()->getName() :
null,
3065 ResourceLoader::inDebugMode(),
3067 $this->isPrintable(),
3071 $this->getResourceLoader(),
3074 if ( $this->contentOverrideCallbacks ) {
3076 $this->rlClientContext->setContentOverrideCallback(
function (
Title $title ) {
3077 foreach ( $this->contentOverrideCallbacks
as $callback ) {
3081 if ( strpos( $text,
'</script>' ) !==
false ) {
3085 $titleFormatted =
$title->getPrefixedText();
3088 "Cannot preview $titleFormatted due to script-closing tag."
3099 return $this->rlClientContext;
3113 public function getRlClient() {
3114 if ( !$this->rlClient ) {
3115 $context = $this->getRlClientContext();
3116 $rl = $this->getResourceLoader();
3117 $this->addModules( [
3122 $this->addModuleStyles( [
3127 $this->
getSkin()->setupSkinUserCss( $this );
3130 $exemptGroups = [
'site' => [],
'noscript' => [],
'private' => [],
'user' => [] ];
3132 $moduleStyles = $this->getModuleStyles(
true );
3136 $userBatch = [
'user.styles',
'user' ];
3137 $siteBatch = array_diff( $moduleStyles, $userBatch );
3143 $moduleStyles = array_filter( $moduleStyles,
3145 $module = $rl->getModule(
$name );
3147 $group = $module->getGroup();
3148 if ( isset( $exemptGroups[$group] ) ) {
3149 $exemptStates[
$name] =
'ready';
3150 if ( !$module->isKnownEmpty(
$context ) ) {
3152 $exemptGroups[$group][] =
$name;
3160 $this->rlExemptStyleModules = $exemptGroups;
3163 'target' => $this->getTarget(),
3164 'nonce' => $this->getCSPNonce(),
3176 $rlClient->
setConfig( $this->getJSVars() );
3177 $rlClient->
setModules( $this->getModules(
true ) );
3180 $this->rlClient = $rlClient;
3182 return $this->rlClient;
3190 public function headElement(
Skin $sk, $includeStyle =
true ) {
3192 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3195 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
3196 $this->getRlClient()->getDocumentAttributes(),
3199 $pieces[] = Html::openElement(
'head' );
3201 if ( $this->getHTMLTitle() ==
'' ) {
3202 $this->setHTMLTitle( $this->
msg(
'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3205 if ( !Html::isXmlMimeType( $this->
getConfig()->
get(
'MimeType' ) ) ) {
3214 $pieces[] = Html::element(
'meta', [
'charset' =>
'UTF-8' ] );
3217 $pieces[] = Html::element(
'title',
null, $this->getHTMLTitle() );
3218 $pieces[] = $this->getRlClient()->getHeadHtml();
3219 $pieces[] = $this->buildExemptModules();
3220 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3221 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3224 $pieces[] =
'<!--[if lt IE 9]>' .
3227 $this->getResourceLoader(),
3233 $this->getCSPNonce()
3237 $pieces[] = Html::closeElement(
'head' );
3239 $bodyClasses = $this->mAdditionalBodyClasses;
3240 $bodyClasses[] =
'mediawiki';
3242 # Classes for LTR/RTL directionality support
3243 $bodyClasses[] = $userdir;
3244 $bodyClasses[] =
"sitedir-$sitedir";
3246 $underline = $this->
getUser()->getOption(
'underline' );
3247 if ( $underline < 2 ) {
3251 $bodyClasses[] =
'mw-underline-' . ( $underline ?
'always' :
'never' );
3254 if ( $this->
getLanguage()->capitalizeAllNouns() ) {
3255 # A <body> class is probably not the best way to do this . . .
3256 $bodyClasses[] =
'capitalize-all-nouns';
3262 $bodyClasses[] =
'mw-hide-empty-elt';
3265 $bodyClasses[] =
'skin-' . Sanitizer::escapeClass( $sk->
getSkinName() );
3272 $bodyAttrs[
'class'] = implode(
' ', $bodyClasses );
3276 Hooks::run(
'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3278 $pieces[] = Html::openElement(
'body', $bodyAttrs );
3280 return self::combineWrappedStrings( $pieces );
3288 public function getResourceLoader() {
3289 if ( is_null( $this->mResourceLoader ) ) {
3291 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3293 return $this->mResourceLoader;
3304 public function makeResourceLoaderLink(
$modules, $only,
array $extraQuery = [] ) {
3309 $this->getRlClientContext(),
3313 $this->getCSPNonce()
3323 protected static function combineWrappedStrings(
array $chunks ) {
3325 $chunks = array_filter( $chunks,
'strlen' );
3326 return WrappedString::join(
"\n", $chunks );
3335 public function getBottomScripts() {
3337 $chunks[] = $this->getRlClient()->getBodyHtml();
3340 $chunks[] = $this->mScripts;
3342 if ( $this->limitReportJSData ) {
3343 $chunks[] = ResourceLoader::makeInlineScript(
3344 ResourceLoader::makeConfigSetScript(
3345 [
'wgPageParseReport' => $this->limitReportJSData ]
3347 $this->getCSPNonce()
3351 return self::combineWrappedStrings( $chunks );
3360 public function getJsConfigVars() {
3361 return $this->mJsConfigVars;
3370 public function addJsConfigVars(
$keys,
$value =
null ) {
3371 if ( is_array(
$keys ) ) {
3373 $this->mJsConfigVars[$key] =
$value;
3390 public function getJSVars() {
3393 $canonicalSpecialPageName =
false; # T23115
3394 $services = MediaWikiServices::getInstance();
3397 $ns =
$title->getNamespace();
3409 list( $canonicalSpecialPageName, ) =
3411 resolveAlias(
$title->getDBkey() );
3414 $curRevisionId = $wikiPage->getLatest();
3415 $articleId = $wikiPage->getId();
3421 $separatorTransTable =
$lang->separatorTransformTable();
3422 $separatorTransTable = $separatorTransTable ?: [];
3423 $compactSeparatorTransTable = [
3424 implode(
"\t", array_keys( $separatorTransTable ) ),
3425 implode(
"\t", $separatorTransTable ),
3427 $digitTransTable =
$lang->digitTransformTable();
3428 $digitTransTable = $digitTransTable ?: [];
3429 $compactDigitTransTable = [
3430 implode(
"\t", array_keys( $digitTransTable ) ),
3431 implode(
"\t", $digitTransTable ),
3437 'wgCanonicalNamespace' => $canonicalNamespace,
3438 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3439 'wgNamespaceNumber' =>
$title->getNamespace(),
3440 'wgPageName' =>
$title->getPrefixedDBkey(),
3441 'wgTitle' =>
$title->getText(),
3442 'wgCurRevisionId' => $curRevisionId,
3443 'wgRevisionId' => (int)$this->getRevisionId(),
3444 'wgArticleId' => $articleId,
3445 'wgIsArticle' => $this->isArticle(),
3446 'wgIsRedirect' =>
$title->isRedirect(),
3449 'wgUserGroups' =>
$user->getEffectiveGroups(),
3450 'wgCategories' => $this->getCategories(),
3451 'wgBreakFrames' => $this->getFrameOptions() ==
'DENY',
3452 'wgPageContentLanguage' =>
$lang->getCode(),
3453 'wgPageContentModel' =>
$title->getContentModel(),
3454 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3455 'wgDigitTransformTable' => $compactDigitTransTable,
3456 'wgDefaultDateFormat' =>
$lang->getDefaultDateFormat(),
3457 'wgMonthNames' =>
$lang->getMonthNamesArray(),
3458 'wgMonthNamesShort' =>
$lang->getMonthAbbreviationsArray(),
3459 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3460 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3462 'wgCSPNonce' => $this->getCSPNonce(),
3465 if (
$user->isLoggedIn() ) {
3467 $vars[
'wgUserEditCount'] =
$user->getEditCount();
3468 $userReg =
$user->getRegistration();
3469 $vars[
'wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX, $userReg ) * 1000 :
null;
3473 $vars[
'wgUserNewMsgRevisionId'] =
$user->getNewMessageRevisionId();
3476 $contLang =
$services->getContentLanguage();
3477 if ( $contLang->hasVariants() ) {
3478 $vars[
'wgUserVariant'] = $contLang->getPreferredVariant();
3484 $vars[
'wgRelevantPageIsProbablyEditable'] = $relevantTitle
3485 && $relevantTitle->quickUserCan(
'edit',
$user )
3486 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan(
'create',
$user ) );
3494 if (
$title->isMainPage() ) {
3495 $vars[
'wgIsMainPage'] =
true;
3498 if ( $this->mRedirectedFrom ) {
3499 $vars[
'wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3502 if ( $relevantUser ) {
3503 $vars[
'wgRelevantUserName'] = $relevantUser->getName();
3513 return array_merge(
$vars, $this->getJsConfigVars() );
3525 public function userCanPreview() {
3528 $request->getVal(
'action' ) !==
'submit' ||
3536 if ( !
$user->isLoggedIn() ) {
3540 if ( !
$user->matchEditToken(
$request->getVal(
'wpEditToken' ) ) ) {
3545 $errors =
$title->getUserPermissionsErrors(
'edit',
$user );
3546 if (
count( $errors ) !== 0 ) {
3556 public function getHeadLinksArray() {
3562 $canonicalUrl = $this->mCanonicalUrl;
3564 $tags[
'meta-generator'] = Html::element(
'meta', [
3565 'name' =>
'generator',
3566 'content' =>
"MediaWiki $wgVersion",
3569 if ( $config->
get(
'ReferrerPolicy' ) !==
false ) {
3572 foreach ( array_reverse( (
array)$config->
get(
'ReferrerPolicy' ) )
as $i => $policy ) {
3573 $tags[
"meta-referrer-$i"] = Html::element(
'meta', [
3574 'name' =>
'referrer',
3575 'content' => $policy,
3580 $p =
"{$this->mIndexPolicy},{$this->mFollowPolicy}";
3581 if ( $p !==
'index,follow' ) {
3584 $tags[
'meta-robots'] = Html::element(
'meta', [
3590 foreach ( $this->mMetatags
as $tag ) {
3591 if ( strncasecmp( $tag[0],
'http:', 5 ) === 0 ) {
3593 $tag[0] = substr( $tag[0], 5 );
3594 } elseif ( strncasecmp( $tag[0],
'og:', 3 ) === 0 ) {
3599 $tagName =
"meta-{$tag[0]}";
3600 if ( isset( $tags[$tagName] ) ) {
3601 $tagName .= $tag[1];
3603 $tags[$tagName] = Html::element(
'meta',
3606 'content' => $tag[1]
3611 foreach ( $this->mLinktags
as $tag ) {
3612 $tags[] = Html::element(
'link', $tag );
3615 # Universal edit button
3616 if ( $config->
get(
'UniversalEditButton' ) && $this->isArticleRelated() ) {
3619 && ( $this->
getTitle()->exists() ||
3623 $msg = $this->
msg(
'edit' )->text();
3624 $tags[
'universal-edit-button'] = Html::element(
'link', [
3625 'rel' =>
'alternate',
3626 'type' =>
'application/x-wiki',
3628 'href' => $this->
getTitle()->getEditURL(),
3631 $tags[
'alternative-edit'] = Html::element(
'link', [
3634 'href' => $this->
getTitle()->getEditURL(),
3639 # Generally the order of the favicon and apple-touch-icon links
3640 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3641 # uses whichever one appears later in the HTML source. Make sure
3642 # apple-touch-icon is specified first to avoid this.
3643 if ( $config->
get(
'AppleTouchIcon' ) !==
false ) {
3644 $tags[
'apple-touch-icon'] = Html::element(
'link', [
3645 'rel' =>
'apple-touch-icon',
3646 'href' => $config->
get(
'AppleTouchIcon' )
3650 if ( $config->
get(
'Favicon' ) !==
false ) {
3651 $tags[
'favicon'] = Html::element(
'link', [
3652 'rel' =>
'shortcut icon',
3653 'href' => $config->
get(
'Favicon' )
3657 # OpenSearch description link
3658 $tags[
'opensearch'] = Html::element(
'link', [
3660 'type' =>
'application/opensearchdescription+xml',
3661 'href' =>
wfScript(
'opensearch_desc' ),
3662 'title' => $this->
msg(
'opensearch-desc' )->inContentLanguage()->
text(),
3665 # Real Simple Discovery link, provides auto-discovery information
3666 # for the MediaWiki API (and potentially additional custom API
3667 # support such as WordPress or Twitter-compatible APIs for a
3668 # blogging extension, etc)
3669 $tags[
'rsd'] = Html::element(
'link', [
3671 'type' =>
'application/rsd+xml',
3677 [
'action' =>
'rsd' ] ),
3683 if ( !$config->
get(
'DisableLangConversion' ) ) {
3685 if (
$lang->hasVariants() ) {
3686 $variants =
$lang->getVariants();
3687 foreach ( $variants
as $variant ) {
3688 $tags[
"variant-$variant"] = Html::element(
'link', [
3689 'rel' =>
'alternate',
3691 'href' => $this->
getTitle()->getLocalURL(
3692 [
'variant' => $variant ] )
3696 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3697 $tags[
"variant-x-default"] = Html::element(
'link', [
3698 'rel' =>
'alternate',
3699 'hreflang' =>
'x-default',
3700 'href' => $this->
getTitle()->getLocalURL() ] );
3705 if ( $this->copyrightUrl !==
null ) {
3706 $copyright = $this->copyrightUrl;
3709 if ( $config->
get(
'RightsPage' ) ) {
3713 $copyright = $copy->getLocalURL();
3717 if ( !$copyright && $config->
get(
'RightsUrl' ) ) {
3718 $copyright = $config->
get(
'RightsUrl' );
3723 $tags[
'copyright'] = Html::element(
'link', [
3725 'href' => $copyright ]
3730 if ( $config->
get(
'Feed' ) ) {
3733 foreach ( $this->getSyndicationLinks()
as $format =>
$link ) {
3734 # Use the page name for the title. In principle, this could
3735 # lead to issues with having the same name for different feeds
3736 # corresponding to the same page, but we can't avoid that at
3739 $feedLinks[] = $this->feedLink(
3742 # Used
messages:
'page-rss-feed' and 'page-atom-feed' (
for an easier grep)
3744 "page-{$format}-feed", $this->
getTitle()->getPrefixedText()
3749 # Recent changes feed should appear on every page (except recentchanges,
3750 # that would be redundant). Put it after the per-page feed to avoid
3751 # changing existing behavior. It's still available, probably via a
3752 # menu in your browser. Some sites might have a different feed they'd
3753 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3754 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3755 # If so, use it instead.
3756 $sitename = $config->
get(
'Sitename' );
3757 $overrideSiteFeed = $config->
get(
'OverrideSiteFeed' );
3758 if ( $overrideSiteFeed ) {
3759 foreach ( $overrideSiteFeed
as $type => $feedUrl ) {
3761 $feedLinks[] = $this->feedLink(
3764 $this->
msg(
"site-{$type}-feed", $sitename )->
text()
3767 } elseif ( !$this->
getTitle()->isSpecial(
'Recentchanges' ) ) {
3769 foreach ( $this->getAdvertisedFeedTypes()
as $format ) {
3770 $feedLinks[] = $this->feedLink(
3772 $rctitle->getLocalURL( [
'feed' => $format ] ),
3773 # For grep: 'site-rss-feed', 'site-atom-feed'
3774 $this->
msg(
"site-{$format}-feed", $sitename )->text()
3779 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3780 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3781 # use OutputPage::addFeedLink() instead.
3782 Hooks::run(
'AfterBuildFeedLinks', [ &$feedLinks ] );
3784 $tags += $feedLinks;
3788 if ( $config->
get(
'EnableCanonicalServerLink' ) ) {
3789 if ( $canonicalUrl !==
false ) {
3791 } elseif ( $this->isArticleRelated() ) {
3800 if ( in_array( $action, [
'history',
'info' ] ) ) {
3801 $query =
"action={$action}";
3807 $reqUrl = $this->
getRequest()->getRequestURL();
3811 if ( $canonicalUrl !==
false ) {
3812 $tags[] = Html::element(
'link', [
3813 'rel' =>
'canonical',
3814 'href' => $canonicalUrl
3823 Hooks::run(
'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3836 private function feedLink(
$type, $url, $text ) {
3837 return Html::element(
'link', [
3838 'rel' =>
'alternate',
3839 'type' =>
"application/$type+xml",
3854 public function addStyle( $style, $media =
'', $condition =
'', $dir =
'' ) {
3860 $options[
'condition'] = $condition;
3875 public function addInlineStyle( $style_css, $flip =
'noflip' ) {
3876 if ( $flip ===
'flip' && $this->
getLanguage()->isRTL() ) {
3877 # If wanted, and the interface is right-to-left, flip the CSS
3878 $style_css = CSSJanus::transform( $style_css,
true,
false );
3880 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3888 protected function buildExemptModules() {
3902 $chunks[] = implode(
'', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3904 $chunks[] = Html::element(
3906 [
'name' =>
'ResourceLoaderDynamicStyles',
'content' =>
'' ]
3909 $separateReq = [
'site.styles',
'user.styles' ];
3910 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3912 $chunks[] = $this->makeResourceLoaderLink(
3913 array_diff( $moduleNames, $separateReq ),
3917 foreach ( array_intersect( $moduleNames, $separateReq )
as $name ) {
3920 $chunks[] = $this->makeResourceLoaderLink(
$name,
3926 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3932 public function buildCssLinksArray() {
3956 if ( isset(
$options[
'media'] ) ) {
3957 $media = self::transformCssMedia(
$options[
'media'] );
3958 if ( is_null( $media ) ) {
3965 if ( substr( $style, 0, 1 ) ==
'/' ||
3966 substr( $style, 0, 5 ) ==
'http:' ||
3967 substr( $style, 0, 6 ) ==
'https:' ) {
3972 $url = self::transformResourcePath(
3974 $config->
get(
'StylePath' ) .
'/' . $style
3978 $link = Html::linkedStyle( $url, $media );
3980 if ( isset(
$options[
'condition'] ) ) {
3981 $condition = htmlspecialchars(
$options[
'condition'] );
3982 $link =
"<!--[if $condition]>$link<![endif]-->";
4008 public static function transformResourcePath(
Config $config,
$path ) {
4012 $remotePathPrefix = $config->
get(
'ResourceBasePath' );
4013 if ( $remotePathPrefix ===
'' ) {
4018 $remotePath = $remotePathPrefix;
4020 if ( strpos(
$path, $remotePath ) !== 0 || substr(
$path, 0, 2 ) ===
'//' ) {
4029 $uploadPath = $config->
get(
'UploadPath' );
4030 if ( strpos(
$path, $uploadPath ) === 0 ) {
4031 $localDir = $config->
get(
'UploadDirectory' );
4032 $remotePathPrefix = $remotePath = $uploadPath;
4035 $path = RelPath::getRelativePath(
$path, $remotePath );
4036 return self::transformFilePath( $remotePathPrefix, $localDir,
$path );
4050 public static function transformFilePath( $remotePathPrefix, $localPath,
$file ) {
4051 $hash = md5_file(
"$localPath/$file" );
4052 if ( $hash ===
false ) {
4053 wfLogWarning( __METHOD__ .
": Failed to hash $localPath/$file" );
4056 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
4066 public static function transformCssMedia( $media ) {
4070 $screenMediaQueryRegex =
'/^(?:only\s+)?screen\b/i';
4074 'printable' =>
'print',
4075 'handheld' =>
'handheld',
4077 foreach ( $switches
as $switch => $targetMedia ) {
4079 if ( $media == $targetMedia ) {
4081 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4095 if ( $targetMedia ==
'print' || $media ==
'screen' ) {
4111 public function addWikiMsg( ) {
4112 $args = func_get_args();
4125 public function addWikiMsgArray(
$name,
$args ) {
4126 $this->addHTML( $this->
msg(
$name,
$args )->parseAsBlock() );
4154 public function wrapWikiMsg( $wrap ) {
4155 $msgSpecs = func_get_args();
4156 array_shift( $msgSpecs );
4157 $msgSpecs = array_values( $msgSpecs );
4159 foreach ( $msgSpecs
as $n => $spec ) {
4160 if ( is_array( $spec ) ) {
4163 if ( isset(
$args[
'options'] ) ) {
4164 unset(
$args[
'options'] );
4166 'Adding "options" to ' . __METHOD__ .
' is no longer supported',
4176 $this->addWikiTextAsInterface(
$s );
4184 public function isTOCEnabled() {
4185 return $this->mEnableTOC;
4194 public function enableSectionEditLinks( $flag =
true ) {
4203 public function sectionEditLinksEnabled() {
4215 public static function setupOOUI( $skinName =
'default', $dir =
'ltr' ) {
4217 $theme = $themes[$skinName] ?? $themes[
'default'];
4219 $themeClass =
"OOUI\\{$theme}Theme";
4220 OOUI\Theme::setSingleton(
new $themeClass() );
4221 OOUI\Element::setDefaultDir( $dir );
4230 public function enableOOUI() {
4232 strtolower( $this->
getSkin()->getSkinName() ),
4235 $this->addModuleStyles( [
4236 'oojs-ui-core.styles',
4237 'oojs-ui.styles.indicators',
4238 'oojs-ui.styles.textures',
4239 'mediawiki.widgets.styles',
4240 'oojs-ui.styles.icons-content',
4241 'oojs-ui.styles.icons-alerts',
4242 'oojs-ui.styles.icons-interactions',
4255 public function getCSPNonce() {
4259 if ( $this->CSPNonce ===
null ) {
4262 $rand = random_bytes( 15 );
4263 $this->CSPNonce = base64_encode( $rand );
4265 return $this->CSPNonce;