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\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Session\SessionManager
;
27 use Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\RelPath
;
29 use Wikimedia\WrappedString
;
30 use Wikimedia\WrappedStringList
;
33 * This class should be covered by a general architecture document which does
34 * not exist as of January 2011. This is one of the Core classes and should
35 * be read at least once by any new developers.
37 * This class is used to prepare the final rendering. A skin is then
38 * applied to the output parameters (links, javascript, html, categories ...).
40 * @todo FIXME: Another class handles sending the whole page to the client.
42 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
47 class OutputPage
extends ContextSource
{
48 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
49 protected $mMetatags = [];
52 protected $mLinktags = [];
55 protected $mCanonicalUrl = false;
58 * @var string The contents of <h1> */
59 private $mPageTitle = '';
62 * @var string Contains all of the "<body>" content. Should be private we
63 * got set/get accessors and the append() method.
65 public $mBodytext = '';
67 /** @var string Stores contents of "<title>" tag */
68 private $mHTMLtitle = '';
71 * @var bool Is the displayed content related to the source of the
72 * corresponding wiki article.
74 private $mIsArticle = false;
76 /** @var bool Stores "article flag" toggle. */
77 private $mIsArticleRelated = true;
80 * @var bool We have to set isPrintable(). Some pages should
81 * never be printed (ex: redirections).
83 private $mPrintable = false;
86 * @var array Contains the page subtitle. Special pages usually have some
87 * links here. Don't confuse with site subtitle added by skins.
89 private $mSubtitle = [];
92 public $mRedirect = '';
95 protected $mStatusCode;
98 * @var string Used for sending cache control.
99 * The whole caching system should probably be moved into its own class.
101 protected $mLastModified = '';
104 protected $mCategoryLinks = [];
107 protected $mCategories = [
113 protected $mIndicators = [];
115 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
116 private $mLanguageLinks = [];
119 * Used for JavaScript (predates ResourceLoader)
120 * @todo We should split JS / CSS.
121 * mScripts content is inserted as is in "<head>" by Skin. This might
122 * contain either a link to a stylesheet or inline CSS.
124 private $mScripts = '';
126 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
127 protected $mInlineStyles = '';
130 * @var string Used by skin template.
131 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
133 public $mPageLinkTitle = '';
135 /** @var array Array of elements in "<head>". Parser might add its own headers! */
136 protected $mHeadItems = [];
138 /** @var array Additional <body> classes; there are also <body> classes from other sources */
139 protected $mAdditionalBodyClasses = [];
142 protected $mModules = [];
145 protected $mModuleScripts = [];
148 protected $mModuleStyles = [];
150 /** @var ResourceLoader */
151 protected $mResourceLoader;
153 /** @var ResourceLoaderClientHtml */
156 /** @var ResourceLoaderContext */
157 private $rlClientContext;
160 private $rlExemptStyleModules;
163 protected $mJsConfigVars = [];
166 protected $mTemplateIds = [];
169 protected $mImageTimeKeys = [];
172 public $mRedirectCode = '';
174 protected $mFeedLinksAppendQuery = null;
177 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
178 * @see ResourceLoaderModule::$origin
179 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
181 protected $mAllowedModules = [
182 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
185 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
186 protected $mDoNothing = false;
191 protected $mContainsNewMagic = 0;
194 * lazy initialised, use parserOptions()
197 protected $mParserOptions = null;
200 * Handles the Atom / RSS links.
201 * We probably only support Atom in 2011.
202 * @see $wgAdvertisedFeedTypes
204 private $mFeedLinks = [];
206 // Gwicke work on squid caching? Roughly from 2003.
207 protected $mEnableClientCache = true;
209 /** @var bool Flag if output should only contain the body of the article. */
210 private $mArticleBodyOnly = false;
213 protected $mNewSectionLink = false;
216 protected $mHideNewSectionLink = false;
219 * @var bool Comes from the parser. This was probably made to load CSS/JS
220 * only if we had "<gallery>". Used directly in CategoryPage.php.
221 * Looks like ResourceLoader can replace this.
223 public $mNoGallery = false;
225 /** @var int Cache stuff. Looks like mEnableClientCache */
226 protected $mCdnMaxage = 0;
227 /** @var int Upper limit on mCdnMaxage */
228 protected $mCdnMaxageLimit = INF
;
231 * @var bool Controls if anti-clickjacking / frame-breaking headers will
232 * be sent. This should be done for pages where edit actions are possible.
233 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
235 protected $mPreventClickjacking = true;
237 /** @var int To include the variable {{REVISIONID}} */
238 private $mRevisionId = null;
241 private $mRevisionTimestamp = null;
244 protected $mFileVersion = null;
247 * @var array An array of stylesheet filenames (relative from skins path),
248 * with options for CSS media, IE conditions, and RTL/LTR direction.
249 * For internal use; add settings in the skin via $this->addStyle()
251 * Style again! This seems like a code duplication since we already have
252 * mStyles. This is what makes Open Source amazing.
254 protected $styles = [];
256 private $mIndexPolicy = 'index';
257 private $mFollowPolicy = 'follow';
260 * @var array Headers that cause the cache to vary. Key is header name, value is an array of
261 * options for the Key header.
263 private $mVaryHeader = [
264 'Accept-Encoding' => [ 'match=gzip' ],
268 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
273 private $mRedirectedFrom = null;
276 * Additional key => value data
278 private $mProperties = [];
281 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
283 private $mTarget = null;
286 * @var bool Whether parser output contains a table of contents
288 private $mEnableTOC = false;
291 * @var string|null The URL to send in a <link> element with rel=license
293 private $copyrightUrl;
295 /** @var array Profiling data */
296 private $limitReportJSData = [];
298 /** @var array Map Title to Content */
299 private $contentOverrides = [];
301 /** @var callable[] */
302 private $contentOverrideCallbacks = [];
305 * Link: header contents
307 private $mLinkHeader = [];
310 * @var string The nonce for Content-Security-Policy
315 * Constructor for OutputPage. This should not be called directly.
316 * Instead a new RequestContext should be created and it will implicitly create
317 * a OutputPage tied to that context.
318 * @param IContextSource $context
320 function __construct( IContextSource
$context ) {
321 $this->setContext( $context );
325 * Redirect to $url rather than displaying the normal page
328 * @param string $responsecode HTTP status code
330 public function redirect( $url, $responsecode = '302' ) {
331 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
332 $this->mRedirect
= str_replace( "\n", '', $url );
333 $this->mRedirectCode
= $responsecode;
337 * Get the URL to redirect to, or an empty string if not redirect URL set
341 public function getRedirect() {
342 return $this->mRedirect
;
346 * Set the copyright URL to send with the output.
347 * Empty string to omit, null to reset.
351 * @param string|null $url
353 public function setCopyrightUrl( $url ) {
354 $this->copyrightUrl
= $url;
358 * Set the HTTP status code to send with the output.
360 * @param int $statusCode
362 public function setStatusCode( $statusCode ) {
363 $this->mStatusCode
= $statusCode;
367 * Add a new "<meta>" tag
368 * To add an http-equiv meta tag, precede the name with "http:"
370 * @param string $name Name of the meta tag
371 * @param string $val Value of the meta tag
373 function addMeta( $name, $val ) {
374 array_push( $this->mMetatags
, [ $name, $val ] );
378 * Returns the current <meta> tags
383 public function getMetaTags() {
384 return $this->mMetatags
;
388 * Add a new \<link\> tag to the page header.
390 * Note: use setCanonicalUrl() for rel=canonical.
392 * @param array $linkarr Associative array of attributes.
394 function addLink( array $linkarr ) {
395 array_push( $this->mLinktags
, $linkarr );
399 * Returns the current <link> tags
404 public function getLinkTags() {
405 return $this->mLinktags
;
409 * Set the URL to be used for the <link rel=canonical>. This should be used
410 * in preference to addLink(), to avoid duplicate link tags.
413 function setCanonicalUrl( $url ) {
414 $this->mCanonicalUrl
= $url;
418 * Returns the URL to be used for the <link rel=canonical> if
422 * @return bool|string
424 public function getCanonicalUrl() {
425 return $this->mCanonicalUrl
;
429 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
430 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
433 * @param string $script Raw HTML
435 function addScript( $script ) {
436 $this->mScripts
.= $script;
440 * Add a JavaScript file to be loaded as `<script>` on this page.
442 * Internal use only. Use OutputPage::addModules() if possible.
444 * @param string $file URL to file (absolute path, protocol-relative, or full url)
445 * @param string|null $unused Previously used to change the cache-busting query parameter
447 public function addScriptFile( $file, $unused = null ) {
448 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
449 // This is not an absolute path, protocol-relative url, or full scheme url,
450 // presumed to be an old call intended to include a file from /w/skins/common,
451 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
452 wfDeprecated( __METHOD__
, '1.24' );
455 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
459 * Add a self-contained script tag with the given contents
460 * Internal use only. Use OutputPage::addModules() if possible.
462 * @param string $script JavaScript text, no script tags
464 public function addInlineScript( $script ) {
465 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
469 * Filter an array of modules to remove insufficiently trustworthy members, and modules
470 * which are no longer registered (eg a page is cached before an extension is disabled)
471 * @param array $modules
472 * @param string|null $position Unused
473 * @param string $type
476 protected function filterModules( array $modules, $position = null,
477 $type = ResourceLoaderModule
::TYPE_COMBINED
479 $resourceLoader = $this->getResourceLoader();
480 $filteredModules = [];
481 foreach ( $modules as $val ) {
482 $module = $resourceLoader->getModule( $val );
483 if ( $module instanceof ResourceLoaderModule
484 && $module->getOrigin() <= $this->getAllowedModules( $type )
486 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
487 $this->warnModuleTargetFilter( $module->getName() );
490 $filteredModules[] = $val;
493 return $filteredModules;
496 private function warnModuleTargetFilter( $moduleName ) {
497 static $warnings = [];
498 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
501 $warnings[$this->mTarget
][$moduleName] = true;
502 $this->getResourceLoader()->getLogger()->debug(
503 'Module "{module}" not loadable on target "{target}".',
505 'module' => $moduleName,
506 'target' => $this->mTarget
,
512 * Get the list of modules to include on this page
514 * @param bool $filter Whether to filter out insufficiently trustworthy modules
515 * @param string|null $position Unused
516 * @param string $param
517 * @param string $type
518 * @return array Array of module names
520 public function getModules( $filter = false, $position = null, $param = 'mModules',
521 $type = ResourceLoaderModule
::TYPE_COMBINED
523 $modules = array_values( array_unique( $this->$param ) );
525 ?
$this->filterModules( $modules, null, $type )
530 * Load one or more ResourceLoader modules on this page.
532 * @param string|array $modules Module name (string) or array of module names
534 public function addModules( $modules ) {
535 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
539 * Get the list of script-only modules to load on this page.
541 * @param bool $filter
542 * @param string|null $position Unused
543 * @return array Array of module names
545 public function getModuleScripts( $filter = false, $position = null ) {
546 return $this->getModules( $filter, null, 'mModuleScripts',
547 ResourceLoaderModule
::TYPE_SCRIPTS
552 * Load the scripts of one or more ResourceLoader modules, on this page.
554 * This method exists purely to provide the legacy behaviour of loading
555 * a module's scripts in the global scope, and without dependency resolution.
556 * See <https://phabricator.wikimedia.org/T188689>.
558 * @deprecated since 1.31 Use addModules() instead.
559 * @param string|array $modules Module name (string) or array of module names
561 public function addModuleScripts( $modules ) {
562 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
566 * Get the list of style-only modules to load on this page.
568 * @param bool $filter
569 * @param string|null $position Unused
570 * @return array Array of module names
572 public function getModuleStyles( $filter = false, $position = null ) {
573 return $this->getModules( $filter, null, 'mModuleStyles',
574 ResourceLoaderModule
::TYPE_STYLES
579 * Load the styles of one or more ResourceLoader modules on this page.
581 * Module styles added through this function will be loaded as a stylesheet,
582 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
583 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
585 * @param string|array $modules Module name (string) or array of module names
587 public function addModuleStyles( $modules ) {
588 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
592 * @return null|string ResourceLoader target
594 public function getTarget() {
595 return $this->mTarget
;
599 * Sets ResourceLoader target for load.php links. If null, will be omitted
601 * @param string|null $target
603 public function setTarget( $target ) {
604 $this->mTarget
= $target;
608 * Add a mapping from a LinkTarget to a Content, for things like page preview.
609 * @see self::addContentOverrideCallback()
611 * @param LinkTarget $target
612 * @param Content $content
614 public function addContentOverride( LinkTarget
$target, Content
$content ) {
615 if ( !$this->contentOverrides
) {
616 // Register a callback for $this->contentOverrides on the first call
617 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
618 $key = $target->getNamespace() . ':' . $target->getDBkey();
619 return $this->contentOverrides
[$key] ??
null;
623 $key = $target->getNamespace() . ':' . $target->getDBkey();
624 $this->contentOverrides
[$key] = $content;
628 * Add a callback for mapping from a Title to a Content object, for things
630 * @see ResourceLoaderContext::getContentOverrideCallback()
632 * @param callable $callback
634 public function addContentOverrideCallback( callable
$callback ) {
635 $this->contentOverrideCallbacks
[] = $callback;
639 * Get an array of head items
643 function getHeadItemsArray() {
644 return $this->mHeadItems
;
648 * Add or replace a head item to the output
650 * Whenever possible, use more specific options like ResourceLoader modules,
651 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
652 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
653 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
654 * This would be your very LAST fallback.
656 * @param string $name Item name
657 * @param string $value Raw HTML
659 public function addHeadItem( $name, $value ) {
660 $this->mHeadItems
[$name] = $value;
664 * Add one or more head items to the output
667 * @param string|string[] $values Raw HTML
669 public function addHeadItems( $values ) {
670 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
674 * Check if the header item $name is already set
676 * @param string $name Item name
679 public function hasHeadItem( $name ) {
680 return isset( $this->mHeadItems
[$name] );
684 * Add a class to the <body> element
687 * @param string|string[] $classes One or more classes to add
689 public function addBodyClasses( $classes ) {
690 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
694 * Set whether the output should only contain the body of the article,
695 * without any skin, sidebar, etc.
696 * Used e.g. when calling with "action=render".
698 * @param bool $only Whether to output only the body of the article
700 public function setArticleBodyOnly( $only ) {
701 $this->mArticleBodyOnly
= $only;
705 * Return whether the output will contain only the body of the article
709 public function getArticleBodyOnly() {
710 return $this->mArticleBodyOnly
;
714 * Set an additional output property
717 * @param string $name
718 * @param mixed $value
720 public function setProperty( $name, $value ) {
721 $this->mProperties
[$name] = $value;
725 * Get an additional output property
728 * @param string $name
729 * @return mixed Property value or null if not found
731 public function getProperty( $name ) {
732 return $this->mProperties
[$name] ??
null;
736 * checkLastModified tells the client to use the client-cached page if
737 * possible. If successful, the OutputPage is disabled so that
738 * any future call to OutputPage->output() have no effect.
740 * Side effect: sets mLastModified for Last-Modified header
742 * @param string $timestamp
744 * @return bool True if cache-ok headers was sent.
746 public function checkLastModified( $timestamp ) {
747 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
748 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
751 $config = $this->getConfig();
752 if ( !$config->get( 'CachePages' ) ) {
753 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
757 $timestamp = wfTimestamp( TS_MW
, $timestamp );
759 'page' => $timestamp,
760 'user' => $this->getUser()->getTouched(),
761 'epoch' => $config->get( 'CacheEpoch' )
763 if ( $config->get( 'UseSquid' ) ) {
764 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
766 $config->get( 'SquidMaxage' )
769 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
771 $maxModified = max( $modifiedTimes );
772 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
774 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
775 if ( $clientHeader === false ) {
776 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
780 # IE sends sizes after the date like this:
781 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
782 # this breaks strtotime().
783 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
785 Wikimedia\
suppressWarnings(); // E_STRICT system time warnings
786 $clientHeaderTime = strtotime( $clientHeader );
787 Wikimedia\restoreWarnings
();
788 if ( !$clientHeaderTime ) {
790 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
793 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
797 foreach ( $modifiedTimes as $name => $value ) {
798 if ( $info !== '' ) {
801 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
804 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
805 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
806 wfDebug( __METHOD__
. ": effective Last-Modified: " .
807 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
808 if ( $clientHeaderTime < $maxModified ) {
809 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
814 # Give a 304 Not Modified response code and disable body output
815 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
816 ini_set( 'zlib.output_compression', 0 );
817 $this->getRequest()->response()->statusHeader( 304 );
818 $this->sendCacheControl();
821 // Don't output a compressed blob when using ob_gzhandler;
822 // it's technically against HTTP spec and seems to confuse
823 // Firefox when the response gets split over two packets.
824 wfClearOutputBuffers();
830 * @param int $reqTime Time of request (eg. now)
831 * @param int $maxAge Cache TTL in seconds
832 * @return int Timestamp
834 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
835 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
836 // because even if the wiki page content hasn't changed since, static
837 // resources may have changed (skin HTML, interface messages, urls, etc.)
838 // and must roll-over in a timely manner (T46570)
839 return $reqTime - $maxAge;
843 * Override the last modified timestamp
845 * @param string $timestamp New timestamp, in a format readable by
848 public function setLastModified( $timestamp ) {
849 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
853 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
855 * @param string $policy The literal string to output as the contents of
856 * the meta tag. Will be parsed according to the spec and output in
860 public function setRobotPolicy( $policy ) {
861 $policy = Article
::formatRobotPolicy( $policy );
863 if ( isset( $policy['index'] ) ) {
864 $this->setIndexPolicy( $policy['index'] );
866 if ( isset( $policy['follow'] ) ) {
867 $this->setFollowPolicy( $policy['follow'] );
872 * Set the index policy for the page, but leave the follow policy un-
875 * @param string $policy Either 'index' or 'noindex'.
878 public function setIndexPolicy( $policy ) {
879 $policy = trim( $policy );
880 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
881 $this->mIndexPolicy
= $policy;
886 * Set the follow policy for the page, but leave the index policy un-
889 * @param string $policy Either 'follow' or 'nofollow'.
892 public function setFollowPolicy( $policy ) {
893 $policy = trim( $policy );
894 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
895 $this->mFollowPolicy
= $policy;
900 * "HTML title" means the contents of "<title>".
901 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
903 * @param string|Message $name
905 public function setHTMLTitle( $name ) {
906 if ( $name instanceof Message
) {
907 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
909 $this->mHTMLtitle
= $name;
914 * Return the "HTML title", i.e. the content of the "<title>" tag.
918 public function getHTMLTitle() {
919 return $this->mHTMLtitle
;
923 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
927 public function setRedirectedFrom( $t ) {
928 $this->mRedirectedFrom
= $t;
932 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
933 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
934 * but not bad tags like \<script\>. This function automatically sets
935 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
936 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
937 * good tags like \<i\> will be dropped entirely.
939 * @param string|Message $name
941 public function setPageTitle( $name ) {
942 if ( $name instanceof Message
) {
943 $name = $name->setContext( $this->getContext() )->text();
946 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
947 # but leave "<i>foobar</i>" alone
948 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
949 $this->mPageTitle
= $nameWithTags;
951 # change "<i>foo&bar</i>" to "foo&bar"
953 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
954 ->inContentLanguage()
959 * Return the "page title", i.e. the content of the \<h1\> tag.
963 public function getPageTitle() {
964 return $this->mPageTitle
;
968 * Set the Title object to use
972 public function setTitle( Title
$t ) {
973 $this->getContext()->setTitle( $t );
977 * Replace the subtitle with $str
979 * @param string|Message $str New value of the subtitle. String should be safe HTML.
981 public function setSubtitle( $str ) {
982 $this->clearSubtitle();
983 $this->addSubtitle( $str );
987 * Add $str to the subtitle
989 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
991 public function addSubtitle( $str ) {
992 if ( $str instanceof Message
) {
993 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
995 $this->mSubtitle
[] = $str;
1000 * Build message object for a subtitle containing a backlink to a page
1002 * @param Title $title Title to link to
1003 * @param array $query Array of additional parameters to include in the link
1007 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1008 if ( $title->isRedirect() ) {
1009 $query['redirect'] = 'no';
1011 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1012 return wfMessage( 'backlinksubtitle' )
1013 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1017 * Add a subtitle containing a backlink to a page
1019 * @param Title $title Title to link to
1020 * @param array $query Array of additional parameters to include in the link
1022 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1023 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1027 * Clear the subtitles
1029 public function clearSubtitle() {
1030 $this->mSubtitle
= [];
1038 public function getSubtitle() {
1039 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1043 * Set the page as printable, i.e. it'll be displayed with all
1044 * print styles included
1046 public function setPrintable() {
1047 $this->mPrintable
= true;
1051 * Return whether the page is "printable"
1055 public function isPrintable() {
1056 return $this->mPrintable
;
1060 * Disable output completely, i.e. calling output() will have no effect
1062 public function disable() {
1063 $this->mDoNothing
= true;
1067 * Return whether the output will be completely disabled
1071 public function isDisabled() {
1072 return $this->mDoNothing
;
1076 * Show an "add new section" link?
1080 public function showNewSectionLink() {
1081 return $this->mNewSectionLink
;
1085 * Forcibly hide the new section link?
1089 public function forceHideNewSectionLink() {
1090 return $this->mHideNewSectionLink
;
1094 * Add or remove feed links in the page header
1095 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1096 * for the new version
1097 * @see addFeedLink()
1099 * @param bool $show True: add default feeds, false: remove all feeds
1101 public function setSyndicated( $show = true ) {
1103 $this->setFeedAppendQuery( false );
1105 $this->mFeedLinks
= [];
1110 * Add default feeds to the page header
1111 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1112 * for the new version
1113 * @see addFeedLink()
1115 * @param string $val Query to append to feed links or false to output
1118 public function setFeedAppendQuery( $val ) {
1119 $this->mFeedLinks
= [];
1121 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1122 $query = "feed=$type";
1123 if ( is_string( $val ) ) {
1124 $query .= '&' . $val;
1126 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1131 * Add a feed link to the page header
1133 * @param string $format Feed type, should be a key of $wgFeedClasses
1134 * @param string $href URL
1136 public function addFeedLink( $format, $href ) {
1137 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1138 $this->mFeedLinks
[$format] = $href;
1143 * Should we output feed links for this page?
1146 public function isSyndicated() {
1147 return count( $this->mFeedLinks
) > 0;
1151 * Return URLs for each supported syndication format for this page.
1152 * @return array Associating format keys with URLs
1154 public function getSyndicationLinks() {
1155 return $this->mFeedLinks
;
1159 * Will currently always return null
1163 public function getFeedAppendQuery() {
1164 return $this->mFeedLinksAppendQuery
;
1168 * Set whether the displayed content is related to the source of the
1169 * corresponding article on the wiki
1170 * Setting true will cause the change "article related" toggle to true
1172 * @param bool $newVal
1174 public function setArticleFlag( $newVal ) {
1175 $this->mIsArticle
= $newVal;
1177 $this->mIsArticleRelated
= $newVal;
1182 * Return whether the content displayed page is related to the source of
1183 * the corresponding article on the wiki
1187 public function isArticle() {
1188 return $this->mIsArticle
;
1192 * Set whether this page is related an article on the wiki
1193 * Setting false will cause the change of "article flag" toggle to false
1195 * @param bool $newVal
1197 public function setArticleRelated( $newVal ) {
1198 $this->mIsArticleRelated
= $newVal;
1200 $this->mIsArticle
= false;
1205 * Return whether this page is related an article on the wiki
1209 public function isArticleRelated() {
1210 return $this->mIsArticleRelated
;
1214 * Add new language links
1216 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1217 * (e.g. 'fr:Test page')
1219 public function addLanguageLinks( array $newLinkArray ) {
1220 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1224 * Reset the language links and add new language links
1226 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1227 * (e.g. 'fr:Test page')
1229 public function setLanguageLinks( array $newLinkArray ) {
1230 $this->mLanguageLinks
= $newLinkArray;
1234 * Get the list of language links
1236 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1238 public function getLanguageLinks() {
1239 return $this->mLanguageLinks
;
1243 * Add an array of categories, with names in the keys
1245 * @param array $categories Mapping category name => sort key
1247 public function addCategoryLinks( array $categories ) {
1248 if ( !$categories ) {
1252 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1254 # Set all the values to 'normal'.
1255 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1257 # Mark hidden categories
1258 foreach ( $res as $row ) {
1259 if ( isset( $row->pp_value
) ) {
1260 $categories[$row->page_title
] = 'hidden';
1264 // Avoid PHP 7.1 warning of passing $this by reference
1265 $outputPage = $this;
1266 # Add the remaining categories to the skin
1268 'OutputPageMakeCategoryLinks',
1269 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1271 $services = MediaWikiServices
::getInstance();
1272 $linkRenderer = $services->getLinkRenderer();
1273 foreach ( $categories as $category => $type ) {
1274 // array keys will cast numeric category names to ints, so cast back to string
1275 $category = (string)$category;
1276 $origcategory = $category;
1277 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1281 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1282 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1285 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1286 $this->mCategories
[$type][] = $title->getText();
1287 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1293 * @param array $categories
1294 * @return bool|IResultWrapper
1296 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1297 # Add the links to a LinkBatch
1298 $arr = [ NS_CATEGORY
=> $categories ];
1299 $lb = new LinkBatch
;
1300 $lb->setArray( $arr );
1302 # Fetch existence plus the hiddencat property
1303 $dbr = wfGetDB( DB_REPLICA
);
1304 $fields = array_merge(
1305 LinkCache
::getSelectFields(),
1306 [ 'page_namespace', 'page_title', 'pp_value' ]
1309 $res = $dbr->select( [ 'page', 'page_props' ],
1311 $lb->constructSet( 'page', $dbr ),
1314 [ 'page_props' => [ 'LEFT JOIN', [
1315 'pp_propname' => 'hiddencat',
1320 # Add the results to the link cache
1321 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1322 $lb->addResultToCache( $linkCache, $res );
1328 * Reset the category links (but not the category list) and add $categories
1330 * @param array $categories Mapping category name => sort key
1332 public function setCategoryLinks( array $categories ) {
1333 $this->mCategoryLinks
= [];
1334 $this->addCategoryLinks( $categories );
1338 * Get the list of category links, in a 2-D array with the following format:
1339 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1340 * hidden categories) and $link a HTML fragment with a link to the category
1345 public function getCategoryLinks() {
1346 return $this->mCategoryLinks
;
1350 * Get the list of category names this page belongs to.
1352 * @param string $type The type of categories which should be returned. Possible values:
1353 * * all: all categories of all types
1354 * * hidden: only the hidden categories
1355 * * normal: all categories, except hidden categories
1356 * @return array Array of strings
1358 public function getCategories( $type = 'all' ) {
1359 if ( $type === 'all' ) {
1360 $allCategories = [];
1361 foreach ( $this->mCategories
as $categories ) {
1362 $allCategories = array_merge( $allCategories, $categories );
1364 return $allCategories;
1366 if ( !isset( $this->mCategories
[$type] ) ) {
1367 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1369 return $this->mCategories
[$type];
1373 * Add an array of indicators, with their identifiers as array
1374 * keys and HTML contents as values.
1376 * In case of duplicate keys, existing values are overwritten.
1378 * @param array $indicators
1381 public function setIndicators( array $indicators ) {
1382 $this->mIndicators
= $indicators +
$this->mIndicators
;
1383 // Keep ordered by key
1384 ksort( $this->mIndicators
);
1388 * Get the indicators associated with this page.
1390 * The array will be internally ordered by item keys.
1392 * @return array Keys: identifiers, values: HTML contents
1395 public function getIndicators() {
1396 return $this->mIndicators
;
1400 * Adds help link with an icon via page indicators.
1401 * Link target can be overridden by a local message containing a wikilink:
1402 * the message key is: lowercase action or special page name + '-helppage'.
1403 * @param string $to Target MediaWiki.org page title or encoded URL.
1404 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1407 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1408 $this->addModuleStyles( 'mediawiki.helplink' );
1409 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1411 if ( $overrideBaseUrl ) {
1414 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1415 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1418 $link = Html
::rawElement(
1422 'target' => '_blank',
1423 'class' => 'mw-helplink',
1428 $this->setIndicators( [ 'mw-helplink' => $link ] );
1432 * Do not allow scripts which can be modified by wiki users to load on this page;
1433 * only allow scripts bundled with, or generated by, the software.
1434 * Site-wide styles are controlled by a config setting, since they can be
1435 * used to create a custom skin/theme, but not user-specific ones.
1437 * @todo this should be given a more accurate name
1439 public function disallowUserJs() {
1440 $this->reduceAllowedModules(
1441 ResourceLoaderModule
::TYPE_SCRIPTS
,
1442 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1445 // Site-wide styles are controlled by a config setting, see T73621
1446 // for background on why. User styles are never allowed.
1447 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1448 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1450 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1452 $this->reduceAllowedModules(
1453 ResourceLoaderModule
::TYPE_STYLES
,
1459 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1460 * @see ResourceLoaderModule::$origin
1461 * @param string $type ResourceLoaderModule TYPE_ constant
1462 * @return int ResourceLoaderModule ORIGIN_ class constant
1464 public function getAllowedModules( $type ) {
1465 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1466 return min( array_values( $this->mAllowedModules
) );
1468 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1473 * Limit the highest level of CSS/JS untrustworthiness allowed.
1475 * If passed the same or a higher level than the current level of untrustworthiness set, the
1476 * level will remain unchanged.
1478 * @param string $type
1479 * @param int $level ResourceLoaderModule class constant
1481 public function reduceAllowedModules( $type, $level ) {
1482 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1486 * Prepend $text to the body HTML
1488 * @param string $text HTML
1490 public function prependHTML( $text ) {
1491 $this->mBodytext
= $text . $this->mBodytext
;
1495 * Append $text to the body HTML
1497 * @param string $text HTML
1499 public function addHTML( $text ) {
1500 $this->mBodytext
.= $text;
1504 * Shortcut for adding an Html::element via addHTML.
1508 * @param string $element
1509 * @param array $attribs
1510 * @param string $contents
1512 public function addElement( $element, array $attribs = [], $contents = '' ) {
1513 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1517 * Clear the body HTML
1519 public function clearHTML() {
1520 $this->mBodytext
= '';
1526 * @return string HTML
1528 public function getHTML() {
1529 return $this->mBodytext
;
1533 * Get/set the ParserOptions object to use for wikitext parsing
1535 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1536 * current ParserOption object. This parameter is deprecated since 1.31.
1537 * @return ParserOptions
1539 public function parserOptions( $options = null ) {
1540 if ( $options !== null ) {
1541 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1544 if ( $options !== null && !empty( $options->isBogus
) ) {
1545 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1546 // been changed somehow, and keep it if so.
1547 $anonPO = ParserOptions
::newFromAnon();
1548 $anonPO->setAllowUnsafeRawHtml( false );
1549 if ( !$options->matches( $anonPO ) ) {
1550 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1551 $options->isBogus
= false;
1555 if ( !$this->mParserOptions
) {
1556 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1557 // $wgUser isn't unstubbable yet, so don't try to get a
1558 // ParserOptions for it. And don't cache this ParserOptions
1560 $po = ParserOptions
::newFromAnon();
1561 $po->setAllowUnsafeRawHtml( false );
1562 $po->isBogus
= true;
1563 if ( $options !== null ) {
1564 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1569 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1570 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1573 if ( $options !== null && !empty( $options->isBogus
) ) {
1574 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1576 return wfSetVar( $this->mParserOptions
, null, true );
1578 return wfSetVar( $this->mParserOptions
, $options );
1583 * Set the revision ID which will be seen by the wiki text parser
1584 * for things such as embedded {{REVISIONID}} variable use.
1586 * @param int|null $revid A positive integer, or null
1587 * @return mixed Previous value
1589 public function setRevisionId( $revid ) {
1590 $val = is_null( $revid ) ?
null : intval( $revid );
1591 return wfSetVar( $this->mRevisionId
, $val, true );
1595 * Get the displayed revision ID
1599 public function getRevisionId() {
1600 return $this->mRevisionId
;
1604 * Set the timestamp of the revision which will be displayed. This is used
1605 * to avoid a extra DB call in Skin::lastModified().
1607 * @param string|null $timestamp
1608 * @return mixed Previous value
1610 public function setRevisionTimestamp( $timestamp ) {
1611 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1615 * Get the timestamp of displayed revision.
1616 * This will be null if not filled by setRevisionTimestamp().
1618 * @return string|null
1620 public function getRevisionTimestamp() {
1621 return $this->mRevisionTimestamp
;
1625 * Set the displayed file version
1627 * @param File|null $file
1628 * @return mixed Previous value
1630 public function setFileVersion( $file ) {
1632 if ( $file instanceof File
&& $file->exists() ) {
1633 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1635 return wfSetVar( $this->mFileVersion
, $val, true );
1639 * Get the displayed file version
1641 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1643 public function getFileVersion() {
1644 return $this->mFileVersion
;
1648 * Get the templates used on this page
1650 * @return array (namespace => dbKey => revId)
1653 public function getTemplateIds() {
1654 return $this->mTemplateIds
;
1658 * Get the files used on this page
1660 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1663 public function getFileSearchOptions() {
1664 return $this->mImageTimeKeys
;
1668 * Convert wikitext to HTML and add it to the buffer
1669 * Default assumes that the current page title will be used.
1671 * @param string $text
1672 * @param bool $linestart Is this the start of a line?
1673 * @param bool $interface Is this text in the user interface language?
1674 * @throws MWException
1676 public function addWikiText( $text, $linestart = true, $interface = true ) {
1677 $title = $this->getTitle(); // Work around E_STRICT
1679 throw new MWException( 'Title is null' );
1681 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1685 * Add wikitext with a custom Title object
1687 * @param string $text Wikitext
1688 * @param Title $title
1689 * @param bool $linestart Is this the start of a line?
1691 public function addWikiTextWithTitle( $text, Title
$title, $linestart = true ) {
1692 $this->addWikiTextTitle( $text, $title, $linestart );
1696 * Add wikitext with a custom Title object and tidy enabled.
1698 * @param string $text Wikitext
1699 * @param Title $title
1700 * @param bool $linestart Is this the start of a line?
1702 function addWikiTextTitleTidy( $text, Title
$title, $linestart = true ) {
1703 $this->addWikiTextTitle( $text, $title, $linestart, true );
1707 * Add wikitext with tidy enabled
1709 * @param string $text Wikitext
1710 * @param bool $linestart Is this the start of a line?
1712 public function addWikiTextTidy( $text, $linestart = true ) {
1713 $title = $this->getTitle();
1714 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1718 * Add wikitext with a custom Title object
1720 * @param string $text Wikitext
1721 * @param Title $title
1722 * @param bool $linestart Is this the start of a line?
1723 * @param bool $tidy Whether to use tidy
1724 * @param bool $interface Whether it is an interface message
1725 * (for example disables conversion)
1727 public function addWikiTextTitle( $text, Title
$title, $linestart,
1728 $tidy = false, $interface = false
1732 $popts = $this->parserOptions();
1733 $oldTidy = $popts->setTidy( $tidy );
1734 $popts->setInterfaceMessage( (bool)$interface );
1736 $parserOutput = $wgParser->getFreshParser()->parse(
1737 $text, $title, $popts,
1738 $linestart, true, $this->mRevisionId
1741 $popts->setTidy( $oldTidy );
1743 $this->addParserOutput( $parserOutput, [
1744 'enableSectionEditLinks' => false,
1749 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1750 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1754 * @param ParserOutput $parserOutput
1756 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1757 $this->mLanguageLinks
=
1758 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1759 $this->addCategoryLinks( $parserOutput->getCategories() );
1760 $this->setIndicators( $parserOutput->getIndicators() );
1761 $this->mNewSectionLink
= $parserOutput->getNewSection();
1762 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1764 if ( !$parserOutput->isCacheable() ) {
1765 $this->enableClientCache( false );
1767 $this->mNoGallery
= $parserOutput->getNoGallery();
1768 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1769 $this->addModules( $parserOutput->getModules() );
1770 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1771 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1772 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1773 $this->mPreventClickjacking
= $this->mPreventClickjacking
1774 ||
$parserOutput->preventClickjacking();
1776 // Template versioning...
1777 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1778 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1779 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1781 $this->mTemplateIds
[$ns] = $dbks;
1784 // File versioning...
1785 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1786 $this->mImageTimeKeys
[$dbk] = $data;
1789 // Hooks registered in the object
1790 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1791 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1792 list( $hookName, $data ) = $hookInfo;
1793 if ( isset( $parserOutputHooks[$hookName] ) ) {
1794 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1798 // Enable OOUI if requested via ParserOutput
1799 if ( $parserOutput->getEnableOOUI() ) {
1800 $this->enableOOUI();
1803 // Include parser limit report
1804 if ( !$this->limitReportJSData
) {
1805 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1808 // Link flags are ignored for now, but may in the future be
1809 // used to mark individual language links.
1811 // Avoid PHP 7.1 warning of passing $this by reference
1812 $outputPage = $this;
1813 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1814 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1816 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1817 // so that extensions may modify ParserOutput to toggle TOC.
1818 // This cannot be moved to addParserOutputText because that is not
1819 // called by EditPage for Preview.
1820 if ( $parserOutput->getTOCHTML() ) {
1821 $this->mEnableTOC
= true;
1826 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1827 * ParserOutput object, without any other metadata.
1830 * @param ParserOutput $parserOutput
1831 * @param array $poOptions Options to ParserOutput::getText()
1833 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
1834 $this->addParserOutputText( $parserOutput, $poOptions );
1836 $this->addModules( $parserOutput->getModules() );
1837 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1838 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1840 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1844 * Add the HTML associated with a ParserOutput object, without any metadata.
1847 * @param ParserOutput $parserOutput
1848 * @param array $poOptions Options to ParserOutput::getText()
1850 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
1851 $text = $parserOutput->getText( $poOptions );
1852 // Avoid PHP 7.1 warning of passing $this by reference
1853 $outputPage = $this;
1854 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1855 $this->addHTML( $text );
1859 * Add everything from a ParserOutput object.
1861 * @param ParserOutput $parserOutput
1862 * @param array $poOptions Options to ParserOutput::getText()
1864 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
1865 $this->addParserOutputMetadata( $parserOutput );
1866 $this->addParserOutputText( $parserOutput, $poOptions );
1870 * Add the output of a QuickTemplate to the output buffer
1872 * @param QuickTemplate &$template
1874 public function addTemplate( &$template ) {
1875 $this->addHTML( $template->getHTML() );
1879 * Parse wikitext and return the HTML.
1881 * @param string $text
1882 * @param bool $linestart Is this the start of a line?
1883 * @param bool $interface Use interface language (instead of content language) while parsing
1884 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1885 * LanguageConverter.
1886 * @param Language|null $language Target language object, will override $interface
1887 * @throws MWException
1888 * @return string HTML
1890 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1893 if ( is_null( $this->getTitle() ) ) {
1894 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1897 $popts = $this->parserOptions();
1899 $popts->setInterfaceMessage( true );
1901 if ( $language !== null ) {
1902 $oldLang = $popts->setTargetLanguage( $language );
1905 $parserOutput = $wgParser->getFreshParser()->parse(
1906 $text, $this->getTitle(), $popts,
1907 $linestart, true, $this->mRevisionId
1911 $popts->setInterfaceMessage( false );
1913 if ( $language !== null ) {
1914 $popts->setTargetLanguage( $oldLang );
1917 return $parserOutput->getText( [
1918 'enableSectionEditLinks' => false,
1923 * Parse wikitext, strip paragraphs, and return the HTML.
1925 * @param string $text
1926 * @param bool $linestart Is this the start of a line?
1927 * @param bool $interface Use interface language (instead of content language) while parsing
1928 * language sensitive magic words like GRAMMAR and PLURAL
1929 * @return string HTML
1931 public function parseInline( $text, $linestart = true, $interface = false ) {
1932 $parsed = $this->parse( $text, $linestart, $interface );
1933 return Parser
::stripOuterParagraph( $parsed );
1937 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1939 * @param int $maxage Maximum cache time on the CDN, in seconds.
1941 public function setCdnMaxage( $maxage ) {
1942 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1946 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
1947 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
1948 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
1951 * @param int $maxage Maximum cache time on the CDN, in seconds
1954 public function lowerCdnMaxage( $maxage ) {
1955 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1956 $this->setCdnMaxage( $this->mCdnMaxage
);
1960 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1962 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1963 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1964 * TTL is 90% of the age of the object, subject to the min and max.
1966 * @param string|int|float|bool|null $mtime Last-Modified timestamp
1967 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
1968 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1969 * @return int TTL in seconds passed to lowerCdnMaxage() (may not be the same as the new
1973 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1974 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1975 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1977 if ( $mtime === null ||
$mtime === false ) {
1978 return $minTTL; // entity does not exist
1981 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1982 $adaptiveTTL = max( 0.9 * $age, $minTTL );
1983 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1985 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1987 return $adaptiveTTL;
1991 * Use enableClientCache(false) to force it to send nocache headers
1993 * @param bool|null $state New value, or null to not set the value
1995 * @return bool Old value
1997 public function enableClientCache( $state ) {
1998 return wfSetVar( $this->mEnableClientCache
, $state );
2002 * Get the list of cookie names that will influence the cache
2006 function getCacheVaryCookies() {
2008 if ( $cookies === null ) {
2009 $config = $this->getConfig();
2010 $cookies = array_merge(
2011 SessionManager
::singleton()->getVaryCookies(),
2015 $config->get( 'CacheVaryCookies' )
2017 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2023 * Check if the request has a cache-varying cookie header
2024 * If it does, it's very important that we don't allow public caching
2028 function haveCacheVaryCookies() {
2029 $request = $this->getRequest();
2030 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2031 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2032 wfDebug( __METHOD__
. ": found $cookieName\n" );
2036 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2041 * Add an HTTP header that will influence on the cache
2043 * @param string $header Header name
2044 * @param string[]|null $option Options for the Key header. See
2045 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2046 * for the list of valid options.
2048 public function addVaryHeader( $header, array $option = null ) {
2049 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2050 $this->mVaryHeader
[$header] = [];
2052 if ( !is_array( $option ) ) {
2055 $this->mVaryHeader
[$header] =
2056 array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2060 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2061 * such as Accept-Encoding or Cookie
2065 public function getVaryHeader() {
2066 // If we vary on cookies, let's make sure it's always included here too.
2067 if ( $this->getCacheVaryCookies() ) {
2068 $this->addVaryHeader( 'Cookie' );
2071 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2072 $this->addVaryHeader( $header, $options );
2074 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2078 * Add an HTTP Link: header
2080 * @param string $header Header value
2082 public function addLinkHeader( $header ) {
2083 $this->mLinkHeader
[] = $header;
2087 * Return a Link: header. Based on the values of $mLinkHeader.
2091 public function getLinkHeader() {
2092 if ( !$this->mLinkHeader
) {
2096 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2100 * Get a complete Key header
2104 public function getKeyHeader() {
2105 $cvCookies = $this->getCacheVaryCookies();
2107 $cookiesOption = [];
2108 foreach ( $cvCookies as $cookieName ) {
2109 $cookiesOption[] = 'param=' . $cookieName;
2111 $this->addVaryHeader( 'Cookie', $cookiesOption );
2113 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2114 $this->addVaryHeader( $header, $options );
2118 foreach ( $this->mVaryHeader
as $header => $option ) {
2119 $newheader = $header;
2120 if ( is_array( $option ) && count( $option ) > 0 ) {
2121 $newheader .= ';' . implode( ';', $option );
2123 $headers[] = $newheader;
2125 $key = 'Key: ' . implode( ',', $headers );
2131 * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
2134 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2135 * /w/index.php?title=Main_page&variant=zh-cn will not.
2137 private function addAcceptLanguage() {
2138 $title = $this->getTitle();
2139 if ( !$title instanceof Title
) {
2143 $lang = $title->getPageLanguage();
2144 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2145 $variants = $lang->getVariants();
2147 foreach ( $variants as $variant ) {
2148 if ( $variant === $lang->getCode() ) {
2152 $aloption[] = "substr=$variant";
2154 // IE and some other browsers use BCP 47 standards in their Accept-Language header,
2155 // like "zh-CN" or "zh-Hant". We should handle these too.
2156 $variantBCP47 = LanguageCode
::bcp47( $variant );
2157 if ( $variantBCP47 !== $variant ) {
2158 $aloption[] = "substr=$variantBCP47";
2161 $this->addVaryHeader( 'Accept-Language', $aloption );
2166 * Set a flag which will cause an X-Frame-Options header appropriate for
2167 * edit pages to be sent. The header value is controlled by
2168 * $wgEditPageFrameOptions.
2170 * This is the default for special pages. If you display a CSRF-protected
2171 * form on an ordinary view page, then you need to call this function.
2173 * @param bool $enable
2175 public function preventClickjacking( $enable = true ) {
2176 $this->mPreventClickjacking
= $enable;
2180 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2181 * This can be called from pages which do not contain any CSRF-protected
2184 public function allowClickjacking() {
2185 $this->mPreventClickjacking
= false;
2189 * Get the prevent-clickjacking flag
2194 public function getPreventClickjacking() {
2195 return $this->mPreventClickjacking
;
2199 * Get the X-Frame-Options header value (without the name part), or false
2200 * if there isn't one. This is used by Skin to determine whether to enable
2201 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2203 * @return string|false
2205 public function getFrameOptions() {
2206 $config = $this->getConfig();
2207 if ( $config->get( 'BreakFrames' ) ) {
2209 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2210 return $config->get( 'EditPageFrameOptions' );
2216 * Send cache control HTTP headers
2218 public function sendCacheControl() {
2219 $response = $this->getRequest()->response();
2220 $config = $this->getConfig();
2222 $this->addVaryHeader( 'Cookie' );
2223 $this->addAcceptLanguage();
2225 # don't serve compressed data to clients who can't handle it
2226 # maintain different caches for logged-in users and non-logged in ones
2227 $response->header( $this->getVaryHeader() );
2229 if ( $config->get( 'UseKeyHeader' ) ) {
2230 $response->header( $this->getKeyHeader() );
2233 if ( $this->mEnableClientCache
) {
2235 $config->get( 'UseSquid' ) &&
2236 !$response->hasCookies() &&
2237 !SessionManager
::getGlobalSession()->isPersistent() &&
2238 !$this->isPrintable() &&
2239 $this->mCdnMaxage
!= 0 &&
2240 !$this->haveCacheVaryCookies()
2242 if ( $config->get( 'UseESI' ) ) {
2243 # We'll purge the proxy cache explicitly, but require end user agents
2244 # to revalidate against the proxy on each visit.
2245 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2246 wfDebug( __METHOD__
.
2247 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2248 # start with a shorter timeout for initial testing
2249 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2251 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2252 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2254 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2256 # We'll purge the proxy cache for anons explicitly, but require end user agents
2257 # to revalidate against the proxy on each visit.
2258 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2259 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2260 wfDebug( __METHOD__
.
2261 ": local proxy caching; {$this->mLastModified} **", 'private' );
2262 # start with a shorter timeout for initial testing
2263 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2264 $response->header( "Cache-Control: " .
2265 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2268 # We do want clients to cache if they can, but they *must* check for updates
2269 # on revisiting the page.
2270 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2271 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2272 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2274 if ( $this->mLastModified
) {
2275 $response->header( "Last-Modified: {$this->mLastModified}" );
2278 wfDebug( __METHOD__
. ": no caching **", 'private' );
2280 # In general, the absence of a last modified header should be enough to prevent
2281 # the client from using its cache. We send a few other things just to make sure.
2282 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2283 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2284 $response->header( 'Pragma: no-cache' );
2289 * Transfer styles and JavaScript modules from skin.
2291 * @param Skin $sk to load modules for
2293 public function loadSkinModules( $sk ) {
2294 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2295 if ( $group === 'styles' ) {
2296 foreach ( $modules as $key => $moduleMembers ) {
2297 $this->addModuleStyles( $moduleMembers );
2300 $this->addModules( $modules );
2306 * Finally, all the text has been munged and accumulated into
2307 * the object, let's actually output it:
2309 * @param bool $return Set to true to get the result as a string rather than sending it
2310 * @return string|null
2312 * @throws FatalError
2313 * @throws MWException
2315 public function output( $return = false ) {
2316 if ( $this->mDoNothing
) {
2317 return $return ?
'' : null;
2320 $response = $this->getRequest()->response();
2321 $config = $this->getConfig();
2323 if ( $this->mRedirect
!= '' ) {
2324 # Standards require redirect URLs to be absolute
2325 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2327 $redirect = $this->mRedirect
;
2328 $code = $this->mRedirectCode
;
2330 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2331 if ( $code == '301' ||
$code == '303' ) {
2332 if ( !$config->get( 'DebugRedirects' ) ) {
2333 $response->statusHeader( $code );
2335 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2337 if ( $config->get( 'VaryOnXFP' ) ) {
2338 $this->addVaryHeader( 'X-Forwarded-Proto' );
2340 $this->sendCacheControl();
2342 $response->header( "Content-Type: text/html; charset=utf-8" );
2343 if ( $config->get( 'DebugRedirects' ) ) {
2344 $url = htmlspecialchars( $redirect );
2345 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2346 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2347 print "</body>\n</html>\n";
2349 $response->header( 'Location: ' . $redirect );
2353 return $return ?
'' : null;
2354 } elseif ( $this->mStatusCode
) {
2355 $response->statusHeader( $this->mStatusCode
);
2358 # Buffer output; final headers may depend on later processing
2361 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2362 $response->header( 'Content-language: ' .
2363 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2365 if ( !$this->mArticleBodyOnly
) {
2366 $sk = $this->getSkin();
2368 if ( $sk->shouldPreloadLogo() ) {
2369 $this->addLogoPreloadLinkHeaders();
2373 $linkHeader = $this->getLinkHeader();
2374 if ( $linkHeader ) {
2375 $response->header( $linkHeader );
2378 // Prevent framing, if requested
2379 $frameOptions = $this->getFrameOptions();
2380 if ( $frameOptions ) {
2381 $response->header( "X-Frame-Options: $frameOptions" );
2384 ContentSecurityPolicy
::sendHeaders( $this );
2386 if ( $this->mArticleBodyOnly
) {
2387 echo $this->mBodytext
;
2389 // Enable safe mode if requested (T152169)
2390 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2391 $this->disallowUserJs();
2394 $sk = $this->getSkin();
2395 $this->loadSkinModules( $sk );
2397 MWDebug
::addModules( $this );
2399 // Avoid PHP 7.1 warning of passing $this by reference
2400 $outputPage = $this;
2401 // Hook that allows last minute changes to the output page, e.g.
2402 // adding of CSS or Javascript by extensions.
2403 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2407 } catch ( Exception
$e ) {
2408 ob_end_clean(); // bug T129657
2414 // This hook allows last minute changes to final overall output by modifying output buffer
2415 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2416 } catch ( Exception
$e ) {
2417 ob_end_clean(); // bug T129657
2421 $this->sendCacheControl();
2424 return ob_get_clean();
2432 * Prepare this object to display an error page; disable caching and
2433 * indexing, clear the current text and redirect, set the page's title
2434 * and optionally an custom HTML title (content of the "<title>" tag).
2436 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2437 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2438 * optional, if not passed the "<title>" attribute will be
2439 * based on $pageTitle
2441 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2442 $this->setPageTitle( $pageTitle );
2443 if ( $htmlTitle !== false ) {
2444 $this->setHTMLTitle( $htmlTitle );
2446 $this->setRobotPolicy( 'noindex,nofollow' );
2447 $this->setArticleRelated( false );
2448 $this->enableClientCache( false );
2449 $this->mRedirect
= '';
2450 $this->clearSubtitle();
2455 * Output a standard error page
2457 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2458 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2459 * showErrorPage( 'titlemsg', $messageObject );
2460 * showErrorPage( $titleMessageObject, $messageObject );
2462 * @param string|Message $title Message key (string) for page title, or a Message object
2463 * @param string|Message $msg Message key (string) for page text, or a Message object
2464 * @param array $params Message parameters; ignored if $msg is a Message object
2466 public function showErrorPage( $title, $msg, $params = [] ) {
2467 if ( !$title instanceof Message
) {
2468 $title = $this->msg( $title );
2471 $this->prepareErrorPage( $title );
2473 if ( $msg instanceof Message
) {
2474 if ( $params !== [] ) {
2475 trigger_error( 'Argument ignored: $params. The message parameters argument '
2476 . 'is discarded when the $msg argument is a Message object instead of '
2477 . 'a string.', E_USER_NOTICE
);
2479 $this->addHTML( $msg->parseAsBlock() );
2481 $this->addWikiMsgArray( $msg, $params );
2484 $this->returnToMain();
2488 * Output a standard permission error page
2490 * @param array $errors Error message keys or [key, param...] arrays
2491 * @param string|null $action Action that was denied or null if unknown
2493 public function showPermissionsErrorPage( array $errors, $action = null ) {
2494 foreach ( $errors as $key => $error ) {
2495 $errors[$key] = (array)$error;
2498 // For some action (read, edit, create and upload), display a "login to do this action"
2499 // error if all of the following conditions are met:
2500 // 1. the user is not logged in
2501 // 2. the only error is insufficient permissions (i.e. no block or something else)
2502 // 3. the error can be avoided simply by logging in
2503 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2504 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2505 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2506 && ( User
::groupHasPermission( 'user', $action )
2507 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2509 $displayReturnto = null;
2511 # Due to T34276, if a user does not have read permissions,
2512 # $this->getTitle() will just give Special:Badtitle, which is
2513 # not especially useful as a returnto parameter. Use the title
2514 # from the request instead, if there was one.
2515 $request = $this->getRequest();
2516 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2517 if ( $action == 'edit' ) {
2518 $msg = 'whitelistedittext';
2519 $displayReturnto = $returnto;
2520 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2521 $msg = 'nocreatetext';
2522 } elseif ( $action == 'upload' ) {
2523 $msg = 'uploadnologintext';
2525 $msg = 'loginreqpagetext';
2526 $displayReturnto = Title
::newMainPage();
2532 $query['returnto'] = $returnto->getPrefixedText();
2534 if ( !$request->wasPosted() ) {
2535 $returntoquery = $request->getValues();
2536 unset( $returntoquery['title'] );
2537 unset( $returntoquery['returnto'] );
2538 unset( $returntoquery['returntoquery'] );
2539 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2542 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2543 $loginLink = $linkRenderer->makeKnownLink(
2544 SpecialPage
::getTitleFor( 'Userlogin' ),
2545 $this->msg( 'loginreqlink' )->text(),
2550 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2551 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2553 # Don't return to a page the user can't read otherwise
2554 # we'll end up in a pointless loop
2555 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2556 $this->returnToMain( null, $displayReturnto );
2559 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2560 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2565 * Display an error page indicating that a given version of MediaWiki is
2566 * required to use it
2568 * @param mixed $version The version of MediaWiki needed to use the page
2570 public function versionRequired( $version ) {
2571 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2573 $this->addWikiMsg( 'versionrequiredtext', $version );
2574 $this->returnToMain();
2578 * Format a list of error messages
2580 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2581 * @param string|null $action Action that was denied or null if unknown
2582 * @return string The wikitext error-messages, formatted into a list.
2584 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2585 if ( $action == null ) {
2586 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2588 $action_desc = $this->msg( "action-$action" )->plain();
2590 'permissionserrorstext-withaction',
2593 )->plain() . "\n\n";
2596 if ( count( $errors ) > 1 ) {
2597 $text .= '<ul class="permissions-errors">' . "\n";
2599 foreach ( $errors as $error ) {
2601 $text .= $this->msg( ...$error )->plain();
2606 $text .= "<div class=\"permissions-errors\">\n" .
2607 $this->msg( ...reset( $errors ) )->plain() .
2615 * Show a warning about replica DB lag
2617 * If the lag is higher than $wgSlaveLagCritical seconds,
2618 * then the warning is a bit more obvious. If the lag is
2619 * lower than $wgSlaveLagWarning, then no warning is shown.
2621 * @param int $lag Slave lag
2623 public function showLagWarning( $lag ) {
2624 $config = $this->getConfig();
2625 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2626 $lag = floor( $lag ); // floor to avoid nano seconds to display
2627 $message = $lag < $config->get( 'SlaveLagCritical' )
2630 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2631 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2636 * Output an error page
2638 * @note FatalError exception class provides an alternative.
2639 * @param string $message Error to output. Must be escaped for HTML.
2641 public function showFatalError( $message ) {
2642 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2644 $this->addHTML( $message );
2648 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2650 public function showUnexpectedValueError( $name, $val ) {
2651 wfDeprecated( __METHOD__
, '1.32' );
2652 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2656 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2658 public function showFileCopyError( $old, $new ) {
2659 wfDeprecated( __METHOD__
, '1.32' );
2660 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2664 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2666 public function showFileRenameError( $old, $new ) {
2667 wfDeprecated( __METHOD__
, '1.32' );
2668 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
2672 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2674 public function showFileDeleteError( $name ) {
2675 wfDeprecated( __METHOD__
, '1.32' );
2676 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
2680 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2682 public function showFileNotFoundError( $name ) {
2683 wfDeprecated( __METHOD__
, '1.32' );
2684 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
2688 * Add a "return to" link pointing to a specified title
2690 * @param Title $title Title to link
2691 * @param array $query Query string parameters
2692 * @param string|null $text Text of the link (input is not escaped)
2693 * @param array $options Options array to pass to Linker
2695 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2696 $linkRenderer = MediaWikiServices
::getInstance()
2697 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2698 $link = $this->msg( 'returnto' )->rawParams(
2699 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2700 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2704 * Add a "return to" link pointing to a specified title,
2705 * or the title indicated in the request, or else the main page
2707 * @param mixed|null $unused
2708 * @param Title|string|null $returnto Title or String to return to
2709 * @param string|null $returntoquery Query string for the return to link
2711 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2712 if ( $returnto == null ) {
2713 $returnto = $this->getRequest()->getText( 'returnto' );
2716 if ( $returntoquery == null ) {
2717 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2720 if ( $returnto === '' ) {
2721 $returnto = Title
::newMainPage();
2724 if ( is_object( $returnto ) ) {
2725 $titleObj = $returnto;
2727 $titleObj = Title
::newFromText( $returnto );
2729 // We don't want people to return to external interwiki. That
2730 // might potentially be used as part of a phishing scheme
2731 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2732 $titleObj = Title
::newMainPage();
2735 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2738 private function getRlClientContext() {
2739 if ( !$this->rlClientContext
) {
2740 $query = ResourceLoader
::makeLoaderQuery(
2741 [], // modules; not relevant
2742 $this->getLanguage()->getCode(),
2743 $this->getSkin()->getSkinName(),
2744 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2745 null, // version; not relevant
2746 ResourceLoader
::inDebugMode(),
2747 null, // only; not relevant
2748 $this->isPrintable(),
2749 $this->getRequest()->getBool( 'handheld' )
2751 $this->rlClientContext
= new ResourceLoaderContext(
2752 $this->getResourceLoader(),
2753 new FauxRequest( $query )
2755 if ( $this->contentOverrideCallbacks
) {
2756 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2757 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2758 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2759 $content = $callback( $title );
2760 if ( $content !== null ) {
2768 return $this->rlClientContext
;
2772 * Call this to freeze the module queue and JS config and create a formatter.
2774 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2775 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2776 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2777 * the module filters retroactively. Skins and extension hooks may also add modules until very
2778 * late in the request lifecycle.
2780 * @return ResourceLoaderClientHtml
2782 public function getRlClient() {
2783 if ( !$this->rlClient
) {
2784 $context = $this->getRlClientContext();
2785 $rl = $this->getResourceLoader();
2786 $this->addModules( [
2791 $this->addModuleStyles( [
2796 $this->getSkin()->setupSkinUserCss( $this );
2798 // Prepare exempt modules for buildExemptModules()
2799 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2801 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2803 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2804 // Separate user-specific batch for improved cache-hit ratio.
2805 $userBatch = [ 'user.styles', 'user' ];
2806 $siteBatch = array_diff( $moduleStyles, $userBatch );
2807 $dbr = wfGetDB( DB_REPLICA
);
2808 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2809 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2811 // Filter out modules handled by buildExemptModules()
2812 $moduleStyles = array_filter( $moduleStyles,
2813 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2814 $module = $rl->getModule( $name );
2816 $group = $module->getGroup();
2817 if ( isset( $exemptGroups[$group] ) ) {
2818 $exemptStates[$name] = 'ready';
2819 if ( !$module->isKnownEmpty( $context ) ) {
2820 // E.g. Don't output empty <styles>
2821 $exemptGroups[$group][] = $name;
2829 $this->rlExemptStyleModules
= $exemptGroups;
2831 $rlClient = new ResourceLoaderClientHtml( $context, [
2832 'target' => $this->getTarget(),
2833 'nonce' => $this->getCSPNonce(),
2834 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2835 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2836 // modules enqueud for loading on this page is filtered to just those.
2837 // However, to make sure we also apply the restriction to dynamic dependencies and
2838 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2839 // StartupModule so that the client-side registry will not contain any restricted
2840 // modules either. (T152169, T185303)
2841 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2842 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2845 $rlClient->setConfig( $this->getJSVars() );
2846 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2847 $rlClient->setModuleStyles( $moduleStyles );
2848 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2849 $rlClient->setExemptStates( $exemptStates );
2850 $this->rlClient
= $rlClient;
2852 return $this->rlClient
;
2856 * @param Skin $sk The given Skin
2857 * @param bool $includeStyle Unused
2858 * @return string The doctype, opening "<html>", and head element.
2860 public function headElement( Skin
$sk, $includeStyle = true ) {
2861 $userdir = $this->getLanguage()->getDir();
2862 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
2865 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2866 $this->getRlClient()->getDocumentAttributes(),
2867 $sk->getHtmlElementAttributes()
2869 $pieces[] = Html
::openElement( 'head' );
2871 if ( $this->getHTMLTitle() == '' ) {
2872 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2875 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2876 // Add <meta charset="UTF-8">
2877 // This should be before <title> since it defines the charset used by
2878 // text including the text inside <title>.
2879 // The spec recommends defining XHTML5's charset using the XML declaration
2881 // Our XML declaration is output by Html::htmlHeader.
2882 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2883 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2884 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2887 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2888 $pieces[] = $this->getRlClient()->getHeadHtml();
2889 $pieces[] = $this->buildExemptModules();
2890 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2891 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2893 // Use an IE conditional comment to serve the script only to old IE
2894 $pieces[] = '<!--[if lt IE 9]>' .
2895 ResourceLoaderClientHtml
::makeLoad(
2896 ResourceLoaderContext
::newDummyContext(),
2898 ResourceLoaderModule
::TYPE_SCRIPTS
,
2900 $this->getCSPNonce()
2904 $pieces[] = Html
::closeElement( 'head' );
2906 $bodyClasses = $this->mAdditionalBodyClasses
;
2907 $bodyClasses[] = 'mediawiki';
2909 # Classes for LTR/RTL directionality support
2910 $bodyClasses[] = $userdir;
2911 $bodyClasses[] = "sitedir-$sitedir";
2913 $underline = $this->getUser()->getOption( 'underline' );
2914 if ( $underline < 2 ) {
2915 // The following classes can be used here:
2916 // * mw-underline-always
2917 // * mw-underline-never
2918 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2921 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2922 # A <body> class is probably not the best way to do this . . .
2923 $bodyClasses[] = 'capitalize-all-nouns';
2926 // Parser feature migration class
2927 // The idea is that this will eventually be removed, after the wikitext
2928 // which requires it is cleaned up.
2929 $bodyClasses[] = 'mw-hide-empty-elt';
2931 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2932 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2934 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2937 // While the implode() is not strictly needed, it's used for backwards compatibility
2938 // (this used to be built as a string and hooks likely still expect that).
2939 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2941 // Allow skins and extensions to add body attributes they need
2942 $sk->addToBodyAttributes( $this, $bodyAttrs );
2943 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2945 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2947 return self
::combineWrappedStrings( $pieces );
2951 * Get a ResourceLoader object associated with this OutputPage
2953 * @return ResourceLoader
2955 public function getResourceLoader() {
2956 if ( is_null( $this->mResourceLoader
) ) {
2957 $this->mResourceLoader
= new ResourceLoader(
2959 LoggerFactory
::getInstance( 'resourceloader' )
2962 return $this->mResourceLoader
;
2966 * Explicily load or embed modules on a page.
2968 * @param array|string $modules One or more module names
2969 * @param string $only ResourceLoaderModule TYPE_ class constant
2970 * @param array $extraQuery [optional] Array with extra query parameters for the request
2971 * @return string|WrappedStringList HTML
2973 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2974 // Apply 'target' and 'origin' filters
2975 $modules = $this->filterModules( (array)$modules, null, $only );
2977 return ResourceLoaderClientHtml
::makeLoad(
2978 $this->getRlClientContext(),
2982 $this->getCSPNonce()
2987 * Combine WrappedString chunks and filter out empty ones
2989 * @param array $chunks
2990 * @return string|WrappedStringList HTML
2992 protected static function combineWrappedStrings( array $chunks ) {
2993 // Filter out empty values
2994 $chunks = array_filter( $chunks, 'strlen' );
2995 return WrappedString
::join( "\n", $chunks );
2999 * JS stuff to put at the bottom of the `<body>`.
3000 * These are legacy scripts ($this->mScripts), and user JS.
3002 * @return string|WrappedStringList HTML
3004 public function getBottomScripts() {
3006 $chunks[] = $this->getRlClient()->getBodyHtml();
3008 // Legacy non-ResourceLoader scripts
3009 $chunks[] = $this->mScripts
;
3011 if ( $this->limitReportJSData
) {
3012 $chunks[] = ResourceLoader
::makeInlineScript(
3013 ResourceLoader
::makeConfigSetScript(
3014 [ 'wgPageParseReport' => $this->limitReportJSData
]
3016 $this->getCSPNonce()
3020 return self
::combineWrappedStrings( $chunks );
3024 * Get the javascript config vars to include on this page
3026 * @return array Array of javascript config vars
3029 public function getJsConfigVars() {
3030 return $this->mJsConfigVars
;
3034 * Add one or more variables to be set in mw.config in JavaScript
3036 * @param string|array $keys Key or array of key/value pairs
3037 * @param mixed|null $value [optional] Value of the configuration variable
3039 public function addJsConfigVars( $keys, $value = null ) {
3040 if ( is_array( $keys ) ) {
3041 foreach ( $keys as $key => $value ) {
3042 $this->mJsConfigVars
[$key] = $value;
3047 $this->mJsConfigVars
[$keys] = $value;
3051 * Get an array containing the variables to be set in mw.config in JavaScript.
3053 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3054 * - in other words, page-independent/site-wide variables (without state).
3055 * You will only be adding bloat to the html page and causing page caches to
3056 * have to be purged on configuration changes.
3059 public function getJSVars() {
3062 $canonicalSpecialPageName = false; # T23115
3063 $services = MediaWikiServices
::getInstance();
3065 $title = $this->getTitle();
3066 $ns = $title->getNamespace();
3067 $canonicalNamespace = MWNamespace
::exists( $ns )
3068 ? MWNamespace
::getCanonicalName( $ns )
3069 : $title->getNsText();
3071 $sk = $this->getSkin();
3072 // Get the relevant title so that AJAX features can use the correct page name
3073 // when making API requests from certain special pages (T36972).
3074 $relevantTitle = $sk->getRelevantTitle();
3075 $relevantUser = $sk->getRelevantUser();
3077 if ( $ns == NS_SPECIAL
) {
3078 list( $canonicalSpecialPageName, /*...*/ ) =
3079 $services->getSpecialPageFactory()->
3080 resolveAlias( $title->getDBkey() );
3081 } elseif ( $this->canUseWikiPage() ) {
3082 $wikiPage = $this->getWikiPage();
3083 $curRevisionId = $wikiPage->getLatest();
3084 $articleId = $wikiPage->getId();
3087 $lang = $title->getPageViewLanguage();
3089 // Pre-process information
3090 $separatorTransTable = $lang->separatorTransformTable();
3091 $separatorTransTable = $separatorTransTable ?
: [];
3092 $compactSeparatorTransTable = [
3093 implode( "\t", array_keys( $separatorTransTable ) ),
3094 implode( "\t", $separatorTransTable ),
3096 $digitTransTable = $lang->digitTransformTable();
3097 $digitTransTable = $digitTransTable ?
: [];
3098 $compactDigitTransTable = [
3099 implode( "\t", array_keys( $digitTransTable ) ),
3100 implode( "\t", $digitTransTable ),
3103 $user = $this->getUser();
3106 'wgCanonicalNamespace' => $canonicalNamespace,
3107 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3108 'wgNamespaceNumber' => $title->getNamespace(),
3109 'wgPageName' => $title->getPrefixedDBkey(),
3110 'wgTitle' => $title->getText(),
3111 'wgCurRevisionId' => $curRevisionId,
3112 'wgRevisionId' => (int)$this->getRevisionId(),
3113 'wgArticleId' => $articleId,
3114 'wgIsArticle' => $this->isArticle(),
3115 'wgIsRedirect' => $title->isRedirect(),
3116 'wgAction' => Action
::getActionName( $this->getContext() ),
3117 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3118 'wgUserGroups' => $user->getEffectiveGroups(),
3119 'wgCategories' => $this->getCategories(),
3120 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3121 'wgPageContentLanguage' => $lang->getCode(),
3122 'wgPageContentModel' => $title->getContentModel(),
3123 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3124 'wgDigitTransformTable' => $compactDigitTransTable,
3125 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3126 'wgMonthNames' => $lang->getMonthNamesArray(),
3127 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3128 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3129 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3130 'wgRequestId' => WebRequest
::getRequestId(),
3131 'wgCSPNonce' => $this->getCSPNonce(),
3134 if ( $user->isLoggedIn() ) {
3135 $vars['wgUserId'] = $user->getId();
3136 $vars['wgUserEditCount'] = $user->getEditCount();
3137 $userReg = $user->getRegistration();
3138 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3139 // Get the revision ID of the oldest new message on the user's talk
3140 // page. This can be used for constructing new message alerts on
3142 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3145 $contLang = $services->getContentLanguage();
3146 if ( $contLang->hasVariants() ) {
3147 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3149 // Same test as SkinTemplate
3150 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3151 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3153 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3154 && $relevantTitle->quickUserCan( 'edit', $user )
3155 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3157 foreach ( $title->getRestrictionTypes() as $type ) {
3158 // Following keys are set in $vars:
3159 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3160 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3163 if ( $title->isMainPage() ) {
3164 $vars['wgIsMainPage'] = true;
3167 if ( $this->mRedirectedFrom
) {
3168 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3171 if ( $relevantUser ) {
3172 $vars['wgRelevantUserName'] = $relevantUser->getName();
3175 // Allow extensions to add their custom variables to the mw.config map.
3176 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3177 // page-dependant but site-wide (without state).
3178 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3179 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3181 // Merge in variables from addJsConfigVars last
3182 return array_merge( $vars, $this->getJsConfigVars() );
3186 * To make it harder for someone to slip a user a fake
3187 * JavaScript or CSS preview, a random token
3188 * is associated with the login session. If it's not
3189 * passed back with the preview request, we won't render
3194 public function userCanPreview() {
3195 $request = $this->getRequest();
3197 $request->getVal( 'action' ) !== 'submit' ||
3198 !$request->wasPosted()
3203 $user = $this->getUser();
3205 if ( !$user->isLoggedIn() ) {
3206 // Anons have predictable edit tokens
3209 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3213 $title = $this->getTitle();
3214 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3215 if ( count( $errors ) !== 0 ) {
3223 * @return array Array in format "link name or number => 'link html'".
3225 public function getHeadLinksArray() {
3229 $config = $this->getConfig();
3231 $canonicalUrl = $this->mCanonicalUrl
;
3233 $tags['meta-generator'] = Html
::element( 'meta', [
3234 'name' => 'generator',
3235 'content' => "MediaWiki $wgVersion",
3238 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3239 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3240 // fallbacks should come before the primary value so we need to reverse the array.
3241 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3242 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3243 'name' => 'referrer',
3244 'content' => $policy,
3249 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3250 if ( $p !== 'index,follow' ) {
3251 // http://www.robotstxt.org/wc/meta-user.html
3252 // Only show if it's different from the default robots policy
3253 $tags['meta-robots'] = Html
::element( 'meta', [
3259 foreach ( $this->mMetatags
as $tag ) {
3260 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3262 $tag[0] = substr( $tag[0], 5 );
3263 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3268 $tagName = "meta-{$tag[0]}";
3269 if ( isset( $tags[$tagName] ) ) {
3270 $tagName .= $tag[1];
3272 $tags[$tagName] = Html
::element( 'meta',
3275 'content' => $tag[1]
3280 foreach ( $this->mLinktags
as $tag ) {
3281 $tags[] = Html
::element( 'link', $tag );
3284 # Universal edit button
3285 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3286 $user = $this->getUser();
3287 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3288 && ( $this->getTitle()->exists() ||
3289 $this->getTitle()->quickUserCan( 'create', $user ) )
3291 // Original UniversalEditButton
3292 $msg = $this->msg( 'edit' )->text();
3293 $tags['universal-edit-button'] = Html
::element( 'link', [
3294 'rel' => 'alternate',
3295 'type' => 'application/x-wiki',
3297 'href' => $this->getTitle()->getEditURL(),
3299 // Alternate edit link
3300 $tags['alternative-edit'] = Html
::element( 'link', [
3303 'href' => $this->getTitle()->getEditURL(),
3308 # Generally the order of the favicon and apple-touch-icon links
3309 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3310 # uses whichever one appears later in the HTML source. Make sure
3311 # apple-touch-icon is specified first to avoid this.
3312 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3313 $tags['apple-touch-icon'] = Html
::element( 'link', [
3314 'rel' => 'apple-touch-icon',
3315 'href' => $config->get( 'AppleTouchIcon' )
3319 if ( $config->get( 'Favicon' ) !== false ) {
3320 $tags['favicon'] = Html
::element( 'link', [
3321 'rel' => 'shortcut icon',
3322 'href' => $config->get( 'Favicon' )
3326 # OpenSearch description link
3327 $tags['opensearch'] = Html
::element( 'link', [
3329 'type' => 'application/opensearchdescription+xml',
3330 'href' => wfScript( 'opensearch_desc' ),
3331 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3334 # Real Simple Discovery link, provides auto-discovery information
3335 # for the MediaWiki API (and potentially additional custom API
3336 # support such as WordPress or Twitter-compatible APIs for a
3337 # blogging extension, etc)
3338 $tags['rsd'] = Html
::element( 'link', [
3340 'type' => 'application/rsd+xml',
3341 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3342 // Whether RSD accepts relative or protocol-relative URLs is completely
3343 // undocumented, though.
3344 'href' => wfExpandUrl( wfAppendQuery(
3346 [ 'action' => 'rsd' ] ),
3352 if ( !$config->get( 'DisableLangConversion' ) ) {
3353 $lang = $this->getTitle()->getPageLanguage();
3354 if ( $lang->hasVariants() ) {
3355 $variants = $lang->getVariants();
3356 foreach ( $variants as $variant ) {
3357 $tags["variant-$variant"] = Html
::element( 'link', [
3358 'rel' => 'alternate',
3359 'hreflang' => LanguageCode
::bcp47( $variant ),
3360 'href' => $this->getTitle()->getLocalURL(
3361 [ 'variant' => $variant ] )
3365 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3366 $tags["variant-x-default"] = Html
::element( 'link', [
3367 'rel' => 'alternate',
3368 'hreflang' => 'x-default',
3369 'href' => $this->getTitle()->getLocalURL() ] );
3374 if ( $this->copyrightUrl
!== null ) {
3375 $copyright = $this->copyrightUrl
;
3378 if ( $config->get( 'RightsPage' ) ) {
3379 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3382 $copyright = $copy->getLocalURL();
3386 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3387 $copyright = $config->get( 'RightsUrl' );
3392 $tags['copyright'] = Html
::element( 'link', [
3394 'href' => $copyright ]
3399 if ( $config->get( 'Feed' ) ) {
3402 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3403 # Use the page name for the title. In principle, this could
3404 # lead to issues with having the same name for different feeds
3405 # corresponding to the same page, but we can't avoid that at
3408 $feedLinks[] = $this->feedLink(
3411 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3413 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3418 # Recent changes feed should appear on every page (except recentchanges,
3419 # that would be redundant). Put it after the per-page feed to avoid
3420 # changing existing behavior. It's still available, probably via a
3421 # menu in your browser. Some sites might have a different feed they'd
3422 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3423 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3424 # If so, use it instead.
3425 $sitename = $config->get( 'Sitename' );
3426 if ( $config->get( 'OverrideSiteFeed' ) ) {
3427 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3428 // Note, this->feedLink escapes the url.
3429 $feedLinks[] = $this->feedLink(
3432 $this->msg( "site-{$type}-feed", $sitename )->text()
3435 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3436 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3437 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3438 $feedLinks[] = $this->feedLink(
3440 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3441 # For grep: 'site-rss-feed', 'site-atom-feed'
3442 $this->msg( "site-{$format}-feed", $sitename )->text()
3447 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3448 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3449 # use OutputPage::addFeedLink() instead.
3450 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3452 $tags +
= $feedLinks;
3456 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3457 if ( $canonicalUrl !== false ) {
3458 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3460 if ( $this->isArticleRelated() ) {
3461 // This affects all requests where "setArticleRelated" is true. This is
3462 // typically all requests that show content (query title, curid, oldid, diff),
3463 // and all wikipage actions (edit, delete, purge, info, history etc.).
3464 // It does not apply to File pages and Special pages.
3465 // 'history' and 'info' actions address page metadata rather than the page
3466 // content itself, so they may not be canonicalized to the view page url.
3467 // TODO: this ought to be better encapsulated in the Action class.
3468 $action = Action
::getActionName( $this->getContext() );
3469 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3470 $query = "action={$action}";
3474 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3476 $reqUrl = $this->getRequest()->getRequestURL();
3477 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3481 if ( $canonicalUrl !== false ) {
3482 $tags[] = Html
::element( 'link', [
3483 'rel' => 'canonical',
3484 'href' => $canonicalUrl
3488 // Allow extensions to add, remove and/or otherwise manipulate these links
3489 // If you want only to *add* <head> links, please use the addHeadItem()
3490 // (or addHeadItems() for multiple items) method instead.
3491 // This hook is provided as a last resort for extensions to modify these
3492 // links before the output is sent to client.
3493 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3499 * Generate a "<link rel/>" for a feed.
3501 * @param string $type Feed type
3502 * @param string $url URL to the feed
3503 * @param string $text Value of the "title" attribute
3504 * @return string HTML fragment
3506 private function feedLink( $type, $url, $text ) {
3507 return Html
::element( 'link', [
3508 'rel' => 'alternate',
3509 'type' => "application/$type+xml",
3516 * Add a local or specified stylesheet, with the given media options.
3517 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3519 * @param string $style URL to the file
3520 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3521 * @param string $condition For IE conditional comments, specifying an IE version
3522 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3524 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3527 $options['media'] = $media;
3530 $options['condition'] = $condition;
3533 $options['dir'] = $dir;
3535 $this->styles
[$style] = $options;
3539 * Adds inline CSS styles
3540 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3542 * @param mixed $style_css Inline CSS
3543 * @param string $flip Set to 'flip' to flip the CSS if needed
3545 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3546 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3547 # If wanted, and the interface is right-to-left, flip the CSS
3548 $style_css = CSSJanus
::transform( $style_css, true, false );
3550 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3554 * Build exempt modules and legacy non-ResourceLoader styles.
3556 * @return string|WrappedStringList HTML
3558 protected function buildExemptModules() {
3560 // Things that go after the ResourceLoaderDynamicStyles marker
3563 // We want site, private and user styles to override dynamically added styles from
3564 // general modules, but we want dynamically added styles to override statically added
3565 // style modules. So the order has to be:
3566 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3567 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3568 // - ResourceLoaderDynamicStyles marker
3569 // - site/private/user styles
3571 // Add legacy styles added through addStyle()/addInlineStyle() here
3572 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3574 $chunks[] = Html
::element(
3576 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3579 $separateReq = [ 'site.styles', 'user.styles' ];
3580 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3581 // Combinable modules
3582 $chunks[] = $this->makeResourceLoaderLink(
3583 array_diff( $moduleNames, $separateReq ),
3584 ResourceLoaderModule
::TYPE_STYLES
3587 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3588 // These require their own dedicated request in order to support "@import"
3589 // syntax, which is incompatible with concatenation. (T147667, T37562)
3590 $chunks[] = $this->makeResourceLoaderLink( $name,
3591 ResourceLoaderModule
::TYPE_STYLES
3596 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3602 public function buildCssLinksArray() {
3605 foreach ( $this->styles
as $file => $options ) {
3606 $link = $this->styleLink( $file, $options );
3608 $links[$file] = $link;
3615 * Generate \<link\> tags for stylesheets
3617 * @param string $style URL to the file
3618 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3619 * @return string HTML fragment
3621 protected function styleLink( $style, array $options ) {
3622 if ( isset( $options['dir'] ) ) {
3623 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3628 if ( isset( $options['media'] ) ) {
3629 $media = self
::transformCssMedia( $options['media'] );
3630 if ( is_null( $media ) ) {
3637 if ( substr( $style, 0, 1 ) == '/' ||
3638 substr( $style, 0, 5 ) == 'http:' ||
3639 substr( $style, 0, 6 ) == 'https:' ) {
3642 $config = $this->getConfig();
3643 // Append file hash as query parameter
3644 $url = self
::transformResourcePath(
3646 $config->get( 'StylePath' ) . '/' . $style
3650 $link = Html
::linkedStyle( $url, $media );
3652 if ( isset( $options['condition'] ) ) {
3653 $condition = htmlspecialchars( $options['condition'] );
3654 $link = "<!--[if $condition]>$link<![endif]-->";
3660 * Transform path to web-accessible static resource.
3662 * This is used to add a validation hash as query string.
3663 * This aids various behaviors:
3665 * - Put long Cache-Control max-age headers on responses for improved
3666 * cache performance.
3667 * - Get the correct version of a file as expected by the current page.
3668 * - Instantly get the updated version of a file after deployment.
3670 * Avoid using this for urls included in HTML as otherwise clients may get different
3671 * versions of a resource when navigating the site depending on when the page was cached.
3672 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3673 * an external stylesheet).
3676 * @param Config $config
3677 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3678 * @return string URL
3680 public static function transformResourcePath( Config
$config, $path ) {
3684 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3685 if ( $remotePathPrefix === '' ) {
3686 // The configured base path is required to be empty string for
3687 // wikis in the domain root
3690 $remotePath = $remotePathPrefix;
3692 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3693 // - Path is outside wgResourceBasePath, ignore.
3694 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3697 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3698 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3699 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3700 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3701 $uploadPath = $config->get( 'UploadPath' );
3702 if ( strpos( $path, $uploadPath ) === 0 ) {
3703 $localDir = $config->get( 'UploadDirectory' );
3704 $remotePathPrefix = $remotePath = $uploadPath;
3707 $path = RelPath
::getRelativePath( $path, $remotePath );
3708 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3712 * Utility method for transformResourceFilePath().
3714 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3717 * @param string $remotePathPrefix URL path prefix that points to $localPath
3718 * @param string $localPath File directory exposed at $remotePath
3719 * @param string $file Path to target file relative to $localPath
3720 * @return string URL
3722 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3723 $hash = md5_file( "$localPath/$file" );
3724 if ( $hash === false ) {
3725 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3728 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3732 * Transform "media" attribute based on request parameters
3734 * @param string $media Current value of the "media" attribute
3735 * @return string Modified value of the "media" attribute, or null to skip
3738 public static function transformCssMedia( $media ) {
3741 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3742 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3744 // Switch in on-screen display for media testing
3746 'printable' => 'print',
3747 'handheld' => 'handheld',
3749 foreach ( $switches as $switch => $targetMedia ) {
3750 if ( $wgRequest->getBool( $switch ) ) {
3751 if ( $media == $targetMedia ) {
3753 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3754 /* This regex will not attempt to understand a comma-separated media_query_list
3756 * Example supported values for $media:
3757 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3758 * Example NOT supported value for $media:
3759 * '3d-glasses, screen, print and resolution > 90dpi'
3761 * If it's a print request, we never want any kind of screen stylesheets
3762 * If it's a handheld request (currently the only other choice with a switch),
3763 * we don't want simple 'screen' but we might want screen queries that
3764 * have a max-width or something, so we'll pass all others on and let the
3765 * client do the query.
3767 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3778 * Add a wikitext-formatted message to the output.
3779 * This is equivalent to:
3781 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3783 public function addWikiMsg( /*...*/ ) {
3784 $args = func_get_args();
3785 $name = array_shift( $args );
3786 $this->addWikiMsgArray( $name, $args );
3790 * Add a wikitext-formatted message to the output.
3791 * Like addWikiMsg() except the parameters are taken as an array
3792 * instead of a variable argument list.
3794 * @param string $name
3795 * @param array $args
3797 public function addWikiMsgArray( $name, $args ) {
3798 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3802 * This function takes a number of message/argument specifications, wraps them in
3803 * some overall structure, and then parses the result and adds it to the output.
3805 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3806 * and so on. The subsequent arguments may be either
3807 * 1) strings, in which case they are message names, or
3808 * 2) arrays, in which case, within each array, the first element is the message
3809 * name, and subsequent elements are the parameters to that message.
3811 * Don't use this for messages that are not in the user's interface language.
3815 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3819 * $wgOut->addWikiText( "<div class='error'>\n"
3820 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3822 * The newline after the opening div is needed in some wikitext. See T21226.
3824 * @param string $wrap
3826 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3827 $msgSpecs = func_get_args();
3828 array_shift( $msgSpecs );
3829 $msgSpecs = array_values( $msgSpecs );
3831 foreach ( $msgSpecs as $n => $spec ) {
3832 if ( is_array( $spec ) ) {
3834 $name = array_shift( $args );
3835 if ( isset( $args['options'] ) ) {
3836 unset( $args['options'] );
3838 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3846 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3848 $this->addWikiText( $s );
3852 * Whether the output has a table of contents
3856 public function isTOCEnabled() {
3857 return $this->mEnableTOC
;
3861 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3864 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3866 public function enableSectionEditLinks( $flag = true ) {
3867 wfDeprecated( __METHOD__
, '1.31' );
3873 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3875 public function sectionEditLinksEnabled() {
3876 wfDeprecated( __METHOD__
, '1.31' );
3881 * Helper function to setup the PHP implementation of OOUI to use in this request.
3884 * @param String $skinName The Skin name to determine the correct OOUI theme
3885 * @param String $dir Language direction
3887 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3888 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3889 $theme = $themes[$skinName] ??
$themes['default'];
3890 // For example, 'OOUI\WikimediaUITheme'.
3891 $themeClass = "OOUI\\{$theme}Theme";
3892 OOUI\Theme
::setSingleton( new $themeClass() );
3893 OOUI\Element
::setDefaultDir( $dir );
3897 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3898 * MediaWiki and this OutputPage instance.
3902 public function enableOOUI() {
3904 strtolower( $this->getSkin()->getSkinName() ),
3905 $this->getLanguage()->getDir()
3907 $this->addModuleStyles( [
3908 'oojs-ui-core.styles',
3909 'oojs-ui.styles.indicators',
3910 'oojs-ui.styles.textures',
3911 'mediawiki.widgets.styles',
3912 'oojs-ui.styles.icons-content',
3913 'oojs-ui.styles.icons-alerts',
3914 'oojs-ui.styles.icons-interactions',
3919 * Add Link headers for preloading the wiki's logo.
3923 protected function addLogoPreloadLinkHeaders() {
3924 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3930 if ( !is_array( $logo ) ) {
3931 // No media queries required if we only have one variant
3932 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3936 if ( isset( $logo['svg'] ) ) {
3937 // No media queries required if we only have a 1x and svg variant
3938 // because all preload-capable browsers support SVGs
3939 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3943 foreach ( $logo as $dppx => $src ) {
3944 // Keys are in this format: "1.5x"
3945 $dppx = substr( $dppx, 0, -1 );
3946 $logosPerDppx[$dppx] = $src;
3949 // Because PHP can't have floats as array keys
3950 uksort( $logosPerDppx, function ( $a , $b ) {
3951 $a = floatval( $a );
3952 $b = floatval( $b );
3953 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3957 foreach ( $logosPerDppx as $dppx => $src ) {
3958 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3961 $logosCount = count( $logos );
3962 // Logic must match ResourceLoaderSkinModule:
3963 // - 1x applies to resolution < 1.5dppx
3964 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3965 // - 2x applies to resolution >= 2dppx
3966 // Note that min-resolution and max-resolution are both inclusive.
3967 for ( $i = 0; $i < $logosCount; $i++
) {
3970 // min-resolution is ">=" (larger than or equal to)
3971 // "not min-resolution" is essentially "<"
3972 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3973 } elseif ( $i !== $logosCount - 1 ) {
3975 // Media query expressions can only apply "not" to the entire expression
3976 // (e.g. can't express ">= 1.5 and not >= 2).
3977 // Workaround: Use <= 1.9999 in place of < 2.
3978 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
3979 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3980 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3983 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
3986 $this->addLinkHeader(
3987 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
3993 * Get (and set if not yet set) the CSP nonce.
3995 * This value needs to be included in any <script> tags on the
3998 * @return string|bool Nonce or false to mean don't output nonce
4001 public function getCSPNonce() {
4002 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4005 if ( $this->CSPNonce
=== null ) {
4006 // XXX It might be expensive to generate randomness
4007 // on every request, on Windows.
4008 $rand = random_bytes( 15 );
4009 $this->CSPNonce
= base64_encode( $rand );
4011 return $this->CSPNonce
;