Go to the documentation of this file.
27 use Wikimedia\RelPath;
28 use Wikimedia\WrappedString;
29 use Wikimedia\WrappedStringList;
191 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
274 'Accept-Encoding' =>
null,
345 public function redirect( $url, $responsecode =
'302' ) {
346 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
347 $this->mRedirect = str_replace(
"\n",
'', $url );
348 $this->mRedirectCode = $responsecode;
369 $this->copyrightUrl = $url;
378 $this->mStatusCode = $statusCode;
389 $this->mMetatags[] = [ $name, $val ];
410 $this->mLinktags[] = $linkarr;
429 $this->mCanonicalUrl = $url;
451 $this->mScripts .= $script;
485 $type = ResourceLoaderModule::TYPE_COMBINED
488 $filteredModules = [];
494 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
498 $filteredModules[] = $val;
501 return $filteredModules;
505 static $warnings = [];
506 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
511 'Module "{module}" not loadable on target "{target}".',
513 'module' => $moduleName,
514 'target' => $this->mTarget,
529 $type = ResourceLoaderModule::TYPE_COMBINED
531 $modules = array_values( array_unique( $this->$param ) );
543 $this->mModules = array_merge( $this->mModules, (array)
$modules );
555 ResourceLoaderModule::TYPE_STYLES
569 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)
$modules );
585 $this->mTarget = $target;
596 if ( !$this->contentOverrides ) {
600 return $this->contentOverrides[$key] ??
null;
605 $this->contentOverrides[$key] =
$content;
616 $this->contentOverrideCallbacks[] = $callback;
641 $this->mHeadItems[$name] = $value;
651 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
661 return isset( $this->mHeadItems[$name] );
671 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
682 $this->mArticleBodyOnly = $only;
702 $this->mProperties[$name] = $value;
713 return $this->mProperties[$name] ??
null;
728 if ( !$timestamp || $timestamp ==
'19700101000000' ) {
729 wfDebug( __METHOD__ .
": CACHE DISABLED, NO TIMESTAMP\n" );
733 if ( !$config->get(
'CachePages' ) ) {
734 wfDebug( __METHOD__ .
": CACHE DISABLED\n" );
740 'page' => $timestamp,
741 'user' => $this->
getUser()->getTouched(),
742 'epoch' => $config->get(
'CacheEpoch' )
744 if ( $config->get(
'UseCdn' ) ) {
747 $config->get(
'CdnMaxAge' )
750 Hooks::run(
'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
752 $maxModified = max( $modifiedTimes );
753 $this->mLastModified =
wfTimestamp( TS_RFC2822, $maxModified );
755 $clientHeader = $this->
getRequest()->getHeader(
'If-Modified-Since' );
756 if ( $clientHeader ===
false ) {
757 wfDebug( __METHOD__ .
": client did not send If-Modified-Since header",
'private' );
761 # IE sends sizes after the date like this:
762 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
763 # this breaks strtotime().
764 $clientHeader = preg_replace(
'/;.*$/',
'', $clientHeader );
766 Wikimedia\suppressWarnings();
767 $clientHeaderTime = strtotime( $clientHeader );
768 Wikimedia\restoreWarnings();
769 if ( !$clientHeaderTime ) {
771 .
": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
774 $clientHeaderTime =
wfTimestamp( TS_MW, $clientHeaderTime );
778 foreach ( $modifiedTimes as $name => $value ) {
779 if ( $info !==
'' ) {
782 $info .=
"$name=" .
wfTimestamp( TS_ISO_8601, $value );
785 wfDebug( __METHOD__ .
": client sent If-Modified-Since: " .
786 wfTimestamp( TS_ISO_8601, $clientHeaderTime ),
'private' );
787 wfDebug( __METHOD__ .
": effective Last-Modified: " .
788 wfTimestamp( TS_ISO_8601, $maxModified ),
'private' );
789 if ( $clientHeaderTime < $maxModified ) {
790 wfDebug( __METHOD__ .
": STALE, $info",
'private' );
795 # Give a 304 Not Modified response code and disable body output
796 wfDebug( __METHOD__ .
": NOT MODIFIED, $info",
'private' );
797 ini_set(
'zlib.output_compression', 0 );
798 $this->
getRequest()->response()->statusHeader( 304 );
820 return $reqTime - $maxAge;
830 $this->mLastModified =
wfTimestamp( TS_RFC2822, $timestamp );
844 if ( isset( $policy[
'index'] ) ) {
847 if ( isset( $policy[
'follow'] ) ) {
860 $policy = trim( $policy );
861 if ( in_array( $policy, [
'index',
'noindex' ] ) ) {
862 $this->mIndexPolicy = $policy;
874 $policy = trim( $policy );
875 if ( in_array( $policy, [
'follow',
'nofollow' ] ) ) {
876 $this->mFollowPolicy = $policy;
887 if ( $name instanceof
Message ) {
888 $this->mHTMLtitle = $name->setContext( $this->
getContext() )->text();
890 $this->mHTMLtitle = $name;
909 $this->mRedirectedFrom =
$t;
925 if ( $name instanceof
Message ) {
926 $name = $name->setContext( $this->
getContext() )->text();
929 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
930 # but leave "<i>foobar</i>" alone
932 $this->mPageTitle = $nameWithTags;
934 # change "<i>foo&bar</i>" to "foo&bar"
937 ->inContentLanguage()
958 $this->displayTitle = $html;
971 if ( $html ===
null ) {
972 $html = $this->
getTitle()->getPrefixedText();
986 $nsPrefix = $this->
getTitle()->getNsText() .
':';
987 $prefix = preg_quote( $nsPrefix,
'/' );
989 return preg_replace(
"/^$prefix/i",
'', $text );
1019 if ( $str instanceof
Message ) {
1020 $this->mSubtitle[] = $str->setContext( $this->
getContext() )->parse();
1022 $this->mSubtitle[] = $str;
1035 if (
$title->isRedirect() ) {
1036 $query[
'redirect'] =
'no';
1038 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1040 ->rawParams( $linkRenderer->makeLink(
$title,
null, [], $query ) );
1057 $this->mSubtitle = [];
1066 return implode(
"<br />\n\t\t\t\t", $this->mSubtitle );
1074 $this->mPrintable =
true;
1090 $this->mDoNothing =
true;
1132 $this->mFeedLinks = [];
1143 if ( $this->
getConfig()->
get(
'Feed' ) ) {
1144 return $this->
getConfig()->get(
'AdvertisedFeedTypes' );
1160 $this->mFeedLinks = [];
1163 $query =
"feed=$type";
1164 if ( is_string( $val ) ) {
1165 $query .=
'&' . $val;
1167 $this->mFeedLinks[
$type] = $this->
getTitle()->getLocalURL( $query );
1179 $this->mFeedLinks[$format] = $href;
1188 return count( $this->mFeedLinks ) > 0;
1216 $this->mIsArticle = $newVal;
1218 $this->mIsArticleRelated = $newVal;
1239 $this->mIsArticleRelated = $newVal;
1241 $this->mIsArticle =
false;
1260 $this->mHasCopyright = $hasCopyright;
1283 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1293 $this->mLanguageLinks = $newLinkArray;
1311 if ( !$categories ) {
1317 # Set all the values to 'normal'.
1318 $categories = array_fill_keys( array_keys( $categories ),
'normal' );
1320 # Mark hidden categories
1321 foreach (
$res as $row ) {
1322 if ( isset( $row->pp_value ) ) {
1323 $categories[$row->page_title] =
'hidden';
1328 $outputPage = $this;
1329 # Add the remaining categories to the skin
1331 'OutputPageMakeCategoryLinks',
1332 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1334 $services = MediaWikiServices::getInstance();
1335 $linkRenderer = $services->getLinkRenderer();
1336 foreach ( $categories as $category =>
$type ) {
1338 $category = (string)$category;
1339 $origcategory = $category;
1344 $services->getContentLanguage()->findVariantLink( $category,
$title,
true );
1345 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1348 $text = $services->getContentLanguage()->convertHtml(
$title->getText() );
1360 # Add the links to a LinkBatch
1365 # Fetch existence plus the hiddencat property
1367 $fields = array_merge(
1369 [
'page_namespace',
'page_title',
'pp_value' ]
1372 $res =
$dbr->select( [
'page',
'page_props' ],
1374 $lb->constructSet(
'page',
$dbr ),
1377 [
'page_props' => [
'LEFT JOIN', [
1378 'pp_propname' =>
'hiddencat',
1383 # Add the results to the link cache
1384 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1385 $lb->addResultToCache( $linkCache,
$res );
1396 $this->mCategoryLinks = [];
1422 if (
$type ===
'all' ) {
1423 $allCategories = [];
1424 foreach ( $this->mCategories as $categories ) {
1425 $allCategories = array_merge( $allCategories, $categories );
1427 return $allCategories;
1429 if ( !isset( $this->mCategories[
$type] ) ) {
1430 throw new InvalidArgumentException(
'Invalid category type given: ' .
$type );
1432 return $this->mCategories[
$type];
1447 ksort( $this->mIndicators );
1472 $text = $this->
msg(
'helppage-top-gethelp' )->escaped();
1474 if ( $overrideBaseUrl ) {
1477 $toUrlencoded =
wfUrlencode( str_replace(
' ',
'_', $to ) );
1478 $helpUrl =
"https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1485 'target' =>
'_blank',
1486 'class' =>
'mw-helplink',
1504 ResourceLoaderModule::TYPE_SCRIPTS,
1505 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1510 if ( $this->
getConfig()->
get(
'AllowSiteCSSOnRestrictedPages' ) ) {
1511 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1513 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1516 ResourceLoaderModule::TYPE_STYLES,
1528 if (
$type == ResourceLoaderModule::TYPE_COMBINED ) {
1529 return min( array_values( $this->mAllowedModules ) );
1531 return $this->mAllowedModules[
$type] ?? ResourceLoaderModule::ORIGIN_ALL;
1563 $this->mBodytext .= $text;
1575 public function addElement( $element, array $attribs = [], $contents =
'' ) {
1583 $this->mBodytext =
'';
1604 if ( $options !==
null ) {
1605 wfDeprecated( __METHOD__ .
' with non-null $options',
'1.31' );
1608 if ( $options !==
null && !empty( $options->isBogus ) ) {
1612 $anonPO->setAllowUnsafeRawHtml(
false );
1613 if ( !$options->matches( $anonPO ) ) {
1615 $options->isBogus =
false;
1619 if ( !$this->mParserOptions ) {
1620 if ( !$this->
getUser()->isSafeToLoad() ) {
1625 $po->setAllowUnsafeRawHtml(
false );
1626 $po->isBogus =
true;
1627 if ( $options !==
null ) {
1628 $this->mParserOptions = empty( $options->isBogus ) ? $options :
null;
1634 $this->mParserOptions->setAllowUnsafeRawHtml(
false );
1637 if ( $options !==
null && !empty( $options->isBogus ) ) {
1640 return wfSetVar( $this->mParserOptions,
null,
true );
1642 return wfSetVar( $this->mParserOptions, $options );
1654 $val = is_null( $revid ) ? null : intval( $revid );
1655 return wfSetVar( $this->mRevisionId, $val,
true );
1674 return $this->mRevisionId == 0 || $this->mRevisionId == $this->
getTitle()->getLatestRevID();
1685 return wfSetVar( $this->mRevisionTimestamp, $timestamp,
true );
1707 $val = [
'time' =>
$file->getTimestamp(),
'sha1' =>
$file->getSha1() ];
1709 return wfSetVar( $this->mFileVersion, $val,
true );
1783 $wrapperClass, $text
1832 $text,
Title $title, $linestart, $interface, $wrapperClass =
null
1835 $text,
$title, $linestart,
true, $interface,
null
1839 'enableSectionEditLinks' =>
false,
1840 'wrapperDivClass' => $wrapperClass ??
'',
1853 $this->mLanguageLinks =
1864 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->
getHeadItems() );
1868 $this->mPreventClickjacking = $this->mPreventClickjacking
1872 foreach ( (array)$parserOutput->
getTemplateIds() as $ns => $dbks ) {
1873 if ( isset( $this->mTemplateIds[$ns] ) ) {
1874 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1876 $this->mTemplateIds[$ns] = $dbks;
1881 $this->mImageTimeKeys[$dbk] = $data;
1885 $parserOutputHooks = $this->
getConfig()->get(
'ParserOutputHooks' );
1887 list( $hookName, $data ) = $hookInfo;
1888 if ( isset( $parserOutputHooks[$hookName] ) ) {
1889 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1899 if ( !$this->limitReportJSData ) {
1907 $outputPage = $this;
1908 Hooks::run(
'LanguageLinks', [ $this->
getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1916 $this->mEnableTOC =
true;
1945 $text = $parserOutput->
getText( $poOptions );
1947 $outputPage = $this;
1969 $this->
addHTML( $template->getHTML() );
1990 public function parse( $text, $linestart =
true, $interface =
false, $language =
null ) {
1993 $text, $this->
getTitle(), $linestart,
false, $interface, $language
1995 'enableSectionEditLinks' =>
false,
2012 $text, $this->
getTitle(), $linestart,
true,
false,
null
2014 'enableSectionEditLinks' =>
false,
2015 'wrapperDivClass' =>
''
2033 $text, $this->
getTitle(), $linestart,
true,
true,
null
2035 'enableSectionEditLinks' =>
false,
2036 'wrapperDivClass' =>
''
2073 public function parseInline( $text, $linestart =
true, $interface =
false ) {
2076 $text, $this->
getTitle(), $linestart,
false, $interface,
null
2078 'enableSectionEditLinks' =>
false,
2079 'wrapperDivClass' =>
'',
2099 if ( is_null(
$title ) ) {
2100 throw new MWException(
'Empty $mTitle in ' . __METHOD__ );
2104 $oldTidy = $popts->setTidy( $tidy );
2105 $oldInterface = $popts->setInterfaceMessage( (
bool)$interface );
2107 if ( $language !==
null ) {
2108 $oldLang = $popts->setTargetLanguage( $language );
2111 $parserOutput = MediaWikiServices::getInstance()->getParser()->getFreshParser()->parse(
2113 $linestart,
true, $this->mRevisionId
2116 $popts->setTidy( $oldTidy );
2117 $popts->setInterfaceMessage( $oldInterface );
2119 if ( $language !==
null ) {
2120 $popts->setTargetLanguage( $oldLang );
2123 return $parserOutput;
2132 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2145 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2163 $maxTTL = $maxTTL ?: $this->
getConfig()->get(
'CdnMaxAge' );
2165 if ( $mtime ===
null || $mtime ===
false ) {
2169 $age = MWTimestamp::time() - (int)
wfTimestamp( TS_UNIX, $mtime );
2170 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2171 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2184 return wfSetVar( $this->mEnableClientCache, $state );
2193 if ( self::$cacheVaryCookies ===
null ) {
2195 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2196 SessionManager::singleton()->getVaryCookies(),
2200 $config->get(
'CacheVaryCookies' )
2202 Hooks::run(
'GetCacheVaryCookies', [ $this, &self::$cacheVaryCookies ] );
2216 if ( $request->getCookie( $cookieName,
'',
'' ) !==
'' ) {
2217 wfDebug( __METHOD__ .
": found $cookieName\n" );
2221 wfDebug( __METHOD__ .
": no cache-varying cookies found\n" );
2235 if ( $option !==
null && count( $option ) > 0 ) {
2236 wfDeprecated(
'addVaryHeader $option is ignored',
'1.34' );
2238 if ( !array_key_exists(
$header, $this->mVaryHeader ) ) {
2239 $this->mVaryHeader[
$header] =
null;
2255 foreach ( SessionManager::singleton()->getVaryHeaders() as
$header => $options ) {
2258 return 'Vary: ' . implode(
', ', array_keys( $this->mVaryHeader ) );
2267 $this->mLinkHeader[] =
$header;
2276 if ( !$this->mLinkHeader ) {
2280 return 'Link: ' . implode(
',', $this->mLinkHeader );
2297 if ( !$this->
getRequest()->getCheck(
'variant' ) &&
$lang->hasVariants() ) {
2313 $this->mPreventClickjacking = $enable;
2322 $this->mPreventClickjacking =
false;
2344 if ( $config->get(
'BreakFrames' ) ) {
2346 } elseif ( $this->mPreventClickjacking && $config->get(
'EditPageFrameOptions' ) ) {
2347 return $config->get(
'EditPageFrameOptions' );
2361 return $config->get(
'OriginTrials' );
2367 $expiry = $config->get(
'ReportToExpiry' );
2373 $endpoints = $config->get(
'ReportToEndpoints' );
2375 if ( !$endpoints ) {
2379 $output = [
'max_age' => $expiry,
'endpoints' => [] ];
2381 foreach ( $endpoints as $endpoint ) {
2382 $output[
'endpoints'][] = [
'url' => $endpoint ];
2385 return json_encode( $output, JSON_UNESCAPED_SLASHES );
2391 $features = $config->get(
'FeaturePolicyReportOnly' );
2392 return implode(
';', $features );
2405 # don't serve compressed data to clients who can't handle it
2406 # maintain different caches for logged-in users and non-logged in ones
2409 if ( $this->mEnableClientCache ) {
2411 $config->get(
'UseCdn' ) &&
2413 !SessionManager::getGlobalSession()->isPersistent() &&
2414 !$this->isPrintable() &&
2415 $this->mCdnMaxage != 0 &&
2416 !$this->haveCacheVaryCookies()
2418 # We'll purge the proxy cache for anons explicitly, but require end user agents
2419 # to revalidate against the proxy on each visit.
2420 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2421 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2423 ": local proxy caching; {$this->mLastModified} **",
'private' );
2424 # start with a shorter timeout for initial testing
2425 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2427 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2429 # We do want clients to cache if they can, but they *must* check for updates
2430 # on revisiting the page.
2431 wfDebug( __METHOD__ .
": private caching; {$this->mLastModified} **",
'private' );
2432 $response->header(
'Expires: ' . gmdate(
'D, d M Y H:i:s', 0 ) .
' GMT' );
2433 $response->header(
"Cache-Control: private, must-revalidate, max-age=0" );
2435 if ( $this->mLastModified ) {
2436 $response->header(
"Last-Modified: {$this->mLastModified}" );
2439 wfDebug( __METHOD__ .
": no caching **",
'private' );
2441 # In general, the absence of a last modified header should be enough to prevent
2442 # the client from using its cache. We send a few other things just to make sure.
2443 $response->header(
'Expires: ' . gmdate(
'D, d M Y H:i:s', 0 ) .
' GMT' );
2444 $response->header(
'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2445 $response->header(
'Pragma: no-cache' );
2455 foreach ( $sk->getDefaultModules() as $group =>
$modules ) {
2456 if ( $group ===
'styles' ) {
2457 foreach (
$modules as $key => $moduleMembers ) {
2477 if ( $this->mDoNothing ) {
2478 return $return ?
'' :
null;
2484 if ( $this->mRedirect !=
'' ) {
2485 # Standards require redirect URLs to be absolute
2491 if (
Hooks::run(
"BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2492 if ( $code ==
'301' || $code ==
'303' ) {
2493 if ( !$config->get(
'DebugRedirects' ) ) {
2498 if ( $config->get(
'VaryOnXFP' ) ) {
2503 $response->header(
"Content-Type: text/html; charset=utf-8" );
2504 if ( $config->get(
'DebugRedirects' ) ) {
2505 $url = htmlspecialchars( $redirect );
2506 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2507 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2508 print "</body>\n</html>\n";
2510 $response->header(
'Location: ' . $redirect );
2514 return $return ?
'' :
null;
2515 } elseif ( $this->mStatusCode ) {
2516 $response->statusHeader( $this->mStatusCode );
2519 # Buffer output; final headers may depend on later processing
2522 $response->header(
'Content-type: ' . $config->get(
'MimeType' ) .
'; charset=UTF-8' );
2523 $response->header(
'Content-language: ' .
2524 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2527 if ( $linkHeader ) {
2533 if ( $frameOptions ) {
2534 $response->header(
"X-Frame-Options: $frameOptions" );
2538 foreach ( $originTrials as $originTrial ) {
2539 $response->header(
"Origin-Trial: $originTrial",
false );
2544 $response->header(
"Report-To: $reportTo" );
2548 if ( $featurePolicyReportOnly ) {
2549 $response->header(
"Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2554 if ( $this->mArticleBodyOnly ) {
2558 if ( $this->
getRequest()->getBool(
'safemode' ) ) {
2568 $outputPage = $this;
2575 }
catch ( Exception $e ) {
2584 }
catch ( Exception $e ) {
2592 return ob_get_clean();
2611 if ( $htmlTitle !==
false ) {
2617 $this->mRedirect =
'';
2641 if ( $msg instanceof
Message ) {
2642 if ( $params !== [] ) {
2643 trigger_error(
'Argument ignored: $params. The message parameters argument '
2644 .
'is discarded when the $msg argument is a Message object instead of '
2645 .
'a string.', E_USER_NOTICE );
2647 $this->
addHTML( $msg->parseAsBlock() );
2662 $services = MediaWikiServices::getInstance();
2663 $permissionManager = $services->getPermissionManager();
2664 foreach ( $errors as $key => $error ) {
2665 $errors[$key] = (array)$error;
2674 if ( in_array( $action, [
'read',
'edit',
'createpage',
'createtalk',
'upload' ] )
2675 && $this->
getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2676 && ( $errors[0][0] ==
'badaccess-groups' || $errors[0][0] ==
'badaccess-group0' )
2677 && ( $permissionManager->groupHasPermission(
'user', $action )
2678 || $permissionManager->groupHasPermission(
'autoconfirmed', $action ) )
2680 $displayReturnto =
null;
2682 # Due to T34276, if a user does not have read permissions,
2683 # $this->getTitle() will just give Special:Badtitle, which is
2684 # not especially useful as a returnto parameter. Use the title
2685 # from the request instead, if there was one.
2688 if ( $action ==
'edit' ) {
2689 $msg =
'whitelistedittext';
2690 $displayReturnto = $returnto;
2691 } elseif ( $action ==
'createpage' || $action ==
'createtalk' ) {
2692 $msg =
'nocreatetext';
2693 } elseif ( $action ==
'upload' ) {
2694 $msg =
'uploadnologintext';
2696 $msg =
'loginreqpagetext';
2703 $query[
'returnto'] = $returnto->getPrefixedText();
2705 if ( !$request->wasPosted() ) {
2706 $returntoquery = $request->getValues();
2707 unset( $returntoquery[
'title'] );
2708 unset( $returntoquery[
'returnto'] );
2709 unset( $returntoquery[
'returntoquery'] );
2710 $query[
'returntoquery'] =
wfArrayToCgi( $returntoquery );
2715 $linkRenderer = $services->getLinkRenderer();
2717 $loginLink = $linkRenderer->makeKnownLink(
2719 $this->
msg(
'loginreqlink' )->text(),
2725 $this->
addHTML( $this->
msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->
parse() );
2727 # Don't return to a page the user can't read otherwise
2728 # we'll end up in a pointless loop
2729 if ( $displayReturnto && $permissionManager->userCan(
2730 'read', $this->getUser(), $displayReturnto
2749 $this->
addWikiMsg(
'versionrequiredtext', $version );
2761 if ( $action ==
null ) {
2762 $text = $this->
msg(
'permissionserrorstext', count( $errors ) )->plain() .
"\n\n";
2764 $action_desc = $this->
msg(
"action-$action" )->plain();
2766 'permissionserrorstext-withaction',
2769 )->plain() .
"\n\n";
2772 if ( count( $errors ) > 1 ) {
2773 $text .=
'<ul class="permissions-errors">' .
"\n";
2775 foreach ( $errors as $error ) {
2777 $text .= $this->
msg( ...$error )->plain();
2782 $text .=
"<div class=\"permissions-errors\">\n" .
2783 $this->
msg( ...reset( $errors ) )->plain() .
2801 if ( $lag >= $config->get(
'SlaveLagWarning' ) ) {
2802 $lag = floor( $lag );
2803 $message = $lag < $config->get(
'SlaveLagCritical' )
2806 $wrap =
Html::rawElement(
'div', [
'class' =>
"mw-{$message}" ],
"\n$1\n" );
2832 $linkRenderer = MediaWikiServices::getInstance()
2833 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2834 $link = $this->
msg(
'returnto' )->rawParams(
2835 $linkRenderer->makeLink(
$title, $text, [], $query ) )->escaped();
2836 $this->
addHTML(
"<p id=\"mw-returnto\">{$link}</p>\n" );
2847 public function returnToMain( $unused =
null, $returnto =
null, $returntoquery =
null ) {
2848 if ( $returnto ==
null ) {
2849 $returnto = $this->
getRequest()->getText(
'returnto' );
2852 if ( $returntoquery ==
null ) {
2853 $returntoquery = $this->
getRequest()->getText(
'returntoquery' );
2856 if ( $returnto ===
'' ) {
2860 if ( is_object( $returnto ) ) {
2861 $titleObj = $returnto;
2867 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2875 if ( !$this->rlClientContext ) {
2879 $this->
getSkin()->getSkinName(),
2880 $this->
getUser()->isLoggedIn() ? $this->
getUser()->getName() :
null,
2891 if ( $this->contentOverrideCallbacks ) {
2893 $this->rlClientContext->setContentOverrideCallback(
function (
Title $title ) {
2894 foreach ( $this->contentOverrideCallbacks as $callback ) {
2898 if ( strpos( $text,
'</script>' ) !==
false ) {
2902 $titleFormatted =
$title->getPrefixedText();
2905 "Cannot preview $titleFormatted due to script-closing tag."
2931 if ( !$this->rlClient ) {
2944 $this->
getSkin()->setupSkinUserCss( $this );
2947 $exemptGroups = [
'site' => [],
'noscript' => [],
'private' => [],
'user' => [] ];
2953 $userBatch = [
'user.styles',
'user' ];
2954 $siteBatch = array_diff( $moduleStyles, $userBatch );
2960 $moduleStyles = array_filter( $moduleStyles,
2961 function ( $name ) use ( $rl,
$context, &$exemptGroups, &$exemptStates ) {
2962 $module = $rl->getModule( $name );
2964 $group = $module->getGroup();
2965 if ( isset( $exemptGroups[$group] ) ) {
2966 $exemptStates[$name] =
'ready';
2967 if ( !$module->isKnownEmpty(
$context ) ) {
2969 $exemptGroups[$group][] = $name;
2977 $this->rlExemptStyleModules = $exemptGroups;
2990 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
3010 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3033 $pieces[] =
Html::element(
'meta', [
'charset' =>
'UTF-8' ] );
3037 $pieces[] = $this->
getRlClient()->getHeadHtml( $htmlAttribs[
'class'] ??
null );
3040 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3048 $shivUrl = $config->get(
'ResourceBasePath' ) .
'/resources/lib/html5shiv/html5shiv.js';
3049 $pieces[] =
'<!--[if lt IE 9]>' .
3056 $bodyClasses[] =
'mediawiki';
3058 # Classes for LTR/RTL directionality support
3059 $bodyClasses[] = $userdir;
3060 $bodyClasses[] =
"sitedir-$sitedir";
3062 $underline = $this->
getUser()->getOption(
'underline' );
3063 if ( $underline < 2 ) {
3067 $bodyClasses[] =
'mw-underline-' . ( $underline ?
'always' :
'never' );
3070 if ( $this->
getLanguage()->capitalizeAllNouns() ) {
3071 # A <body> class is probably not the best way to do this . . .
3072 $bodyClasses[] =
'capitalize-all-nouns';
3078 $bodyClasses[] =
'mw-hide-empty-elt';
3088 $bodyAttrs[
'class'] = implode(
' ', $bodyClasses );
3092 Hooks::run(
'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3105 if ( is_null( $this->mResourceLoader ) ) {
3107 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3141 $chunks = array_filter( $chunks,
'strlen' );
3142 return WrappedString::join(
"\n", $chunks );
3158 if ( $this->limitReportJSData ) {
3161 [
'wgPageParseReport' => $this->limitReportJSData ]
3187 if ( is_array(
$keys ) ) {
3188 foreach (
$keys as $key => $value ) {
3189 $this->mJsConfigVars[$key] = $value;
3194 $this->mJsConfigVars[
$keys] = $value;
3209 $canonicalSpecialPageName =
false; # T23115
3210 $services = MediaWikiServices::getInstance();
3213 $ns =
$title->getNamespace();
3214 $nsInfo = $services->getNamespaceInfo();
3215 $canonicalNamespace = $nsInfo->exists( $ns )
3216 ? $nsInfo->getCanonicalName( $ns )
3222 $relevantTitle = $sk->getRelevantTitle();
3223 $relevantUser = $sk->getRelevantUser();
3226 list( $canonicalSpecialPageName, ) =
3227 $services->getSpecialPageFactory()->
3228 resolveAlias(
$title->getDBkey() );
3231 $curRevisionId = $wikiPage->getLatest();
3232 $articleId = $wikiPage->getId();
3238 $separatorTransTable =
$lang->separatorTransformTable();
3239 $separatorTransTable = $separatorTransTable ?: [];
3240 $compactSeparatorTransTable = [
3241 implode(
"\t", array_keys( $separatorTransTable ) ),
3242 implode(
"\t", $separatorTransTable ),
3244 $digitTransTable =
$lang->digitTransformTable();
3245 $digitTransTable = $digitTransTable ?: [];
3246 $compactDigitTransTable = [
3247 implode(
"\t", array_keys( $digitTransTable ) ),
3248 implode(
"\t", $digitTransTable ),
3254 'wgCanonicalNamespace' => $canonicalNamespace,
3255 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3256 'wgNamespaceNumber' =>
$title->getNamespace(),
3257 'wgPageName' =>
$title->getPrefixedDBkey(),
3258 'wgTitle' =>
$title->getText(),
3259 'wgCurRevisionId' => $curRevisionId,
3261 'wgArticleId' => $articleId,
3263 'wgIsRedirect' =>
$title->isRedirect(),
3265 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3266 'wgUserGroups' => $user->getEffectiveGroups(),
3269 'wgPageContentLanguage' =>
$lang->getCode(),
3270 'wgPageContentModel' =>
$title->getContentModel(),
3271 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3272 'wgDigitTransformTable' => $compactDigitTransTable,
3273 'wgDefaultDateFormat' =>
$lang->getDefaultDateFormat(),
3274 'wgMonthNames' =>
$lang->getMonthNamesArray(),
3275 'wgMonthNamesShort' =>
$lang->getMonthAbbreviationsArray(),
3276 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3277 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3282 if ( $user->isLoggedIn() ) {
3283 $vars[
'wgUserId'] = $user->getId();
3284 $vars[
'wgUserEditCount'] = $user->getEditCount();
3285 $userReg = $user->getRegistration();
3286 $vars[
'wgUserRegistration'] = $userReg ? (int)
wfTimestamp( TS_UNIX, $userReg ) * 1000 :
null;
3290 $vars[
'wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3293 $contLang = $services->getContentLanguage();
3294 if ( $contLang->hasVariants() ) {
3295 $vars[
'wgUserVariant'] = $contLang->getPreferredVariant();
3300 $vars[
'wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3303 foreach (
$title->getRestrictionTypes() as
$type ) {
3306 $vars[
'wgRestriction' . ucfirst(
$type )] =
$title->getRestrictions(
$type );
3309 if (
$title->isMainPage() ) {
3310 $vars[
'wgIsMainPage'] =
true;
3313 if ( $this->mRedirectedFrom ) {
3314 $vars[
'wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3317 if ( $relevantUser ) {
3318 $vars[
'wgRelevantUserName'] = $relevantUser->getName();
3325 Hooks::run(
'MakeGlobalVariablesScript', [ &$vars, $this ] );
3343 $request->getVal(
'action' ) !==
'submit' ||
3344 !$request->wasPosted()
3351 if ( !$user->isLoggedIn() ) {
3355 if ( !$user->matchEditToken( $request->getVal(
'wpEditToken' ) ) ) {
3360 $errors =
$title->getUserPermissionsErrors(
'edit', $user );
3361 if ( count( $errors ) !== 0 ) {
3377 $pm = MediaWikiServices::getInstance()->getPermissionManager();
3378 return $pm->quickUserCan(
'edit', $user,
$title )
3379 && ( $this->
getTitle()->exists() ||
3380 $pm->quickUserCan(
'create', $user,
$title ) );
3395 'name' =>
'generator',
3396 'content' =>
"MediaWiki $wgVersion",
3399 if ( $config->get(
'ReferrerPolicy' ) !==
false ) {
3402 foreach ( array_reverse( (array)$config->get(
'ReferrerPolicy' ) ) as $i => $policy ) {
3404 'name' =>
'referrer',
3405 'content' => $policy,
3410 $p =
"{$this->mIndexPolicy},{$this->mFollowPolicy}";
3411 if ( $p !==
'index,follow' ) {
3420 foreach ( $this->mMetatags as $tag ) {
3421 if ( strncasecmp( $tag[0],
'http:', 5 ) === 0 ) {
3423 $tag[0] = substr( $tag[0], 5 );
3424 } elseif ( strncasecmp( $tag[0],
'og:', 3 ) === 0 ) {
3429 $tagName =
"meta-{$tag[0]}";
3430 if ( isset( $tags[$tagName] ) ) {
3431 $tagName .= $tag[1];
3436 'content' => $tag[1]
3441 foreach ( $this->mLinktags as $tag ) {
3445 # Universal edit button
3446 if ( $config->get(
'UniversalEditButton' ) && $this->isArticleRelated() ) {
3449 $msg = $this->
msg(
'edit' )->text();
3451 'rel' =>
'alternate',
3452 'type' =>
'application/x-wiki',
3454 'href' => $this->
getTitle()->getEditURL(),
3460 'href' => $this->
getTitle()->getEditURL(),
3465 # Generally the order of the favicon and apple-touch-icon links
3466 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3467 # uses whichever one appears later in the HTML source. Make sure
3468 # apple-touch-icon is specified first to avoid this.
3469 if ( $config->get(
'AppleTouchIcon' ) !==
false ) {
3471 'rel' =>
'apple-touch-icon',
3472 'href' => $config->get(
'AppleTouchIcon' )
3476 if ( $config->get(
'Favicon' ) !==
false ) {
3478 'rel' =>
'shortcut icon',
3479 'href' => $config->get(
'Favicon' )
3483 # OpenSearch description link
3486 'type' =>
'application/opensearchdescription+xml',
3487 'href' =>
wfScript(
'opensearch_desc' ),
3488 'title' => $this->
msg(
'opensearch-desc' )->inContentLanguage()->text(),
3491 # Real Simple Discovery link, provides auto-discovery information
3492 # for the MediaWiki API (and potentially additional custom API
3493 # support such as WordPress or Twitter-compatible APIs for a
3494 # blogging extension, etc)
3497 'type' =>
'application/rsd+xml',
3503 [
'action' =>
'rsd' ] ),
3509 if ( !$config->get(
'DisableLangConversion' ) ) {
3511 if (
$lang->hasVariants() ) {
3512 $variants =
$lang->getVariants();
3513 foreach ( $variants as $variant ) {
3515 'rel' =>
'alternate',
3517 'href' => $this->
getTitle()->getLocalURL(
3518 [
'variant' => $variant ] )
3522 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3524 'rel' =>
'alternate',
3525 'hreflang' =>
'x-default',
3526 'href' => $this->
getTitle()->getLocalURL() ] );
3531 if ( $this->copyrightUrl !==
null ) {
3535 if ( $config->get(
'RightsPage' ) ) {
3539 $copyright = $copy->getLocalURL();
3543 if ( !$copyright && $config->get(
'RightsUrl' ) ) {
3544 $copyright = $config->get(
'RightsUrl' );
3551 'href' => $copyright ]
3556 if ( $config->get(
'Feed' ) ) {
3560 # Use the page name for the title. In principle, this could
3561 # lead to issues with having the same name for different feeds
3562 # corresponding to the same page, but we can't avoid that at
3568 # Used messages:
'page-rss-feed' and
'page-atom-feed' (
for an easier grep)
3570 "page-{$format}-feed", $this->
getTitle()->getPrefixedText()
3575 # Recent changes feed should appear on every page (except recentchanges,
3576 # that would be redundant). Put it after the per-page feed to avoid
3577 # changing existing behavior. It's still available, probably via a
3578 # menu in your browser. Some sites might have a different feed they'd
3579 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3580 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3581 # If so, use it instead.
3582 $sitename = $config->get(
'Sitename' );
3583 $overrideSiteFeed = $config->get(
'OverrideSiteFeed' );
3584 if ( $overrideSiteFeed ) {
3585 foreach ( $overrideSiteFeed as
$type => $feedUrl ) {
3590 $this->
msg(
"site-{$type}-feed", $sitename )->text()
3593 } elseif ( !$this->
getTitle()->isSpecial(
'Recentchanges' ) ) {
3598 $rctitle->getLocalURL( [
'feed' => $format ] ),
3599 # For grep:
'site-rss-feed',
'site-atom-feed'
3600 $this->msg(
"site-{$format}-feed", $sitename )->text()
3605 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3606 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3607 # use OutputPage::addFeedLink() instead.
3608 Hooks::run(
'AfterBuildFeedLinks', [ &$feedLinks ] );
3610 $tags += $feedLinks;
3614 if ( $config->get(
'EnableCanonicalServerLink' ) ) {
3615 if ( $canonicalUrl !==
false ) {
3626 if ( in_array( $action, [
'history',
'info' ] ) ) {
3627 $query =
"action={$action}";
3631 $canonicalUrl = $this->
getTitle()->getCanonicalURL( $query );
3633 $reqUrl = $this->
getRequest()->getRequestURL();
3637 if ( $canonicalUrl !==
false ) {
3639 'rel' =>
'canonical',
3640 'href' => $canonicalUrl
3649 Hooks::run(
'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3664 'rel' =>
'alternate',
3665 'type' =>
"application/$type+xml",
3680 public function addStyle( $style, $media =
'', $condition =
'', $dir =
'' ) {
3683 $options[
'media'] = $media;
3686 $options[
'condition'] = $condition;
3689 $options[
'dir'] = $dir;
3691 $this->styles[$style] = $options;
3702 if ( $flip ===
'flip' && $this->
getLanguage()->isRTL() ) {
3703 # If wanted, and the interface is right-to-left, flip the CSS
3704 $style_css = CSSJanus::transform( $style_css,
true,
false );
3738 $separateReq = [
'site.styles',
'user.styles' ];
3739 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3740 if ( $moduleNames ) {
3742 array_diff( $moduleNames, $separateReq ),
3743 ResourceLoaderModule::TYPE_STYLES
3746 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3750 ResourceLoaderModule::TYPE_STYLES
3758 [
'name' =>
'ResourceLoaderDynamicStyles',
'content' =>
'' ]
3760 $chunks = array_merge( $chunks, $append );
3772 foreach ( $this->styles as
$file => $options ) {
3775 $links[
$file] = $link;
3789 if ( isset( $options[
'dir'] ) && $this->
getLanguage()->getDir() != $options[
'dir'] ) {
3793 if ( isset( $options[
'media'] ) ) {
3795 if ( is_null( $media ) ) {
3802 if ( substr( $style, 0, 1 ) ==
'/' ||
3803 substr( $style, 0, 5 ) ==
'http:' ||
3804 substr( $style, 0, 6 ) ==
'https:' ) {
3811 $config->get(
'StylePath' ) .
'/' . $style
3817 if ( isset( $options[
'condition'] ) ) {
3818 $condition = htmlspecialchars( $options[
'condition'] );
3819 $link =
"<!--[if $condition]>$link<![endif]-->";
3849 $remotePathPrefix = $config->
get(
'ResourceBasePath' );
3850 if ( $remotePathPrefix ===
'' ) {
3855 $remotePath = $remotePathPrefix;
3857 if ( strpos(
$path, $remotePath ) !== 0 || substr(
$path, 0, 2 ) ===
'//' ) {
3866 $uploadPath = $config->
get(
'UploadPath' );
3867 if ( strpos(
$path, $uploadPath ) === 0 ) {
3868 $localDir = $config->
get(
'UploadDirectory' );
3869 $remotePathPrefix = $remotePath = $uploadPath;
3872 $path = RelPath::getRelativePath(
$path, $remotePath );
3888 $hash = md5_file(
"$localPath/$file" );
3889 if ( $hash ===
false ) {
3890 wfLogWarning( __METHOD__ .
": Failed to hash $localPath/$file" );
3893 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3907 $screenMediaQueryRegex =
'/^(?:only\s+)?screen\b/i';
3911 'printable' =>
'print',
3912 'handheld' =>
'handheld',
3914 foreach ( $switches as $switch => $targetMedia ) {
3916 if ( $media == $targetMedia ) {
3918 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3932 if ( $targetMedia ==
'print' || $media ==
'screen' ) {
3949 $args = func_get_args();
3950 $name = array_shift(
$args );
3992 $msgSpecs = func_get_args();
3993 array_shift( $msgSpecs );
3994 $msgSpecs = array_values( $msgSpecs );
3996 foreach ( $msgSpecs as $n => $spec ) {
3997 if ( is_array( $spec ) ) {
3999 $name = array_shift(
$args );
4004 $s = str_replace(
'$' . ( $n + 1 ), $this->
msg( $name,
$args )->plain(),
$s );
4025 public static function setupOOUI( $skinName =
'default', $dir =
'ltr' ) {
4027 $theme = $themes[$skinName] ?? $themes[
'default'];
4029 $themeClass =
"OOUI\\{$theme}Theme";
4030 OOUI\Theme::setSingleton(
new $themeClass() );
4031 OOUI\Element::setDefaultDir( $dir );
4042 strtolower( $this->
getSkin()->getSkinName() ),
4046 'oojs-ui-core.styles',
4047 'oojs-ui.styles.indicators',
4048 'mediawiki.widgets.styles',
4049 'oojs-ui-core.icons',
4066 if ( $this->CSPNonce ===
null ) {
4069 $rand = random_bytes( 15 );
4070 $this->CSPNonce = base64_encode( $rand );
static getActionName(IContextSource $context)
Get the action that will be executed, not necessarily the one passed passed through the "action" requ...
preventClickjacking( $enable=true)
Set a flag which will cause an X-Frame-Options header appropriate for edit pages to be sent.
output( $return=false)
Finally, all the text has been munged and accumulated into the object, let's actually output it:
addBacklinkSubtitle(Title $title, $query=[])
Add a subtitle containing a backlink to a page.
string $mLastModified
Used for sending cache control.
Set options of the Parser.
getCategoryLinks()
Get the list of category links, in a 2-D array with the following format: $arr[$type][] = $link,...
addMeta( $name, $val)
Add a new "<meta>" tag To add an http-equiv meta tag, precede the name with "http:".
Context object that contains information about the state of a specific ResourceLoader web request.
getSubtitle()
Get the subtitle.
parseAsInterface( $text, $linestart=true)
Parse wikitext in the user interface language and return the HTML.
WebRequest clone which takes values from a provided array.
enableClientCache( $state)
Use enableClientCache(false) to force it to send nocache headers.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
addWikiMsg()
Add a wikitext-formatted message to the output.
getContext()
Get the base IContextSource object.
getLanguageLinks()
Get the list of language links.
static buildBacklinkSubtitle(Title $title, $query=[])
Build message object for a subtitle containing a backlink to a page.
Marks HTML that shouldn't be escaped.
Load and configure a ResourceLoader client on an HTML page.
reduceAllowedModules( $type, $level)
Limit the highest level of CSS/JS untrustworthiness allowed.
addSubtitle( $str)
Add $str to the subtitle.
addScriptFile( $file, $unused=null)
Add a JavaScript file to be loaded as <script> on this page.
addAcceptLanguage()
T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
static formatRobotPolicy( $policy)
Converts a String robot policy into an associative array, to allow merging of several policies using ...
getJSVars()
Get an array containing the variables to be set in mw.config in JavaScript.
static makeConfigSetScript(array $configuration)
Returns JS code which will set the MediaWiki configuration array to the given value.
getDisplayTitle()
Returns page display title.
Title $mRedirectedFrom
If the current page was reached through a redirect, $mRedirectedFrom contains the Title of the redire...
static stripAllTags( $html)
Take a fragment of (potentially invalid) HTML and return a version with any tags removed,...
setTitle(Title $t)
Set the Title object to use.
array $mVaryHeader
Headers that cause the cache to vary.
showsCopyright()
Return whether the standard copyright should be shown for the current page.
Class representing a list of titles The execute() method checks them all for existence and adds them ...
addLink(array $linkarr)
Add a new <link> tag to the page header.
addContentOverride(LinkTarget $target, Content $content)
Add a mapping from a LinkTarget to a Content, for things like page preview.
addCategoryLinksToLBAndGetResult(array $categories)
hasHeadItem( $name)
Check if the header item $name is already set.
string $CSPNonce
The nonce for Content-Security-Policy.
if(!isset( $args[0])) $lang
getMetaTags()
Returns the current <meta> tags.
addLanguageLinks(array $newLinkArray)
Add new language links.
addLinkHeader( $header)
Add an HTTP Link: header.
addModuleStyles( $modules)
Load the styles of one or more ResourceLoader modules on this page.
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
isArticleRelated()
Return whether this page is related an article on the wiki.
setArticleBodyOnly( $only)
Set whether the output should only contain the body of the article, without any skin,...
getFrameOptions()
Get the X-Frame-Options header value (without the name part), or false if there isn't one.
__construct(IContextSource $context)
Constructor for OutputPage.
static makeInlineScript( $script, $nonce=null)
Returns an HTML script tag that runs given JS code after startup and base modules.
getRevisionId()
Get the displayed revision ID.
clearHTML()
Clear the body HTML.
addScript( $script)
Add raw HTML to the list of scripts (including <script> tag, etc.) Internal use only.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$wgVersion
MediaWiki version number.
returnToMain( $unused=null, $returnto=null, $returntoquery=null)
Add a "return to" link pointing to a specified title, or the title indicated in the request,...
addParserOutputMetadata(ParserOutput $parserOutput)
Add all metadata associated with a ParserOutput object, but without the actual HTML.
static combineWrappedStrings(array $chunks)
Combine WrappedString chunks and filter out empty ones.
static mergeAttributes( $a, $b)
Merge two sets of HTML attributes.
bool $mHideNewSectionLink
array $contentOverrides
Map Title to Content.
string $mBodytext
Contains all of the "<body>" content.
getOriginTrials()
Get the Origin-Trial header values.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
getBottomScripts()
JS stuff to put at the bottom of the <body>.
static newFromAnon()
Get a ParserOptions object for an anonymous user.
addHeadItems( $values)
Add one or more head items to the output.
getModuleStyles( $filter=false, $position=null)
Get the list of style-only modules to load on this page.
getFeaturePolicyReportOnly()
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
addToBodyAttributes( $out, &$bodyAttrs)
This will be called by OutputPage::headElement when it is creating the "<body>" tag,...
versionRequired( $version)
Display an error page indicating that a given version of MediaWiki is required to use it.
setExemptStates(array $states)
Set state of special modules that are handled by the caller manually.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
parseInline( $text, $linestart=true, $interface=false)
Parse wikitext, strip paragraph wrapper, and return the HTML.
parserOptions( $options=null)
Get/set the ParserOptions object to use for wikitext parsing.
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
static escapeClass( $class)
Given a value, escape it so that it can be used as a CSS class and return it.
getFileVersion()
Get the displayed file version.
getSyndicationLinks()
Return URLs for each supported syndication format for this page.
canUseWikiPage()
Check whether a WikiPage object can be get with getWikiPage().
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
static newMainPage(MessageLocalizer $localizer=null)
Create a new Title for the Main Page.
int $mRevisionId
To include the variable {{REVISIONID}}.
getRedirect()
Get the URL to redirect to, or an empty string if not redirect URL set.
setCanonicalUrl( $url)
Set the URL to be used for the <link rel=canonical>>.
getHtmlElementAttributes()
Return values for <html> element.
setArray( $array)
Set the link list to a given 2-d array First key is the namespace, second is the DB key,...
setIndicators(array $indicators)
Add an array of indicators, with their identifiers as array keys and HTML contents as values.
static getSelectFields()
Fields that LinkCache needs to select.
addHTML( $text)
Append $text to the body HTML.
addHeadItem( $name, $value)
Add or replace a head item to the output.
addContentOverrideCallback(callable $callback)
Add a callback for mapping from a Title to a Content object, for things like page preview.
getRevisionTimestamp()
Get the timestamp of displayed revision.
addWikiMsgArray( $name, $args)
Add a wikitext-formatted message to the output.
static transformCssMedia( $media)
Transform "media" attribute based on request parameters.
setLastModified( $timestamp)
Override the last modified timestamp.
setConfig(array $vars)
Set mw.config variables.
showPermissionsErrorPage(array $errors, $action=null)
Output a standard permission error page.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
getLinkTags()
Returns the current <link> tags.
forceHideNewSectionLink()
Forcibly hide the new section link?
static closeElement( $element)
Returns "</$element>".
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
ResourceLoaderContext $rlClientContext
static sendHeaders(IContextSource $context)
Send CSP headers based on wiki config.
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
setArticleRelated( $newVal)
Set whether this page is related an article on the wiki Setting false will cause the change of "artic...
addElement( $element, array $attribs=[], $contents='')
Shortcut for adding an Html::element via addHTML.
addParserOutputContent(ParserOutput $parserOutput, $poOptions=[])
Add the HTML and enhancements for it (like ResourceLoader modules) associated with a ParserOutput obj...
Interface for configuration instances.
userCanEditOrCreate(User $user, LinkTarget $title)
Implements some public methods and some protected utility functions which are required by multiple ch...
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
feedLink( $type, $url, $text)
Generate a "<link rel/>" for a feed.
addWikiTextAsInterface( $text, $linestart=true, Title $title=null)
Convert wikitext in the user interface language to HTML and add it to the buffer.
getModules( $filter=false, $position=null, $param='mModules', $type=ResourceLoaderModule::TYPE_COMBINED)
Get the list of modules to include on this page.
addStyle( $style, $media='', $condition='', $dir='')
Add a local or specified stylesheet, with the given media options.
sendCacheControl()
Send cache control HTTP headers.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
int $mCdnMaxageLimit
Upper limit on mCdnMaxage.
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
static preloadTitleInfo(ResourceLoaderContext $context, IDatabase $db, array $moduleNames)
styleLink( $style, array $options)
Generate <link> tags for stylesheets.
bool $mEnableTOC
Whether parser output contains a table of contents.
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
array $mSubtitle
Contains the page subtitle.
setFileVersion( $file)
Set the displayed file version.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
getLinkHeader()
Return a Link: header.
getResourceLoader()
Get a ResourceLoader object associated with this OutputPage.
isTOCEnabled()
Whether the output has a table of contents.
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
getWikiPage()
Get the WikiPage object.
setFeedAppendQuery( $val)
Add default feeds to the page header This is mainly kept for backward compatibility,...
setDisplayTitle( $html)
Same as page title but only contains name of the page, not any other text.
isDisabled()
Return whether the output will be completely disabled.
setRevisionId( $revid)
Set the revision ID which will be seen by the wiki text parser for things such as embedded {{REVISION...
setArticleFlag( $newVal)
Set whether the displayed content is related to the source of the corresponding article on the wiki S...
disallowUserJs()
Do not allow scripts which can be modified by wiki users to load on this page; only allow scripts bun...
setSubtitle( $str)
Replace the subtitle with $str.
string $mInlineStyles
Inline CSS styles.
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
getVaryHeader()
Return a Vary: header on which to vary caches.
addModules( $modules)
Load one or more ResourceLoader modules on this page.
showLagWarning( $lag)
Show a warning about replica DB lag.
getCacheVaryCookies()
Get the list of cookie names that will influence the cache.
setCopyrightUrl( $url)
Set the copyright URL to send with the output.
ResourceLoaderClientHtml $rlClient
addBodyClasses( $classes)
Add a class to the <body> element.
getOrigin()
Get this module's origin.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
setContext(IContextSource $context)
isArticle()
Return whether the content displayed page is related to the source of the corresponding article on th...
This is one of the Core classes and should be read at least once by any new developers.
showErrorPage( $title, $msg, $params=[])
Output a standard error page.
addParserOutputText(ParserOutput $parserOutput, $poOptions=[])
Add the HTML associated with a ParserOutput object, without any metadata.
getCSPNonce()
Get (and set if not yet set) the CSP nonce.
ParserOptions $mParserOptions
lazy initialised, use parserOptions()
Content for JavaScript pages.
array $limitReportJSData
Profiling data.
addInlineScript( $script)
Add a self-contained script tag with the given contents Internal use only.
getArticleBodyOnly()
Return whether the output will contain only the body of the article.
getPreventClickjacking()
Get the prevent-clickjacking flag.
addWikiTextAsContent( $text, $linestart=true, Title $title=null)
Convert wikitext in the page content language to HTML and add it to the buffer.
getCanonicalUrl()
Returns the URL to be used for the <link rel=canonical>> if one is set.
setStatusCode( $statusCode)
Set the HTTP status code to send with the output.
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
bool $mIsArticle
Is the displayed content related to the source of the corresponding wiki article.
haveCacheVaryCookies()
Check if the request has a cache-varying cookie header If it does, it's very important that we don't ...
getPageTitle()
Return the "page title", i.e.
disable()
Disable output completely, i.e.
setIndexPolicy( $policy)
Set the index policy for the page, but leave the follow policy un- touched.
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
ResourceLoader $mResourceLoader
static runWithoutAbort( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
getPageClasses( $title)
TODO: document.
addCategoryLinks(array $categories)
Add an array of categories, with names in the keys.
setRevisionTimestamp( $timestamp)
Set the timestamp of the revision which will be displayed.
getHeadItemsArray()
Get an array of head items.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
addReturnTo( $title, array $query=[], $text=null, $options=[])
Add a "return to" link pointing to a specified title.
buildExemptModules()
Build exempt modules and legacy non-ResourceLoader styles.
string null $copyrightUrl
The URL to send in a <link> element with rel=license.
getProperty( $name)
Get an additional output property.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
formatPermissionsErrorMessage(array $errors, $action=null)
Format a list of error messages.
setTarget( $target)
Sets ResourceLoader target for load.php links.
callable[] $contentOverrideCallbacks
setHTMLTitle( $name)
"HTML title" means the contents of "<title>".
A mutable version of ResourceLoaderContext.
string[][] $mMetatags
Should be private.
setLanguageLinks(array $newLinkArray)
Reset the language links and add new language links.
static setupOOUI( $skinName='default', $dir='ltr')
Helper function to setup the PHP implementation of OOUI to use in this request.
array $rlExemptStyleModules
$mProperties
Additional key => value data.
wrapWikiMsg( $wrap)
This function takes a number of message/argument specifications, wraps them in some overall structure...
prependHTML( $text)
Prepend $text to the body HTML.
getHTMLTitle()
Return the "HTML title", i.e.
clearSubtitle()
Clear the subtitles.
warnModuleTargetFilter( $moduleName)
int $mCdnMaxage
Cache stuff.
enableOOUI()
Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with MediaW...
static array $cacheVaryCookies
A cache of the names of the cookies that will influence the cache.
$mScripts
Used for JavaScript (predates ResourceLoader)
array $mAllowedModules
What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
static getSkinThemeMap()
Return a map of skin names (in lowercase) to OOUI theme names, defining which theme a given skin shou...
bool $mPrintable
We have to set isPrintable().
Interface for objects which can provide a MediaWiki context on request.
array $mLanguageLinks
Array of Interwiki Prefixed (non DB key) Titles (e.g.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
setCategoryLinks(array $categories)
Reset the category links (but not the category list) and add $categories.
setFollowPolicy( $policy)
Set the follow policy for the page, but leave the index policy un- touched.
Base interface for content objects.
setPageTitle( $name)
"Page title" means the contents of <h1>.
getRlClient()
Call this to freeze the module queue and JS config and create a formatter.
static isNonceRequired(Config $config)
Should we set nonce attribute.
static makeLoad(ResourceLoaderContext $mainContext, array $modules, $only, array $extraQuery=[], $nonce=null)
Explicily load or embed modules on a page.
checkLastModified( $timestamp)
checkLastModified tells the client to use the client-cached page if possible.
bool $mNoGallery
Comes from the parser.
array $mHeadItems
Array of elements in "<head>".
string $mRevisionTimestamp
string $displayTitle
The displayed title of the page.
Represents a title within MediaWiki.
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
setCdnMaxage( $maxage)
Set the value of the "s-maxage" part of the "Cache-control" HTTP header.
static stripOuterParagraph( $html)
Strip outer.
getAllowedModules( $type)
Show what level of JavaScript / CSS untrustworthiness is allowed on this page.
ResourceLoader is a loading system for JavaScript and CSS resources.
addVaryHeader( $header, array $option=null)
Add an HTTP header that will influence on the cache.
static getContentText(Content $content=null)
Convenience function for getting flat text from a Content object.
setProperty( $name, $value)
Set an additional output property.
isPrintable()
Return whether the page is "printable".
setSyndicated( $show=true)
Add or remove feed links in the page header This is mainly kept for backward compatibility,...
wrapWikiTextAsInterface( $wrapperClass, $text)
Convert wikitext in the user interface language to HTML and add it to the buffer with a <div class="$...
parseInternal( $text, $title, $linestart, $tidy, $interface, $language)
Parse wikitext and return the HTML (internal implementation helper)
string null $mTarget
ResourceLoader target for load.php links.
addInlineStyle( $style_css, $flip='noflip')
Adds inline CSS styles Internal use only.
setModules(array $modules)
Ensure one or more modules are loaded.
userCanPreview()
To make it harder for someone to slip a user a fake JavaScript or CSS preview, a random token is asso...
static linkedStyle( $url, $media='all')
Output a "<link rel=stylesheet>" linking to the given URL for the given media type (if any).
string $mPageTitle
The contents of.
static inDebugMode()
Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie,...
setRedirectedFrom( $t)
Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
setModuleStyles(array $modules)
Ensure the styles of one or more modules are loaded.
filterModules(array $modules, $position=null, $type=ResourceLoaderModule::TYPE_COMBINED)
Filter an array of modules to remove insufficiently trustworthy members, and modules which are no lon...
static getRequestId()
Get the unique request ID.
redirect( $url, $responsecode='302')
Redirect to $url rather than displaying the normal page.
getUnprefixedDisplayTitle()
Returns page display title without namespace prefix if possible.
setPrintable()
Set the page as printable, i.e.
adaptCdnTTL( $mtime, $minTTL=0, $maxTTL=0)
Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
getCdnCacheEpoch( $reqTime, $maxAge)
allowClickjacking()
Turn off frame-breaking.
static bcp47( $code)
Get the normalised IETF language tag See unit test for examples.
loadSkinModules( $sk)
Transfer styles and JavaScript modules from skin.
showFatalError( $message)
Output an error page.
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
getHTML()
Get the body HTML.
The Message class provides methods which fulfil two basic services:
parseInlineAsInterface( $text, $linestart=true)
Parse wikitext in the user interface language, strip paragraph wrapper, and return the HTML.
$mLinkHeader
Link: header contents.
array $styles
An array of stylesheet filenames (relative from skins path), with options for CSS media,...
isRevisionCurrent()
Whether the revision displayed is the latest revision of the page.
static normalizeCharReferences( $text)
Ensure that any entities and character references are legal for XML and XHTML specifically.
static addModules(OutputPage $out)
Add ResourceLoader modules to the OutputPage object if debugging is enabled.
showNewSectionLink()
Show an "add new section" link?
parse( $text, $linestart=true, $interface=false, $language=null)
Parse wikitext and return the HTML.
string $mPageLinkTitle
Used by skin template.
getText( $options=[])
Get the output HTML.
string bool $mCanonicalUrl
makeResourceLoaderLink( $modules, $only, array $extraQuery=[])
Explicily load or embed modules on a page.
addWikiTextTitleInternal( $text, Title $title, $linestart, $interface, $wrapperClass=null)
Add wikitext with a custom Title object.
getIndicators()
Get the indicators associated with this page.
if(! $wgDBerrorLogTZ) $wgRequest
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
static makeLoaderQuery( $modules, $lang, $skin, $user=null, $version=null, $debug=false, $only=null, $printable=false, $handheld=false, $extraQuery=[])
Build a query array (array representation of query string) for load.php.
addJsConfigVars( $keys, $value=null)
Add one or more variables to be set in mw.config in JavaScript.
bool $mPreventClickjacking
Controls if anti-clickjacking / frame-breaking headers will be sent.
The main skin class which provides methods and properties for all other skins.
getCategories( $type='all')
Get the list of category names this page belongs to.
getJsConfigVars()
Get the javascript config vars to include on this page.
setCopyright( $hasCopyright)
Set whether the standard copyright should be shown for the current page.
getTemplateIds()
Get the templates used on this page.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
bool $mIsArticleRelated
Stores "article flag" toggle.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
isSyndicated()
Should we output feed links for this page?
getFileSearchOptions()
Get the files used on this page.
$mFeedLinks
Handles the Atom / RSS links.
bool $mDoNothing
Whether output is disabled.
bool $mArticleBodyOnly
Flag if output should only contain the body of the article.
bool $mHasCopyright
Is the content subject to copyright.
addParserOutput(ParserOutput $parserOutput, $poOptions=[])
Add everything from a ParserOutput object.
array $mAdditionalBodyClasses
Additional <body> classes; there are also <body> classes from other sources.
prepareErrorPage( $pageTitle, $htmlTitle=false)
Prepare this object to display an error page; disable caching and indexing, clear the current text an...
addTemplate(&$template)
Add the output of a QuickTemplate to the output buffer.
getFeedAppendQuery()
Will currently always return null.
lowerCdnMaxage( $maxage)
Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is lower t...
string $mHTMLtitle
Stores contents of "<title>" tag.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
addFeedLink( $format, $href)
Add a feed link to the page header.
preventClickjacking( $flag=null)
Get or set the prevent-clickjacking flag.
static transformResourcePath(Config $config, $path)
Transform path to web-accessible static resource.
parseAsContent( $text, $linestart=true)
Parse wikitext in the page content language and return the HTML.
static removeHTMLtags( $text, $processCallback=null, $args=[], $extratags=[], $removetags=[], $warnCallback=null)
Cleans up HTML, removes dangerous tags and attributes, and removes HTML comments.
getAdvertisedFeedTypes()
Return effective list of advertised feed types.
setRobotPolicy( $policy)
Set the robot policy for the page: http://www.robotstxt.org/meta.html
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
static transformFilePath( $remotePathPrefix, $localPath, $file)
Utility method for transformResourceFilePath().
headElement(Skin $sk, $includeStyle=true)