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 $this->getContext()->setTitle( $t );
1002 * Replace the subtitle with $str
1004 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1006 public function setSubtitle( $str ) {
1007 $this->clearSubtitle();
1008 $this->addSubtitle( $str );
1012 * Add $str to the subtitle
1014 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1016 public function addSubtitle( $str ) {
1017 if ( $str instanceof Message
) {
1018 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1020 $this->mSubtitle
[] = $str;
1025 * Build message object for a subtitle containing a backlink to a page
1027 * @param Title $title Title to link to
1028 * @param array $query Array of additional parameters to include in the link
1032 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1033 if ( $title->isRedirect() ) {
1034 $query['redirect'] = 'no';
1036 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1037 return wfMessage( 'backlinksubtitle' )
1038 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1042 * Add a subtitle containing a backlink to a page
1044 * @param Title $title Title to link to
1045 * @param array $query Array of additional parameters to include in the link
1047 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1048 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1052 * Clear the subtitles
1054 public function clearSubtitle() {
1055 $this->mSubtitle
= [];
1063 public function getSubtitle() {
1064 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1068 * Set the page as printable, i.e. it'll be displayed with all
1069 * print styles included
1071 public function setPrintable() {
1072 $this->mPrintable
= true;
1076 * Return whether the page is "printable"
1080 public function isPrintable() {
1081 return $this->mPrintable
;
1085 * Disable output completely, i.e. calling output() will have no effect
1087 public function disable() {
1088 $this->mDoNothing
= true;
1092 * Return whether the output will be completely disabled
1096 public function isDisabled() {
1097 return $this->mDoNothing
;
1101 * Show an "add new section" link?
1105 public function showNewSectionLink() {
1106 return $this->mNewSectionLink
;
1110 * Forcibly hide the new section link?
1114 public function forceHideNewSectionLink() {
1115 return $this->mHideNewSectionLink
;
1119 * Add or remove feed links in the page header
1120 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1121 * for the new version
1122 * @see addFeedLink()
1124 * @param bool $show True: add default feeds, false: remove all feeds
1126 public function setSyndicated( $show = true ) {
1128 $this->setFeedAppendQuery( false );
1130 $this->mFeedLinks
= [];
1135 * Return effective list of advertised feed types
1136 * @see addFeedLink()
1138 * @return array Array of feed type names ( 'rss', 'atom' )
1140 protected function getAdvertisedFeedTypes() {
1141 if ( $this->getConfig()->get( 'Feed' ) ) {
1142 return $this->getConfig()->get( 'AdvertisedFeedTypes' );
1149 * Add default feeds to the page header
1150 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1151 * for the new version
1152 * @see addFeedLink()
1154 * @param string $val Query to append to feed links or false to output
1157 public function setFeedAppendQuery( $val ) {
1158 $this->mFeedLinks
= [];
1160 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1161 $query = "feed=$type";
1162 if ( is_string( $val ) ) {
1163 $query .= '&' . $val;
1165 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1170 * Add a feed link to the page header
1172 * @param string $format Feed type, should be a key of $wgFeedClasses
1173 * @param string $href URL
1175 public function addFeedLink( $format, $href ) {
1176 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1177 $this->mFeedLinks
[$format] = $href;
1182 * Should we output feed links for this page?
1185 public function isSyndicated() {
1186 return count( $this->mFeedLinks
) > 0;
1190 * Return URLs for each supported syndication format for this page.
1191 * @return array Associating format keys with URLs
1193 public function getSyndicationLinks() {
1194 return $this->mFeedLinks
;
1198 * Will currently always return null
1202 public function getFeedAppendQuery() {
1203 return $this->mFeedLinksAppendQuery
;
1207 * Set whether the displayed content is related to the source of the
1208 * corresponding article on the wiki
1209 * Setting true will cause the change "article related" toggle to true
1211 * @param bool $newVal
1213 public function setArticleFlag( $newVal ) {
1214 $this->mIsArticle
= $newVal;
1216 $this->mIsArticleRelated
= $newVal;
1221 * Return whether the content displayed page is related to the source of
1222 * the corresponding article on the wiki
1226 public function isArticle() {
1227 return $this->mIsArticle
;
1231 * Set whether this page is related an article on the wiki
1232 * Setting false will cause the change of "article flag" toggle to false
1234 * @param bool $newVal
1236 public function setArticleRelated( $newVal ) {
1237 $this->mIsArticleRelated
= $newVal;
1239 $this->mIsArticle
= false;
1244 * Return whether this page is related an article on the wiki
1248 public function isArticleRelated() {
1249 return $this->mIsArticleRelated
;
1253 * Set whether the standard copyright should be shown for the current page.
1255 * @param bool $hasCopyright
1257 public function setCopyright( $hasCopyright ) {
1258 $this->mHasCopyright
= $hasCopyright;
1262 * Return whether the standard copyright should be shown for the current page.
1263 * By default, it is true for all articles but other pages
1264 * can signal it by using setCopyright( true ).
1266 * Used by SkinTemplate to decided whether to show the copyright.
1270 public function showsCopyright() {
1271 return $this->isArticle() ||
$this->mHasCopyright
;
1275 * Add new language links
1277 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1278 * (e.g. 'fr:Test page')
1280 public function addLanguageLinks( array $newLinkArray ) {
1281 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1285 * Reset the language links and add new language links
1287 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1288 * (e.g. 'fr:Test page')
1290 public function setLanguageLinks( array $newLinkArray ) {
1291 $this->mLanguageLinks
= $newLinkArray;
1295 * Get the list of language links
1297 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1299 public function getLanguageLinks() {
1300 return $this->mLanguageLinks
;
1304 * Add an array of categories, with names in the keys
1306 * @param array $categories Mapping category name => sort key
1308 public function addCategoryLinks( array $categories ) {
1309 if ( !$categories ) {
1313 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1315 # Set all the values to 'normal'.
1316 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1318 # Mark hidden categories
1319 foreach ( $res as $row ) {
1320 if ( isset( $row->pp_value
) ) {
1321 $categories[$row->page_title
] = 'hidden';
1325 // Avoid PHP 7.1 warning of passing $this by reference
1326 $outputPage = $this;
1327 # Add the remaining categories to the skin
1329 'OutputPageMakeCategoryLinks',
1330 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1332 $services = MediaWikiServices
::getInstance();
1333 $linkRenderer = $services->getLinkRenderer();
1334 foreach ( $categories as $category => $type ) {
1335 // array keys will cast numeric category names to ints, so cast back to string
1336 $category = (string)$category;
1337 $origcategory = $category;
1338 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1342 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1343 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1346 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1347 $this->mCategories
[$type][] = $title->getText();
1348 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1354 * @param array $categories
1355 * @return bool|IResultWrapper
1357 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1358 # Add the links to a LinkBatch
1359 $arr = [ NS_CATEGORY
=> $categories ];
1360 $lb = new LinkBatch
;
1361 $lb->setArray( $arr );
1363 # Fetch existence plus the hiddencat property
1364 $dbr = wfGetDB( DB_REPLICA
);
1365 $fields = array_merge(
1366 LinkCache
::getSelectFields(),
1367 [ 'page_namespace', 'page_title', 'pp_value' ]
1370 $res = $dbr->select( [ 'page', 'page_props' ],
1372 $lb->constructSet( 'page', $dbr ),
1375 [ 'page_props' => [ 'LEFT JOIN', [
1376 'pp_propname' => 'hiddencat',
1381 # Add the results to the link cache
1382 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1383 $lb->addResultToCache( $linkCache, $res );
1389 * Reset the category links (but not the category list) and add $categories
1391 * @param array $categories Mapping category name => sort key
1393 public function setCategoryLinks( array $categories ) {
1394 $this->mCategoryLinks
= [];
1395 $this->addCategoryLinks( $categories );
1399 * Get the list of category links, in a 2-D array with the following format:
1400 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1401 * hidden categories) and $link a HTML fragment with a link to the category
1406 public function getCategoryLinks() {
1407 return $this->mCategoryLinks
;
1411 * Get the list of category names this page belongs to.
1413 * @param string $type The type of categories which should be returned. Possible values:
1414 * * all: all categories of all types
1415 * * hidden: only the hidden categories
1416 * * normal: all categories, except hidden categories
1417 * @return array Array of strings
1419 public function getCategories( $type = 'all' ) {
1420 if ( $type === 'all' ) {
1421 $allCategories = [];
1422 foreach ( $this->mCategories
as $categories ) {
1423 $allCategories = array_merge( $allCategories, $categories );
1425 return $allCategories;
1427 if ( !isset( $this->mCategories
[$type] ) ) {
1428 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1430 return $this->mCategories
[$type];
1434 * Add an array of indicators, with their identifiers as array
1435 * keys and HTML contents as values.
1437 * In case of duplicate keys, existing values are overwritten.
1439 * @param array $indicators
1442 public function setIndicators( array $indicators ) {
1443 $this->mIndicators
= $indicators +
$this->mIndicators
;
1444 // Keep ordered by key
1445 ksort( $this->mIndicators
);
1449 * Get the indicators associated with this page.
1451 * The array will be internally ordered by item keys.
1453 * @return array Keys: identifiers, values: HTML contents
1456 public function getIndicators() {
1457 return $this->mIndicators
;
1461 * Adds help link with an icon via page indicators.
1462 * Link target can be overridden by a local message containing a wikilink:
1463 * the message key is: lowercase action or special page name + '-helppage'.
1464 * @param string $to Target MediaWiki.org page title or encoded URL.
1465 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1468 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1469 $this->addModuleStyles( 'mediawiki.helplink' );
1470 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1472 if ( $overrideBaseUrl ) {
1475 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1476 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1479 $link = Html
::rawElement(
1483 'target' => '_blank',
1484 'class' => 'mw-helplink',
1489 $this->setIndicators( [ 'mw-helplink' => $link ] );
1493 * Do not allow scripts which can be modified by wiki users to load on this page;
1494 * only allow scripts bundled with, or generated by, the software.
1495 * Site-wide styles are controlled by a config setting, since they can be
1496 * used to create a custom skin/theme, but not user-specific ones.
1498 * @todo this should be given a more accurate name
1500 public function disallowUserJs() {
1501 $this->reduceAllowedModules(
1502 ResourceLoaderModule
::TYPE_SCRIPTS
,
1503 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1506 // Site-wide styles are controlled by a config setting, see T73621
1507 // for background on why. User styles are never allowed.
1508 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1509 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1511 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1513 $this->reduceAllowedModules(
1514 ResourceLoaderModule
::TYPE_STYLES
,
1520 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1521 * @see ResourceLoaderModule::$origin
1522 * @param string $type ResourceLoaderModule TYPE_ constant
1523 * @return int ResourceLoaderModule ORIGIN_ class constant
1525 public function getAllowedModules( $type ) {
1526 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1527 return min( array_values( $this->mAllowedModules
) );
1529 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1534 * Limit the highest level of CSS/JS untrustworthiness allowed.
1536 * If passed the same or a higher level than the current level of untrustworthiness set, the
1537 * level will remain unchanged.
1539 * @param string $type
1540 * @param int $level ResourceLoaderModule class constant
1542 public function reduceAllowedModules( $type, $level ) {
1543 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1547 * Prepend $text to the body HTML
1549 * @param string $text HTML
1551 public function prependHTML( $text ) {
1552 $this->mBodytext
= $text . $this->mBodytext
;
1556 * Append $text to the body HTML
1558 * @param string $text HTML
1560 public function addHTML( $text ) {
1561 $this->mBodytext
.= $text;
1565 * Shortcut for adding an Html::element via addHTML.
1569 * @param string $element
1570 * @param array $attribs
1571 * @param string $contents
1573 public function addElement( $element, array $attribs = [], $contents = '' ) {
1574 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1578 * Clear the body HTML
1580 public function clearHTML() {
1581 $this->mBodytext
= '';
1587 * @return string HTML
1589 public function getHTML() {
1590 return $this->mBodytext
;
1594 * Get/set the ParserOptions object to use for wikitext parsing
1596 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1597 * current ParserOption object. This parameter is deprecated since 1.31.
1598 * @return ParserOptions
1600 public function parserOptions( $options = null ) {
1601 if ( $options !== null ) {
1602 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1605 if ( $options !== null && !empty( $options->isBogus
) ) {
1606 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1607 // been changed somehow, and keep it if so.
1608 $anonPO = ParserOptions
::newFromAnon();
1609 $anonPO->setAllowUnsafeRawHtml( false );
1610 if ( !$options->matches( $anonPO ) ) {
1611 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1612 $options->isBogus
= false;
1616 if ( !$this->mParserOptions
) {
1617 if ( !$this->getUser()->isSafeToLoad() ) {
1618 // $wgUser isn't unstubbable yet, so don't try to get a
1619 // ParserOptions for it. And don't cache this ParserOptions
1621 $po = ParserOptions
::newFromAnon();
1622 $po->setAllowUnsafeRawHtml( false );
1623 $po->isBogus
= true;
1624 if ( $options !== null ) {
1625 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1630 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1631 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1634 if ( $options !== null && !empty( $options->isBogus
) ) {
1635 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1637 return wfSetVar( $this->mParserOptions
, null, true );
1639 return wfSetVar( $this->mParserOptions
, $options );
1644 * Set the revision ID which will be seen by the wiki text parser
1645 * for things such as embedded {{REVISIONID}} variable use.
1647 * @param int|null $revid A positive integer, or null
1648 * @return mixed Previous value
1650 public function setRevisionId( $revid ) {
1651 $val = is_null( $revid ) ?
null : intval( $revid );
1652 return wfSetVar( $this->mRevisionId
, $val, true );
1656 * Get the displayed revision ID
1660 public function getRevisionId() {
1661 return $this->mRevisionId
;
1665 * Whether the revision displayed is the latest revision of the page
1670 public function isRevisionCurrent() {
1671 return $this->mRevisionId
== 0 ||
$this->mRevisionId
== $this->getTitle()->getLatestRevID();
1675 * Set the timestamp of the revision which will be displayed. This is used
1676 * to avoid a extra DB call in Skin::lastModified().
1678 * @param string|null $timestamp
1679 * @return mixed Previous value
1681 public function setRevisionTimestamp( $timestamp ) {
1682 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1686 * Get the timestamp of displayed revision.
1687 * This will be null if not filled by setRevisionTimestamp().
1689 * @return string|null
1691 public function getRevisionTimestamp() {
1692 return $this->mRevisionTimestamp
;
1696 * Set the displayed file version
1698 * @param File|null $file
1699 * @return mixed Previous value
1701 public function setFileVersion( $file ) {
1703 if ( $file instanceof File
&& $file->exists() ) {
1704 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1706 return wfSetVar( $this->mFileVersion
, $val, true );
1710 * Get the displayed file version
1712 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1714 public function getFileVersion() {
1715 return $this->mFileVersion
;
1719 * Get the templates used on this page
1721 * @return array (namespace => dbKey => revId)
1724 public function getTemplateIds() {
1725 return $this->mTemplateIds
;
1729 * Get the files used on this page
1731 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1734 public function getFileSearchOptions() {
1735 return $this->mImageTimeKeys
;
1739 * Convert wikitext *in the user interface language* to HTML and
1740 * add it to the buffer. The result will not be
1741 * language-converted, as user interface messages are already
1742 * localized into a specific variant. Assumes that the current
1743 * page title will be used if optional $title is not
1744 * provided. Output will be tidy.
1746 * @param string $text Wikitext in the user interface language
1747 * @param bool $linestart Is this the start of a line? (Defaults to true)
1748 * @param Title|null $title Optional title to use; default of `null`
1749 * means use current page title.
1750 * @throws MWException if $title is not provided and OutputPage::getTitle()
1754 public function addWikiTextAsInterface(
1755 $text, $linestart = true, Title
$title = null
1757 if ( $title === null ) {
1758 $title = $this->getTitle();
1761 throw new MWException( 'Title is null' );
1763 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1767 * Convert wikitext *in the user interface language* to HTML and
1768 * add it to the buffer with a `<div class="$wrapperClass">`
1769 * wrapper. The result will not be language-converted, as user
1770 * interface messages as already localized into a specific
1771 * variant. The $text will be parsed in start-of-line context.
1772 * Output will be tidy.
1774 * @param string $wrapperClass The class attribute value for the <div>
1775 * wrapper in the output HTML
1776 * @param string $text Wikitext in the user interface language
1779 public function wrapWikiTextAsInterface(
1780 $wrapperClass, $text
1782 $this->addWikiTextTitleInternal(
1783 $text, $this->getTitle(),
1784 /*linestart*/true, /*interface*/true,
1790 * Convert wikitext *in the page content language* to HTML and add
1791 * it to the buffer. The result with be language-converted to the
1792 * user's preferred variant. Assumes that the current page title
1793 * will be used if optional $title is not provided. Output will be
1796 * @param string $text Wikitext in the page content language
1797 * @param bool $linestart Is this the start of a line? (Defaults to true)
1798 * @param Title|null $title Optional title to use; default of `null`
1799 * means use current page title.
1800 * @throws MWException if $title is not provided and OutputPage::getTitle()
1804 public function addWikiTextAsContent(
1805 $text, $linestart = true, Title
$title = null
1807 if ( $title === null ) {
1808 $title = $this->getTitle();
1811 throw new MWException( 'Title is null' );
1813 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
1817 * Add wikitext with a custom Title object.
1818 * Output is unwrapped.
1820 * @param string $text Wikitext
1821 * @param Title $title
1822 * @param bool $linestart Is this the start of a line?
1823 * @param bool $interface Whether it is an interface message
1824 * (for example disables conversion)
1825 * @param string $wrapperClass if not empty, wraps the output in
1826 * a `<div class="$wrapperClass">`
1828 private function addWikiTextTitleInternal(
1829 $text, Title
$title, $linestart, $interface, $wrapperClass = null
1831 $parserOutput = $this->parseInternal(
1832 $text, $title, $linestart, true, $interface, /*language*/null
1835 $this->addParserOutput( $parserOutput, [
1836 'enableSectionEditLinks' => false,
1837 'wrapperDivClass' => $wrapperClass ??
'',
1842 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1843 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1847 * @param ParserOutput $parserOutput
1849 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1850 $this->mLanguageLinks
=
1851 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1852 $this->addCategoryLinks( $parserOutput->getCategories() );
1853 $this->setIndicators( $parserOutput->getIndicators() );
1854 $this->mNewSectionLink
= $parserOutput->getNewSection();
1855 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1857 if ( !$parserOutput->isCacheable() ) {
1858 $this->enableClientCache( false );
1860 $this->mNoGallery
= $parserOutput->getNoGallery();
1861 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1862 $this->addModules( $parserOutput->getModules() );
1863 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1864 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1865 $this->mPreventClickjacking
= $this->mPreventClickjacking
1866 ||
$parserOutput->preventClickjacking();
1868 // Template versioning...
1869 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1870 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1871 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1873 $this->mTemplateIds
[$ns] = $dbks;
1876 // File versioning...
1877 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1878 $this->mImageTimeKeys
[$dbk] = $data;
1881 // Hooks registered in the object
1882 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1883 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1884 list( $hookName, $data ) = $hookInfo;
1885 if ( isset( $parserOutputHooks[$hookName] ) ) {
1886 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1890 // Enable OOUI if requested via ParserOutput
1891 if ( $parserOutput->getEnableOOUI() ) {
1892 $this->enableOOUI();
1895 // Include parser limit report
1896 if ( !$this->limitReportJSData
) {
1897 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1900 // Link flags are ignored for now, but may in the future be
1901 // used to mark individual language links.
1903 // Avoid PHP 7.1 warning of passing $this by reference
1904 $outputPage = $this;
1905 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1906 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1908 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1909 // so that extensions may modify ParserOutput to toggle TOC.
1910 // This cannot be moved to addParserOutputText because that is not
1911 // called by EditPage for Preview.
1912 if ( $parserOutput->getTOCHTML() ) {
1913 $this->mEnableTOC
= true;
1918 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1919 * ParserOutput object, without any other metadata.
1922 * @param ParserOutput $parserOutput
1923 * @param array $poOptions Options to ParserOutput::getText()
1925 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
1926 $this->addParserOutputText( $parserOutput, $poOptions );
1928 $this->addModules( $parserOutput->getModules() );
1929 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1931 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1935 * Add the HTML associated with a ParserOutput object, without any metadata.
1938 * @param ParserOutput $parserOutput
1939 * @param array $poOptions Options to ParserOutput::getText()
1941 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
1942 $text = $parserOutput->getText( $poOptions );
1943 // Avoid PHP 7.1 warning of passing $this by reference
1944 $outputPage = $this;
1945 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1946 $this->addHTML( $text );
1950 * Add everything from a ParserOutput object.
1952 * @param ParserOutput $parserOutput
1953 * @param array $poOptions Options to ParserOutput::getText()
1955 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
1956 $this->addParserOutputMetadata( $parserOutput );
1957 $this->addParserOutputText( $parserOutput, $poOptions );
1961 * Add the output of a QuickTemplate to the output buffer
1963 * @param QuickTemplate &$template
1965 public function addTemplate( &$template ) {
1966 $this->addHTML( $template->getHTML() );
1970 * Parse wikitext and return the HTML.
1972 * @todo The output is wrapped in a <div> iff $interface is false; it's
1973 * probably best to always strip the wrapper.
1975 * @param string $text
1976 * @param bool $linestart Is this the start of a line?
1977 * @param bool $interface Use interface language (instead of content language) while parsing
1978 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1979 * LanguageConverter.
1980 * @param Language|null $language Target language object, will override $interface
1981 * @throws MWException
1982 * @return string HTML
1983 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
1984 * use parseAsContent() if $interface is default value or false, or else
1985 * parseAsInterface() if $interface is true.
1987 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1988 wfDeprecated( __METHOD__
, '1.33' );
1989 return $this->parseInternal(
1990 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
1992 'enableSectionEditLinks' => false,
1997 * Parse wikitext *in the page content language* and return the HTML.
1998 * The result will be language-converted to the user's preferred variant.
1999 * Output will be tidy.
2001 * @param string $text Wikitext in the page content language
2002 * @param bool $linestart Is this the start of a line? (Defaults to true)
2003 * @throws MWException
2004 * @return string HTML
2007 public function parseAsContent( $text, $linestart = true ) {
2008 return $this->parseInternal(
2009 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2011 'enableSectionEditLinks' => false,
2012 'wrapperDivClass' => ''
2017 * Parse wikitext *in the user interface language* and return the HTML.
2018 * The result will not be language-converted, as user interface messages
2019 * are already localized into a specific variant.
2020 * Output will be tidy.
2022 * @param string $text Wikitext in the user interface language
2023 * @param bool $linestart Is this the start of a line? (Defaults to true)
2024 * @throws MWException
2025 * @return string HTML
2028 public function parseAsInterface( $text, $linestart = true ) {
2029 return $this->parseInternal(
2030 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2032 'enableSectionEditLinks' => false,
2033 'wrapperDivClass' => ''
2038 * Parse wikitext *in the user interface language*, strip
2039 * paragraph wrapper, and return the HTML.
2040 * The result will not be language-converted, as user interface messages
2041 * are already localized into a specific variant.
2042 * Output will be tidy. Outer paragraph wrapper will only be stripped
2043 * if the result is a single paragraph.
2045 * @param string $text Wikitext in the user interface language
2046 * @param bool $linestart Is this the start of a line? (Defaults to true)
2047 * @throws MWException
2048 * @return string HTML
2051 public function parseInlineAsInterface( $text, $linestart = true ) {
2052 return Parser
::stripOuterParagraph(
2053 $this->parseAsInterface( $text, $linestart )
2058 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2060 * @param string $text
2061 * @param bool $linestart Is this the start of a line?
2062 * @param bool $interface Use interface language (instead of content language) while parsing
2063 * language sensitive magic words like GRAMMAR and PLURAL
2064 * @return string HTML
2065 * @deprecated since 1.32, due to untidy output and confusing default
2066 * for $interface. Use parseInlineAsInterface() if $interface is
2067 * the default value or false, or else use
2068 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2070 public function parseInline( $text, $linestart = true, $interface = false ) {
2071 wfDeprecated( __METHOD__
, '1.33' );
2072 $parsed = $this->parseInternal(
2073 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2075 'enableSectionEditLinks' => false,
2076 'wrapperDivClass' => '', /* no wrapper div */
2078 return Parser
::stripOuterParagraph( $parsed );
2082 * Parse wikitext and return the HTML (internal implementation helper)
2084 * @param string $text
2085 * @param Title $title The title to use
2086 * @param bool $linestart Is this the start of a line?
2087 * @param bool $tidy Whether the output should be tidied
2088 * @param bool $interface Use interface language (instead of content language) while parsing
2089 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2090 * LanguageConverter.
2091 * @param Language|null $language Target language object, will override $interface
2092 * @throws MWException
2093 * @return ParserOutput
2095 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2096 if ( is_null( $title ) ) {
2097 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2100 $popts = $this->parserOptions();
2101 $oldTidy = $popts->setTidy( $tidy );
2102 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2104 if ( $language !== null ) {
2105 $oldLang = $popts->setTargetLanguage( $language );
2108 $parserOutput = MediaWikiServices
::getInstance()->getParser()->getFreshParser()->parse(
2109 $text, $title, $popts,
2110 $linestart, true, $this->mRevisionId
2113 $popts->setTidy( $oldTidy );
2114 $popts->setInterfaceMessage( $oldInterface );
2116 if ( $language !== null ) {
2117 $popts->setTargetLanguage( $oldLang );
2120 return $parserOutput;
2124 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2126 * @param int $maxage Maximum cache time on the CDN, in seconds.
2128 public function setCdnMaxage( $maxage ) {
2129 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2133 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2134 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2135 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2138 * @param int $maxage Maximum cache time on the CDN, in seconds
2141 public function lowerCdnMaxage( $maxage ) {
2142 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2143 $this->setCdnMaxage( $this->mCdnMaxage
);
2147 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2149 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2150 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2151 * TTL is 90% of the age of the object, subject to the min and max.
2153 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2154 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2155 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2158 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2159 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2160 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'CdnMaxAge' );
2162 if ( $mtime === null ||
$mtime === false ) {
2163 return $minTTL; // entity does not exist
2166 $age = MWTimestamp
::time() - wfTimestamp( TS_UNIX
, $mtime );
2167 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2168 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2170 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2174 * Use enableClientCache(false) to force it to send nocache headers
2176 * @param bool|null $state New value, or null to not set the value
2178 * @return bool Old value
2180 public function enableClientCache( $state ) {
2181 return wfSetVar( $this->mEnableClientCache
, $state );
2185 * Get the list of cookie names that will influence the cache
2189 function getCacheVaryCookies() {
2190 if ( self
::$cacheVaryCookies === null ) {
2191 $config = $this->getConfig();
2192 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2193 SessionManager
::singleton()->getVaryCookies(),
2197 $config->get( 'CacheVaryCookies' )
2199 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2201 return self
::$cacheVaryCookies;
2205 * Check if the request has a cache-varying cookie header
2206 * If it does, it's very important that we don't allow public caching
2210 function haveCacheVaryCookies() {
2211 $request = $this->getRequest();
2212 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2213 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2214 wfDebug( __METHOD__
. ": found $cookieName\n" );
2218 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2223 * Add an HTTP header that will influence on the cache
2225 * @param string $header Header name
2226 * @param string[]|null $option Deprecated; formerly options for the
2227 * Key header, deprecated in 1.32 and removed in 1.34. See
2228 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2229 * for the list of formerly-valid options.
2231 public function addVaryHeader( $header, array $option = null ) {
2232 if ( $option !== null && count( $option ) > 0 ) {
2233 wfDeprecated( 'addVaryHeader $option is ignored', '1.34' );
2235 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2236 $this->mVaryHeader
[$header] = null;
2241 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2242 * such as Accept-Encoding or Cookie
2246 public function getVaryHeader() {
2247 // If we vary on cookies, let's make sure it's always included here too.
2248 if ( $this->getCacheVaryCookies() ) {
2249 $this->addVaryHeader( 'Cookie' );
2252 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2253 $this->addVaryHeader( $header, $options );
2255 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2259 * Add an HTTP Link: header
2261 * @param string $header Header value
2263 public function addLinkHeader( $header ) {
2264 $this->mLinkHeader
[] = $header;
2268 * Return a Link: header. Based on the values of $mLinkHeader.
2272 public function getLinkHeader() {
2273 if ( !$this->mLinkHeader
) {
2277 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2281 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2284 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2285 * /w/index.php?title=Main_page&variant=zh-cn will not.
2287 private function addAcceptLanguage() {
2288 $title = $this->getTitle();
2289 if ( !$title instanceof Title
) {
2293 $lang = $title->getPageLanguage();
2294 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2295 $this->addVaryHeader( 'Accept-Language' );
2300 * Set a flag which will cause an X-Frame-Options header appropriate for
2301 * edit pages to be sent. The header value is controlled by
2302 * $wgEditPageFrameOptions.
2304 * This is the default for special pages. If you display a CSRF-protected
2305 * form on an ordinary view page, then you need to call this function.
2307 * @param bool $enable
2309 public function preventClickjacking( $enable = true ) {
2310 $this->mPreventClickjacking
= $enable;
2314 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2315 * This can be called from pages which do not contain any CSRF-protected
2318 public function allowClickjacking() {
2319 $this->mPreventClickjacking
= false;
2323 * Get the prevent-clickjacking flag
2328 public function getPreventClickjacking() {
2329 return $this->mPreventClickjacking
;
2333 * Get the X-Frame-Options header value (without the name part), or false
2334 * if there isn't one. This is used by Skin to determine whether to enable
2335 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2337 * @return string|false
2339 public function getFrameOptions() {
2340 $config = $this->getConfig();
2341 if ( $config->get( 'BreakFrames' ) ) {
2343 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2344 return $config->get( 'EditPageFrameOptions' );
2350 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2351 * Trials: https://github.com/GoogleChrome/OriginTrials
2355 private function getOriginTrials() {
2356 $config = $this->getConfig();
2358 return $config->get( 'OriginTrials' );
2361 private function getReportTo() {
2362 $config = $this->getConfig();
2364 $expiry = $config->get( 'ReportToExpiry' );
2370 $endpoints = $config->get( 'ReportToEndpoints' );
2372 if ( !$endpoints ) {
2376 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2378 foreach ( $endpoints as $endpoint ) {
2379 $output['endpoints'][] = [ 'url' => $endpoint ];
2382 return json_encode( $output, JSON_UNESCAPED_SLASHES
);
2385 private function getFeaturePolicyReportOnly() {
2386 $config = $this->getConfig();
2388 $features = $config->get( 'FeaturePolicyReportOnly' );
2389 return implode( ';', $features );
2393 * Send cache control HTTP headers
2395 public function sendCacheControl() {
2396 $response = $this->getRequest()->response();
2397 $config = $this->getConfig();
2399 $this->addVaryHeader( 'Cookie' );
2400 $this->addAcceptLanguage();
2402 # don't serve compressed data to clients who can't handle it
2403 # maintain different caches for logged-in users and non-logged in ones
2404 $response->header( $this->getVaryHeader() );
2406 if ( $this->mEnableClientCache
) {
2408 $config->get( 'UseCdn' ) &&
2409 !$response->hasCookies() &&
2410 !SessionManager
::getGlobalSession()->isPersistent() &&
2411 !$this->isPrintable() &&
2412 $this->mCdnMaxage
!= 0 &&
2413 !$this->haveCacheVaryCookies()
2415 if ( $config->get( 'UseESI' ) ) {
2416 wfDeprecated( '$wgUseESI = true', '1.33' );
2417 # We'll purge the proxy cache explicitly, but require end user agents
2418 # to revalidate against the proxy on each visit.
2419 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2420 wfDebug( __METHOD__
.
2421 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2422 # start with a shorter timeout for initial testing
2423 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2425 "Surrogate-Control: max-age={$config->get( 'CdnMaxAge' )}" .
2426 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2428 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2430 # We'll purge the proxy cache for anons explicitly, but require end user agents
2431 # to revalidate against the proxy on each visit.
2432 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2433 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2434 wfDebug( __METHOD__
.
2435 ": local proxy caching; {$this->mLastModified} **", 'private' );
2436 # start with a shorter timeout for initial testing
2437 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2438 $response->header( "Cache-Control: " .
2439 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2442 # We do want clients to cache if they can, but they *must* check for updates
2443 # on revisiting the page.
2444 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2445 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2446 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2448 if ( $this->mLastModified
) {
2449 $response->header( "Last-Modified: {$this->mLastModified}" );
2452 wfDebug( __METHOD__
. ": no caching **", 'private' );
2454 # In general, the absence of a last modified header should be enough to prevent
2455 # the client from using its cache. We send a few other things just to make sure.
2456 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2457 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2458 $response->header( 'Pragma: no-cache' );
2463 * Transfer styles and JavaScript modules from skin.
2465 * @param Skin $sk to load modules for
2467 public function loadSkinModules( $sk ) {
2468 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2469 if ( $group === 'styles' ) {
2470 foreach ( $modules as $key => $moduleMembers ) {
2471 $this->addModuleStyles( $moduleMembers );
2474 $this->addModules( $modules );
2480 * Finally, all the text has been munged and accumulated into
2481 * the object, let's actually output it:
2483 * @param bool $return Set to true to get the result as a string rather than sending it
2484 * @return string|null
2486 * @throws FatalError
2487 * @throws MWException
2489 public function output( $return = false ) {
2490 if ( $this->mDoNothing
) {
2491 return $return ?
'' : null;
2494 $response = $this->getRequest()->response();
2495 $config = $this->getConfig();
2497 if ( $this->mRedirect
!= '' ) {
2498 # Standards require redirect URLs to be absolute
2499 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2501 $redirect = $this->mRedirect
;
2502 $code = $this->mRedirectCode
;
2504 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2505 if ( $code == '301' ||
$code == '303' ) {
2506 if ( !$config->get( 'DebugRedirects' ) ) {
2507 $response->statusHeader( $code );
2509 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2511 if ( $config->get( 'VaryOnXFP' ) ) {
2512 $this->addVaryHeader( 'X-Forwarded-Proto' );
2514 $this->sendCacheControl();
2516 $response->header( "Content-Type: text/html; charset=utf-8" );
2517 if ( $config->get( 'DebugRedirects' ) ) {
2518 $url = htmlspecialchars( $redirect );
2519 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2520 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2521 print "</body>\n</html>\n";
2523 $response->header( 'Location: ' . $redirect );
2527 return $return ?
'' : null;
2528 } elseif ( $this->mStatusCode
) {
2529 $response->statusHeader( $this->mStatusCode
);
2532 # Buffer output; final headers may depend on later processing
2535 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2536 $response->header( 'Content-language: ' .
2537 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2539 $linkHeader = $this->getLinkHeader();
2540 if ( $linkHeader ) {
2541 $response->header( $linkHeader );
2544 // Prevent framing, if requested
2545 $frameOptions = $this->getFrameOptions();
2546 if ( $frameOptions ) {
2547 $response->header( "X-Frame-Options: $frameOptions" );
2550 $originTrials = $this->getOriginTrials();
2551 foreach ( $originTrials as $originTrial ) {
2552 $response->header( "Origin-Trial: $originTrial", false );
2555 $reportTo = $this->getReportTo();
2557 $response->header( "Report-To: $reportTo" );
2560 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2561 if ( $featurePolicyReportOnly ) {
2562 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2565 ContentSecurityPolicy
::sendHeaders( $this );
2567 if ( $this->mArticleBodyOnly
) {
2568 echo $this->mBodytext
;
2570 // Enable safe mode if requested (T152169)
2571 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2572 $this->disallowUserJs();
2575 $sk = $this->getSkin();
2576 $this->loadSkinModules( $sk );
2578 MWDebug
::addModules( $this );
2580 // Avoid PHP 7.1 warning of passing $this by reference
2581 $outputPage = $this;
2582 // Hook that allows last minute changes to the output page, e.g.
2583 // adding of CSS or Javascript by extensions.
2584 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2588 } catch ( Exception
$e ) {
2589 ob_end_clean(); // bug T129657
2595 // This hook allows last minute changes to final overall output by modifying output buffer
2596 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2597 } catch ( Exception
$e ) {
2598 ob_end_clean(); // bug T129657
2602 $this->sendCacheControl();
2605 return ob_get_clean();
2613 * Prepare this object to display an error page; disable caching and
2614 * indexing, clear the current text and redirect, set the page's title
2615 * and optionally an custom HTML title (content of the "<title>" tag).
2617 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2618 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2619 * optional, if not passed the "<title>" attribute will be
2620 * based on $pageTitle
2622 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2623 $this->setPageTitle( $pageTitle );
2624 if ( $htmlTitle !== false ) {
2625 $this->setHTMLTitle( $htmlTitle );
2627 $this->setRobotPolicy( 'noindex,nofollow' );
2628 $this->setArticleRelated( false );
2629 $this->enableClientCache( false );
2630 $this->mRedirect
= '';
2631 $this->clearSubtitle();
2636 * Output a standard error page
2638 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2639 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2640 * showErrorPage( 'titlemsg', $messageObject );
2641 * showErrorPage( $titleMessageObject, $messageObject );
2643 * @param string|Message $title Message key (string) for page title, or a Message object
2644 * @param string|Message $msg Message key (string) for page text, or a Message object
2645 * @param array $params Message parameters; ignored if $msg is a Message object
2647 public function showErrorPage( $title, $msg, $params = [] ) {
2648 if ( !$title instanceof Message
) {
2649 $title = $this->msg( $title );
2652 $this->prepareErrorPage( $title );
2654 if ( $msg instanceof Message
) {
2655 if ( $params !== [] ) {
2656 trigger_error( 'Argument ignored: $params. The message parameters argument '
2657 . 'is discarded when the $msg argument is a Message object instead of '
2658 . 'a string.', E_USER_NOTICE
);
2660 $this->addHTML( $msg->parseAsBlock() );
2662 $this->addWikiMsgArray( $msg, $params );
2665 $this->returnToMain();
2669 * Output a standard permission error page
2671 * @param array $errors Error message keys or [key, param...] arrays
2672 * @param string|null $action Action that was denied or null if unknown
2674 public function showPermissionsErrorPage( array $errors, $action = null ) {
2675 $services = MediaWikiServices
::getInstance();
2676 $permissionManager = $services->getPermissionManager();
2677 foreach ( $errors as $key => $error ) {
2678 $errors[$key] = (array)$error;
2681 // For some action (read, edit, create and upload), display a "login to do this action"
2682 // error if all of the following conditions are met:
2683 // 1. the user is not logged in
2684 // 2. the only error is insufficient permissions (i.e. no block or something else)
2685 // 3. the error can be avoided simply by logging in
2687 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2688 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2689 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2690 && ( $permissionManager->groupHasPermission( 'user', $action )
2691 ||
$permissionManager->groupHasPermission( 'autoconfirmed', $action ) )
2693 $displayReturnto = null;
2695 # Due to T34276, if a user does not have read permissions,
2696 # $this->getTitle() will just give Special:Badtitle, which is
2697 # not especially useful as a returnto parameter. Use the title
2698 # from the request instead, if there was one.
2699 $request = $this->getRequest();
2700 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2701 if ( $action == 'edit' ) {
2702 $msg = 'whitelistedittext';
2703 $displayReturnto = $returnto;
2704 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2705 $msg = 'nocreatetext';
2706 } elseif ( $action == 'upload' ) {
2707 $msg = 'uploadnologintext';
2709 $msg = 'loginreqpagetext';
2710 $displayReturnto = Title
::newMainPage();
2716 $query['returnto'] = $returnto->getPrefixedText();
2718 if ( !$request->wasPosted() ) {
2719 $returntoquery = $request->getValues();
2720 unset( $returntoquery['title'] );
2721 unset( $returntoquery['returnto'] );
2722 unset( $returntoquery['returntoquery'] );
2723 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2727 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2728 $linkRenderer = $services->getLinkRenderer();
2729 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2730 $loginLink = $linkRenderer->makeKnownLink(
2732 $this->msg( 'loginreqlink' )->text(),
2737 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2738 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2740 # Don't return to a page the user can't read otherwise
2741 # we'll end up in a pointless loop
2742 if ( $displayReturnto && $permissionManager->userCan(
2743 'read', $this->getUser(), $displayReturnto
2745 $this->returnToMain( null, $displayReturnto );
2748 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2749 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2754 * Display an error page indicating that a given version of MediaWiki is
2755 * required to use it
2757 * @param mixed $version The version of MediaWiki needed to use the page
2759 public function versionRequired( $version ) {
2760 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2762 $this->addWikiMsg( 'versionrequiredtext', $version );
2763 $this->returnToMain();
2767 * Format a list of error messages
2769 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2770 * @param string|null $action Action that was denied or null if unknown
2771 * @return string The wikitext error-messages, formatted into a list.
2773 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2774 if ( $action == null ) {
2775 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2777 $action_desc = $this->msg( "action-$action" )->plain();
2779 'permissionserrorstext-withaction',
2782 )->plain() . "\n\n";
2785 if ( count( $errors ) > 1 ) {
2786 $text .= '<ul class="permissions-errors">' . "\n";
2788 foreach ( $errors as $error ) {
2790 $text .= $this->msg( ...$error )->plain();
2795 $text .= "<div class=\"permissions-errors\">\n" .
2796 $this->msg( ...reset( $errors ) )->plain() .
2804 * Show a warning about replica DB lag
2806 * If the lag is higher than $wgSlaveLagCritical seconds,
2807 * then the warning is a bit more obvious. If the lag is
2808 * lower than $wgSlaveLagWarning, then no warning is shown.
2810 * @param int $lag Replica lag
2812 public function showLagWarning( $lag ) {
2813 $config = $this->getConfig();
2814 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2815 $lag = floor( $lag ); // floor to avoid nano seconds to display
2816 $message = $lag < $config->get( 'SlaveLagCritical' )
2819 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2820 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2825 * Output an error page
2827 * @note FatalError exception class provides an alternative.
2828 * @param string $message Error to output. Must be escaped for HTML.
2830 public function showFatalError( $message ) {
2831 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2833 $this->addHTML( $message );
2837 * Add a "return to" link pointing to a specified title
2839 * @param Title $title Title to link
2840 * @param array $query Query string parameters
2841 * @param string|null $text Text of the link (input is not escaped)
2842 * @param array $options Options array to pass to Linker
2844 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2845 $linkRenderer = MediaWikiServices
::getInstance()
2846 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2847 $link = $this->msg( 'returnto' )->rawParams(
2848 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2849 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2853 * Add a "return to" link pointing to a specified title,
2854 * or the title indicated in the request, or else the main page
2856 * @param mixed|null $unused
2857 * @param Title|string|null $returnto Title or String to return to
2858 * @param string|null $returntoquery Query string for the return to link
2860 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2861 if ( $returnto == null ) {
2862 $returnto = $this->getRequest()->getText( 'returnto' );
2865 if ( $returntoquery == null ) {
2866 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2869 if ( $returnto === '' ) {
2870 $returnto = Title
::newMainPage();
2873 if ( is_object( $returnto ) ) {
2874 $titleObj = $returnto;
2876 $titleObj = Title
::newFromText( $returnto );
2878 // We don't want people to return to external interwiki. That
2879 // might potentially be used as part of a phishing scheme
2880 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2881 $titleObj = Title
::newMainPage();
2884 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2887 private function getRlClientContext() {
2888 if ( !$this->rlClientContext
) {
2889 $query = ResourceLoader
::makeLoaderQuery(
2890 [], // modules; not relevant
2891 $this->getLanguage()->getCode(),
2892 $this->getSkin()->getSkinName(),
2893 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2894 null, // version; not relevant
2895 ResourceLoader
::inDebugMode(),
2896 null, // only; not relevant
2897 $this->isPrintable(),
2898 $this->getRequest()->getBool( 'handheld' )
2900 $this->rlClientContext
= new ResourceLoaderContext(
2901 $this->getResourceLoader(),
2902 new FauxRequest( $query )
2904 if ( $this->contentOverrideCallbacks
) {
2905 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2906 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2907 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2908 $content = $callback( $title );
2909 if ( $content !== null ) {
2910 $text = ContentHandler
::getContentText( $content );
2911 if ( strpos( $text, '</script>' ) !== false ) {
2912 // Proactively replace this so that we can display a message
2913 // to the user, instead of letting it go to Html::inlineScript(),
2914 // where it would be considered a server-side issue.
2915 $titleFormatted = $title->getPrefixedText();
2916 $content = new JavaScriptContent(
2917 Xml
::encodeJsCall( 'mw.log.error', [
2918 "Cannot preview $titleFormatted due to script-closing tag."
2929 return $this->rlClientContext
;
2933 * Call this to freeze the module queue and JS config and create a formatter.
2935 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2936 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2937 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2938 * the module filters retroactively. Skins and extension hooks may also add modules until very
2939 * late in the request lifecycle.
2941 * @return ResourceLoaderClientHtml
2943 public function getRlClient() {
2944 if ( !$this->rlClient
) {
2945 $context = $this->getRlClientContext();
2946 $rl = $this->getResourceLoader();
2947 $this->addModules( [
2952 $this->addModuleStyles( [
2957 $this->getSkin()->setupSkinUserCss( $this );
2959 // Prepare exempt modules for buildExemptModules()
2960 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2962 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2964 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2965 // Separate user-specific batch for improved cache-hit ratio.
2966 $userBatch = [ 'user.styles', 'user' ];
2967 $siteBatch = array_diff( $moduleStyles, $userBatch );
2968 $dbr = wfGetDB( DB_REPLICA
);
2969 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2970 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2972 // Filter out modules handled by buildExemptModules()
2973 $moduleStyles = array_filter( $moduleStyles,
2974 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2975 $module = $rl->getModule( $name );
2977 $group = $module->getGroup();
2978 if ( isset( $exemptGroups[$group] ) ) {
2979 $exemptStates[$name] = 'ready';
2980 if ( !$module->isKnownEmpty( $context ) ) {
2981 // E.g. Don't output empty <styles>
2982 $exemptGroups[$group][] = $name;
2990 $this->rlExemptStyleModules
= $exemptGroups;
2992 $rlClient = new ResourceLoaderClientHtml( $context, [
2993 'target' => $this->getTarget(),
2994 'nonce' => $this->getCSPNonce(),
2995 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2996 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2997 // modules enqueud for loading on this page is filtered to just those.
2998 // However, to make sure we also apply the restriction to dynamic dependencies and
2999 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3000 // StartupModule so that the client-side registry will not contain any restricted
3001 // modules either. (T152169, T185303)
3002 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
3003 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
3006 $rlClient->setConfig( $this->getJSVars() );
3007 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3008 $rlClient->setModuleStyles( $moduleStyles );
3009 $rlClient->setExemptStates( $exemptStates );
3010 $this->rlClient
= $rlClient;
3012 return $this->rlClient
;
3016 * @param Skin $sk The given Skin
3017 * @param bool $includeStyle Unused
3018 * @return string The doctype, opening "<html>", and head element.
3020 public function headElement( Skin
$sk, $includeStyle = true ) {
3021 $config = $this->getConfig();
3022 $userdir = $this->getLanguage()->getDir();
3023 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3026 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
3027 $this->getRlClient()->getDocumentAttributes(),
3028 $sk->getHtmlElementAttributes()
3030 $pieces[] = Html
::openElement( 'head' );
3032 if ( $this->getHTMLTitle() == '' ) {
3033 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3036 if ( !Html
::isXmlMimeType( $config->get( 'MimeType' ) ) ) {
3037 // Add <meta charset="UTF-8">
3038 // This should be before <title> since it defines the charset used by
3039 // text including the text inside <title>.
3040 // The spec recommends defining XHTML5's charset using the XML declaration
3042 // Our XML declaration is output by Html::htmlHeader.
3043 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3044 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3045 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3048 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3049 $pieces[] = $this->getRlClient()->getHeadHtml();
3050 $pieces[] = $this->buildExemptModules();
3051 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3052 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3054 // This library is intended to run on older browsers that MediaWiki no longer
3055 // supports as Grade A. For these Grade C browsers, we provide an experience
3056 // using only HTML and CSS. But, where standards-compliant browsers are able to
3057 // style unknown HTML elements without issue, old IE ignores these styles.
3058 // The html5shiv library fixes that.
3059 // Use an IE conditional comment to serve the script only to old IE
3060 $shivUrl = $config->get( 'ResourceBasePath' ) . '/resources/lib/html5shiv/html5shiv.js';
3061 $pieces[] = '<!--[if lt IE 9]>' .
3062 Html
::linkedScript( $shivUrl, $this->getCSPNonce() ) .
3065 $pieces[] = Html
::closeElement( 'head' );
3067 $bodyClasses = $this->mAdditionalBodyClasses
;
3068 $bodyClasses[] = 'mediawiki';
3070 # Classes for LTR/RTL directionality support
3071 $bodyClasses[] = $userdir;
3072 $bodyClasses[] = "sitedir-$sitedir";
3074 $underline = $this->getUser()->getOption( 'underline' );
3075 if ( $underline < 2 ) {
3076 // The following classes can be used here:
3077 // * mw-underline-always
3078 // * mw-underline-never
3079 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
3082 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3083 # A <body> class is probably not the best way to do this . . .
3084 $bodyClasses[] = 'capitalize-all-nouns';
3087 // Parser feature migration class
3088 // The idea is that this will eventually be removed, after the wikitext
3089 // which requires it is cleaned up.
3090 $bodyClasses[] = 'mw-hide-empty-elt';
3092 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3093 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3095 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3098 // While the implode() is not strictly needed, it's used for backwards compatibility
3099 // (this used to be built as a string and hooks likely still expect that).
3100 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3102 // Allow skins and extensions to add body attributes they need
3103 $sk->addToBodyAttributes( $this, $bodyAttrs );
3104 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3106 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3108 return self
::combineWrappedStrings( $pieces );
3112 * Get a ResourceLoader object associated with this OutputPage
3114 * @return ResourceLoader
3116 public function getResourceLoader() {
3117 if ( is_null( $this->mResourceLoader
) ) {
3118 // Lazy-initialise as needed
3119 $this->mResourceLoader
= MediaWikiServices
::getInstance()->getResourceLoader();
3121 return $this->mResourceLoader
;
3125 * Explicily load or embed modules on a page.
3127 * @param array|string $modules One or more module names
3128 * @param string $only ResourceLoaderModule TYPE_ class constant
3129 * @param array $extraQuery [optional] Array with extra query parameters for the request
3130 * @return string|WrappedStringList HTML
3132 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3133 // Apply 'target' and 'origin' filters
3134 $modules = $this->filterModules( (array)$modules, null, $only );
3136 return ResourceLoaderClientHtml
::makeLoad(
3137 $this->getRlClientContext(),
3141 $this->getCSPNonce()
3146 * Combine WrappedString chunks and filter out empty ones
3148 * @param array $chunks
3149 * @return string|WrappedStringList HTML
3151 protected static function combineWrappedStrings( array $chunks ) {
3152 // Filter out empty values
3153 $chunks = array_filter( $chunks, 'strlen' );
3154 return WrappedString
::join( "\n", $chunks );
3158 * JS stuff to put at the bottom of the `<body>`.
3159 * These are legacy scripts ($this->mScripts), and user JS.
3161 * @return string|WrappedStringList HTML
3163 public function getBottomScripts() {
3165 $chunks[] = $this->getRlClient()->getBodyHtml();
3167 // Legacy non-ResourceLoader scripts
3168 $chunks[] = $this->mScripts
;
3170 if ( $this->limitReportJSData
) {
3171 $chunks[] = ResourceLoader
::makeInlineScript(
3172 ResourceLoader
::makeConfigSetScript(
3173 [ 'wgPageParseReport' => $this->limitReportJSData
]
3175 $this->getCSPNonce()
3179 return self
::combineWrappedStrings( $chunks );
3183 * Get the javascript config vars to include on this page
3185 * @return array Array of javascript config vars
3188 public function getJsConfigVars() {
3189 return $this->mJsConfigVars
;
3193 * Add one or more variables to be set in mw.config in JavaScript
3195 * @param string|array $keys Key or array of key/value pairs
3196 * @param mixed|null $value [optional] Value of the configuration variable
3198 public function addJsConfigVars( $keys, $value = null ) {
3199 if ( is_array( $keys ) ) {
3200 foreach ( $keys as $key => $value ) {
3201 $this->mJsConfigVars
[$key] = $value;
3206 $this->mJsConfigVars
[$keys] = $value;
3210 * Get an array containing the variables to be set in mw.config in JavaScript.
3212 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3213 * - in other words, page-independent/site-wide variables (without state).
3214 * You will only be adding bloat to the html page and causing page caches to
3215 * have to be purged on configuration changes.
3218 public function getJSVars() {
3221 $canonicalSpecialPageName = false; # T23115
3222 $services = MediaWikiServices
::getInstance();
3224 $title = $this->getTitle();
3225 $ns = $title->getNamespace();
3226 $nsInfo = $services->getNamespaceInfo();
3227 $canonicalNamespace = $nsInfo->exists( $ns )
3228 ?
$nsInfo->getCanonicalName( $ns )
3229 : $title->getNsText();
3231 $sk = $this->getSkin();
3232 // Get the relevant title so that AJAX features can use the correct page name
3233 // when making API requests from certain special pages (T36972).
3234 $relevantTitle = $sk->getRelevantTitle();
3235 $relevantUser = $sk->getRelevantUser();
3237 if ( $ns == NS_SPECIAL
) {
3238 list( $canonicalSpecialPageName, /*...*/ ) =
3239 $services->getSpecialPageFactory()->
3240 resolveAlias( $title->getDBkey() );
3241 } elseif ( $this->canUseWikiPage() ) {
3242 $wikiPage = $this->getWikiPage();
3243 $curRevisionId = $wikiPage->getLatest();
3244 $articleId = $wikiPage->getId();
3247 $lang = $title->getPageViewLanguage();
3249 // Pre-process information
3250 $separatorTransTable = $lang->separatorTransformTable();
3251 $separatorTransTable = $separatorTransTable ?
: [];
3252 $compactSeparatorTransTable = [
3253 implode( "\t", array_keys( $separatorTransTable ) ),
3254 implode( "\t", $separatorTransTable ),
3256 $digitTransTable = $lang->digitTransformTable();
3257 $digitTransTable = $digitTransTable ?
: [];
3258 $compactDigitTransTable = [
3259 implode( "\t", array_keys( $digitTransTable ) ),
3260 implode( "\t", $digitTransTable ),
3263 $user = $this->getUser();
3266 'wgCanonicalNamespace' => $canonicalNamespace,
3267 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3268 'wgNamespaceNumber' => $title->getNamespace(),
3269 'wgPageName' => $title->getPrefixedDBkey(),
3270 'wgTitle' => $title->getText(),
3271 'wgCurRevisionId' => $curRevisionId,
3272 'wgRevisionId' => (int)$this->getRevisionId(),
3273 'wgArticleId' => $articleId,
3274 'wgIsArticle' => $this->isArticle(),
3275 'wgIsRedirect' => $title->isRedirect(),
3276 'wgAction' => Action
::getActionName( $this->getContext() ),
3277 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3278 'wgUserGroups' => $user->getEffectiveGroups(),
3279 'wgCategories' => $this->getCategories(),
3280 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3281 'wgPageContentLanguage' => $lang->getCode(),
3282 'wgPageContentModel' => $title->getContentModel(),
3283 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3284 'wgDigitTransformTable' => $compactDigitTransTable,
3285 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3286 'wgMonthNames' => $lang->getMonthNamesArray(),
3287 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3288 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3289 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3290 'wgRequestId' => WebRequest
::getRequestId(),
3291 'wgCSPNonce' => $this->getCSPNonce(),
3294 if ( $user->isLoggedIn() ) {
3295 $vars['wgUserId'] = $user->getId();
3296 $vars['wgUserEditCount'] = $user->getEditCount();
3297 $userReg = $user->getRegistration();
3298 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3299 // Get the revision ID of the oldest new message on the user's talk
3300 // page. This can be used for constructing new message alerts on
3302 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3305 $contLang = $services->getContentLanguage();
3306 if ( $contLang->hasVariants() ) {
3307 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3309 // Same test as SkinTemplate
3310 $vars['wgIsProbablyEditable'] = $this->userCanEditOrCreate( $user, $title );
3312 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3313 $this->userCanEditOrCreate( $user, $relevantTitle );
3315 foreach ( $title->getRestrictionTypes() as $type ) {
3316 // Following keys are set in $vars:
3317 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3318 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3321 if ( $title->isMainPage() ) {
3322 $vars['wgIsMainPage'] = true;
3325 if ( $this->mRedirectedFrom
) {
3326 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3329 if ( $relevantUser ) {
3330 $vars['wgRelevantUserName'] = $relevantUser->getName();
3333 // Allow extensions to add their custom variables to the mw.config map.
3334 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3335 // page-dependant but site-wide (without state).
3336 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3337 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3339 // Merge in variables from addJsConfigVars last
3340 return array_merge( $vars, $this->getJsConfigVars() );
3344 * To make it harder for someone to slip a user a fake
3345 * JavaScript or CSS preview, a random token
3346 * is associated with the login session. If it's not
3347 * passed back with the preview request, we won't render
3352 public function userCanPreview() {
3353 $request = $this->getRequest();
3355 $request->getVal( 'action' ) !== 'submit' ||
3356 !$request->wasPosted()
3361 $user = $this->getUser();
3363 if ( !$user->isLoggedIn() ) {
3364 // Anons have predictable edit tokens
3367 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3371 $title = $this->getTitle();
3372 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3373 if ( count( $errors ) !== 0 ) {
3382 * @param LinkTarget $title
3385 private function userCanEditOrCreate(
3389 $pm = MediaWikiServices
::getInstance()->getPermissionManager();
3390 return $pm->quickUserCan( 'edit', $user, $title )
3391 && ( $this->getTitle()->exists() ||
3392 $pm->quickUserCan( 'create', $user, $title ) );
3396 * @return array Array in format "link name or number => 'link html'".
3398 public function getHeadLinksArray() {
3402 $config = $this->getConfig();
3404 $canonicalUrl = $this->mCanonicalUrl
;
3406 $tags['meta-generator'] = Html
::element( 'meta', [
3407 'name' => 'generator',
3408 'content' => "MediaWiki $wgVersion",
3411 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3412 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3413 // fallbacks should come before the primary value so we need to reverse the array.
3414 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3415 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3416 'name' => 'referrer',
3417 'content' => $policy,
3422 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3423 if ( $p !== 'index,follow' ) {
3424 // http://www.robotstxt.org/wc/meta-user.html
3425 // Only show if it's different from the default robots policy
3426 $tags['meta-robots'] = Html
::element( 'meta', [
3432 foreach ( $this->mMetatags
as $tag ) {
3433 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3435 $tag[0] = substr( $tag[0], 5 );
3436 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3441 $tagName = "meta-{$tag[0]}";
3442 if ( isset( $tags[$tagName] ) ) {
3443 $tagName .= $tag[1];
3445 $tags[$tagName] = Html
::element( 'meta',
3448 'content' => $tag[1]
3453 foreach ( $this->mLinktags
as $tag ) {
3454 $tags[] = Html
::element( 'link', $tag );
3457 # Universal edit button
3458 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3459 if ( $this->userCanEditOrCreate( $this->getUser(), $this->getTitle() ) ) {
3460 // Original UniversalEditButton
3461 $msg = $this->msg( 'edit' )->text();
3462 $tags['universal-edit-button'] = Html
::element( 'link', [
3463 'rel' => 'alternate',
3464 'type' => 'application/x-wiki',
3466 'href' => $this->getTitle()->getEditURL(),
3468 // Alternate edit link
3469 $tags['alternative-edit'] = Html
::element( 'link', [
3472 'href' => $this->getTitle()->getEditURL(),
3477 # Generally the order of the favicon and apple-touch-icon links
3478 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3479 # uses whichever one appears later in the HTML source. Make sure
3480 # apple-touch-icon is specified first to avoid this.
3481 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3482 $tags['apple-touch-icon'] = Html
::element( 'link', [
3483 'rel' => 'apple-touch-icon',
3484 'href' => $config->get( 'AppleTouchIcon' )
3488 if ( $config->get( 'Favicon' ) !== false ) {
3489 $tags['favicon'] = Html
::element( 'link', [
3490 'rel' => 'shortcut icon',
3491 'href' => $config->get( 'Favicon' )
3495 # OpenSearch description link
3496 $tags['opensearch'] = Html
::element( 'link', [
3498 'type' => 'application/opensearchdescription+xml',
3499 'href' => wfScript( 'opensearch_desc' ),
3500 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3503 # Real Simple Discovery link, provides auto-discovery information
3504 # for the MediaWiki API (and potentially additional custom API
3505 # support such as WordPress or Twitter-compatible APIs for a
3506 # blogging extension, etc)
3507 $tags['rsd'] = Html
::element( 'link', [
3509 'type' => 'application/rsd+xml',
3510 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3511 // Whether RSD accepts relative or protocol-relative URLs is completely
3512 // undocumented, though.
3513 'href' => wfExpandUrl( wfAppendQuery(
3515 [ 'action' => 'rsd' ] ),
3521 if ( !$config->get( 'DisableLangConversion' ) ) {
3522 $lang = $this->getTitle()->getPageLanguage();
3523 if ( $lang->hasVariants() ) {
3524 $variants = $lang->getVariants();
3525 foreach ( $variants as $variant ) {
3526 $tags["variant-$variant"] = Html
::element( 'link', [
3527 'rel' => 'alternate',
3528 'hreflang' => LanguageCode
::bcp47( $variant ),
3529 'href' => $this->getTitle()->getLocalURL(
3530 [ 'variant' => $variant ] )
3534 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3535 $tags["variant-x-default"] = Html
::element( 'link', [
3536 'rel' => 'alternate',
3537 'hreflang' => 'x-default',
3538 'href' => $this->getTitle()->getLocalURL() ] );
3543 if ( $this->copyrightUrl
!== null ) {
3544 $copyright = $this->copyrightUrl
;
3547 if ( $config->get( 'RightsPage' ) ) {
3548 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3551 $copyright = $copy->getLocalURL();
3555 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3556 $copyright = $config->get( 'RightsUrl' );
3561 $tags['copyright'] = Html
::element( 'link', [
3563 'href' => $copyright ]
3568 if ( $config->get( 'Feed' ) ) {
3571 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3572 # Use the page name for the title. In principle, this could
3573 # lead to issues with having the same name for different feeds
3574 # corresponding to the same page, but we can't avoid that at
3577 $feedLinks[] = $this->feedLink(
3580 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3582 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3587 # Recent changes feed should appear on every page (except recentchanges,
3588 # that would be redundant). Put it after the per-page feed to avoid
3589 # changing existing behavior. It's still available, probably via a
3590 # menu in your browser. Some sites might have a different feed they'd
3591 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3592 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3593 # If so, use it instead.
3594 $sitename = $config->get( 'Sitename' );
3595 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3596 if ( $overrideSiteFeed ) {
3597 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3598 // Note, this->feedLink escapes the url.
3599 $feedLinks[] = $this->feedLink(
3602 $this->msg( "site-{$type}-feed", $sitename )->text()
3605 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3606 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3607 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3608 $feedLinks[] = $this->feedLink(
3610 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3611 # For grep: 'site-rss-feed', 'site-atom-feed'
3612 $this->msg( "site-{$format}-feed", $sitename )->text()
3617 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3618 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3619 # use OutputPage::addFeedLink() instead.
3620 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3622 $tags +
= $feedLinks;
3626 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3627 if ( $canonicalUrl !== false ) {
3628 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3629 } elseif ( $this->isArticleRelated() ) {
3630 // This affects all requests where "setArticleRelated" is true. This is
3631 // typically all requests that show content (query title, curid, oldid, diff),
3632 // and all wikipage actions (edit, delete, purge, info, history etc.).
3633 // It does not apply to File pages and Special pages.
3634 // 'history' and 'info' actions address page metadata rather than the page
3635 // content itself, so they may not be canonicalized to the view page url.
3636 // TODO: this ought to be better encapsulated in the Action class.
3637 $action = Action
::getActionName( $this->getContext() );
3638 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3639 $query = "action={$action}";
3643 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3645 $reqUrl = $this->getRequest()->getRequestURL();
3646 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3649 if ( $canonicalUrl !== false ) {
3650 $tags[] = Html
::element( 'link', [
3651 'rel' => 'canonical',
3652 'href' => $canonicalUrl
3656 // Allow extensions to add, remove and/or otherwise manipulate these links
3657 // If you want only to *add* <head> links, please use the addHeadItem()
3658 // (or addHeadItems() for multiple items) method instead.
3659 // This hook is provided as a last resort for extensions to modify these
3660 // links before the output is sent to client.
3661 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3667 * Generate a "<link rel/>" for a feed.
3669 * @param string $type Feed type
3670 * @param string $url URL to the feed
3671 * @param string $text Value of the "title" attribute
3672 * @return string HTML fragment
3674 private function feedLink( $type, $url, $text ) {
3675 return Html
::element( 'link', [
3676 'rel' => 'alternate',
3677 'type' => "application/$type+xml",
3684 * Add a local or specified stylesheet, with the given media options.
3685 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3687 * @param string $style URL to the file
3688 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3689 * @param string $condition For IE conditional comments, specifying an IE version
3690 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3692 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3695 $options['media'] = $media;
3698 $options['condition'] = $condition;
3701 $options['dir'] = $dir;
3703 $this->styles
[$style] = $options;
3707 * Adds inline CSS styles
3708 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3710 * @param mixed $style_css Inline CSS
3711 * @param string $flip Set to 'flip' to flip the CSS if needed
3713 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3714 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3715 # If wanted, and the interface is right-to-left, flip the CSS
3716 $style_css = CSSJanus
::transform( $style_css, true, false );
3718 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3722 * Build exempt modules and legacy non-ResourceLoader styles.
3724 * @return string|WrappedStringList HTML
3726 protected function buildExemptModules() {
3730 // - Within modules provided by the software (core, skin, extensions),
3731 // styles from skin stylesheets should be overridden by styles
3732 // from modules dynamically loaded with JavaScript.
3733 // - Styles from site-specific, private, and user modules should override
3734 // both of the above.
3736 // The effective order for stylesheets must thus be:
3737 // 1. Page style modules, formatted server-side by ResourceLoaderClientHtml.
3738 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
3739 // 3. Styles that are site-specific, private or from the user, formatted
3740 // server-side by this function.
3742 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
3745 // Add legacy styles added through addStyle()/addInlineStyle() here
3746 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3748 // Things that go after the ResourceLoaderDynamicStyles marker
3750 $separateReq = [ 'site.styles', 'user.styles' ];
3751 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3752 if ( $moduleNames ) {
3753 $append[] = $this->makeResourceLoaderLink(
3754 array_diff( $moduleNames, $separateReq ),
3755 ResourceLoaderModule
::TYPE_STYLES
3758 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3759 // These require their own dedicated request in order to support "@import"
3760 // syntax, which is incompatible with concatenation. (T147667, T37562)
3761 $append[] = $this->makeResourceLoaderLink( $name,
3762 ResourceLoaderModule
::TYPE_STYLES
3768 $chunks[] = Html
::element(
3770 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3772 $chunks = array_merge( $chunks, $append );
3775 return self
::combineWrappedStrings( $chunks );
3781 public function buildCssLinksArray() {
3784 foreach ( $this->styles
as $file => $options ) {
3785 $link = $this->styleLink( $file, $options );
3787 $links[$file] = $link;
3794 * Generate \<link\> tags for stylesheets
3796 * @param string $style URL to the file
3797 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3798 * @return string HTML fragment
3800 protected function styleLink( $style, array $options ) {
3801 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3805 if ( isset( $options['media'] ) ) {
3806 $media = self
::transformCssMedia( $options['media'] );
3807 if ( is_null( $media ) ) {
3814 if ( substr( $style, 0, 1 ) == '/' ||
3815 substr( $style, 0, 5 ) == 'http:' ||
3816 substr( $style, 0, 6 ) == 'https:' ) {
3819 $config = $this->getConfig();
3820 // Append file hash as query parameter
3821 $url = self
::transformResourcePath(
3823 $config->get( 'StylePath' ) . '/' . $style
3827 $link = Html
::linkedStyle( $url, $media );
3829 if ( isset( $options['condition'] ) ) {
3830 $condition = htmlspecialchars( $options['condition'] );
3831 $link = "<!--[if $condition]>$link<![endif]-->";
3837 * Transform path to web-accessible static resource.
3839 * This is used to add a validation hash as query string.
3840 * This aids various behaviors:
3842 * - Put long Cache-Control max-age headers on responses for improved
3843 * cache performance.
3844 * - Get the correct version of a file as expected by the current page.
3845 * - Instantly get the updated version of a file after deployment.
3847 * Avoid using this for urls included in HTML as otherwise clients may get different
3848 * versions of a resource when navigating the site depending on when the page was cached.
3849 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3850 * an external stylesheet).
3853 * @param Config $config
3854 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3855 * @return string URL
3857 public static function transformResourcePath( Config
$config, $path ) {
3861 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3862 if ( $remotePathPrefix === '' ) {
3863 // The configured base path is required to be empty string for
3864 // wikis in the domain root
3867 $remotePath = $remotePathPrefix;
3869 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3870 // - Path is outside wgResourceBasePath, ignore.
3871 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3874 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3875 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3876 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3877 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3878 $uploadPath = $config->get( 'UploadPath' );
3879 if ( strpos( $path, $uploadPath ) === 0 ) {
3880 $localDir = $config->get( 'UploadDirectory' );
3881 $remotePathPrefix = $remotePath = $uploadPath;
3884 $path = RelPath
::getRelativePath( $path, $remotePath );
3885 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3889 * Utility method for transformResourceFilePath().
3891 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3894 * @param string $remotePathPrefix URL path prefix that points to $localPath
3895 * @param string $localPath File directory exposed at $remotePath
3896 * @param string $file Path to target file relative to $localPath
3897 * @return string URL
3899 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3900 $hash = md5_file( "$localPath/$file" );
3901 if ( $hash === false ) {
3902 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3905 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3909 * Transform "media" attribute based on request parameters
3911 * @param string $media Current value of the "media" attribute
3912 * @return string Modified value of the "media" attribute, or null to skip
3915 public static function transformCssMedia( $media ) {
3918 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3919 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3921 // Switch in on-screen display for media testing
3923 'printable' => 'print',
3924 'handheld' => 'handheld',
3926 foreach ( $switches as $switch => $targetMedia ) {
3927 if ( $wgRequest->getBool( $switch ) ) {
3928 if ( $media == $targetMedia ) {
3930 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3931 /* This regex will not attempt to understand a comma-separated media_query_list
3933 * Example supported values for $media:
3934 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3935 * Example NOT supported value for $media:
3936 * '3d-glasses, screen, print and resolution > 90dpi'
3938 * If it's a print request, we never want any kind of screen stylesheets
3939 * If it's a handheld request (currently the only other choice with a switch),
3940 * we don't want simple 'screen' but we might want screen queries that
3941 * have a max-width or something, so we'll pass all others on and let the
3942 * client do the query.
3944 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3955 * Add a wikitext-formatted message to the output.
3956 * This is equivalent to:
3958 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3960 public function addWikiMsg( /*...*/ ) {
3961 $args = func_get_args();
3962 $name = array_shift( $args );
3963 $this->addWikiMsgArray( $name, $args );
3967 * Add a wikitext-formatted message to the output.
3968 * Like addWikiMsg() except the parameters are taken as an array
3969 * instead of a variable argument list.
3971 * @param string $name
3972 * @param array $args
3974 public function addWikiMsgArray( $name, $args ) {
3975 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3979 * This function takes a number of message/argument specifications, wraps them in
3980 * some overall structure, and then parses the result and adds it to the output.
3982 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3983 * and so on. The subsequent arguments may be either
3984 * 1) strings, in which case they are message names, or
3985 * 2) arrays, in which case, within each array, the first element is the message
3986 * name, and subsequent elements are the parameters to that message.
3988 * Don't use this for messages that are not in the user's interface language.
3992 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3996 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
3997 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3999 * The newline after the opening div is needed in some wikitext. See T21226.
4001 * @param string $wrap
4003 public function wrapWikiMsg( $wrap /*, ...*/ ) {
4004 $msgSpecs = func_get_args();
4005 array_shift( $msgSpecs );
4006 $msgSpecs = array_values( $msgSpecs );
4008 foreach ( $msgSpecs as $n => $spec ) {
4009 if ( is_array( $spec ) ) {
4011 $name = array_shift( $args );
4016 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
4018 $this->addWikiTextAsInterface( $s );
4022 * Whether the output has a table of contents
4026 public function isTOCEnabled() {
4027 return $this->mEnableTOC
;
4031 * Helper function to setup the PHP implementation of OOUI to use in this request.
4034 * @param string $skinName The Skin name to determine the correct OOUI theme
4035 * @param string $dir Language direction
4037 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4038 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4039 $theme = $themes[$skinName] ??
$themes['default'];
4040 // For example, 'OOUI\WikimediaUITheme'.
4041 $themeClass = "OOUI\\{$theme}Theme";
4042 OOUI\Theme
::setSingleton( new $themeClass() );
4043 OOUI\Element
::setDefaultDir( $dir );
4047 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4048 * MediaWiki and this OutputPage instance.
4052 public function enableOOUI() {
4054 strtolower( $this->getSkin()->getSkinName() ),
4055 $this->getLanguage()->getDir()
4057 $this->addModuleStyles( [
4058 'oojs-ui-core.styles',
4059 'oojs-ui.styles.indicators',
4060 'mediawiki.widgets.styles',
4061 'oojs-ui-core.icons',
4066 * Get (and set if not yet set) the CSP nonce.
4068 * This value needs to be included in any <script> tags on the
4071 * @return string|bool Nonce or false to mean don't output nonce
4074 public function getCSPNonce() {
4075 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4078 if ( $this->CSPNonce
=== null ) {
4079 // XXX It might be expensive to generate randomness
4080 // on every request, on Windows.
4081 $rand = random_bytes( 15 );
4082 $this->CSPNonce
= base64_encode( $rand );
4084 return $this->CSPNonce
;