28 use Wikimedia\RelPath;
29 use Wikimedia\WrappedString;
30 use Wikimedia\WrappedStringList;
49 protected $mMetatags = [];
52 protected $mLinktags = [];
55 protected $mCanonicalUrl =
false;
59 private $mPageTitle =
'';
68 private $displayTitle;
74 public $mBodytext =
'';
77 private $mHTMLtitle =
'';
83 private $mIsArticle =
false;
86 private $mIsArticleRelated =
true;
89 private $mHasCopyright =
false;
95 private $mPrintable =
false;
101 private $mSubtitle = [];
104 public $mRedirect =
'';
107 protected $mStatusCode;
113 protected $mLastModified =
'';
116 protected $mCategoryLinks = [];
119 protected $mCategories = [
125 protected $mIndicators = [];
128 private $mLanguageLinks = [];
136 private $mScripts =
'';
139 protected $mInlineStyles =
'';
145 public $mPageLinkTitle =
'';
148 protected $mHeadItems = [];
151 protected $mAdditionalBodyClasses = [];
154 protected $mModules = [];
157 protected $mModuleScripts = [];
160 protected $mModuleStyles = [];
163 protected $mResourceLoader;
169 private $rlClientContext;
172 private $rlExemptStyleModules;
175 protected $mJsConfigVars = [];
178 protected $mTemplateIds = [];
181 protected $mImageTimeKeys = [];
184 public $mRedirectCode =
'';
186 protected $mFeedLinksAppendQuery =
null;
193 protected $mAllowedModules = [
198 protected $mDoNothing =
false;
203 protected $mContainsNewMagic = 0;
209 protected $mParserOptions =
null;
216 private $mFeedLinks = [];
219 protected $mEnableClientCache =
true;
222 private $mArticleBodyOnly =
false;
225 protected $mNewSectionLink =
false;
228 protected $mHideNewSectionLink =
false;
235 public $mNoGallery =
false;
238 protected $mCdnMaxage = 0;
240 protected $mCdnMaxageLimit = INF;
247 protected $mPreventClickjacking =
true;
250 private $mRevisionId =
null;
253 private $mRevisionTimestamp =
null;
256 protected $mFileVersion =
null;
266 protected $styles = [];
268 private $mIndexPolicy =
'index';
269 private $mFollowPolicy =
'follow';
275 private $mVaryHeader = [
276 'Accept-Encoding' => [
'match=gzip' ],
285 private $mRedirectedFrom =
null;
290 private $mProperties = [];
295 private $mTarget =
null;
300 private $mEnableTOC =
false;
305 private $copyrightUrl;
308 private $limitReportJSData = [];
311 private $contentOverrides = [];
314 private $contentOverrideCallbacks = [];
319 private $mLinkHeader = [];
329 private static $cacheVaryCookies =
null;
347 public function redirect( $url, $responsecode =
'302' ) {
348 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
349 $this->mRedirect = str_replace(
"\n",
'', $url );
350 $this->mRedirectCode = $responsecode;
358 public function getRedirect() {
359 return $this->mRedirect;
370 public function setCopyrightUrl( $url ) {
371 $this->copyrightUrl = $url;
379 public function setStatusCode( $statusCode ) {
380 $this->mStatusCode = $statusCode;
390 function addMeta(
$name, $val ) {
391 array_push( $this->mMetatags, [
$name, $val ] );
400 public function getMetaTags() {
401 return $this->mMetatags;
411 function addLink(
array $linkarr ) {
412 array_push( $this->mLinktags, $linkarr );
421 public function getLinkTags() {
422 return $this->mLinktags;
430 function setCanonicalUrl( $url ) {
431 $this->mCanonicalUrl = $url;
441 public function getCanonicalUrl() {
442 return $this->mCanonicalUrl;
452 function addScript( $script ) {
453 $this->mScripts .= $script;
464 public function addScriptFile( $file, $unused =
null ) {
465 if ( substr( $file, 0, 1 ) !==
'/' && !preg_match(
'#^[a-z]*://#i', $file ) ) {
481 public function addInlineScript( $script ) {
493 protected function filterModules(
array $modules, $position =
null,
497 $filteredModules = [];
503 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
504 $this->warnModuleTargetFilter( $module->getName() );
507 $filteredModules[] = $val;
510 return $filteredModules;
513 private function warnModuleTargetFilter( $moduleName ) {
514 static $warnings = [];
515 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
518 $warnings[$this->mTarget][$moduleName] =
true;
519 $this->getResourceLoader()->getLogger()->debug(
520 'Module "{module}" not loadable on target "{target}".',
522 'module' => $moduleName,
523 'target' => $this->mTarget,
537 public function getModules( $filter =
false, $position =
null, $param =
'mModules',
540 $modules = array_values( array_unique( $this->$param ) );
551 public function addModules(
$modules ) {
552 $this->mModules = array_merge( $this->mModules, (
array)
$modules );
562 public function getModuleScripts( $filter =
false, $position =
null ) {
563 return $this->getModules( $filter,
null,
'mModuleScripts',
578 public function addModuleScripts(
$modules ) {
579 $this->mModuleScripts = array_merge( $this->mModuleScripts, (
array)
$modules );
589 public function getModuleStyles( $filter =
false, $position =
null ) {
590 return $this->getModules( $filter,
null,
'mModuleStyles',
604 public function addModuleStyles(
$modules ) {
605 $this->mModuleStyles = array_merge( $this->mModuleStyles, (
array)
$modules );
611 public function getTarget() {
612 return $this->mTarget;
620 public function setTarget( $target ) {
621 $this->mTarget = $target;
632 if ( !$this->contentOverrides ) {
634 $this->addContentOverrideCallback(
function (
LinkTarget $target ) {
636 return $this->contentOverrides[$key] ??
null;
641 $this->contentOverrides[$key] =
$content;
651 public function addContentOverrideCallback( callable $callback ) {
652 $this->contentOverrideCallbacks[] = $callback;
660 function getHeadItemsArray() {
661 return $this->mHeadItems;
686 public function addHeadItems( $values ) {
687 $this->mHeadItems = array_merge( $this->mHeadItems, (
array)$values );
696 public function hasHeadItem(
$name ) {
697 return isset( $this->mHeadItems[
$name] );
706 public function addBodyClasses( $classes ) {
707 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (
array)$classes );
717 public function setArticleBodyOnly( $only ) {
718 $this->mArticleBodyOnly = $only;
726 public function getArticleBodyOnly() {
727 return $this->mArticleBodyOnly;
748 public function getProperty(
$name ) {
749 return $this->mProperties[
$name] ??
null;
763 public function checkLastModified( $timestamp ) {
764 if ( !$timestamp || $timestamp ==
'19700101000000' ) {
765 wfDebug( __METHOD__ .
": CACHE DISABLED, NO TIMESTAMP\n" );
769 if ( !$config->
get(
'CachePages' ) ) {
770 wfDebug( __METHOD__ .
": CACHE DISABLED\n" );
776 'page' => $timestamp,
777 'user' => $this->
getUser()->getTouched(),
778 'epoch' => $config->
get(
'CacheEpoch' )
780 if ( $config->
get(
'UseSquid' ) ) {
781 $modifiedTimes[
'sepoch'] =
wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
783 $config->
get(
'SquidMaxage' )
786 Hooks::run(
'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
788 $maxModified = max( $modifiedTimes );
789 $this->mLastModified =
wfTimestamp( TS_RFC2822, $maxModified );
791 $clientHeader = $this->
getRequest()->getHeader(
'If-Modified-Since' );
792 if ( $clientHeader ===
false ) {
793 wfDebug( __METHOD__ .
": client did not send If-Modified-Since header",
'private' );
797 # IE sends sizes after the date like this:
798 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
799 # this breaks strtotime().
800 $clientHeader = preg_replace(
'/;.*$/',
'', $clientHeader );
802 Wikimedia\suppressWarnings();
803 $clientHeaderTime = strtotime( $clientHeader );
804 Wikimedia\restoreWarnings();
805 if ( !$clientHeaderTime ) {
807 .
": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
810 $clientHeaderTime =
wfTimestamp( TS_MW, $clientHeaderTime );
815 if ( $info !==
'' ) {
821 wfDebug( __METHOD__ .
": client sent If-Modified-Since: " .
822 wfTimestamp( TS_ISO_8601, $clientHeaderTime ),
'private' );
823 wfDebug( __METHOD__ .
": effective Last-Modified: " .
824 wfTimestamp( TS_ISO_8601, $maxModified ),
'private' );
825 if ( $clientHeaderTime < $maxModified ) {
826 wfDebug( __METHOD__ .
": STALE, $info",
'private' );
831 # Give a 304 Not Modified response code and disable body output
832 wfDebug( __METHOD__ .
": NOT MODIFIED, $info",
'private' );
833 ini_set(
'zlib.output_compression', 0 );
834 $this->
getRequest()->response()->statusHeader( 304 );
835 $this->sendCacheControl();
851 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
856 return $reqTime - $maxAge;
865 public function setLastModified( $timestamp ) {
866 $this->mLastModified =
wfTimestamp( TS_RFC2822, $timestamp );
877 public function setRobotPolicy( $policy ) {
880 if ( isset( $policy[
'index'] ) ) {
881 $this->setIndexPolicy( $policy[
'index'] );
883 if ( isset( $policy[
'follow'] ) ) {
884 $this->setFollowPolicy( $policy[
'follow'] );
895 public function setIndexPolicy( $policy ) {
896 $policy = trim( $policy );
897 if ( in_array( $policy, [
'index',
'noindex' ] ) ) {
898 $this->mIndexPolicy = $policy;
909 public function setFollowPolicy( $policy ) {
910 $policy = trim( $policy );
911 if ( in_array( $policy, [
'follow',
'nofollow' ] ) ) {
912 $this->mFollowPolicy = $policy;
922 public function setHTMLTitle(
$name ) {
923 if (
$name instanceof Message ) {
926 $this->mHTMLtitle =
$name;
935 public function getHTMLTitle() {
936 return $this->mHTMLtitle;
944 public function setRedirectedFrom(
$t ) {
945 $this->mRedirectedFrom =
$t;
958 public function setPageTitle(
$name ) {
959 if (
$name instanceof Message ) {
963 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
964 # but leave "<i>foobar</i>" alone
965 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
$name ) );
966 $this->mPageTitle = $nameWithTags;
968 # change "<i>foo&bar</i>" to "foo&bar"
970 $this->
msg(
'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
971 ->inContentLanguage()
980 public function getPageTitle() {
981 return $this->mPageTitle;
991 public function setDisplayTitle(
$html ) {
992 $this->displayTitle =
$html;
1003 public function getDisplayTitle() {
1004 $html = $this->displayTitle;
1005 if (
$html ===
null ) {
1009 return Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags(
$html ) );
1018 public function getUnprefixedDisplayTitle() {
1019 $text = $this->getDisplayTitle();
1020 $nsPrefix = $this->
getTitle()->getNsText() .
':';
1021 $prefix = preg_quote( $nsPrefix,
'/' );
1023 return preg_replace(
"/^$prefix/i",
'', $text );
1031 public function setTitle(
Title $t ) {
1040 public function setSubtitle( $str ) {
1041 $this->clearSubtitle();
1042 $this->addSubtitle( $str );
1050 public function addSubtitle( $str ) {
1051 if ( $str instanceof Message ) {
1052 $this->mSubtitle[] = $str->setContext( $this->
getContext() )->parse();
1054 $this->mSubtitle[] = $str;
1067 if (
$title->isRedirect() ) {
1068 $query[
'redirect'] =
'no';
1070 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1082 $this->addSubtitle( self::buildBacklinkSubtitle(
$title,
$query ) );
1088 public function clearSubtitle() {
1089 $this->mSubtitle = [];
1097 public function getSubtitle() {
1098 return implode(
"<br />\n\t\t\t\t", $this->mSubtitle );
1105 public function setPrintable() {
1106 $this->mPrintable =
true;
1114 public function isPrintable() {
1115 return $this->mPrintable;
1121 public function disable() {
1122 $this->mDoNothing =
true;
1130 public function isDisabled() {
1131 return $this->mDoNothing;
1139 public function showNewSectionLink() {
1140 return $this->mNewSectionLink;
1148 public function forceHideNewSectionLink() {
1149 return $this->mHideNewSectionLink;
1160 public function setSyndicated( $show =
true ) {
1162 $this->setFeedAppendQuery(
false );
1164 $this->mFeedLinks = [];
1177 public function setFeedAppendQuery( $val ) {
1178 $this->mFeedLinks = [];
1180 foreach ( $this->
getConfig()->
get(
'AdvertisedFeedTypes' )
as $type ) {
1182 if ( is_string( $val ) ) {
1195 public function addFeedLink( $format, $href ) {
1196 if ( in_array( $format, $this->
getConfig()->
get(
'AdvertisedFeedTypes' ) ) ) {
1197 $this->mFeedLinks[$format] = $href;
1205 public function isSyndicated() {
1206 return count( $this->mFeedLinks ) > 0;
1213 public function getSyndicationLinks() {
1214 return $this->mFeedLinks;
1222 public function getFeedAppendQuery() {
1223 return $this->mFeedLinksAppendQuery;
1233 public function setArticleFlag( $newVal ) {
1234 $this->mIsArticle = $newVal;
1236 $this->mIsArticleRelated = $newVal;
1246 public function isArticle() {
1247 return $this->mIsArticle;
1256 public function setArticleRelated( $newVal ) {
1257 $this->mIsArticleRelated = $newVal;
1259 $this->mIsArticle =
false;
1268 public function isArticleRelated() {
1269 return $this->mIsArticleRelated;
1277 public function setCopyright( $hasCopyright ) {
1278 $this->mHasCopyright = $hasCopyright;
1290 public function showsCopyright() {
1291 return $this->isArticle() || $this->mHasCopyright;
1300 public function addLanguageLinks(
array $newLinkArray ) {
1301 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1310 public function setLanguageLinks(
array $newLinkArray ) {
1311 $this->mLanguageLinks = $newLinkArray;
1319 public function getLanguageLinks() {
1320 return $this->mLanguageLinks;
1328 public function addCategoryLinks(
array $categories ) {
1329 if ( !$categories ) {
1333 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1335 # Set all the values to 'normal'.
1336 $categories = array_fill_keys( array_keys( $categories ),
'normal' );
1338 # Mark hidden categories
1339 foreach (
$res as $row ) {
1340 if ( isset( $row->pp_value ) ) {
1341 $categories[$row->page_title] =
'hidden';
1346 $outputPage = $this;
1347 # Add the remaining categories to the skin
1349 'OutputPageMakeCategoryLinks',
1350 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1352 $services = MediaWikiServices::getInstance();
1354 foreach ( $categories
as $category =>
$type ) {
1356 $category = (
string)$category;
1357 $origcategory = $category;
1362 $services->getContentLanguage()->findVariantLink( $category,
$title,
true );
1363 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1366 $text =
$services->getContentLanguage()->convertHtml(
$title->getText() );
1377 protected function addCategoryLinksToLBAndGetResult(
array $categories ) {
1378 # Add the links to a LinkBatch
1383 # Fetch existence plus the hiddencat property
1385 $fields = array_merge(
1387 [
'page_namespace',
'page_title',
'pp_value' ]
1390 $res =
$dbr->select( [
'page',
'page_props' ],
1392 $lb->constructSet(
'page',
$dbr ),
1395 [
'page_props' => [
'LEFT JOIN', [
1396 'pp_propname' =>
'hiddencat',
1401 # Add the results to the link cache
1402 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1403 $lb->addResultToCache( $linkCache,
$res );
1413 public function setCategoryLinks(
array $categories ) {
1414 $this->mCategoryLinks = [];
1415 $this->addCategoryLinks( $categories );
1426 public function getCategoryLinks() {
1427 return $this->mCategoryLinks;
1439 public function getCategories(
$type =
'all' ) {
1440 if (
$type ===
'all' ) {
1441 $allCategories = [];
1442 foreach ( $this->mCategories
as $categories ) {
1443 $allCategories = array_merge( $allCategories, $categories );
1445 return $allCategories;
1447 if ( !isset( $this->mCategories[
$type] ) ) {
1448 throw new InvalidArgumentException(
'Invalid category type given: ' .
$type );
1450 return $this->mCategories[
$type];
1462 public function setIndicators(
array $indicators ) {
1463 $this->mIndicators = $indicators + $this->mIndicators;
1465 ksort( $this->mIndicators );
1476 public function getIndicators() {
1477 return $this->mIndicators;
1488 public function addHelpLink( $to, $overrideBaseUrl =
false ) {
1489 $this->addModuleStyles(
'mediawiki.helplink' );
1490 $text = $this->
msg(
'helppage-top-gethelp' )->escaped();
1492 if ( $overrideBaseUrl ) {
1495 $toUrlencoded =
wfUrlencode( str_replace(
' ',
'_', $to ) );
1496 $helpUrl =
"//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1503 'target' =>
'_blank',
1504 'class' =>
'mw-helplink',
1509 $this->setIndicators( [
'mw-helplink' =>
$link ] );
1520 public function disallowUserJs() {
1521 $this->reduceAllowedModules(
1528 if ( $this->
getConfig()->
get(
'AllowSiteCSSOnRestrictedPages' ) ) {
1533 $this->reduceAllowedModules(
1545 public function getAllowedModules(
$type ) {
1547 return min( array_values( $this->mAllowedModules ) );
1562 public function reduceAllowedModules(
$type, $level ) {
1563 $this->mAllowedModules[
$type] = min( $this->getAllowedModules(
$type ), $level );
1571 public function prependHTML( $text ) {
1572 $this->mBodytext = $text . $this->mBodytext;
1580 public function addHTML( $text ) {
1581 $this->mBodytext .= $text;
1593 public function addElement( $element,
array $attribs = [], $contents =
'' ) {
1600 public function clearHTML() {
1601 $this->mBodytext =
'';
1609 public function getHTML() {
1610 return $this->mBodytext;
1620 public function parserOptions(
$options =
null ) {
1622 wfDeprecated( __METHOD__ .
' with non-null $options',
'1.31' );
1629 $anonPO->setAllowUnsafeRawHtml(
false );
1630 if ( !
$options->matches( $anonPO ) ) {
1636 if ( !$this->mParserOptions ) {
1642 $po->setAllowUnsafeRawHtml(
false );
1643 $po->isBogus =
true;
1651 $this->mParserOptions->setAllowUnsafeRawHtml(
false );
1657 return wfSetVar( $this->mParserOptions,
null,
true );
1670 public function setRevisionId( $revid ) {
1671 $val = is_null( $revid ) ? null : intval( $revid );
1672 return wfSetVar( $this->mRevisionId, $val,
true );
1680 public function getRevisionId() {
1681 return $this->mRevisionId;
1691 public function setRevisionTimestamp( $timestamp ) {
1692 return wfSetVar( $this->mRevisionTimestamp, $timestamp,
true );
1701 public function getRevisionTimestamp() {
1702 return $this->mRevisionTimestamp;
1711 public function setFileVersion( $file ) {
1713 if ( $file instanceof
File && $file->
exists() ) {
1714 $val = [
'time' => $file->getTimestamp(),
'sha1' => $file->getSha1() ];
1716 return wfSetVar( $this->mFileVersion, $val,
true );
1724 public function getFileVersion() {
1725 return $this->mFileVersion;
1734 public function getTemplateIds() {
1735 return $this->mTemplateIds;
1744 public function getFileSearchOptions() {
1745 return $this->mImageTimeKeys;
1760 public function addWikiText( $text, $linestart =
true, $interface =
true ) {
1765 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
false, $interface );
1784 public function addWikiTextAsInterface(
1793 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
true );
1809 public function wrapWikiTextAsInterface(
1810 $wrapperClass, $text
1812 $this->addWikiTextTitleInternal(
1834 public function addWikiTextAsContent(
1843 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
false );
1855 public function addWikiTextWithTitle( $text,
Title $title, $linestart =
true ) {
1857 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
false,
false );
1870 function addWikiTextTitleTidy( $text,
Title $title, $linestart =
true ) {
1872 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
false );
1883 public function addWikiTextTidy( $text, $linestart =
true ) {
1889 $this->addWikiTextTitleInternal( $text,
$title, $linestart,
true,
false );
1911 public function addWikiTextTitle( $text,
Title $title, $linestart,
1912 $tidy =
false, $interface =
false
1915 return $this->addWikiTextTitleInternal( $text,
$title, $linestart, $tidy, $interface );
1934 private function addWikiTextTitleInternal(
1935 $text,
Title $title, $linestart, $tidy, $interface, $wrapperClass =
null
1937 $parserOutput = $this->parseInternal(
1938 $text,
$title, $linestart, $tidy, $interface,
null
1941 $this->addParserOutput( $parserOutput, [
1942 'enableSectionEditLinks' =>
false,
1943 'wrapperDivClass' => $wrapperClass ??
'',
1955 public function addParserOutputMetadata(
ParserOutput $parserOutput ) {
1956 $this->mLanguageLinks =
1964 $this->enableClientCache(
false );
1967 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->
getHeadItems() );
1968 $this->addModules( $parserOutput->
getModules() );
1972 $this->mPreventClickjacking = $this->mPreventClickjacking
1977 if ( isset( $this->mTemplateIds[$ns] ) ) {
1978 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1980 $this->mTemplateIds[$ns] = $dbks;
1985 $this->mImageTimeKeys[$dbk] = $data;
1989 $parserOutputHooks = $this->
getConfig()->get(
'ParserOutputHooks' );
1991 list( $hookName, $data ) = $hookInfo;
1992 if ( isset( $parserOutputHooks[$hookName] ) ) {
1993 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1999 $this->enableOOUI();
2003 if ( !$this->limitReportJSData ) {
2011 $outputPage = $this;
2012 Hooks::run(
'LanguageLinks', [ $this->
getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
2020 $this->mEnableTOC =
true;
2032 public function addParserOutputContent(
ParserOutput $parserOutput, $poOptions = [] ) {
2033 $this->addParserOutputText( $parserOutput, $poOptions );
2035 $this->addModules( $parserOutput->
getModules() );
2049 public function addParserOutputText(
ParserOutput $parserOutput, $poOptions = [] ) {
2050 $text = $parserOutput->
getText( $poOptions );
2052 $outputPage = $this;
2054 $this->addHTML( $text );
2063 function addParserOutput(
ParserOutput $parserOutput, $poOptions = [] ) {
2064 $this->addParserOutputMetadata( $parserOutput );
2065 $this->addParserOutputText( $parserOutput, $poOptions );
2073 public function addTemplate( &
$template ) {
2095 public function parse( $text, $linestart =
true, $interface =
false, $language =
null ) {
2096 return $this->parseInternal(
2097 $text, $this->
getTitle(), $linestart,
false, $interface, $language
2099 'enableSectionEditLinks' =>
false,
2114 public function parseAsContent( $text, $linestart =
true ) {
2115 return $this->parseInternal(
2116 $text, $this->
getTitle(), $linestart,
true,
false,
null
2118 'enableSectionEditLinks' =>
false,
2119 'wrapperDivClass' =>
''
2135 public function parseAsInterface( $text, $linestart =
true ) {
2136 return $this->parseInternal(
2137 $text, $this->
getTitle(), $linestart,
true,
true,
null
2139 'enableSectionEditLinks' =>
false,
2140 'wrapperDivClass' =>
''
2158 public function parseInlineAsInterface( $text, $linestart =
true ) {
2159 return Parser::stripOuterParagraph(
2160 $this->parseAsInterface( $text, $linestart )
2177 public function parseInline( $text, $linestart =
true, $interface =
false ) {
2178 $parsed = $this->parseInternal(
2179 $text, $this->
getTitle(), $linestart,
false, $interface,
null
2181 'enableSectionEditLinks' =>
false,
2182 'wrapperDivClass' =>
'',
2184 return Parser::stripOuterParagraph( $parsed );
2201 private function parseInternal( $text,
$title, $linestart, $tidy, $interface, $language ) {
2204 if ( is_null(
$title ) ) {
2205 throw new MWException(
'Empty $mTitle in ' . __METHOD__ );
2208 $popts = $this->parserOptions();
2209 $oldTidy = $popts->setTidy( $tidy );
2210 $oldInterface = $popts->setInterfaceMessage( (
bool)$interface );
2212 if ( $language !==
null ) {
2213 $oldLang = $popts->setTargetLanguage( $language );
2216 $parserOutput =
$wgParser->getFreshParser()->parse(
2218 $linestart,
true, $this->mRevisionId
2221 $popts->setTidy( $oldTidy );
2222 $popts->setInterfaceMessage( $oldInterface );
2224 if ( $language !==
null ) {
2225 $popts->setTargetLanguage( $oldLang );
2228 return $parserOutput;
2236 public function setCdnMaxage( $maxage ) {
2237 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2249 public function lowerCdnMaxage( $maxage ) {
2250 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2251 $this->setCdnMaxage( $this->mCdnMaxage );
2266 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2268 $maxTTL = $maxTTL ?: $this->
getConfig()->get(
'SquidMaxage' );
2270 if ( $mtime ===
null || $mtime ===
false ) {
2274 $age = MWTimestamp::time() -
wfTimestamp( TS_UNIX, $mtime );
2275 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2276 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2278 $this->lowerCdnMaxage( (
int)$adaptiveTTL );
2288 public function enableClientCache( $state ) {
2289 return wfSetVar( $this->mEnableClientCache, $state );
2297 function getCacheVaryCookies() {
2298 if ( self::$cacheVaryCookies ===
null ) {
2300 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2301 SessionManager::singleton()->getVaryCookies(),
2305 $config->
get(
'CacheVaryCookies' )
2307 Hooks::run(
'GetCacheVaryCookies', [ $this, &self::$cacheVaryCookies ] );
2309 return self::$cacheVaryCookies;
2318 function haveCacheVaryCookies() {
2320 foreach ( $this->getCacheVaryCookies()
as $cookieName ) {
2321 if (
$request->getCookie( $cookieName,
'',
'' ) !==
'' ) {
2322 wfDebug( __METHOD__ .
": found $cookieName\n" );
2326 wfDebug( __METHOD__ .
": no cache-varying cookies found\n" );
2338 public function addVaryHeader(
$header,
array $option =
null ) {
2339 if ( !array_key_exists(
$header, $this->mVaryHeader ) ) {
2340 $this->mVaryHeader[
$header] = [];
2342 if ( !is_array( $option ) ) {
2346 array_unique( array_merge( $this->mVaryHeader[
$header], $option ) );
2355 public function getVaryHeader() {
2357 if ( $this->getCacheVaryCookies() ) {
2358 $this->addVaryHeader(
'Cookie' );
2361 foreach ( SessionManager::singleton()->getVaryHeaders()
as $header =>
$options ) {
2364 return 'Vary: ' . implode(
', ', array_keys( $this->mVaryHeader ) );
2372 public function addLinkHeader(
$header ) {
2373 $this->mLinkHeader[] =
$header;
2381 public function getLinkHeader() {
2382 if ( !$this->mLinkHeader ) {
2386 return 'Link: ' . implode(
',', $this->mLinkHeader );
2396 public function getKeyHeader() {
2399 $cvCookies = $this->getCacheVaryCookies();
2401 $cookiesOption = [];
2402 foreach ( $cvCookies
as $cookieName ) {
2403 $cookiesOption[] =
'param=' . $cookieName;
2405 $this->addVaryHeader(
'Cookie', $cookiesOption );
2407 foreach ( SessionManager::singleton()->getVaryHeaders()
as $header =>
$options ) {
2412 foreach ( $this->mVaryHeader
as $header => $option ) {
2414 if ( is_array( $option ) &&
count( $option ) > 0 ) {
2415 $newheader .=
';' . implode(
';', $option );
2417 $headers[] = $newheader;
2419 $key =
'Key: ' . implode(
',', $headers );
2431 private function addAcceptLanguage() {
2433 if ( !$title instanceof
Title ) {
2438 if ( !$this->
getRequest()->getCheck(
'variant' ) &&
$lang->hasVariants() ) {
2439 $variants =
$lang->getVariants();
2441 foreach ( $variants
as $variant ) {
2442 if ( $variant ===
$lang->getCode() ) {
2456 $aloption[] =
"substr=$variant";
2461 if ( $variantBCP47 !== $variant ) {
2462 $aloption[] =
"substr=$variantBCP47";
2465 $this->addVaryHeader(
'Accept-Language', $aloption );
2479 public function preventClickjacking( $enable =
true ) {
2480 $this->mPreventClickjacking = $enable;
2488 public function allowClickjacking() {
2489 $this->mPreventClickjacking =
false;
2498 public function getPreventClickjacking() {
2499 return $this->mPreventClickjacking;
2509 public function getFrameOptions() {
2511 if ( $config->
get(
'BreakFrames' ) ) {
2513 } elseif ( $this->mPreventClickjacking && $config->
get(
'EditPageFrameOptions' ) ) {
2514 return $config->
get(
'EditPageFrameOptions' );
2522 public function sendCacheControl() {
2526 $this->addVaryHeader(
'Cookie' );
2527 $this->addAcceptLanguage();
2529 # don't serve compressed data to clients who can't handle it
2530 # maintain different caches for logged-in users and non-logged in ones
2531 $response->header( $this->getVaryHeader() );
2533 if ( $config->
get(
'UseKeyHeader' ) ) {
2534 $response->header( $this->getKeyHeader() );
2537 if ( $this->mEnableClientCache ) {
2539 $config->
get(
'UseSquid' ) &&
2541 !SessionManager::getGlobalSession()->isPersistent() &&
2542 !$this->isPrintable() &&
2543 $this->mCdnMaxage != 0 &&
2544 !$this->haveCacheVaryCookies()
2546 if ( $config->
get(
'UseESI' ) ) {
2547 # We'll purge the proxy cache explicitly, but require end user agents
2548 # to revalidate against the proxy on each visit.
2549 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2551 ": proxy caching with ESI; {$this->mLastModified} **",
'private' );
2552 # start with a shorter timeout for initial testing
2553 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2555 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2556 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2558 $response->header(
'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2560 # We'll purge the proxy cache for anons explicitly, but require end user agents
2561 # to revalidate against the proxy on each visit.
2562 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2563 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2565 ": local proxy caching; {$this->mLastModified} **",
'private' );
2566 # start with a shorter timeout for initial testing
2567 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2569 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2572 # We do want clients to cache if they can, but they *must* check for updates
2573 # on revisiting the page.
2574 wfDebug( __METHOD__ .
": private caching; {$this->mLastModified} **",
'private' );
2575 $response->header(
'Expires: ' . gmdate(
'D, d M Y H:i:s', 0 ) .
' GMT' );
2576 $response->header(
"Cache-Control: private, must-revalidate, max-age=0" );
2578 if ( $this->mLastModified ) {
2579 $response->header(
"Last-Modified: {$this->mLastModified}" );
2582 wfDebug( __METHOD__ .
": no caching **",
'private' );
2584 # In general, the absence of a last modified header should be enough to prevent
2585 # the client from using its cache. We send a few other things just to make sure.
2586 $response->header(
'Expires: ' . gmdate(
'D, d M Y H:i:s', 0 ) .
' GMT' );
2587 $response->header(
'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2588 $response->header(
'Pragma: no-cache' );
2597 public function loadSkinModules( $sk ) {
2599 if ( $group ===
'styles' ) {
2600 foreach (
$modules as $key => $moduleMembers ) {
2601 $this->addModuleStyles( $moduleMembers );
2619 public function output( $return =
false ) {
2620 if ( $this->mDoNothing ) {
2621 return $return ?
'' :
null;
2627 if ( $this->mRedirect !=
'' ) {
2628 # Standards require redirect URLs to be absolute
2631 $redirect = $this->mRedirect;
2632 $code = $this->mRedirectCode;
2634 if (
Hooks::run(
"BeforePageRedirect", [ $this, &$redirect, &
$code ] ) ) {
2636 if ( !$config->
get(
'DebugRedirects' ) ) {
2641 if ( $config->
get(
'VaryOnXFP' ) ) {
2642 $this->addVaryHeader(
'X-Forwarded-Proto' );
2644 $this->sendCacheControl();
2646 $response->header(
"Content-Type: text/html; charset=utf-8" );
2647 if ( $config->
get(
'DebugRedirects' ) ) {
2648 $url = htmlspecialchars( $redirect );
2649 print
"<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2650 print
"<p>Location: <a href=\"$url\">$url</a></p>\n";
2651 print
"</body>\n</html>\n";
2653 $response->header(
'Location: ' . $redirect );
2657 return $return ?
'' :
null;
2658 } elseif ( $this->mStatusCode ) {
2659 $response->statusHeader( $this->mStatusCode );
2662 # Buffer output; final headers may depend on later processing
2665 $response->header(
'Content-type: ' . $config->
get(
'MimeType' ) .
'; charset=UTF-8' );
2666 $response->header(
'Content-language: ' .
2667 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2669 if ( !$this->mArticleBodyOnly ) {
2673 $linkHeader = $this->getLinkHeader();
2674 if ( $linkHeader ) {
2679 $frameOptions = $this->getFrameOptions();
2680 if ( $frameOptions ) {
2681 $response->header(
"X-Frame-Options: $frameOptions" );
2686 if ( $this->mArticleBodyOnly ) {
2687 echo $this->mBodytext;
2690 if ( $this->
getRequest()->getBool(
'safemode' ) ) {
2691 $this->disallowUserJs();
2695 $this->loadSkinModules( $sk );
2700 $outputPage = $this;
2707 }
catch ( Exception
$e ) {
2716 }
catch ( Exception
$e ) {
2721 $this->sendCacheControl();
2724 return ob_get_clean();
2741 public function prepareErrorPage( $pageTitle, $htmlTitle =
false ) {
2742 $this->setPageTitle( $pageTitle );
2743 if ( $htmlTitle !==
false ) {
2744 $this->setHTMLTitle( $htmlTitle );
2746 $this->setRobotPolicy(
'noindex,nofollow' );
2747 $this->setArticleRelated(
false );
2748 $this->enableClientCache(
false );
2749 $this->mRedirect =
'';
2750 $this->clearSubtitle();
2766 public function showErrorPage(
$title, $msg,
$params = [] ) {
2767 if ( !
$title instanceof Message ) {
2771 $this->prepareErrorPage(
$title );
2773 if ( $msg instanceof Message ) {
2775 trigger_error(
'Argument ignored: $params. The message parameters argument '
2776 .
'is discarded when the $msg argument is a Message object instead of '
2777 .
'a string.', E_USER_NOTICE );
2779 $this->addHTML( $msg->parseAsBlock() );
2781 $this->addWikiMsgArray( $msg,
$params );
2784 $this->returnToMain();
2793 public function showPermissionsErrorPage(
array $errors, $action =
null ) {
2794 foreach ( $errors
as $key => $error ) {
2795 $errors[$key] = (
array)$error;
2803 if ( in_array( $action, [
'read',
'edit',
'createpage',
'createtalk',
'upload' ] )
2804 && $this->
getUser()->isAnon() &&
count( $errors ) == 1 && isset( $errors[0][0] )
2805 && ( $errors[0][0] ==
'badaccess-groups' || $errors[0][0] ==
'badaccess-group0' )
2809 $displayReturnto =
null;
2811 # Due to T34276, if a user does not have read permissions,
2812 # $this->getTitle() will just give Special:Badtitle, which is
2813 # not especially useful as a returnto parameter. Use the title
2814 # from the request instead, if there was one.
2817 if ( $action ==
'edit' ) {
2818 $msg =
'whitelistedittext';
2819 $displayReturnto = $returnto;
2820 } elseif ( $action ==
'createpage' || $action ==
'createtalk' ) {
2821 $msg =
'nocreatetext';
2822 } elseif ( $action ==
'upload' ) {
2823 $msg =
'uploadnologintext';
2825 $msg =
'loginreqpagetext';
2832 $query[
'returnto'] = $returnto->getPrefixedText();
2835 $returntoquery =
$request->getValues();
2836 unset( $returntoquery[
'title'] );
2837 unset( $returntoquery[
'returnto'] );
2838 unset( $returntoquery[
'returntoquery'] );
2842 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2845 $this->
msg(
'loginreqlink' )->
text(),
2850 $this->prepareErrorPage( $this->
msg(
'loginreqtitle' ) );
2851 $this->addHTML( $this->
msg( $msg )->rawParams( $loginLink )->parse() );
2853 # Don't return to a page the user can't read otherwise
2854 # we'll end up in a pointless loop
2855 if ( $displayReturnto && $displayReturnto->userCan(
'read', $this->getUser() ) ) {
2856 $this->returnToMain(
null, $displayReturnto );
2859 $this->prepareErrorPage( $this->
msg(
'permissionserrors' ) );
2860 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2870 public function versionRequired( $version ) {
2871 $this->prepareErrorPage( $this->
msg(
'versionrequired', $version ) );
2873 $this->addWikiMsg(
'versionrequiredtext', $version );
2874 $this->returnToMain();
2884 public function formatPermissionsErrorMessage(
array $errors, $action =
null ) {
2885 if ( $action ==
null ) {
2886 $text = $this->
msg(
'permissionserrorstext',
count( $errors ) )->plain() .
"\n\n";
2888 $action_desc = $this->
msg(
"action-$action" )->plain();
2890 'permissionserrorstext-withaction',
2893 )->plain() .
"\n\n";
2896 if (
count( $errors ) > 1 ) {
2897 $text .=
'<ul class="permissions-errors">' .
"\n";
2899 foreach ( $errors
as $error ) {
2901 $text .= $this->
msg( ...$error )->plain();
2906 $text .=
"<div class=\"permissions-errors\">\n" .
2907 $this->
msg( ...reset( $errors ) )->plain() .
2923 public function showLagWarning( $lag ) {
2925 if ( $lag >= $config->
get(
'SlaveLagWarning' ) ) {
2926 $lag = floor( $lag );
2927 $message = $lag < $config->
get(
'SlaveLagCritical' )
2930 $wrap =
Html::rawElement(
'div', [
'class' =>
"mw-{$message}" ],
"\n$1\n" );
2931 $this->wrapWikiMsg(
"$wrap\n", [ $message, $this->
getLanguage()->formatNum( $lag ) ] );
2941 public function showFatalError( $message ) {
2942 $this->prepareErrorPage( $this->
msg(
'internalerror' ) );
2944 $this->addHTML( $message );
2950 public function showUnexpectedValueError(
$name, $val ) {
2952 $this->showFatalError( $this->
msg(
'unexpected',
$name, $val )->escaped() );
2958 public function showFileCopyError( $old, $new ) {
2960 $this->showFatalError( $this->
msg(
'filecopyerror', $old, $new )->escaped() );
2966 public function showFileRenameError( $old, $new ) {
2968 $this->showFatalError( $this->
msg(
'filerenameerror', $old, $new )->escpaed() );
2974 public function showFileDeleteError(
$name ) {
2976 $this->showFatalError( $this->
msg(
'filedeleteerror',
$name )->escaped() );
2982 public function showFileNotFoundError(
$name ) {
2984 $this->showFatalError( $this->
msg(
'filenotfound',
$name )->escaped() );
2997 ->getLinkRendererFactory()->createFromLegacyOptions(
$options );
2998 $link = $this->
msg(
'returnto' )->rawParams(
3000 $this->addHTML(
"<p id=\"mw-returnto\">{$link}</p>\n" );
3011 public function returnToMain( $unused =
null, $returnto =
null, $returntoquery =
null ) {
3012 if ( $returnto ==
null ) {
3013 $returnto = $this->
getRequest()->getText(
'returnto' );
3016 if ( $returntoquery ==
null ) {
3017 $returntoquery = $this->
getRequest()->getText(
'returntoquery' );
3020 if ( $returnto ===
'' ) {
3024 if ( is_object( $returnto ) ) {
3025 $titleObj = $returnto;
3031 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
3035 $this->addReturnTo( $titleObj,
wfCgiToArray( $returntoquery ) );
3038 private function getRlClientContext() {
3039 if ( !$this->rlClientContext ) {
3040 $query = ResourceLoader::makeLoaderQuery(
3043 $this->
getSkin()->getSkinName(),
3044 $this->
getUser()->isLoggedIn() ? $this->
getUser()->getName() :
null,
3046 ResourceLoader::inDebugMode(),
3048 $this->isPrintable(),
3052 $this->getResourceLoader(),
3055 if ( $this->contentOverrideCallbacks ) {
3057 $this->rlClientContext->setContentOverrideCallback(
function (
Title $title ) {
3058 foreach ( $this->contentOverrideCallbacks
as $callback ) {
3062 if ( strpos( $text,
'</script>' ) !==
false ) {
3066 $titleFormatted =
$title->getPrefixedText();
3069 "Cannot preview $titleFormatted due to script-closing tag."
3080 return $this->rlClientContext;
3094 public function getRlClient() {
3095 if ( !$this->rlClient ) {
3096 $context = $this->getRlClientContext();
3097 $rl = $this->getResourceLoader();
3098 $this->addModules( [
3103 $this->addModuleStyles( [
3108 $this->
getSkin()->setupSkinUserCss( $this );
3111 $exemptGroups = [
'site' => [],
'noscript' => [],
'private' => [],
'user' => [] ];
3113 $moduleStyles = $this->getModuleStyles(
true );
3117 $userBatch = [
'user.styles',
'user' ];
3118 $siteBatch = array_diff( $moduleStyles, $userBatch );
3124 $moduleStyles = array_filter( $moduleStyles,
3126 $module = $rl->getModule(
$name );
3128 $group = $module->getGroup();
3129 if ( isset( $exemptGroups[$group] ) ) {
3130 $exemptStates[
$name] =
'ready';
3131 if ( !$module->isKnownEmpty(
$context ) ) {
3133 $exemptGroups[$group][] =
$name;
3141 $this->rlExemptStyleModules = $exemptGroups;
3144 'target' => $this->getTarget(),
3145 'nonce' => $this->getCSPNonce(),
3157 $rlClient->
setConfig( $this->getJSVars() );
3158 $rlClient->
setModules( $this->getModules(
true ) );
3162 $this->rlClient = $rlClient;
3164 return $this->rlClient;
3172 public function headElement(
Skin $sk, $includeStyle =
true ) {
3174 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3178 $this->getRlClient()->getDocumentAttributes(),
3183 if ( $this->getHTMLTitle() ==
'' ) {
3184 $this->setHTMLTitle( $this->
msg(
'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3196 $pieces[] =
Html::element(
'meta', [
'charset' =>
'UTF-8' ] );
3199 $pieces[] =
Html::element(
'title',
null, $this->getHTMLTitle() );
3200 $pieces[] = $this->getRlClient()->getHeadHtml();
3201 $pieces[] = $this->buildExemptModules();
3202 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3203 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3206 $pieces[] =
'<!--[if lt IE 9]>' .
3212 $this->getCSPNonce()
3218 $bodyClasses = $this->mAdditionalBodyClasses;
3219 $bodyClasses[] =
'mediawiki';
3221 # Classes for LTR/RTL directionality support
3222 $bodyClasses[] = $userdir;
3223 $bodyClasses[] =
"sitedir-$sitedir";
3225 $underline = $this->
getUser()->getOption(
'underline' );
3226 if ( $underline < 2 ) {
3230 $bodyClasses[] =
'mw-underline-' . ( $underline ?
'always' :
'never' );
3233 if ( $this->
getLanguage()->capitalizeAllNouns() ) {
3234 # A <body> class is probably not the best way to do this . . .
3235 $bodyClasses[] =
'capitalize-all-nouns';
3241 $bodyClasses[] =
'mw-hide-empty-elt';
3244 $bodyClasses[] =
'skin-' . Sanitizer::escapeClass( $sk->
getSkinName() );
3251 $bodyAttrs[
'class'] = implode(
' ', $bodyClasses );
3255 Hooks::run(
'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3259 return self::combineWrappedStrings( $pieces );
3267 public function getResourceLoader() {
3268 if ( is_null( $this->mResourceLoader ) ) {
3269 $this->mResourceLoader =
new ResourceLoader(
3271 LoggerFactory::getInstance(
'resourceloader' )
3274 return $this->mResourceLoader;
3285 public function makeResourceLoaderLink(
$modules, $only,
array $extraQuery = [] ) {
3290 $this->getRlClientContext(),
3294 $this->getCSPNonce()
3304 protected static function combineWrappedStrings(
array $chunks ) {
3306 $chunks = array_filter( $chunks,
'strlen' );
3307 return WrappedString::join(
"\n", $chunks );
3316 public function getBottomScripts() {
3318 $chunks[] = $this->getRlClient()->getBodyHtml();
3321 $chunks[] = $this->mScripts;
3323 if ( $this->limitReportJSData ) {
3324 $chunks[] = ResourceLoader::makeInlineScript(
3325 ResourceLoader::makeConfigSetScript(
3326 [
'wgPageParseReport' => $this->limitReportJSData ]
3328 $this->getCSPNonce()
3332 return self::combineWrappedStrings( $chunks );
3341 public function getJsConfigVars() {
3342 return $this->mJsConfigVars;
3351 public function addJsConfigVars(
$keys,
$value =
null ) {
3352 if ( is_array(
$keys ) ) {
3354 $this->mJsConfigVars[$key] =
$value;
3371 public function getJSVars() {
3374 $canonicalSpecialPageName =
false; # T23115
3375 $services = MediaWikiServices::getInstance();
3378 $ns =
$title->getNamespace();
3390 list( $canonicalSpecialPageName, ) =
3392 resolveAlias(
$title->getDBkey() );
3395 $curRevisionId = $wikiPage->getLatest();
3396 $articleId = $wikiPage->getId();
3402 $separatorTransTable =
$lang->separatorTransformTable();
3403 $separatorTransTable = $separatorTransTable ?: [];
3404 $compactSeparatorTransTable = [
3405 implode(
"\t", array_keys( $separatorTransTable ) ),
3406 implode(
"\t", $separatorTransTable ),
3408 $digitTransTable =
$lang->digitTransformTable();
3409 $digitTransTable = $digitTransTable ?: [];
3410 $compactDigitTransTable = [
3411 implode(
"\t", array_keys( $digitTransTable ) ),
3412 implode(
"\t", $digitTransTable ),
3418 'wgCanonicalNamespace' => $canonicalNamespace,
3419 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3420 'wgNamespaceNumber' =>
$title->getNamespace(),
3421 'wgPageName' =>
$title->getPrefixedDBkey(),
3422 'wgTitle' =>
$title->getText(),
3423 'wgCurRevisionId' => $curRevisionId,
3424 'wgRevisionId' => (int)$this->getRevisionId(),
3425 'wgArticleId' => $articleId,
3426 'wgIsArticle' => $this->isArticle(),
3427 'wgIsRedirect' =>
$title->isRedirect(),
3429 'wgUserName' =>
$user->isAnon() ? null :
$user->getName(),
3430 'wgUserGroups' =>
$user->getEffectiveGroups(),
3431 'wgCategories' => $this->getCategories(),
3432 'wgBreakFrames' => $this->getFrameOptions() ==
'DENY',
3433 'wgPageContentLanguage' =>
$lang->getCode(),
3434 'wgPageContentModel' =>
$title->getContentModel(),
3435 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3436 'wgDigitTransformTable' => $compactDigitTransTable,
3437 'wgDefaultDateFormat' =>
$lang->getDefaultDateFormat(),
3438 'wgMonthNames' =>
$lang->getMonthNamesArray(),
3439 'wgMonthNamesShort' =>
$lang->getMonthAbbreviationsArray(),
3440 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3441 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3443 'wgCSPNonce' => $this->getCSPNonce(),
3446 if (
$user->isLoggedIn() ) {
3448 $vars[
'wgUserEditCount'] =
$user->getEditCount();
3449 $userReg =
$user->getRegistration();
3450 $vars[
'wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX, $userReg ) * 1000 :
null;
3454 $vars[
'wgUserNewMsgRevisionId'] =
$user->getNewMessageRevisionId();
3457 $contLang =
$services->getContentLanguage();
3458 if ( $contLang->hasVariants() ) {
3459 $vars[
'wgUserVariant'] = $contLang->getPreferredVariant();
3465 $vars[
'wgRelevantPageIsProbablyEditable'] = $relevantTitle
3466 && $relevantTitle->quickUserCan(
'edit',
$user )
3467 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan(
'create',
$user ) );
3475 if (
$title->isMainPage() ) {
3476 $vars[
'wgIsMainPage'] =
true;
3479 if ( $this->mRedirectedFrom ) {
3480 $vars[
'wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3483 if ( $relevantUser ) {
3484 $vars[
'wgRelevantUserName'] = $relevantUser->getName();
3494 return array_merge(
$vars, $this->getJsConfigVars() );
3506 public function userCanPreview() {
3509 $request->getVal(
'action' ) !==
'submit' ||
3517 if ( !
$user->isLoggedIn() ) {
3521 if ( !
$user->matchEditToken(
$request->getVal(
'wpEditToken' ) ) ) {
3526 $errors =
$title->getUserPermissionsErrors(
'edit',
$user );
3527 if (
count( $errors ) !== 0 ) {
3537 public function getHeadLinksArray() {
3543 $canonicalUrl = $this->mCanonicalUrl;
3546 'name' =>
'generator',
3547 'content' =>
"MediaWiki $wgVersion",
3550 if ( $config->
get(
'ReferrerPolicy' ) !==
false ) {
3553 foreach ( array_reverse( (
array)$config->
get(
'ReferrerPolicy' ) )
as $i => $policy ) {
3555 'name' =>
'referrer',
3556 'content' => $policy,
3561 $p =
"{$this->mIndexPolicy},{$this->mFollowPolicy}";
3562 if ( $p !==
'index,follow' ) {
3571 foreach ( $this->mMetatags
as $tag ) {
3572 if ( strncasecmp( $tag[0],
'http:', 5 ) === 0 ) {
3574 $tag[0] = substr( $tag[0], 5 );
3575 } elseif ( strncasecmp( $tag[0],
'og:', 3 ) === 0 ) {
3580 $tagName =
"meta-{$tag[0]}";
3581 if ( isset( $tags[$tagName] ) ) {
3582 $tagName .= $tag[1];
3587 'content' => $tag[1]
3592 foreach ( $this->mLinktags
as $tag ) {
3596 # Universal edit button
3597 if ( $config->
get(
'UniversalEditButton' ) && $this->isArticleRelated() ) {
3600 && ( $this->
getTitle()->exists() ||
3604 $msg = $this->
msg(
'edit' )->text();
3606 'rel' =>
'alternate',
3607 'type' =>
'application/x-wiki',
3609 'href' => $this->
getTitle()->getEditURL(),
3615 'href' => $this->
getTitle()->getEditURL(),
3620 # Generally the order of the favicon and apple-touch-icon links
3621 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3622 # uses whichever one appears later in the HTML source. Make sure
3623 # apple-touch-icon is specified first to avoid this.
3624 if ( $config->
get(
'AppleTouchIcon' ) !==
false ) {
3626 'rel' =>
'apple-touch-icon',
3627 'href' => $config->
get(
'AppleTouchIcon' )
3631 if ( $config->
get(
'Favicon' ) !==
false ) {
3633 'rel' =>
'shortcut icon',
3634 'href' => $config->
get(
'Favicon' )
3638 # OpenSearch description link
3641 'type' =>
'application/opensearchdescription+xml',
3642 'href' =>
wfScript(
'opensearch_desc' ),
3643 'title' => $this->
msg(
'opensearch-desc' )->inContentLanguage()->
text(),
3646 # Real Simple Discovery link, provides auto-discovery information
3647 # for the MediaWiki API (and potentially additional custom API
3648 # support such as WordPress or Twitter-compatible APIs for a
3649 # blogging extension, etc)
3652 'type' =>
'application/rsd+xml',
3658 [
'action' =>
'rsd' ] ),
3664 if ( !$config->
get(
'DisableLangConversion' ) ) {
3666 if (
$lang->hasVariants() ) {
3667 $variants =
$lang->getVariants();
3668 foreach ( $variants
as $variant ) {
3670 'rel' =>
'alternate',
3672 'href' => $this->
getTitle()->getLocalURL(
3673 [
'variant' => $variant ] )
3677 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3679 'rel' =>
'alternate',
3680 'hreflang' =>
'x-default',
3681 'href' => $this->
getTitle()->getLocalURL() ] );
3686 if ( $this->copyrightUrl !==
null ) {
3687 $copyright = $this->copyrightUrl;
3690 if ( $config->
get(
'RightsPage' ) ) {
3694 $copyright = $copy->getLocalURL();
3698 if ( !$copyright && $config->
get(
'RightsUrl' ) ) {
3699 $copyright = $config->
get(
'RightsUrl' );
3706 'href' => $copyright ]
3711 if ( $config->
get(
'Feed' ) ) {
3714 foreach ( $this->getSyndicationLinks()
as $format =>
$link ) {
3715 # Use the page name for the title. In principle, this could
3716 # lead to issues with having the same name for different feeds
3717 # corresponding to the same page, but we can't avoid that at
3720 $feedLinks[] = $this->feedLink(
3723 # Used
messages:
'page-rss-feed' and 'page-atom-feed' (
for an easier grep)
3725 "page-{$format}-feed", $this->
getTitle()->getPrefixedText()
3730 # Recent changes feed should appear on every page (except recentchanges,
3731 # that would be redundant). Put it after the per-page feed to avoid
3732 # changing existing behavior. It's still available, probably via a
3733 # menu in your browser. Some sites might have a different feed they'd
3734 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3735 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3736 # If so, use it instead.
3737 $sitename = $config->
get(
'Sitename' );
3738 if ( $config->
get(
'OverrideSiteFeed' ) ) {
3739 foreach ( $config->
get(
'OverrideSiteFeed' )
as $type => $feedUrl ) {
3741 $feedLinks[] = $this->feedLink(
3744 $this->
msg(
"site-{$type}-feed", $sitename )->
text()
3747 } elseif ( !$this->
getTitle()->isSpecial(
'Recentchanges' ) ) {
3749 foreach ( $config->
get(
'AdvertisedFeedTypes' )
as $format ) {
3750 $feedLinks[] = $this->feedLink(
3752 $rctitle->getLocalURL( [
'feed' => $format ] ),
3753 # For grep: 'site-rss-feed', 'site-atom-feed'
3754 $this->
msg(
"site-{$format}-feed", $sitename )->text()
3759 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3760 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3761 # use OutputPage::addFeedLink() instead.
3762 Hooks::run(
'AfterBuildFeedLinks', [ &$feedLinks ] );
3764 $tags += $feedLinks;
3768 if ( $config->
get(
'EnableCanonicalServerLink' ) ) {
3769 if ( $canonicalUrl !==
false ) {
3772 if ( $this->isArticleRelated() ) {
3781 if ( in_array( $action, [
'history',
'info' ] ) ) {
3782 $query =
"action={$action}";
3788 $reqUrl = $this->
getRequest()->getRequestURL();
3793 if ( $canonicalUrl !==
false ) {
3795 'rel' =>
'canonical',
3796 'href' => $canonicalUrl
3805 Hooks::run(
'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3818 private function feedLink(
$type, $url, $text ) {
3820 'rel' =>
'alternate',
3821 'type' =>
"application/$type+xml",
3836 public function addStyle( $style, $media =
'', $condition =
'', $dir =
'' ) {
3842 $options[
'condition'] = $condition;
3857 public function addInlineStyle( $style_css, $flip =
'noflip' ) {
3858 if ( $flip ===
'flip' && $this->
getLanguage()->isRTL() ) {
3859 # If wanted, and the interface is right-to-left, flip the CSS
3860 $style_css = CSSJanus::transform( $style_css,
true,
false );
3870 protected function buildExemptModules() {
3884 $chunks[] = implode(
'', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3888 [
'name' =>
'ResourceLoaderDynamicStyles',
'content' =>
'' ]
3891 $separateReq = [
'site.styles',
'user.styles' ];
3892 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3894 $chunks[] = $this->makeResourceLoaderLink(
3895 array_diff( $moduleNames, $separateReq ),
3899 foreach ( array_intersect( $moduleNames, $separateReq )
as $name ) {
3902 $chunks[] = $this->makeResourceLoaderLink(
$name,
3908 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3914 public function buildCssLinksArray() {
3917 foreach ( $this->styles
as $file =>
$options ) {
3920 $links[$file] =
$link;
3940 if ( isset(
$options[
'media'] ) ) {
3941 $media = self::transformCssMedia(
$options[
'media'] );
3942 if ( is_null( $media ) ) {
3949 if ( substr( $style, 0, 1 ) ==
'/' ||
3950 substr( $style, 0, 5 ) ==
'http:' ||
3951 substr( $style, 0, 6 ) ==
'https:' ) {
3956 $url = self::transformResourcePath(
3958 $config->
get(
'StylePath' ) .
'/' . $style
3964 if ( isset(
$options[
'condition'] ) ) {
3965 $condition = htmlspecialchars(
$options[
'condition'] );
3966 $link =
"<!--[if $condition]>$link<![endif]-->";
3992 public static function transformResourcePath(
Config $config,
$path ) {
3996 $remotePathPrefix = $config->
get(
'ResourceBasePath' );
3997 if ( $remotePathPrefix ===
'' ) {
4002 $remotePath = $remotePathPrefix;
4004 if ( strpos(
$path, $remotePath ) !== 0 || substr(
$path, 0, 2 ) ===
'//' ) {
4013 $uploadPath = $config->
get(
'UploadPath' );
4014 if ( strpos(
$path, $uploadPath ) === 0 ) {
4015 $localDir = $config->
get(
'UploadDirectory' );
4016 $remotePathPrefix = $remotePath = $uploadPath;
4019 $path = RelPath::getRelativePath(
$path, $remotePath );
4020 return self::transformFilePath( $remotePathPrefix, $localDir,
$path );
4034 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4035 $hash = md5_file(
"$localPath/$file" );
4036 if ( $hash ===
false ) {
4037 wfLogWarning( __METHOD__ .
": Failed to hash $localPath/$file" );
4040 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
4050 public static function transformCssMedia( $media ) {
4054 $screenMediaQueryRegex =
'/^(?:only\s+)?screen\b/i';
4058 'printable' =>
'print',
4059 'handheld' =>
'handheld',
4061 foreach ( $switches
as $switch => $targetMedia ) {
4063 if ( $media == $targetMedia ) {
4065 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4079 if ( $targetMedia ==
'print' || $media ==
'screen' ) {
4095 public function addWikiMsg( ) {
4096 $args = func_get_args();
4109 public function addWikiMsgArray(
$name,
$args ) {
4110 $this->addHTML( $this->
msg(
$name,
$args )->parseAsBlock() );
4138 public function wrapWikiMsg( $wrap ) {
4139 $msgSpecs = func_get_args();
4140 array_shift( $msgSpecs );
4141 $msgSpecs = array_values( $msgSpecs );
4143 foreach ( $msgSpecs
as $n => $spec ) {
4144 if ( is_array( $spec ) ) {
4147 if ( isset(
$args[
'options'] ) ) {
4148 unset(
$args[
'options'] );
4150 'Adding "options" to ' . __METHOD__ .
' is no longer supported',
4160 $this->addWikiText(
$s );
4168 public function isTOCEnabled() {
4169 return $this->mEnableTOC;
4178 public function enableSectionEditLinks( $flag =
true ) {
4187 public function sectionEditLinksEnabled() {
4199 public static function setupOOUI( $skinName =
'default', $dir =
'ltr' ) {
4201 $theme = $themes[$skinName] ?? $themes[
'default'];
4203 $themeClass =
"OOUI\\{$theme}Theme";
4204 OOUI\Theme::setSingleton(
new $themeClass() );
4205 OOUI\Element::setDefaultDir( $dir );
4214 public function enableOOUI() {
4216 strtolower( $this->
getSkin()->getSkinName() ),
4219 $this->addModuleStyles( [
4220 'oojs-ui-core.styles',
4221 'oojs-ui.styles.indicators',
4222 'oojs-ui.styles.textures',
4223 'mediawiki.widgets.styles',
4224 'oojs-ui.styles.icons-content',
4225 'oojs-ui.styles.icons-alerts',
4226 'oojs-ui.styles.icons-interactions',
4239 public function getCSPNonce() {
4243 if ( $this->CSPNonce ===
null ) {
4246 $rand = random_bytes( 15 );
4247 $this->CSPNonce = base64_encode( $rand );
4249 return $this->CSPNonce;