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 Should be private - has getter and setter. Contains
60 public $mPagetitle = '';
63 * @var string Contains all of the "<body>" content. Should be private we
64 * got set/get accessors and the append() method.
66 public $mBodytext = '';
68 /** @var string Stores contents of "<title>" tag */
69 private $mHTMLtitle = '';
72 * @var bool Is the displayed content related to the source of the
73 * corresponding wiki article.
75 private $mIsarticle = false;
77 /** @var bool Stores "article flag" toggle. */
78 private $mIsArticleRelated = true;
81 * @var bool We have to set isPrintable(). Some pages should
82 * never be printed (ex: redirections).
84 private $mPrintable = false;
87 * @var array Contains the page subtitle. Special pages usually have some
88 * links here. Don't confuse with site subtitle added by skins.
90 private $mSubtitle = [];
93 public $mRedirect = '';
96 protected $mStatusCode;
99 * @var string Used for sending cache control.
100 * The whole caching system should probably be moved into its own class.
102 protected $mLastModified = '';
105 protected $mCategoryLinks = [];
108 protected $mCategories = [
114 protected $mIndicators = [];
116 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
117 private $mLanguageLinks = [];
120 * Used for JavaScript (predates ResourceLoader)
121 * @todo We should split JS / CSS.
122 * mScripts content is inserted as is in "<head>" by Skin. This might
123 * contain either a link to a stylesheet or inline CSS.
125 private $mScripts = '';
127 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
128 protected $mInlineStyles = '';
131 * @var string Used by skin template.
132 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
134 public $mPageLinkTitle = '';
136 /** @var array Array of elements in "<head>". Parser might add its own headers! */
137 protected $mHeadItems = [];
139 /** @var array Additional <body> classes; there are also <body> classes from other sources */
140 protected $mAdditionalBodyClasses = [];
143 protected $mModules = [];
146 protected $mModuleScripts = [];
149 protected $mModuleStyles = [];
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
154 /** @var ResourceLoaderClientHtml */
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
161 private $rlExemptStyleModules;
164 protected $mJsConfigVars = [];
167 protected $mTemplateIds = [];
170 protected $mImageTimeKeys = [];
173 public $mRedirectCode = '';
175 protected $mFeedLinksAppendQuery = null;
178 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
179 * @see ResourceLoaderModule::$origin
180 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
182 protected $mAllowedModules = [
183 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
186 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
187 protected $mDoNothing = false;
192 protected $mContainsNewMagic = 0;
195 * lazy initialised, use parserOptions()
198 protected $mParserOptions = null;
201 * Handles the Atom / RSS links.
202 * We probably only support Atom in 2011.
203 * @see $wgAdvertisedFeedTypes
205 private $mFeedLinks = [];
207 // Gwicke work on squid caching? Roughly from 2003.
208 protected $mEnableClientCache = true;
210 /** @var bool Flag if output should only contain the body of the article. */
211 private $mArticleBodyOnly = false;
214 protected $mNewSectionLink = false;
217 protected $mHideNewSectionLink = false;
220 * @var bool Comes from the parser. This was probably made to load CSS/JS
221 * only if we had "<gallery>". Used directly in CategoryPage.php.
222 * Looks like ResourceLoader can replace this.
224 public $mNoGallery = false;
227 private $mPageTitleActionText = '';
229 /** @var int Cache stuff. Looks like mEnableClientCache */
230 protected $mCdnMaxage = 0;
231 /** @var int Upper limit on mCdnMaxage */
232 protected $mCdnMaxageLimit = INF
;
235 * @var bool Controls if anti-clickjacking / frame-breaking headers will
236 * be sent. This should be done for pages where edit actions are possible.
237 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
239 protected $mPreventClickjacking = true;
241 /** @var int To include the variable {{REVISIONID}} */
242 private $mRevisionId = null;
245 private $mRevisionTimestamp = null;
248 protected $mFileVersion = null;
251 * @var array An array of stylesheet filenames (relative from skins path),
252 * with options for CSS media, IE conditions, and RTL/LTR direction.
253 * For internal use; add settings in the skin via $this->addStyle()
255 * Style again! This seems like a code duplication since we already have
256 * mStyles. This is what makes Open Source amazing.
258 protected $styles = [];
260 private $mIndexPolicy = 'index';
261 private $mFollowPolicy = 'follow';
262 private $mVaryHeader = [
263 'Accept-Encoding' => [ 'match=gzip' ],
267 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
272 private $mRedirectedFrom = null;
275 * Additional key => value data
277 private $mProperties = [];
280 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
282 private $mTarget = null;
285 * @var bool Whether parser output contains a table of contents
287 private $mEnableTOC = false;
290 * @var string|null The URL to send in a <link> element with rel=license
292 private $copyrightUrl;
294 /** @var array Profiling data */
295 private $limitReportJSData = [];
297 /** @var array Map Title to Content */
298 private $contentOverrides = [];
300 /** @var callable[] */
301 private $contentOverrideCallbacks = [];
304 * Link: header contents
306 private $mLinkHeader = [];
309 * @var string The nonce for Content-Security-Policy
314 * Constructor for OutputPage. This should not be called directly.
315 * Instead a new RequestContext should be created and it will implicitly create
316 * a OutputPage tied to that context.
317 * @param IContextSource $context
319 function __construct( IContextSource
$context ) {
320 $this->setContext( $context );
324 * Redirect to $url rather than displaying the normal page
327 * @param string $responsecode HTTP status code
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect
= str_replace( "\n", '', $url );
332 $this->mRedirectCode
= $responsecode;
336 * Get the URL to redirect to, or an empty string if not redirect URL set
340 public function getRedirect() {
341 return $this->mRedirect
;
345 * Set the copyright URL to send with the output.
346 * Empty string to omit, null to reset.
350 * @param string|null $url
352 public function setCopyrightUrl( $url ) {
353 $this->copyrightUrl
= $url;
357 * Set the HTTP status code to send with the output.
359 * @param int $statusCode
361 public function setStatusCode( $statusCode ) {
362 $this->mStatusCode
= $statusCode;
366 * Add a new "<meta>" tag
367 * To add an http-equiv meta tag, precede the name with "http:"
369 * @param string $name Name of the meta tag
370 * @param string $val Value of the meta tag
372 function addMeta( $name, $val ) {
373 array_push( $this->mMetatags
, [ $name, $val ] );
377 * Returns the current <meta> tags
382 public function getMetaTags() {
383 return $this->mMetatags
;
387 * Add a new \<link\> tag to the page header.
389 * Note: use setCanonicalUrl() for rel=canonical.
391 * @param array $linkarr Associative array of attributes.
393 function addLink( array $linkarr ) {
394 array_push( $this->mLinktags
, $linkarr );
398 * Returns the current <link> tags
403 public function getLinkTags() {
404 return $this->mLinktags
;
408 * Add a new \<link\> with "rel" attribute set to "meta"
410 * @param array $linkarr Associative array mapping attribute names to their
411 * values, both keys and values will be escaped, and the
412 * "rel" attribute will be automatically added
414 function addMetadataLink( array $linkarr ) {
415 $linkarr['rel'] = $this->getMetadataAttribute();
416 $this->addLink( $linkarr );
420 * Set the URL to be used for the <link rel=canonical>. This should be used
421 * in preference to addLink(), to avoid duplicate link tags.
424 function setCanonicalUrl( $url ) {
425 $this->mCanonicalUrl
= $url;
429 * Returns the URL to be used for the <link rel=canonical> if
433 * @return bool|string
435 public function getCanonicalUrl() {
436 return $this->mCanonicalUrl
;
440 * Get the value of the "rel" attribute for metadata links
444 public function getMetadataAttribute() {
445 # note: buggy CC software only reads first "meta" link
446 static $haveMeta = false;
448 return 'alternate meta';
456 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
457 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
460 * @param string $script Raw HTML
462 function addScript( $script ) {
463 $this->mScripts
.= $script;
467 * Add a JavaScript file to be loaded as `<script>` on this page.
469 * Internal use only. Use OutputPage::addModules() if possible.
471 * @param string $file URL to file (absolute path, protocol-relative, or full url)
472 * @param string|null $unused Previously used to change the cache-busting query parameter
474 public function addScriptFile( $file, $unused = null ) {
475 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
476 // This is not an absolute path, protocol-relative url, or full scheme url,
477 // presumed to be an old call intended to include a file from /w/skins/common,
478 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
479 wfDeprecated( __METHOD__
, '1.24' );
482 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
486 * Add a self-contained script tag with the given contents
487 * Internal use only. Use OutputPage::addModules() if possible.
489 * @param string $script JavaScript text, no script tags
491 public function addInlineScript( $script ) {
492 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
496 * Filter an array of modules to remove insufficiently trustworthy members, and modules
497 * which are no longer registered (eg a page is cached before an extension is disabled)
498 * @param array $modules
499 * @param string|null $position Unused
500 * @param string $type
503 protected function filterModules( array $modules, $position = null,
504 $type = ResourceLoaderModule
::TYPE_COMBINED
506 $resourceLoader = $this->getResourceLoader();
507 $filteredModules = [];
508 foreach ( $modules as $val ) {
509 $module = $resourceLoader->getModule( $val );
510 if ( $module instanceof ResourceLoaderModule
511 && $module->getOrigin() <= $this->getAllowedModules( $type )
513 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
514 $this->warnModuleTargetFilter( $module->getName() );
517 $filteredModules[] = $val;
520 return $filteredModules;
523 private function warnModuleTargetFilter( $moduleName ) {
524 static $warnings = [];
525 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
528 $warnings[$this->mTarget
][$moduleName] = true;
529 $this->getResourceLoader()->getLogger()->debug(
530 'Module "{module}" not loadable on target "{target}".',
532 'module' => $moduleName,
533 'target' => $this->mTarget
,
539 * Get the list of modules to include on this page
541 * @param bool $filter Whether to filter out insufficiently trustworthy modules
542 * @param string|null $position Unused
543 * @param string $param
544 * @param string $type
545 * @return array Array of module names
547 public function getModules( $filter = false, $position = null, $param = 'mModules',
548 $type = ResourceLoaderModule
::TYPE_COMBINED
550 $modules = array_values( array_unique( $this->$param ) );
552 ?
$this->filterModules( $modules, null, $type )
557 * Load one or more ResourceLoader modules on this page.
559 * @param string|array $modules Module name (string) or array of module names
561 public function addModules( $modules ) {
562 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
566 * Get the list of script-only modules to load on this page.
568 * @param bool $filter
569 * @param string|null $position Unused
570 * @return array Array of module names
572 public function getModuleScripts( $filter = false, $position = null ) {
573 return $this->getModules( $filter, null, 'mModuleScripts',
574 ResourceLoaderModule
::TYPE_SCRIPTS
579 * Load the scripts of one or more ResourceLoader modules, on this page.
581 * This method exists purely to provide the legacy behaviour of loading
582 * a module's scripts in the global scope, and without dependency resolution.
583 * See <https://phabricator.wikimedia.org/T188689>.
585 * @deprecated since 1.31 Use addModules() instead.
586 * @param string|array $modules Module name (string) or array of module names
588 public function addModuleScripts( $modules ) {
589 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
593 * Get the list of style-only modules to load on this page.
595 * @param bool $filter
596 * @param string|null $position Unused
597 * @return array Array of module names
599 public function getModuleStyles( $filter = false, $position = null ) {
600 return $this->getModules( $filter, null, 'mModuleStyles',
601 ResourceLoaderModule
::TYPE_STYLES
606 * Load the styles of one or more ResourceLoader modules on this page.
608 * Module styles added through this function will be loaded as a stylesheet,
609 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
610 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
612 * @param string|array $modules Module name (string) or array of module names
614 public function addModuleStyles( $modules ) {
615 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
619 * @return null|string ResourceLoader target
621 public function getTarget() {
622 return $this->mTarget
;
626 * Sets ResourceLoader target for load.php links. If null, will be omitted
628 * @param string|null $target
630 public function setTarget( $target ) {
631 $this->mTarget
= $target;
635 * Add a mapping from a LinkTarget to a Content, for things like page preview.
636 * @see self::addContentOverrideCallback()
638 * @param LinkTarget $target
639 * @param Content $content
641 public function addContentOverride( LinkTarget
$target, Content
$content ) {
642 if ( !$this->contentOverrides
) {
643 // Register a callback for $this->contentOverrides on the first call
644 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
645 $key = $target->getNamespace() . ':' . $target->getDBkey();
646 return $this->contentOverrides
[$key] ??
null;
650 $key = $target->getNamespace() . ':' . $target->getDBkey();
651 $this->contentOverrides
[$key] = $content;
655 * Add a callback for mapping from a Title to a Content object, for things
657 * @see ResourceLoaderContext::getContentOverrideCallback()
659 * @param callable $callback
661 public function addContentOverrideCallback( callable
$callback ) {
662 $this->contentOverrideCallbacks
[] = $callback;
666 * Get an array of head items
670 function getHeadItemsArray() {
671 return $this->mHeadItems
;
675 * Add or replace a head item to the output
677 * Whenever possible, use more specific options like ResourceLoader modules,
678 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
679 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
680 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
681 * This would be your very LAST fallback.
683 * @param string $name Item name
684 * @param string $value Raw HTML
686 public function addHeadItem( $name, $value ) {
687 $this->mHeadItems
[$name] = $value;
691 * Add one or more head items to the output
694 * @param string|string[] $values Raw HTML
696 public function addHeadItems( $values ) {
697 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
701 * Check if the header item $name is already set
703 * @param string $name Item name
706 public function hasHeadItem( $name ) {
707 return isset( $this->mHeadItems
[$name] );
711 * Add a class to the <body> element
714 * @param string|string[] $classes One or more classes to add
716 public function addBodyClasses( $classes ) {
717 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
721 * Set whether the output should only contain the body of the article,
722 * without any skin, sidebar, etc.
723 * Used e.g. when calling with "action=render".
725 * @param bool $only Whether to output only the body of the article
727 public function setArticleBodyOnly( $only ) {
728 $this->mArticleBodyOnly
= $only;
732 * Return whether the output will contain only the body of the article
736 public function getArticleBodyOnly() {
737 return $this->mArticleBodyOnly
;
741 * Set an additional output property
744 * @param string $name
745 * @param mixed $value
747 public function setProperty( $name, $value ) {
748 $this->mProperties
[$name] = $value;
752 * Get an additional output property
755 * @param string $name
756 * @return mixed Property value or null if not found
758 public function getProperty( $name ) {
759 return $this->mProperties
[$name] ??
null;
763 * checkLastModified tells the client to use the client-cached page if
764 * possible. If successful, the OutputPage is disabled so that
765 * any future call to OutputPage->output() have no effect.
767 * Side effect: sets mLastModified for Last-Modified header
769 * @param string $timestamp
771 * @return bool True if cache-ok headers was sent.
773 public function checkLastModified( $timestamp ) {
774 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
775 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
778 $config = $this->getConfig();
779 if ( !$config->get( 'CachePages' ) ) {
780 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
784 $timestamp = wfTimestamp( TS_MW
, $timestamp );
786 'page' => $timestamp,
787 'user' => $this->getUser()->getTouched(),
788 'epoch' => $config->get( 'CacheEpoch' )
790 if ( $config->get( 'UseSquid' ) ) {
791 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
793 $config->get( 'SquidMaxage' )
796 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
798 $maxModified = max( $modifiedTimes );
799 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
801 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
802 if ( $clientHeader === false ) {
803 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
807 # IE sends sizes after the date like this:
808 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
809 # this breaks strtotime().
810 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
812 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
813 $clientHeaderTime = strtotime( $clientHeader );
814 Wikimedia\restoreWarnings
();
815 if ( !$clientHeaderTime ) {
817 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
820 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
824 foreach ( $modifiedTimes as $name => $value ) {
825 if ( $info !== '' ) {
828 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
831 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
832 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
833 wfDebug( __METHOD__
. ": effective Last-Modified: " .
834 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
835 if ( $clientHeaderTime < $maxModified ) {
836 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
841 # Give a 304 Not Modified response code and disable body output
842 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
843 ini_set( 'zlib.output_compression', 0 );
844 $this->getRequest()->response()->statusHeader( 304 );
845 $this->sendCacheControl();
848 // Don't output a compressed blob when using ob_gzhandler;
849 // it's technically against HTTP spec and seems to confuse
850 // Firefox when the response gets split over two packets.
851 wfClearOutputBuffers();
857 * @param int $reqTime Time of request (eg. now)
858 * @param int $maxAge Cache TTL in seconds
859 * @return int Timestamp
861 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
862 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
863 // because even if the wiki page content hasn't changed since, static
864 // resources may have changed (skin HTML, interface messages, urls, etc.)
865 // and must roll-over in a timely manner (T46570)
866 return $reqTime - $maxAge;
870 * Override the last modified timestamp
872 * @param string $timestamp New timestamp, in a format readable by
875 public function setLastModified( $timestamp ) {
876 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
880 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
882 * @param string $policy The literal string to output as the contents of
883 * the meta tag. Will be parsed according to the spec and output in
887 public function setRobotPolicy( $policy ) {
888 $policy = Article
::formatRobotPolicy( $policy );
890 if ( isset( $policy['index'] ) ) {
891 $this->setIndexPolicy( $policy['index'] );
893 if ( isset( $policy['follow'] ) ) {
894 $this->setFollowPolicy( $policy['follow'] );
899 * Set the index policy for the page, but leave the follow policy un-
902 * @param string $policy Either 'index' or 'noindex'.
905 public function setIndexPolicy( $policy ) {
906 $policy = trim( $policy );
907 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
908 $this->mIndexPolicy
= $policy;
913 * Set the follow policy for the page, but leave the index policy un-
916 * @param string $policy Either 'follow' or 'nofollow'.
919 public function setFollowPolicy( $policy ) {
920 $policy = trim( $policy );
921 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
922 $this->mFollowPolicy
= $policy;
927 * Set the new value of the "action text", this will be added to the
928 * "HTML title", separated from it with " - ".
930 * @param string $text New value of the "action text"
932 public function setPageTitleActionText( $text ) {
933 $this->mPageTitleActionText
= $text;
937 * Get the value of the "action text"
941 public function getPageTitleActionText() {
942 return $this->mPageTitleActionText
;
946 * "HTML title" means the contents of "<title>".
947 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
949 * @param string|Message $name
951 public function setHTMLTitle( $name ) {
952 if ( $name instanceof Message
) {
953 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
955 $this->mHTMLtitle
= $name;
960 * Return the "HTML title", i.e. the content of the "<title>" tag.
964 public function getHTMLTitle() {
965 return $this->mHTMLtitle
;
969 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
973 public function setRedirectedFrom( $t ) {
974 $this->mRedirectedFrom
= $t;
978 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
979 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
980 * but not bad tags like \<script\>. This function automatically sets
981 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
982 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
983 * good tags like \<i\> will be dropped entirely.
985 * @param string|Message $name
987 public function setPageTitle( $name ) {
988 if ( $name instanceof Message
) {
989 $name = $name->setContext( $this->getContext() )->text();
992 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
993 # but leave "<i>foobar</i>" alone
994 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
995 $this->mPagetitle
= $nameWithTags;
997 # change "<i>foo&bar</i>" to "foo&bar"
999 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
1000 ->inContentLanguage()
1005 * Return the "page title", i.e. the content of the \<h1\> tag.
1009 public function getPageTitle() {
1010 return $this->mPagetitle
;
1014 * Set the Title object to use
1018 public function setTitle( Title
$t ) {
1019 $this->getContext()->setTitle( $t );
1023 * Replace the subtitle with $str
1025 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1027 public function setSubtitle( $str ) {
1028 $this->clearSubtitle();
1029 $this->addSubtitle( $str );
1033 * Add $str to the subtitle
1035 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1037 public function addSubtitle( $str ) {
1038 if ( $str instanceof Message
) {
1039 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1041 $this->mSubtitle
[] = $str;
1046 * Build message object for a subtitle containing a backlink to a page
1048 * @param Title $title Title to link to
1049 * @param array $query Array of additional parameters to include in the link
1053 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1054 if ( $title->isRedirect() ) {
1055 $query['redirect'] = 'no';
1057 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1058 return wfMessage( 'backlinksubtitle' )
1059 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1063 * Add a subtitle containing a backlink to a page
1065 * @param Title $title Title to link to
1066 * @param array $query Array of additional parameters to include in the link
1068 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1069 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1073 * Clear the subtitles
1075 public function clearSubtitle() {
1076 $this->mSubtitle
= [];
1084 public function getSubtitle() {
1085 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1089 * Set the page as printable, i.e. it'll be displayed with all
1090 * print styles included
1092 public function setPrintable() {
1093 $this->mPrintable
= true;
1097 * Return whether the page is "printable"
1101 public function isPrintable() {
1102 return $this->mPrintable
;
1106 * Disable output completely, i.e. calling output() will have no effect
1108 public function disable() {
1109 $this->mDoNothing
= true;
1113 * Return whether the output will be completely disabled
1117 public function isDisabled() {
1118 return $this->mDoNothing
;
1122 * Show an "add new section" link?
1126 public function showNewSectionLink() {
1127 return $this->mNewSectionLink
;
1131 * Forcibly hide the new section link?
1135 public function forceHideNewSectionLink() {
1136 return $this->mHideNewSectionLink
;
1140 * Add or remove feed links in the page header
1141 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1142 * for the new version
1143 * @see addFeedLink()
1145 * @param bool $show True: add default feeds, false: remove all feeds
1147 public function setSyndicated( $show = true ) {
1149 $this->setFeedAppendQuery( false );
1151 $this->mFeedLinks
= [];
1156 * Add default feeds to the page header
1157 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1158 * for the new version
1159 * @see addFeedLink()
1161 * @param string $val Query to append to feed links or false to output
1164 public function setFeedAppendQuery( $val ) {
1165 $this->mFeedLinks
= [];
1167 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1168 $query = "feed=$type";
1169 if ( is_string( $val ) ) {
1170 $query .= '&' . $val;
1172 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1177 * Add a feed link to the page header
1179 * @param string $format Feed type, should be a key of $wgFeedClasses
1180 * @param string $href URL
1182 public function addFeedLink( $format, $href ) {
1183 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1184 $this->mFeedLinks
[$format] = $href;
1189 * Should we output feed links for this page?
1192 public function isSyndicated() {
1193 return count( $this->mFeedLinks
) > 0;
1197 * Return URLs for each supported syndication format for this page.
1198 * @return array Associating format keys with URLs
1200 public function getSyndicationLinks() {
1201 return $this->mFeedLinks
;
1205 * Will currently always return null
1209 public function getFeedAppendQuery() {
1210 return $this->mFeedLinksAppendQuery
;
1214 * Set whether the displayed content is related to the source of the
1215 * corresponding article on the wiki
1216 * Setting true will cause the change "article related" toggle to true
1220 public function setArticleFlag( $v ) {
1221 $this->mIsarticle
= $v;
1223 $this->mIsArticleRelated
= $v;
1228 * Return whether the content displayed page is related to the source of
1229 * the corresponding article on the wiki
1233 public function isArticle() {
1234 return $this->mIsarticle
;
1238 * Set whether this page is related an article on the wiki
1239 * Setting false will cause the change of "article flag" toggle to false
1243 public function setArticleRelated( $v ) {
1244 $this->mIsArticleRelated
= $v;
1246 $this->mIsarticle
= false;
1251 * Return whether this page is related an article on the wiki
1255 public function isArticleRelated() {
1256 return $this->mIsArticleRelated
;
1260 * Add new language links
1262 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1263 * (e.g. 'fr:Test page')
1265 public function addLanguageLinks( array $newLinkArray ) {
1266 $this->mLanguageLinks +
= $newLinkArray;
1270 * Reset the language links and add new language links
1272 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1273 * (e.g. 'fr:Test page')
1275 public function setLanguageLinks( array $newLinkArray ) {
1276 $this->mLanguageLinks
= $newLinkArray;
1280 * Get the list of language links
1282 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1284 public function getLanguageLinks() {
1285 return $this->mLanguageLinks
;
1289 * Add an array of categories, with names in the keys
1291 * @param array $categories Mapping category name => sort key
1293 public function addCategoryLinks( array $categories ) {
1296 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1300 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1302 # Set all the values to 'normal'.
1303 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1305 # Mark hidden categories
1306 foreach ( $res as $row ) {
1307 if ( isset( $row->pp_value
) ) {
1308 $categories[$row->page_title
] = 'hidden';
1312 // Avoid PHP 7.1 warning of passing $this by reference
1313 $outputPage = $this;
1314 # Add the remaining categories to the skin
1316 'OutputPageMakeCategoryLinks',
1317 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1319 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1320 foreach ( $categories as $category => $type ) {
1321 // array keys will cast numeric category names to ints, so cast back to string
1322 $category = (string)$category;
1323 $origcategory = $category;
1324 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1328 $wgContLang->findVariantLink( $category, $title, true );
1329 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1332 $text = $wgContLang->convertHtml( $title->getText() );
1333 $this->mCategories
[$type][] = $title->getText();
1334 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1340 * @param array $categories
1341 * @return bool|IResultWrapper
1343 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1344 # Add the links to a LinkBatch
1345 $arr = [ NS_CATEGORY
=> $categories ];
1346 $lb = new LinkBatch
;
1347 $lb->setArray( $arr );
1349 # Fetch existence plus the hiddencat property
1350 $dbr = wfGetDB( DB_REPLICA
);
1351 $fields = array_merge(
1352 LinkCache
::getSelectFields(),
1353 [ 'page_namespace', 'page_title', 'pp_value' ]
1356 $res = $dbr->select( [ 'page', 'page_props' ],
1358 $lb->constructSet( 'page', $dbr ),
1361 [ 'page_props' => [ 'LEFT JOIN', [
1362 'pp_propname' => 'hiddencat',
1367 # Add the results to the link cache
1368 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1369 $lb->addResultToCache( $linkCache, $res );
1375 * Reset the category links (but not the category list) and add $categories
1377 * @param array $categories Mapping category name => sort key
1379 public function setCategoryLinks( array $categories ) {
1380 $this->mCategoryLinks
= [];
1381 $this->addCategoryLinks( $categories );
1385 * Get the list of category links, in a 2-D array with the following format:
1386 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1387 * hidden categories) and $link a HTML fragment with a link to the category
1392 public function getCategoryLinks() {
1393 return $this->mCategoryLinks
;
1397 * Get the list of category names this page belongs to.
1399 * @param string $type The type of categories which should be returned. Possible values:
1400 * * all: all categories of all types
1401 * * hidden: only the hidden categories
1402 * * normal: all categories, except hidden categories
1403 * @return array Array of strings
1405 public function getCategories( $type = 'all' ) {
1406 if ( $type === 'all' ) {
1407 $allCategories = [];
1408 foreach ( $this->mCategories
as $categories ) {
1409 $allCategories = array_merge( $allCategories, $categories );
1411 return $allCategories;
1413 if ( !isset( $this->mCategories
[$type] ) ) {
1414 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1416 return $this->mCategories
[$type];
1420 * Add an array of indicators, with their identifiers as array
1421 * keys and HTML contents as values.
1423 * In case of duplicate keys, existing values are overwritten.
1425 * @param array $indicators
1428 public function setIndicators( array $indicators ) {
1429 $this->mIndicators
= $indicators +
$this->mIndicators
;
1430 // Keep ordered by key
1431 ksort( $this->mIndicators
);
1435 * Get the indicators associated with this page.
1437 * The array will be internally ordered by item keys.
1439 * @return array Keys: identifiers, values: HTML contents
1442 public function getIndicators() {
1443 return $this->mIndicators
;
1447 * Adds help link with an icon via page indicators.
1448 * Link target can be overridden by a local message containing a wikilink:
1449 * the message key is: lowercase action or special page name + '-helppage'.
1450 * @param string $to Target MediaWiki.org page title or encoded URL.
1451 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1454 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1455 $this->addModuleStyles( 'mediawiki.helplink' );
1456 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1458 if ( $overrideBaseUrl ) {
1461 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1462 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1465 $link = Html
::rawElement(
1469 'target' => '_blank',
1470 'class' => 'mw-helplink',
1475 $this->setIndicators( [ 'mw-helplink' => $link ] );
1479 * Do not allow scripts which can be modified by wiki users to load on this page;
1480 * only allow scripts bundled with, or generated by, the software.
1481 * Site-wide styles are controlled by a config setting, since they can be
1482 * used to create a custom skin/theme, but not user-specific ones.
1484 * @todo this should be given a more accurate name
1486 public function disallowUserJs() {
1487 $this->reduceAllowedModules(
1488 ResourceLoaderModule
::TYPE_SCRIPTS
,
1489 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1492 // Site-wide styles are controlled by a config setting, see T73621
1493 // for background on why. User styles are never allowed.
1494 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1495 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1497 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1499 $this->reduceAllowedModules(
1500 ResourceLoaderModule
::TYPE_STYLES
,
1506 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1507 * @see ResourceLoaderModule::$origin
1508 * @param string $type ResourceLoaderModule TYPE_ constant
1509 * @return int ResourceLoaderModule ORIGIN_ class constant
1511 public function getAllowedModules( $type ) {
1512 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1513 return min( array_values( $this->mAllowedModules
) );
1515 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1520 * Limit the highest level of CSS/JS untrustworthiness allowed.
1522 * If passed the same or a higher level than the current level of untrustworthiness set, the
1523 * level will remain unchanged.
1525 * @param string $type
1526 * @param int $level ResourceLoaderModule class constant
1528 public function reduceAllowedModules( $type, $level ) {
1529 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1533 * Prepend $text to the body HTML
1535 * @param string $text HTML
1537 public function prependHTML( $text ) {
1538 $this->mBodytext
= $text . $this->mBodytext
;
1542 * Append $text to the body HTML
1544 * @param string $text HTML
1546 public function addHTML( $text ) {
1547 $this->mBodytext
.= $text;
1551 * Shortcut for adding an Html::element via addHTML.
1555 * @param string $element
1556 * @param array $attribs
1557 * @param string $contents
1559 public function addElement( $element, array $attribs = [], $contents = '' ) {
1560 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1564 * Clear the body HTML
1566 public function clearHTML() {
1567 $this->mBodytext
= '';
1573 * @return string HTML
1575 public function getHTML() {
1576 return $this->mBodytext
;
1580 * Get/set the ParserOptions object to use for wikitext parsing
1582 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1583 * current ParserOption object. This parameter is deprecated since 1.31.
1584 * @return ParserOptions
1586 public function parserOptions( $options = null ) {
1587 if ( $options !== null ) {
1588 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1591 if ( $options !== null && !empty( $options->isBogus
) ) {
1592 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1593 // been changed somehow, and keep it if so.
1594 $anonPO = ParserOptions
::newFromAnon();
1595 $anonPO->setAllowUnsafeRawHtml( false );
1596 if ( !$options->matches( $anonPO ) ) {
1597 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1598 $options->isBogus
= false;
1602 if ( !$this->mParserOptions
) {
1603 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1604 // $wgUser isn't unstubbable yet, so don't try to get a
1605 // ParserOptions for it. And don't cache this ParserOptions
1607 $po = ParserOptions
::newFromAnon();
1608 $po->setAllowUnsafeRawHtml( false );
1609 $po->isBogus
= true;
1610 if ( $options !== null ) {
1611 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1616 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1617 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1620 if ( $options !== null && !empty( $options->isBogus
) ) {
1621 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1623 return wfSetVar( $this->mParserOptions
, null, true );
1625 return wfSetVar( $this->mParserOptions
, $options );
1630 * Set the revision ID which will be seen by the wiki text parser
1631 * for things such as embedded {{REVISIONID}} variable use.
1633 * @param int|null $revid An positive integer, or null
1634 * @return mixed Previous value
1636 public function setRevisionId( $revid ) {
1637 $val = is_null( $revid ) ?
null : intval( $revid );
1638 return wfSetVar( $this->mRevisionId
, $val );
1642 * Get the displayed revision ID
1646 public function getRevisionId() {
1647 return $this->mRevisionId
;
1651 * Set the timestamp of the revision which will be displayed. This is used
1652 * to avoid a extra DB call in Skin::lastModified().
1654 * @param string|null $timestamp
1655 * @return mixed Previous value
1657 public function setRevisionTimestamp( $timestamp ) {
1658 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1662 * Get the timestamp of displayed revision.
1663 * This will be null if not filled by setRevisionTimestamp().
1665 * @return string|null
1667 public function getRevisionTimestamp() {
1668 return $this->mRevisionTimestamp
;
1672 * Set the displayed file version
1674 * @param File|bool $file
1675 * @return mixed Previous value
1677 public function setFileVersion( $file ) {
1679 if ( $file instanceof File
&& $file->exists() ) {
1680 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1682 return wfSetVar( $this->mFileVersion
, $val, true );
1686 * Get the displayed file version
1688 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1690 public function getFileVersion() {
1691 return $this->mFileVersion
;
1695 * Get the templates used on this page
1697 * @return array (namespace => dbKey => revId)
1700 public function getTemplateIds() {
1701 return $this->mTemplateIds
;
1705 * Get the files used on this page
1707 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1710 public function getFileSearchOptions() {
1711 return $this->mImageTimeKeys
;
1715 * Convert wikitext to HTML and add it to the buffer
1716 * Default assumes that the current page title will be used.
1718 * @param string $text
1719 * @param bool $linestart Is this the start of a line?
1720 * @param bool $interface Is this text in the user interface language?
1721 * @throws MWException
1723 public function addWikiText( $text, $linestart = true, $interface = true ) {
1724 $title = $this->getTitle(); // Work around E_STRICT
1726 throw new MWException( 'Title is null' );
1728 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1732 * Add wikitext with a custom Title object
1734 * @param string $text Wikitext
1735 * @param Title &$title
1736 * @param bool $linestart Is this the start of a line?
1738 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1739 $this->addWikiTextTitle( $text, $title, $linestart );
1743 * Add wikitext with a custom Title object and tidy enabled.
1745 * @param string $text Wikitext
1746 * @param Title &$title
1747 * @param bool $linestart Is this the start of a line?
1749 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1750 $this->addWikiTextTitle( $text, $title, $linestart, true );
1754 * Add wikitext with tidy enabled
1756 * @param string $text Wikitext
1757 * @param bool $linestart Is this the start of a line?
1759 public function addWikiTextTidy( $text, $linestart = true ) {
1760 $title = $this->getTitle();
1761 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1765 * Add wikitext with a custom Title object
1767 * @param string $text Wikitext
1768 * @param Title $title
1769 * @param bool $linestart Is this the start of a line?
1770 * @param bool $tidy Whether to use tidy
1771 * @param bool $interface Whether it is an interface message
1772 * (for example disables conversion)
1774 public function addWikiTextTitle( $text, Title
$title, $linestart,
1775 $tidy = false, $interface = false
1779 $popts = $this->parserOptions();
1780 $oldTidy = $popts->setTidy( $tidy );
1781 $popts->setInterfaceMessage( (bool)$interface );
1783 $parserOutput = $wgParser->getFreshParser()->parse(
1784 $text, $title, $popts,
1785 $linestart, true, $this->mRevisionId
1788 $popts->setTidy( $oldTidy );
1790 $this->addParserOutput( $parserOutput, [
1791 'enableSectionEditLinks' => false,
1796 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1797 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1801 * @param ParserOutput $parserOutput
1803 public function addParserOutputMetadata( $parserOutput ) {
1804 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1805 $this->addCategoryLinks( $parserOutput->getCategories() );
1806 $this->setIndicators( $parserOutput->getIndicators() );
1807 $this->mNewSectionLink
= $parserOutput->getNewSection();
1808 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1810 if ( !$parserOutput->isCacheable() ) {
1811 $this->enableClientCache( false );
1813 $this->mNoGallery
= $parserOutput->getNoGallery();
1814 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1815 $this->addModules( $parserOutput->getModules() );
1816 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1817 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1818 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1819 $this->mPreventClickjacking
= $this->mPreventClickjacking
1820 ||
$parserOutput->preventClickjacking();
1822 // Template versioning...
1823 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1824 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1825 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1827 $this->mTemplateIds
[$ns] = $dbks;
1830 // File versioning...
1831 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1832 $this->mImageTimeKeys
[$dbk] = $data;
1835 // Hooks registered in the object
1836 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1837 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1838 list( $hookName, $data ) = $hookInfo;
1839 if ( isset( $parserOutputHooks[$hookName] ) ) {
1840 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1844 // Enable OOUI if requested via ParserOutput
1845 if ( $parserOutput->getEnableOOUI() ) {
1846 $this->enableOOUI();
1849 // Include parser limit report
1850 if ( !$this->limitReportJSData
) {
1851 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1854 // Link flags are ignored for now, but may in the future be
1855 // used to mark individual language links.
1857 // Avoid PHP 7.1 warning of passing $this by reference
1858 $outputPage = $this;
1859 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1860 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1862 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1863 // so that extensions may modify ParserOutput to toggle TOC.
1864 // This cannot be moved to addParserOutputText because that is not
1865 // called by EditPage for Preview.
1866 if ( $parserOutput->getTOCHTML() ) {
1867 $this->mEnableTOC
= true;
1872 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1873 * ParserOutput object, without any other metadata.
1876 * @param ParserOutput $parserOutput
1877 * @param array $poOptions Options to ParserOutput::getText()
1879 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1880 $this->addParserOutputText( $parserOutput, $poOptions );
1882 $this->addModules( $parserOutput->getModules() );
1883 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1884 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1886 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1890 * Add the HTML associated with a ParserOutput object, without any metadata.
1893 * @param ParserOutput $parserOutput
1894 * @param array $poOptions Options to ParserOutput::getText()
1896 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1897 $text = $parserOutput->getText( $poOptions );
1898 // Avoid PHP 7.1 warning of passing $this by reference
1899 $outputPage = $this;
1900 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1901 $this->addHTML( $text );
1905 * Add everything from a ParserOutput object.
1907 * @param ParserOutput $parserOutput
1908 * @param array $poOptions Options to ParserOutput::getText()
1910 function addParserOutput( $parserOutput, $poOptions = [] ) {
1911 $this->addParserOutputMetadata( $parserOutput );
1912 $this->addParserOutputText( $parserOutput, $poOptions );
1916 * Add the output of a QuickTemplate to the output buffer
1918 * @param QuickTemplate &$template
1920 public function addTemplate( &$template ) {
1921 $this->addHTML( $template->getHTML() );
1925 * Parse wikitext and return the HTML.
1927 * @param string $text
1928 * @param bool $linestart Is this the start of a line?
1929 * @param bool $interface Use interface language ($wgLang instead of
1930 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1931 * This also disables LanguageConverter.
1932 * @param Language|null $language Target language object, will override $interface
1933 * @throws MWException
1934 * @return string HTML
1936 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1939 if ( is_null( $this->getTitle() ) ) {
1940 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1943 $popts = $this->parserOptions();
1945 $popts->setInterfaceMessage( true );
1947 if ( $language !== null ) {
1948 $oldLang = $popts->setTargetLanguage( $language );
1951 $parserOutput = $wgParser->getFreshParser()->parse(
1952 $text, $this->getTitle(), $popts,
1953 $linestart, true, $this->mRevisionId
1957 $popts->setInterfaceMessage( false );
1959 if ( $language !== null ) {
1960 $popts->setTargetLanguage( $oldLang );
1963 return $parserOutput->getText( [
1964 'enableSectionEditLinks' => false,
1969 * Parse wikitext, strip paragraphs, and return the HTML.
1971 * @param string $text
1972 * @param bool $linestart Is this the start of a line?
1973 * @param bool $interface Use interface language ($wgLang instead of
1974 * $wgContLang) while parsing language sensitive magic
1975 * words like GRAMMAR and PLURAL
1976 * @return string HTML
1978 public function parseInline( $text, $linestart = true, $interface = false ) {
1979 $parsed = $this->parse( $text, $linestart, $interface );
1980 return Parser
::stripOuterParagraph( $parsed );
1984 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1986 * @param int $maxage Maximum cache time on the CDN, in seconds.
1988 public function setCdnMaxage( $maxage ) {
1989 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1993 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1995 * @param int $maxage Maximum cache time on the CDN, in seconds
1998 public function lowerCdnMaxage( $maxage ) {
1999 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2000 $this->setCdnMaxage( $this->mCdnMaxage
);
2004 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2006 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2007 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2008 * TTL is 90% of the age of the object, subject to the min and max.
2010 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2011 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2012 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2013 * @return int TTL in seconds
2016 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2017 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2018 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2020 if ( $mtime === null ||
$mtime === false ) {
2021 return $minTTL; // entity does not exist
2024 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2025 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2026 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2028 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2030 return $adaptiveTTL;
2034 * Use enableClientCache(false) to force it to send nocache headers
2036 * @param bool $state
2040 public function enableClientCache( $state ) {
2041 return wfSetVar( $this->mEnableClientCache
, $state );
2045 * Get the list of cookies that will influence on the cache
2049 function getCacheVaryCookies() {
2051 if ( $cookies === null ) {
2052 $config = $this->getConfig();
2053 $cookies = array_merge(
2054 SessionManager
::singleton()->getVaryCookies(),
2058 $config->get( 'CacheVaryCookies' )
2060 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2066 * Check if the request has a cache-varying cookie header
2067 * If it does, it's very important that we don't allow public caching
2071 function haveCacheVaryCookies() {
2072 $request = $this->getRequest();
2073 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2074 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2075 wfDebug( __METHOD__
. ": found $cookieName\n" );
2079 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2084 * Add an HTTP header that will influence on the cache
2086 * @param string $header Header name
2087 * @param string[]|null $option Options for the Key header. See
2088 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2089 * for the list of valid options.
2091 public function addVaryHeader( $header, array $option = null ) {
2092 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2093 $this->mVaryHeader
[$header] = [];
2095 if ( !is_array( $option ) ) {
2098 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2102 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2103 * such as Accept-Encoding or Cookie
2107 public function getVaryHeader() {
2108 // If we vary on cookies, let's make sure it's always included here too.
2109 if ( $this->getCacheVaryCookies() ) {
2110 $this->addVaryHeader( 'Cookie' );
2113 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2114 $this->addVaryHeader( $header, $options );
2116 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2120 * Add an HTTP Link: header
2122 * @param string $header Header value
2124 public function addLinkHeader( $header ) {
2125 $this->mLinkHeader
[] = $header;
2129 * Return a Link: header. Based on the values of $mLinkHeader.
2133 public function getLinkHeader() {
2134 if ( !$this->mLinkHeader
) {
2138 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2142 * Get a complete Key header
2146 public function getKeyHeader() {
2147 $cvCookies = $this->getCacheVaryCookies();
2149 $cookiesOption = [];
2150 foreach ( $cvCookies as $cookieName ) {
2151 $cookiesOption[] = 'param=' . $cookieName;
2153 $this->addVaryHeader( 'Cookie', $cookiesOption );
2155 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2156 $this->addVaryHeader( $header, $options );
2160 foreach ( $this->mVaryHeader
as $header => $option ) {
2161 $newheader = $header;
2162 if ( is_array( $option ) && count( $option ) > 0 ) {
2163 $newheader .= ';' . implode( ';', $option );
2165 $headers[] = $newheader;
2167 $key = 'Key: ' . implode( ',', $headers );
2173 * T23672: Add Accept-Language to Vary and Key headers
2174 * if there's no 'variant' parameter existed in GET.
2177 * /w/index.php?title=Main_page should always be served; but
2178 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2180 function addAcceptLanguage() {
2181 $title = $this->getTitle();
2182 if ( !$title instanceof Title
) {
2186 $lang = $title->getPageLanguage();
2187 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2188 $variants = $lang->getVariants();
2190 foreach ( $variants as $variant ) {
2191 if ( $variant === $lang->getCode() ) {
2194 $aloption[] = 'substr=' . $variant;
2196 // IE and some other browsers use BCP 47 standards in
2197 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2198 // We should handle these too.
2199 $variantBCP47 = LanguageCode
::bcp47( $variant );
2200 if ( $variantBCP47 !== $variant ) {
2201 $aloption[] = 'substr=' . $variantBCP47;
2205 $this->addVaryHeader( 'Accept-Language', $aloption );
2210 * Set a flag which will cause an X-Frame-Options header appropriate for
2211 * edit pages to be sent. The header value is controlled by
2212 * $wgEditPageFrameOptions.
2214 * This is the default for special pages. If you display a CSRF-protected
2215 * form on an ordinary view page, then you need to call this function.
2217 * @param bool $enable
2219 public function preventClickjacking( $enable = true ) {
2220 $this->mPreventClickjacking
= $enable;
2224 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2225 * This can be called from pages which do not contain any CSRF-protected
2228 public function allowClickjacking() {
2229 $this->mPreventClickjacking
= false;
2233 * Get the prevent-clickjacking flag
2238 public function getPreventClickjacking() {
2239 return $this->mPreventClickjacking
;
2243 * Get the X-Frame-Options header value (without the name part), or false
2244 * if there isn't one. This is used by Skin to determine whether to enable
2245 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2247 * @return string|false
2249 public function getFrameOptions() {
2250 $config = $this->getConfig();
2251 if ( $config->get( 'BreakFrames' ) ) {
2253 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2254 return $config->get( 'EditPageFrameOptions' );
2260 * Send cache control HTTP headers
2262 public function sendCacheControl() {
2263 $response = $this->getRequest()->response();
2264 $config = $this->getConfig();
2266 $this->addVaryHeader( 'Cookie' );
2267 $this->addAcceptLanguage();
2269 # don't serve compressed data to clients who can't handle it
2270 # maintain different caches for logged-in users and non-logged in ones
2271 $response->header( $this->getVaryHeader() );
2273 if ( $config->get( 'UseKeyHeader' ) ) {
2274 $response->header( $this->getKeyHeader() );
2277 if ( $this->mEnableClientCache
) {
2279 $config->get( 'UseSquid' ) &&
2280 !$response->hasCookies() &&
2281 !SessionManager
::getGlobalSession()->isPersistent() &&
2282 !$this->isPrintable() &&
2283 $this->mCdnMaxage
!= 0 &&
2284 !$this->haveCacheVaryCookies()
2286 if ( $config->get( 'UseESI' ) ) {
2287 # We'll purge the proxy cache explicitly, but require end user agents
2288 # to revalidate against the proxy on each visit.
2289 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2290 wfDebug( __METHOD__
.
2291 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2292 # start with a shorter timeout for initial testing
2293 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2295 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2296 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2298 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2300 # We'll purge the proxy cache for anons explicitly, but require end user agents
2301 # to revalidate against the proxy on each visit.
2302 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2303 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2304 wfDebug( __METHOD__
.
2305 ": local proxy caching; {$this->mLastModified} **", 'private' );
2306 # start with a shorter timeout for initial testing
2307 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2308 $response->header( "Cache-Control: " .
2309 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2312 # We do want clients to cache if they can, but they *must* check for updates
2313 # on revisiting the page.
2314 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2315 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2316 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2318 if ( $this->mLastModified
) {
2319 $response->header( "Last-Modified: {$this->mLastModified}" );
2322 wfDebug( __METHOD__
. ": no caching **", 'private' );
2324 # In general, the absence of a last modified header should be enough to prevent
2325 # the client from using its cache. We send a few other things just to make sure.
2326 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2327 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2328 $response->header( 'Pragma: no-cache' );
2333 * Transfer styles and JavaScript modules from skin.
2335 * @param Skin $sk to load modules for
2337 public function loadSkinModules( $sk ) {
2338 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2339 if ( $group === 'styles' ) {
2340 foreach ( $modules as $key => $moduleMembers ) {
2341 $this->addModuleStyles( $moduleMembers );
2344 $this->addModules( $modules );
2350 * Finally, all the text has been munged and accumulated into
2351 * the object, let's actually output it:
2353 * @param bool $return Set to true to get the result as a string rather than sending it
2354 * @return string|null
2356 * @throws FatalError
2357 * @throws MWException
2359 public function output( $return = false ) {
2362 if ( $this->mDoNothing
) {
2363 return $return ?
'' : null;
2366 $response = $this->getRequest()->response();
2367 $config = $this->getConfig();
2369 if ( $this->mRedirect
!= '' ) {
2370 # Standards require redirect URLs to be absolute
2371 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2373 $redirect = $this->mRedirect
;
2374 $code = $this->mRedirectCode
;
2376 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2377 if ( $code == '301' ||
$code == '303' ) {
2378 if ( !$config->get( 'DebugRedirects' ) ) {
2379 $response->statusHeader( $code );
2381 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2383 if ( $config->get( 'VaryOnXFP' ) ) {
2384 $this->addVaryHeader( 'X-Forwarded-Proto' );
2386 $this->sendCacheControl();
2388 $response->header( "Content-Type: text/html; charset=utf-8" );
2389 if ( $config->get( 'DebugRedirects' ) ) {
2390 $url = htmlspecialchars( $redirect );
2391 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2392 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2393 print "</body>\n</html>\n";
2395 $response->header( 'Location: ' . $redirect );
2399 return $return ?
'' : null;
2400 } elseif ( $this->mStatusCode
) {
2401 $response->statusHeader( $this->mStatusCode
);
2404 # Buffer output; final headers may depend on later processing
2407 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2408 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2410 if ( !$this->mArticleBodyOnly
) {
2411 $sk = $this->getSkin();
2413 if ( $sk->shouldPreloadLogo() ) {
2414 $this->addLogoPreloadLinkHeaders();
2418 $linkHeader = $this->getLinkHeader();
2419 if ( $linkHeader ) {
2420 $response->header( $linkHeader );
2423 // Prevent framing, if requested
2424 $frameOptions = $this->getFrameOptions();
2425 if ( $frameOptions ) {
2426 $response->header( "X-Frame-Options: $frameOptions" );
2429 ContentSecurityPolicy
::sendHeaders( $this );
2431 if ( $this->mArticleBodyOnly
) {
2432 echo $this->mBodytext
;
2434 // Enable safe mode if requested (T152169)
2435 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2436 $this->disallowUserJs();
2439 $sk = $this->getSkin();
2440 $this->loadSkinModules( $sk );
2442 MWDebug
::addModules( $this );
2444 // Avoid PHP 7.1 warning of passing $this by reference
2445 $outputPage = $this;
2446 // Hook that allows last minute changes to the output page, e.g.
2447 // adding of CSS or Javascript by extensions.
2448 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2452 } catch ( Exception
$e ) {
2453 ob_end_clean(); // bug T129657
2459 // This hook allows last minute changes to final overall output by modifying output buffer
2460 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2461 } catch ( Exception
$e ) {
2462 ob_end_clean(); // bug T129657
2466 $this->sendCacheControl();
2469 return ob_get_clean();
2477 * Prepare this object to display an error page; disable caching and
2478 * indexing, clear the current text and redirect, set the page's title
2479 * and optionally an custom HTML title (content of the "<title>" tag).
2481 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2482 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2483 * optional, if not passed the "<title>" attribute will be
2484 * based on $pageTitle
2486 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2487 $this->setPageTitle( $pageTitle );
2488 if ( $htmlTitle !== false ) {
2489 $this->setHTMLTitle( $htmlTitle );
2491 $this->setRobotPolicy( 'noindex,nofollow' );
2492 $this->setArticleRelated( false );
2493 $this->enableClientCache( false );
2494 $this->mRedirect
= '';
2495 $this->clearSubtitle();
2500 * Output a standard error page
2502 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2503 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2504 * showErrorPage( 'titlemsg', $messageObject );
2505 * showErrorPage( $titleMessageObject, $messageObject );
2507 * @param string|Message $title Message key (string) for page title, or a Message object
2508 * @param string|Message $msg Message key (string) for page text, or a Message object
2509 * @param array $params Message parameters; ignored if $msg is a Message object
2511 public function showErrorPage( $title, $msg, $params = [] ) {
2512 if ( !$title instanceof Message
) {
2513 $title = $this->msg( $title );
2516 $this->prepareErrorPage( $title );
2518 if ( $msg instanceof Message
) {
2519 if ( $params !== [] ) {
2520 trigger_error( 'Argument ignored: $params. The message parameters argument '
2521 . 'is discarded when the $msg argument is a Message object instead of '
2522 . 'a string.', E_USER_NOTICE
);
2524 $this->addHTML( $msg->parseAsBlock() );
2526 $this->addWikiMsgArray( $msg, $params );
2529 $this->returnToMain();
2533 * Output a standard permission error page
2535 * @param array $errors Error message keys or [key, param...] arrays
2536 * @param string|null $action Action that was denied or null if unknown
2538 public function showPermissionsErrorPage( array $errors, $action = null ) {
2539 foreach ( $errors as $key => $error ) {
2540 $errors[$key] = (array)$error;
2543 // For some action (read, edit, create and upload), display a "login to do this action"
2544 // error if all of the following conditions are met:
2545 // 1. the user is not logged in
2546 // 2. the only error is insufficient permissions (i.e. no block or something else)
2547 // 3. the error can be avoided simply by logging in
2548 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2549 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2550 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2551 && ( User
::groupHasPermission( 'user', $action )
2552 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2554 $displayReturnto = null;
2556 # Due to T34276, if a user does not have read permissions,
2557 # $this->getTitle() will just give Special:Badtitle, which is
2558 # not especially useful as a returnto parameter. Use the title
2559 # from the request instead, if there was one.
2560 $request = $this->getRequest();
2561 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2562 if ( $action == 'edit' ) {
2563 $msg = 'whitelistedittext';
2564 $displayReturnto = $returnto;
2565 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2566 $msg = 'nocreatetext';
2567 } elseif ( $action == 'upload' ) {
2568 $msg = 'uploadnologintext';
2570 $msg = 'loginreqpagetext';
2571 $displayReturnto = Title
::newMainPage();
2577 $query['returnto'] = $returnto->getPrefixedText();
2579 if ( !$request->wasPosted() ) {
2580 $returntoquery = $request->getValues();
2581 unset( $returntoquery['title'] );
2582 unset( $returntoquery['returnto'] );
2583 unset( $returntoquery['returntoquery'] );
2584 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2587 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2588 $loginLink = $linkRenderer->makeKnownLink(
2589 SpecialPage
::getTitleFor( 'Userlogin' ),
2590 $this->msg( 'loginreqlink' )->text(),
2595 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2596 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2598 # Don't return to a page the user can't read otherwise
2599 # we'll end up in a pointless loop
2600 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2601 $this->returnToMain( null, $displayReturnto );
2604 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2605 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2610 * Display an error page indicating that a given version of MediaWiki is
2611 * required to use it
2613 * @param mixed $version The version of MediaWiki needed to use the page
2615 public function versionRequired( $version ) {
2616 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2618 $this->addWikiMsg( 'versionrequiredtext', $version );
2619 $this->returnToMain();
2623 * Format a list of error messages
2625 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2626 * @param string|null $action Action that was denied or null if unknown
2627 * @return string The wikitext error-messages, formatted into a list.
2629 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2630 if ( $action == null ) {
2631 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2633 $action_desc = $this->msg( "action-$action" )->plain();
2635 'permissionserrorstext-withaction',
2638 )->plain() . "\n\n";
2641 if ( count( $errors ) > 1 ) {
2642 $text .= '<ul class="permissions-errors">' . "\n";
2644 foreach ( $errors as $error ) {
2646 $text .= $this->msg( ...$error )->plain();
2651 $text .= "<div class=\"permissions-errors\">\n" .
2652 $this->msg( ...reset( $errors ) )->plain() .
2660 * Show a warning about replica DB lag
2662 * If the lag is higher than $wgSlaveLagCritical seconds,
2663 * then the warning is a bit more obvious. If the lag is
2664 * lower than $wgSlaveLagWarning, then no warning is shown.
2666 * @param int $lag Slave lag
2668 public function showLagWarning( $lag ) {
2669 $config = $this->getConfig();
2670 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2671 $lag = floor( $lag ); // floor to avoid nano seconds to display
2672 $message = $lag < $config->get( 'SlaveLagCritical' )
2675 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2676 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2680 public function showFatalError( $message ) {
2681 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2683 $this->addHTML( $message );
2686 public function showUnexpectedValueError( $name, $val ) {
2687 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2690 public function showFileCopyError( $old, $new ) {
2691 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2694 public function showFileRenameError( $old, $new ) {
2695 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2698 public function showFileDeleteError( $name ) {
2699 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2702 public function showFileNotFoundError( $name ) {
2703 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2707 * Add a "return to" link pointing to a specified title
2709 * @param Title $title Title to link
2710 * @param array $query Query string parameters
2711 * @param string|null $text Text of the link (input is not escaped)
2712 * @param array $options Options array to pass to Linker
2714 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2715 $linkRenderer = MediaWikiServices
::getInstance()
2716 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2717 $link = $this->msg( 'returnto' )->rawParams(
2718 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2719 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2723 * Add a "return to" link pointing to a specified title,
2724 * or the title indicated in the request, or else the main page
2726 * @param mixed|null $unused
2727 * @param Title|string|null $returnto Title or String to return to
2728 * @param string|null $returntoquery Query string for the return to link
2730 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2731 if ( $returnto == null ) {
2732 $returnto = $this->getRequest()->getText( 'returnto' );
2735 if ( $returntoquery == null ) {
2736 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2739 if ( $returnto === '' ) {
2740 $returnto = Title
::newMainPage();
2743 if ( is_object( $returnto ) ) {
2744 $titleObj = $returnto;
2746 $titleObj = Title
::newFromText( $returnto );
2748 // We don't want people to return to external interwiki. That
2749 // might potentially be used as part of a phishing scheme
2750 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2751 $titleObj = Title
::newMainPage();
2754 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2757 private function getRlClientContext() {
2758 if ( !$this->rlClientContext
) {
2759 $query = ResourceLoader
::makeLoaderQuery(
2760 [], // modules; not relevant
2761 $this->getLanguage()->getCode(),
2762 $this->getSkin()->getSkinName(),
2763 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2764 null, // version; not relevant
2765 ResourceLoader
::inDebugMode(),
2766 null, // only; not relevant
2767 $this->isPrintable(),
2768 $this->getRequest()->getBool( 'handheld' )
2770 $this->rlClientContext
= new ResourceLoaderContext(
2771 $this->getResourceLoader(),
2772 new FauxRequest( $query )
2774 if ( $this->contentOverrideCallbacks
) {
2775 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2776 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2777 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2778 $content = call_user_func( $callback, $title );
2779 if ( $content !== null ) {
2787 return $this->rlClientContext
;
2791 * Call this to freeze the module queue and JS config and create a formatter.
2793 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2794 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2795 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2796 * the module filters retroactively. Skins and extension hooks may also add modules until very
2797 * late in the request lifecycle.
2799 * @return ResourceLoaderClientHtml
2801 public function getRlClient() {
2802 if ( !$this->rlClient
) {
2803 $context = $this->getRlClientContext();
2804 $rl = $this->getResourceLoader();
2805 $this->addModules( [
2810 $this->addModuleStyles( [
2815 $this->getSkin()->setupSkinUserCss( $this );
2817 // Prepare exempt modules for buildExemptModules()
2818 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2820 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2822 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2823 // Separate user-specific batch for improved cache-hit ratio.
2824 $userBatch = [ 'user.styles', 'user' ];
2825 $siteBatch = array_diff( $moduleStyles, $userBatch );
2826 $dbr = wfGetDB( DB_REPLICA
);
2827 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2828 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2830 // Filter out modules handled by buildExemptModules()
2831 $moduleStyles = array_filter( $moduleStyles,
2832 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2833 $module = $rl->getModule( $name );
2835 $group = $module->getGroup();
2836 if ( isset( $exemptGroups[$group] ) ) {
2837 $exemptStates[$name] = 'ready';
2838 if ( !$module->isKnownEmpty( $context ) ) {
2839 // E.g. Don't output empty <styles>
2840 $exemptGroups[$group][] = $name;
2848 $this->rlExemptStyleModules
= $exemptGroups;
2850 $rlClient = new ResourceLoaderClientHtml( $context, [
2851 'target' => $this->getTarget(),
2852 'nonce' => $this->getCSPNonce(),
2853 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2854 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2855 // modules enqueud for loading on this page is filtered to just those.
2856 // However, to make sure we also apply the restriction to dynamic dependencies and
2857 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2858 // StartupModule so that the client-side registry will not contain any restricted
2859 // modules either. (T152169, T185303)
2860 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2861 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2864 $rlClient->setConfig( $this->getJSVars() );
2865 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2866 $rlClient->setModuleStyles( $moduleStyles );
2867 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2868 $rlClient->setExemptStates( $exemptStates );
2869 $this->rlClient
= $rlClient;
2871 return $this->rlClient
;
2875 * @param Skin $sk The given Skin
2876 * @param bool $includeStyle Unused
2877 * @return string The doctype, opening "<html>", and head element.
2879 public function headElement( Skin
$sk, $includeStyle = true ) {
2882 $userdir = $this->getLanguage()->getDir();
2883 $sitedir = $wgContLang->getDir();
2886 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2887 $this->getRlClient()->getDocumentAttributes(),
2888 $sk->getHtmlElementAttributes()
2890 $pieces[] = Html
::openElement( 'head' );
2892 if ( $this->getHTMLTitle() == '' ) {
2893 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2896 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2897 // Add <meta charset="UTF-8">
2898 // This should be before <title> since it defines the charset used by
2899 // text including the text inside <title>.
2900 // The spec recommends defining XHTML5's charset using the XML declaration
2902 // Our XML declaration is output by Html::htmlHeader.
2903 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2904 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2905 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2908 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2909 $pieces[] = $this->getRlClient()->getHeadHtml();
2910 $pieces[] = $this->buildExemptModules();
2911 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2912 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2914 // Use an IE conditional comment to serve the script only to old IE
2915 $pieces[] = '<!--[if lt IE 9]>' .
2916 ResourceLoaderClientHtml
::makeLoad(
2917 ResourceLoaderContext
::newDummyContext(),
2919 ResourceLoaderModule
::TYPE_SCRIPTS
,
2921 $this->getCSPNonce()
2925 $pieces[] = Html
::closeElement( 'head' );
2927 $bodyClasses = $this->mAdditionalBodyClasses
;
2928 $bodyClasses[] = 'mediawiki';
2930 # Classes for LTR/RTL directionality support
2931 $bodyClasses[] = $userdir;
2932 $bodyClasses[] = "sitedir-$sitedir";
2934 $underline = $this->getUser()->getOption( 'underline' );
2935 if ( $underline < 2 ) {
2936 // The following classes can be used here:
2937 // * mw-underline-always
2938 // * mw-underline-never
2939 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2942 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2943 # A <body> class is probably not the best way to do this . . .
2944 $bodyClasses[] = 'capitalize-all-nouns';
2947 // Parser feature migration class
2948 // The idea is that this will eventually be removed, after the wikitext
2949 // which requires it is cleaned up.
2950 $bodyClasses[] = 'mw-hide-empty-elt';
2952 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2953 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2955 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2958 // While the implode() is not strictly needed, it's used for backwards compatibility
2959 // (this used to be built as a string and hooks likely still expect that).
2960 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2962 // Allow skins and extensions to add body attributes they need
2963 $sk->addToBodyAttributes( $this, $bodyAttrs );
2964 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2966 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2968 return self
::combineWrappedStrings( $pieces );
2972 * Get a ResourceLoader object associated with this OutputPage
2974 * @return ResourceLoader
2976 public function getResourceLoader() {
2977 if ( is_null( $this->mResourceLoader
) ) {
2978 $this->mResourceLoader
= new ResourceLoader(
2980 LoggerFactory
::getInstance( 'resourceloader' )
2983 return $this->mResourceLoader
;
2987 * Explicily load or embed modules on a page.
2989 * @param array|string $modules One or more module names
2990 * @param string $only ResourceLoaderModule TYPE_ class constant
2991 * @param array $extraQuery [optional] Array with extra query parameters for the request
2992 * @return string|WrappedStringList HTML
2994 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2995 // Apply 'target' and 'origin' filters
2996 $modules = $this->filterModules( (array)$modules, null, $only );
2998 return ResourceLoaderClientHtml
::makeLoad(
2999 $this->getRlClientContext(),
3003 $this->getCSPNonce()
3008 * Combine WrappedString chunks and filter out empty ones
3010 * @param array $chunks
3011 * @return string|WrappedStringList HTML
3013 protected static function combineWrappedStrings( array $chunks ) {
3014 // Filter out empty values
3015 $chunks = array_filter( $chunks, 'strlen' );
3016 return WrappedString
::join( "\n", $chunks );
3020 * JS stuff to put at the bottom of the `<body>`.
3021 * These are legacy scripts ($this->mScripts), and user JS.
3023 * @return string|WrappedStringList HTML
3025 public function getBottomScripts() {
3027 $chunks[] = $this->getRlClient()->getBodyHtml();
3029 // Legacy non-ResourceLoader scripts
3030 $chunks[] = $this->mScripts
;
3032 if ( $this->limitReportJSData
) {
3033 $chunks[] = ResourceLoader
::makeInlineScript(
3034 ResourceLoader
::makeConfigSetScript(
3035 [ 'wgPageParseReport' => $this->limitReportJSData
]
3037 $this->getCSPNonce()
3041 return self
::combineWrappedStrings( $chunks );
3045 * Get the javascript config vars to include on this page
3047 * @return array Array of javascript config vars
3050 public function getJsConfigVars() {
3051 return $this->mJsConfigVars
;
3055 * Add one or more variables to be set in mw.config in JavaScript
3057 * @param string|array $keys Key or array of key/value pairs
3058 * @param mixed|null $value [optional] Value of the configuration variable
3060 public function addJsConfigVars( $keys, $value = null ) {
3061 if ( is_array( $keys ) ) {
3062 foreach ( $keys as $key => $value ) {
3063 $this->mJsConfigVars
[$key] = $value;
3068 $this->mJsConfigVars
[$keys] = $value;
3072 * Get an array containing the variables to be set in mw.config in JavaScript.
3074 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3075 * - in other words, page-independent/site-wide variables (without state).
3076 * You will only be adding bloat to the html page and causing page caches to
3077 * have to be purged on configuration changes.
3080 public function getJSVars() {
3085 $canonicalSpecialPageName = false; # T23115
3087 $title = $this->getTitle();
3088 $ns = $title->getNamespace();
3089 $canonicalNamespace = MWNamespace
::exists( $ns )
3090 ? MWNamespace
::getCanonicalName( $ns )
3091 : $title->getNsText();
3093 $sk = $this->getSkin();
3094 // Get the relevant title so that AJAX features can use the correct page name
3095 // when making API requests from certain special pages (T36972).
3096 $relevantTitle = $sk->getRelevantTitle();
3097 $relevantUser = $sk->getRelevantUser();
3099 if ( $ns == NS_SPECIAL
) {
3100 list( $canonicalSpecialPageName, /*...*/ ) =
3101 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3102 } elseif ( $this->canUseWikiPage() ) {
3103 $wikiPage = $this->getWikiPage();
3104 $curRevisionId = $wikiPage->getLatest();
3105 $articleId = $wikiPage->getId();
3108 $lang = $title->getPageViewLanguage();
3110 // Pre-process information
3111 $separatorTransTable = $lang->separatorTransformTable();
3112 $separatorTransTable = $separatorTransTable ?
: [];
3113 $compactSeparatorTransTable = [
3114 implode( "\t", array_keys( $separatorTransTable ) ),
3115 implode( "\t", $separatorTransTable ),
3117 $digitTransTable = $lang->digitTransformTable();
3118 $digitTransTable = $digitTransTable ?
: [];
3119 $compactDigitTransTable = [
3120 implode( "\t", array_keys( $digitTransTable ) ),
3121 implode( "\t", $digitTransTable ),
3124 $user = $this->getUser();
3127 'wgCanonicalNamespace' => $canonicalNamespace,
3128 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3129 'wgNamespaceNumber' => $title->getNamespace(),
3130 'wgPageName' => $title->getPrefixedDBkey(),
3131 'wgTitle' => $title->getText(),
3132 'wgCurRevisionId' => $curRevisionId,
3133 'wgRevisionId' => (int)$this->getRevisionId(),
3134 'wgArticleId' => $articleId,
3135 'wgIsArticle' => $this->isArticle(),
3136 'wgIsRedirect' => $title->isRedirect(),
3137 'wgAction' => Action
::getActionName( $this->getContext() ),
3138 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3139 'wgUserGroups' => $user->getEffectiveGroups(),
3140 'wgCategories' => $this->getCategories(),
3141 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3142 'wgPageContentLanguage' => $lang->getCode(),
3143 'wgPageContentModel' => $title->getContentModel(),
3144 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3145 'wgDigitTransformTable' => $compactDigitTransTable,
3146 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3147 'wgMonthNames' => $lang->getMonthNamesArray(),
3148 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3149 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3150 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3151 'wgRequestId' => WebRequest
::getRequestId(),
3154 if ( $user->isLoggedIn() ) {
3155 $vars['wgUserId'] = $user->getId();
3156 $vars['wgUserEditCount'] = $user->getEditCount();
3157 $userReg = $user->getRegistration();
3158 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3159 // Get the revision ID of the oldest new message on the user's talk
3160 // page. This can be used for constructing new message alerts on
3162 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3165 if ( $wgContLang->hasVariants() ) {
3166 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3168 // Same test as SkinTemplate
3169 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3170 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3172 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3173 && $relevantTitle->quickUserCan( 'edit', $user )
3174 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3176 foreach ( $title->getRestrictionTypes() as $type ) {
3177 // Following keys are set in $vars:
3178 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3179 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3182 if ( $title->isMainPage() ) {
3183 $vars['wgIsMainPage'] = true;
3186 if ( $this->mRedirectedFrom
) {
3187 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3190 if ( $relevantUser ) {
3191 $vars['wgRelevantUserName'] = $relevantUser->getName();
3194 // Allow extensions to add their custom variables to the mw.config map.
3195 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3196 // page-dependant but site-wide (without state).
3197 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3198 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3200 // Merge in variables from addJsConfigVars last
3201 return array_merge( $vars, $this->getJsConfigVars() );
3205 * To make it harder for someone to slip a user a fake
3206 * JavaScript or CSS preview, a random token
3207 * is associated with the login session. If it's not
3208 * passed back with the preview request, we won't render
3213 public function userCanPreview() {
3214 $request = $this->getRequest();
3216 $request->getVal( 'action' ) !== 'submit' ||
3217 !$request->wasPosted()
3222 $user = $this->getUser();
3224 if ( !$user->isLoggedIn() ) {
3225 // Anons have predictable edit tokens
3228 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3232 $title = $this->getTitle();
3233 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3234 if ( count( $errors ) !== 0 ) {
3242 * @return array Array in format "link name or number => 'link html'".
3244 public function getHeadLinksArray() {
3248 $config = $this->getConfig();
3250 $canonicalUrl = $this->mCanonicalUrl
;
3252 $tags['meta-generator'] = Html
::element( 'meta', [
3253 'name' => 'generator',
3254 'content' => "MediaWiki $wgVersion",
3257 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3258 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3259 // fallbacks should come before the primary value so we need to reverse the array.
3260 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3261 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3262 'name' => 'referrer',
3263 'content' => $policy,
3268 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3269 if ( $p !== 'index,follow' ) {
3270 // http://www.robotstxt.org/wc/meta-user.html
3271 // Only show if it's different from the default robots policy
3272 $tags['meta-robots'] = Html
::element( 'meta', [
3278 foreach ( $this->mMetatags
as $tag ) {
3279 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3281 $tag[0] = substr( $tag[0], 5 );
3282 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3287 $tagName = "meta-{$tag[0]}";
3288 if ( isset( $tags[$tagName] ) ) {
3289 $tagName .= $tag[1];
3291 $tags[$tagName] = Html
::element( 'meta',
3294 'content' => $tag[1]
3299 foreach ( $this->mLinktags
as $tag ) {
3300 $tags[] = Html
::element( 'link', $tag );
3303 # Universal edit button
3304 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3305 $user = $this->getUser();
3306 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3307 && ( $this->getTitle()->exists() ||
3308 $this->getTitle()->quickUserCan( 'create', $user ) )
3310 // Original UniversalEditButton
3311 $msg = $this->msg( 'edit' )->text();
3312 $tags['universal-edit-button'] = Html
::element( 'link', [
3313 'rel' => 'alternate',
3314 'type' => 'application/x-wiki',
3316 'href' => $this->getTitle()->getEditURL(),
3318 // Alternate edit link
3319 $tags['alternative-edit'] = Html
::element( 'link', [
3322 'href' => $this->getTitle()->getEditURL(),
3327 # Generally the order of the favicon and apple-touch-icon links
3328 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3329 # uses whichever one appears later in the HTML source. Make sure
3330 # apple-touch-icon is specified first to avoid this.
3331 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3332 $tags['apple-touch-icon'] = Html
::element( 'link', [
3333 'rel' => 'apple-touch-icon',
3334 'href' => $config->get( 'AppleTouchIcon' )
3338 if ( $config->get( 'Favicon' ) !== false ) {
3339 $tags['favicon'] = Html
::element( 'link', [
3340 'rel' => 'shortcut icon',
3341 'href' => $config->get( 'Favicon' )
3345 # OpenSearch description link
3346 $tags['opensearch'] = Html
::element( 'link', [
3348 'type' => 'application/opensearchdescription+xml',
3349 'href' => wfScript( 'opensearch_desc' ),
3350 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3353 # Real Simple Discovery link, provides auto-discovery information
3354 # for the MediaWiki API (and potentially additional custom API
3355 # support such as WordPress or Twitter-compatible APIs for a
3356 # blogging extension, etc)
3357 $tags['rsd'] = Html
::element( 'link', [
3359 'type' => 'application/rsd+xml',
3360 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3361 // Whether RSD accepts relative or protocol-relative URLs is completely
3362 // undocumented, though.
3363 'href' => wfExpandUrl( wfAppendQuery(
3365 [ 'action' => 'rsd' ] ),
3371 if ( !$config->get( 'DisableLangConversion' ) ) {
3372 $lang = $this->getTitle()->getPageLanguage();
3373 if ( $lang->hasVariants() ) {
3374 $variants = $lang->getVariants();
3375 foreach ( $variants as $variant ) {
3376 $tags["variant-$variant"] = Html
::element( 'link', [
3377 'rel' => 'alternate',
3378 'hreflang' => LanguageCode
::bcp47( $variant ),
3379 'href' => $this->getTitle()->getLocalURL(
3380 [ 'variant' => $variant ] )
3384 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3385 $tags["variant-x-default"] = Html
::element( 'link', [
3386 'rel' => 'alternate',
3387 'hreflang' => 'x-default',
3388 'href' => $this->getTitle()->getLocalURL() ] );
3393 if ( $this->copyrightUrl
!== null ) {
3394 $copyright = $this->copyrightUrl
;
3397 if ( $config->get( 'RightsPage' ) ) {
3398 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3401 $copyright = $copy->getLocalURL();
3405 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3406 $copyright = $config->get( 'RightsUrl' );
3411 $tags['copyright'] = Html
::element( 'link', [
3413 'href' => $copyright ]
3418 if ( $config->get( 'Feed' ) ) {
3421 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3422 # Use the page name for the title. In principle, this could
3423 # lead to issues with having the same name for different feeds
3424 # corresponding to the same page, but we can't avoid that at
3427 $feedLinks[] = $this->feedLink(
3430 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3432 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3437 # Recent changes feed should appear on every page (except recentchanges,
3438 # that would be redundant). Put it after the per-page feed to avoid
3439 # changing existing behavior. It's still available, probably via a
3440 # menu in your browser. Some sites might have a different feed they'd
3441 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3442 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3443 # If so, use it instead.
3444 $sitename = $config->get( 'Sitename' );
3445 if ( $config->get( 'OverrideSiteFeed' ) ) {
3446 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3447 // Note, this->feedLink escapes the url.
3448 $feedLinks[] = $this->feedLink(
3451 $this->msg( "site-{$type}-feed", $sitename )->text()
3454 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3455 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3456 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3457 $feedLinks[] = $this->feedLink(
3459 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3460 # For grep: 'site-rss-feed', 'site-atom-feed'
3461 $this->msg( "site-{$format}-feed", $sitename )->text()
3466 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3467 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3468 # use OutputPage::addFeedLink() instead.
3469 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3471 $tags +
= $feedLinks;
3475 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3476 if ( $canonicalUrl !== false ) {
3477 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3479 if ( $this->isArticleRelated() ) {
3480 // This affects all requests where "setArticleRelated" is true. This is
3481 // typically all requests that show content (query title, curid, oldid, diff),
3482 // and all wikipage actions (edit, delete, purge, info, history etc.).
3483 // It does not apply to File pages and Special pages.
3484 // 'history' and 'info' actions address page metadata rather than the page
3485 // content itself, so they may not be canonicalized to the view page url.
3486 // TODO: this ought to be better encapsulated in the Action class.
3487 $action = Action
::getActionName( $this->getContext() );
3488 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3489 $query = "action={$action}";
3493 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3495 $reqUrl = $this->getRequest()->getRequestURL();
3496 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3500 if ( $canonicalUrl !== false ) {
3501 $tags[] = Html
::element( 'link', [
3502 'rel' => 'canonical',
3503 'href' => $canonicalUrl
3511 * Generate a "<link rel/>" for a feed.
3513 * @param string $type Feed type
3514 * @param string $url URL to the feed
3515 * @param string $text Value of the "title" attribute
3516 * @return string HTML fragment
3518 private function feedLink( $type, $url, $text ) {
3519 return Html
::element( 'link', [
3520 'rel' => 'alternate',
3521 'type' => "application/$type+xml",
3528 * Add a local or specified stylesheet, with the given media options.
3529 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3531 * @param string $style URL to the file
3532 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3533 * @param string $condition For IE conditional comments, specifying an IE version
3534 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3536 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3539 $options['media'] = $media;
3542 $options['condition'] = $condition;
3545 $options['dir'] = $dir;
3547 $this->styles
[$style] = $options;
3551 * Adds inline CSS styles
3552 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3554 * @param mixed $style_css Inline CSS
3555 * @param string $flip Set to 'flip' to flip the CSS if needed
3557 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3558 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3559 # If wanted, and the interface is right-to-left, flip the CSS
3560 $style_css = CSSJanus
::transform( $style_css, true, false );
3562 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3566 * Build exempt modules and legacy non-ResourceLoader styles.
3568 * @return string|WrappedStringList HTML
3570 protected function buildExemptModules() {
3572 // Things that go after the ResourceLoaderDynamicStyles marker
3575 // We want site, private and user styles to override dynamically added styles from
3576 // general modules, but we want dynamically added styles to override statically added
3577 // style modules. So the order has to be:
3578 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3579 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3580 // - ResourceLoaderDynamicStyles marker
3581 // - site/private/user styles
3583 // Add legacy styles added through addStyle()/addInlineStyle() here
3584 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3586 $chunks[] = Html
::element(
3588 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3591 $separateReq = [ 'site.styles', 'user.styles' ];
3592 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3593 // Combinable modules
3594 $chunks[] = $this->makeResourceLoaderLink(
3595 array_diff( $moduleNames, $separateReq ),
3596 ResourceLoaderModule
::TYPE_STYLES
3599 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3600 // These require their own dedicated request in order to support "@import"
3601 // syntax, which is incompatible with concatenation. (T147667, T37562)
3602 $chunks[] = $this->makeResourceLoaderLink( $name,
3603 ResourceLoaderModule
::TYPE_STYLES
3608 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3614 public function buildCssLinksArray() {
3617 foreach ( $this->styles
as $file => $options ) {
3618 $link = $this->styleLink( $file, $options );
3620 $links[$file] = $link;
3627 * Generate \<link\> tags for stylesheets
3629 * @param string $style URL to the file
3630 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3631 * @return string HTML fragment
3633 protected function styleLink( $style, array $options ) {
3634 if ( isset( $options['dir'] ) ) {
3635 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3640 if ( isset( $options['media'] ) ) {
3641 $media = self
::transformCssMedia( $options['media'] );
3642 if ( is_null( $media ) ) {
3649 if ( substr( $style, 0, 1 ) == '/' ||
3650 substr( $style, 0, 5 ) == 'http:' ||
3651 substr( $style, 0, 6 ) == 'https:' ) {
3654 $config = $this->getConfig();
3655 // Append file hash as query parameter
3656 $url = self
::transformResourcePath(
3658 $config->get( 'StylePath' ) . '/' . $style
3662 $link = Html
::linkedStyle( $url, $media );
3664 if ( isset( $options['condition'] ) ) {
3665 $condition = htmlspecialchars( $options['condition'] );
3666 $link = "<!--[if $condition]>$link<![endif]-->";
3672 * Transform path to web-accessible static resource.
3674 * This is used to add a validation hash as query string.
3675 * This aids various behaviors:
3677 * - Put long Cache-Control max-age headers on responses for improved
3678 * cache performance.
3679 * - Get the correct version of a file as expected by the current page.
3680 * - Instantly get the updated version of a file after deployment.
3682 * Avoid using this for urls included in HTML as otherwise clients may get different
3683 * versions of a resource when navigating the site depending on when the page was cached.
3684 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3685 * an external stylesheet).
3688 * @param Config $config
3689 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3690 * @return string URL
3692 public static function transformResourcePath( Config
$config, $path ) {
3696 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3697 if ( $remotePathPrefix === '' ) {
3698 // The configured base path is required to be empty string for
3699 // wikis in the domain root
3702 $remotePath = $remotePathPrefix;
3704 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3705 // - Path is outside wgResourceBasePath, ignore.
3706 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3709 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3710 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3711 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3712 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3713 $uploadPath = $config->get( 'UploadPath' );
3714 if ( strpos( $path, $uploadPath ) === 0 ) {
3715 $localDir = $config->get( 'UploadDirectory' );
3716 $remotePathPrefix = $remotePath = $uploadPath;
3719 $path = RelPath
::getRelativePath( $path, $remotePath );
3720 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3724 * Utility method for transformResourceFilePath().
3726 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3729 * @param string $remotePathPrefix URL path prefix that points to $localPath
3730 * @param string $localPath File directory exposed at $remotePath
3731 * @param string $file Path to target file relative to $localPath
3732 * @return string URL
3734 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3735 $hash = md5_file( "$localPath/$file" );
3736 if ( $hash === false ) {
3737 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3740 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3744 * Transform "media" attribute based on request parameters
3746 * @param string $media Current value of the "media" attribute
3747 * @return string Modified value of the "media" attribute, or null to skip
3750 public static function transformCssMedia( $media ) {
3753 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3754 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3756 // Switch in on-screen display for media testing
3758 'printable' => 'print',
3759 'handheld' => 'handheld',
3761 foreach ( $switches as $switch => $targetMedia ) {
3762 if ( $wgRequest->getBool( $switch ) ) {
3763 if ( $media == $targetMedia ) {
3765 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3766 /* This regex will not attempt to understand a comma-separated media_query_list
3768 * Example supported values for $media:
3769 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3770 * Example NOT supported value for $media:
3771 * '3d-glasses, screen, print and resolution > 90dpi'
3773 * If it's a print request, we never want any kind of screen stylesheets
3774 * If it's a handheld request (currently the only other choice with a switch),
3775 * we don't want simple 'screen' but we might want screen queries that
3776 * have a max-width or something, so we'll pass all others on and let the
3777 * client do the query.
3779 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3790 * Add a wikitext-formatted message to the output.
3791 * This is equivalent to:
3793 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3795 public function addWikiMsg( /*...*/ ) {
3796 $args = func_get_args();
3797 $name = array_shift( $args );
3798 $this->addWikiMsgArray( $name, $args );
3802 * Add a wikitext-formatted message to the output.
3803 * Like addWikiMsg() except the parameters are taken as an array
3804 * instead of a variable argument list.
3806 * @param string $name
3807 * @param array $args
3809 public function addWikiMsgArray( $name, $args ) {
3810 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3814 * This function takes a number of message/argument specifications, wraps them in
3815 * some overall structure, and then parses the result and adds it to the output.
3817 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3818 * and so on. The subsequent arguments may be either
3819 * 1) strings, in which case they are message names, or
3820 * 2) arrays, in which case, within each array, the first element is the message
3821 * name, and subsequent elements are the parameters to that message.
3823 * Don't use this for messages that are not in the user's interface language.
3827 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3831 * $wgOut->addWikiText( "<div class='error'>\n"
3832 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3834 * The newline after the opening div is needed in some wikitext. See T21226.
3836 * @param string $wrap
3838 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3839 $msgSpecs = func_get_args();
3840 array_shift( $msgSpecs );
3841 $msgSpecs = array_values( $msgSpecs );
3843 foreach ( $msgSpecs as $n => $spec ) {
3844 if ( is_array( $spec ) ) {
3846 $name = array_shift( $args );
3847 if ( isset( $args['options'] ) ) {
3848 unset( $args['options'] );
3850 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3858 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3860 $this->addWikiText( $s );
3864 * Whether the output has a table of contents
3868 public function isTOCEnabled() {
3869 return $this->mEnableTOC
;
3873 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3876 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3878 public function enableSectionEditLinks( $flag = true ) {
3879 wfDeprecated( __METHOD__
, '1.31' );
3885 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3887 public function sectionEditLinksEnabled() {
3888 wfDeprecated( __METHOD__
, '1.31' );
3893 * Helper function to setup the PHP implementation of OOUI to use in this request.
3896 * @param String $skinName The Skin name to determine the correct OOUI theme
3897 * @param String $dir Language direction
3899 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3900 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3901 $theme = $themes[$skinName] ??
$themes['default'];
3902 // For example, 'OOUI\WikimediaUITheme'.
3903 $themeClass = "OOUI\\{$theme}Theme";
3904 OOUI\Theme
::setSingleton( new $themeClass() );
3905 OOUI\Element
::setDefaultDir( $dir );
3909 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3910 * MediaWiki and this OutputPage instance.
3914 public function enableOOUI() {
3916 strtolower( $this->getSkin()->getSkinName() ),
3917 $this->getLanguage()->getDir()
3919 $this->addModuleStyles( [
3920 'oojs-ui-core.styles',
3921 'oojs-ui.styles.indicators',
3922 'oojs-ui.styles.textures',
3923 'mediawiki.widgets.styles',
3924 'oojs-ui.styles.icons-content',
3925 'oojs-ui.styles.icons-alerts',
3926 'oojs-ui.styles.icons-interactions',
3931 * Add Link headers for preloading the wiki's logo.
3935 protected function addLogoPreloadLinkHeaders() {
3936 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3942 if ( !is_array( $logo ) ) {
3943 // No media queries required if we only have one variant
3944 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3948 if ( isset( $logo['svg'] ) ) {
3949 // No media queries required if we only have a 1x and svg variant
3950 // because all preload-capable browsers support SVGs
3951 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3955 foreach ( $logo as $dppx => $src ) {
3956 // Keys are in this format: "1.5x"
3957 $dppx = substr( $dppx, 0, -1 );
3958 $logosPerDppx[$dppx] = $src;
3961 // Because PHP can't have floats as array keys
3962 uksort( $logosPerDppx, function ( $a , $b ) {
3963 $a = floatval( $a );
3964 $b = floatval( $b );
3965 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3969 foreach ( $logosPerDppx as $dppx => $src ) {
3970 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3973 $logosCount = count( $logos );
3974 // Logic must match ResourceLoaderSkinModule:
3975 // - 1x applies to resolution < 1.5dppx
3976 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3977 // - 2x applies to resolution >= 2dppx
3978 // Note that min-resolution and max-resolution are both inclusive.
3979 for ( $i = 0; $i < $logosCount; $i++
) {
3982 // min-resolution is ">=" (larger than or equal to)
3983 // "not min-resolution" is essentially "<"
3984 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3985 } elseif ( $i !== $logosCount - 1 ) {
3987 // Media query expressions can only apply "not" to the entire expression
3988 // (e.g. can't express ">= 1.5 and not >= 2).
3989 // Workaround: Use <= 1.9999 in place of < 2.
3990 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
3991 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3992 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3995 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
3998 $this->addLinkHeader(
3999 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
4005 * Get (and set if not yet set) the CSP nonce.
4007 * This value needs to be included in any <script> tags on the
4010 * @return string|bool Nonce or false to mean don't output nonce
4013 public function getCSPNonce() {
4014 if ( !ContentSecurityPolicy
::isEnabled( $this->getConfig() ) ) {
4017 if ( $this->CSPNonce
=== null ) {
4018 // XXX It might be expensive to generate randomness
4019 // on every request, on Windows.
4020 $rand = random_bytes( 15 );
4021 $this->CSPNonce
= base64_encode( $rand );
4023 return $this->CSPNonce
;