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;
226 private $mPageTitleActionText = '';
228 /** @var int Cache stuff. Looks like mEnableClientCache */
229 protected $mCdnMaxage = 0;
230 /** @var int Upper limit on mCdnMaxage */
231 protected $mCdnMaxageLimit = INF
;
234 * @var bool Controls if anti-clickjacking / frame-breaking headers will
235 * be sent. This should be done for pages where edit actions are possible.
236 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
238 protected $mPreventClickjacking = true;
240 /** @var int To include the variable {{REVISIONID}} */
241 private $mRevisionId = null;
244 private $mRevisionTimestamp = null;
247 protected $mFileVersion = null;
250 * @var array An array of stylesheet filenames (relative from skins path),
251 * with options for CSS media, IE conditions, and RTL/LTR direction.
252 * For internal use; add settings in the skin via $this->addStyle()
254 * Style again! This seems like a code duplication since we already have
255 * mStyles. This is what makes Open Source amazing.
257 protected $styles = [];
259 private $mIndexPolicy = 'index';
260 private $mFollowPolicy = 'follow';
261 private $mVaryHeader = [
262 'Accept-Encoding' => [ 'match=gzip' ],
266 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
271 private $mRedirectedFrom = null;
274 * Additional key => value data
276 private $mProperties = [];
279 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
281 private $mTarget = null;
284 * @var bool Whether parser output contains a table of contents
286 private $mEnableTOC = false;
289 * @var string|null The URL to send in a <link> element with rel=license
291 private $copyrightUrl;
293 /** @var array Profiling data */
294 private $limitReportJSData = [];
296 /** @var array Map Title to Content */
297 private $contentOverrides = [];
299 /** @var callable[] */
300 private $contentOverrideCallbacks = [];
303 * Link: header contents
305 private $mLinkHeader = [];
308 * @var string The nonce for Content-Security-Policy
313 * Constructor for OutputPage. This should not be called directly.
314 * Instead a new RequestContext should be created and it will implicitly create
315 * a OutputPage tied to that context.
316 * @param IContextSource $context
318 function __construct( IContextSource
$context ) {
319 $this->setContext( $context );
323 * Redirect to $url rather than displaying the normal page
326 * @param string $responsecode HTTP status code
328 public function redirect( $url, $responsecode = '302' ) {
329 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
330 $this->mRedirect
= str_replace( "\n", '', $url );
331 $this->mRedirectCode
= $responsecode;
335 * Get the URL to redirect to, or an empty string if not redirect URL set
339 public function getRedirect() {
340 return $this->mRedirect
;
344 * Set the copyright URL to send with the output.
345 * Empty string to omit, null to reset.
349 * @param string|null $url
351 public function setCopyrightUrl( $url ) {
352 $this->copyrightUrl
= $url;
356 * Set the HTTP status code to send with the output.
358 * @param int $statusCode
360 public function setStatusCode( $statusCode ) {
361 $this->mStatusCode
= $statusCode;
365 * Add a new "<meta>" tag
366 * To add an http-equiv meta tag, precede the name with "http:"
368 * @param string $name Name of the meta tag
369 * @param string $val Value of the meta tag
371 function addMeta( $name, $val ) {
372 array_push( $this->mMetatags
, [ $name, $val ] );
376 * Returns the current <meta> tags
381 public function getMetaTags() {
382 return $this->mMetatags
;
386 * Add a new \<link\> tag to the page header.
388 * Note: use setCanonicalUrl() for rel=canonical.
390 * @param array $linkarr Associative array of attributes.
392 function addLink( array $linkarr ) {
393 array_push( $this->mLinktags
, $linkarr );
397 * Returns the current <link> tags
402 public function getLinkTags() {
403 return $this->mLinktags
;
407 * Add a new \<link\> with "rel" attribute set to "meta"
409 * @param array $linkarr Associative array mapping attribute names to their
410 * values, both keys and values will be escaped, and the
411 * "rel" attribute will be automatically added
413 function addMetadataLink( array $linkarr ) {
414 $linkarr['rel'] = $this->getMetadataAttribute();
415 $this->addLink( $linkarr );
419 * Set the URL to be used for the <link rel=canonical>. This should be used
420 * in preference to addLink(), to avoid duplicate link tags.
423 function setCanonicalUrl( $url ) {
424 $this->mCanonicalUrl
= $url;
428 * Returns the URL to be used for the <link rel=canonical> if
432 * @return bool|string
434 public function getCanonicalUrl() {
435 return $this->mCanonicalUrl
;
439 * Get the value of the "rel" attribute for metadata links
443 public function getMetadataAttribute() {
444 # note: buggy CC software only reads first "meta" link
445 static $haveMeta = false;
447 return 'alternate meta';
455 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
456 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
459 * @param string $script Raw HTML
461 function addScript( $script ) {
462 $this->mScripts
.= $script;
466 * Add a JavaScript file to be loaded as `<script>` on this page.
468 * Internal use only. Use OutputPage::addModules() if possible.
470 * @param string $file URL to file (absolute path, protocol-relative, or full url)
471 * @param string|null $unused Previously used to change the cache-busting query parameter
473 public function addScriptFile( $file, $unused = null ) {
474 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
475 // This is not an absolute path, protocol-relative url, or full scheme url,
476 // presumed to be an old call intended to include a file from /w/skins/common,
477 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
478 wfDeprecated( __METHOD__
, '1.24' );
481 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
485 * Add a self-contained script tag with the given contents
486 * Internal use only. Use OutputPage::addModules() if possible.
488 * @param string $script JavaScript text, no script tags
490 public function addInlineScript( $script ) {
491 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
495 * Filter an array of modules to remove insufficiently trustworthy members, and modules
496 * which are no longer registered (eg a page is cached before an extension is disabled)
497 * @param array $modules
498 * @param string|null $position Unused
499 * @param string $type
502 protected function filterModules( array $modules, $position = null,
503 $type = ResourceLoaderModule
::TYPE_COMBINED
505 $resourceLoader = $this->getResourceLoader();
506 $filteredModules = [];
507 foreach ( $modules as $val ) {
508 $module = $resourceLoader->getModule( $val );
509 if ( $module instanceof ResourceLoaderModule
510 && $module->getOrigin() <= $this->getAllowedModules( $type )
512 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
513 $this->warnModuleTargetFilter( $module->getName() );
516 $filteredModules[] = $val;
519 return $filteredModules;
522 private function warnModuleTargetFilter( $moduleName ) {
523 static $warnings = [];
524 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
527 $warnings[$this->mTarget
][$moduleName] = true;
528 $this->getResourceLoader()->getLogger()->debug(
529 'Module "{module}" not loadable on target "{target}".',
531 'module' => $moduleName,
532 'target' => $this->mTarget
,
538 * Get the list of modules to include on this page
540 * @param bool $filter Whether to filter out insufficiently trustworthy modules
541 * @param string|null $position Unused
542 * @param string $param
543 * @param string $type
544 * @return array Array of module names
546 public function getModules( $filter = false, $position = null, $param = 'mModules',
547 $type = ResourceLoaderModule
::TYPE_COMBINED
549 $modules = array_values( array_unique( $this->$param ) );
551 ?
$this->filterModules( $modules, null, $type )
556 * Load one or more ResourceLoader modules on this page.
558 * @param string|array $modules Module name (string) or array of module names
560 public function addModules( $modules ) {
561 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
565 * Get the list of script-only modules to load on this page.
567 * @param bool $filter
568 * @param string|null $position Unused
569 * @return array Array of module names
571 public function getModuleScripts( $filter = false, $position = null ) {
572 return $this->getModules( $filter, null, 'mModuleScripts',
573 ResourceLoaderModule
::TYPE_SCRIPTS
578 * Load the scripts of one or more ResourceLoader modules, on this page.
580 * This method exists purely to provide the legacy behaviour of loading
581 * a module's scripts in the global scope, and without dependency resolution.
582 * See <https://phabricator.wikimedia.org/T188689>.
584 * @deprecated since 1.31 Use addModules() instead.
585 * @param string|array $modules Module name (string) or array of module names
587 public function addModuleScripts( $modules ) {
588 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
592 * Get the list of style-only modules to load on this page.
594 * @param bool $filter
595 * @param string|null $position Unused
596 * @return array Array of module names
598 public function getModuleStyles( $filter = false, $position = null ) {
599 return $this->getModules( $filter, null, 'mModuleStyles',
600 ResourceLoaderModule
::TYPE_STYLES
605 * Load the styles of one or more ResourceLoader modules on this page.
607 * Module styles added through this function will be loaded as a stylesheet,
608 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
609 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
611 * @param string|array $modules Module name (string) or array of module names
613 public function addModuleStyles( $modules ) {
614 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
618 * @return null|string ResourceLoader target
620 public function getTarget() {
621 return $this->mTarget
;
625 * Sets ResourceLoader target for load.php links. If null, will be omitted
627 * @param string|null $target
629 public function setTarget( $target ) {
630 $this->mTarget
= $target;
634 * Add a mapping from a LinkTarget to a Content, for things like page preview.
635 * @see self::addContentOverrideCallback()
637 * @param LinkTarget $target
638 * @param Content $content
640 public function addContentOverride( LinkTarget
$target, Content
$content ) {
641 if ( !$this->contentOverrides
) {
642 // Register a callback for $this->contentOverrides on the first call
643 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
644 $key = $target->getNamespace() . ':' . $target->getDBkey();
645 return $this->contentOverrides
[$key] ??
null;
649 $key = $target->getNamespace() . ':' . $target->getDBkey();
650 $this->contentOverrides
[$key] = $content;
654 * Add a callback for mapping from a Title to a Content object, for things
656 * @see ResourceLoaderContext::getContentOverrideCallback()
658 * @param callable $callback
660 public function addContentOverrideCallback( callable
$callback ) {
661 $this->contentOverrideCallbacks
[] = $callback;
665 * Get an array of head items
669 function getHeadItemsArray() {
670 return $this->mHeadItems
;
674 * Add or replace a head item to the output
676 * Whenever possible, use more specific options like ResourceLoader modules,
677 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
678 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
679 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
680 * This would be your very LAST fallback.
682 * @param string $name Item name
683 * @param string $value Raw HTML
685 public function addHeadItem( $name, $value ) {
686 $this->mHeadItems
[$name] = $value;
690 * Add one or more head items to the output
693 * @param string|string[] $values Raw HTML
695 public function addHeadItems( $values ) {
696 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
700 * Check if the header item $name is already set
702 * @param string $name Item name
705 public function hasHeadItem( $name ) {
706 return isset( $this->mHeadItems
[$name] );
710 * Add a class to the <body> element
713 * @param string|string[] $classes One or more classes to add
715 public function addBodyClasses( $classes ) {
716 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
720 * Set whether the output should only contain the body of the article,
721 * without any skin, sidebar, etc.
722 * Used e.g. when calling with "action=render".
724 * @param bool $only Whether to output only the body of the article
726 public function setArticleBodyOnly( $only ) {
727 $this->mArticleBodyOnly
= $only;
731 * Return whether the output will contain only the body of the article
735 public function getArticleBodyOnly() {
736 return $this->mArticleBodyOnly
;
740 * Set an additional output property
743 * @param string $name
744 * @param mixed $value
746 public function setProperty( $name, $value ) {
747 $this->mProperties
[$name] = $value;
751 * Get an additional output property
754 * @param string $name
755 * @return mixed Property value or null if not found
757 public function getProperty( $name ) {
758 return $this->mProperties
[$name] ??
null;
762 * checkLastModified tells the client to use the client-cached page if
763 * possible. If successful, the OutputPage is disabled so that
764 * any future call to OutputPage->output() have no effect.
766 * Side effect: sets mLastModified for Last-Modified header
768 * @param string $timestamp
770 * @return bool True if cache-ok headers was sent.
772 public function checkLastModified( $timestamp ) {
773 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
774 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
777 $config = $this->getConfig();
778 if ( !$config->get( 'CachePages' ) ) {
779 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
783 $timestamp = wfTimestamp( TS_MW
, $timestamp );
785 'page' => $timestamp,
786 'user' => $this->getUser()->getTouched(),
787 'epoch' => $config->get( 'CacheEpoch' )
789 if ( $config->get( 'UseSquid' ) ) {
790 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
792 $config->get( 'SquidMaxage' )
795 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
797 $maxModified = max( $modifiedTimes );
798 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
800 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
801 if ( $clientHeader === false ) {
802 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
806 # IE sends sizes after the date like this:
807 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
808 # this breaks strtotime().
809 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
811 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
812 $clientHeaderTime = strtotime( $clientHeader );
813 Wikimedia\restoreWarnings
();
814 if ( !$clientHeaderTime ) {
816 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
819 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
823 foreach ( $modifiedTimes as $name => $value ) {
824 if ( $info !== '' ) {
827 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
830 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
831 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
832 wfDebug( __METHOD__
. ": effective Last-Modified: " .
833 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
834 if ( $clientHeaderTime < $maxModified ) {
835 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
840 # Give a 304 Not Modified response code and disable body output
841 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
842 ini_set( 'zlib.output_compression', 0 );
843 $this->getRequest()->response()->statusHeader( 304 );
844 $this->sendCacheControl();
847 // Don't output a compressed blob when using ob_gzhandler;
848 // it's technically against HTTP spec and seems to confuse
849 // Firefox when the response gets split over two packets.
850 wfClearOutputBuffers();
856 * @param int $reqTime Time of request (eg. now)
857 * @param int $maxAge Cache TTL in seconds
858 * @return int Timestamp
860 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
861 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
862 // because even if the wiki page content hasn't changed since, static
863 // resources may have changed (skin HTML, interface messages, urls, etc.)
864 // and must roll-over in a timely manner (T46570)
865 return $reqTime - $maxAge;
869 * Override the last modified timestamp
871 * @param string $timestamp New timestamp, in a format readable by
874 public function setLastModified( $timestamp ) {
875 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
879 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
881 * @param string $policy The literal string to output as the contents of
882 * the meta tag. Will be parsed according to the spec and output in
886 public function setRobotPolicy( $policy ) {
887 $policy = Article
::formatRobotPolicy( $policy );
889 if ( isset( $policy['index'] ) ) {
890 $this->setIndexPolicy( $policy['index'] );
892 if ( isset( $policy['follow'] ) ) {
893 $this->setFollowPolicy( $policy['follow'] );
898 * Set the index policy for the page, but leave the follow policy un-
901 * @param string $policy Either 'index' or 'noindex'.
904 public function setIndexPolicy( $policy ) {
905 $policy = trim( $policy );
906 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
907 $this->mIndexPolicy
= $policy;
912 * Set the follow policy for the page, but leave the index policy un-
915 * @param string $policy Either 'follow' or 'nofollow'.
918 public function setFollowPolicy( $policy ) {
919 $policy = trim( $policy );
920 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
921 $this->mFollowPolicy
= $policy;
926 * Set the new value of the "action text", this will be added to the
927 * "HTML title", separated from it with " - ".
929 * @param string $text New value of the "action text"
931 public function setPageTitleActionText( $text ) {
932 $this->mPageTitleActionText
= $text;
936 * Get the value of the "action text"
940 public function getPageTitleActionText() {
941 return $this->mPageTitleActionText
;
945 * "HTML title" means the contents of "<title>".
946 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
948 * @param string|Message $name
950 public function setHTMLTitle( $name ) {
951 if ( $name instanceof Message
) {
952 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
954 $this->mHTMLtitle
= $name;
959 * Return the "HTML title", i.e. the content of the "<title>" tag.
963 public function getHTMLTitle() {
964 return $this->mHTMLtitle
;
968 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
972 public function setRedirectedFrom( $t ) {
973 $this->mRedirectedFrom
= $t;
977 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
978 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
979 * but not bad tags like \<script\>. This function automatically sets
980 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
981 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
982 * good tags like \<i\> will be dropped entirely.
984 * @param string|Message $name
986 public function setPageTitle( $name ) {
987 if ( $name instanceof Message
) {
988 $name = $name->setContext( $this->getContext() )->text();
991 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
992 # but leave "<i>foobar</i>" alone
993 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
994 $this->mPageTitle
= $nameWithTags;
996 # change "<i>foo&bar</i>" to "foo&bar"
998 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
999 ->inContentLanguage()
1004 * Return the "page title", i.e. the content of the \<h1\> tag.
1008 public function getPageTitle() {
1009 return $this->mPageTitle
;
1013 * Set the Title object to use
1017 public function setTitle( Title
$t ) {
1018 $this->getContext()->setTitle( $t );
1022 * Replace the subtitle with $str
1024 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1026 public function setSubtitle( $str ) {
1027 $this->clearSubtitle();
1028 $this->addSubtitle( $str );
1032 * Add $str to the subtitle
1034 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1036 public function addSubtitle( $str ) {
1037 if ( $str instanceof Message
) {
1038 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1040 $this->mSubtitle
[] = $str;
1045 * Build message object for a subtitle containing a backlink to a page
1047 * @param Title $title Title to link to
1048 * @param array $query Array of additional parameters to include in the link
1052 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1053 if ( $title->isRedirect() ) {
1054 $query['redirect'] = 'no';
1056 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1057 return wfMessage( 'backlinksubtitle' )
1058 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1062 * Add a subtitle containing a backlink to a page
1064 * @param Title $title Title to link to
1065 * @param array $query Array of additional parameters to include in the link
1067 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1068 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1072 * Clear the subtitles
1074 public function clearSubtitle() {
1075 $this->mSubtitle
= [];
1083 public function getSubtitle() {
1084 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1088 * Set the page as printable, i.e. it'll be displayed with all
1089 * print styles included
1091 public function setPrintable() {
1092 $this->mPrintable
= true;
1096 * Return whether the page is "printable"
1100 public function isPrintable() {
1101 return $this->mPrintable
;
1105 * Disable output completely, i.e. calling output() will have no effect
1107 public function disable() {
1108 $this->mDoNothing
= true;
1112 * Return whether the output will be completely disabled
1116 public function isDisabled() {
1117 return $this->mDoNothing
;
1121 * Show an "add new section" link?
1125 public function showNewSectionLink() {
1126 return $this->mNewSectionLink
;
1130 * Forcibly hide the new section link?
1134 public function forceHideNewSectionLink() {
1135 return $this->mHideNewSectionLink
;
1139 * Add or remove feed links in the page header
1140 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1141 * for the new version
1142 * @see addFeedLink()
1144 * @param bool $show True: add default feeds, false: remove all feeds
1146 public function setSyndicated( $show = true ) {
1148 $this->setFeedAppendQuery( false );
1150 $this->mFeedLinks
= [];
1155 * Add default feeds to the page header
1156 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1157 * for the new version
1158 * @see addFeedLink()
1160 * @param string $val Query to append to feed links or false to output
1163 public function setFeedAppendQuery( $val ) {
1164 $this->mFeedLinks
= [];
1166 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1167 $query = "feed=$type";
1168 if ( is_string( $val ) ) {
1169 $query .= '&' . $val;
1171 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1176 * Add a feed link to the page header
1178 * @param string $format Feed type, should be a key of $wgFeedClasses
1179 * @param string $href URL
1181 public function addFeedLink( $format, $href ) {
1182 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1183 $this->mFeedLinks
[$format] = $href;
1188 * Should we output feed links for this page?
1191 public function isSyndicated() {
1192 return count( $this->mFeedLinks
) > 0;
1196 * Return URLs for each supported syndication format for this page.
1197 * @return array Associating format keys with URLs
1199 public function getSyndicationLinks() {
1200 return $this->mFeedLinks
;
1204 * Will currently always return null
1208 public function getFeedAppendQuery() {
1209 return $this->mFeedLinksAppendQuery
;
1213 * Set whether the displayed content is related to the source of the
1214 * corresponding article on the wiki
1215 * Setting true will cause the change "article related" toggle to true
1219 public function setArticleFlag( $v ) {
1220 $this->mIsarticle
= $v;
1222 $this->mIsArticleRelated
= $v;
1227 * Return whether the content displayed page is related to the source of
1228 * the corresponding article on the wiki
1232 public function isArticle() {
1233 return $this->mIsarticle
;
1237 * Set whether this page is related an article on the wiki
1238 * Setting false will cause the change of "article flag" toggle to false
1242 public function setArticleRelated( $v ) {
1243 $this->mIsArticleRelated
= $v;
1245 $this->mIsarticle
= false;
1250 * Return whether this page is related an article on the wiki
1254 public function isArticleRelated() {
1255 return $this->mIsArticleRelated
;
1259 * Add new language links
1261 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1262 * (e.g. 'fr:Test page')
1264 public function addLanguageLinks( array $newLinkArray ) {
1265 $this->mLanguageLinks +
= $newLinkArray;
1269 * Reset the language links and add new language links
1271 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1272 * (e.g. 'fr:Test page')
1274 public function setLanguageLinks( array $newLinkArray ) {
1275 $this->mLanguageLinks
= $newLinkArray;
1279 * Get the list of language links
1281 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1283 public function getLanguageLinks() {
1284 return $this->mLanguageLinks
;
1288 * Add an array of categories, with names in the keys
1290 * @param array $categories Mapping category name => sort key
1292 public function addCategoryLinks( array $categories ) {
1295 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1299 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1301 # Set all the values to 'normal'.
1302 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1304 # Mark hidden categories
1305 foreach ( $res as $row ) {
1306 if ( isset( $row->pp_value
) ) {
1307 $categories[$row->page_title
] = 'hidden';
1311 // Avoid PHP 7.1 warning of passing $this by reference
1312 $outputPage = $this;
1313 # Add the remaining categories to the skin
1315 'OutputPageMakeCategoryLinks',
1316 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1318 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1319 foreach ( $categories as $category => $type ) {
1320 // array keys will cast numeric category names to ints, so cast back to string
1321 $category = (string)$category;
1322 $origcategory = $category;
1323 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1327 $wgContLang->findVariantLink( $category, $title, true );
1328 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1331 $text = $wgContLang->convertHtml( $title->getText() );
1332 $this->mCategories
[$type][] = $title->getText();
1333 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1339 * @param array $categories
1340 * @return bool|IResultWrapper
1342 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1343 # Add the links to a LinkBatch
1344 $arr = [ NS_CATEGORY
=> $categories ];
1345 $lb = new LinkBatch
;
1346 $lb->setArray( $arr );
1348 # Fetch existence plus the hiddencat property
1349 $dbr = wfGetDB( DB_REPLICA
);
1350 $fields = array_merge(
1351 LinkCache
::getSelectFields(),
1352 [ 'page_namespace', 'page_title', 'pp_value' ]
1355 $res = $dbr->select( [ 'page', 'page_props' ],
1357 $lb->constructSet( 'page', $dbr ),
1360 [ 'page_props' => [ 'LEFT JOIN', [
1361 'pp_propname' => 'hiddencat',
1366 # Add the results to the link cache
1367 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1368 $lb->addResultToCache( $linkCache, $res );
1374 * Reset the category links (but not the category list) and add $categories
1376 * @param array $categories Mapping category name => sort key
1378 public function setCategoryLinks( array $categories ) {
1379 $this->mCategoryLinks
= [];
1380 $this->addCategoryLinks( $categories );
1384 * Get the list of category links, in a 2-D array with the following format:
1385 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1386 * hidden categories) and $link a HTML fragment with a link to the category
1391 public function getCategoryLinks() {
1392 return $this->mCategoryLinks
;
1396 * Get the list of category names this page belongs to.
1398 * @param string $type The type of categories which should be returned. Possible values:
1399 * * all: all categories of all types
1400 * * hidden: only the hidden categories
1401 * * normal: all categories, except hidden categories
1402 * @return array Array of strings
1404 public function getCategories( $type = 'all' ) {
1405 if ( $type === 'all' ) {
1406 $allCategories = [];
1407 foreach ( $this->mCategories
as $categories ) {
1408 $allCategories = array_merge( $allCategories, $categories );
1410 return $allCategories;
1412 if ( !isset( $this->mCategories
[$type] ) ) {
1413 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1415 return $this->mCategories
[$type];
1419 * Add an array of indicators, with their identifiers as array
1420 * keys and HTML contents as values.
1422 * In case of duplicate keys, existing values are overwritten.
1424 * @param array $indicators
1427 public function setIndicators( array $indicators ) {
1428 $this->mIndicators
= $indicators +
$this->mIndicators
;
1429 // Keep ordered by key
1430 ksort( $this->mIndicators
);
1434 * Get the indicators associated with this page.
1436 * The array will be internally ordered by item keys.
1438 * @return array Keys: identifiers, values: HTML contents
1441 public function getIndicators() {
1442 return $this->mIndicators
;
1446 * Adds help link with an icon via page indicators.
1447 * Link target can be overridden by a local message containing a wikilink:
1448 * the message key is: lowercase action or special page name + '-helppage'.
1449 * @param string $to Target MediaWiki.org page title or encoded URL.
1450 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1453 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1454 $this->addModuleStyles( 'mediawiki.helplink' );
1455 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1457 if ( $overrideBaseUrl ) {
1460 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1461 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1464 $link = Html
::rawElement(
1468 'target' => '_blank',
1469 'class' => 'mw-helplink',
1474 $this->setIndicators( [ 'mw-helplink' => $link ] );
1478 * Do not allow scripts which can be modified by wiki users to load on this page;
1479 * only allow scripts bundled with, or generated by, the software.
1480 * Site-wide styles are controlled by a config setting, since they can be
1481 * used to create a custom skin/theme, but not user-specific ones.
1483 * @todo this should be given a more accurate name
1485 public function disallowUserJs() {
1486 $this->reduceAllowedModules(
1487 ResourceLoaderModule
::TYPE_SCRIPTS
,
1488 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1491 // Site-wide styles are controlled by a config setting, see T73621
1492 // for background on why. User styles are never allowed.
1493 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1494 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1496 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1498 $this->reduceAllowedModules(
1499 ResourceLoaderModule
::TYPE_STYLES
,
1505 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1506 * @see ResourceLoaderModule::$origin
1507 * @param string $type ResourceLoaderModule TYPE_ constant
1508 * @return int ResourceLoaderModule ORIGIN_ class constant
1510 public function getAllowedModules( $type ) {
1511 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1512 return min( array_values( $this->mAllowedModules
) );
1514 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1519 * Limit the highest level of CSS/JS untrustworthiness allowed.
1521 * If passed the same or a higher level than the current level of untrustworthiness set, the
1522 * level will remain unchanged.
1524 * @param string $type
1525 * @param int $level ResourceLoaderModule class constant
1527 public function reduceAllowedModules( $type, $level ) {
1528 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1532 * Prepend $text to the body HTML
1534 * @param string $text HTML
1536 public function prependHTML( $text ) {
1537 $this->mBodytext
= $text . $this->mBodytext
;
1541 * Append $text to the body HTML
1543 * @param string $text HTML
1545 public function addHTML( $text ) {
1546 $this->mBodytext
.= $text;
1550 * Shortcut for adding an Html::element via addHTML.
1554 * @param string $element
1555 * @param array $attribs
1556 * @param string $contents
1558 public function addElement( $element, array $attribs = [], $contents = '' ) {
1559 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1563 * Clear the body HTML
1565 public function clearHTML() {
1566 $this->mBodytext
= '';
1572 * @return string HTML
1574 public function getHTML() {
1575 return $this->mBodytext
;
1579 * Get/set the ParserOptions object to use for wikitext parsing
1581 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1582 * current ParserOption object. This parameter is deprecated since 1.31.
1583 * @return ParserOptions
1585 public function parserOptions( $options = null ) {
1586 if ( $options !== null ) {
1587 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1590 if ( $options !== null && !empty( $options->isBogus
) ) {
1591 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1592 // been changed somehow, and keep it if so.
1593 $anonPO = ParserOptions
::newFromAnon();
1594 $anonPO->setAllowUnsafeRawHtml( false );
1595 if ( !$options->matches( $anonPO ) ) {
1596 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1597 $options->isBogus
= false;
1601 if ( !$this->mParserOptions
) {
1602 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1603 // $wgUser isn't unstubbable yet, so don't try to get a
1604 // ParserOptions for it. And don't cache this ParserOptions
1606 $po = ParserOptions
::newFromAnon();
1607 $po->setAllowUnsafeRawHtml( false );
1608 $po->isBogus
= true;
1609 if ( $options !== null ) {
1610 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1615 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1616 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1619 if ( $options !== null && !empty( $options->isBogus
) ) {
1620 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1622 return wfSetVar( $this->mParserOptions
, null, true );
1624 return wfSetVar( $this->mParserOptions
, $options );
1629 * Set the revision ID which will be seen by the wiki text parser
1630 * for things such as embedded {{REVISIONID}} variable use.
1632 * @param int|null $revid An positive integer, or null
1633 * @return mixed Previous value
1635 public function setRevisionId( $revid ) {
1636 $val = is_null( $revid ) ?
null : intval( $revid );
1637 return wfSetVar( $this->mRevisionId
, $val );
1641 * Get the displayed revision ID
1645 public function getRevisionId() {
1646 return $this->mRevisionId
;
1650 * Set the timestamp of the revision which will be displayed. This is used
1651 * to avoid a extra DB call in Skin::lastModified().
1653 * @param string|null $timestamp
1654 * @return mixed Previous value
1656 public function setRevisionTimestamp( $timestamp ) {
1657 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1661 * Get the timestamp of displayed revision.
1662 * This will be null if not filled by setRevisionTimestamp().
1664 * @return string|null
1666 public function getRevisionTimestamp() {
1667 return $this->mRevisionTimestamp
;
1671 * Set the displayed file version
1673 * @param File|bool $file
1674 * @return mixed Previous value
1676 public function setFileVersion( $file ) {
1678 if ( $file instanceof File
&& $file->exists() ) {
1679 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1681 return wfSetVar( $this->mFileVersion
, $val, true );
1685 * Get the displayed file version
1687 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1689 public function getFileVersion() {
1690 return $this->mFileVersion
;
1694 * Get the templates used on this page
1696 * @return array (namespace => dbKey => revId)
1699 public function getTemplateIds() {
1700 return $this->mTemplateIds
;
1704 * Get the files used on this page
1706 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1709 public function getFileSearchOptions() {
1710 return $this->mImageTimeKeys
;
1714 * Convert wikitext to HTML and add it to the buffer
1715 * Default assumes that the current page title will be used.
1717 * @param string $text
1718 * @param bool $linestart Is this the start of a line?
1719 * @param bool $interface Is this text in the user interface language?
1720 * @throws MWException
1722 public function addWikiText( $text, $linestart = true, $interface = true ) {
1723 $title = $this->getTitle(); // Work around E_STRICT
1725 throw new MWException( 'Title is null' );
1727 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1731 * Add wikitext with a custom Title object
1733 * @param string $text Wikitext
1734 * @param Title &$title
1735 * @param bool $linestart Is this the start of a line?
1737 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1738 $this->addWikiTextTitle( $text, $title, $linestart );
1742 * Add wikitext with a custom Title object and tidy enabled.
1744 * @param string $text Wikitext
1745 * @param Title &$title
1746 * @param bool $linestart Is this the start of a line?
1748 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1749 $this->addWikiTextTitle( $text, $title, $linestart, true );
1753 * Add wikitext with tidy enabled
1755 * @param string $text Wikitext
1756 * @param bool $linestart Is this the start of a line?
1758 public function addWikiTextTidy( $text, $linestart = true ) {
1759 $title = $this->getTitle();
1760 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1764 * Add wikitext with a custom Title object
1766 * @param string $text Wikitext
1767 * @param Title $title
1768 * @param bool $linestart Is this the start of a line?
1769 * @param bool $tidy Whether to use tidy
1770 * @param bool $interface Whether it is an interface message
1771 * (for example disables conversion)
1773 public function addWikiTextTitle( $text, Title
$title, $linestart,
1774 $tidy = false, $interface = false
1778 $popts = $this->parserOptions();
1779 $oldTidy = $popts->setTidy( $tidy );
1780 $popts->setInterfaceMessage( (bool)$interface );
1782 $parserOutput = $wgParser->getFreshParser()->parse(
1783 $text, $title, $popts,
1784 $linestart, true, $this->mRevisionId
1787 $popts->setTidy( $oldTidy );
1789 $this->addParserOutput( $parserOutput, [
1790 'enableSectionEditLinks' => false,
1795 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1796 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1800 * @param ParserOutput $parserOutput
1802 public function addParserOutputMetadata( $parserOutput ) {
1803 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1804 $this->addCategoryLinks( $parserOutput->getCategories() );
1805 $this->setIndicators( $parserOutput->getIndicators() );
1806 $this->mNewSectionLink
= $parserOutput->getNewSection();
1807 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1809 if ( !$parserOutput->isCacheable() ) {
1810 $this->enableClientCache( false );
1812 $this->mNoGallery
= $parserOutput->getNoGallery();
1813 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1814 $this->addModules( $parserOutput->getModules() );
1815 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1816 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1817 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1818 $this->mPreventClickjacking
= $this->mPreventClickjacking
1819 ||
$parserOutput->preventClickjacking();
1821 // Template versioning...
1822 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1823 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1824 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1826 $this->mTemplateIds
[$ns] = $dbks;
1829 // File versioning...
1830 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1831 $this->mImageTimeKeys
[$dbk] = $data;
1834 // Hooks registered in the object
1835 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1836 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1837 list( $hookName, $data ) = $hookInfo;
1838 if ( isset( $parserOutputHooks[$hookName] ) ) {
1839 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1843 // Enable OOUI if requested via ParserOutput
1844 if ( $parserOutput->getEnableOOUI() ) {
1845 $this->enableOOUI();
1848 // Include parser limit report
1849 if ( !$this->limitReportJSData
) {
1850 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1853 // Link flags are ignored for now, but may in the future be
1854 // used to mark individual language links.
1856 // Avoid PHP 7.1 warning of passing $this by reference
1857 $outputPage = $this;
1858 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1859 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1861 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1862 // so that extensions may modify ParserOutput to toggle TOC.
1863 // This cannot be moved to addParserOutputText because that is not
1864 // called by EditPage for Preview.
1865 if ( $parserOutput->getTOCHTML() ) {
1866 $this->mEnableTOC
= true;
1871 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1872 * ParserOutput object, without any other metadata.
1875 * @param ParserOutput $parserOutput
1876 * @param array $poOptions Options to ParserOutput::getText()
1878 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1879 $this->addParserOutputText( $parserOutput, $poOptions );
1881 $this->addModules( $parserOutput->getModules() );
1882 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1883 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1885 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1889 * Add the HTML associated with a ParserOutput object, without any metadata.
1892 * @param ParserOutput $parserOutput
1893 * @param array $poOptions Options to ParserOutput::getText()
1895 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1896 $text = $parserOutput->getText( $poOptions );
1897 // Avoid PHP 7.1 warning of passing $this by reference
1898 $outputPage = $this;
1899 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1900 $this->addHTML( $text );
1904 * Add everything from a ParserOutput object.
1906 * @param ParserOutput $parserOutput
1907 * @param array $poOptions Options to ParserOutput::getText()
1909 function addParserOutput( $parserOutput, $poOptions = [] ) {
1910 $this->addParserOutputMetadata( $parserOutput );
1911 $this->addParserOutputText( $parserOutput, $poOptions );
1915 * Add the output of a QuickTemplate to the output buffer
1917 * @param QuickTemplate &$template
1919 public function addTemplate( &$template ) {
1920 $this->addHTML( $template->getHTML() );
1924 * Parse wikitext and return the HTML.
1926 * @param string $text
1927 * @param bool $linestart Is this the start of a line?
1928 * @param bool $interface Use interface language ($wgLang instead of
1929 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1930 * This also disables LanguageConverter.
1931 * @param Language|null $language Target language object, will override $interface
1932 * @throws MWException
1933 * @return string HTML
1935 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1938 if ( is_null( $this->getTitle() ) ) {
1939 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1942 $popts = $this->parserOptions();
1944 $popts->setInterfaceMessage( true );
1946 if ( $language !== null ) {
1947 $oldLang = $popts->setTargetLanguage( $language );
1950 $parserOutput = $wgParser->getFreshParser()->parse(
1951 $text, $this->getTitle(), $popts,
1952 $linestart, true, $this->mRevisionId
1956 $popts->setInterfaceMessage( false );
1958 if ( $language !== null ) {
1959 $popts->setTargetLanguage( $oldLang );
1962 return $parserOutput->getText( [
1963 'enableSectionEditLinks' => false,
1968 * Parse wikitext, strip paragraphs, and return the HTML.
1970 * @param string $text
1971 * @param bool $linestart Is this the start of a line?
1972 * @param bool $interface Use interface language ($wgLang instead of
1973 * $wgContLang) while parsing language sensitive magic
1974 * words like GRAMMAR and PLURAL
1975 * @return string HTML
1977 public function parseInline( $text, $linestart = true, $interface = false ) {
1978 $parsed = $this->parse( $text, $linestart, $interface );
1979 return Parser
::stripOuterParagraph( $parsed );
1983 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1985 * @param int $maxage Maximum cache time on the CDN, in seconds.
1987 public function setCdnMaxage( $maxage ) {
1988 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1992 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1994 * @param int $maxage Maximum cache time on the CDN, in seconds
1997 public function lowerCdnMaxage( $maxage ) {
1998 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1999 $this->setCdnMaxage( $this->mCdnMaxage
);
2003 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2005 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2006 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2007 * TTL is 90% of the age of the object, subject to the min and max.
2009 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2010 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2011 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2012 * @return int TTL in seconds
2015 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2016 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2017 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2019 if ( $mtime === null ||
$mtime === false ) {
2020 return $minTTL; // entity does not exist
2023 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2024 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2025 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2027 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2029 return $adaptiveTTL;
2033 * Use enableClientCache(false) to force it to send nocache headers
2035 * @param bool $state
2039 public function enableClientCache( $state ) {
2040 return wfSetVar( $this->mEnableClientCache
, $state );
2044 * Get the list of cookies that will influence on the cache
2048 function getCacheVaryCookies() {
2050 if ( $cookies === null ) {
2051 $config = $this->getConfig();
2052 $cookies = array_merge(
2053 SessionManager
::singleton()->getVaryCookies(),
2057 $config->get( 'CacheVaryCookies' )
2059 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2065 * Check if the request has a cache-varying cookie header
2066 * If it does, it's very important that we don't allow public caching
2070 function haveCacheVaryCookies() {
2071 $request = $this->getRequest();
2072 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2073 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2074 wfDebug( __METHOD__
. ": found $cookieName\n" );
2078 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2083 * Add an HTTP header that will influence on the cache
2085 * @param string $header Header name
2086 * @param string[]|null $option Options for the Key header. See
2087 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2088 * for the list of valid options.
2090 public function addVaryHeader( $header, array $option = null ) {
2091 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2092 $this->mVaryHeader
[$header] = [];
2094 if ( !is_array( $option ) ) {
2097 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2101 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2102 * such as Accept-Encoding or Cookie
2106 public function getVaryHeader() {
2107 // If we vary on cookies, let's make sure it's always included here too.
2108 if ( $this->getCacheVaryCookies() ) {
2109 $this->addVaryHeader( 'Cookie' );
2112 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2113 $this->addVaryHeader( $header, $options );
2115 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2119 * Add an HTTP Link: header
2121 * @param string $header Header value
2123 public function addLinkHeader( $header ) {
2124 $this->mLinkHeader
[] = $header;
2128 * Return a Link: header. Based on the values of $mLinkHeader.
2132 public function getLinkHeader() {
2133 if ( !$this->mLinkHeader
) {
2137 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2141 * Get a complete Key header
2145 public function getKeyHeader() {
2146 $cvCookies = $this->getCacheVaryCookies();
2148 $cookiesOption = [];
2149 foreach ( $cvCookies as $cookieName ) {
2150 $cookiesOption[] = 'param=' . $cookieName;
2152 $this->addVaryHeader( 'Cookie', $cookiesOption );
2154 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2155 $this->addVaryHeader( $header, $options );
2159 foreach ( $this->mVaryHeader
as $header => $option ) {
2160 $newheader = $header;
2161 if ( is_array( $option ) && count( $option ) > 0 ) {
2162 $newheader .= ';' . implode( ';', $option );
2164 $headers[] = $newheader;
2166 $key = 'Key: ' . implode( ',', $headers );
2172 * T23672: Add Accept-Language to Vary and Key headers
2173 * if there's no 'variant' parameter existed in GET.
2176 * /w/index.php?title=Main_page should always be served; but
2177 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2179 function addAcceptLanguage() {
2180 $title = $this->getTitle();
2181 if ( !$title instanceof Title
) {
2185 $lang = $title->getPageLanguage();
2186 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2187 $variants = $lang->getVariants();
2189 foreach ( $variants as $variant ) {
2190 if ( $variant === $lang->getCode() ) {
2193 $aloption[] = 'substr=' . $variant;
2195 // IE and some other browsers use BCP 47 standards in
2196 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2197 // We should handle these too.
2198 $variantBCP47 = LanguageCode
::bcp47( $variant );
2199 if ( $variantBCP47 !== $variant ) {
2200 $aloption[] = 'substr=' . $variantBCP47;
2204 $this->addVaryHeader( 'Accept-Language', $aloption );
2209 * Set a flag which will cause an X-Frame-Options header appropriate for
2210 * edit pages to be sent. The header value is controlled by
2211 * $wgEditPageFrameOptions.
2213 * This is the default for special pages. If you display a CSRF-protected
2214 * form on an ordinary view page, then you need to call this function.
2216 * @param bool $enable
2218 public function preventClickjacking( $enable = true ) {
2219 $this->mPreventClickjacking
= $enable;
2223 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2224 * This can be called from pages which do not contain any CSRF-protected
2227 public function allowClickjacking() {
2228 $this->mPreventClickjacking
= false;
2232 * Get the prevent-clickjacking flag
2237 public function getPreventClickjacking() {
2238 return $this->mPreventClickjacking
;
2242 * Get the X-Frame-Options header value (without the name part), or false
2243 * if there isn't one. This is used by Skin to determine whether to enable
2244 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2246 * @return string|false
2248 public function getFrameOptions() {
2249 $config = $this->getConfig();
2250 if ( $config->get( 'BreakFrames' ) ) {
2252 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2253 return $config->get( 'EditPageFrameOptions' );
2259 * Send cache control HTTP headers
2261 public function sendCacheControl() {
2262 $response = $this->getRequest()->response();
2263 $config = $this->getConfig();
2265 $this->addVaryHeader( 'Cookie' );
2266 $this->addAcceptLanguage();
2268 # don't serve compressed data to clients who can't handle it
2269 # maintain different caches for logged-in users and non-logged in ones
2270 $response->header( $this->getVaryHeader() );
2272 if ( $config->get( 'UseKeyHeader' ) ) {
2273 $response->header( $this->getKeyHeader() );
2276 if ( $this->mEnableClientCache
) {
2278 $config->get( 'UseSquid' ) &&
2279 !$response->hasCookies() &&
2280 !SessionManager
::getGlobalSession()->isPersistent() &&
2281 !$this->isPrintable() &&
2282 $this->mCdnMaxage
!= 0 &&
2283 !$this->haveCacheVaryCookies()
2285 if ( $config->get( 'UseESI' ) ) {
2286 # We'll purge the proxy cache explicitly, but require end user agents
2287 # to revalidate against the proxy on each visit.
2288 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2289 wfDebug( __METHOD__
.
2290 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2291 # start with a shorter timeout for initial testing
2292 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2294 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2295 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2297 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2299 # We'll purge the proxy cache for anons explicitly, but require end user agents
2300 # to revalidate against the proxy on each visit.
2301 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2302 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2303 wfDebug( __METHOD__
.
2304 ": local proxy caching; {$this->mLastModified} **", 'private' );
2305 # start with a shorter timeout for initial testing
2306 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2307 $response->header( "Cache-Control: " .
2308 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2311 # We do want clients to cache if they can, but they *must* check for updates
2312 # on revisiting the page.
2313 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2314 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2315 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2317 if ( $this->mLastModified
) {
2318 $response->header( "Last-Modified: {$this->mLastModified}" );
2321 wfDebug( __METHOD__
. ": no caching **", 'private' );
2323 # In general, the absence of a last modified header should be enough to prevent
2324 # the client from using its cache. We send a few other things just to make sure.
2325 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2326 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2327 $response->header( 'Pragma: no-cache' );
2332 * Transfer styles and JavaScript modules from skin.
2334 * @param Skin $sk to load modules for
2336 public function loadSkinModules( $sk ) {
2337 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2338 if ( $group === 'styles' ) {
2339 foreach ( $modules as $key => $moduleMembers ) {
2340 $this->addModuleStyles( $moduleMembers );
2343 $this->addModules( $modules );
2349 * Finally, all the text has been munged and accumulated into
2350 * the object, let's actually output it:
2352 * @param bool $return Set to true to get the result as a string rather than sending it
2353 * @return string|null
2355 * @throws FatalError
2356 * @throws MWException
2358 public function output( $return = false ) {
2361 if ( $this->mDoNothing
) {
2362 return $return ?
'' : null;
2365 $response = $this->getRequest()->response();
2366 $config = $this->getConfig();
2368 if ( $this->mRedirect
!= '' ) {
2369 # Standards require redirect URLs to be absolute
2370 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2372 $redirect = $this->mRedirect
;
2373 $code = $this->mRedirectCode
;
2375 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2376 if ( $code == '301' ||
$code == '303' ) {
2377 if ( !$config->get( 'DebugRedirects' ) ) {
2378 $response->statusHeader( $code );
2380 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2382 if ( $config->get( 'VaryOnXFP' ) ) {
2383 $this->addVaryHeader( 'X-Forwarded-Proto' );
2385 $this->sendCacheControl();
2387 $response->header( "Content-Type: text/html; charset=utf-8" );
2388 if ( $config->get( 'DebugRedirects' ) ) {
2389 $url = htmlspecialchars( $redirect );
2390 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2391 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2392 print "</body>\n</html>\n";
2394 $response->header( 'Location: ' . $redirect );
2398 return $return ?
'' : null;
2399 } elseif ( $this->mStatusCode
) {
2400 $response->statusHeader( $this->mStatusCode
);
2403 # Buffer output; final headers may depend on later processing
2406 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2407 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2409 if ( !$this->mArticleBodyOnly
) {
2410 $sk = $this->getSkin();
2412 if ( $sk->shouldPreloadLogo() ) {
2413 $this->addLogoPreloadLinkHeaders();
2417 $linkHeader = $this->getLinkHeader();
2418 if ( $linkHeader ) {
2419 $response->header( $linkHeader );
2422 // Prevent framing, if requested
2423 $frameOptions = $this->getFrameOptions();
2424 if ( $frameOptions ) {
2425 $response->header( "X-Frame-Options: $frameOptions" );
2428 ContentSecurityPolicy
::sendHeaders( $this );
2430 if ( $this->mArticleBodyOnly
) {
2431 echo $this->mBodytext
;
2433 // Enable safe mode if requested (T152169)
2434 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2435 $this->disallowUserJs();
2438 $sk = $this->getSkin();
2439 $this->loadSkinModules( $sk );
2441 MWDebug
::addModules( $this );
2443 // Avoid PHP 7.1 warning of passing $this by reference
2444 $outputPage = $this;
2445 // Hook that allows last minute changes to the output page, e.g.
2446 // adding of CSS or Javascript by extensions.
2447 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2451 } catch ( Exception
$e ) {
2452 ob_end_clean(); // bug T129657
2458 // This hook allows last minute changes to final overall output by modifying output buffer
2459 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2460 } catch ( Exception
$e ) {
2461 ob_end_clean(); // bug T129657
2465 $this->sendCacheControl();
2468 return ob_get_clean();
2476 * Prepare this object to display an error page; disable caching and
2477 * indexing, clear the current text and redirect, set the page's title
2478 * and optionally an custom HTML title (content of the "<title>" tag).
2480 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2481 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2482 * optional, if not passed the "<title>" attribute will be
2483 * based on $pageTitle
2485 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2486 $this->setPageTitle( $pageTitle );
2487 if ( $htmlTitle !== false ) {
2488 $this->setHTMLTitle( $htmlTitle );
2490 $this->setRobotPolicy( 'noindex,nofollow' );
2491 $this->setArticleRelated( false );
2492 $this->enableClientCache( false );
2493 $this->mRedirect
= '';
2494 $this->clearSubtitle();
2499 * Output a standard error page
2501 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2502 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2503 * showErrorPage( 'titlemsg', $messageObject );
2504 * showErrorPage( $titleMessageObject, $messageObject );
2506 * @param string|Message $title Message key (string) for page title, or a Message object
2507 * @param string|Message $msg Message key (string) for page text, or a Message object
2508 * @param array $params Message parameters; ignored if $msg is a Message object
2510 public function showErrorPage( $title, $msg, $params = [] ) {
2511 if ( !$title instanceof Message
) {
2512 $title = $this->msg( $title );
2515 $this->prepareErrorPage( $title );
2517 if ( $msg instanceof Message
) {
2518 if ( $params !== [] ) {
2519 trigger_error( 'Argument ignored: $params. The message parameters argument '
2520 . 'is discarded when the $msg argument is a Message object instead of '
2521 . 'a string.', E_USER_NOTICE
);
2523 $this->addHTML( $msg->parseAsBlock() );
2525 $this->addWikiMsgArray( $msg, $params );
2528 $this->returnToMain();
2532 * Output a standard permission error page
2534 * @param array $errors Error message keys or [key, param...] arrays
2535 * @param string|null $action Action that was denied or null if unknown
2537 public function showPermissionsErrorPage( array $errors, $action = null ) {
2538 foreach ( $errors as $key => $error ) {
2539 $errors[$key] = (array)$error;
2542 // For some action (read, edit, create and upload), display a "login to do this action"
2543 // error if all of the following conditions are met:
2544 // 1. the user is not logged in
2545 // 2. the only error is insufficient permissions (i.e. no block or something else)
2546 // 3. the error can be avoided simply by logging in
2547 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2548 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2549 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2550 && ( User
::groupHasPermission( 'user', $action )
2551 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2553 $displayReturnto = null;
2555 # Due to T34276, if a user does not have read permissions,
2556 # $this->getTitle() will just give Special:Badtitle, which is
2557 # not especially useful as a returnto parameter. Use the title
2558 # from the request instead, if there was one.
2559 $request = $this->getRequest();
2560 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2561 if ( $action == 'edit' ) {
2562 $msg = 'whitelistedittext';
2563 $displayReturnto = $returnto;
2564 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2565 $msg = 'nocreatetext';
2566 } elseif ( $action == 'upload' ) {
2567 $msg = 'uploadnologintext';
2569 $msg = 'loginreqpagetext';
2570 $displayReturnto = Title
::newMainPage();
2576 $query['returnto'] = $returnto->getPrefixedText();
2578 if ( !$request->wasPosted() ) {
2579 $returntoquery = $request->getValues();
2580 unset( $returntoquery['title'] );
2581 unset( $returntoquery['returnto'] );
2582 unset( $returntoquery['returntoquery'] );
2583 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2586 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2587 $loginLink = $linkRenderer->makeKnownLink(
2588 SpecialPage
::getTitleFor( 'Userlogin' ),
2589 $this->msg( 'loginreqlink' )->text(),
2594 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2595 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2597 # Don't return to a page the user can't read otherwise
2598 # we'll end up in a pointless loop
2599 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2600 $this->returnToMain( null, $displayReturnto );
2603 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2604 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2609 * Display an error page indicating that a given version of MediaWiki is
2610 * required to use it
2612 * @param mixed $version The version of MediaWiki needed to use the page
2614 public function versionRequired( $version ) {
2615 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2617 $this->addWikiMsg( 'versionrequiredtext', $version );
2618 $this->returnToMain();
2622 * Format a list of error messages
2624 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2625 * @param string|null $action Action that was denied or null if unknown
2626 * @return string The wikitext error-messages, formatted into a list.
2628 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2629 if ( $action == null ) {
2630 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2632 $action_desc = $this->msg( "action-$action" )->plain();
2634 'permissionserrorstext-withaction',
2637 )->plain() . "\n\n";
2640 if ( count( $errors ) > 1 ) {
2641 $text .= '<ul class="permissions-errors">' . "\n";
2643 foreach ( $errors as $error ) {
2645 $text .= $this->msg( ...$error )->plain();
2650 $text .= "<div class=\"permissions-errors\">\n" .
2651 $this->msg( ...reset( $errors ) )->plain() .
2659 * Show a warning about replica DB lag
2661 * If the lag is higher than $wgSlaveLagCritical seconds,
2662 * then the warning is a bit more obvious. If the lag is
2663 * lower than $wgSlaveLagWarning, then no warning is shown.
2665 * @param int $lag Slave lag
2667 public function showLagWarning( $lag ) {
2668 $config = $this->getConfig();
2669 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2670 $lag = floor( $lag ); // floor to avoid nano seconds to display
2671 $message = $lag < $config->get( 'SlaveLagCritical' )
2674 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2675 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2680 * Output an error page
2682 * @note FatalError exception class provides an alternative.
2683 * @param string $message Error to output. Must be escaped for HTML.
2685 public function showFatalError( $message ) {
2686 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2688 $this->addHTML( $message );
2692 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2694 public function showUnexpectedValueError( $name, $val ) {
2695 wfDeprecated( __METHOD__
, '1.32' );
2696 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2700 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2702 public function showFileCopyError( $old, $new ) {
2703 wfDeprecated( __METHOD__
, '1.32' );
2704 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2708 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2710 public function showFileRenameError( $old, $new ) {
2711 wfDeprecated( __METHOD__
, '1.32' );
2712 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
2716 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2718 public function showFileDeleteError( $name ) {
2719 wfDeprecated( __METHOD__
, '1.32' );
2720 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
2724 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2726 public function showFileNotFoundError( $name ) {
2727 wfDeprecated( __METHOD__
, '1.32' );
2728 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
2732 * Add a "return to" link pointing to a specified title
2734 * @param Title $title Title to link
2735 * @param array $query Query string parameters
2736 * @param string|null $text Text of the link (input is not escaped)
2737 * @param array $options Options array to pass to Linker
2739 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2740 $linkRenderer = MediaWikiServices
::getInstance()
2741 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2742 $link = $this->msg( 'returnto' )->rawParams(
2743 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2744 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2748 * Add a "return to" link pointing to a specified title,
2749 * or the title indicated in the request, or else the main page
2751 * @param mixed|null $unused
2752 * @param Title|string|null $returnto Title or String to return to
2753 * @param string|null $returntoquery Query string for the return to link
2755 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2756 if ( $returnto == null ) {
2757 $returnto = $this->getRequest()->getText( 'returnto' );
2760 if ( $returntoquery == null ) {
2761 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2764 if ( $returnto === '' ) {
2765 $returnto = Title
::newMainPage();
2768 if ( is_object( $returnto ) ) {
2769 $titleObj = $returnto;
2771 $titleObj = Title
::newFromText( $returnto );
2773 // We don't want people to return to external interwiki. That
2774 // might potentially be used as part of a phishing scheme
2775 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2776 $titleObj = Title
::newMainPage();
2779 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2782 private function getRlClientContext() {
2783 if ( !$this->rlClientContext
) {
2784 $query = ResourceLoader
::makeLoaderQuery(
2785 [], // modules; not relevant
2786 $this->getLanguage()->getCode(),
2787 $this->getSkin()->getSkinName(),
2788 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2789 null, // version; not relevant
2790 ResourceLoader
::inDebugMode(),
2791 null, // only; not relevant
2792 $this->isPrintable(),
2793 $this->getRequest()->getBool( 'handheld' )
2795 $this->rlClientContext
= new ResourceLoaderContext(
2796 $this->getResourceLoader(),
2797 new FauxRequest( $query )
2799 if ( $this->contentOverrideCallbacks
) {
2800 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2801 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2802 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2803 $content = call_user_func( $callback, $title );
2804 if ( $content !== null ) {
2812 return $this->rlClientContext
;
2816 * Call this to freeze the module queue and JS config and create a formatter.
2818 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2819 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2820 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2821 * the module filters retroactively. Skins and extension hooks may also add modules until very
2822 * late in the request lifecycle.
2824 * @return ResourceLoaderClientHtml
2826 public function getRlClient() {
2827 if ( !$this->rlClient
) {
2828 $context = $this->getRlClientContext();
2829 $rl = $this->getResourceLoader();
2830 $this->addModules( [
2835 $this->addModuleStyles( [
2840 $this->getSkin()->setupSkinUserCss( $this );
2842 // Prepare exempt modules for buildExemptModules()
2843 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2845 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2847 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2848 // Separate user-specific batch for improved cache-hit ratio.
2849 $userBatch = [ 'user.styles', 'user' ];
2850 $siteBatch = array_diff( $moduleStyles, $userBatch );
2851 $dbr = wfGetDB( DB_REPLICA
);
2852 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2853 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2855 // Filter out modules handled by buildExemptModules()
2856 $moduleStyles = array_filter( $moduleStyles,
2857 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2858 $module = $rl->getModule( $name );
2860 $group = $module->getGroup();
2861 if ( isset( $exemptGroups[$group] ) ) {
2862 $exemptStates[$name] = 'ready';
2863 if ( !$module->isKnownEmpty( $context ) ) {
2864 // E.g. Don't output empty <styles>
2865 $exemptGroups[$group][] = $name;
2873 $this->rlExemptStyleModules
= $exemptGroups;
2875 $rlClient = new ResourceLoaderClientHtml( $context, [
2876 'target' => $this->getTarget(),
2877 'nonce' => $this->getCSPNonce(),
2878 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2879 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2880 // modules enqueud for loading on this page is filtered to just those.
2881 // However, to make sure we also apply the restriction to dynamic dependencies and
2882 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2883 // StartupModule so that the client-side registry will not contain any restricted
2884 // modules either. (T152169, T185303)
2885 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2886 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2889 $rlClient->setConfig( $this->getJSVars() );
2890 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2891 $rlClient->setModuleStyles( $moduleStyles );
2892 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2893 $rlClient->setExemptStates( $exemptStates );
2894 $this->rlClient
= $rlClient;
2896 return $this->rlClient
;
2900 * @param Skin $sk The given Skin
2901 * @param bool $includeStyle Unused
2902 * @return string The doctype, opening "<html>", and head element.
2904 public function headElement( Skin
$sk, $includeStyle = true ) {
2907 $userdir = $this->getLanguage()->getDir();
2908 $sitedir = $wgContLang->getDir();
2911 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2912 $this->getRlClient()->getDocumentAttributes(),
2913 $sk->getHtmlElementAttributes()
2915 $pieces[] = Html
::openElement( 'head' );
2917 if ( $this->getHTMLTitle() == '' ) {
2918 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2921 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2922 // Add <meta charset="UTF-8">
2923 // This should be before <title> since it defines the charset used by
2924 // text including the text inside <title>.
2925 // The spec recommends defining XHTML5's charset using the XML declaration
2927 // Our XML declaration is output by Html::htmlHeader.
2928 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2929 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2930 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2933 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2934 $pieces[] = $this->getRlClient()->getHeadHtml();
2935 $pieces[] = $this->buildExemptModules();
2936 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2937 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2939 // Use an IE conditional comment to serve the script only to old IE
2940 $pieces[] = '<!--[if lt IE 9]>' .
2941 ResourceLoaderClientHtml
::makeLoad(
2942 ResourceLoaderContext
::newDummyContext(),
2944 ResourceLoaderModule
::TYPE_SCRIPTS
,
2946 $this->getCSPNonce()
2950 $pieces[] = Html
::closeElement( 'head' );
2952 $bodyClasses = $this->mAdditionalBodyClasses
;
2953 $bodyClasses[] = 'mediawiki';
2955 # Classes for LTR/RTL directionality support
2956 $bodyClasses[] = $userdir;
2957 $bodyClasses[] = "sitedir-$sitedir";
2959 $underline = $this->getUser()->getOption( 'underline' );
2960 if ( $underline < 2 ) {
2961 // The following classes can be used here:
2962 // * mw-underline-always
2963 // * mw-underline-never
2964 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2967 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2968 # A <body> class is probably not the best way to do this . . .
2969 $bodyClasses[] = 'capitalize-all-nouns';
2972 // Parser feature migration class
2973 // The idea is that this will eventually be removed, after the wikitext
2974 // which requires it is cleaned up.
2975 $bodyClasses[] = 'mw-hide-empty-elt';
2977 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2978 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2980 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2983 // While the implode() is not strictly needed, it's used for backwards compatibility
2984 // (this used to be built as a string and hooks likely still expect that).
2985 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2987 // Allow skins and extensions to add body attributes they need
2988 $sk->addToBodyAttributes( $this, $bodyAttrs );
2989 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2991 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2993 return self
::combineWrappedStrings( $pieces );
2997 * Get a ResourceLoader object associated with this OutputPage
2999 * @return ResourceLoader
3001 public function getResourceLoader() {
3002 if ( is_null( $this->mResourceLoader
) ) {
3003 $this->mResourceLoader
= new ResourceLoader(
3005 LoggerFactory
::getInstance( 'resourceloader' )
3008 return $this->mResourceLoader
;
3012 * Explicily load or embed modules on a page.
3014 * @param array|string $modules One or more module names
3015 * @param string $only ResourceLoaderModule TYPE_ class constant
3016 * @param array $extraQuery [optional] Array with extra query parameters for the request
3017 * @return string|WrappedStringList HTML
3019 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3020 // Apply 'target' and 'origin' filters
3021 $modules = $this->filterModules( (array)$modules, null, $only );
3023 return ResourceLoaderClientHtml
::makeLoad(
3024 $this->getRlClientContext(),
3028 $this->getCSPNonce()
3033 * Combine WrappedString chunks and filter out empty ones
3035 * @param array $chunks
3036 * @return string|WrappedStringList HTML
3038 protected static function combineWrappedStrings( array $chunks ) {
3039 // Filter out empty values
3040 $chunks = array_filter( $chunks, 'strlen' );
3041 return WrappedString
::join( "\n", $chunks );
3045 * JS stuff to put at the bottom of the `<body>`.
3046 * These are legacy scripts ($this->mScripts), and user JS.
3048 * @return string|WrappedStringList HTML
3050 public function getBottomScripts() {
3052 $chunks[] = $this->getRlClient()->getBodyHtml();
3054 // Legacy non-ResourceLoader scripts
3055 $chunks[] = $this->mScripts
;
3057 if ( $this->limitReportJSData
) {
3058 $chunks[] = ResourceLoader
::makeInlineScript(
3059 ResourceLoader
::makeConfigSetScript(
3060 [ 'wgPageParseReport' => $this->limitReportJSData
]
3062 $this->getCSPNonce()
3066 return self
::combineWrappedStrings( $chunks );
3070 * Get the javascript config vars to include on this page
3072 * @return array Array of javascript config vars
3075 public function getJsConfigVars() {
3076 return $this->mJsConfigVars
;
3080 * Add one or more variables to be set in mw.config in JavaScript
3082 * @param string|array $keys Key or array of key/value pairs
3083 * @param mixed|null $value [optional] Value of the configuration variable
3085 public function addJsConfigVars( $keys, $value = null ) {
3086 if ( is_array( $keys ) ) {
3087 foreach ( $keys as $key => $value ) {
3088 $this->mJsConfigVars
[$key] = $value;
3093 $this->mJsConfigVars
[$keys] = $value;
3097 * Get an array containing the variables to be set in mw.config in JavaScript.
3099 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3100 * - in other words, page-independent/site-wide variables (without state).
3101 * You will only be adding bloat to the html page and causing page caches to
3102 * have to be purged on configuration changes.
3105 public function getJSVars() {
3110 $canonicalSpecialPageName = false; # T23115
3112 $title = $this->getTitle();
3113 $ns = $title->getNamespace();
3114 $canonicalNamespace = MWNamespace
::exists( $ns )
3115 ? MWNamespace
::getCanonicalName( $ns )
3116 : $title->getNsText();
3118 $sk = $this->getSkin();
3119 // Get the relevant title so that AJAX features can use the correct page name
3120 // when making API requests from certain special pages (T36972).
3121 $relevantTitle = $sk->getRelevantTitle();
3122 $relevantUser = $sk->getRelevantUser();
3124 if ( $ns == NS_SPECIAL
) {
3125 list( $canonicalSpecialPageName, /*...*/ ) =
3126 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3127 } elseif ( $this->canUseWikiPage() ) {
3128 $wikiPage = $this->getWikiPage();
3129 $curRevisionId = $wikiPage->getLatest();
3130 $articleId = $wikiPage->getId();
3133 $lang = $title->getPageViewLanguage();
3135 // Pre-process information
3136 $separatorTransTable = $lang->separatorTransformTable();
3137 $separatorTransTable = $separatorTransTable ?
: [];
3138 $compactSeparatorTransTable = [
3139 implode( "\t", array_keys( $separatorTransTable ) ),
3140 implode( "\t", $separatorTransTable ),
3142 $digitTransTable = $lang->digitTransformTable();
3143 $digitTransTable = $digitTransTable ?
: [];
3144 $compactDigitTransTable = [
3145 implode( "\t", array_keys( $digitTransTable ) ),
3146 implode( "\t", $digitTransTable ),
3149 $user = $this->getUser();
3152 'wgCanonicalNamespace' => $canonicalNamespace,
3153 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3154 'wgNamespaceNumber' => $title->getNamespace(),
3155 'wgPageName' => $title->getPrefixedDBkey(),
3156 'wgTitle' => $title->getText(),
3157 'wgCurRevisionId' => $curRevisionId,
3158 'wgRevisionId' => (int)$this->getRevisionId(),
3159 'wgArticleId' => $articleId,
3160 'wgIsArticle' => $this->isArticle(),
3161 'wgIsRedirect' => $title->isRedirect(),
3162 'wgAction' => Action
::getActionName( $this->getContext() ),
3163 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3164 'wgUserGroups' => $user->getEffectiveGroups(),
3165 'wgCategories' => $this->getCategories(),
3166 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3167 'wgPageContentLanguage' => $lang->getCode(),
3168 'wgPageContentModel' => $title->getContentModel(),
3169 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3170 'wgDigitTransformTable' => $compactDigitTransTable,
3171 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3172 'wgMonthNames' => $lang->getMonthNamesArray(),
3173 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3174 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3175 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3176 'wgRequestId' => WebRequest
::getRequestId(),
3179 if ( $user->isLoggedIn() ) {
3180 $vars['wgUserId'] = $user->getId();
3181 $vars['wgUserEditCount'] = $user->getEditCount();
3182 $userReg = $user->getRegistration();
3183 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3184 // Get the revision ID of the oldest new message on the user's talk
3185 // page. This can be used for constructing new message alerts on
3187 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3190 if ( $wgContLang->hasVariants() ) {
3191 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3193 // Same test as SkinTemplate
3194 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3195 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3197 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3198 && $relevantTitle->quickUserCan( 'edit', $user )
3199 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3201 foreach ( $title->getRestrictionTypes() as $type ) {
3202 // Following keys are set in $vars:
3203 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3204 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3207 if ( $title->isMainPage() ) {
3208 $vars['wgIsMainPage'] = true;
3211 if ( $this->mRedirectedFrom
) {
3212 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3215 if ( $relevantUser ) {
3216 $vars['wgRelevantUserName'] = $relevantUser->getName();
3219 // Allow extensions to add their custom variables to the mw.config map.
3220 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3221 // page-dependant but site-wide (without state).
3222 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3223 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3225 // Merge in variables from addJsConfigVars last
3226 return array_merge( $vars, $this->getJsConfigVars() );
3230 * To make it harder for someone to slip a user a fake
3231 * JavaScript or CSS preview, a random token
3232 * is associated with the login session. If it's not
3233 * passed back with the preview request, we won't render
3238 public function userCanPreview() {
3239 $request = $this->getRequest();
3241 $request->getVal( 'action' ) !== 'submit' ||
3242 !$request->wasPosted()
3247 $user = $this->getUser();
3249 if ( !$user->isLoggedIn() ) {
3250 // Anons have predictable edit tokens
3253 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3257 $title = $this->getTitle();
3258 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3259 if ( count( $errors ) !== 0 ) {
3267 * @return array Array in format "link name or number => 'link html'".
3269 public function getHeadLinksArray() {
3273 $config = $this->getConfig();
3275 $canonicalUrl = $this->mCanonicalUrl
;
3277 $tags['meta-generator'] = Html
::element( 'meta', [
3278 'name' => 'generator',
3279 'content' => "MediaWiki $wgVersion",
3282 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3283 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3284 // fallbacks should come before the primary value so we need to reverse the array.
3285 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3286 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3287 'name' => 'referrer',
3288 'content' => $policy,
3293 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3294 if ( $p !== 'index,follow' ) {
3295 // http://www.robotstxt.org/wc/meta-user.html
3296 // Only show if it's different from the default robots policy
3297 $tags['meta-robots'] = Html
::element( 'meta', [
3303 foreach ( $this->mMetatags
as $tag ) {
3304 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3306 $tag[0] = substr( $tag[0], 5 );
3307 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3312 $tagName = "meta-{$tag[0]}";
3313 if ( isset( $tags[$tagName] ) ) {
3314 $tagName .= $tag[1];
3316 $tags[$tagName] = Html
::element( 'meta',
3319 'content' => $tag[1]
3324 foreach ( $this->mLinktags
as $tag ) {
3325 $tags[] = Html
::element( 'link', $tag );
3328 # Universal edit button
3329 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3330 $user = $this->getUser();
3331 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3332 && ( $this->getTitle()->exists() ||
3333 $this->getTitle()->quickUserCan( 'create', $user ) )
3335 // Original UniversalEditButton
3336 $msg = $this->msg( 'edit' )->text();
3337 $tags['universal-edit-button'] = Html
::element( 'link', [
3338 'rel' => 'alternate',
3339 'type' => 'application/x-wiki',
3341 'href' => $this->getTitle()->getEditURL(),
3343 // Alternate edit link
3344 $tags['alternative-edit'] = Html
::element( 'link', [
3347 'href' => $this->getTitle()->getEditURL(),
3352 # Generally the order of the favicon and apple-touch-icon links
3353 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3354 # uses whichever one appears later in the HTML source. Make sure
3355 # apple-touch-icon is specified first to avoid this.
3356 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3357 $tags['apple-touch-icon'] = Html
::element( 'link', [
3358 'rel' => 'apple-touch-icon',
3359 'href' => $config->get( 'AppleTouchIcon' )
3363 if ( $config->get( 'Favicon' ) !== false ) {
3364 $tags['favicon'] = Html
::element( 'link', [
3365 'rel' => 'shortcut icon',
3366 'href' => $config->get( 'Favicon' )
3370 # OpenSearch description link
3371 $tags['opensearch'] = Html
::element( 'link', [
3373 'type' => 'application/opensearchdescription+xml',
3374 'href' => wfScript( 'opensearch_desc' ),
3375 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3378 # Real Simple Discovery link, provides auto-discovery information
3379 # for the MediaWiki API (and potentially additional custom API
3380 # support such as WordPress or Twitter-compatible APIs for a
3381 # blogging extension, etc)
3382 $tags['rsd'] = Html
::element( 'link', [
3384 'type' => 'application/rsd+xml',
3385 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3386 // Whether RSD accepts relative or protocol-relative URLs is completely
3387 // undocumented, though.
3388 'href' => wfExpandUrl( wfAppendQuery(
3390 [ 'action' => 'rsd' ] ),
3396 if ( !$config->get( 'DisableLangConversion' ) ) {
3397 $lang = $this->getTitle()->getPageLanguage();
3398 if ( $lang->hasVariants() ) {
3399 $variants = $lang->getVariants();
3400 foreach ( $variants as $variant ) {
3401 $tags["variant-$variant"] = Html
::element( 'link', [
3402 'rel' => 'alternate',
3403 'hreflang' => LanguageCode
::bcp47( $variant ),
3404 'href' => $this->getTitle()->getLocalURL(
3405 [ 'variant' => $variant ] )
3409 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3410 $tags["variant-x-default"] = Html
::element( 'link', [
3411 'rel' => 'alternate',
3412 'hreflang' => 'x-default',
3413 'href' => $this->getTitle()->getLocalURL() ] );
3418 if ( $this->copyrightUrl
!== null ) {
3419 $copyright = $this->copyrightUrl
;
3422 if ( $config->get( 'RightsPage' ) ) {
3423 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3426 $copyright = $copy->getLocalURL();
3430 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3431 $copyright = $config->get( 'RightsUrl' );
3436 $tags['copyright'] = Html
::element( 'link', [
3438 'href' => $copyright ]
3443 if ( $config->get( 'Feed' ) ) {
3446 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3447 # Use the page name for the title. In principle, this could
3448 # lead to issues with having the same name for different feeds
3449 # corresponding to the same page, but we can't avoid that at
3452 $feedLinks[] = $this->feedLink(
3455 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3457 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3462 # Recent changes feed should appear on every page (except recentchanges,
3463 # that would be redundant). Put it after the per-page feed to avoid
3464 # changing existing behavior. It's still available, probably via a
3465 # menu in your browser. Some sites might have a different feed they'd
3466 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3467 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3468 # If so, use it instead.
3469 $sitename = $config->get( 'Sitename' );
3470 if ( $config->get( 'OverrideSiteFeed' ) ) {
3471 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3472 // Note, this->feedLink escapes the url.
3473 $feedLinks[] = $this->feedLink(
3476 $this->msg( "site-{$type}-feed", $sitename )->text()
3479 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3480 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3481 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3482 $feedLinks[] = $this->feedLink(
3484 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3485 # For grep: 'site-rss-feed', 'site-atom-feed'
3486 $this->msg( "site-{$format}-feed", $sitename )->text()
3491 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3492 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3493 # use OutputPage::addFeedLink() instead.
3494 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3496 $tags +
= $feedLinks;
3500 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3501 if ( $canonicalUrl !== false ) {
3502 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3504 if ( $this->isArticleRelated() ) {
3505 // This affects all requests where "setArticleRelated" is true. This is
3506 // typically all requests that show content (query title, curid, oldid, diff),
3507 // and all wikipage actions (edit, delete, purge, info, history etc.).
3508 // It does not apply to File pages and Special pages.
3509 // 'history' and 'info' actions address page metadata rather than the page
3510 // content itself, so they may not be canonicalized to the view page url.
3511 // TODO: this ought to be better encapsulated in the Action class.
3512 $action = Action
::getActionName( $this->getContext() );
3513 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3514 $query = "action={$action}";
3518 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3520 $reqUrl = $this->getRequest()->getRequestURL();
3521 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3525 if ( $canonicalUrl !== false ) {
3526 $tags[] = Html
::element( 'link', [
3527 'rel' => 'canonical',
3528 'href' => $canonicalUrl
3532 // Allow extensions to add, remove and/or otherwise manipulate these links
3533 // If you want only to *add* <head> links, please use the addHeadItem()
3534 // (or addHeadItems() for multiple items) method instead.
3535 // This hook is provided as a last resort for extensions to modify these
3536 // links before the output is sent to client.
3537 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3543 * Generate a "<link rel/>" for a feed.
3545 * @param string $type Feed type
3546 * @param string $url URL to the feed
3547 * @param string $text Value of the "title" attribute
3548 * @return string HTML fragment
3550 private function feedLink( $type, $url, $text ) {
3551 return Html
::element( 'link', [
3552 'rel' => 'alternate',
3553 'type' => "application/$type+xml",
3560 * Add a local or specified stylesheet, with the given media options.
3561 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3563 * @param string $style URL to the file
3564 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3565 * @param string $condition For IE conditional comments, specifying an IE version
3566 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3568 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3571 $options['media'] = $media;
3574 $options['condition'] = $condition;
3577 $options['dir'] = $dir;
3579 $this->styles
[$style] = $options;
3583 * Adds inline CSS styles
3584 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3586 * @param mixed $style_css Inline CSS
3587 * @param string $flip Set to 'flip' to flip the CSS if needed
3589 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3590 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3591 # If wanted, and the interface is right-to-left, flip the CSS
3592 $style_css = CSSJanus
::transform( $style_css, true, false );
3594 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3598 * Build exempt modules and legacy non-ResourceLoader styles.
3600 * @return string|WrappedStringList HTML
3602 protected function buildExemptModules() {
3604 // Things that go after the ResourceLoaderDynamicStyles marker
3607 // We want site, private and user styles to override dynamically added styles from
3608 // general modules, but we want dynamically added styles to override statically added
3609 // style modules. So the order has to be:
3610 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3611 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3612 // - ResourceLoaderDynamicStyles marker
3613 // - site/private/user styles
3615 // Add legacy styles added through addStyle()/addInlineStyle() here
3616 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3618 $chunks[] = Html
::element(
3620 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3623 $separateReq = [ 'site.styles', 'user.styles' ];
3624 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3625 // Combinable modules
3626 $chunks[] = $this->makeResourceLoaderLink(
3627 array_diff( $moduleNames, $separateReq ),
3628 ResourceLoaderModule
::TYPE_STYLES
3631 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3632 // These require their own dedicated request in order to support "@import"
3633 // syntax, which is incompatible with concatenation. (T147667, T37562)
3634 $chunks[] = $this->makeResourceLoaderLink( $name,
3635 ResourceLoaderModule
::TYPE_STYLES
3640 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3646 public function buildCssLinksArray() {
3649 foreach ( $this->styles
as $file => $options ) {
3650 $link = $this->styleLink( $file, $options );
3652 $links[$file] = $link;
3659 * Generate \<link\> tags for stylesheets
3661 * @param string $style URL to the file
3662 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3663 * @return string HTML fragment
3665 protected function styleLink( $style, array $options ) {
3666 if ( isset( $options['dir'] ) ) {
3667 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3672 if ( isset( $options['media'] ) ) {
3673 $media = self
::transformCssMedia( $options['media'] );
3674 if ( is_null( $media ) ) {
3681 if ( substr( $style, 0, 1 ) == '/' ||
3682 substr( $style, 0, 5 ) == 'http:' ||
3683 substr( $style, 0, 6 ) == 'https:' ) {
3686 $config = $this->getConfig();
3687 // Append file hash as query parameter
3688 $url = self
::transformResourcePath(
3690 $config->get( 'StylePath' ) . '/' . $style
3694 $link = Html
::linkedStyle( $url, $media );
3696 if ( isset( $options['condition'] ) ) {
3697 $condition = htmlspecialchars( $options['condition'] );
3698 $link = "<!--[if $condition]>$link<![endif]-->";
3704 * Transform path to web-accessible static resource.
3706 * This is used to add a validation hash as query string.
3707 * This aids various behaviors:
3709 * - Put long Cache-Control max-age headers on responses for improved
3710 * cache performance.
3711 * - Get the correct version of a file as expected by the current page.
3712 * - Instantly get the updated version of a file after deployment.
3714 * Avoid using this for urls included in HTML as otherwise clients may get different
3715 * versions of a resource when navigating the site depending on when the page was cached.
3716 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3717 * an external stylesheet).
3720 * @param Config $config
3721 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3722 * @return string URL
3724 public static function transformResourcePath( Config
$config, $path ) {
3728 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3729 if ( $remotePathPrefix === '' ) {
3730 // The configured base path is required to be empty string for
3731 // wikis in the domain root
3734 $remotePath = $remotePathPrefix;
3736 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3737 // - Path is outside wgResourceBasePath, ignore.
3738 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3741 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3742 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3743 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3744 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3745 $uploadPath = $config->get( 'UploadPath' );
3746 if ( strpos( $path, $uploadPath ) === 0 ) {
3747 $localDir = $config->get( 'UploadDirectory' );
3748 $remotePathPrefix = $remotePath = $uploadPath;
3751 $path = RelPath
::getRelativePath( $path, $remotePath );
3752 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3756 * Utility method for transformResourceFilePath().
3758 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3761 * @param string $remotePathPrefix URL path prefix that points to $localPath
3762 * @param string $localPath File directory exposed at $remotePath
3763 * @param string $file Path to target file relative to $localPath
3764 * @return string URL
3766 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3767 $hash = md5_file( "$localPath/$file" );
3768 if ( $hash === false ) {
3769 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3772 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3776 * Transform "media" attribute based on request parameters
3778 * @param string $media Current value of the "media" attribute
3779 * @return string Modified value of the "media" attribute, or null to skip
3782 public static function transformCssMedia( $media ) {
3785 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3786 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3788 // Switch in on-screen display for media testing
3790 'printable' => 'print',
3791 'handheld' => 'handheld',
3793 foreach ( $switches as $switch => $targetMedia ) {
3794 if ( $wgRequest->getBool( $switch ) ) {
3795 if ( $media == $targetMedia ) {
3797 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3798 /* This regex will not attempt to understand a comma-separated media_query_list
3800 * Example supported values for $media:
3801 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3802 * Example NOT supported value for $media:
3803 * '3d-glasses, screen, print and resolution > 90dpi'
3805 * If it's a print request, we never want any kind of screen stylesheets
3806 * If it's a handheld request (currently the only other choice with a switch),
3807 * we don't want simple 'screen' but we might want screen queries that
3808 * have a max-width or something, so we'll pass all others on and let the
3809 * client do the query.
3811 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3822 * Add a wikitext-formatted message to the output.
3823 * This is equivalent to:
3825 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3827 public function addWikiMsg( /*...*/ ) {
3828 $args = func_get_args();
3829 $name = array_shift( $args );
3830 $this->addWikiMsgArray( $name, $args );
3834 * Add a wikitext-formatted message to the output.
3835 * Like addWikiMsg() except the parameters are taken as an array
3836 * instead of a variable argument list.
3838 * @param string $name
3839 * @param array $args
3841 public function addWikiMsgArray( $name, $args ) {
3842 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3846 * This function takes a number of message/argument specifications, wraps them in
3847 * some overall structure, and then parses the result and adds it to the output.
3849 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3850 * and so on. The subsequent arguments may be either
3851 * 1) strings, in which case they are message names, or
3852 * 2) arrays, in which case, within each array, the first element is the message
3853 * name, and subsequent elements are the parameters to that message.
3855 * Don't use this for messages that are not in the user's interface language.
3859 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3863 * $wgOut->addWikiText( "<div class='error'>\n"
3864 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3866 * The newline after the opening div is needed in some wikitext. See T21226.
3868 * @param string $wrap
3870 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3871 $msgSpecs = func_get_args();
3872 array_shift( $msgSpecs );
3873 $msgSpecs = array_values( $msgSpecs );
3875 foreach ( $msgSpecs as $n => $spec ) {
3876 if ( is_array( $spec ) ) {
3878 $name = array_shift( $args );
3879 if ( isset( $args['options'] ) ) {
3880 unset( $args['options'] );
3882 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3890 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3892 $this->addWikiText( $s );
3896 * Whether the output has a table of contents
3900 public function isTOCEnabled() {
3901 return $this->mEnableTOC
;
3905 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3908 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3910 public function enableSectionEditLinks( $flag = true ) {
3911 wfDeprecated( __METHOD__
, '1.31' );
3917 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3919 public function sectionEditLinksEnabled() {
3920 wfDeprecated( __METHOD__
, '1.31' );
3925 * Helper function to setup the PHP implementation of OOUI to use in this request.
3928 * @param String $skinName The Skin name to determine the correct OOUI theme
3929 * @param String $dir Language direction
3931 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3932 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3933 $theme = $themes[$skinName] ??
$themes['default'];
3934 // For example, 'OOUI\WikimediaUITheme'.
3935 $themeClass = "OOUI\\{$theme}Theme";
3936 OOUI\Theme
::setSingleton( new $themeClass() );
3937 OOUI\Element
::setDefaultDir( $dir );
3941 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3942 * MediaWiki and this OutputPage instance.
3946 public function enableOOUI() {
3948 strtolower( $this->getSkin()->getSkinName() ),
3949 $this->getLanguage()->getDir()
3951 $this->addModuleStyles( [
3952 'oojs-ui-core.styles',
3953 'oojs-ui.styles.indicators',
3954 'oojs-ui.styles.textures',
3955 'mediawiki.widgets.styles',
3956 'oojs-ui.styles.icons-content',
3957 'oojs-ui.styles.icons-alerts',
3958 'oojs-ui.styles.icons-interactions',
3963 * Add Link headers for preloading the wiki's logo.
3967 protected function addLogoPreloadLinkHeaders() {
3968 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3974 if ( !is_array( $logo ) ) {
3975 // No media queries required if we only have one variant
3976 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3980 if ( isset( $logo['svg'] ) ) {
3981 // No media queries required if we only have a 1x and svg variant
3982 // because all preload-capable browsers support SVGs
3983 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3987 foreach ( $logo as $dppx => $src ) {
3988 // Keys are in this format: "1.5x"
3989 $dppx = substr( $dppx, 0, -1 );
3990 $logosPerDppx[$dppx] = $src;
3993 // Because PHP can't have floats as array keys
3994 uksort( $logosPerDppx, function ( $a , $b ) {
3995 $a = floatval( $a );
3996 $b = floatval( $b );
3997 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
4001 foreach ( $logosPerDppx as $dppx => $src ) {
4002 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
4005 $logosCount = count( $logos );
4006 // Logic must match ResourceLoaderSkinModule:
4007 // - 1x applies to resolution < 1.5dppx
4008 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
4009 // - 2x applies to resolution >= 2dppx
4010 // Note that min-resolution and max-resolution are both inclusive.
4011 for ( $i = 0; $i < $logosCount; $i++
) {
4014 // min-resolution is ">=" (larger than or equal to)
4015 // "not min-resolution" is essentially "<"
4016 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4017 } elseif ( $i !== $logosCount - 1 ) {
4019 // Media query expressions can only apply "not" to the entire expression
4020 // (e.g. can't express ">= 1.5 and not >= 2).
4021 // Workaround: Use <= 1.9999 in place of < 2.
4022 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
4023 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4024 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4027 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4030 $this->addLinkHeader(
4031 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
4037 * Get (and set if not yet set) the CSP nonce.
4039 * This value needs to be included in any <script> tags on the
4042 * @return string|bool Nonce or false to mean don't output nonce
4045 public function getCSPNonce() {
4046 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4049 if ( $this->CSPNonce
=== null ) {
4050 // XXX It might be expensive to generate randomness
4051 // on every request, on Windows.
4052 $rand = random_bytes( 15 );
4053 $this->CSPNonce
= base64_encode( $rand );
4055 return $this->CSPNonce
;