3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use Wikimedia\Rdbms\IResultWrapper
;
27 use Wikimedia\RelPath
;
28 use Wikimedia\WrappedString
;
29 use Wikimedia\WrappedStringList
;
32 * This is one of the Core classes and should
33 * be read at least once by any new developers. Also documented at
34 * https://www.mediawiki.org/wiki/Manual:Architectural_modules/OutputPage
36 * This class is used to prepare the final rendering. A skin is then
37 * applied to the output parameters (links, javascript, html, categories ...).
39 * @todo FIXME: Another class handles sending the whole page to the client.
41 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
46 class OutputPage
extends ContextSource
{
47 /** @var string[][] Should be private. Used with addMeta() which adds "<meta>" */
48 protected $mMetatags = [];
51 protected $mLinktags = [];
53 /** @var string|bool */
54 protected $mCanonicalUrl = false;
57 * @var string The contents of <h1>
59 private $mPageTitle = '';
62 * @var string The displayed title of the page. Different from page title
63 * if overridden by display title magic word or hooks. Can contain safe
64 * HTML. Different from page title which may contain messages such as
65 * "Editing X" which is displayed in h1. This can be used for other places
66 * where the page name is referred on the page.
68 private $displayTitle;
71 * @var string Contains all of the "<body>" content. Should be private we
72 * got set/get accessors and the append() method.
74 public $mBodytext = '';
76 /** @var string Stores contents of "<title>" tag */
77 private $mHTMLtitle = '';
80 * @var bool Is the displayed content related to the source of the
81 * corresponding wiki article.
83 private $mIsArticle = false;
85 /** @var bool Stores "article flag" toggle. */
86 private $mIsArticleRelated = true;
88 /** @var bool Is the content subject to copyright */
89 private $mHasCopyright = false;
92 * @var bool We have to set isPrintable(). Some pages should
93 * never be printed (ex: redirections).
95 private $mPrintable = false;
98 * @var array Contains the page subtitle. Special pages usually have some
99 * links here. Don't confuse with site subtitle added by skins.
101 private $mSubtitle = [];
104 public $mRedirect = '';
107 protected $mStatusCode;
110 * @var string Used for sending cache control.
111 * The whole caching system should probably be moved into its own class.
113 protected $mLastModified = '';
116 protected $mCategoryLinks = [];
119 protected $mCategories = [
125 protected $mIndicators = [];
127 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
128 private $mLanguageLinks = [];
131 * Used for JavaScript (predates ResourceLoader)
132 * @todo We should split JS / CSS.
133 * mScripts content is inserted as is in "<head>" by Skin. This might
134 * contain either a link to a stylesheet or inline CSS.
136 private $mScripts = '';
138 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
139 protected $mInlineStyles = '';
142 * @var string Used by skin template.
143 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
145 public $mPageLinkTitle = '';
147 /** @var array Array of elements in "<head>". Parser might add its own headers! */
148 protected $mHeadItems = [];
150 /** @var array Additional <body> classes; there are also <body> classes from other sources */
151 protected $mAdditionalBodyClasses = [];
154 protected $mModules = [];
157 protected $mModuleStyles = [];
159 /** @var ResourceLoader */
160 protected $mResourceLoader;
162 /** @var ResourceLoaderClientHtml */
165 /** @var ResourceLoaderContext */
166 private $rlClientContext;
169 private $rlExemptStyleModules;
172 protected $mJsConfigVars = [];
175 protected $mTemplateIds = [];
178 protected $mImageTimeKeys = [];
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
186 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
187 * @see ResourceLoaderModule::$origin
188 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
190 protected $mAllowedModules = [
191 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
194 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
195 protected $mDoNothing = false;
200 protected $mContainsNewMagic = 0;
203 * lazy initialised, use parserOptions()
206 protected $mParserOptions = null;
209 * Handles the Atom / RSS links.
210 * We probably only support Atom in 2011.
211 * @see $wgAdvertisedFeedTypes
213 private $mFeedLinks = [];
215 // Gwicke work on squid caching? Roughly from 2003.
216 protected $mEnableClientCache = true;
218 /** @var bool Flag if output should only contain the body of the article. */
219 private $mArticleBodyOnly = false;
222 protected $mNewSectionLink = false;
225 protected $mHideNewSectionLink = false;
228 * @var bool Comes from the parser. This was probably made to load CSS/JS
229 * only if we had "<gallery>". Used directly in CategoryPage.php.
230 * Looks like ResourceLoader can replace this.
232 public $mNoGallery = false;
234 /** @var int Cache stuff. Looks like mEnableClientCache */
235 protected $mCdnMaxage = 0;
236 /** @var int Upper limit on mCdnMaxage */
237 protected $mCdnMaxageLimit = INF
;
240 * @var bool Controls if anti-clickjacking / frame-breaking headers will
241 * be sent. This should be done for pages where edit actions are possible.
242 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
244 protected $mPreventClickjacking = true;
246 /** @var int To include the variable {{REVISIONID}} */
247 private $mRevisionId = null;
250 private $mRevisionTimestamp = null;
253 protected $mFileVersion = null;
256 * @var array An array of stylesheet filenames (relative from skins path),
257 * with options for CSS media, IE conditions, and RTL/LTR direction.
258 * For internal use; add settings in the skin via $this->addStyle()
260 * Style again! This seems like a code duplication since we already have
261 * mStyles. This is what makes Open Source amazing.
263 protected $styles = [];
265 private $mIndexPolicy = 'index';
266 private $mFollowPolicy = 'follow';
269 * @var array Headers that cause the cache to vary. Key is header name,
270 * value should always be null. (Value was an array of options for
271 * the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
273 private $mVaryHeader = [
274 'Accept-Encoding' => null,
278 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
283 private $mRedirectedFrom = null;
286 * Additional key => value data
288 private $mProperties = [];
291 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
293 private $mTarget = null;
296 * @var bool Whether parser output contains a table of contents
298 private $mEnableTOC = false;
301 * @var string|null The URL to send in a <link> element with rel=license
303 private $copyrightUrl;
305 /** @var array Profiling data */
306 private $limitReportJSData = [];
308 /** @var array Map Title to Content */
309 private $contentOverrides = [];
311 /** @var callable[] */
312 private $contentOverrideCallbacks = [];
315 * Link: header contents
317 private $mLinkHeader = [];
320 * @var string The nonce for Content-Security-Policy
325 * @var array A cache of the names of the cookies that will influence the cache
327 private static $cacheVaryCookies = null;
330 * Constructor for OutputPage. This should not be called directly.
331 * Instead a new RequestContext should be created and it will implicitly create
332 * a OutputPage tied to that context.
333 * @param IContextSource $context
335 public function __construct( IContextSource
$context ) {
336 $this->setContext( $context );
340 * Redirect to $url rather than displaying the normal page
343 * @param string $responsecode HTTP status code
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;
352 * Get the URL to redirect to, or an empty string if not redirect URL set
356 public function getRedirect() {
357 return $this->mRedirect
;
361 * Set the copyright URL to send with the output.
362 * Empty string to omit, null to reset.
366 * @param string|null $url
368 public function setCopyrightUrl( $url ) {
369 $this->copyrightUrl
= $url;
373 * Set the HTTP status code to send with the output.
375 * @param int $statusCode
377 public function setStatusCode( $statusCode ) {
378 $this->mStatusCode
= $statusCode;
382 * Add a new "<meta>" tag
383 * To add an http-equiv meta tag, precede the name with "http:"
385 * @param string $name Name of the meta tag
386 * @param string $val Value of the meta tag
388 public function addMeta( $name, $val ) {
389 $this->mMetatags
[] = [ $name, $val ];
393 * Returns the current <meta> tags
398 public function getMetaTags() {
399 return $this->mMetatags
;
403 * Add a new \<link\> tag to the page header.
405 * Note: use setCanonicalUrl() for rel=canonical.
407 * @param array $linkarr Associative array of attributes.
409 public function addLink( array $linkarr ) {
410 $this->mLinktags
[] = $linkarr;
414 * Returns the current <link> tags
419 public function getLinkTags() {
420 return $this->mLinktags
;
424 * Set the URL to be used for the <link rel=canonical>. This should be used
425 * in preference to addLink(), to avoid duplicate link tags.
428 public function setCanonicalUrl( $url ) {
429 $this->mCanonicalUrl
= $url;
433 * Returns the URL to be used for the <link rel=canonical> if
437 * @return bool|string
439 public function getCanonicalUrl() {
440 return $this->mCanonicalUrl
;
444 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
445 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
448 * @param string $script Raw HTML
450 public function addScript( $script ) {
451 $this->mScripts
.= $script;
455 * Add a JavaScript file to be loaded as `<script>` on this page.
457 * Internal use only. Use OutputPage::addModules() if possible.
459 * @param string $file URL to file (absolute path, protocol-relative, or full url)
460 * @param string|null $unused Previously used to change the cache-busting query parameter
462 public function addScriptFile( $file, $unused = null ) {
463 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
467 * Add a self-contained script tag with the given contents
468 * Internal use only. Use OutputPage::addModules() if possible.
470 * @param string $script JavaScript text, no script tags
472 public function addInlineScript( $script ) {
473 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
477 * Filter an array of modules to remove insufficiently trustworthy members, and modules
478 * which are no longer registered (eg a page is cached before an extension is disabled)
479 * @param array $modules
480 * @param string|null $position Unused
481 * @param string $type
484 protected function filterModules( array $modules, $position = null,
485 $type = ResourceLoaderModule
::TYPE_COMBINED
487 $resourceLoader = $this->getResourceLoader();
488 $filteredModules = [];
489 foreach ( $modules as $val ) {
490 $module = $resourceLoader->getModule( $val );
491 if ( $module instanceof ResourceLoaderModule
492 && $module->getOrigin() <= $this->getAllowedModules( $type )
494 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
495 $this->warnModuleTargetFilter( $module->getName() );
498 $filteredModules[] = $val;
501 return $filteredModules;
504 private function warnModuleTargetFilter( $moduleName ) {
505 static $warnings = [];
506 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
509 $warnings[$this->mTarget
][$moduleName] = true;
510 $this->getResourceLoader()->getLogger()->debug(
511 'Module "{module}" not loadable on target "{target}".',
513 'module' => $moduleName,
514 'target' => $this->mTarget
,
520 * Get the list of modules to include on this page
522 * @param bool $filter Whether to filter out insufficiently trustworthy modules
523 * @param string|null $position Unused
524 * @param string $param
525 * @param string $type
526 * @return array Array of module names
528 public function getModules( $filter = false, $position = null, $param = 'mModules',
529 $type = ResourceLoaderModule
::TYPE_COMBINED
531 $modules = array_values( array_unique( $this->$param ) );
533 ?
$this->filterModules( $modules, null, $type )
538 * Load one or more ResourceLoader modules on this page.
540 * @param string|array $modules Module name (string) or array of module names
542 public function addModules( $modules ) {
543 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
547 * Get the list of style-only modules to load on this page.
549 * @param bool $filter
550 * @param string|null $position Unused
551 * @return array Array of module names
553 public function getModuleStyles( $filter = false, $position = null ) {
554 return $this->getModules( $filter, null, 'mModuleStyles',
555 ResourceLoaderModule
::TYPE_STYLES
560 * Load the styles of one or more ResourceLoader modules on this page.
562 * Module styles added through this function will be loaded as a stylesheet,
563 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
564 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
566 * @param string|array $modules Module name (string) or array of module names
568 public function addModuleStyles( $modules ) {
569 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
573 * @return null|string ResourceLoader target
575 public function getTarget() {
576 return $this->mTarget
;
580 * Sets ResourceLoader target for load.php links. If null, will be omitted
582 * @param string|null $target
584 public function setTarget( $target ) {
585 $this->mTarget
= $target;
589 * Add a mapping from a LinkTarget to a Content, for things like page preview.
590 * @see self::addContentOverrideCallback()
592 * @param LinkTarget $target
593 * @param Content $content
595 public function addContentOverride( LinkTarget
$target, Content
$content ) {
596 if ( !$this->contentOverrides
) {
597 // Register a callback for $this->contentOverrides on the first call
598 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
599 $key = $target->getNamespace() . ':' . $target->getDBkey();
600 return $this->contentOverrides
[$key] ??
null;
604 $key = $target->getNamespace() . ':' . $target->getDBkey();
605 $this->contentOverrides
[$key] = $content;
609 * Add a callback for mapping from a Title to a Content object, for things
611 * @see ResourceLoaderContext::getContentOverrideCallback()
613 * @param callable $callback
615 public function addContentOverrideCallback( callable
$callback ) {
616 $this->contentOverrideCallbacks
[] = $callback;
620 * Get an array of head items
624 public function getHeadItemsArray() {
625 return $this->mHeadItems
;
629 * Add or replace a head item to the output
631 * Whenever possible, use more specific options like ResourceLoader modules,
632 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
633 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
634 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
635 * This would be your very LAST fallback.
637 * @param string $name Item name
638 * @param string $value Raw HTML
640 public function addHeadItem( $name, $value ) {
641 $this->mHeadItems
[$name] = $value;
645 * Add one or more head items to the output
648 * @param string|string[] $values Raw HTML
650 public function addHeadItems( $values ) {
651 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
655 * Check if the header item $name is already set
657 * @param string $name Item name
660 public function hasHeadItem( $name ) {
661 return isset( $this->mHeadItems
[$name] );
665 * Add a class to the <body> element
668 * @param string|string[] $classes One or more classes to add
670 public function addBodyClasses( $classes ) {
671 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
675 * Set whether the output should only contain the body of the article,
676 * without any skin, sidebar, etc.
677 * Used e.g. when calling with "action=render".
679 * @param bool $only Whether to output only the body of the article
681 public function setArticleBodyOnly( $only ) {
682 $this->mArticleBodyOnly
= $only;
686 * Return whether the output will contain only the body of the article
690 public function getArticleBodyOnly() {
691 return $this->mArticleBodyOnly
;
695 * Set an additional output property
698 * @param string $name
699 * @param mixed $value
701 public function setProperty( $name, $value ) {
702 $this->mProperties
[$name] = $value;
706 * Get an additional output property
709 * @param string $name
710 * @return mixed Property value or null if not found
712 public function getProperty( $name ) {
713 return $this->mProperties
[$name] ??
null;
717 * checkLastModified tells the client to use the client-cached page if
718 * possible. If successful, the OutputPage is disabled so that
719 * any future call to OutputPage->output() have no effect.
721 * Side effect: sets mLastModified for Last-Modified header
723 * @param string $timestamp
725 * @return bool True if cache-ok headers was sent.
727 public function checkLastModified( $timestamp ) {
728 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
729 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
732 $config = $this->getConfig();
733 if ( !$config->get( 'CachePages' ) ) {
734 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
738 $timestamp = wfTimestamp( TS_MW
, $timestamp );
740 'page' => $timestamp,
741 'user' => $this->getUser()->getTouched(),
742 'epoch' => $config->get( 'CacheEpoch' )
744 if ( $config->get( 'UseCdn' ) ) {
745 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
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(); // E_STRICT system time warnings
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 );
799 $this->sendCacheControl();
802 // Don't output a compressed blob when using ob_gzhandler;
803 // it's technically against HTTP spec and seems to confuse
804 // Firefox when the response gets split over two packets.
805 wfClearOutputBuffers();
811 * @param int $reqTime Time of request (eg. now)
812 * @param int $maxAge Cache TTL in seconds
813 * @return int Timestamp
815 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
816 // Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
817 // because even if the wiki page content hasn't changed since, static
818 // resources may have changed (skin HTML, interface messages, urls, etc.)
819 // and must roll-over in a timely manner (T46570)
820 return $reqTime - $maxAge;
824 * Override the last modified timestamp
826 * @param string $timestamp New timestamp, in a format readable by
829 public function setLastModified( $timestamp ) {
830 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
834 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
836 * @param string $policy The literal string to output as the contents of
837 * the meta tag. Will be parsed according to the spec and output in
841 public function setRobotPolicy( $policy ) {
842 $policy = Article
::formatRobotPolicy( $policy );
844 if ( isset( $policy['index'] ) ) {
845 $this->setIndexPolicy( $policy['index'] );
847 if ( isset( $policy['follow'] ) ) {
848 $this->setFollowPolicy( $policy['follow'] );
853 * Set the index policy for the page, but leave the follow policy un-
856 * @param string $policy Either 'index' or 'noindex'.
859 public function setIndexPolicy( $policy ) {
860 $policy = trim( $policy );
861 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
862 $this->mIndexPolicy
= $policy;
867 * Set the follow policy for the page, but leave the index policy un-
870 * @param string $policy Either 'follow' or 'nofollow'.
873 public function setFollowPolicy( $policy ) {
874 $policy = trim( $policy );
875 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
876 $this->mFollowPolicy
= $policy;
881 * "HTML title" means the contents of "<title>".
882 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
884 * @param string|Message $name
886 public function setHTMLTitle( $name ) {
887 if ( $name instanceof Message
) {
888 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
890 $this->mHTMLtitle
= $name;
895 * Return the "HTML title", i.e. the content of the "<title>" tag.
899 public function getHTMLTitle() {
900 return $this->mHTMLtitle
;
904 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
908 public function setRedirectedFrom( $t ) {
909 $this->mRedirectedFrom
= $t;
913 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
914 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
915 * but not bad tags like \<script\>. This function automatically sets
916 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
917 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
918 * good tags like \<i\> will be dropped entirely.
920 * @param string|Message $name
921 * @param-taint $name tainted
922 * Phan-taint-check gets very confused by $name being either a string or a Message
924 public function setPageTitle( $name ) {
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
931 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
932 $this->mPageTitle
= $nameWithTags;
934 # change "<i>foo&bar</i>" to "foo&bar"
936 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer
::stripAllTags( $nameWithTags ) )
937 ->inContentLanguage()
942 * Return the "page title", i.e. the content of the \<h1\> tag.
946 public function getPageTitle() {
947 return $this->mPageTitle
;
951 * Same as page title but only contains name of the page, not any other text.
954 * @param string $html Page title text.
955 * @see OutputPage::setPageTitle
957 public function setDisplayTitle( $html ) {
958 $this->displayTitle
= $html;
962 * Returns page display title.
964 * Performs some normalization, but this not as strict the magic word.
967 * @return string HTML
969 public function getDisplayTitle() {
970 $html = $this->displayTitle
;
971 if ( $html === null ) {
972 $html = $this->getTitle()->getPrefixedText();
975 return Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $html ) );
979 * Returns page display title without namespace prefix if possible.
982 * @return string HTML
984 public function getUnprefixedDisplayTitle() {
985 $text = $this->getDisplayTitle();
986 $nsPrefix = $this->getTitle()->getNsText() . ':';
987 $prefix = preg_quote( $nsPrefix, '/' );
989 return preg_replace( "/^$prefix/i", '', $text );
993 * Set the Title object to use
997 public function setTitle( Title
$t ) {
998 // @phan-suppress-next-next-line PhanUndeclaredMethod
999 // @fixme Not all implementations of IContextSource have this method!
1000 $this->getContext()->setTitle( $t );
1004 * Replace the subtitle with $str
1006 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1008 public function setSubtitle( $str ) {
1009 $this->clearSubtitle();
1010 $this->addSubtitle( $str );
1014 * Add $str to the subtitle
1016 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1018 public function addSubtitle( $str ) {
1019 if ( $str instanceof Message
) {
1020 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1022 $this->mSubtitle
[] = $str;
1027 * Build message object for a subtitle containing a backlink to a page
1029 * @param Title $title Title to link to
1030 * @param array $query Array of additional parameters to include in the link
1034 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1035 if ( $title->isRedirect() ) {
1036 $query['redirect'] = 'no';
1038 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1039 return wfMessage( 'backlinksubtitle' )
1040 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1044 * Add a subtitle containing a backlink to a page
1046 * @param Title $title Title to link to
1047 * @param array $query Array of additional parameters to include in the link
1049 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1050 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1054 * Clear the subtitles
1056 public function clearSubtitle() {
1057 $this->mSubtitle
= [];
1065 public function getSubtitle() {
1066 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1070 * Set the page as printable, i.e. it'll be displayed with all
1071 * print styles included
1073 public function setPrintable() {
1074 $this->mPrintable
= true;
1078 * Return whether the page is "printable"
1082 public function isPrintable() {
1083 return $this->mPrintable
;
1087 * Disable output completely, i.e. calling output() will have no effect
1089 public function disable() {
1090 $this->mDoNothing
= true;
1094 * Return whether the output will be completely disabled
1098 public function isDisabled() {
1099 return $this->mDoNothing
;
1103 * Show an "add new section" link?
1107 public function showNewSectionLink() {
1108 return $this->mNewSectionLink
;
1112 * Forcibly hide the new section link?
1116 public function forceHideNewSectionLink() {
1117 return $this->mHideNewSectionLink
;
1121 * Add or remove feed links in the page header
1122 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1123 * for the new version
1124 * @see addFeedLink()
1126 * @param bool $show True: add default feeds, false: remove all feeds
1128 public function setSyndicated( $show = true ) {
1130 $this->setFeedAppendQuery( false );
1132 $this->mFeedLinks
= [];
1137 * Return effective list of advertised feed types
1138 * @see addFeedLink()
1140 * @return array Array of feed type names ( 'rss', 'atom' )
1142 protected function getAdvertisedFeedTypes() {
1143 if ( $this->getConfig()->get( 'Feed' ) ) {
1144 return $this->getConfig()->get( 'AdvertisedFeedTypes' );
1151 * Add default feeds to the page header
1152 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1153 * for the new version
1154 * @see addFeedLink()
1156 * @param string $val Query to append to feed links or false to output
1159 public function setFeedAppendQuery( $val ) {
1160 $this->mFeedLinks
= [];
1162 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1163 $query = "feed=$type";
1164 if ( is_string( $val ) ) {
1165 $query .= '&' . $val;
1167 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1172 * Add a feed link to the page header
1174 * @param string $format Feed type, should be a key of $wgFeedClasses
1175 * @param string $href URL
1177 public function addFeedLink( $format, $href ) {
1178 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1179 $this->mFeedLinks
[$format] = $href;
1184 * Should we output feed links for this page?
1187 public function isSyndicated() {
1188 return count( $this->mFeedLinks
) > 0;
1192 * Return URLs for each supported syndication format for this page.
1193 * @return array Associating format keys with URLs
1195 public function getSyndicationLinks() {
1196 return $this->mFeedLinks
;
1200 * Will currently always return null
1204 public function getFeedAppendQuery() {
1205 return $this->mFeedLinksAppendQuery
;
1209 * Set whether the displayed content is related to the source of the
1210 * corresponding article on the wiki
1211 * Setting true will cause the change "article related" toggle to true
1213 * @param bool $newVal
1215 public function setArticleFlag( $newVal ) {
1216 $this->mIsArticle
= $newVal;
1218 $this->mIsArticleRelated
= $newVal;
1223 * Return whether the content displayed page is related to the source of
1224 * the corresponding article on the wiki
1228 public function isArticle() {
1229 return $this->mIsArticle
;
1233 * Set whether this page is related an article on the wiki
1234 * Setting false will cause the change of "article flag" toggle to false
1236 * @param bool $newVal
1238 public function setArticleRelated( $newVal ) {
1239 $this->mIsArticleRelated
= $newVal;
1241 $this->mIsArticle
= false;
1246 * Return whether this page is related an article on the wiki
1250 public function isArticleRelated() {
1251 return $this->mIsArticleRelated
;
1255 * Set whether the standard copyright should be shown for the current page.
1257 * @param bool $hasCopyright
1259 public function setCopyright( $hasCopyright ) {
1260 $this->mHasCopyright
= $hasCopyright;
1264 * Return whether the standard copyright should be shown for the current page.
1265 * By default, it is true for all articles but other pages
1266 * can signal it by using setCopyright( true ).
1268 * Used by SkinTemplate to decided whether to show the copyright.
1272 public function showsCopyright() {
1273 return $this->isArticle() ||
$this->mHasCopyright
;
1277 * Add new language links
1279 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1280 * (e.g. 'fr:Test page')
1282 public function addLanguageLinks( array $newLinkArray ) {
1283 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1287 * Reset the language links and add new language links
1289 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1290 * (e.g. 'fr:Test page')
1292 public function setLanguageLinks( array $newLinkArray ) {
1293 $this->mLanguageLinks
= $newLinkArray;
1297 * Get the list of language links
1299 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1301 public function getLanguageLinks() {
1302 return $this->mLanguageLinks
;
1306 * Add an array of categories, with names in the keys
1308 * @param array $categories Mapping category name => sort key
1310 public function addCategoryLinks( array $categories ) {
1311 if ( !$categories ) {
1315 $res = $this->addCategoryLinksToLBAndGetResult( $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';
1327 // Avoid PHP 7.1 warning of passing $this by reference
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 ) {
1337 // array keys will cast numeric category names to ints, so cast back to string
1338 $category = (string)$category;
1339 $origcategory = $category;
1340 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1344 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1345 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1348 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1349 $this->mCategories
[$type][] = $title->getText();
1350 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1356 * @param array $categories
1357 * @return bool|IResultWrapper
1359 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1360 # Add the links to a LinkBatch
1361 $arr = [ NS_CATEGORY
=> $categories ];
1362 $lb = new LinkBatch
;
1363 $lb->setArray( $arr );
1365 # Fetch existence plus the hiddencat property
1366 $dbr = wfGetDB( DB_REPLICA
);
1367 $fields = array_merge(
1368 LinkCache
::getSelectFields(),
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 );
1391 * Reset the category links (but not the category list) and add $categories
1393 * @param array $categories Mapping category name => sort key
1395 public function setCategoryLinks( array $categories ) {
1396 $this->mCategoryLinks
= [];
1397 $this->addCategoryLinks( $categories );
1401 * Get the list of category links, in a 2-D array with the following format:
1402 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1403 * hidden categories) and $link a HTML fragment with a link to the category
1408 public function getCategoryLinks() {
1409 return $this->mCategoryLinks
;
1413 * Get the list of category names this page belongs to.
1415 * @param string $type The type of categories which should be returned. Possible values:
1416 * * all: all categories of all types
1417 * * hidden: only the hidden categories
1418 * * normal: all categories, except hidden categories
1419 * @return array Array of strings
1421 public function getCategories( $type = 'all' ) {
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];
1436 * Add an array of indicators, with their identifiers as array
1437 * keys and HTML contents as values.
1439 * In case of duplicate keys, existing values are overwritten.
1441 * @param array $indicators
1444 public function setIndicators( array $indicators ) {
1445 $this->mIndicators
= $indicators +
$this->mIndicators
;
1446 // Keep ordered by key
1447 ksort( $this->mIndicators
);
1451 * Get the indicators associated with this page.
1453 * The array will be internally ordered by item keys.
1455 * @return array Keys: identifiers, values: HTML contents
1458 public function getIndicators() {
1459 return $this->mIndicators
;
1463 * Adds help link with an icon via page indicators.
1464 * Link target can be overridden by a local message containing a wikilink:
1465 * the message key is: lowercase action or special page name + '-helppage'.
1466 * @param string $to Target MediaWiki.org page title or encoded URL.
1467 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1470 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1471 $this->addModuleStyles( 'mediawiki.helplink' );
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";
1481 $link = Html
::rawElement(
1485 'target' => '_blank',
1486 'class' => 'mw-helplink',
1491 $this->setIndicators( [ 'mw-helplink' => $link ] );
1495 * Do not allow scripts which can be modified by wiki users to load on this page;
1496 * only allow scripts bundled with, or generated by, the software.
1497 * Site-wide styles are controlled by a config setting, since they can be
1498 * used to create a custom skin/theme, but not user-specific ones.
1500 * @todo this should be given a more accurate name
1502 public function disallowUserJs() {
1503 $this->reduceAllowedModules(
1504 ResourceLoaderModule
::TYPE_SCRIPTS
,
1505 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1508 // Site-wide styles are controlled by a config setting, see T73621
1509 // for background on why. User styles are never allowed.
1510 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1511 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1513 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1515 $this->reduceAllowedModules(
1516 ResourceLoaderModule
::TYPE_STYLES
,
1522 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1523 * @see ResourceLoaderModule::$origin
1524 * @param string $type ResourceLoaderModule TYPE_ constant
1525 * @return int ResourceLoaderModule ORIGIN_ class constant
1527 public function getAllowedModules( $type ) {
1528 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1529 return min( array_values( $this->mAllowedModules
) );
1531 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1536 * Limit the highest level of CSS/JS untrustworthiness allowed.
1538 * If passed the same or a higher level than the current level of untrustworthiness set, the
1539 * level will remain unchanged.
1541 * @param string $type
1542 * @param int $level ResourceLoaderModule class constant
1544 public function reduceAllowedModules( $type, $level ) {
1545 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1549 * Prepend $text to the body HTML
1551 * @param string $text HTML
1553 public function prependHTML( $text ) {
1554 $this->mBodytext
= $text . $this->mBodytext
;
1558 * Append $text to the body HTML
1560 * @param string $text HTML
1562 public function addHTML( $text ) {
1563 $this->mBodytext
.= $text;
1567 * Shortcut for adding an Html::element via addHTML.
1571 * @param string $element
1572 * @param array $attribs
1573 * @param string $contents
1575 public function addElement( $element, array $attribs = [], $contents = '' ) {
1576 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1580 * Clear the body HTML
1582 public function clearHTML() {
1583 $this->mBodytext
= '';
1589 * @return string HTML
1591 public function getHTML() {
1592 return $this->mBodytext
;
1596 * Get/set the ParserOptions object to use for wikitext parsing
1598 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1599 * current ParserOption object. This parameter is deprecated since 1.31.
1600 * @return ParserOptions
1601 * @suppress PhanUndeclaredProperty For isBogus
1603 public function parserOptions( $options = null ) {
1604 if ( $options !== null ) {
1605 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1608 if ( $options !== null && !empty( $options->isBogus
) ) {
1609 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1610 // been changed somehow, and keep it if so.
1611 $anonPO = ParserOptions
::newFromAnon();
1612 $anonPO->setAllowUnsafeRawHtml( false );
1613 if ( !$options->matches( $anonPO ) ) {
1614 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1615 $options->isBogus
= false;
1619 if ( !$this->mParserOptions
) {
1620 if ( !$this->getUser()->isSafeToLoad() ) {
1621 // $wgUser isn't unstubbable yet, so don't try to get a
1622 // ParserOptions for it. And don't cache this ParserOptions
1624 $po = ParserOptions
::newFromAnon();
1625 $po->setAllowUnsafeRawHtml( false );
1626 $po->isBogus
= true;
1627 if ( $options !== null ) {
1628 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1633 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1634 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1637 if ( $options !== null && !empty( $options->isBogus
) ) {
1638 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1640 return wfSetVar( $this->mParserOptions
, null, true );
1642 return wfSetVar( $this->mParserOptions
, $options );
1647 * Set the revision ID which will be seen by the wiki text parser
1648 * for things such as embedded {{REVISIONID}} variable use.
1650 * @param int|null $revid A positive integer, or null
1651 * @return mixed Previous value
1653 public function setRevisionId( $revid ) {
1654 $val = is_null( $revid ) ?
null : intval( $revid );
1655 return wfSetVar( $this->mRevisionId
, $val, true );
1659 * Get the displayed revision ID
1663 public function getRevisionId() {
1664 return $this->mRevisionId
;
1668 * Whether the revision displayed is the latest revision of the page
1673 public function isRevisionCurrent() {
1674 return $this->mRevisionId
== 0 ||
$this->mRevisionId
== $this->getTitle()->getLatestRevID();
1678 * Set the timestamp of the revision which will be displayed. This is used
1679 * to avoid a extra DB call in Skin::lastModified().
1681 * @param string|null $timestamp
1682 * @return mixed Previous value
1684 public function setRevisionTimestamp( $timestamp ) {
1685 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1689 * Get the timestamp of displayed revision.
1690 * This will be null if not filled by setRevisionTimestamp().
1692 * @return string|null
1694 public function getRevisionTimestamp() {
1695 return $this->mRevisionTimestamp
;
1699 * Set the displayed file version
1701 * @param File|null $file
1702 * @return mixed Previous value
1704 public function setFileVersion( $file ) {
1706 if ( $file instanceof File
&& $file->exists() ) {
1707 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1709 return wfSetVar( $this->mFileVersion
, $val, true );
1713 * Get the displayed file version
1715 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1717 public function getFileVersion() {
1718 return $this->mFileVersion
;
1722 * Get the templates used on this page
1724 * @return array (namespace => dbKey => revId)
1727 public function getTemplateIds() {
1728 return $this->mTemplateIds
;
1732 * Get the files used on this page
1734 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1737 public function getFileSearchOptions() {
1738 return $this->mImageTimeKeys
;
1742 * Convert wikitext *in the user interface language* to HTML and
1743 * add it to the buffer. The result will not be
1744 * language-converted, as user interface messages are already
1745 * localized into a specific variant. Assumes that the current
1746 * page title will be used if optional $title is not
1747 * provided. Output will be tidy.
1749 * @param string $text Wikitext in the user interface language
1750 * @param bool $linestart Is this the start of a line? (Defaults to true)
1751 * @param Title|null $title Optional title to use; default of `null`
1752 * means use current page title.
1753 * @throws MWException if $title is not provided and OutputPage::getTitle()
1757 public function addWikiTextAsInterface(
1758 $text, $linestart = true, Title
$title = null
1760 if ( $title === null ) {
1761 $title = $this->getTitle();
1764 throw new MWException( 'Title is null' );
1766 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1770 * Convert wikitext *in the user interface language* to HTML and
1771 * add it to the buffer with a `<div class="$wrapperClass">`
1772 * wrapper. The result will not be language-converted, as user
1773 * interface messages as already localized into a specific
1774 * variant. The $text will be parsed in start-of-line context.
1775 * Output will be tidy.
1777 * @param string $wrapperClass The class attribute value for the <div>
1778 * wrapper in the output HTML
1779 * @param string $text Wikitext in the user interface language
1782 public function wrapWikiTextAsInterface(
1783 $wrapperClass, $text
1785 $this->addWikiTextTitleInternal(
1786 $text, $this->getTitle(),
1787 /*linestart*/true, /*interface*/true,
1793 * Convert wikitext *in the page content language* to HTML and add
1794 * it to the buffer. The result with be language-converted to the
1795 * user's preferred variant. Assumes that the current page title
1796 * will be used if optional $title is not provided. Output will be
1799 * @param string $text Wikitext in the page content language
1800 * @param bool $linestart Is this the start of a line? (Defaults to true)
1801 * @param Title|null $title Optional title to use; default of `null`
1802 * means use current page title.
1803 * @throws MWException if $title is not provided and OutputPage::getTitle()
1807 public function addWikiTextAsContent(
1808 $text, $linestart = true, Title
$title = null
1810 if ( $title === null ) {
1811 $title = $this->getTitle();
1814 throw new MWException( 'Title is null' );
1816 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
1820 * Add wikitext with a custom Title object.
1821 * Output is unwrapped.
1823 * @param string $text Wikitext
1824 * @param Title $title
1825 * @param bool $linestart Is this the start of a line?
1826 * @param bool $interface Whether it is an interface message
1827 * (for example disables conversion)
1828 * @param string $wrapperClass if not empty, wraps the output in
1829 * a `<div class="$wrapperClass">`
1831 private function addWikiTextTitleInternal(
1832 $text, Title
$title, $linestart, $interface, $wrapperClass = null
1834 $parserOutput = $this->parseInternal(
1835 $text, $title, $linestart, true, $interface, /*language*/null
1838 $this->addParserOutput( $parserOutput, [
1839 'enableSectionEditLinks' => false,
1840 'wrapperDivClass' => $wrapperClass ??
'',
1845 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1846 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1850 * @param ParserOutput $parserOutput
1852 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1853 $this->mLanguageLinks
=
1854 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1855 $this->addCategoryLinks( $parserOutput->getCategories() );
1856 $this->setIndicators( $parserOutput->getIndicators() );
1857 $this->mNewSectionLink
= $parserOutput->getNewSection();
1858 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1860 if ( !$parserOutput->isCacheable() ) {
1861 $this->enableClientCache( false );
1863 $this->mNoGallery
= $parserOutput->getNoGallery();
1864 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1865 $this->addModules( $parserOutput->getModules() );
1866 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1867 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1868 $this->mPreventClickjacking
= $this->mPreventClickjacking
1869 ||
$parserOutput->preventClickjacking();
1871 // Template versioning...
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;
1879 // File versioning...
1880 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1881 $this->mImageTimeKeys
[$dbk] = $data;
1884 // Hooks registered in the object
1885 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1886 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1887 list( $hookName, $data ) = $hookInfo;
1888 if ( isset( $parserOutputHooks[$hookName] ) ) {
1889 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1893 // Enable OOUI if requested via ParserOutput
1894 if ( $parserOutput->getEnableOOUI() ) {
1895 $this->enableOOUI();
1898 // Include parser limit report
1899 if ( !$this->limitReportJSData
) {
1900 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1903 // Link flags are ignored for now, but may in the future be
1904 // used to mark individual language links.
1906 // Avoid PHP 7.1 warning of passing $this by reference
1907 $outputPage = $this;
1908 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1909 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1911 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1912 // so that extensions may modify ParserOutput to toggle TOC.
1913 // This cannot be moved to addParserOutputText because that is not
1914 // called by EditPage for Preview.
1915 if ( $parserOutput->getTOCHTML() ) {
1916 $this->mEnableTOC
= true;
1921 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1922 * ParserOutput object, without any other metadata.
1925 * @param ParserOutput $parserOutput
1926 * @param array $poOptions Options to ParserOutput::getText()
1928 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
1929 $this->addParserOutputText( $parserOutput, $poOptions );
1931 $this->addModules( $parserOutput->getModules() );
1932 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1934 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1938 * Add the HTML associated with a ParserOutput object, without any metadata.
1941 * @param ParserOutput $parserOutput
1942 * @param array $poOptions Options to ParserOutput::getText()
1944 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
1945 $text = $parserOutput->getText( $poOptions );
1946 // Avoid PHP 7.1 warning of passing $this by reference
1947 $outputPage = $this;
1948 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1949 $this->addHTML( $text );
1953 * Add everything from a ParserOutput object.
1955 * @param ParserOutput $parserOutput
1956 * @param array $poOptions Options to ParserOutput::getText()
1958 public function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
1959 $this->addParserOutputMetadata( $parserOutput );
1960 $this->addParserOutputText( $parserOutput, $poOptions );
1964 * Add the output of a QuickTemplate to the output buffer
1966 * @param QuickTemplate &$template
1968 public function addTemplate( &$template ) {
1969 $this->addHTML( $template->getHTML() );
1973 * Parse wikitext and return the HTML.
1975 * @todo The output is wrapped in a <div> iff $interface is false; it's
1976 * probably best to always strip the wrapper.
1978 * @param string $text
1979 * @param bool $linestart Is this the start of a line?
1980 * @param bool $interface Use interface language (instead of content language) while parsing
1981 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1982 * LanguageConverter.
1983 * @param Language|null $language Target language object, will override $interface
1984 * @throws MWException
1985 * @return string HTML
1986 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
1987 * use parseAsContent() if $interface is default value or false, or else
1988 * parseAsInterface() if $interface is true.
1990 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1991 wfDeprecated( __METHOD__
, '1.33' );
1992 return $this->parseInternal(
1993 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
1995 'enableSectionEditLinks' => false,
2000 * Parse wikitext *in the page content language* and return the HTML.
2001 * The result will be language-converted to the user's preferred variant.
2002 * Output will be tidy.
2004 * @param string $text Wikitext in the page content language
2005 * @param bool $linestart Is this the start of a line? (Defaults to true)
2006 * @throws MWException
2007 * @return string HTML
2010 public function parseAsContent( $text, $linestart = true ) {
2011 return $this->parseInternal(
2012 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2014 'enableSectionEditLinks' => false,
2015 'wrapperDivClass' => ''
2020 * Parse wikitext *in the user interface language* and return the HTML.
2021 * The result will not be language-converted, as user interface messages
2022 * are already localized into a specific variant.
2023 * Output will be tidy.
2025 * @param string $text Wikitext in the user interface language
2026 * @param bool $linestart Is this the start of a line? (Defaults to true)
2027 * @throws MWException
2028 * @return string HTML
2031 public function parseAsInterface( $text, $linestart = true ) {
2032 return $this->parseInternal(
2033 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2035 'enableSectionEditLinks' => false,
2036 'wrapperDivClass' => ''
2041 * Parse wikitext *in the user interface language*, strip
2042 * paragraph wrapper, and return the HTML.
2043 * The result will not be language-converted, as user interface messages
2044 * are already localized into a specific variant.
2045 * Output will be tidy. Outer paragraph wrapper will only be stripped
2046 * if the result is a single paragraph.
2048 * @param string $text Wikitext in the user interface language
2049 * @param bool $linestart Is this the start of a line? (Defaults to true)
2050 * @throws MWException
2051 * @return string HTML
2054 public function parseInlineAsInterface( $text, $linestart = true ) {
2055 return Parser
::stripOuterParagraph(
2056 $this->parseAsInterface( $text, $linestart )
2061 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2063 * @param string $text
2064 * @param bool $linestart Is this the start of a line?
2065 * @param bool $interface Use interface language (instead of content language) while parsing
2066 * language sensitive magic words like GRAMMAR and PLURAL
2067 * @return string HTML
2068 * @deprecated since 1.32, due to untidy output and confusing default
2069 * for $interface. Use parseInlineAsInterface() if $interface is
2070 * the default value or false, or else use
2071 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2073 public function parseInline( $text, $linestart = true, $interface = false ) {
2074 wfDeprecated( __METHOD__
, '1.33' );
2075 $parsed = $this->parseInternal(
2076 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2078 'enableSectionEditLinks' => false,
2079 'wrapperDivClass' => '', /* no wrapper div */
2081 return Parser
::stripOuterParagraph( $parsed );
2085 * Parse wikitext and return the HTML (internal implementation helper)
2087 * @param string $text
2088 * @param Title $title The title to use
2089 * @param bool $linestart Is this the start of a line?
2090 * @param bool $tidy Whether the output should be tidied
2091 * @param bool $interface Use interface language (instead of content language) while parsing
2092 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2093 * LanguageConverter.
2094 * @param Language|null $language Target language object, will override $interface
2095 * @throws MWException
2096 * @return ParserOutput
2098 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2099 if ( is_null( $title ) ) {
2100 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2103 $popts = $this->parserOptions();
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(
2112 $text, $title, $popts,
2113 $linestart, true, $this->mRevisionId
2116 $popts->setTidy( $oldTidy );
2117 $popts->setInterfaceMessage( $oldInterface );
2119 if ( $language !== null ) {
2120 $popts->setTargetLanguage( $oldLang );
2123 return $parserOutput;
2127 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2129 * @param int $maxage Maximum cache time on the CDN, in seconds.
2131 public function setCdnMaxage( $maxage ) {
2132 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2136 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2137 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2138 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2141 * @param int $maxage Maximum cache time on the CDN, in seconds
2144 public function lowerCdnMaxage( $maxage ) {
2145 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2146 $this->setCdnMaxage( $this->mCdnMaxage
);
2150 * Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
2152 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2153 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2154 * TTL is 90% of the age of the object, subject to the min and max.
2156 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2157 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2158 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2161 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2162 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2163 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'CdnMaxAge' );
2165 if ( $mtime === null ||
$mtime === false ) {
2166 return; // entity does not exist
2169 $age = MWTimestamp
::time() - (int)wfTimestamp( TS_UNIX
, $mtime );
2170 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2171 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2173 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2177 * Use enableClientCache(false) to force it to send nocache headers
2179 * @param bool|null $state New value, or null to not set the value
2181 * @return bool Old value
2183 public function enableClientCache( $state ) {
2184 return wfSetVar( $this->mEnableClientCache
, $state );
2188 * Get the list of cookie names that will influence the cache
2192 public function getCacheVaryCookies() {
2193 if ( self
::$cacheVaryCookies === null ) {
2194 $config = $this->getConfig();
2195 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2196 SessionManager
::singleton()->getVaryCookies(),
2200 $config->get( 'CacheVaryCookies' )
2202 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2204 return self
::$cacheVaryCookies;
2208 * Check if the request has a cache-varying cookie header
2209 * If it does, it's very important that we don't allow public caching
2213 public function haveCacheVaryCookies() {
2214 $request = $this->getRequest();
2215 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2216 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2217 wfDebug( __METHOD__
. ": found $cookieName\n" );
2221 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2226 * Add an HTTP header that will influence on the cache
2228 * @param string $header Header name
2229 * @param string[]|null $option Deprecated; formerly options for the
2230 * Key header, deprecated in 1.32 and removed in 1.34. See
2231 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2232 * for the list of formerly-valid options.
2234 public function addVaryHeader( $header, array $option = null ) {
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;
2244 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2245 * such as Accept-Encoding or Cookie
2249 public function getVaryHeader() {
2250 // If we vary on cookies, let's make sure it's always included here too.
2251 if ( $this->getCacheVaryCookies() ) {
2252 $this->addVaryHeader( 'Cookie' );
2255 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2256 $this->addVaryHeader( $header, $options );
2258 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2262 * Add an HTTP Link: header
2264 * @param string $header Header value
2266 public function addLinkHeader( $header ) {
2267 $this->mLinkHeader
[] = $header;
2271 * Return a Link: header. Based on the values of $mLinkHeader.
2273 * @return string|false
2275 public function getLinkHeader() {
2276 if ( !$this->mLinkHeader
) {
2280 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2284 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2287 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2288 * /w/index.php?title=Main_page&variant=zh-cn will not.
2290 private function addAcceptLanguage() {
2291 $title = $this->getTitle();
2292 if ( !$title instanceof Title
) {
2296 $lang = $title->getPageLanguage();
2297 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2298 $this->addVaryHeader( 'Accept-Language' );
2303 * Set a flag which will cause an X-Frame-Options header appropriate for
2304 * edit pages to be sent. The header value is controlled by
2305 * $wgEditPageFrameOptions.
2307 * This is the default for special pages. If you display a CSRF-protected
2308 * form on an ordinary view page, then you need to call this function.
2310 * @param bool $enable
2312 public function preventClickjacking( $enable = true ) {
2313 $this->mPreventClickjacking
= $enable;
2317 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2318 * This can be called from pages which do not contain any CSRF-protected
2321 public function allowClickjacking() {
2322 $this->mPreventClickjacking
= false;
2326 * Get the prevent-clickjacking flag
2331 public function getPreventClickjacking() {
2332 return $this->mPreventClickjacking
;
2336 * Get the X-Frame-Options header value (without the name part), or false
2337 * if there isn't one. This is used by Skin to determine whether to enable
2338 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2340 * @return string|false
2342 public function getFrameOptions() {
2343 $config = $this->getConfig();
2344 if ( $config->get( 'BreakFrames' ) ) {
2346 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2347 return $config->get( 'EditPageFrameOptions' );
2353 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2354 * Trials: https://github.com/GoogleChrome/OriginTrials
2358 private function getOriginTrials() {
2359 $config = $this->getConfig();
2361 return $config->get( 'OriginTrials' );
2364 private function getReportTo() {
2365 $config = $this->getConfig();
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
);
2388 private function getFeaturePolicyReportOnly() {
2389 $config = $this->getConfig();
2391 $features = $config->get( 'FeaturePolicyReportOnly' );
2392 return implode( ';', $features );
2396 * Send cache control HTTP headers
2398 public function sendCacheControl() {
2399 $response = $this->getRequest()->response();
2400 $config = $this->getConfig();
2402 $this->addVaryHeader( 'Cookie' );
2403 $this->addAcceptLanguage();
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
2407 $response->header( $this->getVaryHeader() );
2409 if ( $this->mEnableClientCache
) {
2411 $config->get( 'UseCdn' ) &&
2412 !$response->hasCookies() &&
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
2422 wfDebug( __METHOD__
.
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" );
2426 $response->header( "Cache-Control: " .
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' );
2450 * Transfer styles and JavaScript modules from skin.
2452 * @param Skin $sk to load modules for
2454 public function loadSkinModules( $sk ) {
2455 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2456 if ( $group === 'styles' ) {
2457 foreach ( $modules as $key => $moduleMembers ) {
2458 $this->addModuleStyles( $moduleMembers );
2461 $this->addModules( $modules );
2467 * Finally, all the text has been munged and accumulated into
2468 * the object, let's actually output it:
2470 * @param bool $return Set to true to get the result as a string rather than sending it
2471 * @return string|null
2473 * @throws FatalError
2474 * @throws MWException
2476 public function output( $return = false ) {
2477 if ( $this->mDoNothing
) {
2478 return $return ?
'' : null;
2481 $response = $this->getRequest()->response();
2482 $config = $this->getConfig();
2484 if ( $this->mRedirect
!= '' ) {
2485 # Standards require redirect URLs to be absolute
2486 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2488 $redirect = $this->mRedirect
;
2489 $code = $this->mRedirectCode
;
2491 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2492 if ( $code == '301' ||
$code == '303' ) {
2493 if ( !$config->get( 'DebugRedirects' ) ) {
2494 $response->statusHeader( $code );
2496 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2498 if ( $config->get( 'VaryOnXFP' ) ) {
2499 $this->addVaryHeader( 'X-Forwarded-Proto' );
2501 $this->sendCacheControl();
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() );
2526 $linkHeader = $this->getLinkHeader();
2527 if ( $linkHeader ) {
2528 $response->header( $linkHeader );
2531 // Prevent framing, if requested
2532 $frameOptions = $this->getFrameOptions();
2533 if ( $frameOptions ) {
2534 $response->header( "X-Frame-Options: $frameOptions" );
2537 $originTrials = $this->getOriginTrials();
2538 foreach ( $originTrials as $originTrial ) {
2539 $response->header( "Origin-Trial: $originTrial", false );
2542 $reportTo = $this->getReportTo();
2544 $response->header( "Report-To: $reportTo" );
2547 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2548 if ( $featurePolicyReportOnly ) {
2549 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2552 ContentSecurityPolicy
::sendHeaders( $this );
2554 if ( $this->mArticleBodyOnly
) {
2555 echo $this->mBodytext
;
2557 // Enable safe mode if requested (T152169)
2558 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2559 $this->disallowUserJs();
2562 $sk = $this->getSkin();
2563 $this->loadSkinModules( $sk );
2565 MWDebug
::addModules( $this );
2567 // Avoid PHP 7.1 warning of passing $this by reference
2568 $outputPage = $this;
2569 // Hook that allows last minute changes to the output page, e.g.
2570 // adding of CSS or Javascript by extensions.
2571 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2575 } catch ( Exception
$e ) {
2576 ob_end_clean(); // bug T129657
2582 // This hook allows last minute changes to final overall output by modifying output buffer
2583 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2584 } catch ( Exception
$e ) {
2585 ob_end_clean(); // bug T129657
2589 $this->sendCacheControl();
2592 return ob_get_clean();
2600 * Prepare this object to display an error page; disable caching and
2601 * indexing, clear the current text and redirect, set the page's title
2602 * and optionally an custom HTML title (content of the "<title>" tag).
2604 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2605 * @param string|Message|false $htmlTitle Will be passed directly to setHTMLTitle();
2606 * optional, if not passed the "<title>" attribute will be
2607 * based on $pageTitle
2609 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2610 $this->setPageTitle( $pageTitle );
2611 if ( $htmlTitle !== false ) {
2612 $this->setHTMLTitle( $htmlTitle );
2614 $this->setRobotPolicy( 'noindex,nofollow' );
2615 $this->setArticleRelated( false );
2616 $this->enableClientCache( false );
2617 $this->mRedirect
= '';
2618 $this->clearSubtitle();
2623 * Output a standard error page
2625 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2626 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2627 * showErrorPage( 'titlemsg', $messageObject );
2628 * showErrorPage( $titleMessageObject, $messageObject );
2630 * @param string|Message $title Message key (string) for page title, or a Message object
2631 * @param string|Message $msg Message key (string) for page text, or a Message object
2632 * @param array $params Message parameters; ignored if $msg is a Message object
2634 public function showErrorPage( $title, $msg, $params = [] ) {
2635 if ( !$title instanceof Message
) {
2636 $title = $this->msg( $title );
2639 $this->prepareErrorPage( $title );
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() );
2649 $this->addWikiMsgArray( $msg, $params );
2652 $this->returnToMain();
2656 * Output a standard permission error page
2658 * @param array $errors Error message keys or [key, param...] arrays
2659 * @param string|null $action Action that was denied or null if unknown
2661 public function showPermissionsErrorPage( array $errors, $action = null ) {
2662 $services = MediaWikiServices
::getInstance();
2663 $permissionManager = $services->getPermissionManager();
2664 foreach ( $errors as $key => $error ) {
2665 $errors[$key] = (array)$error;
2668 // For some action (read, edit, create and upload), display a "login to do this action"
2669 // error if all of the following conditions are met:
2670 // 1. the user is not logged in
2671 // 2. the only error is insufficient permissions (i.e. no block or something else)
2672 // 3. the error can be avoided simply by logging in
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.
2686 $request = $this->getRequest();
2687 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
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';
2697 $displayReturnto = Title
::newMainPage();
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 );
2714 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2715 $linkRenderer = $services->getLinkRenderer();
2716 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2717 $loginLink = $linkRenderer->makeKnownLink(
2719 $this->msg( 'loginreqlink' )->text(),
2724 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
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
2732 $this->returnToMain( null, $displayReturnto );
2735 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2736 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2741 * Display an error page indicating that a given version of MediaWiki is
2742 * required to use it
2744 * @param mixed $version The version of MediaWiki needed to use the page
2746 public function versionRequired( $version ) {
2747 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2749 $this->addWikiMsg( 'versionrequiredtext', $version );
2750 $this->returnToMain();
2754 * Format a list of error messages
2756 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2757 * @param string|null $action Action that was denied or null if unknown
2758 * @return string The wikitext error-messages, formatted into a list.
2760 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
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() .
2791 * Show a warning about replica DB lag
2793 * If the lag is higher than $wgSlaveLagCritical seconds,
2794 * then the warning is a bit more obvious. If the lag is
2795 * lower than $wgSlaveLagWarning, then no warning is shown.
2797 * @param int $lag Replica lag
2799 public function showLagWarning( $lag ) {
2800 $config = $this->getConfig();
2801 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2802 $lag = floor( $lag ); // floor to avoid nano seconds to display
2803 $message = $lag < $config->get( 'SlaveLagCritical' )
2806 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2807 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2812 * Output an error page
2814 * @note FatalError exception class provides an alternative.
2815 * @param string $message Error to output. Must be escaped for HTML.
2817 public function showFatalError( $message ) {
2818 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2820 $this->addHTML( $message );
2824 * Add a "return to" link pointing to a specified title
2826 * @param LinkTarget $title Title to link
2827 * @param array $query Query string parameters
2828 * @param string|null $text Text of the link (input is not escaped)
2829 * @param array $options Options array to pass to Linker
2831 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
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" );
2840 * Add a "return to" link pointing to a specified title,
2841 * or the title indicated in the request, or else the main page
2843 * @param mixed|null $unused
2844 * @param Title|string|null $returnto Title or String to return to
2845 * @param string|null $returntoquery Query string for the return to link
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 === '' ) {
2857 $returnto = Title
::newMainPage();
2860 if ( is_object( $returnto ) ) {
2861 $titleObj = $returnto;
2863 $titleObj = Title
::newFromText( $returnto );
2865 // We don't want people to return to external interwiki. That
2866 // might potentially be used as part of a phishing scheme
2867 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2868 $titleObj = Title
::newMainPage();
2871 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2874 private function getRlClientContext() {
2875 if ( !$this->rlClientContext
) {
2876 $query = ResourceLoader
::makeLoaderQuery(
2877 [], // modules; not relevant
2878 $this->getLanguage()->getCode(),
2879 $this->getSkin()->getSkinName(),
2880 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2881 null, // version; not relevant
2882 ResourceLoader
::inDebugMode(),
2883 null, // only; not relevant
2884 $this->isPrintable(),
2885 $this->getRequest()->getBool( 'handheld' )
2887 $this->rlClientContext
= new ResourceLoaderContext(
2888 $this->getResourceLoader(),
2889 new FauxRequest( $query )
2891 if ( $this->contentOverrideCallbacks
) {
2892 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2893 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2894 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2895 $content = $callback( $title );
2896 if ( $content !== null ) {
2897 $text = ContentHandler
::getContentText( $content );
2898 if ( strpos( $text, '</script>' ) !== false ) {
2899 // Proactively replace this so that we can display a message
2900 // to the user, instead of letting it go to Html::inlineScript(),
2901 // where it would be considered a server-side issue.
2902 $titleFormatted = $title->getPrefixedText();
2903 $content = new JavaScriptContent(
2904 Xml
::encodeJsCall( 'mw.log.error', [
2905 "Cannot preview $titleFormatted due to script-closing tag."
2916 return $this->rlClientContext
;
2920 * Call this to freeze the module queue and JS config and create a formatter.
2922 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2923 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2924 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2925 * the module filters retroactively. Skins and extension hooks may also add modules until very
2926 * late in the request lifecycle.
2928 * @return ResourceLoaderClientHtml
2930 public function getRlClient() {
2931 if ( !$this->rlClient
) {
2932 $context = $this->getRlClientContext();
2933 $rl = $this->getResourceLoader();
2934 $this->addModules( [
2939 $this->addModuleStyles( [
2944 $this->getSkin()->setupSkinUserCss( $this );
2946 // Prepare exempt modules for buildExemptModules()
2947 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2949 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2951 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2952 // Separate user-specific batch for improved cache-hit ratio.
2953 $userBatch = [ 'user.styles', 'user' ];
2954 $siteBatch = array_diff( $moduleStyles, $userBatch );
2955 $dbr = wfGetDB( DB_REPLICA
);
2956 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2957 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2959 // Filter out modules handled by buildExemptModules()
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 ) ) {
2968 // E.g. Don't output empty <styles>
2969 $exemptGroups[$group][] = $name;
2977 $this->rlExemptStyleModules
= $exemptGroups;
2979 $rlClient = new ResourceLoaderClientHtml( $context, [
2980 'target' => $this->getTarget(),
2981 'nonce' => $this->getCSPNonce(),
2982 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2983 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2984 // modules enqueud for loading on this page is filtered to just those.
2985 // However, to make sure we also apply the restriction to dynamic dependencies and
2986 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2987 // StartupModule so that the client-side registry will not contain any restricted
2988 // modules either. (T152169, T185303)
2989 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2990 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2993 $rlClient->setConfig( $this->getJSVars() );
2994 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2995 $rlClient->setModuleStyles( $moduleStyles );
2996 $rlClient->setExemptStates( $exemptStates );
2997 $this->rlClient
= $rlClient;
2999 return $this->rlClient
;
3003 * @param Skin $sk The given Skin
3004 * @param bool $includeStyle Unused
3005 * @return string The doctype, opening "<html>", and head element.
3007 public function headElement( Skin
$sk, $includeStyle = true ) {
3008 $config = $this->getConfig();
3009 $userdir = $this->getLanguage()->getDir();
3010 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3013 $htmlAttribs = Sanitizer
::mergeAttributes(
3014 $this->getRlClient()->getDocumentAttributes(),
3015 $sk->getHtmlElementAttributes()
3017 $pieces[] = Html
::htmlHeader( $htmlAttribs );
3018 $pieces[] = Html
::openElement( 'head' );
3020 if ( $this->getHTMLTitle() == '' ) {
3021 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3024 if ( !Html
::isXmlMimeType( $config->get( 'MimeType' ) ) ) {
3025 // Add <meta charset="UTF-8">
3026 // This should be before <title> since it defines the charset used by
3027 // text including the text inside <title>.
3028 // The spec recommends defining XHTML5's charset using the XML declaration
3030 // Our XML declaration is output by Html::htmlHeader.
3031 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3032 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3033 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3036 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3037 $pieces[] = $this->getRlClient()->getHeadHtml( $htmlAttribs['class'] ??
null );
3038 $pieces[] = $this->buildExemptModules();
3039 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3040 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3042 // This library is intended to run on older browsers that MediaWiki no longer
3043 // supports as Grade A. For these Grade C browsers, we provide an experience
3044 // using only HTML and CSS. But, where standards-compliant browsers are able to
3045 // style unknown HTML elements without issue, old IE ignores these styles.
3046 // The html5shiv library fixes that.
3047 // Use an IE conditional comment to serve the script only to old IE
3048 $shivUrl = $config->get( 'ResourceBasePath' ) . '/resources/lib/html5shiv/html5shiv.js';
3049 $pieces[] = '<!--[if lt IE 9]>' .
3050 Html
::linkedScript( $shivUrl, $this->getCSPNonce() ) .
3053 $pieces[] = Html
::closeElement( 'head' );
3055 $bodyClasses = $this->mAdditionalBodyClasses
;
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 ) {
3064 // The following classes can be used here:
3065 // * mw-underline-always
3066 // * mw-underline-never
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';
3075 // Parser feature migration class
3076 // The idea is that this will eventually be removed, after the wikitext
3077 // which requires it is cleaned up.
3078 $bodyClasses[] = 'mw-hide-empty-elt';
3080 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3081 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3083 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3086 // While the implode() is not strictly needed, it's used for backwards compatibility
3087 // (this used to be built as a string and hooks likely still expect that).
3088 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3090 // Allow skins and extensions to add body attributes they need
3091 $sk->addToBodyAttributes( $this, $bodyAttrs );
3092 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3094 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3096 return self
::combineWrappedStrings( $pieces );
3100 * Get a ResourceLoader object associated with this OutputPage
3102 * @return ResourceLoader
3104 public function getResourceLoader() {
3105 if ( is_null( $this->mResourceLoader
) ) {
3106 // Lazy-initialise as needed
3107 $this->mResourceLoader
= MediaWikiServices
::getInstance()->getResourceLoader();
3109 return $this->mResourceLoader
;
3113 * Explicily load or embed modules on a page.
3115 * @param array|string $modules One or more module names
3116 * @param string $only ResourceLoaderModule TYPE_ class constant
3117 * @param array $extraQuery [optional] Array with extra query parameters for the request
3118 * @return string|WrappedStringList HTML
3120 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3121 // Apply 'target' and 'origin' filters
3122 $modules = $this->filterModules( (array)$modules, null, $only );
3124 return ResourceLoaderClientHtml
::makeLoad(
3125 $this->getRlClientContext(),
3129 $this->getCSPNonce()
3134 * Combine WrappedString chunks and filter out empty ones
3136 * @param array $chunks
3137 * @return string|WrappedStringList HTML
3139 protected static function combineWrappedStrings( array $chunks ) {
3140 // Filter out empty values
3141 $chunks = array_filter( $chunks, 'strlen' );
3142 return WrappedString
::join( "\n", $chunks );
3146 * JS stuff to put at the bottom of the `<body>`.
3147 * These are legacy scripts ($this->mScripts), and user JS.
3149 * @return string|WrappedStringList HTML
3151 public function getBottomScripts() {
3153 $chunks[] = $this->getRlClient()->getBodyHtml();
3155 // Legacy non-ResourceLoader scripts
3156 $chunks[] = $this->mScripts
;
3158 if ( $this->limitReportJSData
) {
3159 $chunks[] = ResourceLoader
::makeInlineScript(
3160 ResourceLoader
::makeConfigSetScript(
3161 [ 'wgPageParseReport' => $this->limitReportJSData
]
3163 $this->getCSPNonce()
3167 return self
::combineWrappedStrings( $chunks );
3171 * Get the javascript config vars to include on this page
3173 * @return array Array of javascript config vars
3176 public function getJsConfigVars() {
3177 return $this->mJsConfigVars
;
3181 * Add one or more variables to be set in mw.config in JavaScript
3183 * @param string|array $keys Key or array of key/value pairs
3184 * @param mixed|null $value [optional] Value of the configuration variable
3186 public function addJsConfigVars( $keys, $value = null ) {
3187 if ( is_array( $keys ) ) {
3188 foreach ( $keys as $key => $value ) {
3189 $this->mJsConfigVars
[$key] = $value;
3194 $this->mJsConfigVars
[$keys] = $value;
3198 * Get an array containing the variables to be set in mw.config in JavaScript.
3200 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3201 * - in other words, page-independent/site-wide variables (without state).
3202 * You will only be adding bloat to the html page and causing page caches to
3203 * have to be purged on configuration changes.
3206 public function getJSVars() {
3209 $canonicalSpecialPageName = false; # T23115
3210 $services = MediaWikiServices
::getInstance();
3212 $title = $this->getTitle();
3213 $ns = $title->getNamespace();
3214 $nsInfo = $services->getNamespaceInfo();
3215 $canonicalNamespace = $nsInfo->exists( $ns )
3216 ?
$nsInfo->getCanonicalName( $ns )
3217 : $title->getNsText();
3219 $sk = $this->getSkin();
3220 // Get the relevant title so that AJAX features can use the correct page name
3221 // when making API requests from certain special pages (T36972).
3222 $relevantTitle = $sk->getRelevantTitle();
3223 $relevantUser = $sk->getRelevantUser();
3225 if ( $ns == NS_SPECIAL
) {
3226 list( $canonicalSpecialPageName, /*...*/ ) =
3227 $services->getSpecialPageFactory()->
3228 resolveAlias( $title->getDBkey() );
3229 } elseif ( $this->canUseWikiPage() ) {
3230 $wikiPage = $this->getWikiPage();
3231 $curRevisionId = $wikiPage->getLatest();
3232 $articleId = $wikiPage->getId();
3235 $lang = $title->getPageViewLanguage();
3237 // Pre-process information
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 ),
3251 $user = $this->getUser();
3254 'wgCanonicalNamespace' => $canonicalNamespace,
3255 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3256 'wgNamespaceNumber' => $title->getNamespace(),
3257 'wgPageName' => $title->getPrefixedDBkey(),
3258 'wgTitle' => $title->getText(),
3259 'wgCurRevisionId' => $curRevisionId,
3260 'wgRevisionId' => (int)$this->getRevisionId(),
3261 'wgArticleId' => $articleId,
3262 'wgIsArticle' => $this->isArticle(),
3263 'wgIsRedirect' => $title->isRedirect(),
3264 'wgAction' => Action
::getActionName( $this->getContext() ),
3265 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3266 'wgUserGroups' => $user->getEffectiveGroups(),
3267 'wgCategories' => $this->getCategories(),
3268 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
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(),
3278 'wgRequestId' => WebRequest
::getRequestId(),
3279 'wgCSPNonce' => $this->getCSPNonce(),
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;
3287 // Get the revision ID of the oldest new message on the user's talk
3288 // page. This can be used for constructing new message alerts on
3290 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3293 $contLang = $services->getContentLanguage();
3294 if ( $contLang->hasVariants() ) {
3295 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3297 // Same test as SkinTemplate
3298 $vars['wgIsProbablyEditable'] = $this->userCanEditOrCreate( $user, $title );
3300 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3301 $this->userCanEditOrCreate( $user, $relevantTitle );
3303 foreach ( $title->getRestrictionTypes() as $type ) {
3304 // Following keys are set in $vars:
3305 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
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();
3321 // Allow extensions to add their custom variables to the mw.config map.
3322 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3323 // page-dependant but site-wide (without state).
3324 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3325 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3327 // Merge in variables from addJsConfigVars last
3328 return array_merge( $vars, $this->getJsConfigVars() );
3332 * To make it harder for someone to slip a user a fake
3333 * JavaScript or CSS preview, a random token
3334 * is associated with the login session. If it's not
3335 * passed back with the preview request, we won't render
3340 public function userCanPreview() {
3341 $request = $this->getRequest();
3343 $request->getVal( 'action' ) !== 'submit' ||
3344 !$request->wasPosted()
3349 $user = $this->getUser();
3351 if ( !$user->isLoggedIn() ) {
3352 // Anons have predictable edit tokens
3355 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3359 $title = $this->getTitle();
3360 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3361 if ( count( $errors ) !== 0 ) {
3370 * @param LinkTarget $title
3373 private function userCanEditOrCreate(
3377 $pm = MediaWikiServices
::getInstance()->getPermissionManager();
3378 return $pm->quickUserCan( 'edit', $user, $title )
3379 && ( $this->getTitle()->exists() ||
3380 $pm->quickUserCan( 'create', $user, $title ) );
3384 * @return array Array in format "link name or number => 'link html'".
3386 public function getHeadLinksArray() {
3390 $config = $this->getConfig();
3392 $canonicalUrl = $this->mCanonicalUrl
;
3394 $tags['meta-generator'] = Html
::element( 'meta', [
3395 'name' => 'generator',
3396 'content' => "MediaWiki $wgVersion",
3399 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3400 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3401 // fallbacks should come before the primary value so we need to reverse the array.
3402 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3403 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3404 'name' => 'referrer',
3405 'content' => $policy,
3410 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3411 if ( $p !== 'index,follow' ) {
3412 // http://www.robotstxt.org/wc/meta-user.html
3413 // Only show if it's different from the default robots policy
3414 $tags['meta-robots'] = Html
::element( 'meta', [
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];
3433 $tags[$tagName] = Html
::element( 'meta',
3436 'content' => $tag[1]
3441 foreach ( $this->mLinktags
as $tag ) {
3442 $tags[] = Html
::element( 'link', $tag );
3445 # Universal edit button
3446 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3447 if ( $this->userCanEditOrCreate( $this->getUser(), $this->getTitle() ) ) {
3448 // Original UniversalEditButton
3449 $msg = $this->msg( 'edit' )->text();
3450 $tags['universal-edit-button'] = Html
::element( 'link', [
3451 'rel' => 'alternate',
3452 'type' => 'application/x-wiki',
3454 'href' => $this->getTitle()->getEditURL(),
3456 // Alternate edit link
3457 $tags['alternative-edit'] = Html
::element( 'link', [
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 ) {
3470 $tags['apple-touch-icon'] = Html
::element( 'link', [
3471 'rel' => 'apple-touch-icon',
3472 'href' => $config->get( 'AppleTouchIcon' )
3476 if ( $config->get( 'Favicon' ) !== false ) {
3477 $tags['favicon'] = Html
::element( 'link', [
3478 'rel' => 'shortcut icon',
3479 'href' => $config->get( 'Favicon' )
3483 # OpenSearch description link
3484 $tags['opensearch'] = Html
::element( '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)
3495 $tags['rsd'] = Html
::element( 'link', [
3497 'type' => 'application/rsd+xml',
3498 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3499 // Whether RSD accepts relative or protocol-relative URLs is completely
3500 // undocumented, though.
3501 'href' => wfExpandUrl( wfAppendQuery(
3503 [ 'action' => 'rsd' ] ),
3509 if ( !$config->get( 'DisableLangConversion' ) ) {
3510 $lang = $this->getTitle()->getPageLanguage();
3511 if ( $lang->hasVariants() ) {
3512 $variants = $lang->getVariants();
3513 foreach ( $variants as $variant ) {
3514 $tags["variant-$variant"] = Html
::element( 'link', [
3515 'rel' => 'alternate',
3516 'hreflang' => LanguageCode
::bcp47( $variant ),
3517 'href' => $this->getTitle()->getLocalURL(
3518 [ 'variant' => $variant ] )
3522 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3523 $tags["variant-x-default"] = Html
::element( 'link', [
3524 'rel' => 'alternate',
3525 'hreflang' => 'x-default',
3526 'href' => $this->getTitle()->getLocalURL() ] );
3531 if ( $this->copyrightUrl
!== null ) {
3532 $copyright = $this->copyrightUrl
;
3535 if ( $config->get( 'RightsPage' ) ) {
3536 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3539 $copyright = $copy->getLocalURL();
3543 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3544 $copyright = $config->get( 'RightsUrl' );
3549 $tags['copyright'] = Html
::element( 'link', [
3551 'href' => $copyright ]
3556 if ( $config->get( 'Feed' ) ) {
3559 foreach ( $this->getSyndicationLinks() as $format => $link ) {
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
3565 $feedLinks[] = $this->feedLink(
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 ) {
3586 // Note, this->feedLink escapes the url.
3587 $feedLinks[] = $this->feedLink(
3590 $this->msg( "site-{$type}-feed", $sitename )->text()
3593 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3594 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3595 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3596 $feedLinks[] = $this->feedLink(
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 ) {
3616 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3617 } elseif ( $this->isArticleRelated() ) {
3618 // This affects all requests where "setArticleRelated" is true. This is
3619 // typically all requests that show content (query title, curid, oldid, diff),
3620 // and all wikipage actions (edit, delete, purge, info, history etc.).
3621 // It does not apply to File pages and Special pages.
3622 // 'history' and 'info' actions address page metadata rather than the page
3623 // content itself, so they may not be canonicalized to the view page url.
3624 // TODO: this ought to be better encapsulated in the Action class.
3625 $action = Action
::getActionName( $this->getContext() );
3626 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3627 $query = "action={$action}";
3631 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3633 $reqUrl = $this->getRequest()->getRequestURL();
3634 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3637 if ( $canonicalUrl !== false ) {
3638 $tags[] = Html
::element( 'link', [
3639 'rel' => 'canonical',
3640 'href' => $canonicalUrl
3644 // Allow extensions to add, remove and/or otherwise manipulate these links
3645 // If you want only to *add* <head> links, please use the addHeadItem()
3646 // (or addHeadItems() for multiple items) method instead.
3647 // This hook is provided as a last resort for extensions to modify these
3648 // links before the output is sent to client.
3649 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3655 * Generate a "<link rel/>" for a feed.
3657 * @param string $type Feed type
3658 * @param string $url URL to the feed
3659 * @param string $text Value of the "title" attribute
3660 * @return string HTML fragment
3662 private function feedLink( $type, $url, $text ) {
3663 return Html
::element( 'link', [
3664 'rel' => 'alternate',
3665 'type' => "application/$type+xml",
3672 * Add a local or specified stylesheet, with the given media options.
3673 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3675 * @param string $style URL to the file
3676 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3677 * @param string $condition For IE conditional comments, specifying an IE version
3678 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
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;
3695 * Adds inline CSS styles
3696 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3698 * @param mixed $style_css Inline CSS
3699 * @param string $flip Set to 'flip' to flip the CSS if needed
3701 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
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 );
3706 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3710 * Build exempt modules and legacy non-ResourceLoader styles.
3712 * @return string|WrappedStringList HTML
3714 protected function buildExemptModules() {
3718 // - Within modules provided by the software (core, skin, extensions),
3719 // styles from skin stylesheets should be overridden by styles
3720 // from modules dynamically loaded with JavaScript.
3721 // - Styles from site-specific, private, and user modules should override
3722 // both of the above.
3724 // The effective order for stylesheets must thus be:
3725 // 1. Page style modules, formatted server-side by ResourceLoaderClientHtml.
3726 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
3727 // 3. Styles that are site-specific, private or from the user, formatted
3728 // server-side by this function.
3730 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
3733 // Add legacy styles added through addStyle()/addInlineStyle() here
3734 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3736 // Things that go after the ResourceLoaderDynamicStyles marker
3738 $separateReq = [ 'site.styles', 'user.styles' ];
3739 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3740 if ( $moduleNames ) {
3741 $append[] = $this->makeResourceLoaderLink(
3742 array_diff( $moduleNames, $separateReq ),
3743 ResourceLoaderModule
::TYPE_STYLES
3746 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3747 // These require their own dedicated request in order to support "@import"
3748 // syntax, which is incompatible with concatenation. (T147667, T37562)
3749 $append[] = $this->makeResourceLoaderLink( $name,
3750 ResourceLoaderModule
::TYPE_STYLES
3756 $chunks[] = Html
::element(
3758 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3760 $chunks = array_merge( $chunks, $append );
3763 return self
::combineWrappedStrings( $chunks );
3769 public function buildCssLinksArray() {
3772 foreach ( $this->styles
as $file => $options ) {
3773 $link = $this->styleLink( $file, $options );
3775 $links[$file] = $link;
3782 * Generate \<link\> tags for stylesheets
3784 * @param string $style URL to the file
3785 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3786 * @return string HTML fragment
3788 protected function styleLink( $style, array $options ) {
3789 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3793 if ( isset( $options['media'] ) ) {
3794 $media = self
::transformCssMedia( $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:' ) {
3807 $config = $this->getConfig();
3808 // Append file hash as query parameter
3809 $url = self
::transformResourcePath(
3811 $config->get( 'StylePath' ) . '/' . $style
3815 $link = Html
::linkedStyle( $url, $media );
3817 if ( isset( $options['condition'] ) ) {
3818 $condition = htmlspecialchars( $options['condition'] );
3819 $link = "<!--[if $condition]>$link<![endif]-->";
3825 * Transform path to web-accessible static resource.
3827 * This is used to add a validation hash as query string.
3828 * This aids various behaviors:
3830 * - Put long Cache-Control max-age headers on responses for improved
3831 * cache performance.
3832 * - Get the correct version of a file as expected by the current page.
3833 * - Instantly get the updated version of a file after deployment.
3835 * Avoid using this for urls included in HTML as otherwise clients may get different
3836 * versions of a resource when navigating the site depending on when the page was cached.
3837 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3838 * an external stylesheet).
3841 * @param Config $config
3842 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3843 * @return string URL
3845 public static function transformResourcePath( Config
$config, $path ) {
3849 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3850 if ( $remotePathPrefix === '' ) {
3851 // The configured base path is required to be empty string for
3852 // wikis in the domain root
3855 $remotePath = $remotePathPrefix;
3857 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3858 // - Path is outside wgResourceBasePath, ignore.
3859 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3862 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3863 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3864 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3865 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
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 );
3873 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3877 * Utility method for transformResourceFilePath().
3879 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3882 * @param string $remotePathPrefix URL path prefix that points to $localPath
3883 * @param string $localPath File directory exposed at $remotePath
3884 * @param string $file Path to target file relative to $localPath
3885 * @return string URL
3887 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
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 );
3897 * Transform "media" attribute based on request parameters
3899 * @param string $media Current value of the "media" attribute
3900 * @return string Modified value of the "media" attribute, or null to skip
3903 public static function transformCssMedia( $media ) {
3906 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3907 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3909 // Switch in on-screen display for media testing
3911 'printable' => 'print',
3912 'handheld' => 'handheld',
3914 foreach ( $switches as $switch => $targetMedia ) {
3915 if ( $wgRequest->getBool( $switch ) ) {
3916 if ( $media == $targetMedia ) {
3918 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3919 /* This regex will not attempt to understand a comma-separated media_query_list
3921 * Example supported values for $media:
3922 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3923 * Example NOT supported value for $media:
3924 * '3d-glasses, screen, print and resolution > 90dpi'
3926 * If it's a print request, we never want any kind of screen stylesheets
3927 * If it's a handheld request (currently the only other choice with a switch),
3928 * we don't want simple 'screen' but we might want screen queries that
3929 * have a max-width or something, so we'll pass all others on and let the
3930 * client do the query.
3932 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3943 * Add a wikitext-formatted message to the output.
3944 * This is equivalent to:
3946 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3948 public function addWikiMsg( /*...*/ ) {
3949 $args = func_get_args();
3950 $name = array_shift( $args );
3951 $this->addWikiMsgArray( $name, $args );
3955 * Add a wikitext-formatted message to the output.
3956 * Like addWikiMsg() except the parameters are taken as an array
3957 * instead of a variable argument list.
3959 * @param string $name
3960 * @param array $args
3962 public function addWikiMsgArray( $name, $args ) {
3963 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3967 * This function takes a number of message/argument specifications, wraps them in
3968 * some overall structure, and then parses the result and adds it to the output.
3970 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3971 * and so on. The subsequent arguments may be either
3972 * 1) strings, in which case they are message names, or
3973 * 2) arrays, in which case, within each array, the first element is the message
3974 * name, and subsequent elements are the parameters to that message.
3976 * Don't use this for messages that are not in the user's interface language.
3980 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3984 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
3985 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3987 * The newline after the opening div is needed in some wikitext. See T21226.
3989 * @param string $wrap
3991 public function wrapWikiMsg( $wrap /*, ...*/ ) {
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 );
4006 $this->addWikiTextAsInterface( $s );
4010 * Whether the output has a table of contents
4014 public function isTOCEnabled() {
4015 return $this->mEnableTOC
;
4019 * Helper function to setup the PHP implementation of OOUI to use in this request.
4022 * @param string $skinName The Skin name to determine the correct OOUI theme
4023 * @param string $dir Language direction
4025 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4026 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4027 $theme = $themes[$skinName] ??
$themes['default'];
4028 // For example, 'OOUI\WikimediaUITheme'.
4029 $themeClass = "OOUI\\{$theme}Theme";
4030 OOUI\Theme
::setSingleton( new $themeClass() );
4031 OOUI\Element
::setDefaultDir( $dir );
4035 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4036 * MediaWiki and this OutputPage instance.
4040 public function enableOOUI() {
4042 strtolower( $this->getSkin()->getSkinName() ),
4043 $this->getLanguage()->getDir()
4045 $this->addModuleStyles( [
4046 'oojs-ui-core.styles',
4047 'oojs-ui.styles.indicators',
4048 'mediawiki.widgets.styles',
4049 'oojs-ui-core.icons',
4054 * Get (and set if not yet set) the CSP nonce.
4056 * This value needs to be included in any <script> tags on the
4059 * @return string|bool Nonce or false to mean don't output nonce
4062 public function getCSPNonce() {
4063 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4066 if ( $this->CSPNonce
=== null ) {
4067 // XXX It might be expensive to generate randomness
4068 // on every request, on Windows.
4069 $rand = random_bytes( 15 );
4070 $this->CSPNonce
= base64_encode( $rand );
4072 return $this->CSPNonce
;