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 = [];
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 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 function addMeta( $name, $val ) {
389 array_push( $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 function addLink( array $linkarr ) {
410 array_push( $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 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 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 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
1602 public function parserOptions( $options = null ) {
1603 if ( $options !== null ) {
1604 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1607 if ( $options !== null && !empty( $options->isBogus
) ) {
1608 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1609 // been changed somehow, and keep it if so.
1610 $anonPO = ParserOptions
::newFromAnon();
1611 $anonPO->setAllowUnsafeRawHtml( false );
1612 if ( !$options->matches( $anonPO ) ) {
1613 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1614 $options->isBogus
= false;
1618 if ( !$this->mParserOptions
) {
1619 if ( !$this->getUser()->isSafeToLoad() ) {
1620 // $wgUser isn't unstubbable yet, so don't try to get a
1621 // ParserOptions for it. And don't cache this ParserOptions
1623 $po = ParserOptions
::newFromAnon();
1624 $po->setAllowUnsafeRawHtml( false );
1625 $po->isBogus
= true;
1626 if ( $options !== null ) {
1627 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1632 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1633 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1636 if ( $options !== null && !empty( $options->isBogus
) ) {
1637 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1639 return wfSetVar( $this->mParserOptions
, null, true );
1641 return wfSetVar( $this->mParserOptions
, $options );
1646 * Set the revision ID which will be seen by the wiki text parser
1647 * for things such as embedded {{REVISIONID}} variable use.
1649 * @param int|null $revid A positive integer, or null
1650 * @return mixed Previous value
1652 public function setRevisionId( $revid ) {
1653 $val = is_null( $revid ) ?
null : intval( $revid );
1654 return wfSetVar( $this->mRevisionId
, $val, true );
1658 * Get the displayed revision ID
1662 public function getRevisionId() {
1663 return $this->mRevisionId
;
1667 * Whether the revision displayed is the latest revision of the page
1672 public function isRevisionCurrent() {
1673 return $this->mRevisionId
== 0 ||
$this->mRevisionId
== $this->getTitle()->getLatestRevID();
1677 * Set the timestamp of the revision which will be displayed. This is used
1678 * to avoid a extra DB call in Skin::lastModified().
1680 * @param string|null $timestamp
1681 * @return mixed Previous value
1683 public function setRevisionTimestamp( $timestamp ) {
1684 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1688 * Get the timestamp of displayed revision.
1689 * This will be null if not filled by setRevisionTimestamp().
1691 * @return string|null
1693 public function getRevisionTimestamp() {
1694 return $this->mRevisionTimestamp
;
1698 * Set the displayed file version
1700 * @param File|null $file
1701 * @return mixed Previous value
1703 public function setFileVersion( $file ) {
1705 if ( $file instanceof File
&& $file->exists() ) {
1706 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1708 return wfSetVar( $this->mFileVersion
, $val, true );
1712 * Get the displayed file version
1714 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1716 public function getFileVersion() {
1717 return $this->mFileVersion
;
1721 * Get the templates used on this page
1723 * @return array (namespace => dbKey => revId)
1726 public function getTemplateIds() {
1727 return $this->mTemplateIds
;
1731 * Get the files used on this page
1733 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1736 public function getFileSearchOptions() {
1737 return $this->mImageTimeKeys
;
1741 * Convert wikitext *in the user interface language* to HTML and
1742 * add it to the buffer. The result will not be
1743 * language-converted, as user interface messages are already
1744 * localized into a specific variant. Assumes that the current
1745 * page title will be used if optional $title is not
1746 * provided. Output will be tidy.
1748 * @param string $text Wikitext in the user interface language
1749 * @param bool $linestart Is this the start of a line? (Defaults to true)
1750 * @param Title|null $title Optional title to use; default of `null`
1751 * means use current page title.
1752 * @throws MWException if $title is not provided and OutputPage::getTitle()
1756 public function addWikiTextAsInterface(
1757 $text, $linestart = true, Title
$title = null
1759 if ( $title === null ) {
1760 $title = $this->getTitle();
1763 throw new MWException( 'Title is null' );
1765 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1769 * Convert wikitext *in the user interface language* to HTML and
1770 * add it to the buffer with a `<div class="$wrapperClass">`
1771 * wrapper. The result will not be language-converted, as user
1772 * interface messages as already localized into a specific
1773 * variant. The $text will be parsed in start-of-line context.
1774 * Output will be tidy.
1776 * @param string $wrapperClass The class attribute value for the <div>
1777 * wrapper in the output HTML
1778 * @param string $text Wikitext in the user interface language
1781 public function wrapWikiTextAsInterface(
1782 $wrapperClass, $text
1784 $this->addWikiTextTitleInternal(
1785 $text, $this->getTitle(),
1786 /*linestart*/true, /*interface*/true,
1792 * Convert wikitext *in the page content language* to HTML and add
1793 * it to the buffer. The result with be language-converted to the
1794 * user's preferred variant. Assumes that the current page title
1795 * will be used if optional $title is not provided. Output will be
1798 * @param string $text Wikitext in the page content language
1799 * @param bool $linestart Is this the start of a line? (Defaults to true)
1800 * @param Title|null $title Optional title to use; default of `null`
1801 * means use current page title.
1802 * @throws MWException if $title is not provided and OutputPage::getTitle()
1806 public function addWikiTextAsContent(
1807 $text, $linestart = true, Title
$title = null
1809 if ( $title === null ) {
1810 $title = $this->getTitle();
1813 throw new MWException( 'Title is null' );
1815 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
1819 * Add wikitext with a custom Title object.
1820 * Output is unwrapped.
1822 * @param string $text Wikitext
1823 * @param Title $title
1824 * @param bool $linestart Is this the start of a line?
1825 * @param bool $interface Whether it is an interface message
1826 * (for example disables conversion)
1827 * @param string $wrapperClass if not empty, wraps the output in
1828 * a `<div class="$wrapperClass">`
1830 private function addWikiTextTitleInternal(
1831 $text, Title
$title, $linestart, $interface, $wrapperClass = null
1833 $parserOutput = $this->parseInternal(
1834 $text, $title, $linestart, true, $interface, /*language*/null
1837 $this->addParserOutput( $parserOutput, [
1838 'enableSectionEditLinks' => false,
1839 'wrapperDivClass' => $wrapperClass ??
'',
1844 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1845 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1849 * @param ParserOutput $parserOutput
1851 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1852 $this->mLanguageLinks
=
1853 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1854 $this->addCategoryLinks( $parserOutput->getCategories() );
1855 $this->setIndicators( $parserOutput->getIndicators() );
1856 $this->mNewSectionLink
= $parserOutput->getNewSection();
1857 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1859 if ( !$parserOutput->isCacheable() ) {
1860 $this->enableClientCache( false );
1862 $this->mNoGallery
= $parserOutput->getNoGallery();
1863 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1864 $this->addModules( $parserOutput->getModules() );
1865 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1866 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1867 $this->mPreventClickjacking
= $this->mPreventClickjacking
1868 ||
$parserOutput->preventClickjacking();
1870 // Template versioning...
1871 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1872 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1873 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1875 $this->mTemplateIds
[$ns] = $dbks;
1878 // File versioning...
1879 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1880 $this->mImageTimeKeys
[$dbk] = $data;
1883 // Hooks registered in the object
1884 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1885 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1886 list( $hookName, $data ) = $hookInfo;
1887 if ( isset( $parserOutputHooks[$hookName] ) ) {
1888 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1892 // Enable OOUI if requested via ParserOutput
1893 if ( $parserOutput->getEnableOOUI() ) {
1894 $this->enableOOUI();
1897 // Include parser limit report
1898 if ( !$this->limitReportJSData
) {
1899 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1902 // Link flags are ignored for now, but may in the future be
1903 // used to mark individual language links.
1905 // Avoid PHP 7.1 warning of passing $this by reference
1906 $outputPage = $this;
1907 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1908 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1910 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1911 // so that extensions may modify ParserOutput to toggle TOC.
1912 // This cannot be moved to addParserOutputText because that is not
1913 // called by EditPage for Preview.
1914 if ( $parserOutput->getTOCHTML() ) {
1915 $this->mEnableTOC
= true;
1920 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1921 * ParserOutput object, without any other metadata.
1924 * @param ParserOutput $parserOutput
1925 * @param array $poOptions Options to ParserOutput::getText()
1927 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
1928 $this->addParserOutputText( $parserOutput, $poOptions );
1930 $this->addModules( $parserOutput->getModules() );
1931 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1933 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1937 * Add the HTML associated with a ParserOutput object, without any metadata.
1940 * @param ParserOutput $parserOutput
1941 * @param array $poOptions Options to ParserOutput::getText()
1943 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
1944 $text = $parserOutput->getText( $poOptions );
1945 // Avoid PHP 7.1 warning of passing $this by reference
1946 $outputPage = $this;
1947 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1948 $this->addHTML( $text );
1952 * Add everything from a ParserOutput object.
1954 * @param ParserOutput $parserOutput
1955 * @param array $poOptions Options to ParserOutput::getText()
1957 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
1958 $this->addParserOutputMetadata( $parserOutput );
1959 $this->addParserOutputText( $parserOutput, $poOptions );
1963 * Add the output of a QuickTemplate to the output buffer
1965 * @param QuickTemplate &$template
1967 public function addTemplate( &$template ) {
1968 $this->addHTML( $template->getHTML() );
1972 * Parse wikitext and return the HTML.
1974 * @todo The output is wrapped in a <div> iff $interface is false; it's
1975 * probably best to always strip the wrapper.
1977 * @param string $text
1978 * @param bool $linestart Is this the start of a line?
1979 * @param bool $interface Use interface language (instead of content language) while parsing
1980 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1981 * LanguageConverter.
1982 * @param Language|null $language Target language object, will override $interface
1983 * @throws MWException
1984 * @return string HTML
1985 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
1986 * use parseAsContent() if $interface is default value or false, or else
1987 * parseAsInterface() if $interface is true.
1989 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1990 wfDeprecated( __METHOD__
, '1.33' );
1991 return $this->parseInternal(
1992 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
1994 'enableSectionEditLinks' => false,
1999 * Parse wikitext *in the page content language* and return the HTML.
2000 * The result will be language-converted to the user's preferred variant.
2001 * Output will be tidy.
2003 * @param string $text Wikitext in the page content language
2004 * @param bool $linestart Is this the start of a line? (Defaults to true)
2005 * @throws MWException
2006 * @return string HTML
2009 public function parseAsContent( $text, $linestart = true ) {
2010 return $this->parseInternal(
2011 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2013 'enableSectionEditLinks' => false,
2014 'wrapperDivClass' => ''
2019 * Parse wikitext *in the user interface language* and return the HTML.
2020 * The result will not be language-converted, as user interface messages
2021 * are already localized into a specific variant.
2022 * Output will be tidy.
2024 * @param string $text Wikitext in the user interface language
2025 * @param bool $linestart Is this the start of a line? (Defaults to true)
2026 * @throws MWException
2027 * @return string HTML
2030 public function parseAsInterface( $text, $linestart = true ) {
2031 return $this->parseInternal(
2032 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2034 'enableSectionEditLinks' => false,
2035 'wrapperDivClass' => ''
2040 * Parse wikitext *in the user interface language*, strip
2041 * paragraph wrapper, and return the HTML.
2042 * The result will not be language-converted, as user interface messages
2043 * are already localized into a specific variant.
2044 * Output will be tidy. Outer paragraph wrapper will only be stripped
2045 * if the result is a single paragraph.
2047 * @param string $text Wikitext in the user interface language
2048 * @param bool $linestart Is this the start of a line? (Defaults to true)
2049 * @throws MWException
2050 * @return string HTML
2053 public function parseInlineAsInterface( $text, $linestart = true ) {
2054 return Parser
::stripOuterParagraph(
2055 $this->parseAsInterface( $text, $linestart )
2060 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2062 * @param string $text
2063 * @param bool $linestart Is this the start of a line?
2064 * @param bool $interface Use interface language (instead of content language) while parsing
2065 * language sensitive magic words like GRAMMAR and PLURAL
2066 * @return string HTML
2067 * @deprecated since 1.32, due to untidy output and confusing default
2068 * for $interface. Use parseInlineAsInterface() if $interface is
2069 * the default value or false, or else use
2070 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2072 public function parseInline( $text, $linestart = true, $interface = false ) {
2073 wfDeprecated( __METHOD__
, '1.33' );
2074 $parsed = $this->parseInternal(
2075 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2077 'enableSectionEditLinks' => false,
2078 'wrapperDivClass' => '', /* no wrapper div */
2080 return Parser
::stripOuterParagraph( $parsed );
2084 * Parse wikitext and return the HTML (internal implementation helper)
2086 * @param string $text
2087 * @param Title $title The title to use
2088 * @param bool $linestart Is this the start of a line?
2089 * @param bool $tidy Whether the output should be tidied
2090 * @param bool $interface Use interface language (instead of content language) while parsing
2091 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2092 * LanguageConverter.
2093 * @param Language|null $language Target language object, will override $interface
2094 * @throws MWException
2095 * @return ParserOutput
2097 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2098 if ( is_null( $title ) ) {
2099 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2102 $popts = $this->parserOptions();
2103 $oldTidy = $popts->setTidy( $tidy );
2104 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2106 if ( $language !== null ) {
2107 $oldLang = $popts->setTargetLanguage( $language );
2110 $parserOutput = MediaWikiServices
::getInstance()->getParser()->getFreshParser()->parse(
2111 $text, $title, $popts,
2112 $linestart, true, $this->mRevisionId
2115 $popts->setTidy( $oldTidy );
2116 $popts->setInterfaceMessage( $oldInterface );
2118 if ( $language !== null ) {
2119 $popts->setTargetLanguage( $oldLang );
2122 return $parserOutput;
2126 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2128 * @param int $maxage Maximum cache time on the CDN, in seconds.
2130 public function setCdnMaxage( $maxage ) {
2131 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2135 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2136 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2137 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2140 * @param int $maxage Maximum cache time on the CDN, in seconds
2143 public function lowerCdnMaxage( $maxage ) {
2144 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2145 $this->setCdnMaxage( $this->mCdnMaxage
);
2149 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2151 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2152 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2153 * TTL is 90% of the age of the object, subject to the min and max.
2155 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2156 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2157 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2160 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2161 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2162 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'CdnMaxAge' );
2164 if ( $mtime === null ||
$mtime === false ) {
2165 return $minTTL; // entity does not exist
2168 $age = MWTimestamp
::time() - wfTimestamp( TS_UNIX
, $mtime );
2169 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2170 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2172 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2176 * Use enableClientCache(false) to force it to send nocache headers
2178 * @param bool|null $state New value, or null to not set the value
2180 * @return bool Old value
2182 public function enableClientCache( $state ) {
2183 return wfSetVar( $this->mEnableClientCache
, $state );
2187 * Get the list of cookie names that will influence the cache
2191 function getCacheVaryCookies() {
2192 if ( self
::$cacheVaryCookies === null ) {
2193 $config = $this->getConfig();
2194 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2195 SessionManager
::singleton()->getVaryCookies(),
2199 $config->get( 'CacheVaryCookies' )
2201 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2203 return self
::$cacheVaryCookies;
2207 * Check if the request has a cache-varying cookie header
2208 * If it does, it's very important that we don't allow public caching
2212 function haveCacheVaryCookies() {
2213 $request = $this->getRequest();
2214 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2215 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2216 wfDebug( __METHOD__
. ": found $cookieName\n" );
2220 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2225 * Add an HTTP header that will influence on the cache
2227 * @param string $header Header name
2228 * @param string[]|null $option Deprecated; formerly options for the
2229 * Key header, deprecated in 1.32 and removed in 1.34. See
2230 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2231 * for the list of formerly-valid options.
2233 public function addVaryHeader( $header, array $option = null ) {
2234 if ( $option !== null && count( $option ) > 0 ) {
2235 wfDeprecated( 'addVaryHeader $option is ignored', '1.34' );
2237 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2238 $this->mVaryHeader
[$header] = null;
2243 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2244 * such as Accept-Encoding or Cookie
2248 public function getVaryHeader() {
2249 // If we vary on cookies, let's make sure it's always included here too.
2250 if ( $this->getCacheVaryCookies() ) {
2251 $this->addVaryHeader( 'Cookie' );
2254 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2255 $this->addVaryHeader( $header, $options );
2257 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2261 * Add an HTTP Link: header
2263 * @param string $header Header value
2265 public function addLinkHeader( $header ) {
2266 $this->mLinkHeader
[] = $header;
2270 * Return a Link: header. Based on the values of $mLinkHeader.
2274 public function getLinkHeader() {
2275 if ( !$this->mLinkHeader
) {
2279 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2283 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2286 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2287 * /w/index.php?title=Main_page&variant=zh-cn will not.
2289 private function addAcceptLanguage() {
2290 $title = $this->getTitle();
2291 if ( !$title instanceof Title
) {
2295 $lang = $title->getPageLanguage();
2296 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2297 $this->addVaryHeader( 'Accept-Language' );
2302 * Set a flag which will cause an X-Frame-Options header appropriate for
2303 * edit pages to be sent. The header value is controlled by
2304 * $wgEditPageFrameOptions.
2306 * This is the default for special pages. If you display a CSRF-protected
2307 * form on an ordinary view page, then you need to call this function.
2309 * @param bool $enable
2311 public function preventClickjacking( $enable = true ) {
2312 $this->mPreventClickjacking
= $enable;
2316 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2317 * This can be called from pages which do not contain any CSRF-protected
2320 public function allowClickjacking() {
2321 $this->mPreventClickjacking
= false;
2325 * Get the prevent-clickjacking flag
2330 public function getPreventClickjacking() {
2331 return $this->mPreventClickjacking
;
2335 * Get the X-Frame-Options header value (without the name part), or false
2336 * if there isn't one. This is used by Skin to determine whether to enable
2337 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2339 * @return string|false
2341 public function getFrameOptions() {
2342 $config = $this->getConfig();
2343 if ( $config->get( 'BreakFrames' ) ) {
2345 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2346 return $config->get( 'EditPageFrameOptions' );
2352 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2353 * Trials: https://github.com/GoogleChrome/OriginTrials
2357 private function getOriginTrials() {
2358 $config = $this->getConfig();
2360 return $config->get( 'OriginTrials' );
2363 private function getReportTo() {
2364 $config = $this->getConfig();
2366 $expiry = $config->get( 'ReportToExpiry' );
2372 $endpoints = $config->get( 'ReportToEndpoints' );
2374 if ( !$endpoints ) {
2378 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2380 foreach ( $endpoints as $endpoint ) {
2381 $output['endpoints'][] = [ 'url' => $endpoint ];
2384 return json_encode( $output, JSON_UNESCAPED_SLASHES
);
2387 private function getFeaturePolicyReportOnly() {
2388 $config = $this->getConfig();
2390 $features = $config->get( 'FeaturePolicyReportOnly' );
2391 return implode( ';', $features );
2395 * Send cache control HTTP headers
2397 public function sendCacheControl() {
2398 $response = $this->getRequest()->response();
2399 $config = $this->getConfig();
2401 $this->addVaryHeader( 'Cookie' );
2402 $this->addAcceptLanguage();
2404 # don't serve compressed data to clients who can't handle it
2405 # maintain different caches for logged-in users and non-logged in ones
2406 $response->header( $this->getVaryHeader() );
2408 if ( $this->mEnableClientCache
) {
2410 $config->get( 'UseCdn' ) &&
2411 !$response->hasCookies() &&
2412 !SessionManager
::getGlobalSession()->isPersistent() &&
2413 !$this->isPrintable() &&
2414 $this->mCdnMaxage
!= 0 &&
2415 !$this->haveCacheVaryCookies()
2417 # We'll purge the proxy cache for anons explicitly, but require end user agents
2418 # to revalidate against the proxy on each visit.
2419 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2420 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2421 wfDebug( __METHOD__
.
2422 ": local proxy caching; {$this->mLastModified} **", 'private' );
2423 # start with a shorter timeout for initial testing
2424 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2425 $response->header( "Cache-Control: " .
2426 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2428 # We do want clients to cache if they can, but they *must* check for updates
2429 # on revisiting the page.
2430 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2431 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2432 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2434 if ( $this->mLastModified
) {
2435 $response->header( "Last-Modified: {$this->mLastModified}" );
2438 wfDebug( __METHOD__
. ": no caching **", 'private' );
2440 # In general, the absence of a last modified header should be enough to prevent
2441 # the client from using its cache. We send a few other things just to make sure.
2442 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2443 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2444 $response->header( 'Pragma: no-cache' );
2449 * Transfer styles and JavaScript modules from skin.
2451 * @param Skin $sk to load modules for
2453 public function loadSkinModules( $sk ) {
2454 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2455 if ( $group === 'styles' ) {
2456 foreach ( $modules as $key => $moduleMembers ) {
2457 $this->addModuleStyles( $moduleMembers );
2460 $this->addModules( $modules );
2466 * Finally, all the text has been munged and accumulated into
2467 * the object, let's actually output it:
2469 * @param bool $return Set to true to get the result as a string rather than sending it
2470 * @return string|null
2472 * @throws FatalError
2473 * @throws MWException
2475 public function output( $return = false ) {
2476 if ( $this->mDoNothing
) {
2477 return $return ?
'' : null;
2480 $response = $this->getRequest()->response();
2481 $config = $this->getConfig();
2483 if ( $this->mRedirect
!= '' ) {
2484 # Standards require redirect URLs to be absolute
2485 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2487 $redirect = $this->mRedirect
;
2488 $code = $this->mRedirectCode
;
2490 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2491 if ( $code == '301' ||
$code == '303' ) {
2492 if ( !$config->get( 'DebugRedirects' ) ) {
2493 $response->statusHeader( $code );
2495 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2497 if ( $config->get( 'VaryOnXFP' ) ) {
2498 $this->addVaryHeader( 'X-Forwarded-Proto' );
2500 $this->sendCacheControl();
2502 $response->header( "Content-Type: text/html; charset=utf-8" );
2503 if ( $config->get( 'DebugRedirects' ) ) {
2504 $url = htmlspecialchars( $redirect );
2505 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2506 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2507 print "</body>\n</html>\n";
2509 $response->header( 'Location: ' . $redirect );
2513 return $return ?
'' : null;
2514 } elseif ( $this->mStatusCode
) {
2515 $response->statusHeader( $this->mStatusCode
);
2518 # Buffer output; final headers may depend on later processing
2521 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2522 $response->header( 'Content-language: ' .
2523 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2525 $linkHeader = $this->getLinkHeader();
2526 if ( $linkHeader ) {
2527 $response->header( $linkHeader );
2530 // Prevent framing, if requested
2531 $frameOptions = $this->getFrameOptions();
2532 if ( $frameOptions ) {
2533 $response->header( "X-Frame-Options: $frameOptions" );
2536 $originTrials = $this->getOriginTrials();
2537 foreach ( $originTrials as $originTrial ) {
2538 $response->header( "Origin-Trial: $originTrial", false );
2541 $reportTo = $this->getReportTo();
2543 $response->header( "Report-To: $reportTo" );
2546 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2547 if ( $featurePolicyReportOnly ) {
2548 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2551 ContentSecurityPolicy
::sendHeaders( $this );
2553 if ( $this->mArticleBodyOnly
) {
2554 echo $this->mBodytext
;
2556 // Enable safe mode if requested (T152169)
2557 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2558 $this->disallowUserJs();
2561 $sk = $this->getSkin();
2562 $this->loadSkinModules( $sk );
2564 MWDebug
::addModules( $this );
2566 // Avoid PHP 7.1 warning of passing $this by reference
2567 $outputPage = $this;
2568 // Hook that allows last minute changes to the output page, e.g.
2569 // adding of CSS or Javascript by extensions.
2570 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2574 } catch ( Exception
$e ) {
2575 ob_end_clean(); // bug T129657
2581 // This hook allows last minute changes to final overall output by modifying output buffer
2582 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2583 } catch ( Exception
$e ) {
2584 ob_end_clean(); // bug T129657
2588 $this->sendCacheControl();
2591 return ob_get_clean();
2599 * Prepare this object to display an error page; disable caching and
2600 * indexing, clear the current text and redirect, set the page's title
2601 * and optionally an custom HTML title (content of the "<title>" tag).
2603 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2604 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2605 * optional, if not passed the "<title>" attribute will be
2606 * based on $pageTitle
2608 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2609 $this->setPageTitle( $pageTitle );
2610 if ( $htmlTitle !== false ) {
2611 $this->setHTMLTitle( $htmlTitle );
2613 $this->setRobotPolicy( 'noindex,nofollow' );
2614 $this->setArticleRelated( false );
2615 $this->enableClientCache( false );
2616 $this->mRedirect
= '';
2617 $this->clearSubtitle();
2622 * Output a standard error page
2624 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2625 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2626 * showErrorPage( 'titlemsg', $messageObject );
2627 * showErrorPage( $titleMessageObject, $messageObject );
2629 * @param string|Message $title Message key (string) for page title, or a Message object
2630 * @param string|Message $msg Message key (string) for page text, or a Message object
2631 * @param array $params Message parameters; ignored if $msg is a Message object
2633 public function showErrorPage( $title, $msg, $params = [] ) {
2634 if ( !$title instanceof Message
) {
2635 $title = $this->msg( $title );
2638 $this->prepareErrorPage( $title );
2640 if ( $msg instanceof Message
) {
2641 if ( $params !== [] ) {
2642 trigger_error( 'Argument ignored: $params. The message parameters argument '
2643 . 'is discarded when the $msg argument is a Message object instead of '
2644 . 'a string.', E_USER_NOTICE
);
2646 $this->addHTML( $msg->parseAsBlock() );
2648 $this->addWikiMsgArray( $msg, $params );
2651 $this->returnToMain();
2655 * Output a standard permission error page
2657 * @param array $errors Error message keys or [key, param...] arrays
2658 * @param string|null $action Action that was denied or null if unknown
2660 public function showPermissionsErrorPage( array $errors, $action = null ) {
2661 $services = MediaWikiServices
::getInstance();
2662 $permissionManager = $services->getPermissionManager();
2663 foreach ( $errors as $key => $error ) {
2664 $errors[$key] = (array)$error;
2667 // For some action (read, edit, create and upload), display a "login to do this action"
2668 // error if all of the following conditions are met:
2669 // 1. the user is not logged in
2670 // 2. the only error is insufficient permissions (i.e. no block or something else)
2671 // 3. the error can be avoided simply by logging in
2673 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2674 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2675 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2676 && ( $permissionManager->groupHasPermission( 'user', $action )
2677 ||
$permissionManager->groupHasPermission( 'autoconfirmed', $action ) )
2679 $displayReturnto = null;
2681 # Due to T34276, if a user does not have read permissions,
2682 # $this->getTitle() will just give Special:Badtitle, which is
2683 # not especially useful as a returnto parameter. Use the title
2684 # from the request instead, if there was one.
2685 $request = $this->getRequest();
2686 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2687 if ( $action == 'edit' ) {
2688 $msg = 'whitelistedittext';
2689 $displayReturnto = $returnto;
2690 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2691 $msg = 'nocreatetext';
2692 } elseif ( $action == 'upload' ) {
2693 $msg = 'uploadnologintext';
2695 $msg = 'loginreqpagetext';
2696 $displayReturnto = Title
::newMainPage();
2702 $query['returnto'] = $returnto->getPrefixedText();
2704 if ( !$request->wasPosted() ) {
2705 $returntoquery = $request->getValues();
2706 unset( $returntoquery['title'] );
2707 unset( $returntoquery['returnto'] );
2708 unset( $returntoquery['returntoquery'] );
2709 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2713 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2714 $linkRenderer = $services->getLinkRenderer();
2715 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2716 $loginLink = $linkRenderer->makeKnownLink(
2718 $this->msg( 'loginreqlink' )->text(),
2723 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2724 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2726 # Don't return to a page the user can't read otherwise
2727 # we'll end up in a pointless loop
2728 if ( $displayReturnto && $permissionManager->userCan(
2729 'read', $this->getUser(), $displayReturnto
2731 $this->returnToMain( null, $displayReturnto );
2734 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2735 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2740 * Display an error page indicating that a given version of MediaWiki is
2741 * required to use it
2743 * @param mixed $version The version of MediaWiki needed to use the page
2745 public function versionRequired( $version ) {
2746 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2748 $this->addWikiMsg( 'versionrequiredtext', $version );
2749 $this->returnToMain();
2753 * Format a list of error messages
2755 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2756 * @param string|null $action Action that was denied or null if unknown
2757 * @return string The wikitext error-messages, formatted into a list.
2759 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2760 if ( $action == null ) {
2761 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2763 $action_desc = $this->msg( "action-$action" )->plain();
2765 'permissionserrorstext-withaction',
2768 )->plain() . "\n\n";
2771 if ( count( $errors ) > 1 ) {
2772 $text .= '<ul class="permissions-errors">' . "\n";
2774 foreach ( $errors as $error ) {
2776 $text .= $this->msg( ...$error )->plain();
2781 $text .= "<div class=\"permissions-errors\">\n" .
2782 $this->msg( ...reset( $errors ) )->plain() .
2790 * Show a warning about replica DB lag
2792 * If the lag is higher than $wgSlaveLagCritical seconds,
2793 * then the warning is a bit more obvious. If the lag is
2794 * lower than $wgSlaveLagWarning, then no warning is shown.
2796 * @param int $lag Replica lag
2798 public function showLagWarning( $lag ) {
2799 $config = $this->getConfig();
2800 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2801 $lag = floor( $lag ); // floor to avoid nano seconds to display
2802 $message = $lag < $config->get( 'SlaveLagCritical' )
2805 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2806 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2811 * Output an error page
2813 * @note FatalError exception class provides an alternative.
2814 * @param string $message Error to output. Must be escaped for HTML.
2816 public function showFatalError( $message ) {
2817 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2819 $this->addHTML( $message );
2823 * Add a "return to" link pointing to a specified title
2825 * @param Title $title Title to link
2826 * @param array $query Query string parameters
2827 * @param string|null $text Text of the link (input is not escaped)
2828 * @param array $options Options array to pass to Linker
2830 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2831 $linkRenderer = MediaWikiServices
::getInstance()
2832 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2833 $link = $this->msg( 'returnto' )->rawParams(
2834 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2835 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2839 * Add a "return to" link pointing to a specified title,
2840 * or the title indicated in the request, or else the main page
2842 * @param mixed|null $unused
2843 * @param Title|string|null $returnto Title or String to return to
2844 * @param string|null $returntoquery Query string for the return to link
2846 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2847 if ( $returnto == null ) {
2848 $returnto = $this->getRequest()->getText( 'returnto' );
2851 if ( $returntoquery == null ) {
2852 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2855 if ( $returnto === '' ) {
2856 $returnto = Title
::newMainPage();
2859 if ( is_object( $returnto ) ) {
2860 $titleObj = $returnto;
2862 $titleObj = Title
::newFromText( $returnto );
2864 // We don't want people to return to external interwiki. That
2865 // might potentially be used as part of a phishing scheme
2866 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2867 $titleObj = Title
::newMainPage();
2870 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2873 private function getRlClientContext() {
2874 if ( !$this->rlClientContext
) {
2875 $query = ResourceLoader
::makeLoaderQuery(
2876 [], // modules; not relevant
2877 $this->getLanguage()->getCode(),
2878 $this->getSkin()->getSkinName(),
2879 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2880 null, // version; not relevant
2881 ResourceLoader
::inDebugMode(),
2882 null, // only; not relevant
2883 $this->isPrintable(),
2884 $this->getRequest()->getBool( 'handheld' )
2886 $this->rlClientContext
= new ResourceLoaderContext(
2887 $this->getResourceLoader(),
2888 new FauxRequest( $query )
2890 if ( $this->contentOverrideCallbacks
) {
2891 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2892 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2893 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2894 $content = $callback( $title );
2895 if ( $content !== null ) {
2896 $text = ContentHandler
::getContentText( $content );
2897 if ( strpos( $text, '</script>' ) !== false ) {
2898 // Proactively replace this so that we can display a message
2899 // to the user, instead of letting it go to Html::inlineScript(),
2900 // where it would be considered a server-side issue.
2901 $titleFormatted = $title->getPrefixedText();
2902 $content = new JavaScriptContent(
2903 Xml
::encodeJsCall( 'mw.log.error', [
2904 "Cannot preview $titleFormatted due to script-closing tag."
2915 return $this->rlClientContext
;
2919 * Call this to freeze the module queue and JS config and create a formatter.
2921 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2922 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2923 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2924 * the module filters retroactively. Skins and extension hooks may also add modules until very
2925 * late in the request lifecycle.
2927 * @return ResourceLoaderClientHtml
2929 public function getRlClient() {
2930 if ( !$this->rlClient
) {
2931 $context = $this->getRlClientContext();
2932 $rl = $this->getResourceLoader();
2933 $this->addModules( [
2938 $this->addModuleStyles( [
2943 $this->getSkin()->setupSkinUserCss( $this );
2945 // Prepare exempt modules for buildExemptModules()
2946 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2948 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2950 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2951 // Separate user-specific batch for improved cache-hit ratio.
2952 $userBatch = [ 'user.styles', 'user' ];
2953 $siteBatch = array_diff( $moduleStyles, $userBatch );
2954 $dbr = wfGetDB( DB_REPLICA
);
2955 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2956 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2958 // Filter out modules handled by buildExemptModules()
2959 $moduleStyles = array_filter( $moduleStyles,
2960 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2961 $module = $rl->getModule( $name );
2963 $group = $module->getGroup();
2964 if ( isset( $exemptGroups[$group] ) ) {
2965 $exemptStates[$name] = 'ready';
2966 if ( !$module->isKnownEmpty( $context ) ) {
2967 // E.g. Don't output empty <styles>
2968 $exemptGroups[$group][] = $name;
2976 $this->rlExemptStyleModules
= $exemptGroups;
2978 $rlClient = new ResourceLoaderClientHtml( $context, [
2979 'target' => $this->getTarget(),
2980 'nonce' => $this->getCSPNonce(),
2981 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2982 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2983 // modules enqueud for loading on this page is filtered to just those.
2984 // However, to make sure we also apply the restriction to dynamic dependencies and
2985 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2986 // StartupModule so that the client-side registry will not contain any restricted
2987 // modules either. (T152169, T185303)
2988 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2989 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2992 $rlClient->setConfig( $this->getJSVars() );
2993 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2994 $rlClient->setModuleStyles( $moduleStyles );
2995 $rlClient->setExemptStates( $exemptStates );
2996 $this->rlClient
= $rlClient;
2998 return $this->rlClient
;
3002 * @param Skin $sk The given Skin
3003 * @param bool $includeStyle Unused
3004 * @return string The doctype, opening "<html>", and head element.
3006 public function headElement( Skin
$sk, $includeStyle = true ) {
3007 $config = $this->getConfig();
3008 $userdir = $this->getLanguage()->getDir();
3009 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3012 $htmlAttribs = Sanitizer
::mergeAttributes(
3013 $this->getRlClient()->getDocumentAttributes(),
3014 $sk->getHtmlElementAttributes()
3016 $pieces[] = Html
::htmlHeader( $htmlAttribs );
3017 $pieces[] = Html
::openElement( 'head' );
3019 if ( $this->getHTMLTitle() == '' ) {
3020 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3023 if ( !Html
::isXmlMimeType( $config->get( 'MimeType' ) ) ) {
3024 // Add <meta charset="UTF-8">
3025 // This should be before <title> since it defines the charset used by
3026 // text including the text inside <title>.
3027 // The spec recommends defining XHTML5's charset using the XML declaration
3029 // Our XML declaration is output by Html::htmlHeader.
3030 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3031 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3032 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3035 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3036 $pieces[] = $this->getRlClient()->getHeadHtml( $htmlAttribs['class'] ??
null );
3037 $pieces[] = $this->buildExemptModules();
3038 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3039 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3041 // This library is intended to run on older browsers that MediaWiki no longer
3042 // supports as Grade A. For these Grade C browsers, we provide an experience
3043 // using only HTML and CSS. But, where standards-compliant browsers are able to
3044 // style unknown HTML elements without issue, old IE ignores these styles.
3045 // The html5shiv library fixes that.
3046 // Use an IE conditional comment to serve the script only to old IE
3047 $shivUrl = $config->get( 'ResourceBasePath' ) . '/resources/lib/html5shiv/html5shiv.js';
3048 $pieces[] = '<!--[if lt IE 9]>' .
3049 Html
::linkedScript( $shivUrl, $this->getCSPNonce() ) .
3052 $pieces[] = Html
::closeElement( 'head' );
3054 $bodyClasses = $this->mAdditionalBodyClasses
;
3055 $bodyClasses[] = 'mediawiki';
3057 # Classes for LTR/RTL directionality support
3058 $bodyClasses[] = $userdir;
3059 $bodyClasses[] = "sitedir-$sitedir";
3061 $underline = $this->getUser()->getOption( 'underline' );
3062 if ( $underline < 2 ) {
3063 // The following classes can be used here:
3064 // * mw-underline-always
3065 // * mw-underline-never
3066 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
3069 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3070 # A <body> class is probably not the best way to do this . . .
3071 $bodyClasses[] = 'capitalize-all-nouns';
3074 // Parser feature migration class
3075 // The idea is that this will eventually be removed, after the wikitext
3076 // which requires it is cleaned up.
3077 $bodyClasses[] = 'mw-hide-empty-elt';
3079 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3080 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3082 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3085 // While the implode() is not strictly needed, it's used for backwards compatibility
3086 // (this used to be built as a string and hooks likely still expect that).
3087 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3089 // Allow skins and extensions to add body attributes they need
3090 $sk->addToBodyAttributes( $this, $bodyAttrs );
3091 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3093 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3095 return self
::combineWrappedStrings( $pieces );
3099 * Get a ResourceLoader object associated with this OutputPage
3101 * @return ResourceLoader
3103 public function getResourceLoader() {
3104 if ( is_null( $this->mResourceLoader
) ) {
3105 // Lazy-initialise as needed
3106 $this->mResourceLoader
= MediaWikiServices
::getInstance()->getResourceLoader();
3108 return $this->mResourceLoader
;
3112 * Explicily load or embed modules on a page.
3114 * @param array|string $modules One or more module names
3115 * @param string $only ResourceLoaderModule TYPE_ class constant
3116 * @param array $extraQuery [optional] Array with extra query parameters for the request
3117 * @return string|WrappedStringList HTML
3119 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3120 // Apply 'target' and 'origin' filters
3121 $modules = $this->filterModules( (array)$modules, null, $only );
3123 return ResourceLoaderClientHtml
::makeLoad(
3124 $this->getRlClientContext(),
3128 $this->getCSPNonce()
3133 * Combine WrappedString chunks and filter out empty ones
3135 * @param array $chunks
3136 * @return string|WrappedStringList HTML
3138 protected static function combineWrappedStrings( array $chunks ) {
3139 // Filter out empty values
3140 $chunks = array_filter( $chunks, 'strlen' );
3141 return WrappedString
::join( "\n", $chunks );
3145 * JS stuff to put at the bottom of the `<body>`.
3146 * These are legacy scripts ($this->mScripts), and user JS.
3148 * @return string|WrappedStringList HTML
3150 public function getBottomScripts() {
3152 $chunks[] = $this->getRlClient()->getBodyHtml();
3154 // Legacy non-ResourceLoader scripts
3155 $chunks[] = $this->mScripts
;
3157 if ( $this->limitReportJSData
) {
3158 $chunks[] = ResourceLoader
::makeInlineScript(
3159 ResourceLoader
::makeConfigSetScript(
3160 [ 'wgPageParseReport' => $this->limitReportJSData
]
3162 $this->getCSPNonce()
3166 return self
::combineWrappedStrings( $chunks );
3170 * Get the javascript config vars to include on this page
3172 * @return array Array of javascript config vars
3175 public function getJsConfigVars() {
3176 return $this->mJsConfigVars
;
3180 * Add one or more variables to be set in mw.config in JavaScript
3182 * @param string|array $keys Key or array of key/value pairs
3183 * @param mixed|null $value [optional] Value of the configuration variable
3185 public function addJsConfigVars( $keys, $value = null ) {
3186 if ( is_array( $keys ) ) {
3187 foreach ( $keys as $key => $value ) {
3188 $this->mJsConfigVars
[$key] = $value;
3193 $this->mJsConfigVars
[$keys] = $value;
3197 * Get an array containing the variables to be set in mw.config in JavaScript.
3199 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3200 * - in other words, page-independent/site-wide variables (without state).
3201 * You will only be adding bloat to the html page and causing page caches to
3202 * have to be purged on configuration changes.
3205 public function getJSVars() {
3208 $canonicalSpecialPageName = false; # T23115
3209 $services = MediaWikiServices
::getInstance();
3211 $title = $this->getTitle();
3212 $ns = $title->getNamespace();
3213 $nsInfo = $services->getNamespaceInfo();
3214 $canonicalNamespace = $nsInfo->exists( $ns )
3215 ?
$nsInfo->getCanonicalName( $ns )
3216 : $title->getNsText();
3218 $sk = $this->getSkin();
3219 // Get the relevant title so that AJAX features can use the correct page name
3220 // when making API requests from certain special pages (T36972).
3221 $relevantTitle = $sk->getRelevantTitle();
3222 $relevantUser = $sk->getRelevantUser();
3224 if ( $ns == NS_SPECIAL
) {
3225 list( $canonicalSpecialPageName, /*...*/ ) =
3226 $services->getSpecialPageFactory()->
3227 resolveAlias( $title->getDBkey() );
3228 } elseif ( $this->canUseWikiPage() ) {
3229 $wikiPage = $this->getWikiPage();
3230 $curRevisionId = $wikiPage->getLatest();
3231 $articleId = $wikiPage->getId();
3234 $lang = $title->getPageViewLanguage();
3236 // Pre-process information
3237 $separatorTransTable = $lang->separatorTransformTable();
3238 $separatorTransTable = $separatorTransTable ?
: [];
3239 $compactSeparatorTransTable = [
3240 implode( "\t", array_keys( $separatorTransTable ) ),
3241 implode( "\t", $separatorTransTable ),
3243 $digitTransTable = $lang->digitTransformTable();
3244 $digitTransTable = $digitTransTable ?
: [];
3245 $compactDigitTransTable = [
3246 implode( "\t", array_keys( $digitTransTable ) ),
3247 implode( "\t", $digitTransTable ),
3250 $user = $this->getUser();
3253 'wgCanonicalNamespace' => $canonicalNamespace,
3254 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3255 'wgNamespaceNumber' => $title->getNamespace(),
3256 'wgPageName' => $title->getPrefixedDBkey(),
3257 'wgTitle' => $title->getText(),
3258 'wgCurRevisionId' => $curRevisionId,
3259 'wgRevisionId' => (int)$this->getRevisionId(),
3260 'wgArticleId' => $articleId,
3261 'wgIsArticle' => $this->isArticle(),
3262 'wgIsRedirect' => $title->isRedirect(),
3263 'wgAction' => Action
::getActionName( $this->getContext() ),
3264 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3265 'wgUserGroups' => $user->getEffectiveGroups(),
3266 'wgCategories' => $this->getCategories(),
3267 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3268 'wgPageContentLanguage' => $lang->getCode(),
3269 'wgPageContentModel' => $title->getContentModel(),
3270 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3271 'wgDigitTransformTable' => $compactDigitTransTable,
3272 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3273 'wgMonthNames' => $lang->getMonthNamesArray(),
3274 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3275 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3276 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3277 'wgRequestId' => WebRequest
::getRequestId(),
3278 'wgCSPNonce' => $this->getCSPNonce(),
3281 if ( $user->isLoggedIn() ) {
3282 $vars['wgUserId'] = $user->getId();
3283 $vars['wgUserEditCount'] = $user->getEditCount();
3284 $userReg = $user->getRegistration();
3285 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3286 // Get the revision ID of the oldest new message on the user's talk
3287 // page. This can be used for constructing new message alerts on
3289 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3292 $contLang = $services->getContentLanguage();
3293 if ( $contLang->hasVariants() ) {
3294 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3296 // Same test as SkinTemplate
3297 $vars['wgIsProbablyEditable'] = $this->userCanEditOrCreate( $user, $title );
3299 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3300 $this->userCanEditOrCreate( $user, $relevantTitle );
3302 foreach ( $title->getRestrictionTypes() as $type ) {
3303 // Following keys are set in $vars:
3304 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3305 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3308 if ( $title->isMainPage() ) {
3309 $vars['wgIsMainPage'] = true;
3312 if ( $this->mRedirectedFrom
) {
3313 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3316 if ( $relevantUser ) {
3317 $vars['wgRelevantUserName'] = $relevantUser->getName();
3320 // Allow extensions to add their custom variables to the mw.config map.
3321 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3322 // page-dependant but site-wide (without state).
3323 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3324 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3326 // Merge in variables from addJsConfigVars last
3327 return array_merge( $vars, $this->getJsConfigVars() );
3331 * To make it harder for someone to slip a user a fake
3332 * JavaScript or CSS preview, a random token
3333 * is associated with the login session. If it's not
3334 * passed back with the preview request, we won't render
3339 public function userCanPreview() {
3340 $request = $this->getRequest();
3342 $request->getVal( 'action' ) !== 'submit' ||
3343 !$request->wasPosted()
3348 $user = $this->getUser();
3350 if ( !$user->isLoggedIn() ) {
3351 // Anons have predictable edit tokens
3354 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3358 $title = $this->getTitle();
3359 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3360 if ( count( $errors ) !== 0 ) {
3369 * @param LinkTarget $title
3372 private function userCanEditOrCreate(
3376 $pm = MediaWikiServices
::getInstance()->getPermissionManager();
3377 return $pm->quickUserCan( 'edit', $user, $title )
3378 && ( $this->getTitle()->exists() ||
3379 $pm->quickUserCan( 'create', $user, $title ) );
3383 * @return array Array in format "link name or number => 'link html'".
3385 public function getHeadLinksArray() {
3389 $config = $this->getConfig();
3391 $canonicalUrl = $this->mCanonicalUrl
;
3393 $tags['meta-generator'] = Html
::element( 'meta', [
3394 'name' => 'generator',
3395 'content' => "MediaWiki $wgVersion",
3398 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3399 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3400 // fallbacks should come before the primary value so we need to reverse the array.
3401 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3402 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3403 'name' => 'referrer',
3404 'content' => $policy,
3409 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3410 if ( $p !== 'index,follow' ) {
3411 // http://www.robotstxt.org/wc/meta-user.html
3412 // Only show if it's different from the default robots policy
3413 $tags['meta-robots'] = Html
::element( 'meta', [
3419 foreach ( $this->mMetatags
as $tag ) {
3420 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3422 $tag[0] = substr( $tag[0], 5 );
3423 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3428 $tagName = "meta-{$tag[0]}";
3429 if ( isset( $tags[$tagName] ) ) {
3430 $tagName .= $tag[1];
3432 $tags[$tagName] = Html
::element( 'meta',
3435 'content' => $tag[1]
3440 foreach ( $this->mLinktags
as $tag ) {
3441 $tags[] = Html
::element( 'link', $tag );
3444 # Universal edit button
3445 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3446 if ( $this->userCanEditOrCreate( $this->getUser(), $this->getTitle() ) ) {
3447 // Original UniversalEditButton
3448 $msg = $this->msg( 'edit' )->text();
3449 $tags['universal-edit-button'] = Html
::element( 'link', [
3450 'rel' => 'alternate',
3451 'type' => 'application/x-wiki',
3453 'href' => $this->getTitle()->getEditURL(),
3455 // Alternate edit link
3456 $tags['alternative-edit'] = Html
::element( 'link', [
3459 'href' => $this->getTitle()->getEditURL(),
3464 # Generally the order of the favicon and apple-touch-icon links
3465 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3466 # uses whichever one appears later in the HTML source. Make sure
3467 # apple-touch-icon is specified first to avoid this.
3468 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3469 $tags['apple-touch-icon'] = Html
::element( 'link', [
3470 'rel' => 'apple-touch-icon',
3471 'href' => $config->get( 'AppleTouchIcon' )
3475 if ( $config->get( 'Favicon' ) !== false ) {
3476 $tags['favicon'] = Html
::element( 'link', [
3477 'rel' => 'shortcut icon',
3478 'href' => $config->get( 'Favicon' )
3482 # OpenSearch description link
3483 $tags['opensearch'] = Html
::element( 'link', [
3485 'type' => 'application/opensearchdescription+xml',
3486 'href' => wfScript( 'opensearch_desc' ),
3487 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3490 # Real Simple Discovery link, provides auto-discovery information
3491 # for the MediaWiki API (and potentially additional custom API
3492 # support such as WordPress or Twitter-compatible APIs for a
3493 # blogging extension, etc)
3494 $tags['rsd'] = Html
::element( 'link', [
3496 'type' => 'application/rsd+xml',
3497 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3498 // Whether RSD accepts relative or protocol-relative URLs is completely
3499 // undocumented, though.
3500 'href' => wfExpandUrl( wfAppendQuery(
3502 [ 'action' => 'rsd' ] ),
3508 if ( !$config->get( 'DisableLangConversion' ) ) {
3509 $lang = $this->getTitle()->getPageLanguage();
3510 if ( $lang->hasVariants() ) {
3511 $variants = $lang->getVariants();
3512 foreach ( $variants as $variant ) {
3513 $tags["variant-$variant"] = Html
::element( 'link', [
3514 'rel' => 'alternate',
3515 'hreflang' => LanguageCode
::bcp47( $variant ),
3516 'href' => $this->getTitle()->getLocalURL(
3517 [ 'variant' => $variant ] )
3521 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3522 $tags["variant-x-default"] = Html
::element( 'link', [
3523 'rel' => 'alternate',
3524 'hreflang' => 'x-default',
3525 'href' => $this->getTitle()->getLocalURL() ] );
3530 if ( $this->copyrightUrl
!== null ) {
3531 $copyright = $this->copyrightUrl
;
3534 if ( $config->get( 'RightsPage' ) ) {
3535 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3538 $copyright = $copy->getLocalURL();
3542 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3543 $copyright = $config->get( 'RightsUrl' );
3548 $tags['copyright'] = Html
::element( 'link', [
3550 'href' => $copyright ]
3555 if ( $config->get( 'Feed' ) ) {
3558 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3559 # Use the page name for the title. In principle, this could
3560 # lead to issues with having the same name for different feeds
3561 # corresponding to the same page, but we can't avoid that at
3564 $feedLinks[] = $this->feedLink(
3567 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3569 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3574 # Recent changes feed should appear on every page (except recentchanges,
3575 # that would be redundant). Put it after the per-page feed to avoid
3576 # changing existing behavior. It's still available, probably via a
3577 # menu in your browser. Some sites might have a different feed they'd
3578 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3579 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3580 # If so, use it instead.
3581 $sitename = $config->get( 'Sitename' );
3582 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3583 if ( $overrideSiteFeed ) {
3584 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3585 // Note, this->feedLink escapes the url.
3586 $feedLinks[] = $this->feedLink(
3589 $this->msg( "site-{$type}-feed", $sitename )->text()
3592 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3593 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3594 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3595 $feedLinks[] = $this->feedLink(
3597 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3598 # For grep: 'site-rss-feed', 'site-atom-feed'
3599 $this->msg( "site-{$format}-feed", $sitename )->text()
3604 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3605 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3606 # use OutputPage::addFeedLink() instead.
3607 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3609 $tags +
= $feedLinks;
3613 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3614 if ( $canonicalUrl !== false ) {
3615 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3616 } elseif ( $this->isArticleRelated() ) {
3617 // This affects all requests where "setArticleRelated" is true. This is
3618 // typically all requests that show content (query title, curid, oldid, diff),
3619 // and all wikipage actions (edit, delete, purge, info, history etc.).
3620 // It does not apply to File pages and Special pages.
3621 // 'history' and 'info' actions address page metadata rather than the page
3622 // content itself, so they may not be canonicalized to the view page url.
3623 // TODO: this ought to be better encapsulated in the Action class.
3624 $action = Action
::getActionName( $this->getContext() );
3625 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3626 $query = "action={$action}";
3630 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3632 $reqUrl = $this->getRequest()->getRequestURL();
3633 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3636 if ( $canonicalUrl !== false ) {
3637 $tags[] = Html
::element( 'link', [
3638 'rel' => 'canonical',
3639 'href' => $canonicalUrl
3643 // Allow extensions to add, remove and/or otherwise manipulate these links
3644 // If you want only to *add* <head> links, please use the addHeadItem()
3645 // (or addHeadItems() for multiple items) method instead.
3646 // This hook is provided as a last resort for extensions to modify these
3647 // links before the output is sent to client.
3648 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3654 * Generate a "<link rel/>" for a feed.
3656 * @param string $type Feed type
3657 * @param string $url URL to the feed
3658 * @param string $text Value of the "title" attribute
3659 * @return string HTML fragment
3661 private function feedLink( $type, $url, $text ) {
3662 return Html
::element( 'link', [
3663 'rel' => 'alternate',
3664 'type' => "application/$type+xml",
3671 * Add a local or specified stylesheet, with the given media options.
3672 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3674 * @param string $style URL to the file
3675 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3676 * @param string $condition For IE conditional comments, specifying an IE version
3677 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3679 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3682 $options['media'] = $media;
3685 $options['condition'] = $condition;
3688 $options['dir'] = $dir;
3690 $this->styles
[$style] = $options;
3694 * Adds inline CSS styles
3695 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3697 * @param mixed $style_css Inline CSS
3698 * @param string $flip Set to 'flip' to flip the CSS if needed
3700 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3701 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3702 # If wanted, and the interface is right-to-left, flip the CSS
3703 $style_css = CSSJanus
::transform( $style_css, true, false );
3705 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3709 * Build exempt modules and legacy non-ResourceLoader styles.
3711 * @return string|WrappedStringList HTML
3713 protected function buildExemptModules() {
3717 // - Within modules provided by the software (core, skin, extensions),
3718 // styles from skin stylesheets should be overridden by styles
3719 // from modules dynamically loaded with JavaScript.
3720 // - Styles from site-specific, private, and user modules should override
3721 // both of the above.
3723 // The effective order for stylesheets must thus be:
3724 // 1. Page style modules, formatted server-side by ResourceLoaderClientHtml.
3725 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
3726 // 3. Styles that are site-specific, private or from the user, formatted
3727 // server-side by this function.
3729 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
3732 // Add legacy styles added through addStyle()/addInlineStyle() here
3733 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3735 // Things that go after the ResourceLoaderDynamicStyles marker
3737 $separateReq = [ 'site.styles', 'user.styles' ];
3738 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3739 if ( $moduleNames ) {
3740 $append[] = $this->makeResourceLoaderLink(
3741 array_diff( $moduleNames, $separateReq ),
3742 ResourceLoaderModule
::TYPE_STYLES
3745 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3746 // These require their own dedicated request in order to support "@import"
3747 // syntax, which is incompatible with concatenation. (T147667, T37562)
3748 $append[] = $this->makeResourceLoaderLink( $name,
3749 ResourceLoaderModule
::TYPE_STYLES
3755 $chunks[] = Html
::element(
3757 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3759 $chunks = array_merge( $chunks, $append );
3762 return self
::combineWrappedStrings( $chunks );
3768 public function buildCssLinksArray() {
3771 foreach ( $this->styles
as $file => $options ) {
3772 $link = $this->styleLink( $file, $options );
3774 $links[$file] = $link;
3781 * Generate \<link\> tags for stylesheets
3783 * @param string $style URL to the file
3784 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3785 * @return string HTML fragment
3787 protected function styleLink( $style, array $options ) {
3788 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3792 if ( isset( $options['media'] ) ) {
3793 $media = self
::transformCssMedia( $options['media'] );
3794 if ( is_null( $media ) ) {
3801 if ( substr( $style, 0, 1 ) == '/' ||
3802 substr( $style, 0, 5 ) == 'http:' ||
3803 substr( $style, 0, 6 ) == 'https:' ) {
3806 $config = $this->getConfig();
3807 // Append file hash as query parameter
3808 $url = self
::transformResourcePath(
3810 $config->get( 'StylePath' ) . '/' . $style
3814 $link = Html
::linkedStyle( $url, $media );
3816 if ( isset( $options['condition'] ) ) {
3817 $condition = htmlspecialchars( $options['condition'] );
3818 $link = "<!--[if $condition]>$link<![endif]-->";
3824 * Transform path to web-accessible static resource.
3826 * This is used to add a validation hash as query string.
3827 * This aids various behaviors:
3829 * - Put long Cache-Control max-age headers on responses for improved
3830 * cache performance.
3831 * - Get the correct version of a file as expected by the current page.
3832 * - Instantly get the updated version of a file after deployment.
3834 * Avoid using this for urls included in HTML as otherwise clients may get different
3835 * versions of a resource when navigating the site depending on when the page was cached.
3836 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3837 * an external stylesheet).
3840 * @param Config $config
3841 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3842 * @return string URL
3844 public static function transformResourcePath( Config
$config, $path ) {
3848 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3849 if ( $remotePathPrefix === '' ) {
3850 // The configured base path is required to be empty string for
3851 // wikis in the domain root
3854 $remotePath = $remotePathPrefix;
3856 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3857 // - Path is outside wgResourceBasePath, ignore.
3858 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3861 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3862 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3863 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3864 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3865 $uploadPath = $config->get( 'UploadPath' );
3866 if ( strpos( $path, $uploadPath ) === 0 ) {
3867 $localDir = $config->get( 'UploadDirectory' );
3868 $remotePathPrefix = $remotePath = $uploadPath;
3871 $path = RelPath
::getRelativePath( $path, $remotePath );
3872 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3876 * Utility method for transformResourceFilePath().
3878 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3881 * @param string $remotePathPrefix URL path prefix that points to $localPath
3882 * @param string $localPath File directory exposed at $remotePath
3883 * @param string $file Path to target file relative to $localPath
3884 * @return string URL
3886 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3887 $hash = md5_file( "$localPath/$file" );
3888 if ( $hash === false ) {
3889 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3892 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3896 * Transform "media" attribute based on request parameters
3898 * @param string $media Current value of the "media" attribute
3899 * @return string Modified value of the "media" attribute, or null to skip
3902 public static function transformCssMedia( $media ) {
3905 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3906 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3908 // Switch in on-screen display for media testing
3910 'printable' => 'print',
3911 'handheld' => 'handheld',
3913 foreach ( $switches as $switch => $targetMedia ) {
3914 if ( $wgRequest->getBool( $switch ) ) {
3915 if ( $media == $targetMedia ) {
3917 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3918 /* This regex will not attempt to understand a comma-separated media_query_list
3920 * Example supported values for $media:
3921 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3922 * Example NOT supported value for $media:
3923 * '3d-glasses, screen, print and resolution > 90dpi'
3925 * If it's a print request, we never want any kind of screen stylesheets
3926 * If it's a handheld request (currently the only other choice with a switch),
3927 * we don't want simple 'screen' but we might want screen queries that
3928 * have a max-width or something, so we'll pass all others on and let the
3929 * client do the query.
3931 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3942 * Add a wikitext-formatted message to the output.
3943 * This is equivalent to:
3945 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3947 public function addWikiMsg( /*...*/ ) {
3948 $args = func_get_args();
3949 $name = array_shift( $args );
3950 $this->addWikiMsgArray( $name, $args );
3954 * Add a wikitext-formatted message to the output.
3955 * Like addWikiMsg() except the parameters are taken as an array
3956 * instead of a variable argument list.
3958 * @param string $name
3959 * @param array $args
3961 public function addWikiMsgArray( $name, $args ) {
3962 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3966 * This function takes a number of message/argument specifications, wraps them in
3967 * some overall structure, and then parses the result and adds it to the output.
3969 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3970 * and so on. The subsequent arguments may be either
3971 * 1) strings, in which case they are message names, or
3972 * 2) arrays, in which case, within each array, the first element is the message
3973 * name, and subsequent elements are the parameters to that message.
3975 * Don't use this for messages that are not in the user's interface language.
3979 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3983 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
3984 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3986 * The newline after the opening div is needed in some wikitext. See T21226.
3988 * @param string $wrap
3990 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3991 $msgSpecs = func_get_args();
3992 array_shift( $msgSpecs );
3993 $msgSpecs = array_values( $msgSpecs );
3995 foreach ( $msgSpecs as $n => $spec ) {
3996 if ( is_array( $spec ) ) {
3998 $name = array_shift( $args );
4003 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
4005 $this->addWikiTextAsInterface( $s );
4009 * Whether the output has a table of contents
4013 public function isTOCEnabled() {
4014 return $this->mEnableTOC
;
4018 * Helper function to setup the PHP implementation of OOUI to use in this request.
4021 * @param string $skinName The Skin name to determine the correct OOUI theme
4022 * @param string $dir Language direction
4024 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4025 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4026 $theme = $themes[$skinName] ??
$themes['default'];
4027 // For example, 'OOUI\WikimediaUITheme'.
4028 $themeClass = "OOUI\\{$theme}Theme";
4029 OOUI\Theme
::setSingleton( new $themeClass() );
4030 OOUI\Element
::setDefaultDir( $dir );
4034 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4035 * MediaWiki and this OutputPage instance.
4039 public function enableOOUI() {
4041 strtolower( $this->getSkin()->getSkinName() ),
4042 $this->getLanguage()->getDir()
4044 $this->addModuleStyles( [
4045 'oojs-ui-core.styles',
4046 'oojs-ui.styles.indicators',
4047 'mediawiki.widgets.styles',
4048 'oojs-ui-core.icons',
4053 * Get (and set if not yet set) the CSP nonce.
4055 * This value needs to be included in any <script> tags on the
4058 * @return string|bool Nonce or false to mean don't output nonce
4061 public function getCSPNonce() {
4062 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4065 if ( $this->CSPNonce
=== null ) {
4066 // XXX It might be expensive to generate randomness
4067 // on every request, on Windows.
4068 $rand = random_bytes( 15 );
4069 $this->CSPNonce
= base64_encode( $rand );
4071 return $this->CSPNonce
;