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 array 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> */
58 private $mPageTitle = '';
61 * @var string The displayed title of the page. Different from page title
62 * if overridden by display title magic word or hooks. Can contain safe
63 * HTML. Different from page title which may contain messages such as
64 * "Editing X" which is displayed in h1. This can be used for other places
65 * where the page name is referred on the page.
67 private $displayTitle;
70 * @var string Contains all of the "<body>" content. Should be private we
71 * got set/get accessors and the append() method.
73 public $mBodytext = '';
75 /** @var string Stores contents of "<title>" tag */
76 private $mHTMLtitle = '';
79 * @var bool Is the displayed content related to the source of the
80 * corresponding wiki article.
82 private $mIsArticle = false;
84 /** @var bool Stores "article flag" toggle. */
85 private $mIsArticleRelated = true;
87 /** @var bool Is the content subject to copyright */
88 private $mHasCopyright = false;
91 * @var bool We have to set isPrintable(). Some pages should
92 * never be printed (ex: redirections).
94 private $mPrintable = false;
97 * @var array Contains the page subtitle. Special pages usually have some
98 * links here. Don't confuse with site subtitle added by skins.
100 private $mSubtitle = [];
103 public $mRedirect = '';
106 protected $mStatusCode;
109 * @var string Used for sending cache control.
110 * The whole caching system should probably be moved into its own class.
112 protected $mLastModified = '';
115 protected $mCategoryLinks = [];
118 protected $mCategories = [
124 protected $mIndicators = [];
126 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
127 private $mLanguageLinks = [];
130 * Used for JavaScript (predates ResourceLoader)
131 * @todo We should split JS / CSS.
132 * mScripts content is inserted as is in "<head>" by Skin. This might
133 * contain either a link to a stylesheet or inline CSS.
135 private $mScripts = '';
137 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
138 protected $mInlineStyles = '';
141 * @var string Used by skin template.
142 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
144 public $mPageLinkTitle = '';
146 /** @var array Array of elements in "<head>". Parser might add its own headers! */
147 protected $mHeadItems = [];
149 /** @var array Additional <body> classes; there are also <body> classes from other sources */
150 protected $mAdditionalBodyClasses = [];
153 protected $mModules = [];
156 protected $mModuleStyles = [];
158 /** @var ResourceLoader */
159 protected $mResourceLoader;
161 /** @var ResourceLoaderClientHtml */
164 /** @var ResourceLoaderContext */
165 private $rlClientContext;
168 private $rlExemptStyleModules;
171 protected $mJsConfigVars = [];
174 protected $mTemplateIds = [];
177 protected $mImageTimeKeys = [];
180 public $mRedirectCode = '';
182 protected $mFeedLinksAppendQuery = null;
185 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
186 * @see ResourceLoaderModule::$origin
187 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
189 protected $mAllowedModules = [
190 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
193 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
194 protected $mDoNothing = false;
199 protected $mContainsNewMagic = 0;
202 * lazy initialised, use parserOptions()
205 protected $mParserOptions = null;
208 * Handles the Atom / RSS links.
209 * We probably only support Atom in 2011.
210 * @see $wgAdvertisedFeedTypes
212 private $mFeedLinks = [];
214 // Gwicke work on squid caching? Roughly from 2003.
215 protected $mEnableClientCache = true;
217 /** @var bool Flag if output should only contain the body of the article. */
218 private $mArticleBodyOnly = false;
221 protected $mNewSectionLink = false;
224 protected $mHideNewSectionLink = false;
227 * @var bool Comes from the parser. This was probably made to load CSS/JS
228 * only if we had "<gallery>". Used directly in CategoryPage.php.
229 * Looks like ResourceLoader can replace this.
231 public $mNoGallery = false;
233 /** @var int Cache stuff. Looks like mEnableClientCache */
234 protected $mCdnMaxage = 0;
235 /** @var int Upper limit on mCdnMaxage */
236 protected $mCdnMaxageLimit = INF
;
239 * @var bool Controls if anti-clickjacking / frame-breaking headers will
240 * be sent. This should be done for pages where edit actions are possible.
241 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
243 protected $mPreventClickjacking = true;
245 /** @var int To include the variable {{REVISIONID}} */
246 private $mRevisionId = null;
249 private $mRevisionTimestamp = null;
252 protected $mFileVersion = null;
255 * @var array An array of stylesheet filenames (relative from skins path),
256 * with options for CSS media, IE conditions, and RTL/LTR direction.
257 * For internal use; add settings in the skin via $this->addStyle()
259 * Style again! This seems like a code duplication since we already have
260 * mStyles. This is what makes Open Source amazing.
262 protected $styles = [];
264 private $mIndexPolicy = 'index';
265 private $mFollowPolicy = 'follow';
268 * @var array Headers that cause the cache to vary. Key is header name,
269 * value should always be null. (Value was an array of options for
270 * the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
272 private $mVaryHeader = [
273 'Accept-Encoding' => null,
277 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
282 private $mRedirectedFrom = null;
285 * Additional key => value data
287 private $mProperties = [];
290 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
292 private $mTarget = null;
295 * @var bool Whether parser output contains a table of contents
297 private $mEnableTOC = false;
300 * @var string|null The URL to send in a <link> element with rel=license
302 private $copyrightUrl;
304 /** @var array Profiling data */
305 private $limitReportJSData = [];
307 /** @var array Map Title to Content */
308 private $contentOverrides = [];
310 /** @var callable[] */
311 private $contentOverrideCallbacks = [];
314 * Link: header contents
316 private $mLinkHeader = [];
319 * @var string The nonce for Content-Security-Policy
324 * @var array A cache of the names of the cookies that will influence the cache
326 private static $cacheVaryCookies = null;
329 * Constructor for OutputPage. This should not be called directly.
330 * Instead a new RequestContext should be created and it will implicitly create
331 * a OutputPage tied to that context.
332 * @param IContextSource $context
334 function __construct( IContextSource
$context ) {
335 $this->setContext( $context );
339 * Redirect to $url rather than displaying the normal page
342 * @param string $responsecode HTTP status code
344 public function redirect( $url, $responsecode = '302' ) {
345 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
346 $this->mRedirect
= str_replace( "\n", '', $url );
347 $this->mRedirectCode
= $responsecode;
351 * Get the URL to redirect to, or an empty string if not redirect URL set
355 public function getRedirect() {
356 return $this->mRedirect
;
360 * Set the copyright URL to send with the output.
361 * Empty string to omit, null to reset.
365 * @param string|null $url
367 public function setCopyrightUrl( $url ) {
368 $this->copyrightUrl
= $url;
372 * Set the HTTP status code to send with the output.
374 * @param int $statusCode
376 public function setStatusCode( $statusCode ) {
377 $this->mStatusCode
= $statusCode;
381 * Add a new "<meta>" tag
382 * To add an http-equiv meta tag, precede the name with "http:"
384 * @param string $name Name of the meta tag
385 * @param string $val Value of the meta tag
387 function addMeta( $name, $val ) {
388 array_push( $this->mMetatags
, [ $name, $val ] );
392 * Returns the current <meta> tags
397 public function getMetaTags() {
398 return $this->mMetatags
;
402 * Add a new \<link\> tag to the page header.
404 * Note: use setCanonicalUrl() for rel=canonical.
406 * @param array $linkarr Associative array of attributes.
408 function addLink( array $linkarr ) {
409 array_push( $this->mLinktags
, $linkarr );
413 * Returns the current <link> tags
418 public function getLinkTags() {
419 return $this->mLinktags
;
423 * Set the URL to be used for the <link rel=canonical>. This should be used
424 * in preference to addLink(), to avoid duplicate link tags.
427 function setCanonicalUrl( $url ) {
428 $this->mCanonicalUrl
= $url;
432 * Returns the URL to be used for the <link rel=canonical> if
436 * @return bool|string
438 public function getCanonicalUrl() {
439 return $this->mCanonicalUrl
;
443 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
444 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
447 * @param string $script Raw HTML
449 function addScript( $script ) {
450 $this->mScripts
.= $script;
454 * Add a JavaScript file to be loaded as `<script>` on this page.
456 * Internal use only. Use OutputPage::addModules() if possible.
458 * @param string $file URL to file (absolute path, protocol-relative, or full url)
459 * @param string|null $unused Previously used to change the cache-busting query parameter
461 public function addScriptFile( $file, $unused = null ) {
462 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
466 * Add a self-contained script tag with the given contents
467 * Internal use only. Use OutputPage::addModules() if possible.
469 * @param string $script JavaScript text, no script tags
471 public function addInlineScript( $script ) {
472 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
476 * Filter an array of modules to remove insufficiently trustworthy members, and modules
477 * which are no longer registered (eg a page is cached before an extension is disabled)
478 * @param array $modules
479 * @param string|null $position Unused
480 * @param string $type
483 protected function filterModules( array $modules, $position = null,
484 $type = ResourceLoaderModule
::TYPE_COMBINED
486 $resourceLoader = $this->getResourceLoader();
487 $filteredModules = [];
488 foreach ( $modules as $val ) {
489 $module = $resourceLoader->getModule( $val );
490 if ( $module instanceof ResourceLoaderModule
491 && $module->getOrigin() <= $this->getAllowedModules( $type )
493 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
494 $this->warnModuleTargetFilter( $module->getName() );
497 $filteredModules[] = $val;
500 return $filteredModules;
503 private function warnModuleTargetFilter( $moduleName ) {
504 static $warnings = [];
505 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
508 $warnings[$this->mTarget
][$moduleName] = true;
509 $this->getResourceLoader()->getLogger()->debug(
510 'Module "{module}" not loadable on target "{target}".',
512 'module' => $moduleName,
513 'target' => $this->mTarget
,
519 * Get the list of modules to include on this page
521 * @param bool $filter Whether to filter out insufficiently trustworthy modules
522 * @param string|null $position Unused
523 * @param string $param
524 * @param string $type
525 * @return array Array of module names
527 public function getModules( $filter = false, $position = null, $param = 'mModules',
528 $type = ResourceLoaderModule
::TYPE_COMBINED
530 $modules = array_values( array_unique( $this->$param ) );
532 ?
$this->filterModules( $modules, null, $type )
537 * Load one or more ResourceLoader modules on this page.
539 * @param string|array $modules Module name (string) or array of module names
541 public function addModules( $modules ) {
542 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
546 * Get the list of style-only modules to load on this page.
548 * @param bool $filter
549 * @param string|null $position Unused
550 * @return array Array of module names
552 public function getModuleStyles( $filter = false, $position = null ) {
553 return $this->getModules( $filter, null, 'mModuleStyles',
554 ResourceLoaderModule
::TYPE_STYLES
559 * Load the styles of one or more ResourceLoader modules on this page.
561 * Module styles added through this function will be loaded as a stylesheet,
562 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
563 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
565 * @param string|array $modules Module name (string) or array of module names
567 public function addModuleStyles( $modules ) {
568 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
572 * @return null|string ResourceLoader target
574 public function getTarget() {
575 return $this->mTarget
;
579 * Sets ResourceLoader target for load.php links. If null, will be omitted
581 * @param string|null $target
583 public function setTarget( $target ) {
584 $this->mTarget
= $target;
588 * Add a mapping from a LinkTarget to a Content, for things like page preview.
589 * @see self::addContentOverrideCallback()
591 * @param LinkTarget $target
592 * @param Content $content
594 public function addContentOverride( LinkTarget
$target, Content
$content ) {
595 if ( !$this->contentOverrides
) {
596 // Register a callback for $this->contentOverrides on the first call
597 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
598 $key = $target->getNamespace() . ':' . $target->getDBkey();
599 return $this->contentOverrides
[$key] ??
null;
603 $key = $target->getNamespace() . ':' . $target->getDBkey();
604 $this->contentOverrides
[$key] = $content;
608 * Add a callback for mapping from a Title to a Content object, for things
610 * @see ResourceLoaderContext::getContentOverrideCallback()
612 * @param callable $callback
614 public function addContentOverrideCallback( callable
$callback ) {
615 $this->contentOverrideCallbacks
[] = $callback;
619 * Get an array of head items
623 function getHeadItemsArray() {
624 return $this->mHeadItems
;
628 * Add or replace a head item to the output
630 * Whenever possible, use more specific options like ResourceLoader modules,
631 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
632 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
633 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
634 * This would be your very LAST fallback.
636 * @param string $name Item name
637 * @param string $value Raw HTML
639 public function addHeadItem( $name, $value ) {
640 $this->mHeadItems
[$name] = $value;
644 * Add one or more head items to the output
647 * @param string|string[] $values Raw HTML
649 public function addHeadItems( $values ) {
650 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
654 * Check if the header item $name is already set
656 * @param string $name Item name
659 public function hasHeadItem( $name ) {
660 return isset( $this->mHeadItems
[$name] );
664 * Add a class to the <body> element
667 * @param string|string[] $classes One or more classes to add
669 public function addBodyClasses( $classes ) {
670 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
674 * Set whether the output should only contain the body of the article,
675 * without any skin, sidebar, etc.
676 * Used e.g. when calling with "action=render".
678 * @param bool $only Whether to output only the body of the article
680 public function setArticleBodyOnly( $only ) {
681 $this->mArticleBodyOnly
= $only;
685 * Return whether the output will contain only the body of the article
689 public function getArticleBodyOnly() {
690 return $this->mArticleBodyOnly
;
694 * Set an additional output property
697 * @param string $name
698 * @param mixed $value
700 public function setProperty( $name, $value ) {
701 $this->mProperties
[$name] = $value;
705 * Get an additional output property
708 * @param string $name
709 * @return mixed Property value or null if not found
711 public function getProperty( $name ) {
712 return $this->mProperties
[$name] ??
null;
716 * checkLastModified tells the client to use the client-cached page if
717 * possible. If successful, the OutputPage is disabled so that
718 * any future call to OutputPage->output() have no effect.
720 * Side effect: sets mLastModified for Last-Modified header
722 * @param string $timestamp
724 * @return bool True if cache-ok headers was sent.
726 public function checkLastModified( $timestamp ) {
727 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
728 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
731 $config = $this->getConfig();
732 if ( !$config->get( 'CachePages' ) ) {
733 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
737 $timestamp = wfTimestamp( TS_MW
, $timestamp );
739 'page' => $timestamp,
740 'user' => $this->getUser()->getTouched(),
741 'epoch' => $config->get( 'CacheEpoch' )
743 if ( $config->get( 'UseCdn' ) ) {
744 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
746 $config->get( 'CdnMaxAge' )
749 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
751 $maxModified = max( $modifiedTimes );
752 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
754 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
755 if ( $clientHeader === false ) {
756 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
760 # IE sends sizes after the date like this:
761 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
762 # this breaks strtotime().
763 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
765 Wikimedia\
suppressWarnings(); // E_STRICT system time warnings
766 $clientHeaderTime = strtotime( $clientHeader );
767 Wikimedia\restoreWarnings
();
768 if ( !$clientHeaderTime ) {
770 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
773 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
777 foreach ( $modifiedTimes as $name => $value ) {
778 if ( $info !== '' ) {
781 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
784 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
785 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
786 wfDebug( __METHOD__
. ": effective Last-Modified: " .
787 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
788 if ( $clientHeaderTime < $maxModified ) {
789 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
794 # Give a 304 Not Modified response code and disable body output
795 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
796 ini_set( 'zlib.output_compression', 0 );
797 $this->getRequest()->response()->statusHeader( 304 );
798 $this->sendCacheControl();
801 // Don't output a compressed blob when using ob_gzhandler;
802 // it's technically against HTTP spec and seems to confuse
803 // Firefox when the response gets split over two packets.
804 wfClearOutputBuffers();
810 * @param int $reqTime Time of request (eg. now)
811 * @param int $maxAge Cache TTL in seconds
812 * @return int Timestamp
814 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
815 // Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
816 // because even if the wiki page content hasn't changed since, static
817 // resources may have changed (skin HTML, interface messages, urls, etc.)
818 // and must roll-over in a timely manner (T46570)
819 return $reqTime - $maxAge;
823 * Override the last modified timestamp
825 * @param string $timestamp New timestamp, in a format readable by
828 public function setLastModified( $timestamp ) {
829 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
833 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
835 * @param string $policy The literal string to output as the contents of
836 * the meta tag. Will be parsed according to the spec and output in
840 public function setRobotPolicy( $policy ) {
841 $policy = Article
::formatRobotPolicy( $policy );
843 if ( isset( $policy['index'] ) ) {
844 $this->setIndexPolicy( $policy['index'] );
846 if ( isset( $policy['follow'] ) ) {
847 $this->setFollowPolicy( $policy['follow'] );
852 * Set the index policy for the page, but leave the follow policy un-
855 * @param string $policy Either 'index' or 'noindex'.
858 public function setIndexPolicy( $policy ) {
859 $policy = trim( $policy );
860 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
861 $this->mIndexPolicy
= $policy;
866 * Set the follow policy for the page, but leave the index policy un-
869 * @param string $policy Either 'follow' or 'nofollow'.
872 public function setFollowPolicy( $policy ) {
873 $policy = trim( $policy );
874 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
875 $this->mFollowPolicy
= $policy;
880 * "HTML title" means the contents of "<title>".
881 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
883 * @param string|Message $name
885 public function setHTMLTitle( $name ) {
886 if ( $name instanceof Message
) {
887 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
889 $this->mHTMLtitle
= $name;
894 * Return the "HTML title", i.e. the content of the "<title>" tag.
898 public function getHTMLTitle() {
899 return $this->mHTMLtitle
;
903 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
907 public function setRedirectedFrom( $t ) {
908 $this->mRedirectedFrom
= $t;
912 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
913 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
914 * but not bad tags like \<script\>. This function automatically sets
915 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
916 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
917 * good tags like \<i\> will be dropped entirely.
919 * @param string|Message $name
920 * @param-taint $name tainted
921 * Phan-taint-check gets very confused by $name being either a string or a Message
923 public function setPageTitle( $name ) {
924 if ( $name instanceof Message
) {
925 $name = $name->setContext( $this->getContext() )->text();
928 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
929 # but leave "<i>foobar</i>" alone
930 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
931 $this->mPageTitle
= $nameWithTags;
933 # change "<i>foo&bar</i>" to "foo&bar"
935 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer
::stripAllTags( $nameWithTags ) )
936 ->inContentLanguage()
941 * Return the "page title", i.e. the content of the \<h1\> tag.
945 public function getPageTitle() {
946 return $this->mPageTitle
;
950 * Same as page title but only contains name of the page, not any other text.
953 * @param string $html Page title text.
954 * @see OutputPage::setPageTitle
956 public function setDisplayTitle( $html ) {
957 $this->displayTitle
= $html;
961 * Returns page display title.
963 * Performs some normalization, but this not as strict the magic word.
966 * @return string HTML
968 public function getDisplayTitle() {
969 $html = $this->displayTitle
;
970 if ( $html === null ) {
971 $html = $this->getTitle()->getPrefixedText();
974 return Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $html ) );
978 * Returns page display title without namespace prefix if possible.
981 * @return string HTML
983 public function getUnprefixedDisplayTitle() {
984 $text = $this->getDisplayTitle();
985 $nsPrefix = $this->getTitle()->getNsText() . ':';
986 $prefix = preg_quote( $nsPrefix, '/' );
988 return preg_replace( "/^$prefix/i", '', $text );
992 * Set the Title object to use
996 public function setTitle( Title
$t ) {
997 $this->getContext()->setTitle( $t );
1001 * Replace the subtitle with $str
1003 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1005 public function setSubtitle( $str ) {
1006 $this->clearSubtitle();
1007 $this->addSubtitle( $str );
1011 * Add $str to the subtitle
1013 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1015 public function addSubtitle( $str ) {
1016 if ( $str instanceof Message
) {
1017 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1019 $this->mSubtitle
[] = $str;
1024 * Build message object for a subtitle containing a backlink to a page
1026 * @param Title $title Title to link to
1027 * @param array $query Array of additional parameters to include in the link
1031 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1032 if ( $title->isRedirect() ) {
1033 $query['redirect'] = 'no';
1035 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1036 return wfMessage( 'backlinksubtitle' )
1037 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1041 * Add a subtitle containing a backlink to a page
1043 * @param Title $title Title to link to
1044 * @param array $query Array of additional parameters to include in the link
1046 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1047 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1051 * Clear the subtitles
1053 public function clearSubtitle() {
1054 $this->mSubtitle
= [];
1062 public function getSubtitle() {
1063 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1067 * Set the page as printable, i.e. it'll be displayed with all
1068 * print styles included
1070 public function setPrintable() {
1071 $this->mPrintable
= true;
1075 * Return whether the page is "printable"
1079 public function isPrintable() {
1080 return $this->mPrintable
;
1084 * Disable output completely, i.e. calling output() will have no effect
1086 public function disable() {
1087 $this->mDoNothing
= true;
1091 * Return whether the output will be completely disabled
1095 public function isDisabled() {
1096 return $this->mDoNothing
;
1100 * Show an "add new section" link?
1104 public function showNewSectionLink() {
1105 return $this->mNewSectionLink
;
1109 * Forcibly hide the new section link?
1113 public function forceHideNewSectionLink() {
1114 return $this->mHideNewSectionLink
;
1118 * Add or remove feed links in the page header
1119 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1120 * for the new version
1121 * @see addFeedLink()
1123 * @param bool $show True: add default feeds, false: remove all feeds
1125 public function setSyndicated( $show = true ) {
1127 $this->setFeedAppendQuery( false );
1129 $this->mFeedLinks
= [];
1134 * Return effective list of advertised feed types
1135 * @see addFeedLink()
1137 * @return array Array of feed type names ( 'rss', 'atom' )
1139 protected function getAdvertisedFeedTypes() {
1140 if ( $this->getConfig()->get( 'Feed' ) ) {
1141 return $this->getConfig()->get( 'AdvertisedFeedTypes' );
1148 * Add default feeds to the page header
1149 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1150 * for the new version
1151 * @see addFeedLink()
1153 * @param string $val Query to append to feed links or false to output
1156 public function setFeedAppendQuery( $val ) {
1157 $this->mFeedLinks
= [];
1159 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1160 $query = "feed=$type";
1161 if ( is_string( $val ) ) {
1162 $query .= '&' . $val;
1164 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1169 * Add a feed link to the page header
1171 * @param string $format Feed type, should be a key of $wgFeedClasses
1172 * @param string $href URL
1174 public function addFeedLink( $format, $href ) {
1175 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1176 $this->mFeedLinks
[$format] = $href;
1181 * Should we output feed links for this page?
1184 public function isSyndicated() {
1185 return count( $this->mFeedLinks
) > 0;
1189 * Return URLs for each supported syndication format for this page.
1190 * @return array Associating format keys with URLs
1192 public function getSyndicationLinks() {
1193 return $this->mFeedLinks
;
1197 * Will currently always return null
1201 public function getFeedAppendQuery() {
1202 return $this->mFeedLinksAppendQuery
;
1206 * Set whether the displayed content is related to the source of the
1207 * corresponding article on the wiki
1208 * Setting true will cause the change "article related" toggle to true
1210 * @param bool $newVal
1212 public function setArticleFlag( $newVal ) {
1213 $this->mIsArticle
= $newVal;
1215 $this->mIsArticleRelated
= $newVal;
1220 * Return whether the content displayed page is related to the source of
1221 * the corresponding article on the wiki
1225 public function isArticle() {
1226 return $this->mIsArticle
;
1230 * Set whether this page is related an article on the wiki
1231 * Setting false will cause the change of "article flag" toggle to false
1233 * @param bool $newVal
1235 public function setArticleRelated( $newVal ) {
1236 $this->mIsArticleRelated
= $newVal;
1238 $this->mIsArticle
= false;
1243 * Return whether this page is related an article on the wiki
1247 public function isArticleRelated() {
1248 return $this->mIsArticleRelated
;
1252 * Set whether the standard copyright should be shown for the current page.
1254 * @param bool $hasCopyright
1256 public function setCopyright( $hasCopyright ) {
1257 $this->mHasCopyright
= $hasCopyright;
1261 * Return whether the standard copyright should be shown for the current page.
1262 * By default, it is true for all articles but other pages
1263 * can signal it by using setCopyright( true ).
1265 * Used by SkinTemplate to decided whether to show the copyright.
1269 public function showsCopyright() {
1270 return $this->isArticle() ||
$this->mHasCopyright
;
1274 * Add new language links
1276 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1277 * (e.g. 'fr:Test page')
1279 public function addLanguageLinks( array $newLinkArray ) {
1280 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1284 * Reset the language links and add new language links
1286 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1287 * (e.g. 'fr:Test page')
1289 public function setLanguageLinks( array $newLinkArray ) {
1290 $this->mLanguageLinks
= $newLinkArray;
1294 * Get the list of language links
1296 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1298 public function getLanguageLinks() {
1299 return $this->mLanguageLinks
;
1303 * Add an array of categories, with names in the keys
1305 * @param array $categories Mapping category name => sort key
1307 public function addCategoryLinks( array $categories ) {
1308 if ( !$categories ) {
1312 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1314 # Set all the values to 'normal'.
1315 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1317 # Mark hidden categories
1318 foreach ( $res as $row ) {
1319 if ( isset( $row->pp_value
) ) {
1320 $categories[$row->page_title
] = 'hidden';
1324 // Avoid PHP 7.1 warning of passing $this by reference
1325 $outputPage = $this;
1326 # Add the remaining categories to the skin
1328 'OutputPageMakeCategoryLinks',
1329 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1331 $services = MediaWikiServices
::getInstance();
1332 $linkRenderer = $services->getLinkRenderer();
1333 foreach ( $categories as $category => $type ) {
1334 // array keys will cast numeric category names to ints, so cast back to string
1335 $category = (string)$category;
1336 $origcategory = $category;
1337 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1341 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1342 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1345 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1346 $this->mCategories
[$type][] = $title->getText();
1347 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1353 * @param array $categories
1354 * @return bool|IResultWrapper
1356 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1357 # Add the links to a LinkBatch
1358 $arr = [ NS_CATEGORY
=> $categories ];
1359 $lb = new LinkBatch
;
1360 $lb->setArray( $arr );
1362 # Fetch existence plus the hiddencat property
1363 $dbr = wfGetDB( DB_REPLICA
);
1364 $fields = array_merge(
1365 LinkCache
::getSelectFields(),
1366 [ 'page_namespace', 'page_title', 'pp_value' ]
1369 $res = $dbr->select( [ 'page', 'page_props' ],
1371 $lb->constructSet( 'page', $dbr ),
1374 [ 'page_props' => [ 'LEFT JOIN', [
1375 'pp_propname' => 'hiddencat',
1380 # Add the results to the link cache
1381 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1382 $lb->addResultToCache( $linkCache, $res );
1388 * Reset the category links (but not the category list) and add $categories
1390 * @param array $categories Mapping category name => sort key
1392 public function setCategoryLinks( array $categories ) {
1393 $this->mCategoryLinks
= [];
1394 $this->addCategoryLinks( $categories );
1398 * Get the list of category links, in a 2-D array with the following format:
1399 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1400 * hidden categories) and $link a HTML fragment with a link to the category
1405 public function getCategoryLinks() {
1406 return $this->mCategoryLinks
;
1410 * Get the list of category names this page belongs to.
1412 * @param string $type The type of categories which should be returned. Possible values:
1413 * * all: all categories of all types
1414 * * hidden: only the hidden categories
1415 * * normal: all categories, except hidden categories
1416 * @return array Array of strings
1418 public function getCategories( $type = 'all' ) {
1419 if ( $type === 'all' ) {
1420 $allCategories = [];
1421 foreach ( $this->mCategories
as $categories ) {
1422 $allCategories = array_merge( $allCategories, $categories );
1424 return $allCategories;
1426 if ( !isset( $this->mCategories
[$type] ) ) {
1427 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1429 return $this->mCategories
[$type];
1433 * Add an array of indicators, with their identifiers as array
1434 * keys and HTML contents as values.
1436 * In case of duplicate keys, existing values are overwritten.
1438 * @param array $indicators
1441 public function setIndicators( array $indicators ) {
1442 $this->mIndicators
= $indicators +
$this->mIndicators
;
1443 // Keep ordered by key
1444 ksort( $this->mIndicators
);
1448 * Get the indicators associated with this page.
1450 * The array will be internally ordered by item keys.
1452 * @return array Keys: identifiers, values: HTML contents
1455 public function getIndicators() {
1456 return $this->mIndicators
;
1460 * Adds help link with an icon via page indicators.
1461 * Link target can be overridden by a local message containing a wikilink:
1462 * the message key is: lowercase action or special page name + '-helppage'.
1463 * @param string $to Target MediaWiki.org page title or encoded URL.
1464 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1467 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1468 $this->addModuleStyles( 'mediawiki.helplink' );
1469 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1471 if ( $overrideBaseUrl ) {
1474 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1475 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1478 $link = Html
::rawElement(
1482 'target' => '_blank',
1483 'class' => 'mw-helplink',
1488 $this->setIndicators( [ 'mw-helplink' => $link ] );
1492 * Do not allow scripts which can be modified by wiki users to load on this page;
1493 * only allow scripts bundled with, or generated by, the software.
1494 * Site-wide styles are controlled by a config setting, since they can be
1495 * used to create a custom skin/theme, but not user-specific ones.
1497 * @todo this should be given a more accurate name
1499 public function disallowUserJs() {
1500 $this->reduceAllowedModules(
1501 ResourceLoaderModule
::TYPE_SCRIPTS
,
1502 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1505 // Site-wide styles are controlled by a config setting, see T73621
1506 // for background on why. User styles are never allowed.
1507 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1508 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1510 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1512 $this->reduceAllowedModules(
1513 ResourceLoaderModule
::TYPE_STYLES
,
1519 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1520 * @see ResourceLoaderModule::$origin
1521 * @param string $type ResourceLoaderModule TYPE_ constant
1522 * @return int ResourceLoaderModule ORIGIN_ class constant
1524 public function getAllowedModules( $type ) {
1525 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1526 return min( array_values( $this->mAllowedModules
) );
1528 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1533 * Limit the highest level of CSS/JS untrustworthiness allowed.
1535 * If passed the same or a higher level than the current level of untrustworthiness set, the
1536 * level will remain unchanged.
1538 * @param string $type
1539 * @param int $level ResourceLoaderModule class constant
1541 public function reduceAllowedModules( $type, $level ) {
1542 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1546 * Prepend $text to the body HTML
1548 * @param string $text HTML
1550 public function prependHTML( $text ) {
1551 $this->mBodytext
= $text . $this->mBodytext
;
1555 * Append $text to the body HTML
1557 * @param string $text HTML
1559 public function addHTML( $text ) {
1560 $this->mBodytext
.= $text;
1564 * Shortcut for adding an Html::element via addHTML.
1568 * @param string $element
1569 * @param array $attribs
1570 * @param string $contents
1572 public function addElement( $element, array $attribs = [], $contents = '' ) {
1573 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1577 * Clear the body HTML
1579 public function clearHTML() {
1580 $this->mBodytext
= '';
1586 * @return string HTML
1588 public function getHTML() {
1589 return $this->mBodytext
;
1593 * Get/set the ParserOptions object to use for wikitext parsing
1595 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1596 * current ParserOption object. This parameter is deprecated since 1.31.
1597 * @return ParserOptions
1599 public function parserOptions( $options = null ) {
1600 if ( $options !== null ) {
1601 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1604 if ( $options !== null && !empty( $options->isBogus
) ) {
1605 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1606 // been changed somehow, and keep it if so.
1607 $anonPO = ParserOptions
::newFromAnon();
1608 $anonPO->setAllowUnsafeRawHtml( false );
1609 if ( !$options->matches( $anonPO ) ) {
1610 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1611 $options->isBogus
= false;
1615 if ( !$this->mParserOptions
) {
1616 if ( !$this->getUser()->isSafeToLoad() ) {
1617 // $wgUser isn't unstubbable yet, so don't try to get a
1618 // ParserOptions for it. And don't cache this ParserOptions
1620 $po = ParserOptions
::newFromAnon();
1621 $po->setAllowUnsafeRawHtml( false );
1622 $po->isBogus
= true;
1623 if ( $options !== null ) {
1624 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1629 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1630 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1633 if ( $options !== null && !empty( $options->isBogus
) ) {
1634 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1636 return wfSetVar( $this->mParserOptions
, null, true );
1638 return wfSetVar( $this->mParserOptions
, $options );
1643 * Set the revision ID which will be seen by the wiki text parser
1644 * for things such as embedded {{REVISIONID}} variable use.
1646 * @param int|null $revid A positive integer, or null
1647 * @return mixed Previous value
1649 public function setRevisionId( $revid ) {
1650 $val = is_null( $revid ) ?
null : intval( $revid );
1651 return wfSetVar( $this->mRevisionId
, $val, true );
1655 * Get the displayed revision ID
1659 public function getRevisionId() {
1660 return $this->mRevisionId
;
1664 * Set the timestamp of the revision which will be displayed. This is used
1665 * to avoid a extra DB call in Skin::lastModified().
1667 * @param string|null $timestamp
1668 * @return mixed Previous value
1670 public function setRevisionTimestamp( $timestamp ) {
1671 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1675 * Get the timestamp of displayed revision.
1676 * This will be null if not filled by setRevisionTimestamp().
1678 * @return string|null
1680 public function getRevisionTimestamp() {
1681 return $this->mRevisionTimestamp
;
1685 * Set the displayed file version
1687 * @param File|null $file
1688 * @return mixed Previous value
1690 public function setFileVersion( $file ) {
1692 if ( $file instanceof File
&& $file->exists() ) {
1693 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1695 return wfSetVar( $this->mFileVersion
, $val, true );
1699 * Get the displayed file version
1701 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1703 public function getFileVersion() {
1704 return $this->mFileVersion
;
1708 * Get the templates used on this page
1710 * @return array (namespace => dbKey => revId)
1713 public function getTemplateIds() {
1714 return $this->mTemplateIds
;
1718 * Get the files used on this page
1720 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1723 public function getFileSearchOptions() {
1724 return $this->mImageTimeKeys
;
1728 * Convert wikitext *in the user interface language* to HTML and
1729 * add it to the buffer. The result will not be
1730 * language-converted, as user interface messages are already
1731 * localized into a specific variant. Assumes that the current
1732 * page title will be used if optional $title is not
1733 * provided. Output will be tidy.
1735 * @param string $text Wikitext in the user interface language
1736 * @param bool $linestart Is this the start of a line? (Defaults to true)
1737 * @param Title|null $title Optional title to use; default of `null`
1738 * means use current page title.
1739 * @throws MWException if $title is not provided and OutputPage::getTitle()
1743 public function addWikiTextAsInterface(
1744 $text, $linestart = true, Title
$title = null
1746 if ( $title === null ) {
1747 $title = $this->getTitle();
1750 throw new MWException( 'Title is null' );
1752 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1756 * Convert wikitext *in the user interface language* to HTML and
1757 * add it to the buffer with a `<div class="$wrapperClass">`
1758 * wrapper. The result will not be language-converted, as user
1759 * interface messages as already localized into a specific
1760 * variant. The $text will be parsed in start-of-line context.
1761 * Output will be tidy.
1763 * @param string $wrapperClass The class attribute value for the <div>
1764 * wrapper in the output HTML
1765 * @param string $text Wikitext in the user interface language
1768 public function wrapWikiTextAsInterface(
1769 $wrapperClass, $text
1771 $this->addWikiTextTitleInternal(
1772 $text, $this->getTitle(),
1773 /*linestart*/true, /*interface*/true,
1779 * Convert wikitext *in the page content language* to HTML and add
1780 * it to the buffer. The result with be language-converted to the
1781 * user's preferred variant. Assumes that the current page title
1782 * will be used if optional $title is not provided. Output will be
1785 * @param string $text Wikitext in the page content language
1786 * @param bool $linestart Is this the start of a line? (Defaults to true)
1787 * @param Title|null $title Optional title to use; default of `null`
1788 * means use current page title.
1789 * @throws MWException if $title is not provided and OutputPage::getTitle()
1793 public function addWikiTextAsContent(
1794 $text, $linestart = true, Title
$title = null
1796 if ( $title === null ) {
1797 $title = $this->getTitle();
1800 throw new MWException( 'Title is null' );
1802 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
1806 * Add wikitext with a custom Title object.
1807 * Output is unwrapped.
1809 * @param string $text Wikitext
1810 * @param Title $title
1811 * @param bool $linestart Is this the start of a line?
1812 * @param bool $tidy Whether to use tidy.
1813 * Setting this to false (or omitting it) is deprecated
1814 * since 1.32; all wikitext should be tidied.
1815 * @param bool $interface Whether it is an interface message
1816 * (for example disables conversion)
1817 * @param string $wrapperClass if not empty, wraps the output in
1818 * a `<div class="$wrapperClass">`
1821 private function addWikiTextTitleInternal(
1822 $text, Title
$title, $linestart, $interface, $wrapperClass = null
1824 $parserOutput = $this->parseInternal(
1825 $text, $title, $linestart, true, $interface, /*language*/null
1828 $this->addParserOutput( $parserOutput, [
1829 'enableSectionEditLinks' => false,
1830 'wrapperDivClass' => $wrapperClass ??
'',
1835 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1836 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1840 * @param ParserOutput $parserOutput
1842 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1843 $this->mLanguageLinks
=
1844 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1845 $this->addCategoryLinks( $parserOutput->getCategories() );
1846 $this->setIndicators( $parserOutput->getIndicators() );
1847 $this->mNewSectionLink
= $parserOutput->getNewSection();
1848 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1850 if ( !$parserOutput->isCacheable() ) {
1851 $this->enableClientCache( false );
1853 $this->mNoGallery
= $parserOutput->getNoGallery();
1854 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1855 $this->addModules( $parserOutput->getModules() );
1856 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1857 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1858 $this->mPreventClickjacking
= $this->mPreventClickjacking
1859 ||
$parserOutput->preventClickjacking();
1861 // Template versioning...
1862 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1863 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1864 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1866 $this->mTemplateIds
[$ns] = $dbks;
1869 // File versioning...
1870 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1871 $this->mImageTimeKeys
[$dbk] = $data;
1874 // Hooks registered in the object
1875 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1876 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1877 list( $hookName, $data ) = $hookInfo;
1878 if ( isset( $parserOutputHooks[$hookName] ) ) {
1879 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1883 // Enable OOUI if requested via ParserOutput
1884 if ( $parserOutput->getEnableOOUI() ) {
1885 $this->enableOOUI();
1888 // Include parser limit report
1889 if ( !$this->limitReportJSData
) {
1890 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1893 // Link flags are ignored for now, but may in the future be
1894 // used to mark individual language links.
1896 // Avoid PHP 7.1 warning of passing $this by reference
1897 $outputPage = $this;
1898 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1899 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1901 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1902 // so that extensions may modify ParserOutput to toggle TOC.
1903 // This cannot be moved to addParserOutputText because that is not
1904 // called by EditPage for Preview.
1905 if ( $parserOutput->getTOCHTML() ) {
1906 $this->mEnableTOC
= true;
1911 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1912 * ParserOutput object, without any other metadata.
1915 * @param ParserOutput $parserOutput
1916 * @param array $poOptions Options to ParserOutput::getText()
1918 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
1919 $this->addParserOutputText( $parserOutput, $poOptions );
1921 $this->addModules( $parserOutput->getModules() );
1922 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1924 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1928 * Add the HTML associated with a ParserOutput object, without any metadata.
1931 * @param ParserOutput $parserOutput
1932 * @param array $poOptions Options to ParserOutput::getText()
1934 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
1935 $text = $parserOutput->getText( $poOptions );
1936 // Avoid PHP 7.1 warning of passing $this by reference
1937 $outputPage = $this;
1938 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1939 $this->addHTML( $text );
1943 * Add everything from a ParserOutput object.
1945 * @param ParserOutput $parserOutput
1946 * @param array $poOptions Options to ParserOutput::getText()
1948 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
1949 $this->addParserOutputMetadata( $parserOutput );
1950 $this->addParserOutputText( $parserOutput, $poOptions );
1954 * Add the output of a QuickTemplate to the output buffer
1956 * @param QuickTemplate &$template
1958 public function addTemplate( &$template ) {
1959 $this->addHTML( $template->getHTML() );
1963 * Parse wikitext and return the HTML.
1965 * @todo The output is wrapped in a <div> iff $interface is false; it's
1966 * probably best to always strip the wrapper.
1968 * @param string $text
1969 * @param bool $linestart Is this the start of a line?
1970 * @param bool $interface Use interface language (instead of content language) while parsing
1971 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1972 * LanguageConverter.
1973 * @param Language|null $language Target language object, will override $interface
1974 * @throws MWException
1975 * @return string HTML
1976 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
1977 * use parseAsContent() if $interface is default value or false, or else
1978 * parseAsInterface() if $interface is true.
1980 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1981 wfDeprecated( __METHOD__
, '1.33' );
1982 return $this->parseInternal(
1983 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
1985 'enableSectionEditLinks' => false,
1990 * Parse wikitext *in the page content language* and return the HTML.
1991 * The result will be language-converted to the user's preferred variant.
1992 * Output will be tidy.
1994 * @param string $text Wikitext in the page content language
1995 * @param bool $linestart Is this the start of a line? (Defaults to true)
1996 * @throws MWException
1997 * @return string HTML
2000 public function parseAsContent( $text, $linestart = true ) {
2001 return $this->parseInternal(
2002 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2004 'enableSectionEditLinks' => false,
2005 'wrapperDivClass' => ''
2010 * Parse wikitext *in the user interface language* and return the HTML.
2011 * The result will not be language-converted, as user interface messages
2012 * are already localized into a specific variant.
2013 * Output will be tidy.
2015 * @param string $text Wikitext in the user interface language
2016 * @param bool $linestart Is this the start of a line? (Defaults to true)
2017 * @throws MWException
2018 * @return string HTML
2021 public function parseAsInterface( $text, $linestart = true ) {
2022 return $this->parseInternal(
2023 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2025 'enableSectionEditLinks' => false,
2026 'wrapperDivClass' => ''
2031 * Parse wikitext *in the user interface language*, strip
2032 * paragraph wrapper, and return the HTML.
2033 * The result will not be language-converted, as user interface messages
2034 * are already localized into a specific variant.
2035 * Output will be tidy. Outer paragraph wrapper will only be stripped
2036 * if the result is a single paragraph.
2038 * @param string $text Wikitext in the user interface language
2039 * @param bool $linestart Is this the start of a line? (Defaults to true)
2040 * @throws MWException
2041 * @return string HTML
2044 public function parseInlineAsInterface( $text, $linestart = true ) {
2045 return Parser
::stripOuterParagraph(
2046 $this->parseAsInterface( $text, $linestart )
2051 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2053 * @param string $text
2054 * @param bool $linestart Is this the start of a line?
2055 * @param bool $interface Use interface language (instead of content language) while parsing
2056 * language sensitive magic words like GRAMMAR and PLURAL
2057 * @return string HTML
2058 * @deprecated since 1.32, due to untidy output and confusing default
2059 * for $interface. Use parseInlineAsInterface() if $interface is
2060 * the default value or false, or else use
2061 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2063 public function parseInline( $text, $linestart = true, $interface = false ) {
2064 wfDeprecated( __METHOD__
, '1.33' );
2065 $parsed = $this->parseInternal(
2066 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2068 'enableSectionEditLinks' => false,
2069 'wrapperDivClass' => '', /* no wrapper div */
2071 return Parser
::stripOuterParagraph( $parsed );
2075 * Parse wikitext and return the HTML (internal implementation helper)
2077 * @param string $text
2078 * @param Title $title The title to use
2079 * @param bool $linestart Is this the start of a line?
2080 * @param bool $tidy Whether the output should be tidied
2081 * @param bool $interface Use interface language (instead of content language) while parsing
2082 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2083 * LanguageConverter.
2084 * @param Language|null $language Target language object, will override $interface
2085 * @throws MWException
2086 * @return ParserOutput
2088 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2089 if ( is_null( $title ) ) {
2090 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2093 $popts = $this->parserOptions();
2094 $oldTidy = $popts->setTidy( $tidy );
2095 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2097 if ( $language !== null ) {
2098 $oldLang = $popts->setTargetLanguage( $language );
2101 $parserOutput = MediaWikiServices
::getInstance()->getParser()->getFreshParser()->parse(
2102 $text, $title, $popts,
2103 $linestart, true, $this->mRevisionId
2106 $popts->setTidy( $oldTidy );
2107 $popts->setInterfaceMessage( $oldInterface );
2109 if ( $language !== null ) {
2110 $popts->setTargetLanguage( $oldLang );
2113 return $parserOutput;
2117 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2119 * @param int $maxage Maximum cache time on the CDN, in seconds.
2121 public function setCdnMaxage( $maxage ) {
2122 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2126 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2127 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2128 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2131 * @param int $maxage Maximum cache time on the CDN, in seconds
2134 public function lowerCdnMaxage( $maxage ) {
2135 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2136 $this->setCdnMaxage( $this->mCdnMaxage
);
2140 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2142 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2143 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2144 * TTL is 90% of the age of the object, subject to the min and max.
2146 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2147 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2148 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2151 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2152 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2153 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'CdnMaxAge' );
2155 if ( $mtime === null ||
$mtime === false ) {
2156 return $minTTL; // entity does not exist
2159 $age = MWTimestamp
::time() - wfTimestamp( TS_UNIX
, $mtime );
2160 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2161 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2163 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2167 * Use enableClientCache(false) to force it to send nocache headers
2169 * @param bool|null $state New value, or null to not set the value
2171 * @return bool Old value
2173 public function enableClientCache( $state ) {
2174 return wfSetVar( $this->mEnableClientCache
, $state );
2178 * Get the list of cookie names that will influence the cache
2182 function getCacheVaryCookies() {
2183 if ( self
::$cacheVaryCookies === null ) {
2184 $config = $this->getConfig();
2185 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2186 SessionManager
::singleton()->getVaryCookies(),
2190 $config->get( 'CacheVaryCookies' )
2192 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2194 return self
::$cacheVaryCookies;
2198 * Check if the request has a cache-varying cookie header
2199 * If it does, it's very important that we don't allow public caching
2203 function haveCacheVaryCookies() {
2204 $request = $this->getRequest();
2205 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2206 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2207 wfDebug( __METHOD__
. ": found $cookieName\n" );
2211 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2216 * Add an HTTP header that will influence on the cache
2218 * @param string $header Header name
2219 * @param string[]|null $option Deprecated; formerly options for the
2220 * Key header, deprecated in 1.32 and removed in 1.34. See
2221 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2222 * for the list of formerly-valid options.
2224 public function addVaryHeader( $header, array $option = null ) {
2225 if ( $option !== null && count( $option ) > 0 ) {
2226 wfDeprecated( 'addVaryHeader $option is ignored', '1.34' );
2228 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2229 $this->mVaryHeader
[$header] = null;
2234 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2235 * such as Accept-Encoding or Cookie
2239 public function getVaryHeader() {
2240 // If we vary on cookies, let's make sure it's always included here too.
2241 if ( $this->getCacheVaryCookies() ) {
2242 $this->addVaryHeader( 'Cookie' );
2245 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2246 $this->addVaryHeader( $header, $options );
2248 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2252 * Add an HTTP Link: header
2254 * @param string $header Header value
2256 public function addLinkHeader( $header ) {
2257 $this->mLinkHeader
[] = $header;
2261 * Return a Link: header. Based on the values of $mLinkHeader.
2265 public function getLinkHeader() {
2266 if ( !$this->mLinkHeader
) {
2270 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2274 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2277 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2278 * /w/index.php?title=Main_page&variant=zh-cn will not.
2280 private function addAcceptLanguage() {
2281 $title = $this->getTitle();
2282 if ( !$title instanceof Title
) {
2286 $lang = $title->getPageLanguage();
2287 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2288 $this->addVaryHeader( 'Accept-Language' );
2293 * Set a flag which will cause an X-Frame-Options header appropriate for
2294 * edit pages to be sent. The header value is controlled by
2295 * $wgEditPageFrameOptions.
2297 * This is the default for special pages. If you display a CSRF-protected
2298 * form on an ordinary view page, then you need to call this function.
2300 * @param bool $enable
2302 public function preventClickjacking( $enable = true ) {
2303 $this->mPreventClickjacking
= $enable;
2307 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2308 * This can be called from pages which do not contain any CSRF-protected
2311 public function allowClickjacking() {
2312 $this->mPreventClickjacking
= false;
2316 * Get the prevent-clickjacking flag
2321 public function getPreventClickjacking() {
2322 return $this->mPreventClickjacking
;
2326 * Get the X-Frame-Options header value (without the name part), or false
2327 * if there isn't one. This is used by Skin to determine whether to enable
2328 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2330 * @return string|false
2332 public function getFrameOptions() {
2333 $config = $this->getConfig();
2334 if ( $config->get( 'BreakFrames' ) ) {
2336 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2337 return $config->get( 'EditPageFrameOptions' );
2343 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2344 * Trials: https://github.com/GoogleChrome/OriginTrials
2348 private function getOriginTrials() {
2349 $config = $this->getConfig();
2351 return $config->get( 'OriginTrials' );
2354 private function getReportTo() {
2355 $config = $this->getConfig();
2357 $expiry = $config->get( 'ReportToExpiry' );
2363 $endpoints = $config->get( 'ReportToEndpoints' );
2365 if ( !$endpoints ) {
2369 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2371 foreach ( $endpoints as $endpoint ) {
2372 $output['endpoints'][] = [ 'url' => $endpoint ];
2375 return json_encode( $output, JSON_UNESCAPED_SLASHES
);
2378 private function getFeaturePolicyReportOnly() {
2379 $config = $this->getConfig();
2381 $features = $config->get( 'FeaturePolicyReportOnly' );
2382 return implode( ';', $features );
2386 * Send cache control HTTP headers
2388 public function sendCacheControl() {
2389 $response = $this->getRequest()->response();
2390 $config = $this->getConfig();
2392 $this->addVaryHeader( 'Cookie' );
2393 $this->addAcceptLanguage();
2395 # don't serve compressed data to clients who can't handle it
2396 # maintain different caches for logged-in users and non-logged in ones
2397 $response->header( $this->getVaryHeader() );
2399 if ( $this->mEnableClientCache
) {
2401 $config->get( 'UseCdn' ) &&
2402 !$response->hasCookies() &&
2403 !SessionManager
::getGlobalSession()->isPersistent() &&
2404 !$this->isPrintable() &&
2405 $this->mCdnMaxage
!= 0 &&
2406 !$this->haveCacheVaryCookies()
2408 if ( $config->get( 'UseESI' ) ) {
2409 wfDeprecated( '$wgUseESI = true', '1.33' );
2410 # We'll purge the proxy cache explicitly, but require end user agents
2411 # to revalidate against the proxy on each visit.
2412 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2413 wfDebug( __METHOD__
.
2414 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2415 # start with a shorter timeout for initial testing
2416 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2418 "Surrogate-Control: max-age={$config->get( 'CdnMaxAge' )}" .
2419 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2421 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2423 # We'll purge the proxy cache for anons explicitly, but require end user agents
2424 # to revalidate against the proxy on each visit.
2425 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2426 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2427 wfDebug( __METHOD__
.
2428 ": local proxy caching; {$this->mLastModified} **", 'private' );
2429 # start with a shorter timeout for initial testing
2430 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2431 $response->header( "Cache-Control: " .
2432 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2435 # We do want clients to cache if they can, but they *must* check for updates
2436 # on revisiting the page.
2437 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2438 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2439 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2441 if ( $this->mLastModified
) {
2442 $response->header( "Last-Modified: {$this->mLastModified}" );
2445 wfDebug( __METHOD__
. ": no caching **", 'private' );
2447 # In general, the absence of a last modified header should be enough to prevent
2448 # the client from using its cache. We send a few other things just to make sure.
2449 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2450 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2451 $response->header( 'Pragma: no-cache' );
2456 * Transfer styles and JavaScript modules from skin.
2458 * @param Skin $sk to load modules for
2460 public function loadSkinModules( $sk ) {
2461 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2462 if ( $group === 'styles' ) {
2463 foreach ( $modules as $key => $moduleMembers ) {
2464 $this->addModuleStyles( $moduleMembers );
2467 $this->addModules( $modules );
2473 * Finally, all the text has been munged and accumulated into
2474 * the object, let's actually output it:
2476 * @param bool $return Set to true to get the result as a string rather than sending it
2477 * @return string|null
2479 * @throws FatalError
2480 * @throws MWException
2482 public function output( $return = false ) {
2483 if ( $this->mDoNothing
) {
2484 return $return ?
'' : null;
2487 $response = $this->getRequest()->response();
2488 $config = $this->getConfig();
2490 if ( $this->mRedirect
!= '' ) {
2491 # Standards require redirect URLs to be absolute
2492 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2494 $redirect = $this->mRedirect
;
2495 $code = $this->mRedirectCode
;
2497 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2498 if ( $code == '301' ||
$code == '303' ) {
2499 if ( !$config->get( 'DebugRedirects' ) ) {
2500 $response->statusHeader( $code );
2502 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2504 if ( $config->get( 'VaryOnXFP' ) ) {
2505 $this->addVaryHeader( 'X-Forwarded-Proto' );
2507 $this->sendCacheControl();
2509 $response->header( "Content-Type: text/html; charset=utf-8" );
2510 if ( $config->get( 'DebugRedirects' ) ) {
2511 $url = htmlspecialchars( $redirect );
2512 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2513 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2514 print "</body>\n</html>\n";
2516 $response->header( 'Location: ' . $redirect );
2520 return $return ?
'' : null;
2521 } elseif ( $this->mStatusCode
) {
2522 $response->statusHeader( $this->mStatusCode
);
2525 # Buffer output; final headers may depend on later processing
2528 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2529 $response->header( 'Content-language: ' .
2530 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2532 $linkHeader = $this->getLinkHeader();
2533 if ( $linkHeader ) {
2534 $response->header( $linkHeader );
2537 // Prevent framing, if requested
2538 $frameOptions = $this->getFrameOptions();
2539 if ( $frameOptions ) {
2540 $response->header( "X-Frame-Options: $frameOptions" );
2543 $originTrials = $this->getOriginTrials();
2544 foreach ( $originTrials as $originTrial ) {
2545 $response->header( "Origin-Trial: $originTrial", false );
2548 $reportTo = $this->getReportTo();
2550 $response->header( "Report-To: $reportTo" );
2553 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2554 if ( $featurePolicyReportOnly ) {
2555 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2558 ContentSecurityPolicy
::sendHeaders( $this );
2560 if ( $this->mArticleBodyOnly
) {
2561 echo $this->mBodytext
;
2563 // Enable safe mode if requested (T152169)
2564 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2565 $this->disallowUserJs();
2568 $sk = $this->getSkin();
2569 $this->loadSkinModules( $sk );
2571 MWDebug
::addModules( $this );
2573 // Avoid PHP 7.1 warning of passing $this by reference
2574 $outputPage = $this;
2575 // Hook that allows last minute changes to the output page, e.g.
2576 // adding of CSS or Javascript by extensions.
2577 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2581 } catch ( Exception
$e ) {
2582 ob_end_clean(); // bug T129657
2588 // This hook allows last minute changes to final overall output by modifying output buffer
2589 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2590 } catch ( Exception
$e ) {
2591 ob_end_clean(); // bug T129657
2595 $this->sendCacheControl();
2598 return ob_get_clean();
2606 * Prepare this object to display an error page; disable caching and
2607 * indexing, clear the current text and redirect, set the page's title
2608 * and optionally an custom HTML title (content of the "<title>" tag).
2610 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2611 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2612 * optional, if not passed the "<title>" attribute will be
2613 * based on $pageTitle
2615 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2616 $this->setPageTitle( $pageTitle );
2617 if ( $htmlTitle !== false ) {
2618 $this->setHTMLTitle( $htmlTitle );
2620 $this->setRobotPolicy( 'noindex,nofollow' );
2621 $this->setArticleRelated( false );
2622 $this->enableClientCache( false );
2623 $this->mRedirect
= '';
2624 $this->clearSubtitle();
2629 * Output a standard error page
2631 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2632 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2633 * showErrorPage( 'titlemsg', $messageObject );
2634 * showErrorPage( $titleMessageObject, $messageObject );
2636 * @param string|Message $title Message key (string) for page title, or a Message object
2637 * @param string|Message $msg Message key (string) for page text, or a Message object
2638 * @param array $params Message parameters; ignored if $msg is a Message object
2640 public function showErrorPage( $title, $msg, $params = [] ) {
2641 if ( !$title instanceof Message
) {
2642 $title = $this->msg( $title );
2645 $this->prepareErrorPage( $title );
2647 if ( $msg instanceof Message
) {
2648 if ( $params !== [] ) {
2649 trigger_error( 'Argument ignored: $params. The message parameters argument '
2650 . 'is discarded when the $msg argument is a Message object instead of '
2651 . 'a string.', E_USER_NOTICE
);
2653 $this->addHTML( $msg->parseAsBlock() );
2655 $this->addWikiMsgArray( $msg, $params );
2658 $this->returnToMain();
2662 * Output a standard permission error page
2664 * @param array $errors Error message keys or [key, param...] arrays
2665 * @param string|null $action Action that was denied or null if unknown
2667 public function showPermissionsErrorPage( array $errors, $action = null ) {
2668 foreach ( $errors as $key => $error ) {
2669 $errors[$key] = (array)$error;
2672 // For some action (read, edit, create and upload), display a "login to do this action"
2673 // error if all of the following conditions are met:
2674 // 1. the user is not logged in
2675 // 2. the only error is insufficient permissions (i.e. no block or something else)
2676 // 3. the error can be avoided simply by logging in
2677 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2678 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2679 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2680 && ( User
::groupHasPermission( 'user', $action )
2681 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2683 $displayReturnto = null;
2685 # Due to T34276, if a user does not have read permissions,
2686 # $this->getTitle() will just give Special:Badtitle, which is
2687 # not especially useful as a returnto parameter. Use the title
2688 # from the request instead, if there was one.
2689 $request = $this->getRequest();
2690 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2691 if ( $action == 'edit' ) {
2692 $msg = 'whitelistedittext';
2693 $displayReturnto = $returnto;
2694 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2695 $msg = 'nocreatetext';
2696 } elseif ( $action == 'upload' ) {
2697 $msg = 'uploadnologintext';
2699 $msg = 'loginreqpagetext';
2700 $displayReturnto = Title
::newMainPage();
2706 $query['returnto'] = $returnto->getPrefixedText();
2708 if ( !$request->wasPosted() ) {
2709 $returntoquery = $request->getValues();
2710 unset( $returntoquery['title'] );
2711 unset( $returntoquery['returnto'] );
2712 unset( $returntoquery['returntoquery'] );
2713 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2717 $services = MediaWikiServices
::getInstance();
2719 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2720 $linkRenderer = $services->getLinkRenderer();
2721 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2722 $loginLink = $linkRenderer->makeKnownLink(
2724 $this->msg( 'loginreqlink' )->text(),
2729 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2730 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2732 $permissionManager = $services->getPermissionManager();
2734 # Don't return to a page the user can't read otherwise
2735 # we'll end up in a pointless loop
2736 if ( $displayReturnto && $permissionManager->userCan(
2737 'read', $this->getUser(), $displayReturnto
2739 $this->returnToMain( null, $displayReturnto );
2742 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2743 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2748 * Display an error page indicating that a given version of MediaWiki is
2749 * required to use it
2751 * @param mixed $version The version of MediaWiki needed to use the page
2753 public function versionRequired( $version ) {
2754 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2756 $this->addWikiMsg( 'versionrequiredtext', $version );
2757 $this->returnToMain();
2761 * Format a list of error messages
2763 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2764 * @param string|null $action Action that was denied or null if unknown
2765 * @return string The wikitext error-messages, formatted into a list.
2767 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2768 if ( $action == null ) {
2769 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2771 $action_desc = $this->msg( "action-$action" )->plain();
2773 'permissionserrorstext-withaction',
2776 )->plain() . "\n\n";
2779 if ( count( $errors ) > 1 ) {
2780 $text .= '<ul class="permissions-errors">' . "\n";
2782 foreach ( $errors as $error ) {
2784 $text .= $this->msg( ...$error )->plain();
2789 $text .= "<div class=\"permissions-errors\">\n" .
2790 $this->msg( ...reset( $errors ) )->plain() .
2798 * Show a warning about replica DB lag
2800 * If the lag is higher than $wgSlaveLagCritical seconds,
2801 * then the warning is a bit more obvious. If the lag is
2802 * lower than $wgSlaveLagWarning, then no warning is shown.
2804 * @param int $lag Replica lag
2806 public function showLagWarning( $lag ) {
2807 $config = $this->getConfig();
2808 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2809 $lag = floor( $lag ); // floor to avoid nano seconds to display
2810 $message = $lag < $config->get( 'SlaveLagCritical' )
2813 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2814 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2819 * Output an error page
2821 * @note FatalError exception class provides an alternative.
2822 * @param string $message Error to output. Must be escaped for HTML.
2824 public function showFatalError( $message ) {
2825 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2827 $this->addHTML( $message );
2831 * Add a "return to" link pointing to a specified title
2833 * @param Title $title Title to link
2834 * @param array $query Query string parameters
2835 * @param string|null $text Text of the link (input is not escaped)
2836 * @param array $options Options array to pass to Linker
2838 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2839 $linkRenderer = MediaWikiServices
::getInstance()
2840 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2841 $link = $this->msg( 'returnto' )->rawParams(
2842 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2843 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2847 * Add a "return to" link pointing to a specified title,
2848 * or the title indicated in the request, or else the main page
2850 * @param mixed|null $unused
2851 * @param Title|string|null $returnto Title or String to return to
2852 * @param string|null $returntoquery Query string for the return to link
2854 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2855 if ( $returnto == null ) {
2856 $returnto = $this->getRequest()->getText( 'returnto' );
2859 if ( $returntoquery == null ) {
2860 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2863 if ( $returnto === '' ) {
2864 $returnto = Title
::newMainPage();
2867 if ( is_object( $returnto ) ) {
2868 $titleObj = $returnto;
2870 $titleObj = Title
::newFromText( $returnto );
2872 // We don't want people to return to external interwiki. That
2873 // might potentially be used as part of a phishing scheme
2874 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2875 $titleObj = Title
::newMainPage();
2878 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2881 private function getRlClientContext() {
2882 if ( !$this->rlClientContext
) {
2883 $query = ResourceLoader
::makeLoaderQuery(
2884 [], // modules; not relevant
2885 $this->getLanguage()->getCode(),
2886 $this->getSkin()->getSkinName(),
2887 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2888 null, // version; not relevant
2889 ResourceLoader
::inDebugMode(),
2890 null, // only; not relevant
2891 $this->isPrintable(),
2892 $this->getRequest()->getBool( 'handheld' )
2894 $this->rlClientContext
= new ResourceLoaderContext(
2895 $this->getResourceLoader(),
2896 new FauxRequest( $query )
2898 if ( $this->contentOverrideCallbacks
) {
2899 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2900 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2901 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2902 $content = $callback( $title );
2903 if ( $content !== null ) {
2904 $text = ContentHandler
::getContentText( $content );
2905 if ( strpos( $text, '</script>' ) !== false ) {
2906 // Proactively replace this so that we can display a message
2907 // to the user, instead of letting it go to Html::inlineScript(),
2908 // where it would be considered a server-side issue.
2909 $titleFormatted = $title->getPrefixedText();
2910 $content = new JavaScriptContent(
2911 Xml
::encodeJsCall( 'mw.log.error', [
2912 "Cannot preview $titleFormatted due to script-closing tag."
2923 return $this->rlClientContext
;
2927 * Call this to freeze the module queue and JS config and create a formatter.
2929 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2930 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2931 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2932 * the module filters retroactively. Skins and extension hooks may also add modules until very
2933 * late in the request lifecycle.
2935 * @return ResourceLoaderClientHtml
2937 public function getRlClient() {
2938 if ( !$this->rlClient
) {
2939 $context = $this->getRlClientContext();
2940 $rl = $this->getResourceLoader();
2941 $this->addModules( [
2946 $this->addModuleStyles( [
2951 $this->getSkin()->setupSkinUserCss( $this );
2953 // Prepare exempt modules for buildExemptModules()
2954 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2956 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2958 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2959 // Separate user-specific batch for improved cache-hit ratio.
2960 $userBatch = [ 'user.styles', 'user' ];
2961 $siteBatch = array_diff( $moduleStyles, $userBatch );
2962 $dbr = wfGetDB( DB_REPLICA
);
2963 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2964 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2966 // Filter out modules handled by buildExemptModules()
2967 $moduleStyles = array_filter( $moduleStyles,
2968 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2969 $module = $rl->getModule( $name );
2971 $group = $module->getGroup();
2972 if ( isset( $exemptGroups[$group] ) ) {
2973 $exemptStates[$name] = 'ready';
2974 if ( !$module->isKnownEmpty( $context ) ) {
2975 // E.g. Don't output empty <styles>
2976 $exemptGroups[$group][] = $name;
2984 $this->rlExemptStyleModules
= $exemptGroups;
2986 $rlClient = new ResourceLoaderClientHtml( $context, [
2987 'target' => $this->getTarget(),
2988 'nonce' => $this->getCSPNonce(),
2989 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2990 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2991 // modules enqueud for loading on this page is filtered to just those.
2992 // However, to make sure we also apply the restriction to dynamic dependencies and
2993 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2994 // StartupModule so that the client-side registry will not contain any restricted
2995 // modules either. (T152169, T185303)
2996 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2997 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
3000 $rlClient->setConfig( $this->getJSVars() );
3001 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3002 $rlClient->setModuleStyles( $moduleStyles );
3003 $rlClient->setExemptStates( $exemptStates );
3004 $this->rlClient
= $rlClient;
3006 return $this->rlClient
;
3010 * @param Skin $sk The given Skin
3011 * @param bool $includeStyle Unused
3012 * @return string The doctype, opening "<html>", and head element.
3014 public function headElement( Skin
$sk, $includeStyle = true ) {
3015 $config = $this->getConfig();
3016 $userdir = $this->getLanguage()->getDir();
3017 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3020 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
3021 $this->getRlClient()->getDocumentAttributes(),
3022 $sk->getHtmlElementAttributes()
3024 $pieces[] = Html
::openElement( 'head' );
3026 if ( $this->getHTMLTitle() == '' ) {
3027 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3030 if ( !Html
::isXmlMimeType( $config->get( 'MimeType' ) ) ) {
3031 // Add <meta charset="UTF-8">
3032 // This should be before <title> since it defines the charset used by
3033 // text including the text inside <title>.
3034 // The spec recommends defining XHTML5's charset using the XML declaration
3036 // Our XML declaration is output by Html::htmlHeader.
3037 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3038 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3039 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3042 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3043 $pieces[] = $this->getRlClient()->getHeadHtml();
3044 $pieces[] = $this->buildExemptModules();
3045 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3046 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3048 // This library is intended to run on older browsers that MediaWiki no longer
3049 // supports as Grade A. For these Grade C browsers, we provide an experience
3050 // using only HTML and CSS. But, where standards-compliant browsers are able to
3051 // style unknown HTML elements without issue, old IE ignores these styles.
3052 // The html5shiv library fixes that.
3053 // Use an IE conditional comment to serve the script only to old IE
3054 $shivUrl = $config->get( 'ResourceBasePath' ) . '/resources/lib/html5shiv/html5shiv.js';
3055 $pieces[] = '<!--[if lt IE 9]>' .
3056 Html
::linkedScript( $shivUrl, $this->getCSPNonce() ) .
3059 $pieces[] = Html
::closeElement( 'head' );
3061 $bodyClasses = $this->mAdditionalBodyClasses
;
3062 $bodyClasses[] = 'mediawiki';
3064 # Classes for LTR/RTL directionality support
3065 $bodyClasses[] = $userdir;
3066 $bodyClasses[] = "sitedir-$sitedir";
3068 $underline = $this->getUser()->getOption( 'underline' );
3069 if ( $underline < 2 ) {
3070 // The following classes can be used here:
3071 // * mw-underline-always
3072 // * mw-underline-never
3073 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
3076 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3077 # A <body> class is probably not the best way to do this . . .
3078 $bodyClasses[] = 'capitalize-all-nouns';
3081 // Parser feature migration class
3082 // The idea is that this will eventually be removed, after the wikitext
3083 // which requires it is cleaned up.
3084 $bodyClasses[] = 'mw-hide-empty-elt';
3086 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3087 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3089 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3092 // While the implode() is not strictly needed, it's used for backwards compatibility
3093 // (this used to be built as a string and hooks likely still expect that).
3094 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3096 // Allow skins and extensions to add body attributes they need
3097 $sk->addToBodyAttributes( $this, $bodyAttrs );
3098 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3100 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3102 return self
::combineWrappedStrings( $pieces );
3106 * Get a ResourceLoader object associated with this OutputPage
3108 * @return ResourceLoader
3110 public function getResourceLoader() {
3111 if ( is_null( $this->mResourceLoader
) ) {
3112 // Lazy-initialise as needed
3113 $this->mResourceLoader
= MediaWikiServices
::getInstance()->getResourceLoader();
3115 return $this->mResourceLoader
;
3119 * Explicily load or embed modules on a page.
3121 * @param array|string $modules One or more module names
3122 * @param string $only ResourceLoaderModule TYPE_ class constant
3123 * @param array $extraQuery [optional] Array with extra query parameters for the request
3124 * @return string|WrappedStringList HTML
3126 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3127 // Apply 'target' and 'origin' filters
3128 $modules = $this->filterModules( (array)$modules, null, $only );
3130 return ResourceLoaderClientHtml
::makeLoad(
3131 $this->getRlClientContext(),
3135 $this->getCSPNonce()
3140 * Combine WrappedString chunks and filter out empty ones
3142 * @param array $chunks
3143 * @return string|WrappedStringList HTML
3145 protected static function combineWrappedStrings( array $chunks ) {
3146 // Filter out empty values
3147 $chunks = array_filter( $chunks, 'strlen' );
3148 return WrappedString
::join( "\n", $chunks );
3152 * JS stuff to put at the bottom of the `<body>`.
3153 * These are legacy scripts ($this->mScripts), and user JS.
3155 * @return string|WrappedStringList HTML
3157 public function getBottomScripts() {
3159 $chunks[] = $this->getRlClient()->getBodyHtml();
3161 // Legacy non-ResourceLoader scripts
3162 $chunks[] = $this->mScripts
;
3164 if ( $this->limitReportJSData
) {
3165 $chunks[] = ResourceLoader
::makeInlineScript(
3166 ResourceLoader
::makeConfigSetScript(
3167 [ 'wgPageParseReport' => $this->limitReportJSData
]
3169 $this->getCSPNonce()
3173 return self
::combineWrappedStrings( $chunks );
3177 * Get the javascript config vars to include on this page
3179 * @return array Array of javascript config vars
3182 public function getJsConfigVars() {
3183 return $this->mJsConfigVars
;
3187 * Add one or more variables to be set in mw.config in JavaScript
3189 * @param string|array $keys Key or array of key/value pairs
3190 * @param mixed|null $value [optional] Value of the configuration variable
3192 public function addJsConfigVars( $keys, $value = null ) {
3193 if ( is_array( $keys ) ) {
3194 foreach ( $keys as $key => $value ) {
3195 $this->mJsConfigVars
[$key] = $value;
3200 $this->mJsConfigVars
[$keys] = $value;
3204 * Get an array containing the variables to be set in mw.config in JavaScript.
3206 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3207 * - in other words, page-independent/site-wide variables (without state).
3208 * You will only be adding bloat to the html page and causing page caches to
3209 * have to be purged on configuration changes.
3212 public function getJSVars() {
3215 $canonicalSpecialPageName = false; # T23115
3216 $services = MediaWikiServices
::getInstance();
3218 $title = $this->getTitle();
3219 $ns = $title->getNamespace();
3220 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
3221 $canonicalNamespace = $nsInfo->exists( $ns )
3222 ?
$nsInfo->getCanonicalName( $ns )
3223 : $title->getNsText();
3225 $sk = $this->getSkin();
3226 // Get the relevant title so that AJAX features can use the correct page name
3227 // when making API requests from certain special pages (T36972).
3228 $relevantTitle = $sk->getRelevantTitle();
3229 $relevantUser = $sk->getRelevantUser();
3231 if ( $ns == NS_SPECIAL
) {
3232 list( $canonicalSpecialPageName, /*...*/ ) =
3233 $services->getSpecialPageFactory()->
3234 resolveAlias( $title->getDBkey() );
3235 } elseif ( $this->canUseWikiPage() ) {
3236 $wikiPage = $this->getWikiPage();
3237 $curRevisionId = $wikiPage->getLatest();
3238 $articleId = $wikiPage->getId();
3241 $lang = $title->getPageViewLanguage();
3243 // Pre-process information
3244 $separatorTransTable = $lang->separatorTransformTable();
3245 $separatorTransTable = $separatorTransTable ?
: [];
3246 $compactSeparatorTransTable = [
3247 implode( "\t", array_keys( $separatorTransTable ) ),
3248 implode( "\t", $separatorTransTable ),
3250 $digitTransTable = $lang->digitTransformTable();
3251 $digitTransTable = $digitTransTable ?
: [];
3252 $compactDigitTransTable = [
3253 implode( "\t", array_keys( $digitTransTable ) ),
3254 implode( "\t", $digitTransTable ),
3257 $user = $this->getUser();
3260 'wgCanonicalNamespace' => $canonicalNamespace,
3261 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3262 'wgNamespaceNumber' => $title->getNamespace(),
3263 'wgPageName' => $title->getPrefixedDBkey(),
3264 'wgTitle' => $title->getText(),
3265 'wgCurRevisionId' => $curRevisionId,
3266 'wgRevisionId' => (int)$this->getRevisionId(),
3267 'wgArticleId' => $articleId,
3268 'wgIsArticle' => $this->isArticle(),
3269 'wgIsRedirect' => $title->isRedirect(),
3270 'wgAction' => Action
::getActionName( $this->getContext() ),
3271 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3272 'wgUserGroups' => $user->getEffectiveGroups(),
3273 'wgCategories' => $this->getCategories(),
3274 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3275 'wgPageContentLanguage' => $lang->getCode(),
3276 'wgPageContentModel' => $title->getContentModel(),
3277 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3278 'wgDigitTransformTable' => $compactDigitTransTable,
3279 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3280 'wgMonthNames' => $lang->getMonthNamesArray(),
3281 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3282 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3283 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3284 'wgRequestId' => WebRequest
::getRequestId(),
3285 'wgCSPNonce' => $this->getCSPNonce(),
3288 if ( $user->isLoggedIn() ) {
3289 $vars['wgUserId'] = $user->getId();
3290 $vars['wgUserEditCount'] = $user->getEditCount();
3291 $userReg = $user->getRegistration();
3292 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3293 // Get the revision ID of the oldest new message on the user's talk
3294 // page. This can be used for constructing new message alerts on
3296 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3299 $contLang = $services->getContentLanguage();
3300 if ( $contLang->hasVariants() ) {
3301 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3303 // Same test as SkinTemplate
3304 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3305 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3307 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3308 && $relevantTitle->quickUserCan( 'edit', $user )
3309 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3311 foreach ( $title->getRestrictionTypes() as $type ) {
3312 // Following keys are set in $vars:
3313 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3314 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3317 if ( $title->isMainPage() ) {
3318 $vars['wgIsMainPage'] = true;
3321 if ( $this->mRedirectedFrom
) {
3322 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3325 if ( $relevantUser ) {
3326 $vars['wgRelevantUserName'] = $relevantUser->getName();
3329 // Allow extensions to add their custom variables to the mw.config map.
3330 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3331 // page-dependant but site-wide (without state).
3332 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3333 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3335 // Merge in variables from addJsConfigVars last
3336 return array_merge( $vars, $this->getJsConfigVars() );
3340 * To make it harder for someone to slip a user a fake
3341 * JavaScript or CSS preview, a random token
3342 * is associated with the login session. If it's not
3343 * passed back with the preview request, we won't render
3348 public function userCanPreview() {
3349 $request = $this->getRequest();
3351 $request->getVal( 'action' ) !== 'submit' ||
3352 !$request->wasPosted()
3357 $user = $this->getUser();
3359 if ( !$user->isLoggedIn() ) {
3360 // Anons have predictable edit tokens
3363 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3367 $title = $this->getTitle();
3368 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3369 if ( count( $errors ) !== 0 ) {
3377 * @return array Array in format "link name or number => 'link html'".
3379 public function getHeadLinksArray() {
3383 $config = $this->getConfig();
3385 $canonicalUrl = $this->mCanonicalUrl
;
3387 $tags['meta-generator'] = Html
::element( 'meta', [
3388 'name' => 'generator',
3389 'content' => "MediaWiki $wgVersion",
3392 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3393 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3394 // fallbacks should come before the primary value so we need to reverse the array.
3395 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3396 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3397 'name' => 'referrer',
3398 'content' => $policy,
3403 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3404 if ( $p !== 'index,follow' ) {
3405 // http://www.robotstxt.org/wc/meta-user.html
3406 // Only show if it's different from the default robots policy
3407 $tags['meta-robots'] = Html
::element( 'meta', [
3413 foreach ( $this->mMetatags
as $tag ) {
3414 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3416 $tag[0] = substr( $tag[0], 5 );
3417 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3422 $tagName = "meta-{$tag[0]}";
3423 if ( isset( $tags[$tagName] ) ) {
3424 $tagName .= $tag[1];
3426 $tags[$tagName] = Html
::element( 'meta',
3429 'content' => $tag[1]
3434 foreach ( $this->mLinktags
as $tag ) {
3435 $tags[] = Html
::element( 'link', $tag );
3438 # Universal edit button
3439 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3440 $user = $this->getUser();
3441 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3442 && ( $this->getTitle()->exists() ||
3443 $this->getTitle()->quickUserCan( 'create', $user ) )
3445 // Original UniversalEditButton
3446 $msg = $this->msg( 'edit' )->text();
3447 $tags['universal-edit-button'] = Html
::element( 'link', [
3448 'rel' => 'alternate',
3449 'type' => 'application/x-wiki',
3451 'href' => $this->getTitle()->getEditURL(),
3453 // Alternate edit link
3454 $tags['alternative-edit'] = Html
::element( 'link', [
3457 'href' => $this->getTitle()->getEditURL(),
3462 # Generally the order of the favicon and apple-touch-icon links
3463 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3464 # uses whichever one appears later in the HTML source. Make sure
3465 # apple-touch-icon is specified first to avoid this.
3466 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3467 $tags['apple-touch-icon'] = Html
::element( 'link', [
3468 'rel' => 'apple-touch-icon',
3469 'href' => $config->get( 'AppleTouchIcon' )
3473 if ( $config->get( 'Favicon' ) !== false ) {
3474 $tags['favicon'] = Html
::element( 'link', [
3475 'rel' => 'shortcut icon',
3476 'href' => $config->get( 'Favicon' )
3480 # OpenSearch description link
3481 $tags['opensearch'] = Html
::element( 'link', [
3483 'type' => 'application/opensearchdescription+xml',
3484 'href' => wfScript( 'opensearch_desc' ),
3485 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3488 # Real Simple Discovery link, provides auto-discovery information
3489 # for the MediaWiki API (and potentially additional custom API
3490 # support such as WordPress or Twitter-compatible APIs for a
3491 # blogging extension, etc)
3492 $tags['rsd'] = Html
::element( 'link', [
3494 'type' => 'application/rsd+xml',
3495 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3496 // Whether RSD accepts relative or protocol-relative URLs is completely
3497 // undocumented, though.
3498 'href' => wfExpandUrl( wfAppendQuery(
3500 [ 'action' => 'rsd' ] ),
3506 if ( !$config->get( 'DisableLangConversion' ) ) {
3507 $lang = $this->getTitle()->getPageLanguage();
3508 if ( $lang->hasVariants() ) {
3509 $variants = $lang->getVariants();
3510 foreach ( $variants as $variant ) {
3511 $tags["variant-$variant"] = Html
::element( 'link', [
3512 'rel' => 'alternate',
3513 'hreflang' => LanguageCode
::bcp47( $variant ),
3514 'href' => $this->getTitle()->getLocalURL(
3515 [ 'variant' => $variant ] )
3519 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3520 $tags["variant-x-default"] = Html
::element( 'link', [
3521 'rel' => 'alternate',
3522 'hreflang' => 'x-default',
3523 'href' => $this->getTitle()->getLocalURL() ] );
3528 if ( $this->copyrightUrl
!== null ) {
3529 $copyright = $this->copyrightUrl
;
3532 if ( $config->get( 'RightsPage' ) ) {
3533 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3536 $copyright = $copy->getLocalURL();
3540 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3541 $copyright = $config->get( 'RightsUrl' );
3546 $tags['copyright'] = Html
::element( 'link', [
3548 'href' => $copyright ]
3553 if ( $config->get( 'Feed' ) ) {
3556 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3557 # Use the page name for the title. In principle, this could
3558 # lead to issues with having the same name for different feeds
3559 # corresponding to the same page, but we can't avoid that at
3562 $feedLinks[] = $this->feedLink(
3565 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3567 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3572 # Recent changes feed should appear on every page (except recentchanges,
3573 # that would be redundant). Put it after the per-page feed to avoid
3574 # changing existing behavior. It's still available, probably via a
3575 # menu in your browser. Some sites might have a different feed they'd
3576 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3577 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3578 # If so, use it instead.
3579 $sitename = $config->get( 'Sitename' );
3580 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3581 if ( $overrideSiteFeed ) {
3582 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3583 // Note, this->feedLink escapes the url.
3584 $feedLinks[] = $this->feedLink(
3587 $this->msg( "site-{$type}-feed", $sitename )->text()
3590 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3591 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3592 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3593 $feedLinks[] = $this->feedLink(
3595 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3596 # For grep: 'site-rss-feed', 'site-atom-feed'
3597 $this->msg( "site-{$format}-feed", $sitename )->text()
3602 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3603 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3604 # use OutputPage::addFeedLink() instead.
3605 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3607 $tags +
= $feedLinks;
3611 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3612 if ( $canonicalUrl !== false ) {
3613 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3614 } elseif ( $this->isArticleRelated() ) {
3615 // This affects all requests where "setArticleRelated" is true. This is
3616 // typically all requests that show content (query title, curid, oldid, diff),
3617 // and all wikipage actions (edit, delete, purge, info, history etc.).
3618 // It does not apply to File pages and Special pages.
3619 // 'history' and 'info' actions address page metadata rather than the page
3620 // content itself, so they may not be canonicalized to the view page url.
3621 // TODO: this ought to be better encapsulated in the Action class.
3622 $action = Action
::getActionName( $this->getContext() );
3623 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3624 $query = "action={$action}";
3628 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3630 $reqUrl = $this->getRequest()->getRequestURL();
3631 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3634 if ( $canonicalUrl !== false ) {
3635 $tags[] = Html
::element( 'link', [
3636 'rel' => 'canonical',
3637 'href' => $canonicalUrl
3641 // Allow extensions to add, remove and/or otherwise manipulate these links
3642 // If you want only to *add* <head> links, please use the addHeadItem()
3643 // (or addHeadItems() for multiple items) method instead.
3644 // This hook is provided as a last resort for extensions to modify these
3645 // links before the output is sent to client.
3646 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3652 * Generate a "<link rel/>" for a feed.
3654 * @param string $type Feed type
3655 * @param string $url URL to the feed
3656 * @param string $text Value of the "title" attribute
3657 * @return string HTML fragment
3659 private function feedLink( $type, $url, $text ) {
3660 return Html
::element( 'link', [
3661 'rel' => 'alternate',
3662 'type' => "application/$type+xml",
3669 * Add a local or specified stylesheet, with the given media options.
3670 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3672 * @param string $style URL to the file
3673 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3674 * @param string $condition For IE conditional comments, specifying an IE version
3675 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3677 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3680 $options['media'] = $media;
3683 $options['condition'] = $condition;
3686 $options['dir'] = $dir;
3688 $this->styles
[$style] = $options;
3692 * Adds inline CSS styles
3693 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3695 * @param mixed $style_css Inline CSS
3696 * @param string $flip Set to 'flip' to flip the CSS if needed
3698 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3699 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3700 # If wanted, and the interface is right-to-left, flip the CSS
3701 $style_css = CSSJanus
::transform( $style_css, true, false );
3703 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3707 * Build exempt modules and legacy non-ResourceLoader styles.
3709 * @return string|WrappedStringList HTML
3711 protected function buildExemptModules() {
3715 // - Within modules provided by the software (core, skin, extensions),
3716 // styles from skin stylesheets should be overridden by styles
3717 // from modules dynamically loaded with JavaScript.
3718 // - Styles from site-specific, private, and user modules should override
3719 // both of the above.
3721 // The effective order for stylesheets must thus be:
3722 // 1. Page style modules, formatted server-side by ResourceLoaderClientHtml.
3723 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
3724 // 3. Styles that are site-specific, private or from the user, formatted
3725 // server-side by this function.
3727 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
3730 // Add legacy styles added through addStyle()/addInlineStyle() here
3731 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3733 // Things that go after the ResourceLoaderDynamicStyles marker
3735 $separateReq = [ 'site.styles', 'user.styles' ];
3736 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3737 if ( $moduleNames ) {
3738 $append[] = $this->makeResourceLoaderLink(
3739 array_diff( $moduleNames, $separateReq ),
3740 ResourceLoaderModule
::TYPE_STYLES
3743 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3744 // These require their own dedicated request in order to support "@import"
3745 // syntax, which is incompatible with concatenation. (T147667, T37562)
3746 $append[] = $this->makeResourceLoaderLink( $name,
3747 ResourceLoaderModule
::TYPE_STYLES
3753 $chunks[] = Html
::element(
3755 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3757 $chunks = array_merge( $chunks, $append );
3760 return self
::combineWrappedStrings( $chunks );
3766 public function buildCssLinksArray() {
3769 foreach ( $this->styles
as $file => $options ) {
3770 $link = $this->styleLink( $file, $options );
3772 $links[$file] = $link;
3779 * Generate \<link\> tags for stylesheets
3781 * @param string $style URL to the file
3782 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3783 * @return string HTML fragment
3785 protected function styleLink( $style, array $options ) {
3786 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3790 if ( isset( $options['media'] ) ) {
3791 $media = self
::transformCssMedia( $options['media'] );
3792 if ( is_null( $media ) ) {
3799 if ( substr( $style, 0, 1 ) == '/' ||
3800 substr( $style, 0, 5 ) == 'http:' ||
3801 substr( $style, 0, 6 ) == 'https:' ) {
3804 $config = $this->getConfig();
3805 // Append file hash as query parameter
3806 $url = self
::transformResourcePath(
3808 $config->get( 'StylePath' ) . '/' . $style
3812 $link = Html
::linkedStyle( $url, $media );
3814 if ( isset( $options['condition'] ) ) {
3815 $condition = htmlspecialchars( $options['condition'] );
3816 $link = "<!--[if $condition]>$link<![endif]-->";
3822 * Transform path to web-accessible static resource.
3824 * This is used to add a validation hash as query string.
3825 * This aids various behaviors:
3827 * - Put long Cache-Control max-age headers on responses for improved
3828 * cache performance.
3829 * - Get the correct version of a file as expected by the current page.
3830 * - Instantly get the updated version of a file after deployment.
3832 * Avoid using this for urls included in HTML as otherwise clients may get different
3833 * versions of a resource when navigating the site depending on when the page was cached.
3834 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3835 * an external stylesheet).
3838 * @param Config $config
3839 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3840 * @return string URL
3842 public static function transformResourcePath( Config
$config, $path ) {
3846 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3847 if ( $remotePathPrefix === '' ) {
3848 // The configured base path is required to be empty string for
3849 // wikis in the domain root
3852 $remotePath = $remotePathPrefix;
3854 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3855 // - Path is outside wgResourceBasePath, ignore.
3856 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3859 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3860 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3861 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3862 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3863 $uploadPath = $config->get( 'UploadPath' );
3864 if ( strpos( $path, $uploadPath ) === 0 ) {
3865 $localDir = $config->get( 'UploadDirectory' );
3866 $remotePathPrefix = $remotePath = $uploadPath;
3869 $path = RelPath
::getRelativePath( $path, $remotePath );
3870 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3874 * Utility method for transformResourceFilePath().
3876 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3879 * @param string $remotePathPrefix URL path prefix that points to $localPath
3880 * @param string $localPath File directory exposed at $remotePath
3881 * @param string $file Path to target file relative to $localPath
3882 * @return string URL
3884 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3885 $hash = md5_file( "$localPath/$file" );
3886 if ( $hash === false ) {
3887 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3890 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3894 * Transform "media" attribute based on request parameters
3896 * @param string $media Current value of the "media" attribute
3897 * @return string Modified value of the "media" attribute, or null to skip
3900 public static function transformCssMedia( $media ) {
3903 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3904 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3906 // Switch in on-screen display for media testing
3908 'printable' => 'print',
3909 'handheld' => 'handheld',
3911 foreach ( $switches as $switch => $targetMedia ) {
3912 if ( $wgRequest->getBool( $switch ) ) {
3913 if ( $media == $targetMedia ) {
3915 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3916 /* This regex will not attempt to understand a comma-separated media_query_list
3918 * Example supported values for $media:
3919 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3920 * Example NOT supported value for $media:
3921 * '3d-glasses, screen, print and resolution > 90dpi'
3923 * If it's a print request, we never want any kind of screen stylesheets
3924 * If it's a handheld request (currently the only other choice with a switch),
3925 * we don't want simple 'screen' but we might want screen queries that
3926 * have a max-width or something, so we'll pass all others on and let the
3927 * client do the query.
3929 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3940 * Add a wikitext-formatted message to the output.
3941 * This is equivalent to:
3943 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3945 public function addWikiMsg( /*...*/ ) {
3946 $args = func_get_args();
3947 $name = array_shift( $args );
3948 $this->addWikiMsgArray( $name, $args );
3952 * Add a wikitext-formatted message to the output.
3953 * Like addWikiMsg() except the parameters are taken as an array
3954 * instead of a variable argument list.
3956 * @param string $name
3957 * @param array $args
3959 public function addWikiMsgArray( $name, $args ) {
3960 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3964 * This function takes a number of message/argument specifications, wraps them in
3965 * some overall structure, and then parses the result and adds it to the output.
3967 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3968 * and so on. The subsequent arguments may be either
3969 * 1) strings, in which case they are message names, or
3970 * 2) arrays, in which case, within each array, the first element is the message
3971 * name, and subsequent elements are the parameters to that message.
3973 * Don't use this for messages that are not in the user's interface language.
3977 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3981 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
3982 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3984 * The newline after the opening div is needed in some wikitext. See T21226.
3986 * @param string $wrap
3988 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3989 $msgSpecs = func_get_args();
3990 array_shift( $msgSpecs );
3991 $msgSpecs = array_values( $msgSpecs );
3993 foreach ( $msgSpecs as $n => $spec ) {
3994 if ( is_array( $spec ) ) {
3996 $name = array_shift( $args );
4001 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
4003 $this->addWikiTextAsInterface( $s );
4007 * Whether the output has a table of contents
4011 public function isTOCEnabled() {
4012 return $this->mEnableTOC
;
4016 * Helper function to setup the PHP implementation of OOUI to use in this request.
4019 * @param string $skinName The Skin name to determine the correct OOUI theme
4020 * @param string $dir Language direction
4022 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4023 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4024 $theme = $themes[$skinName] ??
$themes['default'];
4025 // For example, 'OOUI\WikimediaUITheme'.
4026 $themeClass = "OOUI\\{$theme}Theme";
4027 OOUI\Theme
::setSingleton( new $themeClass() );
4028 OOUI\Element
::setDefaultDir( $dir );
4032 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4033 * MediaWiki and this OutputPage instance.
4037 public function enableOOUI() {
4039 strtolower( $this->getSkin()->getSkinName() ),
4040 $this->getLanguage()->getDir()
4042 $this->addModuleStyles( [
4043 'oojs-ui-core.styles',
4044 'oojs-ui.styles.indicators',
4045 'mediawiki.widgets.styles',
4046 'oojs-ui-core.icons',
4051 * Get (and set if not yet set) the CSP nonce.
4053 * This value needs to be included in any <script> tags on the
4056 * @return string|bool Nonce or false to mean don't output nonce
4059 public function getCSPNonce() {
4060 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4063 if ( $this->CSPNonce
=== null ) {
4064 // XXX It might be expensive to generate randomness
4065 // on every request, on Windows.
4066 $rand = random_bytes( 15 );
4067 $this->CSPNonce
= base64_encode( $rand );
4069 return $this->CSPNonce
;