3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use Wikimedia\Rdbms\IResultWrapper
;
27 use Wikimedia\RelPath
;
28 use Wikimedia\WrappedString
;
29 use Wikimedia\WrappedStringList
;
32 * This class should be covered by a general architecture document which does
33 * not exist as of January 2011. This is one of the Core classes and should
34 * be read at least once by any new developers.
36 * This class is used to prepare the final rendering. A skin is then
37 * applied to the output parameters (links, javascript, html, categories ...).
39 * @todo FIXME: Another class handles sending the whole page to the client.
41 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
46 class OutputPage
extends ContextSource
{
47 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
48 protected $mMetatags = [];
51 protected $mLinktags = [];
54 protected $mCanonicalUrl = false;
57 * @var string The contents of <h1> */
58 private $mPageTitle = '';
61 * @var string The displayed title of the page. Different from page title
62 * if overridden by display title magic word or hooks. Can contain safe
63 * HTML. Different from page title which may contain messages such as
64 * "Editing X" which is displayed in h1. This can be used for other places
65 * where the page name is referred on the page.
67 private $displayTitle;
70 * @var string Contains all of the "<body>" content. Should be private we
71 * got set/get accessors and the append() method.
73 public $mBodytext = '';
75 /** @var string Stores contents of "<title>" tag */
76 private $mHTMLtitle = '';
79 * @var bool Is the displayed content related to the source of the
80 * corresponding wiki article.
82 private $mIsArticle = false;
84 /** @var bool Stores "article flag" toggle. */
85 private $mIsArticleRelated = true;
87 /** @var bool Is the content subject to copyright */
88 private $mHasCopyright = false;
91 * @var bool We have to set isPrintable(). Some pages should
92 * never be printed (ex: redirections).
94 private $mPrintable = false;
97 * @var array Contains the page subtitle. Special pages usually have some
98 * links here. Don't confuse with site subtitle added by skins.
100 private $mSubtitle = [];
103 public $mRedirect = '';
106 protected $mStatusCode;
109 * @var string Used for sending cache control.
110 * The whole caching system should probably be moved into its own class.
112 protected $mLastModified = '';
115 protected $mCategoryLinks = [];
118 protected $mCategories = [
124 protected $mIndicators = [];
126 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
127 private $mLanguageLinks = [];
130 * Used for JavaScript (predates ResourceLoader)
131 * @todo We should split JS / CSS.
132 * mScripts content is inserted as is in "<head>" by Skin. This might
133 * contain either a link to a stylesheet or inline CSS.
135 private $mScripts = '';
137 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
138 protected $mInlineStyles = '';
141 * @var string Used by skin template.
142 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
144 public $mPageLinkTitle = '';
146 /** @var array Array of elements in "<head>". Parser might add its own headers! */
147 protected $mHeadItems = [];
149 /** @var array Additional <body> classes; there are also <body> classes from other sources */
150 protected $mAdditionalBodyClasses = [];
153 protected $mModules = [];
156 protected $mModuleStyles = [];
158 /** @var ResourceLoader */
159 protected $mResourceLoader;
161 /** @var ResourceLoaderClientHtml */
164 /** @var ResourceLoaderContext */
165 private $rlClientContext;
168 private $rlExemptStyleModules;
171 protected $mJsConfigVars = [];
174 protected $mTemplateIds = [];
177 protected $mImageTimeKeys = [];
180 public $mRedirectCode = '';
182 protected $mFeedLinksAppendQuery = null;
185 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
186 * @see ResourceLoaderModule::$origin
187 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
189 protected $mAllowedModules = [
190 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
193 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
194 protected $mDoNothing = false;
199 protected $mContainsNewMagic = 0;
202 * lazy initialised, use parserOptions()
205 protected $mParserOptions = null;
208 * Handles the Atom / RSS links.
209 * We probably only support Atom in 2011.
210 * @see $wgAdvertisedFeedTypes
212 private $mFeedLinks = [];
214 // Gwicke work on squid caching? Roughly from 2003.
215 protected $mEnableClientCache = true;
217 /** @var bool Flag if output should only contain the body of the article. */
218 private $mArticleBodyOnly = false;
221 protected $mNewSectionLink = false;
224 protected $mHideNewSectionLink = false;
227 * @var bool Comes from the parser. This was probably made to load CSS/JS
228 * only if we had "<gallery>". Used directly in CategoryPage.php.
229 * Looks like ResourceLoader can replace this.
231 public $mNoGallery = false;
233 /** @var int Cache stuff. Looks like mEnableClientCache */
234 protected $mCdnMaxage = 0;
235 /** @var int Upper limit on mCdnMaxage */
236 protected $mCdnMaxageLimit = INF
;
239 * @var bool Controls if anti-clickjacking / frame-breaking headers will
240 * be sent. This should be done for pages where edit actions are possible.
241 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
243 protected $mPreventClickjacking = true;
245 /** @var int To include the variable {{REVISIONID}} */
246 private $mRevisionId = null;
249 private $mRevisionTimestamp = null;
252 protected $mFileVersion = null;
255 * @var array An array of stylesheet filenames (relative from skins path),
256 * with options for CSS media, IE conditions, and RTL/LTR direction.
257 * For internal use; add settings in the skin via $this->addStyle()
259 * Style again! This seems like a code duplication since we already have
260 * mStyles. This is what makes Open Source amazing.
262 protected $styles = [];
264 private $mIndexPolicy = 'index';
265 private $mFollowPolicy = 'follow';
268 * @var array Headers that cause the cache to vary. Key is header name, value is an array of
269 * options for the Key header.
271 private $mVaryHeader = [
272 'Accept-Encoding' => [ 'match=gzip' ],
276 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
281 private $mRedirectedFrom = null;
284 * Additional key => value data
286 private $mProperties = [];
289 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
291 private $mTarget = null;
294 * @var bool Whether parser output contains a table of contents
296 private $mEnableTOC = false;
299 * @var string|null The URL to send in a <link> element with rel=license
301 private $copyrightUrl;
303 /** @var array Profiling data */
304 private $limitReportJSData = [];
306 /** @var array Map Title to Content */
307 private $contentOverrides = [];
309 /** @var callable[] */
310 private $contentOverrideCallbacks = [];
313 * Link: header contents
315 private $mLinkHeader = [];
318 * @var string The nonce for Content-Security-Policy
323 * @var array A cache of the names of the cookies that will influence the cache
325 private static $cacheVaryCookies = null;
328 * Constructor for OutputPage. This should not be called directly.
329 * Instead a new RequestContext should be created and it will implicitly create
330 * a OutputPage tied to that context.
331 * @param IContextSource $context
333 function __construct( IContextSource
$context ) {
334 $this->setContext( $context );
338 * Redirect to $url rather than displaying the normal page
341 * @param string $responsecode HTTP status code
343 public function redirect( $url, $responsecode = '302' ) {
344 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
345 $this->mRedirect
= str_replace( "\n", '', $url );
346 $this->mRedirectCode
= $responsecode;
350 * Get the URL to redirect to, or an empty string if not redirect URL set
354 public function getRedirect() {
355 return $this->mRedirect
;
359 * Set the copyright URL to send with the output.
360 * Empty string to omit, null to reset.
364 * @param string|null $url
366 public function setCopyrightUrl( $url ) {
367 $this->copyrightUrl
= $url;
371 * Set the HTTP status code to send with the output.
373 * @param int $statusCode
375 public function setStatusCode( $statusCode ) {
376 $this->mStatusCode
= $statusCode;
380 * Add a new "<meta>" tag
381 * To add an http-equiv meta tag, precede the name with "http:"
383 * @param string $name Name of the meta tag
384 * @param string $val Value of the meta tag
386 function addMeta( $name, $val ) {
387 array_push( $this->mMetatags
, [ $name, $val ] );
391 * Returns the current <meta> tags
396 public function getMetaTags() {
397 return $this->mMetatags
;
401 * Add a new \<link\> tag to the page header.
403 * Note: use setCanonicalUrl() for rel=canonical.
405 * @param array $linkarr Associative array of attributes.
407 function addLink( array $linkarr ) {
408 array_push( $this->mLinktags
, $linkarr );
412 * Returns the current <link> tags
417 public function getLinkTags() {
418 return $this->mLinktags
;
422 * Set the URL to be used for the <link rel=canonical>. This should be used
423 * in preference to addLink(), to avoid duplicate link tags.
426 function setCanonicalUrl( $url ) {
427 $this->mCanonicalUrl
= $url;
431 * Returns the URL to be used for the <link rel=canonical> if
435 * @return bool|string
437 public function getCanonicalUrl() {
438 return $this->mCanonicalUrl
;
442 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
443 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
446 * @param string $script Raw HTML
448 function addScript( $script ) {
449 $this->mScripts
.= $script;
453 * Add a JavaScript file to be loaded as `<script>` on this page.
455 * Internal use only. Use OutputPage::addModules() if possible.
457 * @param string $file URL to file (absolute path, protocol-relative, or full url)
458 * @param string|null $unused Previously used to change the cache-busting query parameter
460 public function addScriptFile( $file, $unused = null ) {
461 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
462 // This is not an absolute path, protocol-relative url, or full scheme url,
463 // presumed to be an old call intended to include a file from /w/skins/common,
464 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
465 wfDeprecated( __METHOD__
, '1.24' );
468 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
472 * Add a self-contained script tag with the given contents
473 * Internal use only. Use OutputPage::addModules() if possible.
475 * @param string $script JavaScript text, no script tags
477 public function addInlineScript( $script ) {
478 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
482 * Filter an array of modules to remove insufficiently trustworthy members, and modules
483 * which are no longer registered (eg a page is cached before an extension is disabled)
484 * @param array $modules
485 * @param string|null $position Unused
486 * @param string $type
489 protected function filterModules( array $modules, $position = null,
490 $type = ResourceLoaderModule
::TYPE_COMBINED
492 $resourceLoader = $this->getResourceLoader();
493 $filteredModules = [];
494 foreach ( $modules as $val ) {
495 $module = $resourceLoader->getModule( $val );
496 if ( $module instanceof ResourceLoaderModule
497 && $module->getOrigin() <= $this->getAllowedModules( $type )
499 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
500 $this->warnModuleTargetFilter( $module->getName() );
503 $filteredModules[] = $val;
506 return $filteredModules;
509 private function warnModuleTargetFilter( $moduleName ) {
510 static $warnings = [];
511 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
514 $warnings[$this->mTarget
][$moduleName] = true;
515 $this->getResourceLoader()->getLogger()->debug(
516 'Module "{module}" not loadable on target "{target}".',
518 'module' => $moduleName,
519 'target' => $this->mTarget
,
525 * Get the list of modules to include on this page
527 * @param bool $filter Whether to filter out insufficiently trustworthy modules
528 * @param string|null $position Unused
529 * @param string $param
530 * @param string $type
531 * @return array Array of module names
533 public function getModules( $filter = false, $position = null, $param = 'mModules',
534 $type = ResourceLoaderModule
::TYPE_COMBINED
536 $modules = array_values( array_unique( $this->$param ) );
538 ?
$this->filterModules( $modules, null, $type )
543 * Load one or more ResourceLoader modules on this page.
545 * @param string|array $modules Module name (string) or array of module names
547 public function addModules( $modules ) {
548 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
552 * @deprecated since 1.33 Use getModules() instead.
555 public function getModuleScripts() {
556 wfDeprecated( __METHOD__
, '1.33' );
561 * Get the list of style-only modules to load on this page.
563 * @param bool $filter
564 * @param string|null $position Unused
565 * @return array Array of module names
567 public function getModuleStyles( $filter = false, $position = null ) {
568 return $this->getModules( $filter, null, 'mModuleStyles',
569 ResourceLoaderModule
::TYPE_STYLES
574 * Load the styles of one or more ResourceLoader modules on this page.
576 * Module styles added through this function will be loaded as a stylesheet,
577 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
578 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
580 * @param string|array $modules Module name (string) or array of module names
582 public function addModuleStyles( $modules ) {
583 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
587 * @return null|string ResourceLoader target
589 public function getTarget() {
590 return $this->mTarget
;
594 * Sets ResourceLoader target for load.php links. If null, will be omitted
596 * @param string|null $target
598 public function setTarget( $target ) {
599 $this->mTarget
= $target;
603 * Add a mapping from a LinkTarget to a Content, for things like page preview.
604 * @see self::addContentOverrideCallback()
606 * @param LinkTarget $target
607 * @param Content $content
609 public function addContentOverride( LinkTarget
$target, Content
$content ) {
610 if ( !$this->contentOverrides
) {
611 // Register a callback for $this->contentOverrides on the first call
612 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
613 $key = $target->getNamespace() . ':' . $target->getDBkey();
614 return $this->contentOverrides
[$key] ??
null;
618 $key = $target->getNamespace() . ':' . $target->getDBkey();
619 $this->contentOverrides
[$key] = $content;
623 * Add a callback for mapping from a Title to a Content object, for things
625 * @see ResourceLoaderContext::getContentOverrideCallback()
627 * @param callable $callback
629 public function addContentOverrideCallback( callable
$callback ) {
630 $this->contentOverrideCallbacks
[] = $callback;
634 * Get an array of head items
638 function getHeadItemsArray() {
639 return $this->mHeadItems
;
643 * Add or replace a head item to the output
645 * Whenever possible, use more specific options like ResourceLoader modules,
646 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
647 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
648 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
649 * This would be your very LAST fallback.
651 * @param string $name Item name
652 * @param string $value Raw HTML
654 public function addHeadItem( $name, $value ) {
655 $this->mHeadItems
[$name] = $value;
659 * Add one or more head items to the output
662 * @param string|string[] $values Raw HTML
664 public function addHeadItems( $values ) {
665 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
669 * Check if the header item $name is already set
671 * @param string $name Item name
674 public function hasHeadItem( $name ) {
675 return isset( $this->mHeadItems
[$name] );
679 * Add a class to the <body> element
682 * @param string|string[] $classes One or more classes to add
684 public function addBodyClasses( $classes ) {
685 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
689 * Set whether the output should only contain the body of the article,
690 * without any skin, sidebar, etc.
691 * Used e.g. when calling with "action=render".
693 * @param bool $only Whether to output only the body of the article
695 public function setArticleBodyOnly( $only ) {
696 $this->mArticleBodyOnly
= $only;
700 * Return whether the output will contain only the body of the article
704 public function getArticleBodyOnly() {
705 return $this->mArticleBodyOnly
;
709 * Set an additional output property
712 * @param string $name
713 * @param mixed $value
715 public function setProperty( $name, $value ) {
716 $this->mProperties
[$name] = $value;
720 * Get an additional output property
723 * @param string $name
724 * @return mixed Property value or null if not found
726 public function getProperty( $name ) {
727 return $this->mProperties
[$name] ??
null;
731 * checkLastModified tells the client to use the client-cached page if
732 * possible. If successful, the OutputPage is disabled so that
733 * any future call to OutputPage->output() have no effect.
735 * Side effect: sets mLastModified for Last-Modified header
737 * @param string $timestamp
739 * @return bool True if cache-ok headers was sent.
741 public function checkLastModified( $timestamp ) {
742 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
743 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
746 $config = $this->getConfig();
747 if ( !$config->get( 'CachePages' ) ) {
748 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
752 $timestamp = wfTimestamp( TS_MW
, $timestamp );
754 'page' => $timestamp,
755 'user' => $this->getUser()->getTouched(),
756 'epoch' => $config->get( 'CacheEpoch' )
758 if ( $config->get( 'UseSquid' ) ) {
759 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
761 $config->get( 'SquidMaxage' )
764 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
766 $maxModified = max( $modifiedTimes );
767 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
769 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
770 if ( $clientHeader === false ) {
771 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
775 # IE sends sizes after the date like this:
776 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
777 # this breaks strtotime().
778 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
780 Wikimedia\
suppressWarnings(); // E_STRICT system time warnings
781 $clientHeaderTime = strtotime( $clientHeader );
782 Wikimedia\restoreWarnings
();
783 if ( !$clientHeaderTime ) {
785 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
788 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
792 foreach ( $modifiedTimes as $name => $value ) {
793 if ( $info !== '' ) {
796 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
799 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
800 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
801 wfDebug( __METHOD__
. ": effective Last-Modified: " .
802 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
803 if ( $clientHeaderTime < $maxModified ) {
804 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
809 # Give a 304 Not Modified response code and disable body output
810 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
811 ini_set( 'zlib.output_compression', 0 );
812 $this->getRequest()->response()->statusHeader( 304 );
813 $this->sendCacheControl();
816 // Don't output a compressed blob when using ob_gzhandler;
817 // it's technically against HTTP spec and seems to confuse
818 // Firefox when the response gets split over two packets.
819 wfClearOutputBuffers();
825 * @param int $reqTime Time of request (eg. now)
826 * @param int $maxAge Cache TTL in seconds
827 * @return int Timestamp
829 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
830 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
831 // because even if the wiki page content hasn't changed since, static
832 // resources may have changed (skin HTML, interface messages, urls, etc.)
833 // and must roll-over in a timely manner (T46570)
834 return $reqTime - $maxAge;
838 * Override the last modified timestamp
840 * @param string $timestamp New timestamp, in a format readable by
843 public function setLastModified( $timestamp ) {
844 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
848 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
850 * @param string $policy The literal string to output as the contents of
851 * the meta tag. Will be parsed according to the spec and output in
855 public function setRobotPolicy( $policy ) {
856 $policy = Article
::formatRobotPolicy( $policy );
858 if ( isset( $policy['index'] ) ) {
859 $this->setIndexPolicy( $policy['index'] );
861 if ( isset( $policy['follow'] ) ) {
862 $this->setFollowPolicy( $policy['follow'] );
867 * Set the index policy for the page, but leave the follow policy un-
870 * @param string $policy Either 'index' or 'noindex'.
873 public function setIndexPolicy( $policy ) {
874 $policy = trim( $policy );
875 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
876 $this->mIndexPolicy
= $policy;
881 * Set the follow policy for the page, but leave the index policy un-
884 * @param string $policy Either 'follow' or 'nofollow'.
887 public function setFollowPolicy( $policy ) {
888 $policy = trim( $policy );
889 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
890 $this->mFollowPolicy
= $policy;
895 * "HTML title" means the contents of "<title>".
896 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
898 * @param string|Message $name
900 public function setHTMLTitle( $name ) {
901 if ( $name instanceof Message
) {
902 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
904 $this->mHTMLtitle
= $name;
909 * Return the "HTML title", i.e. the content of the "<title>" tag.
913 public function getHTMLTitle() {
914 return $this->mHTMLtitle
;
918 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
922 public function setRedirectedFrom( $t ) {
923 $this->mRedirectedFrom
= $t;
927 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
928 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
929 * but not bad tags like \<script\>. This function automatically sets
930 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
931 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
932 * good tags like \<i\> will be dropped entirely.
934 * @param string|Message $name
935 * @param-taint $name tainted
936 * Phan-taint-check gets very confused by $name being either a string or a Message
938 public function setPageTitle( $name ) {
939 if ( $name instanceof Message
) {
940 $name = $name->setContext( $this->getContext() )->text();
943 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
944 # but leave "<i>foobar</i>" alone
945 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
946 $this->mPageTitle
= $nameWithTags;
948 # change "<i>foo&bar</i>" to "foo&bar"
950 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer
::stripAllTags( $nameWithTags ) )
951 ->inContentLanguage()
956 * Return the "page title", i.e. the content of the \<h1\> tag.
960 public function getPageTitle() {
961 return $this->mPageTitle
;
965 * Same as page title but only contains name of the page, not any other text.
968 * @param string $html Page title text.
969 * @see OutputPage::setPageTitle
971 public function setDisplayTitle( $html ) {
972 $this->displayTitle
= $html;
976 * Returns page display title.
978 * Performs some normalization, but this not as strict the magic word.
981 * @return string HTML
983 public function getDisplayTitle() {
984 $html = $this->displayTitle
;
985 if ( $html === null ) {
986 $html = $this->getTitle()->getPrefixedText();
989 return Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $html ) );
993 * Returns page display title without namespace prefix if possible.
996 * @return string HTML
998 public function getUnprefixedDisplayTitle() {
999 $text = $this->getDisplayTitle();
1000 $nsPrefix = $this->getTitle()->getNsText() . ':';
1001 $prefix = preg_quote( $nsPrefix, '/' );
1003 return preg_replace( "/^$prefix/i", '', $text );
1007 * Set the Title object to use
1011 public function setTitle( Title
$t ) {
1012 $this->getContext()->setTitle( $t );
1016 * Replace the subtitle with $str
1018 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1020 public function setSubtitle( $str ) {
1021 $this->clearSubtitle();
1022 $this->addSubtitle( $str );
1026 * Add $str to the subtitle
1028 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1030 public function addSubtitle( $str ) {
1031 if ( $str instanceof Message
) {
1032 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1034 $this->mSubtitle
[] = $str;
1039 * Build message object for a subtitle containing a backlink to a page
1041 * @param Title $title Title to link to
1042 * @param array $query Array of additional parameters to include in the link
1046 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1047 if ( $title->isRedirect() ) {
1048 $query['redirect'] = 'no';
1050 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1051 return wfMessage( 'backlinksubtitle' )
1052 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1056 * Add a subtitle containing a backlink to a page
1058 * @param Title $title Title to link to
1059 * @param array $query Array of additional parameters to include in the link
1061 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1062 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1066 * Clear the subtitles
1068 public function clearSubtitle() {
1069 $this->mSubtitle
= [];
1077 public function getSubtitle() {
1078 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1082 * Set the page as printable, i.e. it'll be displayed with all
1083 * print styles included
1085 public function setPrintable() {
1086 $this->mPrintable
= true;
1090 * Return whether the page is "printable"
1094 public function isPrintable() {
1095 return $this->mPrintable
;
1099 * Disable output completely, i.e. calling output() will have no effect
1101 public function disable() {
1102 $this->mDoNothing
= true;
1106 * Return whether the output will be completely disabled
1110 public function isDisabled() {
1111 return $this->mDoNothing
;
1115 * Show an "add new section" link?
1119 public function showNewSectionLink() {
1120 return $this->mNewSectionLink
;
1124 * Forcibly hide the new section link?
1128 public function forceHideNewSectionLink() {
1129 return $this->mHideNewSectionLink
;
1133 * Add or remove feed links in the page header
1134 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1135 * for the new version
1136 * @see addFeedLink()
1138 * @param bool $show True: add default feeds, false: remove all feeds
1140 public function setSyndicated( $show = true ) {
1142 $this->setFeedAppendQuery( false );
1144 $this->mFeedLinks
= [];
1149 * Return effective list of advertised feed types
1150 * @see addFeedLink()
1152 * @return array Array of feed type names ( 'rss', 'atom' )
1154 protected function getAdvertisedFeedTypes() {
1155 if ( $this->getConfig()->get( 'Feed' ) ) {
1156 return $this->getConfig()->get( 'AdvertisedFeedTypes' );
1163 * Add default feeds to the page header
1164 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1165 * for the new version
1166 * @see addFeedLink()
1168 * @param string $val Query to append to feed links or false to output
1171 public function setFeedAppendQuery( $val ) {
1172 $this->mFeedLinks
= [];
1174 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1175 $query = "feed=$type";
1176 if ( is_string( $val ) ) {
1177 $query .= '&' . $val;
1179 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1184 * Add a feed link to the page header
1186 * @param string $format Feed type, should be a key of $wgFeedClasses
1187 * @param string $href URL
1189 public function addFeedLink( $format, $href ) {
1190 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1191 $this->mFeedLinks
[$format] = $href;
1196 * Should we output feed links for this page?
1199 public function isSyndicated() {
1200 return count( $this->mFeedLinks
) > 0;
1204 * Return URLs for each supported syndication format for this page.
1205 * @return array Associating format keys with URLs
1207 public function getSyndicationLinks() {
1208 return $this->mFeedLinks
;
1212 * Will currently always return null
1216 public function getFeedAppendQuery() {
1217 return $this->mFeedLinksAppendQuery
;
1221 * Set whether the displayed content is related to the source of the
1222 * corresponding article on the wiki
1223 * Setting true will cause the change "article related" toggle to true
1225 * @param bool $newVal
1227 public function setArticleFlag( $newVal ) {
1228 $this->mIsArticle
= $newVal;
1230 $this->mIsArticleRelated
= $newVal;
1235 * Return whether the content displayed page is related to the source of
1236 * the corresponding article on the wiki
1240 public function isArticle() {
1241 return $this->mIsArticle
;
1245 * Set whether this page is related an article on the wiki
1246 * Setting false will cause the change of "article flag" toggle to false
1248 * @param bool $newVal
1250 public function setArticleRelated( $newVal ) {
1251 $this->mIsArticleRelated
= $newVal;
1253 $this->mIsArticle
= false;
1258 * Return whether this page is related an article on the wiki
1262 public function isArticleRelated() {
1263 return $this->mIsArticleRelated
;
1267 * Set whether the standard copyright should be shown for the current page.
1269 * @param bool $hasCopyright
1271 public function setCopyright( $hasCopyright ) {
1272 $this->mHasCopyright
= $hasCopyright;
1276 * Return whether the standard copyright should be shown for the current page.
1277 * By default, it is true for all articles but other pages
1278 * can signal it by using setCopyright( true ).
1280 * Used by SkinTemplate to decided whether to show the copyright.
1284 public function showsCopyright() {
1285 return $this->isArticle() ||
$this->mHasCopyright
;
1289 * Add new language links
1291 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1292 * (e.g. 'fr:Test page')
1294 public function addLanguageLinks( array $newLinkArray ) {
1295 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1299 * Reset the language links and add new language links
1301 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1302 * (e.g. 'fr:Test page')
1304 public function setLanguageLinks( array $newLinkArray ) {
1305 $this->mLanguageLinks
= $newLinkArray;
1309 * Get the list of language links
1311 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1313 public function getLanguageLinks() {
1314 return $this->mLanguageLinks
;
1318 * Add an array of categories, with names in the keys
1320 * @param array $categories Mapping category name => sort key
1322 public function addCategoryLinks( array $categories ) {
1323 if ( !$categories ) {
1327 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1329 # Set all the values to 'normal'.
1330 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1332 # Mark hidden categories
1333 foreach ( $res as $row ) {
1334 if ( isset( $row->pp_value
) ) {
1335 $categories[$row->page_title
] = 'hidden';
1339 // Avoid PHP 7.1 warning of passing $this by reference
1340 $outputPage = $this;
1341 # Add the remaining categories to the skin
1343 'OutputPageMakeCategoryLinks',
1344 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1346 $services = MediaWikiServices
::getInstance();
1347 $linkRenderer = $services->getLinkRenderer();
1348 foreach ( $categories as $category => $type ) {
1349 // array keys will cast numeric category names to ints, so cast back to string
1350 $category = (string)$category;
1351 $origcategory = $category;
1352 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1356 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1357 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1360 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1361 $this->mCategories
[$type][] = $title->getText();
1362 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1368 * @param array $categories
1369 * @return bool|IResultWrapper
1371 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1372 # Add the links to a LinkBatch
1373 $arr = [ NS_CATEGORY
=> $categories ];
1374 $lb = new LinkBatch
;
1375 $lb->setArray( $arr );
1377 # Fetch existence plus the hiddencat property
1378 $dbr = wfGetDB( DB_REPLICA
);
1379 $fields = array_merge(
1380 LinkCache
::getSelectFields(),
1381 [ 'page_namespace', 'page_title', 'pp_value' ]
1384 $res = $dbr->select( [ 'page', 'page_props' ],
1386 $lb->constructSet( 'page', $dbr ),
1389 [ 'page_props' => [ 'LEFT JOIN', [
1390 'pp_propname' => 'hiddencat',
1395 # Add the results to the link cache
1396 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1397 $lb->addResultToCache( $linkCache, $res );
1403 * Reset the category links (but not the category list) and add $categories
1405 * @param array $categories Mapping category name => sort key
1407 public function setCategoryLinks( array $categories ) {
1408 $this->mCategoryLinks
= [];
1409 $this->addCategoryLinks( $categories );
1413 * Get the list of category links, in a 2-D array with the following format:
1414 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1415 * hidden categories) and $link a HTML fragment with a link to the category
1420 public function getCategoryLinks() {
1421 return $this->mCategoryLinks
;
1425 * Get the list of category names this page belongs to.
1427 * @param string $type The type of categories which should be returned. Possible values:
1428 * * all: all categories of all types
1429 * * hidden: only the hidden categories
1430 * * normal: all categories, except hidden categories
1431 * @return array Array of strings
1433 public function getCategories( $type = 'all' ) {
1434 if ( $type === 'all' ) {
1435 $allCategories = [];
1436 foreach ( $this->mCategories
as $categories ) {
1437 $allCategories = array_merge( $allCategories, $categories );
1439 return $allCategories;
1441 if ( !isset( $this->mCategories
[$type] ) ) {
1442 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1444 return $this->mCategories
[$type];
1448 * Add an array of indicators, with their identifiers as array
1449 * keys and HTML contents as values.
1451 * In case of duplicate keys, existing values are overwritten.
1453 * @param array $indicators
1456 public function setIndicators( array $indicators ) {
1457 $this->mIndicators
= $indicators +
$this->mIndicators
;
1458 // Keep ordered by key
1459 ksort( $this->mIndicators
);
1463 * Get the indicators associated with this page.
1465 * The array will be internally ordered by item keys.
1467 * @return array Keys: identifiers, values: HTML contents
1470 public function getIndicators() {
1471 return $this->mIndicators
;
1475 * Adds help link with an icon via page indicators.
1476 * Link target can be overridden by a local message containing a wikilink:
1477 * the message key is: lowercase action or special page name + '-helppage'.
1478 * @param string $to Target MediaWiki.org page title or encoded URL.
1479 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1482 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1483 $this->addModuleStyles( 'mediawiki.helplink' );
1484 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1486 if ( $overrideBaseUrl ) {
1489 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1490 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1493 $link = Html
::rawElement(
1497 'target' => '_blank',
1498 'class' => 'mw-helplink',
1503 $this->setIndicators( [ 'mw-helplink' => $link ] );
1507 * Do not allow scripts which can be modified by wiki users to load on this page;
1508 * only allow scripts bundled with, or generated by, the software.
1509 * Site-wide styles are controlled by a config setting, since they can be
1510 * used to create a custom skin/theme, but not user-specific ones.
1512 * @todo this should be given a more accurate name
1514 public function disallowUserJs() {
1515 $this->reduceAllowedModules(
1516 ResourceLoaderModule
::TYPE_SCRIPTS
,
1517 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1520 // Site-wide styles are controlled by a config setting, see T73621
1521 // for background on why. User styles are never allowed.
1522 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1523 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1525 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1527 $this->reduceAllowedModules(
1528 ResourceLoaderModule
::TYPE_STYLES
,
1534 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1535 * @see ResourceLoaderModule::$origin
1536 * @param string $type ResourceLoaderModule TYPE_ constant
1537 * @return int ResourceLoaderModule ORIGIN_ class constant
1539 public function getAllowedModules( $type ) {
1540 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1541 return min( array_values( $this->mAllowedModules
) );
1543 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1548 * Limit the highest level of CSS/JS untrustworthiness allowed.
1550 * If passed the same or a higher level than the current level of untrustworthiness set, the
1551 * level will remain unchanged.
1553 * @param string $type
1554 * @param int $level ResourceLoaderModule class constant
1556 public function reduceAllowedModules( $type, $level ) {
1557 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1561 * Prepend $text to the body HTML
1563 * @param string $text HTML
1565 public function prependHTML( $text ) {
1566 $this->mBodytext
= $text . $this->mBodytext
;
1570 * Append $text to the body HTML
1572 * @param string $text HTML
1574 public function addHTML( $text ) {
1575 $this->mBodytext
.= $text;
1579 * Shortcut for adding an Html::element via addHTML.
1583 * @param string $element
1584 * @param array $attribs
1585 * @param string $contents
1587 public function addElement( $element, array $attribs = [], $contents = '' ) {
1588 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1592 * Clear the body HTML
1594 public function clearHTML() {
1595 $this->mBodytext
= '';
1601 * @return string HTML
1603 public function getHTML() {
1604 return $this->mBodytext
;
1608 * Get/set the ParserOptions object to use for wikitext parsing
1610 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1611 * current ParserOption object. This parameter is deprecated since 1.31.
1612 * @return ParserOptions
1614 public function parserOptions( $options = null ) {
1615 if ( $options !== null ) {
1616 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1619 if ( $options !== null && !empty( $options->isBogus
) ) {
1620 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1621 // been changed somehow, and keep it if so.
1622 $anonPO = ParserOptions
::newFromAnon();
1623 $anonPO->setAllowUnsafeRawHtml( false );
1624 if ( !$options->matches( $anonPO ) ) {
1625 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1626 $options->isBogus
= false;
1630 if ( !$this->mParserOptions
) {
1631 if ( !$this->getUser()->isSafeToLoad() ) {
1632 // $wgUser isn't unstubbable yet, so don't try to get a
1633 // ParserOptions for it. And don't cache this ParserOptions
1635 $po = ParserOptions
::newFromAnon();
1636 $po->setAllowUnsafeRawHtml( false );
1637 $po->isBogus
= true;
1638 if ( $options !== null ) {
1639 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1644 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1645 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1648 if ( $options !== null && !empty( $options->isBogus
) ) {
1649 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1651 return wfSetVar( $this->mParserOptions
, null, true );
1653 return wfSetVar( $this->mParserOptions
, $options );
1658 * Set the revision ID which will be seen by the wiki text parser
1659 * for things such as embedded {{REVISIONID}} variable use.
1661 * @param int|null $revid A positive integer, or null
1662 * @return mixed Previous value
1664 public function setRevisionId( $revid ) {
1665 $val = is_null( $revid ) ?
null : intval( $revid );
1666 return wfSetVar( $this->mRevisionId
, $val, true );
1670 * Get the displayed revision ID
1674 public function getRevisionId() {
1675 return $this->mRevisionId
;
1679 * Set the timestamp of the revision which will be displayed. This is used
1680 * to avoid a extra DB call in Skin::lastModified().
1682 * @param string|null $timestamp
1683 * @return mixed Previous value
1685 public function setRevisionTimestamp( $timestamp ) {
1686 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1690 * Get the timestamp of displayed revision.
1691 * This will be null if not filled by setRevisionTimestamp().
1693 * @return string|null
1695 public function getRevisionTimestamp() {
1696 return $this->mRevisionTimestamp
;
1700 * Set the displayed file version
1702 * @param File|null $file
1703 * @return mixed Previous value
1705 public function setFileVersion( $file ) {
1707 if ( $file instanceof File
&& $file->exists() ) {
1708 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1710 return wfSetVar( $this->mFileVersion
, $val, true );
1714 * Get the displayed file version
1716 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1718 public function getFileVersion() {
1719 return $this->mFileVersion
;
1723 * Get the templates used on this page
1725 * @return array (namespace => dbKey => revId)
1728 public function getTemplateIds() {
1729 return $this->mTemplateIds
;
1733 * Get the files used on this page
1735 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1738 public function getFileSearchOptions() {
1739 return $this->mImageTimeKeys
;
1743 * Convert wikitext to HTML and add it to the buffer
1744 * Default assumes that the current page title will be used.
1746 * @param string $text
1747 * @param bool $linestart Is this the start of a line?
1748 * @param bool $interface Is this text in the user interface language?
1749 * @throws MWException
1750 * @deprecated since 1.32 due to untidy output; use
1751 * addWikiTextAsInterface() if $interface is default value or true,
1752 * or else addWikiTextAsContent() if $interface is false.
1754 public function addWikiText( $text, $linestart = true, $interface = true ) {
1755 wfDeprecated( __METHOD__
, '1.32' );
1756 $title = $this->getTitle();
1758 throw new MWException( 'Title is null' );
1760 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, $interface );
1764 * Convert wikitext *in the user interface language* to HTML and
1765 * add it to the buffer. The result will not be
1766 * language-converted, as user interface messages are already
1767 * localized into a specific variant. Assumes that the current
1768 * page title will be used if optional $title is not
1769 * provided. Output will be tidy.
1771 * @param string $text Wikitext in the user interface language
1772 * @param bool $linestart Is this the start of a line? (Defaults to true)
1773 * @param Title|null $title Optional title to use; default of `null`
1774 * means use current page title.
1775 * @throws MWException if $title is not provided and OutputPage::getTitle()
1779 public function addWikiTextAsInterface(
1780 $text, $linestart = true, Title
$title = null
1782 if ( $title === null ) {
1783 $title = $this->getTitle();
1786 throw new MWException( 'Title is null' );
1788 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/true );
1792 * Convert wikitext *in the user interface language* to HTML and
1793 * add it to the buffer with a `<div class="$wrapperClass">`
1794 * wrapper. The result will not be language-converted, as user
1795 * interface messages as already localized into a specific
1796 * variant. The $text will be parsed in start-of-line context.
1797 * Output will be tidy.
1799 * @param string $wrapperClass The class attribute value for the <div>
1800 * wrapper in the output HTML
1801 * @param string $text Wikitext in the user interface language
1804 public function wrapWikiTextAsInterface(
1805 $wrapperClass, $text
1807 $this->addWikiTextTitleInternal(
1808 $text, $this->getTitle(),
1809 /*linestart*/true, /*tidy*/true, /*interface*/true,
1815 * Convert wikitext *in the page content language* to HTML and add
1816 * it to the buffer. The result with be language-converted to the
1817 * user's preferred variant. Assumes that the current page title
1818 * will be used if optional $title is not provided. Output will be
1821 * @param string $text Wikitext in the page content language
1822 * @param bool $linestart Is this the start of a line? (Defaults to true)
1823 * @param Title|null $title Optional title to use; default of `null`
1824 * means use current page title.
1825 * @throws MWException if $title is not provided and OutputPage::getTitle()
1829 public function addWikiTextAsContent(
1830 $text, $linestart = true, Title
$title = null
1832 if ( $title === null ) {
1833 $title = $this->getTitle();
1836 throw new MWException( 'Title is null' );
1838 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1842 * Add wikitext with a custom Title object
1844 * @param string $text Wikitext
1845 * @param Title $title
1846 * @param bool $linestart Is this the start of a line?
1847 * @deprecated since 1.32 due to untidy output; use
1848 * addWikiTextAsInterface()
1850 public function addWikiTextWithTitle( $text, Title
$title, $linestart = true ) {
1851 wfDeprecated( __METHOD__
, '1.32' );
1852 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, /*interface*/false );
1856 * Add wikitext *in content language* with a custom Title object.
1857 * Output will be tidy.
1859 * @param string $text Wikitext in content language
1860 * @param Title $title
1861 * @param bool $linestart Is this the start of a line?
1862 * @deprecated since 1.32 to rename methods consistently; use
1863 * addWikiTextAsContent()
1865 function addWikiTextTitleTidy( $text, Title
$title, $linestart = true ) {
1866 wfDeprecated( __METHOD__
, '1.32' );
1867 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1871 * Add wikitext *in content language*. Output will be tidy.
1873 * @param string $text Wikitext in content language
1874 * @param bool $linestart Is this the start of a line?
1875 * @deprecated since 1.32 to rename methods consistently; use
1876 * addWikiTextAsContent()
1878 public function addWikiTextTidy( $text, $linestart = true ) {
1879 wfDeprecated( __METHOD__
, '1.32' );
1880 $title = $this->getTitle();
1882 throw new MWException( 'Title is null' );
1884 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1888 * Add wikitext with a custom Title object.
1889 * Output is unwrapped.
1891 * @param string $text Wikitext
1892 * @param Title $title
1893 * @param bool $linestart Is this the start of a line?
1894 * @param bool $tidy Whether to use tidy.
1895 * Setting this to false (or omitting it) is deprecated
1896 * since 1.32; all wikitext should be tidied.
1897 * For backwards-compatibility with prior MW releases,
1898 * you may wish to invoke this method but set $tidy=true;
1899 * this will result in equivalent output to the non-deprecated
1900 * addWikiTextAsContent()/addWikiTextAsInterface() methods.
1901 * @param bool $interface Whether it is an interface message
1902 * (for example disables conversion)
1903 * @deprecated since 1.32, use addWikiTextAsContent() or
1904 * addWikiTextAsInterface() (depending on $interface)
1906 public function addWikiTextTitle( $text, Title
$title, $linestart,
1907 $tidy = false, $interface = false
1909 wfDeprecated( __METHOD__
, '1.32' );
1910 return $this->addWikiTextTitleInternal( $text, $title, $linestart, $tidy, $interface );
1914 * Add wikitext with a custom Title object.
1915 * Output is unwrapped.
1917 * @param string $text Wikitext
1918 * @param Title $title
1919 * @param bool $linestart Is this the start of a line?
1920 * @param bool $tidy Whether to use tidy.
1921 * Setting this to false (or omitting it) is deprecated
1922 * since 1.32; all wikitext should be tidied.
1923 * @param bool $interface Whether it is an interface message
1924 * (for example disables conversion)
1925 * @param string $wrapperClass if not empty, wraps the output in
1926 * a `<div class="$wrapperClass">`
1929 private function addWikiTextTitleInternal(
1930 $text, Title
$title, $linestart, $tidy, $interface, $wrapperClass = null
1933 wfDeprecated( 'disabling tidy', '1.32' );
1936 $parserOutput = $this->parseInternal(
1937 $text, $title, $linestart, $tidy, $interface, /*language*/null
1940 $this->addParserOutput( $parserOutput, [
1941 'enableSectionEditLinks' => false,
1942 'wrapperDivClass' => $wrapperClass ??
'',
1947 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1948 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1952 * @param ParserOutput $parserOutput
1954 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1955 $this->mLanguageLinks
=
1956 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1957 $this->addCategoryLinks( $parserOutput->getCategories() );
1958 $this->setIndicators( $parserOutput->getIndicators() );
1959 $this->mNewSectionLink
= $parserOutput->getNewSection();
1960 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1962 if ( !$parserOutput->isCacheable() ) {
1963 $this->enableClientCache( false );
1965 $this->mNoGallery
= $parserOutput->getNoGallery();
1966 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1967 $this->addModules( $parserOutput->getModules() );
1968 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1969 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1970 $this->mPreventClickjacking
= $this->mPreventClickjacking
1971 ||
$parserOutput->preventClickjacking();
1973 // Template versioning...
1974 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1975 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1976 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1978 $this->mTemplateIds
[$ns] = $dbks;
1981 // File versioning...
1982 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1983 $this->mImageTimeKeys
[$dbk] = $data;
1986 // Hooks registered in the object
1987 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1988 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1989 list( $hookName, $data ) = $hookInfo;
1990 if ( isset( $parserOutputHooks[$hookName] ) ) {
1991 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1995 // Enable OOUI if requested via ParserOutput
1996 if ( $parserOutput->getEnableOOUI() ) {
1997 $this->enableOOUI();
2000 // Include parser limit report
2001 if ( !$this->limitReportJSData
) {
2002 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
2005 // Link flags are ignored for now, but may in the future be
2006 // used to mark individual language links.
2008 // Avoid PHP 7.1 warning of passing $this by reference
2009 $outputPage = $this;
2010 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
2011 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
2013 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2014 // so that extensions may modify ParserOutput to toggle TOC.
2015 // This cannot be moved to addParserOutputText because that is not
2016 // called by EditPage for Preview.
2017 if ( $parserOutput->getTOCHTML() ) {
2018 $this->mEnableTOC
= true;
2023 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2024 * ParserOutput object, without any other metadata.
2027 * @param ParserOutput $parserOutput
2028 * @param array $poOptions Options to ParserOutput::getText()
2030 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
2031 $this->addParserOutputText( $parserOutput, $poOptions );
2033 $this->addModules( $parserOutput->getModules() );
2034 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2036 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2040 * Add the HTML associated with a ParserOutput object, without any metadata.
2043 * @param ParserOutput $parserOutput
2044 * @param array $poOptions Options to ParserOutput::getText()
2046 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
2047 $text = $parserOutput->getText( $poOptions );
2048 // Avoid PHP 7.1 warning of passing $this by reference
2049 $outputPage = $this;
2050 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
2051 $this->addHTML( $text );
2055 * Add everything from a ParserOutput object.
2057 * @param ParserOutput $parserOutput
2058 * @param array $poOptions Options to ParserOutput::getText()
2060 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
2061 $this->addParserOutputMetadata( $parserOutput );
2062 $this->addParserOutputText( $parserOutput, $poOptions );
2066 * Add the output of a QuickTemplate to the output buffer
2068 * @param QuickTemplate &$template
2070 public function addTemplate( &$template ) {
2071 $this->addHTML( $template->getHTML() );
2075 * Parse wikitext and return the HTML.
2077 * @todo The output is wrapped in a <div> iff $interface is false; it's
2078 * probably best to always strip the wrapper.
2080 * @param string $text
2081 * @param bool $linestart Is this the start of a line?
2082 * @param bool $interface Use interface language (instead of content language) while parsing
2083 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2084 * LanguageConverter.
2085 * @param Language|null $language Target language object, will override $interface
2086 * @throws MWException
2087 * @return string HTML
2088 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
2089 * use parseAsContent() if $interface is default value or false, or else
2090 * parseAsInterface() if $interface is true.
2092 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
2093 wfDeprecated( __METHOD__
, '1.33' );
2094 return $this->parseInternal(
2095 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
2097 'enableSectionEditLinks' => false,
2102 * Parse wikitext *in the page content language* and return the HTML.
2103 * The result will be language-converted to the user's preferred variant.
2104 * Output will be tidy.
2106 * @param string $text Wikitext in the page content language
2107 * @param bool $linestart Is this the start of a line? (Defaults to true)
2108 * @throws MWException
2109 * @return string HTML
2112 public function parseAsContent( $text, $linestart = true ) {
2113 return $this->parseInternal(
2114 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2116 'enableSectionEditLinks' => false,
2117 'wrapperDivClass' => ''
2122 * Parse wikitext *in the user interface language* and return the HTML.
2123 * The result will not be language-converted, as user interface messages
2124 * are already localized into a specific variant.
2125 * Output will be tidy.
2127 * @param string $text Wikitext in the user interface language
2128 * @param bool $linestart Is this the start of a line? (Defaults to true)
2129 * @throws MWException
2130 * @return string HTML
2133 public function parseAsInterface( $text, $linestart = true ) {
2134 return $this->parseInternal(
2135 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2137 'enableSectionEditLinks' => false,
2138 'wrapperDivClass' => ''
2143 * Parse wikitext *in the user interface language*, strip
2144 * paragraph wrapper, and return the HTML.
2145 * The result will not be language-converted, as user interface messages
2146 * are already localized into a specific variant.
2147 * Output will be tidy. Outer paragraph wrapper will only be stripped
2148 * if the result is a single paragraph.
2150 * @param string $text Wikitext in the user interface language
2151 * @param bool $linestart Is this the start of a line? (Defaults to true)
2152 * @throws MWException
2153 * @return string HTML
2156 public function parseInlineAsInterface( $text, $linestart = true ) {
2157 return Parser
::stripOuterParagraph(
2158 $this->parseAsInterface( $text, $linestart )
2163 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2165 * @param string $text
2166 * @param bool $linestart Is this the start of a line?
2167 * @param bool $interface Use interface language (instead of content language) while parsing
2168 * language sensitive magic words like GRAMMAR and PLURAL
2169 * @return string HTML
2170 * @deprecated since 1.32, due to untidy output and confusing default
2171 * for $interface. Use parseInlineAsInterface() if $interface is
2172 * the default value or false, or else use
2173 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2175 public function parseInline( $text, $linestart = true, $interface = false ) {
2176 wfDeprecated( __METHOD__
, '1.33' );
2177 $parsed = $this->parseInternal(
2178 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2180 'enableSectionEditLinks' => false,
2181 'wrapperDivClass' => '', /* no wrapper div */
2183 return Parser
::stripOuterParagraph( $parsed );
2187 * Parse wikitext and return the HTML (internal implementation helper)
2189 * @param string $text
2190 * @param Title $title The title to use
2191 * @param bool $linestart Is this the start of a line?
2192 * @param bool $tidy Whether the output should be tidied
2193 * @param bool $interface Use interface language (instead of content language) while parsing
2194 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2195 * LanguageConverter.
2196 * @param Language|null $language Target language object, will override $interface
2197 * @throws MWException
2198 * @return ParserOutput
2200 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2203 if ( is_null( $title ) ) {
2204 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2207 $popts = $this->parserOptions();
2208 $oldTidy = $popts->setTidy( $tidy );
2209 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2211 if ( $language !== null ) {
2212 $oldLang = $popts->setTargetLanguage( $language );
2215 $parserOutput = $wgParser->getFreshParser()->parse(
2216 $text, $title, $popts,
2217 $linestart, true, $this->mRevisionId
2220 $popts->setTidy( $oldTidy );
2221 $popts->setInterfaceMessage( $oldInterface );
2223 if ( $language !== null ) {
2224 $popts->setTargetLanguage( $oldLang );
2227 return $parserOutput;
2231 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2233 * @param int $maxage Maximum cache time on the CDN, in seconds.
2235 public function setCdnMaxage( $maxage ) {
2236 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2240 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2241 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2242 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2245 * @param int $maxage Maximum cache time on the CDN, in seconds
2248 public function lowerCdnMaxage( $maxage ) {
2249 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2250 $this->setCdnMaxage( $this->mCdnMaxage
);
2254 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2256 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2257 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2258 * TTL is 90% of the age of the object, subject to the min and max.
2260 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2261 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2262 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2265 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2266 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2267 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2269 if ( $mtime === null ||
$mtime === false ) {
2270 return $minTTL; // entity does not exist
2273 $age = MWTimestamp
::time() - wfTimestamp( TS_UNIX
, $mtime );
2274 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2275 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2277 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2281 * Use enableClientCache(false) to force it to send nocache headers
2283 * @param bool|null $state New value, or null to not set the value
2285 * @return bool Old value
2287 public function enableClientCache( $state ) {
2288 return wfSetVar( $this->mEnableClientCache
, $state );
2292 * Get the list of cookie names that will influence the cache
2296 function getCacheVaryCookies() {
2297 if ( self
::$cacheVaryCookies === null ) {
2298 $config = $this->getConfig();
2299 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2300 SessionManager
::singleton()->getVaryCookies(),
2304 $config->get( 'CacheVaryCookies' )
2306 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2308 return self
::$cacheVaryCookies;
2312 * Check if the request has a cache-varying cookie header
2313 * If it does, it's very important that we don't allow public caching
2317 function haveCacheVaryCookies() {
2318 $request = $this->getRequest();
2319 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2320 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2321 wfDebug( __METHOD__
. ": found $cookieName\n" );
2325 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2330 * Add an HTTP header that will influence on the cache
2332 * @param string $header Header name
2333 * @param string[]|null $option Options for the Key header. See
2334 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2335 * for the list of valid options.
2337 public function addVaryHeader( $header, array $option = null ) {
2338 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2339 $this->mVaryHeader
[$header] = [];
2341 if ( !is_array( $option ) ) {
2344 $this->mVaryHeader
[$header] =
2345 array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2349 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2350 * such as Accept-Encoding or Cookie
2354 public function getVaryHeader() {
2355 // If we vary on cookies, let's make sure it's always included here too.
2356 if ( $this->getCacheVaryCookies() ) {
2357 $this->addVaryHeader( 'Cookie' );
2360 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2361 $this->addVaryHeader( $header, $options );
2363 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2367 * Add an HTTP Link: header
2369 * @param string $header Header value
2371 public function addLinkHeader( $header ) {
2372 $this->mLinkHeader
[] = $header;
2376 * Return a Link: header. Based on the values of $mLinkHeader.
2380 public function getLinkHeader() {
2381 if ( !$this->mLinkHeader
) {
2385 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2389 * Get a complete Key header
2392 * @deprecated in 1.32; the IETF spec for this header expired w/o becoming
2395 public function getKeyHeader() {
2396 wfDeprecated( '$wgUseKeyHeader', '1.32' );
2398 $cvCookies = $this->getCacheVaryCookies();
2400 $cookiesOption = [];
2401 foreach ( $cvCookies as $cookieName ) {
2402 $cookiesOption[] = 'param=' . $cookieName;
2404 $this->addVaryHeader( 'Cookie', $cookiesOption );
2406 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2407 $this->addVaryHeader( $header, $options );
2411 foreach ( $this->mVaryHeader
as $header => $option ) {
2412 $newheader = $header;
2413 if ( is_array( $option ) && count( $option ) > 0 ) {
2414 $newheader .= ';' . implode( ';', $option );
2416 $headers[] = $newheader;
2418 $key = 'Key: ' . implode( ',', $headers );
2424 * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
2427 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2428 * /w/index.php?title=Main_page&variant=zh-cn will not.
2430 private function addAcceptLanguage() {
2431 $title = $this->getTitle();
2432 if ( !$title instanceof Title
) {
2436 $lang = $title->getPageLanguage();
2437 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2438 $variants = $lang->getVariants();
2440 foreach ( $variants as $variant ) {
2441 if ( $variant === $lang->getCode() ) {
2445 // XXX Note that this code is not strictly correct: we
2446 // do a case-insensitive match in
2447 // LanguageConverter::getHeaderVariant() while the
2448 // (abandoned, draft) spec for the `Key` header only
2449 // allows case-sensitive matches. To match the logic
2450 // in LanguageConverter::getHeaderVariant() we should
2451 // also be looking at fallback variants and deprecated
2452 // mediawiki-internal codes, as well as BCP 47
2453 // normalized forms.
2455 $aloption[] = "substr=$variant";
2457 // IE and some other browsers use BCP 47 standards in their Accept-Language header,
2458 // like "zh-CN" or "zh-Hant". We should handle these too.
2459 $variantBCP47 = LanguageCode
::bcp47( $variant );
2460 if ( $variantBCP47 !== $variant ) {
2461 $aloption[] = "substr=$variantBCP47";
2464 $this->addVaryHeader( 'Accept-Language', $aloption );
2469 * Set a flag which will cause an X-Frame-Options header appropriate for
2470 * edit pages to be sent. The header value is controlled by
2471 * $wgEditPageFrameOptions.
2473 * This is the default for special pages. If you display a CSRF-protected
2474 * form on an ordinary view page, then you need to call this function.
2476 * @param bool $enable
2478 public function preventClickjacking( $enable = true ) {
2479 $this->mPreventClickjacking
= $enable;
2483 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2484 * This can be called from pages which do not contain any CSRF-protected
2487 public function allowClickjacking() {
2488 $this->mPreventClickjacking
= false;
2492 * Get the prevent-clickjacking flag
2497 public function getPreventClickjacking() {
2498 return $this->mPreventClickjacking
;
2502 * Get the X-Frame-Options header value (without the name part), or false
2503 * if there isn't one. This is used by Skin to determine whether to enable
2504 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2506 * @return string|false
2508 public function getFrameOptions() {
2509 $config = $this->getConfig();
2510 if ( $config->get( 'BreakFrames' ) ) {
2512 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2513 return $config->get( 'EditPageFrameOptions' );
2519 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2520 * Trials: https://github.com/GoogleChrome/OriginTrials
2524 private function getOriginTrials() {
2525 $config = $this->getConfig();
2527 return $config->get( 'OriginTrials' );
2531 * Send cache control HTTP headers
2533 public function sendCacheControl() {
2534 $response = $this->getRequest()->response();
2535 $config = $this->getConfig();
2537 $this->addVaryHeader( 'Cookie' );
2538 $this->addAcceptLanguage();
2540 # don't serve compressed data to clients who can't handle it
2541 # maintain different caches for logged-in users and non-logged in ones
2542 $response->header( $this->getVaryHeader() );
2544 if ( $config->get( 'UseKeyHeader' ) ) {
2545 $response->header( $this->getKeyHeader() );
2548 if ( $this->mEnableClientCache
) {
2550 $config->get( 'UseSquid' ) &&
2551 !$response->hasCookies() &&
2552 !SessionManager
::getGlobalSession()->isPersistent() &&
2553 !$this->isPrintable() &&
2554 $this->mCdnMaxage
!= 0 &&
2555 !$this->haveCacheVaryCookies()
2557 if ( $config->get( 'UseESI' ) ) {
2558 wfDeprecated( '$wgUseESI = true', '1.33' );
2559 # We'll purge the proxy cache explicitly, but require end user agents
2560 # to revalidate against the proxy on each visit.
2561 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2562 wfDebug( __METHOD__
.
2563 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2564 # start with a shorter timeout for initial testing
2565 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2567 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2568 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2570 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2572 # We'll purge the proxy cache for anons explicitly, but require end user agents
2573 # to revalidate against the proxy on each visit.
2574 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2575 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2576 wfDebug( __METHOD__
.
2577 ": local proxy caching; {$this->mLastModified} **", 'private' );
2578 # start with a shorter timeout for initial testing
2579 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2580 $response->header( "Cache-Control: " .
2581 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2584 # We do want clients to cache if they can, but they *must* check for updates
2585 # on revisiting the page.
2586 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2587 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2588 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2590 if ( $this->mLastModified
) {
2591 $response->header( "Last-Modified: {$this->mLastModified}" );
2594 wfDebug( __METHOD__
. ": no caching **", 'private' );
2596 # In general, the absence of a last modified header should be enough to prevent
2597 # the client from using its cache. We send a few other things just to make sure.
2598 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2599 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2600 $response->header( 'Pragma: no-cache' );
2605 * Transfer styles and JavaScript modules from skin.
2607 * @param Skin $sk to load modules for
2609 public function loadSkinModules( $sk ) {
2610 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2611 if ( $group === 'styles' ) {
2612 foreach ( $modules as $key => $moduleMembers ) {
2613 $this->addModuleStyles( $moduleMembers );
2616 $this->addModules( $modules );
2622 * Finally, all the text has been munged and accumulated into
2623 * the object, let's actually output it:
2625 * @param bool $return Set to true to get the result as a string rather than sending it
2626 * @return string|null
2628 * @throws FatalError
2629 * @throws MWException
2631 public function output( $return = false ) {
2632 if ( $this->mDoNothing
) {
2633 return $return ?
'' : null;
2636 $response = $this->getRequest()->response();
2637 $config = $this->getConfig();
2639 if ( $this->mRedirect
!= '' ) {
2640 # Standards require redirect URLs to be absolute
2641 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2643 $redirect = $this->mRedirect
;
2644 $code = $this->mRedirectCode
;
2646 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2647 if ( $code == '301' ||
$code == '303' ) {
2648 if ( !$config->get( 'DebugRedirects' ) ) {
2649 $response->statusHeader( $code );
2651 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2653 if ( $config->get( 'VaryOnXFP' ) ) {
2654 $this->addVaryHeader( 'X-Forwarded-Proto' );
2656 $this->sendCacheControl();
2658 $response->header( "Content-Type: text/html; charset=utf-8" );
2659 if ( $config->get( 'DebugRedirects' ) ) {
2660 $url = htmlspecialchars( $redirect );
2661 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2662 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2663 print "</body>\n</html>\n";
2665 $response->header( 'Location: ' . $redirect );
2669 return $return ?
'' : null;
2670 } elseif ( $this->mStatusCode
) {
2671 $response->statusHeader( $this->mStatusCode
);
2674 # Buffer output; final headers may depend on later processing
2677 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2678 $response->header( 'Content-language: ' .
2679 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2681 $linkHeader = $this->getLinkHeader();
2682 if ( $linkHeader ) {
2683 $response->header( $linkHeader );
2686 // Prevent framing, if requested
2687 $frameOptions = $this->getFrameOptions();
2688 if ( $frameOptions ) {
2689 $response->header( "X-Frame-Options: $frameOptions" );
2692 $originTrials = $this->getOriginTrials();
2693 foreach ( $originTrials as $originTrial ) {
2694 $response->header( "Origin-Trial: $originTrial", false );
2697 ContentSecurityPolicy
::sendHeaders( $this );
2699 if ( $this->mArticleBodyOnly
) {
2700 echo $this->mBodytext
;
2702 // Enable safe mode if requested (T152169)
2703 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2704 $this->disallowUserJs();
2707 $sk = $this->getSkin();
2708 $this->loadSkinModules( $sk );
2710 MWDebug
::addModules( $this );
2712 // Avoid PHP 7.1 warning of passing $this by reference
2713 $outputPage = $this;
2714 // Hook that allows last minute changes to the output page, e.g.
2715 // adding of CSS or Javascript by extensions.
2716 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2720 } catch ( Exception
$e ) {
2721 ob_end_clean(); // bug T129657
2727 // This hook allows last minute changes to final overall output by modifying output buffer
2728 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2729 } catch ( Exception
$e ) {
2730 ob_end_clean(); // bug T129657
2734 $this->sendCacheControl();
2737 return ob_get_clean();
2745 * Prepare this object to display an error page; disable caching and
2746 * indexing, clear the current text and redirect, set the page's title
2747 * and optionally an custom HTML title (content of the "<title>" tag).
2749 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2750 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2751 * optional, if not passed the "<title>" attribute will be
2752 * based on $pageTitle
2754 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2755 $this->setPageTitle( $pageTitle );
2756 if ( $htmlTitle !== false ) {
2757 $this->setHTMLTitle( $htmlTitle );
2759 $this->setRobotPolicy( 'noindex,nofollow' );
2760 $this->setArticleRelated( false );
2761 $this->enableClientCache( false );
2762 $this->mRedirect
= '';
2763 $this->clearSubtitle();
2768 * Output a standard error page
2770 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2771 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2772 * showErrorPage( 'titlemsg', $messageObject );
2773 * showErrorPage( $titleMessageObject, $messageObject );
2775 * @param string|Message $title Message key (string) for page title, or a Message object
2776 * @param string|Message $msg Message key (string) for page text, or a Message object
2777 * @param array $params Message parameters; ignored if $msg is a Message object
2779 public function showErrorPage( $title, $msg, $params = [] ) {
2780 if ( !$title instanceof Message
) {
2781 $title = $this->msg( $title );
2784 $this->prepareErrorPage( $title );
2786 if ( $msg instanceof Message
) {
2787 if ( $params !== [] ) {
2788 trigger_error( 'Argument ignored: $params. The message parameters argument '
2789 . 'is discarded when the $msg argument is a Message object instead of '
2790 . 'a string.', E_USER_NOTICE
);
2792 $this->addHTML( $msg->parseAsBlock() );
2794 $this->addWikiMsgArray( $msg, $params );
2797 $this->returnToMain();
2801 * Output a standard permission error page
2803 * @param array $errors Error message keys or [key, param...] arrays
2804 * @param string|null $action Action that was denied or null if unknown
2806 public function showPermissionsErrorPage( array $errors, $action = null ) {
2807 foreach ( $errors as $key => $error ) {
2808 $errors[$key] = (array)$error;
2811 // For some action (read, edit, create and upload), display a "login to do this action"
2812 // error if all of the following conditions are met:
2813 // 1. the user is not logged in
2814 // 2. the only error is insufficient permissions (i.e. no block or something else)
2815 // 3. the error can be avoided simply by logging in
2816 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2817 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2818 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2819 && ( User
::groupHasPermission( 'user', $action )
2820 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2822 $displayReturnto = null;
2824 # Due to T34276, if a user does not have read permissions,
2825 # $this->getTitle() will just give Special:Badtitle, which is
2826 # not especially useful as a returnto parameter. Use the title
2827 # from the request instead, if there was one.
2828 $request = $this->getRequest();
2829 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2830 if ( $action == 'edit' ) {
2831 $msg = 'whitelistedittext';
2832 $displayReturnto = $returnto;
2833 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2834 $msg = 'nocreatetext';
2835 } elseif ( $action == 'upload' ) {
2836 $msg = 'uploadnologintext';
2838 $msg = 'loginreqpagetext';
2839 $displayReturnto = Title
::newMainPage();
2845 $query['returnto'] = $returnto->getPrefixedText();
2847 if ( !$request->wasPosted() ) {
2848 $returntoquery = $request->getValues();
2849 unset( $returntoquery['title'] );
2850 unset( $returntoquery['returnto'] );
2851 unset( $returntoquery['returntoquery'] );
2852 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2855 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2856 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2857 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2858 $loginLink = $linkRenderer->makeKnownLink(
2860 $this->msg( 'loginreqlink' )->text(),
2865 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2866 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2868 # Don't return to a page the user can't read otherwise
2869 # we'll end up in a pointless loop
2870 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2871 $this->returnToMain( null, $displayReturnto );
2874 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2875 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2880 * Display an error page indicating that a given version of MediaWiki is
2881 * required to use it
2883 * @param mixed $version The version of MediaWiki needed to use the page
2885 public function versionRequired( $version ) {
2886 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2888 $this->addWikiMsg( 'versionrequiredtext', $version );
2889 $this->returnToMain();
2893 * Format a list of error messages
2895 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2896 * @param string|null $action Action that was denied or null if unknown
2897 * @return string The wikitext error-messages, formatted into a list.
2899 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2900 if ( $action == null ) {
2901 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2903 $action_desc = $this->msg( "action-$action" )->plain();
2905 'permissionserrorstext-withaction',
2908 )->plain() . "\n\n";
2911 if ( count( $errors ) > 1 ) {
2912 $text .= '<ul class="permissions-errors">' . "\n";
2914 foreach ( $errors as $error ) {
2916 $text .= $this->msg( ...$error )->plain();
2921 $text .= "<div class=\"permissions-errors\">\n" .
2922 $this->msg( ...reset( $errors ) )->plain() .
2930 * Show a warning about replica DB lag
2932 * If the lag is higher than $wgSlaveLagCritical seconds,
2933 * then the warning is a bit more obvious. If the lag is
2934 * lower than $wgSlaveLagWarning, then no warning is shown.
2936 * @param int $lag Replica lag
2938 public function showLagWarning( $lag ) {
2939 $config = $this->getConfig();
2940 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2941 $lag = floor( $lag ); // floor to avoid nano seconds to display
2942 $message = $lag < $config->get( 'SlaveLagCritical' )
2945 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2946 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2951 * Output an error page
2953 * @note FatalError exception class provides an alternative.
2954 * @param string $message Error to output. Must be escaped for HTML.
2956 public function showFatalError( $message ) {
2957 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2959 $this->addHTML( $message );
2963 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2965 public function showUnexpectedValueError( $name, $val ) {
2966 wfDeprecated( __METHOD__
, '1.32' );
2967 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2971 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2973 public function showFileCopyError( $old, $new ) {
2974 wfDeprecated( __METHOD__
, '1.32' );
2975 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2979 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2981 public function showFileRenameError( $old, $new ) {
2982 wfDeprecated( __METHOD__
, '1.32' );
2983 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escaped() );
2987 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2989 public function showFileDeleteError( $name ) {
2990 wfDeprecated( __METHOD__
, '1.32' );
2991 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
2995 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2997 public function showFileNotFoundError( $name ) {
2998 wfDeprecated( __METHOD__
, '1.32' );
2999 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
3003 * Add a "return to" link pointing to a specified title
3005 * @param Title $title Title to link
3006 * @param array $query Query string parameters
3007 * @param string|null $text Text of the link (input is not escaped)
3008 * @param array $options Options array to pass to Linker
3010 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3011 $linkRenderer = MediaWikiServices
::getInstance()
3012 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3013 $link = $this->msg( 'returnto' )->rawParams(
3014 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3015 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3019 * Add a "return to" link pointing to a specified title,
3020 * or the title indicated in the request, or else the main page
3022 * @param mixed|null $unused
3023 * @param Title|string|null $returnto Title or String to return to
3024 * @param string|null $returntoquery Query string for the return to link
3026 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3027 if ( $returnto == null ) {
3028 $returnto = $this->getRequest()->getText( 'returnto' );
3031 if ( $returntoquery == null ) {
3032 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
3035 if ( $returnto === '' ) {
3036 $returnto = Title
::newMainPage();
3039 if ( is_object( $returnto ) ) {
3040 $titleObj = $returnto;
3042 $titleObj = Title
::newFromText( $returnto );
3044 // We don't want people to return to external interwiki. That
3045 // might potentially be used as part of a phishing scheme
3046 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
3047 $titleObj = Title
::newMainPage();
3050 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
3053 private function getRlClientContext() {
3054 if ( !$this->rlClientContext
) {
3055 $query = ResourceLoader
::makeLoaderQuery(
3056 [], // modules; not relevant
3057 $this->getLanguage()->getCode(),
3058 $this->getSkin()->getSkinName(),
3059 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
3060 null, // version; not relevant
3061 ResourceLoader
::inDebugMode(),
3062 null, // only; not relevant
3063 $this->isPrintable(),
3064 $this->getRequest()->getBool( 'handheld' )
3066 $this->rlClientContext
= new ResourceLoaderContext(
3067 $this->getResourceLoader(),
3068 new FauxRequest( $query )
3070 if ( $this->contentOverrideCallbacks
) {
3071 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
3072 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
3073 foreach ( $this->contentOverrideCallbacks
as $callback ) {
3074 $content = $callback( $title );
3075 if ( $content !== null ) {
3076 $text = ContentHandler
::getContentText( $content );
3077 if ( strpos( $text, '</script>' ) !== false ) {
3078 // Proactively replace this so that we can display a message
3079 // to the user, instead of letting it go to Html::inlineScript(),
3080 // where it would be considered a server-side issue.
3081 $titleFormatted = $title->getPrefixedText();
3082 $content = new JavaScriptContent(
3083 Xml
::encodeJsCall( 'mw.log.error', [
3084 "Cannot preview $titleFormatted due to script-closing tag."
3095 return $this->rlClientContext
;
3099 * Call this to freeze the module queue and JS config and create a formatter.
3101 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3102 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3103 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3104 * the module filters retroactively. Skins and extension hooks may also add modules until very
3105 * late in the request lifecycle.
3107 * @return ResourceLoaderClientHtml
3109 public function getRlClient() {
3110 if ( !$this->rlClient
) {
3111 $context = $this->getRlClientContext();
3112 $rl = $this->getResourceLoader();
3113 $this->addModules( [
3118 $this->addModuleStyles( [
3123 $this->getSkin()->setupSkinUserCss( $this );
3125 // Prepare exempt modules for buildExemptModules()
3126 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
3128 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3130 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
3131 // Separate user-specific batch for improved cache-hit ratio.
3132 $userBatch = [ 'user.styles', 'user' ];
3133 $siteBatch = array_diff( $moduleStyles, $userBatch );
3134 $dbr = wfGetDB( DB_REPLICA
);
3135 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
3136 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
3138 // Filter out modules handled by buildExemptModules()
3139 $moduleStyles = array_filter( $moduleStyles,
3140 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3141 $module = $rl->getModule( $name );
3143 $group = $module->getGroup();
3144 if ( isset( $exemptGroups[$group] ) ) {
3145 $exemptStates[$name] = 'ready';
3146 if ( !$module->isKnownEmpty( $context ) ) {
3147 // E.g. Don't output empty <styles>
3148 $exemptGroups[$group][] = $name;
3156 $this->rlExemptStyleModules
= $exemptGroups;
3158 $rlClient = new ResourceLoaderClientHtml( $context, [
3159 'target' => $this->getTarget(),
3160 'nonce' => $this->getCSPNonce(),
3161 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3162 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3163 // modules enqueud for loading on this page is filtered to just those.
3164 // However, to make sure we also apply the restriction to dynamic dependencies and
3165 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3166 // StartupModule so that the client-side registry will not contain any restricted
3167 // modules either. (T152169, T185303)
3168 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
3169 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
3172 $rlClient->setConfig( $this->getJSVars() );
3173 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3174 $rlClient->setModuleStyles( $moduleStyles );
3175 $rlClient->setExemptStates( $exemptStates );
3176 $this->rlClient
= $rlClient;
3178 return $this->rlClient
;
3182 * @param Skin $sk The given Skin
3183 * @param bool $includeStyle Unused
3184 * @return string The doctype, opening "<html>", and head element.
3186 public function headElement( Skin
$sk, $includeStyle = true ) {
3187 $userdir = $this->getLanguage()->getDir();
3188 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3191 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
3192 $this->getRlClient()->getDocumentAttributes(),
3193 $sk->getHtmlElementAttributes()
3195 $pieces[] = Html
::openElement( 'head' );
3197 if ( $this->getHTMLTitle() == '' ) {
3198 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3201 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
3202 // Add <meta charset="UTF-8">
3203 // This should be before <title> since it defines the charset used by
3204 // text including the text inside <title>.
3205 // The spec recommends defining XHTML5's charset using the XML declaration
3207 // Our XML declaration is output by Html::htmlHeader.
3208 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3209 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3210 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3213 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3214 $pieces[] = $this->getRlClient()->getHeadHtml();
3215 $pieces[] = $this->buildExemptModules();
3216 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3217 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3219 // Use an IE conditional comment to serve the script only to old IE
3220 $pieces[] = '<!--[if lt IE 9]>' .
3221 ResourceLoaderClientHtml
::makeLoad(
3222 new ResourceLoaderContext(
3223 $this->getResourceLoader(),
3224 new FauxRequest( [] )
3227 ResourceLoaderModule
::TYPE_SCRIPTS
,
3229 $this->getCSPNonce()
3233 $pieces[] = Html
::closeElement( 'head' );
3235 $bodyClasses = $this->mAdditionalBodyClasses
;
3236 $bodyClasses[] = 'mediawiki';
3238 # Classes for LTR/RTL directionality support
3239 $bodyClasses[] = $userdir;
3240 $bodyClasses[] = "sitedir-$sitedir";
3242 $underline = $this->getUser()->getOption( 'underline' );
3243 if ( $underline < 2 ) {
3244 // The following classes can be used here:
3245 // * mw-underline-always
3246 // * mw-underline-never
3247 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
3250 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3251 # A <body> class is probably not the best way to do this . . .
3252 $bodyClasses[] = 'capitalize-all-nouns';
3255 // Parser feature migration class
3256 // The idea is that this will eventually be removed, after the wikitext
3257 // which requires it is cleaned up.
3258 $bodyClasses[] = 'mw-hide-empty-elt';
3260 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3261 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3263 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3266 // While the implode() is not strictly needed, it's used for backwards compatibility
3267 // (this used to be built as a string and hooks likely still expect that).
3268 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3270 // Allow skins and extensions to add body attributes they need
3271 $sk->addToBodyAttributes( $this, $bodyAttrs );
3272 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3274 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3276 return self
::combineWrappedStrings( $pieces );
3280 * Get a ResourceLoader object associated with this OutputPage
3282 * @return ResourceLoader
3284 public function getResourceLoader() {
3285 if ( is_null( $this->mResourceLoader
) ) {
3286 // Lazy-initialise as needed
3287 $this->mResourceLoader
= MediaWikiServices
::getInstance()->getResourceLoader();
3289 return $this->mResourceLoader
;
3293 * Explicily load or embed modules on a page.
3295 * @param array|string $modules One or more module names
3296 * @param string $only ResourceLoaderModule TYPE_ class constant
3297 * @param array $extraQuery [optional] Array with extra query parameters for the request
3298 * @return string|WrappedStringList HTML
3300 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3301 // Apply 'target' and 'origin' filters
3302 $modules = $this->filterModules( (array)$modules, null, $only );
3304 return ResourceLoaderClientHtml
::makeLoad(
3305 $this->getRlClientContext(),
3309 $this->getCSPNonce()
3314 * Combine WrappedString chunks and filter out empty ones
3316 * @param array $chunks
3317 * @return string|WrappedStringList HTML
3319 protected static function combineWrappedStrings( array $chunks ) {
3320 // Filter out empty values
3321 $chunks = array_filter( $chunks, 'strlen' );
3322 return WrappedString
::join( "\n", $chunks );
3326 * JS stuff to put at the bottom of the `<body>`.
3327 * These are legacy scripts ($this->mScripts), and user JS.
3329 * @return string|WrappedStringList HTML
3331 public function getBottomScripts() {
3333 $chunks[] = $this->getRlClient()->getBodyHtml();
3335 // Legacy non-ResourceLoader scripts
3336 $chunks[] = $this->mScripts
;
3338 if ( $this->limitReportJSData
) {
3339 $chunks[] = ResourceLoader
::makeInlineScript(
3340 ResourceLoader
::makeConfigSetScript(
3341 [ 'wgPageParseReport' => $this->limitReportJSData
]
3343 $this->getCSPNonce()
3347 return self
::combineWrappedStrings( $chunks );
3351 * Get the javascript config vars to include on this page
3353 * @return array Array of javascript config vars
3356 public function getJsConfigVars() {
3357 return $this->mJsConfigVars
;
3361 * Add one or more variables to be set in mw.config in JavaScript
3363 * @param string|array $keys Key or array of key/value pairs
3364 * @param mixed|null $value [optional] Value of the configuration variable
3366 public function addJsConfigVars( $keys, $value = null ) {
3367 if ( is_array( $keys ) ) {
3368 foreach ( $keys as $key => $value ) {
3369 $this->mJsConfigVars
[$key] = $value;
3374 $this->mJsConfigVars
[$keys] = $value;
3378 * Get an array containing the variables to be set in mw.config in JavaScript.
3380 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3381 * - in other words, page-independent/site-wide variables (without state).
3382 * You will only be adding bloat to the html page and causing page caches to
3383 * have to be purged on configuration changes.
3386 public function getJSVars() {
3389 $canonicalSpecialPageName = false; # T23115
3390 $services = MediaWikiServices
::getInstance();
3392 $title = $this->getTitle();
3393 $ns = $title->getNamespace();
3394 $canonicalNamespace = MWNamespace
::exists( $ns )
3395 ? MWNamespace
::getCanonicalName( $ns )
3396 : $title->getNsText();
3398 $sk = $this->getSkin();
3399 // Get the relevant title so that AJAX features can use the correct page name
3400 // when making API requests from certain special pages (T36972).
3401 $relevantTitle = $sk->getRelevantTitle();
3402 $relevantUser = $sk->getRelevantUser();
3404 if ( $ns == NS_SPECIAL
) {
3405 list( $canonicalSpecialPageName, /*...*/ ) =
3406 $services->getSpecialPageFactory()->
3407 resolveAlias( $title->getDBkey() );
3408 } elseif ( $this->canUseWikiPage() ) {
3409 $wikiPage = $this->getWikiPage();
3410 $curRevisionId = $wikiPage->getLatest();
3411 $articleId = $wikiPage->getId();
3414 $lang = $title->getPageViewLanguage();
3416 // Pre-process information
3417 $separatorTransTable = $lang->separatorTransformTable();
3418 $separatorTransTable = $separatorTransTable ?
: [];
3419 $compactSeparatorTransTable = [
3420 implode( "\t", array_keys( $separatorTransTable ) ),
3421 implode( "\t", $separatorTransTable ),
3423 $digitTransTable = $lang->digitTransformTable();
3424 $digitTransTable = $digitTransTable ?
: [];
3425 $compactDigitTransTable = [
3426 implode( "\t", array_keys( $digitTransTable ) ),
3427 implode( "\t", $digitTransTable ),
3430 $user = $this->getUser();
3433 'wgCanonicalNamespace' => $canonicalNamespace,
3434 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3435 'wgNamespaceNumber' => $title->getNamespace(),
3436 'wgPageName' => $title->getPrefixedDBkey(),
3437 'wgTitle' => $title->getText(),
3438 'wgCurRevisionId' => $curRevisionId,
3439 'wgRevisionId' => (int)$this->getRevisionId(),
3440 'wgArticleId' => $articleId,
3441 'wgIsArticle' => $this->isArticle(),
3442 'wgIsRedirect' => $title->isRedirect(),
3443 'wgAction' => Action
::getActionName( $this->getContext() ),
3444 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3445 'wgUserGroups' => $user->getEffectiveGroups(),
3446 'wgCategories' => $this->getCategories(),
3447 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3448 'wgPageContentLanguage' => $lang->getCode(),
3449 'wgPageContentModel' => $title->getContentModel(),
3450 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3451 'wgDigitTransformTable' => $compactDigitTransTable,
3452 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3453 'wgMonthNames' => $lang->getMonthNamesArray(),
3454 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3455 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3456 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3457 'wgRequestId' => WebRequest
::getRequestId(),
3458 'wgCSPNonce' => $this->getCSPNonce(),
3461 if ( $user->isLoggedIn() ) {
3462 $vars['wgUserId'] = $user->getId();
3463 $vars['wgUserEditCount'] = $user->getEditCount();
3464 $userReg = $user->getRegistration();
3465 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3466 // Get the revision ID of the oldest new message on the user's talk
3467 // page. This can be used for constructing new message alerts on
3469 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3472 $contLang = $services->getContentLanguage();
3473 if ( $contLang->hasVariants() ) {
3474 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3476 // Same test as SkinTemplate
3477 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3478 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3480 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3481 && $relevantTitle->quickUserCan( 'edit', $user )
3482 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3484 foreach ( $title->getRestrictionTypes() as $type ) {
3485 // Following keys are set in $vars:
3486 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3487 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3490 if ( $title->isMainPage() ) {
3491 $vars['wgIsMainPage'] = true;
3494 if ( $this->mRedirectedFrom
) {
3495 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3498 if ( $relevantUser ) {
3499 $vars['wgRelevantUserName'] = $relevantUser->getName();
3502 // Allow extensions to add their custom variables to the mw.config map.
3503 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3504 // page-dependant but site-wide (without state).
3505 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3506 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3508 // Merge in variables from addJsConfigVars last
3509 return array_merge( $vars, $this->getJsConfigVars() );
3513 * To make it harder for someone to slip a user a fake
3514 * JavaScript or CSS preview, a random token
3515 * is associated with the login session. If it's not
3516 * passed back with the preview request, we won't render
3521 public function userCanPreview() {
3522 $request = $this->getRequest();
3524 $request->getVal( 'action' ) !== 'submit' ||
3525 !$request->wasPosted()
3530 $user = $this->getUser();
3532 if ( !$user->isLoggedIn() ) {
3533 // Anons have predictable edit tokens
3536 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3540 $title = $this->getTitle();
3541 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3542 if ( count( $errors ) !== 0 ) {
3550 * @return array Array in format "link name or number => 'link html'".
3552 public function getHeadLinksArray() {
3556 $config = $this->getConfig();
3558 $canonicalUrl = $this->mCanonicalUrl
;
3560 $tags['meta-generator'] = Html
::element( 'meta', [
3561 'name' => 'generator',
3562 'content' => "MediaWiki $wgVersion",
3565 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3566 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3567 // fallbacks should come before the primary value so we need to reverse the array.
3568 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3569 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3570 'name' => 'referrer',
3571 'content' => $policy,
3576 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3577 if ( $p !== 'index,follow' ) {
3578 // http://www.robotstxt.org/wc/meta-user.html
3579 // Only show if it's different from the default robots policy
3580 $tags['meta-robots'] = Html
::element( 'meta', [
3586 foreach ( $this->mMetatags
as $tag ) {
3587 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3589 $tag[0] = substr( $tag[0], 5 );
3590 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3595 $tagName = "meta-{$tag[0]}";
3596 if ( isset( $tags[$tagName] ) ) {
3597 $tagName .= $tag[1];
3599 $tags[$tagName] = Html
::element( 'meta',
3602 'content' => $tag[1]
3607 foreach ( $this->mLinktags
as $tag ) {
3608 $tags[] = Html
::element( 'link', $tag );
3611 # Universal edit button
3612 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3613 $user = $this->getUser();
3614 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3615 && ( $this->getTitle()->exists() ||
3616 $this->getTitle()->quickUserCan( 'create', $user ) )
3618 // Original UniversalEditButton
3619 $msg = $this->msg( 'edit' )->text();
3620 $tags['universal-edit-button'] = Html
::element( 'link', [
3621 'rel' => 'alternate',
3622 'type' => 'application/x-wiki',
3624 'href' => $this->getTitle()->getEditURL(),
3626 // Alternate edit link
3627 $tags['alternative-edit'] = Html
::element( 'link', [
3630 'href' => $this->getTitle()->getEditURL(),
3635 # Generally the order of the favicon and apple-touch-icon links
3636 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3637 # uses whichever one appears later in the HTML source. Make sure
3638 # apple-touch-icon is specified first to avoid this.
3639 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3640 $tags['apple-touch-icon'] = Html
::element( 'link', [
3641 'rel' => 'apple-touch-icon',
3642 'href' => $config->get( 'AppleTouchIcon' )
3646 if ( $config->get( 'Favicon' ) !== false ) {
3647 $tags['favicon'] = Html
::element( 'link', [
3648 'rel' => 'shortcut icon',
3649 'href' => $config->get( 'Favicon' )
3653 # OpenSearch description link
3654 $tags['opensearch'] = Html
::element( 'link', [
3656 'type' => 'application/opensearchdescription+xml',
3657 'href' => wfScript( 'opensearch_desc' ),
3658 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3661 # Real Simple Discovery link, provides auto-discovery information
3662 # for the MediaWiki API (and potentially additional custom API
3663 # support such as WordPress or Twitter-compatible APIs for a
3664 # blogging extension, etc)
3665 $tags['rsd'] = Html
::element( 'link', [
3667 'type' => 'application/rsd+xml',
3668 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3669 // Whether RSD accepts relative or protocol-relative URLs is completely
3670 // undocumented, though.
3671 'href' => wfExpandUrl( wfAppendQuery(
3673 [ 'action' => 'rsd' ] ),
3679 if ( !$config->get( 'DisableLangConversion' ) ) {
3680 $lang = $this->getTitle()->getPageLanguage();
3681 if ( $lang->hasVariants() ) {
3682 $variants = $lang->getVariants();
3683 foreach ( $variants as $variant ) {
3684 $tags["variant-$variant"] = Html
::element( 'link', [
3685 'rel' => 'alternate',
3686 'hreflang' => LanguageCode
::bcp47( $variant ),
3687 'href' => $this->getTitle()->getLocalURL(
3688 [ 'variant' => $variant ] )
3692 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3693 $tags["variant-x-default"] = Html
::element( 'link', [
3694 'rel' => 'alternate',
3695 'hreflang' => 'x-default',
3696 'href' => $this->getTitle()->getLocalURL() ] );
3701 if ( $this->copyrightUrl
!== null ) {
3702 $copyright = $this->copyrightUrl
;
3705 if ( $config->get( 'RightsPage' ) ) {
3706 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3709 $copyright = $copy->getLocalURL();
3713 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3714 $copyright = $config->get( 'RightsUrl' );
3719 $tags['copyright'] = Html
::element( 'link', [
3721 'href' => $copyright ]
3726 if ( $config->get( 'Feed' ) ) {
3729 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3730 # Use the page name for the title. In principle, this could
3731 # lead to issues with having the same name for different feeds
3732 # corresponding to the same page, but we can't avoid that at
3735 $feedLinks[] = $this->feedLink(
3738 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3740 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3745 # Recent changes feed should appear on every page (except recentchanges,
3746 # that would be redundant). Put it after the per-page feed to avoid
3747 # changing existing behavior. It's still available, probably via a
3748 # menu in your browser. Some sites might have a different feed they'd
3749 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3750 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3751 # If so, use it instead.
3752 $sitename = $config->get( 'Sitename' );
3753 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3754 if ( $overrideSiteFeed ) {
3755 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3756 // Note, this->feedLink escapes the url.
3757 $feedLinks[] = $this->feedLink(
3760 $this->msg( "site-{$type}-feed", $sitename )->text()
3763 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3764 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3765 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3766 $feedLinks[] = $this->feedLink(
3768 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3769 # For grep: 'site-rss-feed', 'site-atom-feed'
3770 $this->msg( "site-{$format}-feed", $sitename )->text()
3775 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3776 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3777 # use OutputPage::addFeedLink() instead.
3778 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3780 $tags +
= $feedLinks;
3784 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3785 if ( $canonicalUrl !== false ) {
3786 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3787 } elseif ( $this->isArticleRelated() ) {
3788 // This affects all requests where "setArticleRelated" is true. This is
3789 // typically all requests that show content (query title, curid, oldid, diff),
3790 // and all wikipage actions (edit, delete, purge, info, history etc.).
3791 // It does not apply to File pages and Special pages.
3792 // 'history' and 'info' actions address page metadata rather than the page
3793 // content itself, so they may not be canonicalized to the view page url.
3794 // TODO: this ought to be better encapsulated in the Action class.
3795 $action = Action
::getActionName( $this->getContext() );
3796 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3797 $query = "action={$action}";
3801 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3803 $reqUrl = $this->getRequest()->getRequestURL();
3804 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3807 if ( $canonicalUrl !== false ) {
3808 $tags[] = Html
::element( 'link', [
3809 'rel' => 'canonical',
3810 'href' => $canonicalUrl
3814 // Allow extensions to add, remove and/or otherwise manipulate these links
3815 // If you want only to *add* <head> links, please use the addHeadItem()
3816 // (or addHeadItems() for multiple items) method instead.
3817 // This hook is provided as a last resort for extensions to modify these
3818 // links before the output is sent to client.
3819 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3825 * Generate a "<link rel/>" for a feed.
3827 * @param string $type Feed type
3828 * @param string $url URL to the feed
3829 * @param string $text Value of the "title" attribute
3830 * @return string HTML fragment
3832 private function feedLink( $type, $url, $text ) {
3833 return Html
::element( 'link', [
3834 'rel' => 'alternate',
3835 'type' => "application/$type+xml",
3842 * Add a local or specified stylesheet, with the given media options.
3843 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3845 * @param string $style URL to the file
3846 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3847 * @param string $condition For IE conditional comments, specifying an IE version
3848 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3850 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3853 $options['media'] = $media;
3856 $options['condition'] = $condition;
3859 $options['dir'] = $dir;
3861 $this->styles
[$style] = $options;
3865 * Adds inline CSS styles
3866 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3868 * @param mixed $style_css Inline CSS
3869 * @param string $flip Set to 'flip' to flip the CSS if needed
3871 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3872 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3873 # If wanted, and the interface is right-to-left, flip the CSS
3874 $style_css = CSSJanus
::transform( $style_css, true, false );
3876 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3880 * Build exempt modules and legacy non-ResourceLoader styles.
3882 * @return string|WrappedStringList HTML
3884 protected function buildExemptModules() {
3886 // Things that go after the ResourceLoaderDynamicStyles marker
3889 // We want site, private and user styles to override dynamically added styles from
3890 // general modules, but we want dynamically added styles to override statically added
3891 // style modules. So the order has to be:
3892 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3893 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3894 // - ResourceLoaderDynamicStyles marker
3895 // - site/private/user styles
3897 // Add legacy styles added through addStyle()/addInlineStyle() here
3898 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3900 $chunks[] = Html
::element(
3902 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3905 $separateReq = [ 'site.styles', 'user.styles' ];
3906 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3907 // Combinable modules
3908 $chunks[] = $this->makeResourceLoaderLink(
3909 array_diff( $moduleNames, $separateReq ),
3910 ResourceLoaderModule
::TYPE_STYLES
3913 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3914 // These require their own dedicated request in order to support "@import"
3915 // syntax, which is incompatible with concatenation. (T147667, T37562)
3916 $chunks[] = $this->makeResourceLoaderLink( $name,
3917 ResourceLoaderModule
::TYPE_STYLES
3922 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3928 public function buildCssLinksArray() {
3931 foreach ( $this->styles
as $file => $options ) {
3932 $link = $this->styleLink( $file, $options );
3934 $links[$file] = $link;
3941 * Generate \<link\> tags for stylesheets
3943 * @param string $style URL to the file
3944 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3945 * @return string HTML fragment
3947 protected function styleLink( $style, array $options ) {
3948 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3952 if ( isset( $options['media'] ) ) {
3953 $media = self
::transformCssMedia( $options['media'] );
3954 if ( is_null( $media ) ) {
3961 if ( substr( $style, 0, 1 ) == '/' ||
3962 substr( $style, 0, 5 ) == 'http:' ||
3963 substr( $style, 0, 6 ) == 'https:' ) {
3966 $config = $this->getConfig();
3967 // Append file hash as query parameter
3968 $url = self
::transformResourcePath(
3970 $config->get( 'StylePath' ) . '/' . $style
3974 $link = Html
::linkedStyle( $url, $media );
3976 if ( isset( $options['condition'] ) ) {
3977 $condition = htmlspecialchars( $options['condition'] );
3978 $link = "<!--[if $condition]>$link<![endif]-->";
3984 * Transform path to web-accessible static resource.
3986 * This is used to add a validation hash as query string.
3987 * This aids various behaviors:
3989 * - Put long Cache-Control max-age headers on responses for improved
3990 * cache performance.
3991 * - Get the correct version of a file as expected by the current page.
3992 * - Instantly get the updated version of a file after deployment.
3994 * Avoid using this for urls included in HTML as otherwise clients may get different
3995 * versions of a resource when navigating the site depending on when the page was cached.
3996 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3997 * an external stylesheet).
4000 * @param Config $config
4001 * @param string $path Path-absolute URL to file (from document root, must start with "/")
4002 * @return string URL
4004 public static function transformResourcePath( Config
$config, $path ) {
4008 $remotePathPrefix = $config->get( 'ResourceBasePath' );
4009 if ( $remotePathPrefix === '' ) {
4010 // The configured base path is required to be empty string for
4011 // wikis in the domain root
4014 $remotePath = $remotePathPrefix;
4016 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
4017 // - Path is outside wgResourceBasePath, ignore.
4018 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
4021 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
4022 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
4023 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
4024 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
4025 $uploadPath = $config->get( 'UploadPath' );
4026 if ( strpos( $path, $uploadPath ) === 0 ) {
4027 $localDir = $config->get( 'UploadDirectory' );
4028 $remotePathPrefix = $remotePath = $uploadPath;
4031 $path = RelPath
::getRelativePath( $path, $remotePath );
4032 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
4036 * Utility method for transformResourceFilePath().
4038 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
4041 * @param string $remotePathPrefix URL path prefix that points to $localPath
4042 * @param string $localPath File directory exposed at $remotePath
4043 * @param string $file Path to target file relative to $localPath
4044 * @return string URL
4046 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4047 $hash = md5_file( "$localPath/$file" );
4048 if ( $hash === false ) {
4049 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
4052 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
4056 * Transform "media" attribute based on request parameters
4058 * @param string $media Current value of the "media" attribute
4059 * @return string Modified value of the "media" attribute, or null to skip
4062 public static function transformCssMedia( $media ) {
4065 // https://www.w3.org/TR/css3-mediaqueries/#syntax
4066 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
4068 // Switch in on-screen display for media testing
4070 'printable' => 'print',
4071 'handheld' => 'handheld',
4073 foreach ( $switches as $switch => $targetMedia ) {
4074 if ( $wgRequest->getBool( $switch ) ) {
4075 if ( $media == $targetMedia ) {
4077 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4078 /* This regex will not attempt to understand a comma-separated media_query_list
4080 * Example supported values for $media:
4081 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
4082 * Example NOT supported value for $media:
4083 * '3d-glasses, screen, print and resolution > 90dpi'
4085 * If it's a print request, we never want any kind of screen stylesheets
4086 * If it's a handheld request (currently the only other choice with a switch),
4087 * we don't want simple 'screen' but we might want screen queries that
4088 * have a max-width or something, so we'll pass all others on and let the
4089 * client do the query.
4091 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
4102 * Add a wikitext-formatted message to the output.
4103 * This is equivalent to:
4105 * $wgOut->addWikiText( wfMessage( ... )->plain() )
4107 public function addWikiMsg( /*...*/ ) {
4108 $args = func_get_args();
4109 $name = array_shift( $args );
4110 $this->addWikiMsgArray( $name, $args );
4114 * Add a wikitext-formatted message to the output.
4115 * Like addWikiMsg() except the parameters are taken as an array
4116 * instead of a variable argument list.
4118 * @param string $name
4119 * @param array $args
4121 public function addWikiMsgArray( $name, $args ) {
4122 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
4126 * This function takes a number of message/argument specifications, wraps them in
4127 * some overall structure, and then parses the result and adds it to the output.
4129 * In the $wrap, $1 is replaced with the first message, $2 with the second,
4130 * and so on. The subsequent arguments may be either
4131 * 1) strings, in which case they are message names, or
4132 * 2) arrays, in which case, within each array, the first element is the message
4133 * name, and subsequent elements are the parameters to that message.
4135 * Don't use this for messages that are not in the user's interface language.
4139 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
4143 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
4144 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
4146 * The newline after the opening div is needed in some wikitext. See T21226.
4148 * @param string $wrap
4150 public function wrapWikiMsg( $wrap /*, ...*/ ) {
4151 $msgSpecs = func_get_args();
4152 array_shift( $msgSpecs );
4153 $msgSpecs = array_values( $msgSpecs );
4155 foreach ( $msgSpecs as $n => $spec ) {
4156 if ( is_array( $spec ) ) {
4158 $name = array_shift( $args );
4159 if ( isset( $args['options'] ) ) {
4160 unset( $args['options'] );
4162 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
4170 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
4172 $this->addWikiTextAsInterface( $s );
4176 * Whether the output has a table of contents
4180 public function isTOCEnabled() {
4181 return $this->mEnableTOC
;
4185 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
4188 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
4190 public function enableSectionEditLinks( $flag = true ) {
4191 wfDeprecated( __METHOD__
, '1.31' );
4197 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
4199 public function sectionEditLinksEnabled() {
4200 wfDeprecated( __METHOD__
, '1.31' );
4205 * Helper function to setup the PHP implementation of OOUI to use in this request.
4208 * @param string $skinName The Skin name to determine the correct OOUI theme
4209 * @param string $dir Language direction
4211 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4212 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4213 $theme = $themes[$skinName] ??
$themes['default'];
4214 // For example, 'OOUI\WikimediaUITheme'.
4215 $themeClass = "OOUI\\{$theme}Theme";
4216 OOUI\Theme
::setSingleton( new $themeClass() );
4217 OOUI\Element
::setDefaultDir( $dir );
4221 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4222 * MediaWiki and this OutputPage instance.
4226 public function enableOOUI() {
4228 strtolower( $this->getSkin()->getSkinName() ),
4229 $this->getLanguage()->getDir()
4231 $this->addModuleStyles( [
4232 'oojs-ui-core.styles',
4233 'oojs-ui.styles.indicators',
4234 'oojs-ui.styles.textures',
4235 'mediawiki.widgets.styles',
4236 'oojs-ui.styles.icons-content',
4237 'oojs-ui.styles.icons-alerts',
4238 'oojs-ui.styles.icons-interactions',
4243 * Get (and set if not yet set) the CSP nonce.
4245 * This value needs to be included in any <script> tags on the
4248 * @return string|bool Nonce or false to mean don't output nonce
4251 public function getCSPNonce() {
4252 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4255 if ( $this->CSPNonce
=== null ) {
4256 // XXX It might be expensive to generate randomness
4257 // on every request, on Windows.
4258 $rand = random_bytes( 15 );
4259 $this->CSPNonce
= base64_encode( $rand );
4261 return $this->CSPNonce
;