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 * Get the list of style-only modules to load on this page.
554 * @param bool $filter
555 * @param string|null $position Unused
556 * @return array Array of module names
558 public function getModuleStyles( $filter = false, $position = null ) {
559 return $this->getModules( $filter, null, 'mModuleStyles',
560 ResourceLoaderModule
::TYPE_STYLES
565 * Load the styles of one or more ResourceLoader modules on this page.
567 * Module styles added through this function will be loaded as a stylesheet,
568 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
569 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
571 * @param string|array $modules Module name (string) or array of module names
573 public function addModuleStyles( $modules ) {
574 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
578 * @return null|string ResourceLoader target
580 public function getTarget() {
581 return $this->mTarget
;
585 * Sets ResourceLoader target for load.php links. If null, will be omitted
587 * @param string|null $target
589 public function setTarget( $target ) {
590 $this->mTarget
= $target;
594 * Add a mapping from a LinkTarget to a Content, for things like page preview.
595 * @see self::addContentOverrideCallback()
597 * @param LinkTarget $target
598 * @param Content $content
600 public function addContentOverride( LinkTarget
$target, Content
$content ) {
601 if ( !$this->contentOverrides
) {
602 // Register a callback for $this->contentOverrides on the first call
603 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
604 $key = $target->getNamespace() . ':' . $target->getDBkey();
605 return $this->contentOverrides
[$key] ??
null;
609 $key = $target->getNamespace() . ':' . $target->getDBkey();
610 $this->contentOverrides
[$key] = $content;
614 * Add a callback for mapping from a Title to a Content object, for things
616 * @see ResourceLoaderContext::getContentOverrideCallback()
618 * @param callable $callback
620 public function addContentOverrideCallback( callable
$callback ) {
621 $this->contentOverrideCallbacks
[] = $callback;
625 * Get an array of head items
629 function getHeadItemsArray() {
630 return $this->mHeadItems
;
634 * Add or replace a head item to the output
636 * Whenever possible, use more specific options like ResourceLoader modules,
637 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
638 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
639 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
640 * This would be your very LAST fallback.
642 * @param string $name Item name
643 * @param string $value Raw HTML
645 public function addHeadItem( $name, $value ) {
646 $this->mHeadItems
[$name] = $value;
650 * Add one or more head items to the output
653 * @param string|string[] $values Raw HTML
655 public function addHeadItems( $values ) {
656 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
660 * Check if the header item $name is already set
662 * @param string $name Item name
665 public function hasHeadItem( $name ) {
666 return isset( $this->mHeadItems
[$name] );
670 * Add a class to the <body> element
673 * @param string|string[] $classes One or more classes to add
675 public function addBodyClasses( $classes ) {
676 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
680 * Set whether the output should only contain the body of the article,
681 * without any skin, sidebar, etc.
682 * Used e.g. when calling with "action=render".
684 * @param bool $only Whether to output only the body of the article
686 public function setArticleBodyOnly( $only ) {
687 $this->mArticleBodyOnly
= $only;
691 * Return whether the output will contain only the body of the article
695 public function getArticleBodyOnly() {
696 return $this->mArticleBodyOnly
;
700 * Set an additional output property
703 * @param string $name
704 * @param mixed $value
706 public function setProperty( $name, $value ) {
707 $this->mProperties
[$name] = $value;
711 * Get an additional output property
714 * @param string $name
715 * @return mixed Property value or null if not found
717 public function getProperty( $name ) {
718 return $this->mProperties
[$name] ??
null;
722 * checkLastModified tells the client to use the client-cached page if
723 * possible. If successful, the OutputPage is disabled so that
724 * any future call to OutputPage->output() have no effect.
726 * Side effect: sets mLastModified for Last-Modified header
728 * @param string $timestamp
730 * @return bool True if cache-ok headers was sent.
732 public function checkLastModified( $timestamp ) {
733 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
734 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
737 $config = $this->getConfig();
738 if ( !$config->get( 'CachePages' ) ) {
739 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
743 $timestamp = wfTimestamp( TS_MW
, $timestamp );
745 'page' => $timestamp,
746 'user' => $this->getUser()->getTouched(),
747 'epoch' => $config->get( 'CacheEpoch' )
749 if ( $config->get( 'UseCdn' ) ) {
750 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
752 $config->get( 'CdnMaxAge' )
755 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
757 $maxModified = max( $modifiedTimes );
758 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
760 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
761 if ( $clientHeader === false ) {
762 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
766 # IE sends sizes after the date like this:
767 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
768 # this breaks strtotime().
769 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
771 Wikimedia\
suppressWarnings(); // E_STRICT system time warnings
772 $clientHeaderTime = strtotime( $clientHeader );
773 Wikimedia\restoreWarnings
();
774 if ( !$clientHeaderTime ) {
776 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
779 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
783 foreach ( $modifiedTimes as $name => $value ) {
784 if ( $info !== '' ) {
787 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
790 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
791 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
792 wfDebug( __METHOD__
. ": effective Last-Modified: " .
793 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
794 if ( $clientHeaderTime < $maxModified ) {
795 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
800 # Give a 304 Not Modified response code and disable body output
801 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
802 ini_set( 'zlib.output_compression', 0 );
803 $this->getRequest()->response()->statusHeader( 304 );
804 $this->sendCacheControl();
807 // Don't output a compressed blob when using ob_gzhandler;
808 // it's technically against HTTP spec and seems to confuse
809 // Firefox when the response gets split over two packets.
810 wfClearOutputBuffers();
816 * @param int $reqTime Time of request (eg. now)
817 * @param int $maxAge Cache TTL in seconds
818 * @return int Timestamp
820 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
821 // Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
822 // because even if the wiki page content hasn't changed since, static
823 // resources may have changed (skin HTML, interface messages, urls, etc.)
824 // and must roll-over in a timely manner (T46570)
825 return $reqTime - $maxAge;
829 * Override the last modified timestamp
831 * @param string $timestamp New timestamp, in a format readable by
834 public function setLastModified( $timestamp ) {
835 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
839 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
841 * @param string $policy The literal string to output as the contents of
842 * the meta tag. Will be parsed according to the spec and output in
846 public function setRobotPolicy( $policy ) {
847 $policy = Article
::formatRobotPolicy( $policy );
849 if ( isset( $policy['index'] ) ) {
850 $this->setIndexPolicy( $policy['index'] );
852 if ( isset( $policy['follow'] ) ) {
853 $this->setFollowPolicy( $policy['follow'] );
858 * Set the index policy for the page, but leave the follow policy un-
861 * @param string $policy Either 'index' or 'noindex'.
864 public function setIndexPolicy( $policy ) {
865 $policy = trim( $policy );
866 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
867 $this->mIndexPolicy
= $policy;
872 * Set the follow policy for the page, but leave the index policy un-
875 * @param string $policy Either 'follow' or 'nofollow'.
878 public function setFollowPolicy( $policy ) {
879 $policy = trim( $policy );
880 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
881 $this->mFollowPolicy
= $policy;
886 * "HTML title" means the contents of "<title>".
887 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
889 * @param string|Message $name
891 public function setHTMLTitle( $name ) {
892 if ( $name instanceof Message
) {
893 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
895 $this->mHTMLtitle
= $name;
900 * Return the "HTML title", i.e. the content of the "<title>" tag.
904 public function getHTMLTitle() {
905 return $this->mHTMLtitle
;
909 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
913 public function setRedirectedFrom( $t ) {
914 $this->mRedirectedFrom
= $t;
918 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
919 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
920 * but not bad tags like \<script\>. This function automatically sets
921 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
922 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
923 * good tags like \<i\> will be dropped entirely.
925 * @param string|Message $name
926 * @param-taint $name tainted
927 * Phan-taint-check gets very confused by $name being either a string or a Message
929 public function setPageTitle( $name ) {
930 if ( $name instanceof Message
) {
931 $name = $name->setContext( $this->getContext() )->text();
934 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
935 # but leave "<i>foobar</i>" alone
936 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
937 $this->mPageTitle
= $nameWithTags;
939 # change "<i>foo&bar</i>" to "foo&bar"
941 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer
::stripAllTags( $nameWithTags ) )
942 ->inContentLanguage()
947 * Return the "page title", i.e. the content of the \<h1\> tag.
951 public function getPageTitle() {
952 return $this->mPageTitle
;
956 * Same as page title but only contains name of the page, not any other text.
959 * @param string $html Page title text.
960 * @see OutputPage::setPageTitle
962 public function setDisplayTitle( $html ) {
963 $this->displayTitle
= $html;
967 * Returns page display title.
969 * Performs some normalization, but this not as strict the magic word.
972 * @return string HTML
974 public function getDisplayTitle() {
975 $html = $this->displayTitle
;
976 if ( $html === null ) {
977 $html = $this->getTitle()->getPrefixedText();
980 return Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $html ) );
984 * Returns page display title without namespace prefix if possible.
987 * @return string HTML
989 public function getUnprefixedDisplayTitle() {
990 $text = $this->getDisplayTitle();
991 $nsPrefix = $this->getTitle()->getNsText() . ':';
992 $prefix = preg_quote( $nsPrefix, '/' );
994 return preg_replace( "/^$prefix/i", '', $text );
998 * Set the Title object to use
1002 public function setTitle( Title
$t ) {
1003 $this->getContext()->setTitle( $t );
1007 * Replace the subtitle with $str
1009 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1011 public function setSubtitle( $str ) {
1012 $this->clearSubtitle();
1013 $this->addSubtitle( $str );
1017 * Add $str to the subtitle
1019 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1021 public function addSubtitle( $str ) {
1022 if ( $str instanceof Message
) {
1023 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1025 $this->mSubtitle
[] = $str;
1030 * Build message object for a subtitle containing a backlink to a page
1032 * @param Title $title Title to link to
1033 * @param array $query Array of additional parameters to include in the link
1037 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1038 if ( $title->isRedirect() ) {
1039 $query['redirect'] = 'no';
1041 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1042 return wfMessage( 'backlinksubtitle' )
1043 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1047 * Add a subtitle containing a backlink to a page
1049 * @param Title $title Title to link to
1050 * @param array $query Array of additional parameters to include in the link
1052 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1053 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1057 * Clear the subtitles
1059 public function clearSubtitle() {
1060 $this->mSubtitle
= [];
1068 public function getSubtitle() {
1069 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1073 * Set the page as printable, i.e. it'll be displayed with all
1074 * print styles included
1076 public function setPrintable() {
1077 $this->mPrintable
= true;
1081 * Return whether the page is "printable"
1085 public function isPrintable() {
1086 return $this->mPrintable
;
1090 * Disable output completely, i.e. calling output() will have no effect
1092 public function disable() {
1093 $this->mDoNothing
= true;
1097 * Return whether the output will be completely disabled
1101 public function isDisabled() {
1102 return $this->mDoNothing
;
1106 * Show an "add new section" link?
1110 public function showNewSectionLink() {
1111 return $this->mNewSectionLink
;
1115 * Forcibly hide the new section link?
1119 public function forceHideNewSectionLink() {
1120 return $this->mHideNewSectionLink
;
1124 * Add or remove feed links in the page header
1125 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1126 * for the new version
1127 * @see addFeedLink()
1129 * @param bool $show True: add default feeds, false: remove all feeds
1131 public function setSyndicated( $show = true ) {
1133 $this->setFeedAppendQuery( false );
1135 $this->mFeedLinks
= [];
1140 * Return effective list of advertised feed types
1141 * @see addFeedLink()
1143 * @return array Array of feed type names ( 'rss', 'atom' )
1145 protected function getAdvertisedFeedTypes() {
1146 if ( $this->getConfig()->get( 'Feed' ) ) {
1147 return $this->getConfig()->get( 'AdvertisedFeedTypes' );
1154 * Add default feeds to the page header
1155 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1156 * for the new version
1157 * @see addFeedLink()
1159 * @param string $val Query to append to feed links or false to output
1162 public function setFeedAppendQuery( $val ) {
1163 $this->mFeedLinks
= [];
1165 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1166 $query = "feed=$type";
1167 if ( is_string( $val ) ) {
1168 $query .= '&' . $val;
1170 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1175 * Add a feed link to the page header
1177 * @param string $format Feed type, should be a key of $wgFeedClasses
1178 * @param string $href URL
1180 public function addFeedLink( $format, $href ) {
1181 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1182 $this->mFeedLinks
[$format] = $href;
1187 * Should we output feed links for this page?
1190 public function isSyndicated() {
1191 return count( $this->mFeedLinks
) > 0;
1195 * Return URLs for each supported syndication format for this page.
1196 * @return array Associating format keys with URLs
1198 public function getSyndicationLinks() {
1199 return $this->mFeedLinks
;
1203 * Will currently always return null
1207 public function getFeedAppendQuery() {
1208 return $this->mFeedLinksAppendQuery
;
1212 * Set whether the displayed content is related to the source of the
1213 * corresponding article on the wiki
1214 * Setting true will cause the change "article related" toggle to true
1216 * @param bool $newVal
1218 public function setArticleFlag( $newVal ) {
1219 $this->mIsArticle
= $newVal;
1221 $this->mIsArticleRelated
= $newVal;
1226 * Return whether the content displayed page is related to the source of
1227 * the corresponding article on the wiki
1231 public function isArticle() {
1232 return $this->mIsArticle
;
1236 * Set whether this page is related an article on the wiki
1237 * Setting false will cause the change of "article flag" toggle to false
1239 * @param bool $newVal
1241 public function setArticleRelated( $newVal ) {
1242 $this->mIsArticleRelated
= $newVal;
1244 $this->mIsArticle
= false;
1249 * Return whether this page is related an article on the wiki
1253 public function isArticleRelated() {
1254 return $this->mIsArticleRelated
;
1258 * Set whether the standard copyright should be shown for the current page.
1260 * @param bool $hasCopyright
1262 public function setCopyright( $hasCopyright ) {
1263 $this->mHasCopyright
= $hasCopyright;
1267 * Return whether the standard copyright should be shown for the current page.
1268 * By default, it is true for all articles but other pages
1269 * can signal it by using setCopyright( true ).
1271 * Used by SkinTemplate to decided whether to show the copyright.
1275 public function showsCopyright() {
1276 return $this->isArticle() ||
$this->mHasCopyright
;
1280 * Add new language links
1282 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1283 * (e.g. 'fr:Test page')
1285 public function addLanguageLinks( array $newLinkArray ) {
1286 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1290 * Reset the language links and add new language links
1292 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1293 * (e.g. 'fr:Test page')
1295 public function setLanguageLinks( array $newLinkArray ) {
1296 $this->mLanguageLinks
= $newLinkArray;
1300 * Get the list of language links
1302 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1304 public function getLanguageLinks() {
1305 return $this->mLanguageLinks
;
1309 * Add an array of categories, with names in the keys
1311 * @param array $categories Mapping category name => sort key
1313 public function addCategoryLinks( array $categories ) {
1314 if ( !$categories ) {
1318 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1320 # Set all the values to 'normal'.
1321 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1323 # Mark hidden categories
1324 foreach ( $res as $row ) {
1325 if ( isset( $row->pp_value
) ) {
1326 $categories[$row->page_title
] = 'hidden';
1330 // Avoid PHP 7.1 warning of passing $this by reference
1331 $outputPage = $this;
1332 # Add the remaining categories to the skin
1334 'OutputPageMakeCategoryLinks',
1335 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1337 $services = MediaWikiServices
::getInstance();
1338 $linkRenderer = $services->getLinkRenderer();
1339 foreach ( $categories as $category => $type ) {
1340 // array keys will cast numeric category names to ints, so cast back to string
1341 $category = (string)$category;
1342 $origcategory = $category;
1343 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1347 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1348 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1351 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1352 $this->mCategories
[$type][] = $title->getText();
1353 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1359 * @param array $categories
1360 * @return bool|IResultWrapper
1362 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1363 # Add the links to a LinkBatch
1364 $arr = [ NS_CATEGORY
=> $categories ];
1365 $lb = new LinkBatch
;
1366 $lb->setArray( $arr );
1368 # Fetch existence plus the hiddencat property
1369 $dbr = wfGetDB( DB_REPLICA
);
1370 $fields = array_merge(
1371 LinkCache
::getSelectFields(),
1372 [ 'page_namespace', 'page_title', 'pp_value' ]
1375 $res = $dbr->select( [ 'page', 'page_props' ],
1377 $lb->constructSet( 'page', $dbr ),
1380 [ 'page_props' => [ 'LEFT JOIN', [
1381 'pp_propname' => 'hiddencat',
1386 # Add the results to the link cache
1387 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1388 $lb->addResultToCache( $linkCache, $res );
1394 * Reset the category links (but not the category list) and add $categories
1396 * @param array $categories Mapping category name => sort key
1398 public function setCategoryLinks( array $categories ) {
1399 $this->mCategoryLinks
= [];
1400 $this->addCategoryLinks( $categories );
1404 * Get the list of category links, in a 2-D array with the following format:
1405 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1406 * hidden categories) and $link a HTML fragment with a link to the category
1411 public function getCategoryLinks() {
1412 return $this->mCategoryLinks
;
1416 * Get the list of category names this page belongs to.
1418 * @param string $type The type of categories which should be returned. Possible values:
1419 * * all: all categories of all types
1420 * * hidden: only the hidden categories
1421 * * normal: all categories, except hidden categories
1422 * @return array Array of strings
1424 public function getCategories( $type = 'all' ) {
1425 if ( $type === 'all' ) {
1426 $allCategories = [];
1427 foreach ( $this->mCategories
as $categories ) {
1428 $allCategories = array_merge( $allCategories, $categories );
1430 return $allCategories;
1432 if ( !isset( $this->mCategories
[$type] ) ) {
1433 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1435 return $this->mCategories
[$type];
1439 * Add an array of indicators, with their identifiers as array
1440 * keys and HTML contents as values.
1442 * In case of duplicate keys, existing values are overwritten.
1444 * @param array $indicators
1447 public function setIndicators( array $indicators ) {
1448 $this->mIndicators
= $indicators +
$this->mIndicators
;
1449 // Keep ordered by key
1450 ksort( $this->mIndicators
);
1454 * Get the indicators associated with this page.
1456 * The array will be internally ordered by item keys.
1458 * @return array Keys: identifiers, values: HTML contents
1461 public function getIndicators() {
1462 return $this->mIndicators
;
1466 * Adds help link with an icon via page indicators.
1467 * Link target can be overridden by a local message containing a wikilink:
1468 * the message key is: lowercase action or special page name + '-helppage'.
1469 * @param string $to Target MediaWiki.org page title or encoded URL.
1470 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1473 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1474 $this->addModuleStyles( 'mediawiki.helplink' );
1475 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1477 if ( $overrideBaseUrl ) {
1480 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1481 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1484 $link = Html
::rawElement(
1488 'target' => '_blank',
1489 'class' => 'mw-helplink',
1494 $this->setIndicators( [ 'mw-helplink' => $link ] );
1498 * Do not allow scripts which can be modified by wiki users to load on this page;
1499 * only allow scripts bundled with, or generated by, the software.
1500 * Site-wide styles are controlled by a config setting, since they can be
1501 * used to create a custom skin/theme, but not user-specific ones.
1503 * @todo this should be given a more accurate name
1505 public function disallowUserJs() {
1506 $this->reduceAllowedModules(
1507 ResourceLoaderModule
::TYPE_SCRIPTS
,
1508 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1511 // Site-wide styles are controlled by a config setting, see T73621
1512 // for background on why. User styles are never allowed.
1513 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1514 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1516 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1518 $this->reduceAllowedModules(
1519 ResourceLoaderModule
::TYPE_STYLES
,
1525 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1526 * @see ResourceLoaderModule::$origin
1527 * @param string $type ResourceLoaderModule TYPE_ constant
1528 * @return int ResourceLoaderModule ORIGIN_ class constant
1530 public function getAllowedModules( $type ) {
1531 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1532 return min( array_values( $this->mAllowedModules
) );
1534 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1539 * Limit the highest level of CSS/JS untrustworthiness allowed.
1541 * If passed the same or a higher level than the current level of untrustworthiness set, the
1542 * level will remain unchanged.
1544 * @param string $type
1545 * @param int $level ResourceLoaderModule class constant
1547 public function reduceAllowedModules( $type, $level ) {
1548 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1552 * Prepend $text to the body HTML
1554 * @param string $text HTML
1556 public function prependHTML( $text ) {
1557 $this->mBodytext
= $text . $this->mBodytext
;
1561 * Append $text to the body HTML
1563 * @param string $text HTML
1565 public function addHTML( $text ) {
1566 $this->mBodytext
.= $text;
1570 * Shortcut for adding an Html::element via addHTML.
1574 * @param string $element
1575 * @param array $attribs
1576 * @param string $contents
1578 public function addElement( $element, array $attribs = [], $contents = '' ) {
1579 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1583 * Clear the body HTML
1585 public function clearHTML() {
1586 $this->mBodytext
= '';
1592 * @return string HTML
1594 public function getHTML() {
1595 return $this->mBodytext
;
1599 * Get/set the ParserOptions object to use for wikitext parsing
1601 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1602 * current ParserOption object. This parameter is deprecated since 1.31.
1603 * @return ParserOptions
1605 public function parserOptions( $options = null ) {
1606 if ( $options !== null ) {
1607 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1610 if ( $options !== null && !empty( $options->isBogus
) ) {
1611 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1612 // been changed somehow, and keep it if so.
1613 $anonPO = ParserOptions
::newFromAnon();
1614 $anonPO->setAllowUnsafeRawHtml( false );
1615 if ( !$options->matches( $anonPO ) ) {
1616 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1617 $options->isBogus
= false;
1621 if ( !$this->mParserOptions
) {
1622 if ( !$this->getUser()->isSafeToLoad() ) {
1623 // $wgUser isn't unstubbable yet, so don't try to get a
1624 // ParserOptions for it. And don't cache this ParserOptions
1626 $po = ParserOptions
::newFromAnon();
1627 $po->setAllowUnsafeRawHtml( false );
1628 $po->isBogus
= true;
1629 if ( $options !== null ) {
1630 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1635 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1636 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1639 if ( $options !== null && !empty( $options->isBogus
) ) {
1640 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1642 return wfSetVar( $this->mParserOptions
, null, true );
1644 return wfSetVar( $this->mParserOptions
, $options );
1649 * Set the revision ID which will be seen by the wiki text parser
1650 * for things such as embedded {{REVISIONID}} variable use.
1652 * @param int|null $revid A positive integer, or null
1653 * @return mixed Previous value
1655 public function setRevisionId( $revid ) {
1656 $val = is_null( $revid ) ?
null : intval( $revid );
1657 return wfSetVar( $this->mRevisionId
, $val, true );
1661 * Get the displayed revision ID
1665 public function getRevisionId() {
1666 return $this->mRevisionId
;
1670 * Set the timestamp of the revision which will be displayed. This is used
1671 * to avoid a extra DB call in Skin::lastModified().
1673 * @param string|null $timestamp
1674 * @return mixed Previous value
1676 public function setRevisionTimestamp( $timestamp ) {
1677 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1681 * Get the timestamp of displayed revision.
1682 * This will be null if not filled by setRevisionTimestamp().
1684 * @return string|null
1686 public function getRevisionTimestamp() {
1687 return $this->mRevisionTimestamp
;
1691 * Set the displayed file version
1693 * @param File|null $file
1694 * @return mixed Previous value
1696 public function setFileVersion( $file ) {
1698 if ( $file instanceof File
&& $file->exists() ) {
1699 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1701 return wfSetVar( $this->mFileVersion
, $val, true );
1705 * Get the displayed file version
1707 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1709 public function getFileVersion() {
1710 return $this->mFileVersion
;
1714 * Get the templates used on this page
1716 * @return array (namespace => dbKey => revId)
1719 public function getTemplateIds() {
1720 return $this->mTemplateIds
;
1724 * Get the files used on this page
1726 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1729 public function getFileSearchOptions() {
1730 return $this->mImageTimeKeys
;
1734 * Convert wikitext to HTML and add it to the buffer
1735 * Default assumes that the current page title will be used.
1737 * @param string $text
1738 * @param bool $linestart Is this the start of a line?
1739 * @param bool $interface Is this text in the user interface language?
1740 * @throws MWException
1741 * @deprecated since 1.32 due to untidy output; use
1742 * addWikiTextAsInterface() if $interface is default value or true,
1743 * or else addWikiTextAsContent() if $interface is false.
1745 public function addWikiText( $text, $linestart = true, $interface = true ) {
1746 wfDeprecated( __METHOD__
, '1.32' );
1747 $title = $this->getTitle();
1749 throw new MWException( 'Title is null' );
1751 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, $interface );
1755 * Convert wikitext *in the user interface language* to HTML and
1756 * add it to the buffer. The result will not be
1757 * language-converted, as user interface messages are already
1758 * localized into a specific variant. Assumes that the current
1759 * page title will be used if optional $title is not
1760 * provided. Output will be tidy.
1762 * @param string $text Wikitext in the user interface language
1763 * @param bool $linestart Is this the start of a line? (Defaults to true)
1764 * @param Title|null $title Optional title to use; default of `null`
1765 * means use current page title.
1766 * @throws MWException if $title is not provided and OutputPage::getTitle()
1770 public function addWikiTextAsInterface(
1771 $text, $linestart = true, Title
$title = null
1773 if ( $title === null ) {
1774 $title = $this->getTitle();
1777 throw new MWException( 'Title is null' );
1779 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/true );
1783 * Convert wikitext *in the user interface language* to HTML and
1784 * add it to the buffer with a `<div class="$wrapperClass">`
1785 * wrapper. The result will not be language-converted, as user
1786 * interface messages as already localized into a specific
1787 * variant. The $text will be parsed in start-of-line context.
1788 * Output will be tidy.
1790 * @param string $wrapperClass The class attribute value for the <div>
1791 * wrapper in the output HTML
1792 * @param string $text Wikitext in the user interface language
1795 public function wrapWikiTextAsInterface(
1796 $wrapperClass, $text
1798 $this->addWikiTextTitleInternal(
1799 $text, $this->getTitle(),
1800 /*linestart*/true, /*tidy*/true, /*interface*/true,
1806 * Convert wikitext *in the page content language* to HTML and add
1807 * it to the buffer. The result with be language-converted to the
1808 * user's preferred variant. Assumes that the current page title
1809 * will be used if optional $title is not provided. Output will be
1812 * @param string $text Wikitext in the page content language
1813 * @param bool $linestart Is this the start of a line? (Defaults to true)
1814 * @param Title|null $title Optional title to use; default of `null`
1815 * means use current page title.
1816 * @throws MWException if $title is not provided and OutputPage::getTitle()
1820 public function addWikiTextAsContent(
1821 $text, $linestart = true, Title
$title = null
1823 if ( $title === null ) {
1824 $title = $this->getTitle();
1827 throw new MWException( 'Title is null' );
1829 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1833 * Add wikitext with a custom Title object
1835 * @param string $text Wikitext
1836 * @param Title $title
1837 * @param bool $linestart Is this the start of a line?
1838 * @deprecated since 1.32 due to untidy output; use
1839 * addWikiTextAsInterface()
1841 public function addWikiTextWithTitle( $text, Title
$title, $linestart = true ) {
1842 wfDeprecated( __METHOD__
, '1.32' );
1843 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, /*interface*/false );
1847 * Add wikitext *in content language* with a custom Title object.
1848 * Output will be tidy.
1850 * @param string $text Wikitext in content language
1851 * @param Title $title
1852 * @param bool $linestart Is this the start of a line?
1853 * @deprecated since 1.32 to rename methods consistently; use
1854 * addWikiTextAsContent()
1856 function addWikiTextTitleTidy( $text, Title
$title, $linestart = true ) {
1857 wfDeprecated( __METHOD__
, '1.32' );
1858 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1862 * Add wikitext *in content language*. Output will be tidy.
1864 * @param string $text Wikitext in content language
1865 * @param bool $linestart Is this the start of a line?
1866 * @deprecated since 1.32 to rename methods consistently; use
1867 * addWikiTextAsContent()
1869 public function addWikiTextTidy( $text, $linestart = true ) {
1870 wfDeprecated( __METHOD__
, '1.32' );
1871 $title = $this->getTitle();
1873 throw new MWException( 'Title is null' );
1875 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1879 * Add wikitext with a custom Title object.
1880 * Output is unwrapped.
1882 * @param string $text Wikitext
1883 * @param Title $title
1884 * @param bool $linestart Is this the start of a line?
1885 * @param bool $tidy Whether to use tidy.
1886 * Setting this to false (or omitting it) is deprecated
1887 * since 1.32; all wikitext should be tidied.
1888 * For backwards-compatibility with prior MW releases,
1889 * you may wish to invoke this method but set $tidy=true;
1890 * this will result in equivalent output to the non-deprecated
1891 * addWikiTextAsContent()/addWikiTextAsInterface() methods.
1892 * @param bool $interface Whether it is an interface message
1893 * (for example disables conversion)
1894 * @deprecated since 1.32, use addWikiTextAsContent() or
1895 * addWikiTextAsInterface() (depending on $interface)
1897 public function addWikiTextTitle( $text, Title
$title, $linestart,
1898 $tidy = false, $interface = false
1900 wfDeprecated( __METHOD__
, '1.32' );
1901 return $this->addWikiTextTitleInternal( $text, $title, $linestart, $tidy, $interface );
1905 * Add wikitext with a custom Title object.
1906 * Output is unwrapped.
1908 * @param string $text Wikitext
1909 * @param Title $title
1910 * @param bool $linestart Is this the start of a line?
1911 * @param bool $tidy Whether to use tidy.
1912 * Setting this to false (or omitting it) is deprecated
1913 * since 1.32; all wikitext should be tidied.
1914 * @param bool $interface Whether it is an interface message
1915 * (for example disables conversion)
1916 * @param string $wrapperClass if not empty, wraps the output in
1917 * a `<div class="$wrapperClass">`
1920 private function addWikiTextTitleInternal(
1921 $text, Title
$title, $linestart, $tidy, $interface, $wrapperClass = null
1924 wfDeprecated( 'disabling tidy', '1.32' );
1927 $parserOutput = $this->parseInternal(
1928 $text, $title, $linestart, $tidy, $interface, /*language*/null
1931 $this->addParserOutput( $parserOutput, [
1932 'enableSectionEditLinks' => false,
1933 'wrapperDivClass' => $wrapperClass ??
'',
1938 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1939 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1943 * @param ParserOutput $parserOutput
1945 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1946 $this->mLanguageLinks
=
1947 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1948 $this->addCategoryLinks( $parserOutput->getCategories() );
1949 $this->setIndicators( $parserOutput->getIndicators() );
1950 $this->mNewSectionLink
= $parserOutput->getNewSection();
1951 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1953 if ( !$parserOutput->isCacheable() ) {
1954 $this->enableClientCache( false );
1956 $this->mNoGallery
= $parserOutput->getNoGallery();
1957 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1958 $this->addModules( $parserOutput->getModules() );
1959 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1960 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1961 $this->mPreventClickjacking
= $this->mPreventClickjacking
1962 ||
$parserOutput->preventClickjacking();
1964 // Template versioning...
1965 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1966 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1967 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1969 $this->mTemplateIds
[$ns] = $dbks;
1972 // File versioning...
1973 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1974 $this->mImageTimeKeys
[$dbk] = $data;
1977 // Hooks registered in the object
1978 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1979 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1980 list( $hookName, $data ) = $hookInfo;
1981 if ( isset( $parserOutputHooks[$hookName] ) ) {
1982 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1986 // Enable OOUI if requested via ParserOutput
1987 if ( $parserOutput->getEnableOOUI() ) {
1988 $this->enableOOUI();
1991 // Include parser limit report
1992 if ( !$this->limitReportJSData
) {
1993 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1996 // Link flags are ignored for now, but may in the future be
1997 // used to mark individual language links.
1999 // Avoid PHP 7.1 warning of passing $this by reference
2000 $outputPage = $this;
2001 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
2002 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
2004 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2005 // so that extensions may modify ParserOutput to toggle TOC.
2006 // This cannot be moved to addParserOutputText because that is not
2007 // called by EditPage for Preview.
2008 if ( $parserOutput->getTOCHTML() ) {
2009 $this->mEnableTOC
= true;
2014 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2015 * ParserOutput object, without any other metadata.
2018 * @param ParserOutput $parserOutput
2019 * @param array $poOptions Options to ParserOutput::getText()
2021 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
2022 $this->addParserOutputText( $parserOutput, $poOptions );
2024 $this->addModules( $parserOutput->getModules() );
2025 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2027 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2031 * Add the HTML associated with a ParserOutput object, without any metadata.
2034 * @param ParserOutput $parserOutput
2035 * @param array $poOptions Options to ParserOutput::getText()
2037 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
2038 $text = $parserOutput->getText( $poOptions );
2039 // Avoid PHP 7.1 warning of passing $this by reference
2040 $outputPage = $this;
2041 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
2042 $this->addHTML( $text );
2046 * Add everything from a ParserOutput object.
2048 * @param ParserOutput $parserOutput
2049 * @param array $poOptions Options to ParserOutput::getText()
2051 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
2052 $this->addParserOutputMetadata( $parserOutput );
2053 $this->addParserOutputText( $parserOutput, $poOptions );
2057 * Add the output of a QuickTemplate to the output buffer
2059 * @param QuickTemplate &$template
2061 public function addTemplate( &$template ) {
2062 $this->addHTML( $template->getHTML() );
2066 * Parse wikitext and return the HTML.
2068 * @todo The output is wrapped in a <div> iff $interface is false; it's
2069 * probably best to always strip the wrapper.
2071 * @param string $text
2072 * @param bool $linestart Is this the start of a line?
2073 * @param bool $interface Use interface language (instead of content language) while parsing
2074 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2075 * LanguageConverter.
2076 * @param Language|null $language Target language object, will override $interface
2077 * @throws MWException
2078 * @return string HTML
2079 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
2080 * use parseAsContent() if $interface is default value or false, or else
2081 * parseAsInterface() if $interface is true.
2083 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
2084 wfDeprecated( __METHOD__
, '1.33' );
2085 return $this->parseInternal(
2086 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
2088 'enableSectionEditLinks' => false,
2093 * Parse wikitext *in the page content language* and return the HTML.
2094 * The result will be language-converted to the user's preferred variant.
2095 * Output will be tidy.
2097 * @param string $text Wikitext in the page content language
2098 * @param bool $linestart Is this the start of a line? (Defaults to true)
2099 * @throws MWException
2100 * @return string HTML
2103 public function parseAsContent( $text, $linestart = true ) {
2104 return $this->parseInternal(
2105 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2107 'enableSectionEditLinks' => false,
2108 'wrapperDivClass' => ''
2113 * Parse wikitext *in the user interface language* and return the HTML.
2114 * The result will not be language-converted, as user interface messages
2115 * are already localized into a specific variant.
2116 * Output will be tidy.
2118 * @param string $text Wikitext in the user interface language
2119 * @param bool $linestart Is this the start of a line? (Defaults to true)
2120 * @throws MWException
2121 * @return string HTML
2124 public function parseAsInterface( $text, $linestart = true ) {
2125 return $this->parseInternal(
2126 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2128 'enableSectionEditLinks' => false,
2129 'wrapperDivClass' => ''
2134 * Parse wikitext *in the user interface language*, strip
2135 * paragraph wrapper, and return the HTML.
2136 * The result will not be language-converted, as user interface messages
2137 * are already localized into a specific variant.
2138 * Output will be tidy. Outer paragraph wrapper will only be stripped
2139 * if the result is a single paragraph.
2141 * @param string $text Wikitext in the user interface language
2142 * @param bool $linestart Is this the start of a line? (Defaults to true)
2143 * @throws MWException
2144 * @return string HTML
2147 public function parseInlineAsInterface( $text, $linestart = true ) {
2148 return Parser
::stripOuterParagraph(
2149 $this->parseAsInterface( $text, $linestart )
2154 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2156 * @param string $text
2157 * @param bool $linestart Is this the start of a line?
2158 * @param bool $interface Use interface language (instead of content language) while parsing
2159 * language sensitive magic words like GRAMMAR and PLURAL
2160 * @return string HTML
2161 * @deprecated since 1.32, due to untidy output and confusing default
2162 * for $interface. Use parseInlineAsInterface() if $interface is
2163 * the default value or false, or else use
2164 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2166 public function parseInline( $text, $linestart = true, $interface = false ) {
2167 wfDeprecated( __METHOD__
, '1.33' );
2168 $parsed = $this->parseInternal(
2169 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2171 'enableSectionEditLinks' => false,
2172 'wrapperDivClass' => '', /* no wrapper div */
2174 return Parser
::stripOuterParagraph( $parsed );
2178 * Parse wikitext and return the HTML (internal implementation helper)
2180 * @param string $text
2181 * @param Title $title The title to use
2182 * @param bool $linestart Is this the start of a line?
2183 * @param bool $tidy Whether the output should be tidied
2184 * @param bool $interface Use interface language (instead of content language) while parsing
2185 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2186 * LanguageConverter.
2187 * @param Language|null $language Target language object, will override $interface
2188 * @throws MWException
2189 * @return ParserOutput
2191 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2192 if ( is_null( $title ) ) {
2193 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2196 $popts = $this->parserOptions();
2197 $oldTidy = $popts->setTidy( $tidy );
2198 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2200 if ( $language !== null ) {
2201 $oldLang = $popts->setTargetLanguage( $language );
2204 $parserOutput = MediaWikiServices
::getInstance()->getParser()->getFreshParser()->parse(
2205 $text, $title, $popts,
2206 $linestart, true, $this->mRevisionId
2209 $popts->setTidy( $oldTidy );
2210 $popts->setInterfaceMessage( $oldInterface );
2212 if ( $language !== null ) {
2213 $popts->setTargetLanguage( $oldLang );
2216 return $parserOutput;
2220 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2222 * @param int $maxage Maximum cache time on the CDN, in seconds.
2224 public function setCdnMaxage( $maxage ) {
2225 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2229 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2230 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2231 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2234 * @param int $maxage Maximum cache time on the CDN, in seconds
2237 public function lowerCdnMaxage( $maxage ) {
2238 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2239 $this->setCdnMaxage( $this->mCdnMaxage
);
2243 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2245 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2246 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2247 * TTL is 90% of the age of the object, subject to the min and max.
2249 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2250 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2251 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2254 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2255 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2256 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'CdnMaxAge' );
2258 if ( $mtime === null ||
$mtime === false ) {
2259 return $minTTL; // entity does not exist
2262 $age = MWTimestamp
::time() - wfTimestamp( TS_UNIX
, $mtime );
2263 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2264 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2266 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2270 * Use enableClientCache(false) to force it to send nocache headers
2272 * @param bool|null $state New value, or null to not set the value
2274 * @return bool Old value
2276 public function enableClientCache( $state ) {
2277 return wfSetVar( $this->mEnableClientCache
, $state );
2281 * Get the list of cookie names that will influence the cache
2285 function getCacheVaryCookies() {
2286 if ( self
::$cacheVaryCookies === null ) {
2287 $config = $this->getConfig();
2288 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2289 SessionManager
::singleton()->getVaryCookies(),
2293 $config->get( 'CacheVaryCookies' )
2295 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2297 return self
::$cacheVaryCookies;
2301 * Check if the request has a cache-varying cookie header
2302 * If it does, it's very important that we don't allow public caching
2306 function haveCacheVaryCookies() {
2307 $request = $this->getRequest();
2308 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2309 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2310 wfDebug( __METHOD__
. ": found $cookieName\n" );
2314 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2319 * Add an HTTP header that will influence on the cache
2321 * @param string $header Header name
2322 * @param string[]|null $option Options for the Key header. See
2323 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2324 * for the list of valid options.
2326 public function addVaryHeader( $header, array $option = null ) {
2327 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2328 $this->mVaryHeader
[$header] = [];
2330 if ( !is_array( $option ) ) {
2333 $this->mVaryHeader
[$header] =
2334 array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2338 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2339 * such as Accept-Encoding or Cookie
2343 public function getVaryHeader() {
2344 // If we vary on cookies, let's make sure it's always included here too.
2345 if ( $this->getCacheVaryCookies() ) {
2346 $this->addVaryHeader( 'Cookie' );
2349 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2350 $this->addVaryHeader( $header, $options );
2352 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2356 * Add an HTTP Link: header
2358 * @param string $header Header value
2360 public function addLinkHeader( $header ) {
2361 $this->mLinkHeader
[] = $header;
2365 * Return a Link: header. Based on the values of $mLinkHeader.
2369 public function getLinkHeader() {
2370 if ( !$this->mLinkHeader
) {
2374 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2378 * Get a complete Key header
2381 * @deprecated in 1.32; the IETF spec for this header expired w/o becoming
2384 public function getKeyHeader() {
2385 wfDeprecated( '$wgUseKeyHeader', '1.32' );
2387 $cvCookies = $this->getCacheVaryCookies();
2389 $cookiesOption = [];
2390 foreach ( $cvCookies as $cookieName ) {
2391 $cookiesOption[] = 'param=' . $cookieName;
2393 $this->addVaryHeader( 'Cookie', $cookiesOption );
2395 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2396 $this->addVaryHeader( $header, $options );
2400 foreach ( $this->mVaryHeader
as $header => $option ) {
2401 $newheader = $header;
2402 if ( is_array( $option ) && count( $option ) > 0 ) {
2403 $newheader .= ';' . implode( ';', $option );
2405 $headers[] = $newheader;
2407 $key = 'Key: ' . implode( ',', $headers );
2413 * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
2416 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2417 * /w/index.php?title=Main_page&variant=zh-cn will not.
2419 private function addAcceptLanguage() {
2420 $title = $this->getTitle();
2421 if ( !$title instanceof Title
) {
2425 $lang = $title->getPageLanguage();
2426 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2427 $variants = $lang->getVariants();
2429 foreach ( $variants as $variant ) {
2430 if ( $variant === $lang->getCode() ) {
2434 // XXX Note that this code is not strictly correct: we
2435 // do a case-insensitive match in
2436 // LanguageConverter::getHeaderVariant() while the
2437 // (abandoned, draft) spec for the `Key` header only
2438 // allows case-sensitive matches. To match the logic
2439 // in LanguageConverter::getHeaderVariant() we should
2440 // also be looking at fallback variants and deprecated
2441 // mediawiki-internal codes, as well as BCP 47
2442 // normalized forms.
2444 $aloption[] = "substr=$variant";
2446 // IE and some other browsers use BCP 47 standards in their Accept-Language header,
2447 // like "zh-CN" or "zh-Hant". We should handle these too.
2448 $variantBCP47 = LanguageCode
::bcp47( $variant );
2449 if ( $variantBCP47 !== $variant ) {
2450 $aloption[] = "substr=$variantBCP47";
2453 $this->addVaryHeader( 'Accept-Language', $aloption );
2458 * Set a flag which will cause an X-Frame-Options header appropriate for
2459 * edit pages to be sent. The header value is controlled by
2460 * $wgEditPageFrameOptions.
2462 * This is the default for special pages. If you display a CSRF-protected
2463 * form on an ordinary view page, then you need to call this function.
2465 * @param bool $enable
2467 public function preventClickjacking( $enable = true ) {
2468 $this->mPreventClickjacking
= $enable;
2472 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2473 * This can be called from pages which do not contain any CSRF-protected
2476 public function allowClickjacking() {
2477 $this->mPreventClickjacking
= false;
2481 * Get the prevent-clickjacking flag
2486 public function getPreventClickjacking() {
2487 return $this->mPreventClickjacking
;
2491 * Get the X-Frame-Options header value (without the name part), or false
2492 * if there isn't one. This is used by Skin to determine whether to enable
2493 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2495 * @return string|false
2497 public function getFrameOptions() {
2498 $config = $this->getConfig();
2499 if ( $config->get( 'BreakFrames' ) ) {
2501 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2502 return $config->get( 'EditPageFrameOptions' );
2508 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2509 * Trials: https://github.com/GoogleChrome/OriginTrials
2513 private function getOriginTrials() {
2514 $config = $this->getConfig();
2516 return $config->get( 'OriginTrials' );
2519 private function getReportTo() {
2520 $config = $this->getConfig();
2522 $expiry = $config->get( 'ReportToExpiry' );
2528 $endpoints = $config->get( 'ReportToEndpoints' );
2530 if ( !$endpoints ) {
2534 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2536 foreach ( $endpoints as $endpoint ) {
2537 $output['endpoints'][] = [ 'url' => $endpoint ];
2540 return json_encode( $output, JSON_UNESCAPED_SLASHES
);
2543 private function getFeaturePolicyReportOnly() {
2544 $config = $this->getConfig();
2546 $features = $config->get( 'FeaturePolicyReportOnly' );
2547 return implode( ';', $features );
2551 * Send cache control HTTP headers
2553 public function sendCacheControl() {
2554 $response = $this->getRequest()->response();
2555 $config = $this->getConfig();
2557 $this->addVaryHeader( 'Cookie' );
2558 $this->addAcceptLanguage();
2560 # don't serve compressed data to clients who can't handle it
2561 # maintain different caches for logged-in users and non-logged in ones
2562 $response->header( $this->getVaryHeader() );
2564 if ( $config->get( 'UseKeyHeader' ) ) {
2565 $response->header( $this->getKeyHeader() );
2568 if ( $this->mEnableClientCache
) {
2570 $config->get( 'UseCdn' ) &&
2571 !$response->hasCookies() &&
2572 !SessionManager
::getGlobalSession()->isPersistent() &&
2573 !$this->isPrintable() &&
2574 $this->mCdnMaxage
!= 0 &&
2575 !$this->haveCacheVaryCookies()
2577 if ( $config->get( 'UseESI' ) ) {
2578 wfDeprecated( '$wgUseESI = true', '1.33' );
2579 # We'll purge the proxy cache explicitly, but require end user agents
2580 # to revalidate against the proxy on each visit.
2581 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2582 wfDebug( __METHOD__
.
2583 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2584 # start with a shorter timeout for initial testing
2585 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2587 "Surrogate-Control: max-age={$config->get( 'CdnMaxAge' )}" .
2588 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2590 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2592 # We'll purge the proxy cache for anons explicitly, but require end user agents
2593 # to revalidate against the proxy on each visit.
2594 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2595 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2596 wfDebug( __METHOD__
.
2597 ": local proxy caching; {$this->mLastModified} **", 'private' );
2598 # start with a shorter timeout for initial testing
2599 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2600 $response->header( "Cache-Control: " .
2601 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2604 # We do want clients to cache if they can, but they *must* check for updates
2605 # on revisiting the page.
2606 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2607 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2608 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2610 if ( $this->mLastModified
) {
2611 $response->header( "Last-Modified: {$this->mLastModified}" );
2614 wfDebug( __METHOD__
. ": no caching **", 'private' );
2616 # In general, the absence of a last modified header should be enough to prevent
2617 # the client from using its cache. We send a few other things just to make sure.
2618 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2619 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2620 $response->header( 'Pragma: no-cache' );
2625 * Transfer styles and JavaScript modules from skin.
2627 * @param Skin $sk to load modules for
2629 public function loadSkinModules( $sk ) {
2630 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2631 if ( $group === 'styles' ) {
2632 foreach ( $modules as $key => $moduleMembers ) {
2633 $this->addModuleStyles( $moduleMembers );
2636 $this->addModules( $modules );
2642 * Finally, all the text has been munged and accumulated into
2643 * the object, let's actually output it:
2645 * @param bool $return Set to true to get the result as a string rather than sending it
2646 * @return string|null
2648 * @throws FatalError
2649 * @throws MWException
2651 public function output( $return = false ) {
2652 if ( $this->mDoNothing
) {
2653 return $return ?
'' : null;
2656 $response = $this->getRequest()->response();
2657 $config = $this->getConfig();
2659 if ( $this->mRedirect
!= '' ) {
2660 # Standards require redirect URLs to be absolute
2661 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2663 $redirect = $this->mRedirect
;
2664 $code = $this->mRedirectCode
;
2666 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2667 if ( $code == '301' ||
$code == '303' ) {
2668 if ( !$config->get( 'DebugRedirects' ) ) {
2669 $response->statusHeader( $code );
2671 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2673 if ( $config->get( 'VaryOnXFP' ) ) {
2674 $this->addVaryHeader( 'X-Forwarded-Proto' );
2676 $this->sendCacheControl();
2678 $response->header( "Content-Type: text/html; charset=utf-8" );
2679 if ( $config->get( 'DebugRedirects' ) ) {
2680 $url = htmlspecialchars( $redirect );
2681 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2682 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2683 print "</body>\n</html>\n";
2685 $response->header( 'Location: ' . $redirect );
2689 return $return ?
'' : null;
2690 } elseif ( $this->mStatusCode
) {
2691 $response->statusHeader( $this->mStatusCode
);
2694 # Buffer output; final headers may depend on later processing
2697 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2698 $response->header( 'Content-language: ' .
2699 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2701 $linkHeader = $this->getLinkHeader();
2702 if ( $linkHeader ) {
2703 $response->header( $linkHeader );
2706 // Prevent framing, if requested
2707 $frameOptions = $this->getFrameOptions();
2708 if ( $frameOptions ) {
2709 $response->header( "X-Frame-Options: $frameOptions" );
2712 $originTrials = $this->getOriginTrials();
2713 foreach ( $originTrials as $originTrial ) {
2714 $response->header( "Origin-Trial: $originTrial", false );
2717 $reportTo = $this->getReportTo();
2719 $response->header( "Report-To: $reportTo" );
2722 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2723 if ( $featurePolicyReportOnly ) {
2724 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2727 ContentSecurityPolicy
::sendHeaders( $this );
2729 if ( $this->mArticleBodyOnly
) {
2730 echo $this->mBodytext
;
2732 // Enable safe mode if requested (T152169)
2733 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2734 $this->disallowUserJs();
2737 $sk = $this->getSkin();
2738 $this->loadSkinModules( $sk );
2740 MWDebug
::addModules( $this );
2742 // Avoid PHP 7.1 warning of passing $this by reference
2743 $outputPage = $this;
2744 // Hook that allows last minute changes to the output page, e.g.
2745 // adding of CSS or Javascript by extensions.
2746 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2750 } catch ( Exception
$e ) {
2751 ob_end_clean(); // bug T129657
2757 // This hook allows last minute changes to final overall output by modifying output buffer
2758 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2759 } catch ( Exception
$e ) {
2760 ob_end_clean(); // bug T129657
2764 $this->sendCacheControl();
2767 return ob_get_clean();
2775 * Prepare this object to display an error page; disable caching and
2776 * indexing, clear the current text and redirect, set the page's title
2777 * and optionally an custom HTML title (content of the "<title>" tag).
2779 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2780 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2781 * optional, if not passed the "<title>" attribute will be
2782 * based on $pageTitle
2784 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2785 $this->setPageTitle( $pageTitle );
2786 if ( $htmlTitle !== false ) {
2787 $this->setHTMLTitle( $htmlTitle );
2789 $this->setRobotPolicy( 'noindex,nofollow' );
2790 $this->setArticleRelated( false );
2791 $this->enableClientCache( false );
2792 $this->mRedirect
= '';
2793 $this->clearSubtitle();
2798 * Output a standard error page
2800 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2801 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2802 * showErrorPage( 'titlemsg', $messageObject );
2803 * showErrorPage( $titleMessageObject, $messageObject );
2805 * @param string|Message $title Message key (string) for page title, or a Message object
2806 * @param string|Message $msg Message key (string) for page text, or a Message object
2807 * @param array $params Message parameters; ignored if $msg is a Message object
2809 public function showErrorPage( $title, $msg, $params = [] ) {
2810 if ( !$title instanceof Message
) {
2811 $title = $this->msg( $title );
2814 $this->prepareErrorPage( $title );
2816 if ( $msg instanceof Message
) {
2817 if ( $params !== [] ) {
2818 trigger_error( 'Argument ignored: $params. The message parameters argument '
2819 . 'is discarded when the $msg argument is a Message object instead of '
2820 . 'a string.', E_USER_NOTICE
);
2822 $this->addHTML( $msg->parseAsBlock() );
2824 $this->addWikiMsgArray( $msg, $params );
2827 $this->returnToMain();
2831 * Output a standard permission error page
2833 * @param array $errors Error message keys or [key, param...] arrays
2834 * @param string|null $action Action that was denied or null if unknown
2836 public function showPermissionsErrorPage( array $errors, $action = null ) {
2837 foreach ( $errors as $key => $error ) {
2838 $errors[$key] = (array)$error;
2841 // For some action (read, edit, create and upload), display a "login to do this action"
2842 // error if all of the following conditions are met:
2843 // 1. the user is not logged in
2844 // 2. the only error is insufficient permissions (i.e. no block or something else)
2845 // 3. the error can be avoided simply by logging in
2846 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2847 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2848 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2849 && ( User
::groupHasPermission( 'user', $action )
2850 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2852 $displayReturnto = null;
2854 # Due to T34276, if a user does not have read permissions,
2855 # $this->getTitle() will just give Special:Badtitle, which is
2856 # not especially useful as a returnto parameter. Use the title
2857 # from the request instead, if there was one.
2858 $request = $this->getRequest();
2859 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2860 if ( $action == 'edit' ) {
2861 $msg = 'whitelistedittext';
2862 $displayReturnto = $returnto;
2863 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2864 $msg = 'nocreatetext';
2865 } elseif ( $action == 'upload' ) {
2866 $msg = 'uploadnologintext';
2868 $msg = 'loginreqpagetext';
2869 $displayReturnto = Title
::newMainPage();
2875 $query['returnto'] = $returnto->getPrefixedText();
2877 if ( !$request->wasPosted() ) {
2878 $returntoquery = $request->getValues();
2879 unset( $returntoquery['title'] );
2880 unset( $returntoquery['returnto'] );
2881 unset( $returntoquery['returntoquery'] );
2882 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2886 $services = MediaWikiServices
::getInstance();
2888 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2889 $linkRenderer = $services->getLinkRenderer();
2890 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2891 $loginLink = $linkRenderer->makeKnownLink(
2893 $this->msg( 'loginreqlink' )->text(),
2898 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2899 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2901 $permissionManager = $services->getPermissionManager();
2903 # Don't return to a page the user can't read otherwise
2904 # we'll end up in a pointless loop
2905 if ( $displayReturnto && $permissionManager->userCan(
2906 'read', $this->getUser(), $displayReturnto
2908 $this->returnToMain( null, $displayReturnto );
2911 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2912 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2917 * Display an error page indicating that a given version of MediaWiki is
2918 * required to use it
2920 * @param mixed $version The version of MediaWiki needed to use the page
2922 public function versionRequired( $version ) {
2923 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2925 $this->addWikiMsg( 'versionrequiredtext', $version );
2926 $this->returnToMain();
2930 * Format a list of error messages
2932 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2933 * @param string|null $action Action that was denied or null if unknown
2934 * @return string The wikitext error-messages, formatted into a list.
2936 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2937 if ( $action == null ) {
2938 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2940 $action_desc = $this->msg( "action-$action" )->plain();
2942 'permissionserrorstext-withaction',
2945 )->plain() . "\n\n";
2948 if ( count( $errors ) > 1 ) {
2949 $text .= '<ul class="permissions-errors">' . "\n";
2951 foreach ( $errors as $error ) {
2953 $text .= $this->msg( ...$error )->plain();
2958 $text .= "<div class=\"permissions-errors\">\n" .
2959 $this->msg( ...reset( $errors ) )->plain() .
2967 * Show a warning about replica DB lag
2969 * If the lag is higher than $wgSlaveLagCritical seconds,
2970 * then the warning is a bit more obvious. If the lag is
2971 * lower than $wgSlaveLagWarning, then no warning is shown.
2973 * @param int $lag Replica lag
2975 public function showLagWarning( $lag ) {
2976 $config = $this->getConfig();
2977 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2978 $lag = floor( $lag ); // floor to avoid nano seconds to display
2979 $message = $lag < $config->get( 'SlaveLagCritical' )
2982 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2983 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2988 * Output an error page
2990 * @note FatalError exception class provides an alternative.
2991 * @param string $message Error to output. Must be escaped for HTML.
2993 public function showFatalError( $message ) {
2994 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2996 $this->addHTML( $message );
3000 * Add a "return to" link pointing to a specified title
3002 * @param Title $title Title to link
3003 * @param array $query Query string parameters
3004 * @param string|null $text Text of the link (input is not escaped)
3005 * @param array $options Options array to pass to Linker
3007 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3008 $linkRenderer = MediaWikiServices
::getInstance()
3009 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3010 $link = $this->msg( 'returnto' )->rawParams(
3011 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3012 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3016 * Add a "return to" link pointing to a specified title,
3017 * or the title indicated in the request, or else the main page
3019 * @param mixed|null $unused
3020 * @param Title|string|null $returnto Title or String to return to
3021 * @param string|null $returntoquery Query string for the return to link
3023 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3024 if ( $returnto == null ) {
3025 $returnto = $this->getRequest()->getText( 'returnto' );
3028 if ( $returntoquery == null ) {
3029 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
3032 if ( $returnto === '' ) {
3033 $returnto = Title
::newMainPage();
3036 if ( is_object( $returnto ) ) {
3037 $titleObj = $returnto;
3039 $titleObj = Title
::newFromText( $returnto );
3041 // We don't want people to return to external interwiki. That
3042 // might potentially be used as part of a phishing scheme
3043 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
3044 $titleObj = Title
::newMainPage();
3047 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
3050 private function getRlClientContext() {
3051 if ( !$this->rlClientContext
) {
3052 $query = ResourceLoader
::makeLoaderQuery(
3053 [], // modules; not relevant
3054 $this->getLanguage()->getCode(),
3055 $this->getSkin()->getSkinName(),
3056 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
3057 null, // version; not relevant
3058 ResourceLoader
::inDebugMode(),
3059 null, // only; not relevant
3060 $this->isPrintable(),
3061 $this->getRequest()->getBool( 'handheld' )
3063 $this->rlClientContext
= new ResourceLoaderContext(
3064 $this->getResourceLoader(),
3065 new FauxRequest( $query )
3067 if ( $this->contentOverrideCallbacks
) {
3068 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
3069 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
3070 foreach ( $this->contentOverrideCallbacks
as $callback ) {
3071 $content = $callback( $title );
3072 if ( $content !== null ) {
3073 $text = ContentHandler
::getContentText( $content );
3074 if ( strpos( $text, '</script>' ) !== false ) {
3075 // Proactively replace this so that we can display a message
3076 // to the user, instead of letting it go to Html::inlineScript(),
3077 // where it would be considered a server-side issue.
3078 $titleFormatted = $title->getPrefixedText();
3079 $content = new JavaScriptContent(
3080 Xml
::encodeJsCall( 'mw.log.error', [
3081 "Cannot preview $titleFormatted due to script-closing tag."
3092 return $this->rlClientContext
;
3096 * Call this to freeze the module queue and JS config and create a formatter.
3098 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3099 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3100 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3101 * the module filters retroactively. Skins and extension hooks may also add modules until very
3102 * late in the request lifecycle.
3104 * @return ResourceLoaderClientHtml
3106 public function getRlClient() {
3107 if ( !$this->rlClient
) {
3108 $context = $this->getRlClientContext();
3109 $rl = $this->getResourceLoader();
3110 $this->addModules( [
3115 $this->addModuleStyles( [
3120 $this->getSkin()->setupSkinUserCss( $this );
3122 // Prepare exempt modules for buildExemptModules()
3123 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
3125 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3127 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
3128 // Separate user-specific batch for improved cache-hit ratio.
3129 $userBatch = [ 'user.styles', 'user' ];
3130 $siteBatch = array_diff( $moduleStyles, $userBatch );
3131 $dbr = wfGetDB( DB_REPLICA
);
3132 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
3133 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
3135 // Filter out modules handled by buildExemptModules()
3136 $moduleStyles = array_filter( $moduleStyles,
3137 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3138 $module = $rl->getModule( $name );
3140 $group = $module->getGroup();
3141 if ( isset( $exemptGroups[$group] ) ) {
3142 $exemptStates[$name] = 'ready';
3143 if ( !$module->isKnownEmpty( $context ) ) {
3144 // E.g. Don't output empty <styles>
3145 $exemptGroups[$group][] = $name;
3153 $this->rlExemptStyleModules
= $exemptGroups;
3155 $rlClient = new ResourceLoaderClientHtml( $context, [
3156 'target' => $this->getTarget(),
3157 'nonce' => $this->getCSPNonce(),
3158 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3159 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3160 // modules enqueud for loading on this page is filtered to just those.
3161 // However, to make sure we also apply the restriction to dynamic dependencies and
3162 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3163 // StartupModule so that the client-side registry will not contain any restricted
3164 // modules either. (T152169, T185303)
3165 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
3166 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
3169 $rlClient->setConfig( $this->getJSVars() );
3170 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3171 $rlClient->setModuleStyles( $moduleStyles );
3172 $rlClient->setExemptStates( $exemptStates );
3173 $this->rlClient
= $rlClient;
3175 return $this->rlClient
;
3179 * @param Skin $sk The given Skin
3180 * @param bool $includeStyle Unused
3181 * @return string The doctype, opening "<html>", and head element.
3183 public function headElement( Skin
$sk, $includeStyle = true ) {
3184 $userdir = $this->getLanguage()->getDir();
3185 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3188 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
3189 $this->getRlClient()->getDocumentAttributes(),
3190 $sk->getHtmlElementAttributes()
3192 $pieces[] = Html
::openElement( 'head' );
3194 if ( $this->getHTMLTitle() == '' ) {
3195 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3198 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
3199 // Add <meta charset="UTF-8">
3200 // This should be before <title> since it defines the charset used by
3201 // text including the text inside <title>.
3202 // The spec recommends defining XHTML5's charset using the XML declaration
3204 // Our XML declaration is output by Html::htmlHeader.
3205 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3206 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3207 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3210 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3211 $pieces[] = $this->getRlClient()->getHeadHtml();
3212 $pieces[] = $this->buildExemptModules();
3213 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3214 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3216 // Use an IE conditional comment to serve the script only to old IE
3217 $pieces[] = '<!--[if lt IE 9]>' .
3218 ResourceLoaderClientHtml
::makeLoad(
3219 new ResourceLoaderContext(
3220 $this->getResourceLoader(),
3221 new FauxRequest( [] )
3224 ResourceLoaderModule
::TYPE_SCRIPTS
,
3225 [ 'raw' => '1', 'sync' => '1' ],
3226 $this->getCSPNonce()
3230 $pieces[] = Html
::closeElement( 'head' );
3232 $bodyClasses = $this->mAdditionalBodyClasses
;
3233 $bodyClasses[] = 'mediawiki';
3235 # Classes for LTR/RTL directionality support
3236 $bodyClasses[] = $userdir;
3237 $bodyClasses[] = "sitedir-$sitedir";
3239 $underline = $this->getUser()->getOption( 'underline' );
3240 if ( $underline < 2 ) {
3241 // The following classes can be used here:
3242 // * mw-underline-always
3243 // * mw-underline-never
3244 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
3247 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3248 # A <body> class is probably not the best way to do this . . .
3249 $bodyClasses[] = 'capitalize-all-nouns';
3252 // Parser feature migration class
3253 // The idea is that this will eventually be removed, after the wikitext
3254 // which requires it is cleaned up.
3255 $bodyClasses[] = 'mw-hide-empty-elt';
3257 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3258 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3260 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3263 // While the implode() is not strictly needed, it's used for backwards compatibility
3264 // (this used to be built as a string and hooks likely still expect that).
3265 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3267 // Allow skins and extensions to add body attributes they need
3268 $sk->addToBodyAttributes( $this, $bodyAttrs );
3269 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3271 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3273 return self
::combineWrappedStrings( $pieces );
3277 * Get a ResourceLoader object associated with this OutputPage
3279 * @return ResourceLoader
3281 public function getResourceLoader() {
3282 if ( is_null( $this->mResourceLoader
) ) {
3283 // Lazy-initialise as needed
3284 $this->mResourceLoader
= MediaWikiServices
::getInstance()->getResourceLoader();
3286 return $this->mResourceLoader
;
3290 * Explicily load or embed modules on a page.
3292 * @param array|string $modules One or more module names
3293 * @param string $only ResourceLoaderModule TYPE_ class constant
3294 * @param array $extraQuery [optional] Array with extra query parameters for the request
3295 * @return string|WrappedStringList HTML
3297 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3298 // Apply 'target' and 'origin' filters
3299 $modules = $this->filterModules( (array)$modules, null, $only );
3301 return ResourceLoaderClientHtml
::makeLoad(
3302 $this->getRlClientContext(),
3306 $this->getCSPNonce()
3311 * Combine WrappedString chunks and filter out empty ones
3313 * @param array $chunks
3314 * @return string|WrappedStringList HTML
3316 protected static function combineWrappedStrings( array $chunks ) {
3317 // Filter out empty values
3318 $chunks = array_filter( $chunks, 'strlen' );
3319 return WrappedString
::join( "\n", $chunks );
3323 * JS stuff to put at the bottom of the `<body>`.
3324 * These are legacy scripts ($this->mScripts), and user JS.
3326 * @return string|WrappedStringList HTML
3328 public function getBottomScripts() {
3330 $chunks[] = $this->getRlClient()->getBodyHtml();
3332 // Legacy non-ResourceLoader scripts
3333 $chunks[] = $this->mScripts
;
3335 if ( $this->limitReportJSData
) {
3336 $chunks[] = ResourceLoader
::makeInlineScript(
3337 ResourceLoader
::makeConfigSetScript(
3338 [ 'wgPageParseReport' => $this->limitReportJSData
]
3340 $this->getCSPNonce()
3344 return self
::combineWrappedStrings( $chunks );
3348 * Get the javascript config vars to include on this page
3350 * @return array Array of javascript config vars
3353 public function getJsConfigVars() {
3354 return $this->mJsConfigVars
;
3358 * Add one or more variables to be set in mw.config in JavaScript
3360 * @param string|array $keys Key or array of key/value pairs
3361 * @param mixed|null $value [optional] Value of the configuration variable
3363 public function addJsConfigVars( $keys, $value = null ) {
3364 if ( is_array( $keys ) ) {
3365 foreach ( $keys as $key => $value ) {
3366 $this->mJsConfigVars
[$key] = $value;
3371 $this->mJsConfigVars
[$keys] = $value;
3375 * Get an array containing the variables to be set in mw.config in JavaScript.
3377 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3378 * - in other words, page-independent/site-wide variables (without state).
3379 * You will only be adding bloat to the html page and causing page caches to
3380 * have to be purged on configuration changes.
3383 public function getJSVars() {
3386 $canonicalSpecialPageName = false; # T23115
3387 $services = MediaWikiServices
::getInstance();
3389 $title = $this->getTitle();
3390 $ns = $title->getNamespace();
3391 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
3392 $canonicalNamespace = $nsInfo->exists( $ns )
3393 ?
$nsInfo->getCanonicalName( $ns )
3394 : $title->getNsText();
3396 $sk = $this->getSkin();
3397 // Get the relevant title so that AJAX features can use the correct page name
3398 // when making API requests from certain special pages (T36972).
3399 $relevantTitle = $sk->getRelevantTitle();
3400 $relevantUser = $sk->getRelevantUser();
3402 if ( $ns == NS_SPECIAL
) {
3403 list( $canonicalSpecialPageName, /*...*/ ) =
3404 $services->getSpecialPageFactory()->
3405 resolveAlias( $title->getDBkey() );
3406 } elseif ( $this->canUseWikiPage() ) {
3407 $wikiPage = $this->getWikiPage();
3408 $curRevisionId = $wikiPage->getLatest();
3409 $articleId = $wikiPage->getId();
3412 $lang = $title->getPageViewLanguage();
3414 // Pre-process information
3415 $separatorTransTable = $lang->separatorTransformTable();
3416 $separatorTransTable = $separatorTransTable ?
: [];
3417 $compactSeparatorTransTable = [
3418 implode( "\t", array_keys( $separatorTransTable ) ),
3419 implode( "\t", $separatorTransTable ),
3421 $digitTransTable = $lang->digitTransformTable();
3422 $digitTransTable = $digitTransTable ?
: [];
3423 $compactDigitTransTable = [
3424 implode( "\t", array_keys( $digitTransTable ) ),
3425 implode( "\t", $digitTransTable ),
3428 $user = $this->getUser();
3431 'wgCanonicalNamespace' => $canonicalNamespace,
3432 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3433 'wgNamespaceNumber' => $title->getNamespace(),
3434 'wgPageName' => $title->getPrefixedDBkey(),
3435 'wgTitle' => $title->getText(),
3436 'wgCurRevisionId' => $curRevisionId,
3437 'wgRevisionId' => (int)$this->getRevisionId(),
3438 'wgArticleId' => $articleId,
3439 'wgIsArticle' => $this->isArticle(),
3440 'wgIsRedirect' => $title->isRedirect(),
3441 'wgAction' => Action
::getActionName( $this->getContext() ),
3442 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3443 'wgUserGroups' => $user->getEffectiveGroups(),
3444 'wgCategories' => $this->getCategories(),
3445 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3446 'wgPageContentLanguage' => $lang->getCode(),
3447 'wgPageContentModel' => $title->getContentModel(),
3448 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3449 'wgDigitTransformTable' => $compactDigitTransTable,
3450 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3451 'wgMonthNames' => $lang->getMonthNamesArray(),
3452 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3453 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3454 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3455 'wgRequestId' => WebRequest
::getRequestId(),
3456 'wgCSPNonce' => $this->getCSPNonce(),
3459 if ( $user->isLoggedIn() ) {
3460 $vars['wgUserId'] = $user->getId();
3461 $vars['wgUserEditCount'] = $user->getEditCount();
3462 $userReg = $user->getRegistration();
3463 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3464 // Get the revision ID of the oldest new message on the user's talk
3465 // page. This can be used for constructing new message alerts on
3467 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3470 $contLang = $services->getContentLanguage();
3471 if ( $contLang->hasVariants() ) {
3472 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3474 // Same test as SkinTemplate
3475 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3476 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3478 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3479 && $relevantTitle->quickUserCan( 'edit', $user )
3480 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3482 foreach ( $title->getRestrictionTypes() as $type ) {
3483 // Following keys are set in $vars:
3484 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3485 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3488 if ( $title->isMainPage() ) {
3489 $vars['wgIsMainPage'] = true;
3492 if ( $this->mRedirectedFrom
) {
3493 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3496 if ( $relevantUser ) {
3497 $vars['wgRelevantUserName'] = $relevantUser->getName();
3500 // Allow extensions to add their custom variables to the mw.config map.
3501 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3502 // page-dependant but site-wide (without state).
3503 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3504 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3506 // Merge in variables from addJsConfigVars last
3507 return array_merge( $vars, $this->getJsConfigVars() );
3511 * To make it harder for someone to slip a user a fake
3512 * JavaScript or CSS preview, a random token
3513 * is associated with the login session. If it's not
3514 * passed back with the preview request, we won't render
3519 public function userCanPreview() {
3520 $request = $this->getRequest();
3522 $request->getVal( 'action' ) !== 'submit' ||
3523 !$request->wasPosted()
3528 $user = $this->getUser();
3530 if ( !$user->isLoggedIn() ) {
3531 // Anons have predictable edit tokens
3534 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3538 $title = $this->getTitle();
3539 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3540 if ( count( $errors ) !== 0 ) {
3548 * @return array Array in format "link name or number => 'link html'".
3550 public function getHeadLinksArray() {
3554 $config = $this->getConfig();
3556 $canonicalUrl = $this->mCanonicalUrl
;
3558 $tags['meta-generator'] = Html
::element( 'meta', [
3559 'name' => 'generator',
3560 'content' => "MediaWiki $wgVersion",
3563 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3564 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3565 // fallbacks should come before the primary value so we need to reverse the array.
3566 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3567 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3568 'name' => 'referrer',
3569 'content' => $policy,
3574 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3575 if ( $p !== 'index,follow' ) {
3576 // http://www.robotstxt.org/wc/meta-user.html
3577 // Only show if it's different from the default robots policy
3578 $tags['meta-robots'] = Html
::element( 'meta', [
3584 foreach ( $this->mMetatags
as $tag ) {
3585 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3587 $tag[0] = substr( $tag[0], 5 );
3588 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3593 $tagName = "meta-{$tag[0]}";
3594 if ( isset( $tags[$tagName] ) ) {
3595 $tagName .= $tag[1];
3597 $tags[$tagName] = Html
::element( 'meta',
3600 'content' => $tag[1]
3605 foreach ( $this->mLinktags
as $tag ) {
3606 $tags[] = Html
::element( 'link', $tag );
3609 # Universal edit button
3610 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3611 $user = $this->getUser();
3612 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3613 && ( $this->getTitle()->exists() ||
3614 $this->getTitle()->quickUserCan( 'create', $user ) )
3616 // Original UniversalEditButton
3617 $msg = $this->msg( 'edit' )->text();
3618 $tags['universal-edit-button'] = Html
::element( 'link', [
3619 'rel' => 'alternate',
3620 'type' => 'application/x-wiki',
3622 'href' => $this->getTitle()->getEditURL(),
3624 // Alternate edit link
3625 $tags['alternative-edit'] = Html
::element( 'link', [
3628 'href' => $this->getTitle()->getEditURL(),
3633 # Generally the order of the favicon and apple-touch-icon links
3634 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3635 # uses whichever one appears later in the HTML source. Make sure
3636 # apple-touch-icon is specified first to avoid this.
3637 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3638 $tags['apple-touch-icon'] = Html
::element( 'link', [
3639 'rel' => 'apple-touch-icon',
3640 'href' => $config->get( 'AppleTouchIcon' )
3644 if ( $config->get( 'Favicon' ) !== false ) {
3645 $tags['favicon'] = Html
::element( 'link', [
3646 'rel' => 'shortcut icon',
3647 'href' => $config->get( 'Favicon' )
3651 # OpenSearch description link
3652 $tags['opensearch'] = Html
::element( 'link', [
3654 'type' => 'application/opensearchdescription+xml',
3655 'href' => wfScript( 'opensearch_desc' ),
3656 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3659 # Real Simple Discovery link, provides auto-discovery information
3660 # for the MediaWiki API (and potentially additional custom API
3661 # support such as WordPress or Twitter-compatible APIs for a
3662 # blogging extension, etc)
3663 $tags['rsd'] = Html
::element( 'link', [
3665 'type' => 'application/rsd+xml',
3666 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3667 // Whether RSD accepts relative or protocol-relative URLs is completely
3668 // undocumented, though.
3669 'href' => wfExpandUrl( wfAppendQuery(
3671 [ 'action' => 'rsd' ] ),
3677 if ( !$config->get( 'DisableLangConversion' ) ) {
3678 $lang = $this->getTitle()->getPageLanguage();
3679 if ( $lang->hasVariants() ) {
3680 $variants = $lang->getVariants();
3681 foreach ( $variants as $variant ) {
3682 $tags["variant-$variant"] = Html
::element( 'link', [
3683 'rel' => 'alternate',
3684 'hreflang' => LanguageCode
::bcp47( $variant ),
3685 'href' => $this->getTitle()->getLocalURL(
3686 [ 'variant' => $variant ] )
3690 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3691 $tags["variant-x-default"] = Html
::element( 'link', [
3692 'rel' => 'alternate',
3693 'hreflang' => 'x-default',
3694 'href' => $this->getTitle()->getLocalURL() ] );
3699 if ( $this->copyrightUrl
!== null ) {
3700 $copyright = $this->copyrightUrl
;
3703 if ( $config->get( 'RightsPage' ) ) {
3704 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3707 $copyright = $copy->getLocalURL();
3711 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3712 $copyright = $config->get( 'RightsUrl' );
3717 $tags['copyright'] = Html
::element( 'link', [
3719 'href' => $copyright ]
3724 if ( $config->get( 'Feed' ) ) {
3727 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3728 # Use the page name for the title. In principle, this could
3729 # lead to issues with having the same name for different feeds
3730 # corresponding to the same page, but we can't avoid that at
3733 $feedLinks[] = $this->feedLink(
3736 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3738 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3743 # Recent changes feed should appear on every page (except recentchanges,
3744 # that would be redundant). Put it after the per-page feed to avoid
3745 # changing existing behavior. It's still available, probably via a
3746 # menu in your browser. Some sites might have a different feed they'd
3747 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3748 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3749 # If so, use it instead.
3750 $sitename = $config->get( 'Sitename' );
3751 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3752 if ( $overrideSiteFeed ) {
3753 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3754 // Note, this->feedLink escapes the url.
3755 $feedLinks[] = $this->feedLink(
3758 $this->msg( "site-{$type}-feed", $sitename )->text()
3761 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3762 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3763 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3764 $feedLinks[] = $this->feedLink(
3766 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3767 # For grep: 'site-rss-feed', 'site-atom-feed'
3768 $this->msg( "site-{$format}-feed", $sitename )->text()
3773 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3774 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3775 # use OutputPage::addFeedLink() instead.
3776 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3778 $tags +
= $feedLinks;
3782 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3783 if ( $canonicalUrl !== false ) {
3784 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3785 } elseif ( $this->isArticleRelated() ) {
3786 // This affects all requests where "setArticleRelated" is true. This is
3787 // typically all requests that show content (query title, curid, oldid, diff),
3788 // and all wikipage actions (edit, delete, purge, info, history etc.).
3789 // It does not apply to File pages and Special pages.
3790 // 'history' and 'info' actions address page metadata rather than the page
3791 // content itself, so they may not be canonicalized to the view page url.
3792 // TODO: this ought to be better encapsulated in the Action class.
3793 $action = Action
::getActionName( $this->getContext() );
3794 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3795 $query = "action={$action}";
3799 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3801 $reqUrl = $this->getRequest()->getRequestURL();
3802 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3805 if ( $canonicalUrl !== false ) {
3806 $tags[] = Html
::element( 'link', [
3807 'rel' => 'canonical',
3808 'href' => $canonicalUrl
3812 // Allow extensions to add, remove and/or otherwise manipulate these links
3813 // If you want only to *add* <head> links, please use the addHeadItem()
3814 // (or addHeadItems() for multiple items) method instead.
3815 // This hook is provided as a last resort for extensions to modify these
3816 // links before the output is sent to client.
3817 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3823 * Generate a "<link rel/>" for a feed.
3825 * @param string $type Feed type
3826 * @param string $url URL to the feed
3827 * @param string $text Value of the "title" attribute
3828 * @return string HTML fragment
3830 private function feedLink( $type, $url, $text ) {
3831 return Html
::element( 'link', [
3832 'rel' => 'alternate',
3833 'type' => "application/$type+xml",
3840 * Add a local or specified stylesheet, with the given media options.
3841 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3843 * @param string $style URL to the file
3844 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3845 * @param string $condition For IE conditional comments, specifying an IE version
3846 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3848 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3851 $options['media'] = $media;
3854 $options['condition'] = $condition;
3857 $options['dir'] = $dir;
3859 $this->styles
[$style] = $options;
3863 * Adds inline CSS styles
3864 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3866 * @param mixed $style_css Inline CSS
3867 * @param string $flip Set to 'flip' to flip the CSS if needed
3869 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3870 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3871 # If wanted, and the interface is right-to-left, flip the CSS
3872 $style_css = CSSJanus
::transform( $style_css, true, false );
3874 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3878 * Build exempt modules and legacy non-ResourceLoader styles.
3880 * @return string|WrappedStringList HTML
3882 protected function buildExemptModules() {
3884 // Things that go after the ResourceLoaderDynamicStyles marker
3887 // We want site, private and user styles to override dynamically added styles from
3888 // general modules, but we want dynamically added styles to override statically added
3889 // style modules. So the order has to be:
3890 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3891 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3892 // - ResourceLoaderDynamicStyles marker
3893 // - site/private/user styles
3895 // Add legacy styles added through addStyle()/addInlineStyle() here
3896 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3898 $chunks[] = Html
::element(
3900 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3903 $separateReq = [ 'site.styles', 'user.styles' ];
3904 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3905 // Combinable modules
3906 $chunks[] = $this->makeResourceLoaderLink(
3907 array_diff( $moduleNames, $separateReq ),
3908 ResourceLoaderModule
::TYPE_STYLES
3911 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3912 // These require their own dedicated request in order to support "@import"
3913 // syntax, which is incompatible with concatenation. (T147667, T37562)
3914 $chunks[] = $this->makeResourceLoaderLink( $name,
3915 ResourceLoaderModule
::TYPE_STYLES
3920 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3926 public function buildCssLinksArray() {
3929 foreach ( $this->styles
as $file => $options ) {
3930 $link = $this->styleLink( $file, $options );
3932 $links[$file] = $link;
3939 * Generate \<link\> tags for stylesheets
3941 * @param string $style URL to the file
3942 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3943 * @return string HTML fragment
3945 protected function styleLink( $style, array $options ) {
3946 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3950 if ( isset( $options['media'] ) ) {
3951 $media = self
::transformCssMedia( $options['media'] );
3952 if ( is_null( $media ) ) {
3959 if ( substr( $style, 0, 1 ) == '/' ||
3960 substr( $style, 0, 5 ) == 'http:' ||
3961 substr( $style, 0, 6 ) == 'https:' ) {
3964 $config = $this->getConfig();
3965 // Append file hash as query parameter
3966 $url = self
::transformResourcePath(
3968 $config->get( 'StylePath' ) . '/' . $style
3972 $link = Html
::linkedStyle( $url, $media );
3974 if ( isset( $options['condition'] ) ) {
3975 $condition = htmlspecialchars( $options['condition'] );
3976 $link = "<!--[if $condition]>$link<![endif]-->";
3982 * Transform path to web-accessible static resource.
3984 * This is used to add a validation hash as query string.
3985 * This aids various behaviors:
3987 * - Put long Cache-Control max-age headers on responses for improved
3988 * cache performance.
3989 * - Get the correct version of a file as expected by the current page.
3990 * - Instantly get the updated version of a file after deployment.
3992 * Avoid using this for urls included in HTML as otherwise clients may get different
3993 * versions of a resource when navigating the site depending on when the page was cached.
3994 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3995 * an external stylesheet).
3998 * @param Config $config
3999 * @param string $path Path-absolute URL to file (from document root, must start with "/")
4000 * @return string URL
4002 public static function transformResourcePath( Config
$config, $path ) {
4006 $remotePathPrefix = $config->get( 'ResourceBasePath' );
4007 if ( $remotePathPrefix === '' ) {
4008 // The configured base path is required to be empty string for
4009 // wikis in the domain root
4012 $remotePath = $remotePathPrefix;
4014 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
4015 // - Path is outside wgResourceBasePath, ignore.
4016 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
4019 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
4020 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
4021 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
4022 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
4023 $uploadPath = $config->get( 'UploadPath' );
4024 if ( strpos( $path, $uploadPath ) === 0 ) {
4025 $localDir = $config->get( 'UploadDirectory' );
4026 $remotePathPrefix = $remotePath = $uploadPath;
4029 $path = RelPath
::getRelativePath( $path, $remotePath );
4030 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
4034 * Utility method for transformResourceFilePath().
4036 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
4039 * @param string $remotePathPrefix URL path prefix that points to $localPath
4040 * @param string $localPath File directory exposed at $remotePath
4041 * @param string $file Path to target file relative to $localPath
4042 * @return string URL
4044 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4045 $hash = md5_file( "$localPath/$file" );
4046 if ( $hash === false ) {
4047 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
4050 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
4054 * Transform "media" attribute based on request parameters
4056 * @param string $media Current value of the "media" attribute
4057 * @return string Modified value of the "media" attribute, or null to skip
4060 public static function transformCssMedia( $media ) {
4063 // https://www.w3.org/TR/css3-mediaqueries/#syntax
4064 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
4066 // Switch in on-screen display for media testing
4068 'printable' => 'print',
4069 'handheld' => 'handheld',
4071 foreach ( $switches as $switch => $targetMedia ) {
4072 if ( $wgRequest->getBool( $switch ) ) {
4073 if ( $media == $targetMedia ) {
4075 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4076 /* This regex will not attempt to understand a comma-separated media_query_list
4078 * Example supported values for $media:
4079 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
4080 * Example NOT supported value for $media:
4081 * '3d-glasses, screen, print and resolution > 90dpi'
4083 * If it's a print request, we never want any kind of screen stylesheets
4084 * If it's a handheld request (currently the only other choice with a switch),
4085 * we don't want simple 'screen' but we might want screen queries that
4086 * have a max-width or something, so we'll pass all others on and let the
4087 * client do the query.
4089 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
4100 * Add a wikitext-formatted message to the output.
4101 * This is equivalent to:
4103 * $wgOut->addWikiText( wfMessage( ... )->plain() )
4105 public function addWikiMsg( /*...*/ ) {
4106 $args = func_get_args();
4107 $name = array_shift( $args );
4108 $this->addWikiMsgArray( $name, $args );
4112 * Add a wikitext-formatted message to the output.
4113 * Like addWikiMsg() except the parameters are taken as an array
4114 * instead of a variable argument list.
4116 * @param string $name
4117 * @param array $args
4119 public function addWikiMsgArray( $name, $args ) {
4120 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
4124 * This function takes a number of message/argument specifications, wraps them in
4125 * some overall structure, and then parses the result and adds it to the output.
4127 * In the $wrap, $1 is replaced with the first message, $2 with the second,
4128 * and so on. The subsequent arguments may be either
4129 * 1) strings, in which case they are message names, or
4130 * 2) arrays, in which case, within each array, the first element is the message
4131 * name, and subsequent elements are the parameters to that message.
4133 * Don't use this for messages that are not in the user's interface language.
4137 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
4141 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
4142 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
4144 * The newline after the opening div is needed in some wikitext. See T21226.
4146 * @param string $wrap
4148 public function wrapWikiMsg( $wrap /*, ...*/ ) {
4149 $msgSpecs = func_get_args();
4150 array_shift( $msgSpecs );
4151 $msgSpecs = array_values( $msgSpecs );
4153 foreach ( $msgSpecs as $n => $spec ) {
4154 if ( is_array( $spec ) ) {
4156 $name = array_shift( $args );
4157 if ( isset( $args['options'] ) ) {
4158 unset( $args['options'] );
4160 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
4168 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
4170 $this->addWikiTextAsInterface( $s );
4174 * Whether the output has a table of contents
4178 public function isTOCEnabled() {
4179 return $this->mEnableTOC
;
4183 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
4186 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
4188 public function enableSectionEditLinks( $flag = true ) {
4189 wfDeprecated( __METHOD__
, '1.31' );
4193 * Helper function to setup the PHP implementation of OOUI to use in this request.
4196 * @param string $skinName The Skin name to determine the correct OOUI theme
4197 * @param string $dir Language direction
4199 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4200 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4201 $theme = $themes[$skinName] ??
$themes['default'];
4202 // For example, 'OOUI\WikimediaUITheme'.
4203 $themeClass = "OOUI\\{$theme}Theme";
4204 OOUI\Theme
::setSingleton( new $themeClass() );
4205 OOUI\Element
::setDefaultDir( $dir );
4209 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4210 * MediaWiki and this OutputPage instance.
4214 public function enableOOUI() {
4216 strtolower( $this->getSkin()->getSkinName() ),
4217 $this->getLanguage()->getDir()
4219 $this->addModuleStyles( [
4220 'oojs-ui-core.styles',
4221 'oojs-ui.styles.indicators',
4222 'oojs-ui.styles.textures',
4223 'mediawiki.widgets.styles',
4224 'oojs-ui-core.icons',
4229 * Get (and set if not yet set) the CSP nonce.
4231 * This value needs to be included in any <script> tags on the
4234 * @return string|bool Nonce or false to mean don't output nonce
4237 public function getCSPNonce() {
4238 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4241 if ( $this->CSPNonce
=== null ) {
4242 // XXX It might be expensive to generate randomness
4243 // on every request, on Windows.
4244 $rand = random_bytes( 15 );
4245 $this->CSPNonce
= base64_encode( $rand );
4247 return $this->CSPNonce
;