3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Session\SessionManager
;
27 use Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\RelPath
;
29 use Wikimedia\WrappedString
;
30 use Wikimedia\WrappedStringList
;
33 * This class should be covered by a general architecture document which does
34 * not exist as of January 2011. This is one of the Core classes and should
35 * be read at least once by any new developers.
37 * This class is used to prepare the final rendering. A skin is then
38 * applied to the output parameters (links, javascript, html, categories ...).
40 * @todo FIXME: Another class handles sending the whole page to the client.
42 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
47 class OutputPage
extends ContextSource
{
48 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
49 protected $mMetatags = [];
52 protected $mLinktags = [];
55 protected $mCanonicalUrl = false;
58 * @var string The contents of <h1> */
59 private $mPageTitle = '';
62 * @var string The displayed title of the page. Different from page title
63 * if overridden by display title magic word or hooks. Can contain safe
64 * HTML. Different from page title which may contain messages such as
65 * "Editing X" which is displayed in h1. This can be used for other places
66 * where the page name is referred on the page.
68 private $displayTitle;
71 * @var string Contains all of the "<body>" content. Should be private we
72 * got set/get accessors and the append() method.
74 public $mBodytext = '';
76 /** @var string Stores contents of "<title>" tag */
77 private $mHTMLtitle = '';
80 * @var bool Is the displayed content related to the source of the
81 * corresponding wiki article.
83 private $mIsArticle = false;
85 /** @var bool Stores "article flag" toggle. */
86 private $mIsArticleRelated = true;
88 /** @var bool Is the content subject to copyright */
89 private $mHasCopyright = false;
92 * @var bool We have to set isPrintable(). Some pages should
93 * never be printed (ex: redirections).
95 private $mPrintable = false;
98 * @var array Contains the page subtitle. Special pages usually have some
99 * links here. Don't confuse with site subtitle added by skins.
101 private $mSubtitle = [];
104 public $mRedirect = '';
107 protected $mStatusCode;
110 * @var string Used for sending cache control.
111 * The whole caching system should probably be moved into its own class.
113 protected $mLastModified = '';
116 protected $mCategoryLinks = [];
119 protected $mCategories = [
125 protected $mIndicators = [];
127 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
128 private $mLanguageLinks = [];
131 * Used for JavaScript (predates ResourceLoader)
132 * @todo We should split JS / CSS.
133 * mScripts content is inserted as is in "<head>" by Skin. This might
134 * contain either a link to a stylesheet or inline CSS.
136 private $mScripts = '';
138 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
139 protected $mInlineStyles = '';
142 * @var string Used by skin template.
143 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
145 public $mPageLinkTitle = '';
147 /** @var array Array of elements in "<head>". Parser might add its own headers! */
148 protected $mHeadItems = [];
150 /** @var array Additional <body> classes; there are also <body> classes from other sources */
151 protected $mAdditionalBodyClasses = [];
154 protected $mModules = [];
157 protected $mModuleScripts = [];
160 protected $mModuleStyles = [];
162 /** @var ResourceLoader */
163 protected $mResourceLoader;
165 /** @var ResourceLoaderClientHtml */
168 /** @var ResourceLoaderContext */
169 private $rlClientContext;
172 private $rlExemptStyleModules;
175 protected $mJsConfigVars = [];
178 protected $mTemplateIds = [];
181 protected $mImageTimeKeys = [];
184 public $mRedirectCode = '';
186 protected $mFeedLinksAppendQuery = null;
189 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
190 * @see ResourceLoaderModule::$origin
191 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
193 protected $mAllowedModules = [
194 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
197 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
198 protected $mDoNothing = false;
203 protected $mContainsNewMagic = 0;
206 * lazy initialised, use parserOptions()
209 protected $mParserOptions = null;
212 * Handles the Atom / RSS links.
213 * We probably only support Atom in 2011.
214 * @see $wgAdvertisedFeedTypes
216 private $mFeedLinks = [];
218 // Gwicke work on squid caching? Roughly from 2003.
219 protected $mEnableClientCache = true;
221 /** @var bool Flag if output should only contain the body of the article. */
222 private $mArticleBodyOnly = false;
225 protected $mNewSectionLink = false;
228 protected $mHideNewSectionLink = false;
231 * @var bool Comes from the parser. This was probably made to load CSS/JS
232 * only if we had "<gallery>". Used directly in CategoryPage.php.
233 * Looks like ResourceLoader can replace this.
235 public $mNoGallery = false;
237 /** @var int Cache stuff. Looks like mEnableClientCache */
238 protected $mCdnMaxage = 0;
239 /** @var int Upper limit on mCdnMaxage */
240 protected $mCdnMaxageLimit = INF
;
243 * @var bool Controls if anti-clickjacking / frame-breaking headers will
244 * be sent. This should be done for pages where edit actions are possible.
245 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
247 protected $mPreventClickjacking = true;
249 /** @var int To include the variable {{REVISIONID}} */
250 private $mRevisionId = null;
253 private $mRevisionTimestamp = null;
256 protected $mFileVersion = null;
259 * @var array An array of stylesheet filenames (relative from skins path),
260 * with options for CSS media, IE conditions, and RTL/LTR direction.
261 * For internal use; add settings in the skin via $this->addStyle()
263 * Style again! This seems like a code duplication since we already have
264 * mStyles. This is what makes Open Source amazing.
266 protected $styles = [];
268 private $mIndexPolicy = 'index';
269 private $mFollowPolicy = 'follow';
272 * @var array Headers that cause the cache to vary. Key is header name, value is an array of
273 * options for the Key header.
275 private $mVaryHeader = [
276 'Accept-Encoding' => [ 'match=gzip' ],
280 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
285 private $mRedirectedFrom = null;
288 * Additional key => value data
290 private $mProperties = [];
293 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
295 private $mTarget = null;
298 * @var bool Whether parser output contains a table of contents
300 private $mEnableTOC = false;
303 * @var string|null The URL to send in a <link> element with rel=license
305 private $copyrightUrl;
307 /** @var array Profiling data */
308 private $limitReportJSData = [];
310 /** @var array Map Title to Content */
311 private $contentOverrides = [];
313 /** @var callable[] */
314 private $contentOverrideCallbacks = [];
317 * Link: header contents
319 private $mLinkHeader = [];
322 * @var string The nonce for Content-Security-Policy
327 * @var array A cache of the names of the cookies that will influence the cache
329 private static $cacheVaryCookies = null;
332 * Constructor for OutputPage. This should not be called directly.
333 * Instead a new RequestContext should be created and it will implicitly create
334 * a OutputPage tied to that context.
335 * @param IContextSource $context
337 function __construct( IContextSource
$context ) {
338 $this->setContext( $context );
342 * Redirect to $url rather than displaying the normal page
345 * @param string $responsecode HTTP status code
347 public function redirect( $url, $responsecode = '302' ) {
348 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
349 $this->mRedirect
= str_replace( "\n", '', $url );
350 $this->mRedirectCode
= $responsecode;
354 * Get the URL to redirect to, or an empty string if not redirect URL set
358 public function getRedirect() {
359 return $this->mRedirect
;
363 * Set the copyright URL to send with the output.
364 * Empty string to omit, null to reset.
368 * @param string|null $url
370 public function setCopyrightUrl( $url ) {
371 $this->copyrightUrl
= $url;
375 * Set the HTTP status code to send with the output.
377 * @param int $statusCode
379 public function setStatusCode( $statusCode ) {
380 $this->mStatusCode
= $statusCode;
384 * Add a new "<meta>" tag
385 * To add an http-equiv meta tag, precede the name with "http:"
387 * @param string $name Name of the meta tag
388 * @param string $val Value of the meta tag
390 function addMeta( $name, $val ) {
391 array_push( $this->mMetatags
, [ $name, $val ] );
395 * Returns the current <meta> tags
400 public function getMetaTags() {
401 return $this->mMetatags
;
405 * Add a new \<link\> tag to the page header.
407 * Note: use setCanonicalUrl() for rel=canonical.
409 * @param array $linkarr Associative array of attributes.
411 function addLink( array $linkarr ) {
412 array_push( $this->mLinktags
, $linkarr );
416 * Returns the current <link> tags
421 public function getLinkTags() {
422 return $this->mLinktags
;
426 * Set the URL to be used for the <link rel=canonical>. This should be used
427 * in preference to addLink(), to avoid duplicate link tags.
430 function setCanonicalUrl( $url ) {
431 $this->mCanonicalUrl
= $url;
435 * Returns the URL to be used for the <link rel=canonical> if
439 * @return bool|string
441 public function getCanonicalUrl() {
442 return $this->mCanonicalUrl
;
446 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
447 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
450 * @param string $script Raw HTML
452 function addScript( $script ) {
453 $this->mScripts
.= $script;
457 * Add a JavaScript file to be loaded as `<script>` on this page.
459 * Internal use only. Use OutputPage::addModules() if possible.
461 * @param string $file URL to file (absolute path, protocol-relative, or full url)
462 * @param string|null $unused Previously used to change the cache-busting query parameter
464 public function addScriptFile( $file, $unused = null ) {
465 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
466 // This is not an absolute path, protocol-relative url, or full scheme url,
467 // presumed to be an old call intended to include a file from /w/skins/common,
468 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
469 wfDeprecated( __METHOD__
, '1.24' );
472 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
476 * Add a self-contained script tag with the given contents
477 * Internal use only. Use OutputPage::addModules() if possible.
479 * @param string $script JavaScript text, no script tags
481 public function addInlineScript( $script ) {
482 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
486 * Filter an array of modules to remove insufficiently trustworthy members, and modules
487 * which are no longer registered (eg a page is cached before an extension is disabled)
488 * @param array $modules
489 * @param string|null $position Unused
490 * @param string $type
493 protected function filterModules( array $modules, $position = null,
494 $type = ResourceLoaderModule
::TYPE_COMBINED
496 $resourceLoader = $this->getResourceLoader();
497 $filteredModules = [];
498 foreach ( $modules as $val ) {
499 $module = $resourceLoader->getModule( $val );
500 if ( $module instanceof ResourceLoaderModule
501 && $module->getOrigin() <= $this->getAllowedModules( $type )
503 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
504 $this->warnModuleTargetFilter( $module->getName() );
507 $filteredModules[] = $val;
510 return $filteredModules;
513 private function warnModuleTargetFilter( $moduleName ) {
514 static $warnings = [];
515 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
518 $warnings[$this->mTarget
][$moduleName] = true;
519 $this->getResourceLoader()->getLogger()->debug(
520 'Module "{module}" not loadable on target "{target}".',
522 'module' => $moduleName,
523 'target' => $this->mTarget
,
529 * Get the list of modules to include on this page
531 * @param bool $filter Whether to filter out insufficiently trustworthy modules
532 * @param string|null $position Unused
533 * @param string $param
534 * @param string $type
535 * @return array Array of module names
537 public function getModules( $filter = false, $position = null, $param = 'mModules',
538 $type = ResourceLoaderModule
::TYPE_COMBINED
540 $modules = array_values( array_unique( $this->$param ) );
542 ?
$this->filterModules( $modules, null, $type )
547 * Load one or more ResourceLoader modules on this page.
549 * @param string|array $modules Module name (string) or array of module names
551 public function addModules( $modules ) {
552 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
556 * Get the list of script-only modules to load on this page.
558 * @param bool $filter
559 * @param string|null $position Unused
560 * @return array Array of module names
562 public function getModuleScripts( $filter = false, $position = null ) {
563 return $this->getModules( $filter, null, 'mModuleScripts',
564 ResourceLoaderModule
::TYPE_SCRIPTS
569 * Load the scripts of one or more ResourceLoader modules, on this page.
571 * This method exists purely to provide the legacy behaviour of loading
572 * a module's scripts in the global scope, and without dependency resolution.
573 * See <https://phabricator.wikimedia.org/T188689>.
575 * @deprecated since 1.31 Use addModules() instead.
576 * @param string|array $modules Module name (string) or array of module names
578 public function addModuleScripts( $modules ) {
579 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
583 * Get the list of style-only modules to load on this page.
585 * @param bool $filter
586 * @param string|null $position Unused
587 * @return array Array of module names
589 public function getModuleStyles( $filter = false, $position = null ) {
590 return $this->getModules( $filter, null, 'mModuleStyles',
591 ResourceLoaderModule
::TYPE_STYLES
596 * Load the styles of one or more ResourceLoader modules on this page.
598 * Module styles added through this function will be loaded as a stylesheet,
599 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
600 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
602 * @param string|array $modules Module name (string) or array of module names
604 public function addModuleStyles( $modules ) {
605 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
609 * @return null|string ResourceLoader target
611 public function getTarget() {
612 return $this->mTarget
;
616 * Sets ResourceLoader target for load.php links. If null, will be omitted
618 * @param string|null $target
620 public function setTarget( $target ) {
621 $this->mTarget
= $target;
625 * Add a mapping from a LinkTarget to a Content, for things like page preview.
626 * @see self::addContentOverrideCallback()
628 * @param LinkTarget $target
629 * @param Content $content
631 public function addContentOverride( LinkTarget
$target, Content
$content ) {
632 if ( !$this->contentOverrides
) {
633 // Register a callback for $this->contentOverrides on the first call
634 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
635 $key = $target->getNamespace() . ':' . $target->getDBkey();
636 return $this->contentOverrides
[$key] ??
null;
640 $key = $target->getNamespace() . ':' . $target->getDBkey();
641 $this->contentOverrides
[$key] = $content;
645 * Add a callback for mapping from a Title to a Content object, for things
647 * @see ResourceLoaderContext::getContentOverrideCallback()
649 * @param callable $callback
651 public function addContentOverrideCallback( callable
$callback ) {
652 $this->contentOverrideCallbacks
[] = $callback;
656 * Get an array of head items
660 function getHeadItemsArray() {
661 return $this->mHeadItems
;
665 * Add or replace a head item to the output
667 * Whenever possible, use more specific options like ResourceLoader modules,
668 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
669 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
670 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
671 * This would be your very LAST fallback.
673 * @param string $name Item name
674 * @param string $value Raw HTML
676 public function addHeadItem( $name, $value ) {
677 $this->mHeadItems
[$name] = $value;
681 * Add one or more head items to the output
684 * @param string|string[] $values Raw HTML
686 public function addHeadItems( $values ) {
687 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
691 * Check if the header item $name is already set
693 * @param string $name Item name
696 public function hasHeadItem( $name ) {
697 return isset( $this->mHeadItems
[$name] );
701 * Add a class to the <body> element
704 * @param string|string[] $classes One or more classes to add
706 public function addBodyClasses( $classes ) {
707 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
711 * Set whether the output should only contain the body of the article,
712 * without any skin, sidebar, etc.
713 * Used e.g. when calling with "action=render".
715 * @param bool $only Whether to output only the body of the article
717 public function setArticleBodyOnly( $only ) {
718 $this->mArticleBodyOnly
= $only;
722 * Return whether the output will contain only the body of the article
726 public function getArticleBodyOnly() {
727 return $this->mArticleBodyOnly
;
731 * Set an additional output property
734 * @param string $name
735 * @param mixed $value
737 public function setProperty( $name, $value ) {
738 $this->mProperties
[$name] = $value;
742 * Get an additional output property
745 * @param string $name
746 * @return mixed Property value or null if not found
748 public function getProperty( $name ) {
749 return $this->mProperties
[$name] ??
null;
753 * checkLastModified tells the client to use the client-cached page if
754 * possible. If successful, the OutputPage is disabled so that
755 * any future call to OutputPage->output() have no effect.
757 * Side effect: sets mLastModified for Last-Modified header
759 * @param string $timestamp
761 * @return bool True if cache-ok headers was sent.
763 public function checkLastModified( $timestamp ) {
764 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
765 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
768 $config = $this->getConfig();
769 if ( !$config->get( 'CachePages' ) ) {
770 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
774 $timestamp = wfTimestamp( TS_MW
, $timestamp );
776 'page' => $timestamp,
777 'user' => $this->getUser()->getTouched(),
778 'epoch' => $config->get( 'CacheEpoch' )
780 if ( $config->get( 'UseSquid' ) ) {
781 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
783 $config->get( 'SquidMaxage' )
786 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
788 $maxModified = max( $modifiedTimes );
789 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
791 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
792 if ( $clientHeader === false ) {
793 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
797 # IE sends sizes after the date like this:
798 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
799 # this breaks strtotime().
800 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
802 Wikimedia\
suppressWarnings(); // E_STRICT system time warnings
803 $clientHeaderTime = strtotime( $clientHeader );
804 Wikimedia\restoreWarnings
();
805 if ( !$clientHeaderTime ) {
807 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
810 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
814 foreach ( $modifiedTimes as $name => $value ) {
815 if ( $info !== '' ) {
818 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
821 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
822 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
823 wfDebug( __METHOD__
. ": effective Last-Modified: " .
824 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
825 if ( $clientHeaderTime < $maxModified ) {
826 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
831 # Give a 304 Not Modified response code and disable body output
832 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
833 ini_set( 'zlib.output_compression', 0 );
834 $this->getRequest()->response()->statusHeader( 304 );
835 $this->sendCacheControl();
838 // Don't output a compressed blob when using ob_gzhandler;
839 // it's technically against HTTP spec and seems to confuse
840 // Firefox when the response gets split over two packets.
841 wfClearOutputBuffers();
847 * @param int $reqTime Time of request (eg. now)
848 * @param int $maxAge Cache TTL in seconds
849 * @return int Timestamp
851 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
852 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
853 // because even if the wiki page content hasn't changed since, static
854 // resources may have changed (skin HTML, interface messages, urls, etc.)
855 // and must roll-over in a timely manner (T46570)
856 return $reqTime - $maxAge;
860 * Override the last modified timestamp
862 * @param string $timestamp New timestamp, in a format readable by
865 public function setLastModified( $timestamp ) {
866 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
870 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
872 * @param string $policy The literal string to output as the contents of
873 * the meta tag. Will be parsed according to the spec and output in
877 public function setRobotPolicy( $policy ) {
878 $policy = Article
::formatRobotPolicy( $policy );
880 if ( isset( $policy['index'] ) ) {
881 $this->setIndexPolicy( $policy['index'] );
883 if ( isset( $policy['follow'] ) ) {
884 $this->setFollowPolicy( $policy['follow'] );
889 * Set the index policy for the page, but leave the follow policy un-
892 * @param string $policy Either 'index' or 'noindex'.
895 public function setIndexPolicy( $policy ) {
896 $policy = trim( $policy );
897 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
898 $this->mIndexPolicy
= $policy;
903 * Set the follow policy for the page, but leave the index policy un-
906 * @param string $policy Either 'follow' or 'nofollow'.
909 public function setFollowPolicy( $policy ) {
910 $policy = trim( $policy );
911 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
912 $this->mFollowPolicy
= $policy;
917 * "HTML title" means the contents of "<title>".
918 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
920 * @param string|Message $name
922 public function setHTMLTitle( $name ) {
923 if ( $name instanceof Message
) {
924 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
926 $this->mHTMLtitle
= $name;
931 * Return the "HTML title", i.e. the content of the "<title>" tag.
935 public function getHTMLTitle() {
936 return $this->mHTMLtitle
;
940 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
944 public function setRedirectedFrom( $t ) {
945 $this->mRedirectedFrom
= $t;
949 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
950 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
951 * but not bad tags like \<script\>. This function automatically sets
952 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
953 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
954 * good tags like \<i\> will be dropped entirely.
956 * @param string|Message $name
958 public function setPageTitle( $name ) {
959 if ( $name instanceof Message
) {
960 $name = $name->setContext( $this->getContext() )->text();
963 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
964 # but leave "<i>foobar</i>" alone
965 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
966 $this->mPageTitle
= $nameWithTags;
968 # change "<i>foo&bar</i>" to "foo&bar"
970 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
971 ->inContentLanguage()
976 * Return the "page title", i.e. the content of the \<h1\> tag.
980 public function getPageTitle() {
981 return $this->mPageTitle
;
985 * Same as page title but only contains name of the page, not any other text.
988 * @param string $html Page title text.
989 * @see OutputPage::setPageTitle
991 public function setDisplayTitle( $html ) {
992 $this->displayTitle
= $html;
996 * Returns page display title.
998 * Performs some normalization, but this not as strict the magic word.
1001 * @return string HTML
1003 public function getDisplayTitle() {
1004 $html = $this->displayTitle
;
1005 if ( $html === null ) {
1006 $html = $this->getTitle()->getPrefixedText();
1009 return Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $html ) );
1013 * Returns page display title without namespace prefix if possible.
1016 * @return string HTML
1018 public function getUnprefixedDisplayTitle() {
1019 $text = $this->getDisplayTitle();
1020 $nsPrefix = $this->getTitle()->getNsText() . ':';
1021 $prefix = preg_quote( $nsPrefix, '/' );
1023 return preg_replace( "/^$prefix/i", '', $text );
1027 * Set the Title object to use
1031 public function setTitle( Title
$t ) {
1032 $this->getContext()->setTitle( $t );
1036 * Replace the subtitle with $str
1038 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1040 public function setSubtitle( $str ) {
1041 $this->clearSubtitle();
1042 $this->addSubtitle( $str );
1046 * Add $str to the subtitle
1048 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1050 public function addSubtitle( $str ) {
1051 if ( $str instanceof Message
) {
1052 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1054 $this->mSubtitle
[] = $str;
1059 * Build message object for a subtitle containing a backlink to a page
1061 * @param Title $title Title to link to
1062 * @param array $query Array of additional parameters to include in the link
1066 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1067 if ( $title->isRedirect() ) {
1068 $query['redirect'] = 'no';
1070 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1071 return wfMessage( 'backlinksubtitle' )
1072 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1076 * Add a subtitle containing a backlink to a page
1078 * @param Title $title Title to link to
1079 * @param array $query Array of additional parameters to include in the link
1081 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1082 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1086 * Clear the subtitles
1088 public function clearSubtitle() {
1089 $this->mSubtitle
= [];
1097 public function getSubtitle() {
1098 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1102 * Set the page as printable, i.e. it'll be displayed with all
1103 * print styles included
1105 public function setPrintable() {
1106 $this->mPrintable
= true;
1110 * Return whether the page is "printable"
1114 public function isPrintable() {
1115 return $this->mPrintable
;
1119 * Disable output completely, i.e. calling output() will have no effect
1121 public function disable() {
1122 $this->mDoNothing
= true;
1126 * Return whether the output will be completely disabled
1130 public function isDisabled() {
1131 return $this->mDoNothing
;
1135 * Show an "add new section" link?
1139 public function showNewSectionLink() {
1140 return $this->mNewSectionLink
;
1144 * Forcibly hide the new section link?
1148 public function forceHideNewSectionLink() {
1149 return $this->mHideNewSectionLink
;
1153 * Add or remove feed links in the page header
1154 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1155 * for the new version
1156 * @see addFeedLink()
1158 * @param bool $show True: add default feeds, false: remove all feeds
1160 public function setSyndicated( $show = true ) {
1162 $this->setFeedAppendQuery( false );
1164 $this->mFeedLinks
= [];
1169 * Add default feeds to the page header
1170 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1171 * for the new version
1172 * @see addFeedLink()
1174 * @param string $val Query to append to feed links or false to output
1177 public function setFeedAppendQuery( $val ) {
1178 $this->mFeedLinks
= [];
1180 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1181 $query = "feed=$type";
1182 if ( is_string( $val ) ) {
1183 $query .= '&' . $val;
1185 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1190 * Add a feed link to the page header
1192 * @param string $format Feed type, should be a key of $wgFeedClasses
1193 * @param string $href URL
1195 public function addFeedLink( $format, $href ) {
1196 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1197 $this->mFeedLinks
[$format] = $href;
1202 * Should we output feed links for this page?
1205 public function isSyndicated() {
1206 return count( $this->mFeedLinks
) > 0;
1210 * Return URLs for each supported syndication format for this page.
1211 * @return array Associating format keys with URLs
1213 public function getSyndicationLinks() {
1214 return $this->mFeedLinks
;
1218 * Will currently always return null
1222 public function getFeedAppendQuery() {
1223 return $this->mFeedLinksAppendQuery
;
1227 * Set whether the displayed content is related to the source of the
1228 * corresponding article on the wiki
1229 * Setting true will cause the change "article related" toggle to true
1231 * @param bool $newVal
1233 public function setArticleFlag( $newVal ) {
1234 $this->mIsArticle
= $newVal;
1236 $this->mIsArticleRelated
= $newVal;
1241 * Return whether the content displayed page is related to the source of
1242 * the corresponding article on the wiki
1246 public function isArticle() {
1247 return $this->mIsArticle
;
1251 * Set whether this page is related an article on the wiki
1252 * Setting false will cause the change of "article flag" toggle to false
1254 * @param bool $newVal
1256 public function setArticleRelated( $newVal ) {
1257 $this->mIsArticleRelated
= $newVal;
1259 $this->mIsArticle
= false;
1264 * Return whether this page is related an article on the wiki
1268 public function isArticleRelated() {
1269 return $this->mIsArticleRelated
;
1273 * Set whether the standard copyright should be shown for the current page.
1275 * @param bool $hasCopyright
1277 public function setCopyright( $hasCopyright ) {
1278 $this->mHasCopyright
= $hasCopyright;
1282 * Return whether the standard copyright should be shown for the current page.
1283 * By default, it is true for all articles but other pages
1284 * can signal it by using setCopyright( true ).
1286 * Used by SkinTemplate to decided whether to show the copyright.
1290 public function showsCopyright() {
1291 return $this->isArticle() ||
$this->mHasCopyright
;
1295 * Add new language links
1297 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1298 * (e.g. 'fr:Test page')
1300 public function addLanguageLinks( array $newLinkArray ) {
1301 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1305 * Reset the language links and add new language links
1307 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1308 * (e.g. 'fr:Test page')
1310 public function setLanguageLinks( array $newLinkArray ) {
1311 $this->mLanguageLinks
= $newLinkArray;
1315 * Get the list of language links
1317 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1319 public function getLanguageLinks() {
1320 return $this->mLanguageLinks
;
1324 * Add an array of categories, with names in the keys
1326 * @param array $categories Mapping category name => sort key
1328 public function addCategoryLinks( array $categories ) {
1329 if ( !$categories ) {
1333 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1335 # Set all the values to 'normal'.
1336 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1338 # Mark hidden categories
1339 foreach ( $res as $row ) {
1340 if ( isset( $row->pp_value
) ) {
1341 $categories[$row->page_title
] = 'hidden';
1345 // Avoid PHP 7.1 warning of passing $this by reference
1346 $outputPage = $this;
1347 # Add the remaining categories to the skin
1349 'OutputPageMakeCategoryLinks',
1350 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1352 $services = MediaWikiServices
::getInstance();
1353 $linkRenderer = $services->getLinkRenderer();
1354 foreach ( $categories as $category => $type ) {
1355 // array keys will cast numeric category names to ints, so cast back to string
1356 $category = (string)$category;
1357 $origcategory = $category;
1358 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1362 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1363 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1366 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1367 $this->mCategories
[$type][] = $title->getText();
1368 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1374 * @param array $categories
1375 * @return bool|IResultWrapper
1377 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1378 # Add the links to a LinkBatch
1379 $arr = [ NS_CATEGORY
=> $categories ];
1380 $lb = new LinkBatch
;
1381 $lb->setArray( $arr );
1383 # Fetch existence plus the hiddencat property
1384 $dbr = wfGetDB( DB_REPLICA
);
1385 $fields = array_merge(
1386 LinkCache
::getSelectFields(),
1387 [ 'page_namespace', 'page_title', 'pp_value' ]
1390 $res = $dbr->select( [ 'page', 'page_props' ],
1392 $lb->constructSet( 'page', $dbr ),
1395 [ 'page_props' => [ 'LEFT JOIN', [
1396 'pp_propname' => 'hiddencat',
1401 # Add the results to the link cache
1402 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1403 $lb->addResultToCache( $linkCache, $res );
1409 * Reset the category links (but not the category list) and add $categories
1411 * @param array $categories Mapping category name => sort key
1413 public function setCategoryLinks( array $categories ) {
1414 $this->mCategoryLinks
= [];
1415 $this->addCategoryLinks( $categories );
1419 * Get the list of category links, in a 2-D array with the following format:
1420 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1421 * hidden categories) and $link a HTML fragment with a link to the category
1426 public function getCategoryLinks() {
1427 return $this->mCategoryLinks
;
1431 * Get the list of category names this page belongs to.
1433 * @param string $type The type of categories which should be returned. Possible values:
1434 * * all: all categories of all types
1435 * * hidden: only the hidden categories
1436 * * normal: all categories, except hidden categories
1437 * @return array Array of strings
1439 public function getCategories( $type = 'all' ) {
1440 if ( $type === 'all' ) {
1441 $allCategories = [];
1442 foreach ( $this->mCategories
as $categories ) {
1443 $allCategories = array_merge( $allCategories, $categories );
1445 return $allCategories;
1447 if ( !isset( $this->mCategories
[$type] ) ) {
1448 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1450 return $this->mCategories
[$type];
1454 * Add an array of indicators, with their identifiers as array
1455 * keys and HTML contents as values.
1457 * In case of duplicate keys, existing values are overwritten.
1459 * @param array $indicators
1462 public function setIndicators( array $indicators ) {
1463 $this->mIndicators
= $indicators +
$this->mIndicators
;
1464 // Keep ordered by key
1465 ksort( $this->mIndicators
);
1469 * Get the indicators associated with this page.
1471 * The array will be internally ordered by item keys.
1473 * @return array Keys: identifiers, values: HTML contents
1476 public function getIndicators() {
1477 return $this->mIndicators
;
1481 * Adds help link with an icon via page indicators.
1482 * Link target can be overridden by a local message containing a wikilink:
1483 * the message key is: lowercase action or special page name + '-helppage'.
1484 * @param string $to Target MediaWiki.org page title or encoded URL.
1485 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1488 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1489 $this->addModuleStyles( 'mediawiki.helplink' );
1490 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1492 if ( $overrideBaseUrl ) {
1495 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1496 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1499 $link = Html
::rawElement(
1503 'target' => '_blank',
1504 'class' => 'mw-helplink',
1509 $this->setIndicators( [ 'mw-helplink' => $link ] );
1513 * Do not allow scripts which can be modified by wiki users to load on this page;
1514 * only allow scripts bundled with, or generated by, the software.
1515 * Site-wide styles are controlled by a config setting, since they can be
1516 * used to create a custom skin/theme, but not user-specific ones.
1518 * @todo this should be given a more accurate name
1520 public function disallowUserJs() {
1521 $this->reduceAllowedModules(
1522 ResourceLoaderModule
::TYPE_SCRIPTS
,
1523 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1526 // Site-wide styles are controlled by a config setting, see T73621
1527 // for background on why. User styles are never allowed.
1528 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1529 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1531 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1533 $this->reduceAllowedModules(
1534 ResourceLoaderModule
::TYPE_STYLES
,
1540 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1541 * @see ResourceLoaderModule::$origin
1542 * @param string $type ResourceLoaderModule TYPE_ constant
1543 * @return int ResourceLoaderModule ORIGIN_ class constant
1545 public function getAllowedModules( $type ) {
1546 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1547 return min( array_values( $this->mAllowedModules
) );
1549 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1554 * Limit the highest level of CSS/JS untrustworthiness allowed.
1556 * If passed the same or a higher level than the current level of untrustworthiness set, the
1557 * level will remain unchanged.
1559 * @param string $type
1560 * @param int $level ResourceLoaderModule class constant
1562 public function reduceAllowedModules( $type, $level ) {
1563 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1567 * Prepend $text to the body HTML
1569 * @param string $text HTML
1571 public function prependHTML( $text ) {
1572 $this->mBodytext
= $text . $this->mBodytext
;
1576 * Append $text to the body HTML
1578 * @param string $text HTML
1580 public function addHTML( $text ) {
1581 $this->mBodytext
.= $text;
1585 * Shortcut for adding an Html::element via addHTML.
1589 * @param string $element
1590 * @param array $attribs
1591 * @param string $contents
1593 public function addElement( $element, array $attribs = [], $contents = '' ) {
1594 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1598 * Clear the body HTML
1600 public function clearHTML() {
1601 $this->mBodytext
= '';
1607 * @return string HTML
1609 public function getHTML() {
1610 return $this->mBodytext
;
1614 * Get/set the ParserOptions object to use for wikitext parsing
1616 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1617 * current ParserOption object. This parameter is deprecated since 1.31.
1618 * @return ParserOptions
1620 public function parserOptions( $options = null ) {
1621 if ( $options !== null ) {
1622 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1625 if ( $options !== null && !empty( $options->isBogus
) ) {
1626 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1627 // been changed somehow, and keep it if so.
1628 $anonPO = ParserOptions
::newFromAnon();
1629 $anonPO->setAllowUnsafeRawHtml( false );
1630 if ( !$options->matches( $anonPO ) ) {
1631 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1632 $options->isBogus
= false;
1636 if ( !$this->mParserOptions
) {
1637 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1638 // $wgUser isn't unstubbable yet, so don't try to get a
1639 // ParserOptions for it. And don't cache this ParserOptions
1641 $po = ParserOptions
::newFromAnon();
1642 $po->setAllowUnsafeRawHtml( false );
1643 $po->isBogus
= true;
1644 if ( $options !== null ) {
1645 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1650 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1651 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1654 if ( $options !== null && !empty( $options->isBogus
) ) {
1655 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1657 return wfSetVar( $this->mParserOptions
, null, true );
1659 return wfSetVar( $this->mParserOptions
, $options );
1664 * Set the revision ID which will be seen by the wiki text parser
1665 * for things such as embedded {{REVISIONID}} variable use.
1667 * @param int|null $revid A positive integer, or null
1668 * @return mixed Previous value
1670 public function setRevisionId( $revid ) {
1671 $val = is_null( $revid ) ?
null : intval( $revid );
1672 return wfSetVar( $this->mRevisionId
, $val, true );
1676 * Get the displayed revision ID
1680 public function getRevisionId() {
1681 return $this->mRevisionId
;
1685 * Set the timestamp of the revision which will be displayed. This is used
1686 * to avoid a extra DB call in Skin::lastModified().
1688 * @param string|null $timestamp
1689 * @return mixed Previous value
1691 public function setRevisionTimestamp( $timestamp ) {
1692 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1696 * Get the timestamp of displayed revision.
1697 * This will be null if not filled by setRevisionTimestamp().
1699 * @return string|null
1701 public function getRevisionTimestamp() {
1702 return $this->mRevisionTimestamp
;
1706 * Set the displayed file version
1708 * @param File|null $file
1709 * @return mixed Previous value
1711 public function setFileVersion( $file ) {
1713 if ( $file instanceof File
&& $file->exists() ) {
1714 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1716 return wfSetVar( $this->mFileVersion
, $val, true );
1720 * Get the displayed file version
1722 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1724 public function getFileVersion() {
1725 return $this->mFileVersion
;
1729 * Get the templates used on this page
1731 * @return array (namespace => dbKey => revId)
1734 public function getTemplateIds() {
1735 return $this->mTemplateIds
;
1739 * Get the files used on this page
1741 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1744 public function getFileSearchOptions() {
1745 return $this->mImageTimeKeys
;
1749 * Convert wikitext to HTML and add it to the buffer
1750 * Default assumes that the current page title will be used.
1752 * @param string $text
1753 * @param bool $linestart Is this the start of a line?
1754 * @param bool $interface Is this text in the user interface language?
1755 * @throws MWException
1756 * @deprecated since 1.32 due to untidy output; use
1757 * addWikiTextAsInterface() if $interface is default value or true,
1758 * or else addWikiTextAsContent() if $interface is false.
1760 public function addWikiText( $text, $linestart = true, $interface = true ) {
1761 wfDeprecated( __METHOD__
, '1.32' );
1762 $title = $this->getTitle();
1764 throw new MWException( 'Title is null' );
1766 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, $interface );
1770 * Convert wikitext *in the user interface language* to HTML and
1771 * add it to the buffer. The result will not be
1772 * language-converted, as user interface messages are already
1773 * localized into a specific variant. Assumes that the current
1774 * page title will be used if optional $title is not
1775 * provided. Output will be tidy.
1777 * @param string $text Wikitext in the user interface language
1778 * @param bool $linestart Is this the start of a line? (Defaults to true)
1779 * @param Title|null $title Optional title to use; default of `null`
1780 * means use current page title.
1781 * @throws MWException if $title is not provided and OutputPage::getTitle()
1785 public function addWikiTextAsInterface(
1786 $text, $linestart = true, Title
$title = null
1788 if ( $title === null ) {
1789 $title = $this->getTitle();
1792 throw new MWException( 'Title is null' );
1794 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/true );
1798 * Convert wikitext *in the user interface language* to HTML and
1799 * add it to the buffer with a `<div class="$wrapperClass">`
1800 * wrapper. The result will not be language-converted, as user
1801 * interface messages as already localized into a specific
1802 * variant. The $text will be parsed in start-of-line context.
1803 * Output will be tidy.
1805 * @param string $wrapperClass The class attribute value for the <div>
1806 * wrapper in the output HTML
1807 * @param string $text Wikitext in the user interface language
1810 public function wrapWikiTextAsInterface(
1811 $wrapperClass, $text
1813 $this->addWikiTextTitleInternal(
1814 $text, $this->getTitle(),
1815 /*linestart*/true, /*tidy*/true, /*interface*/true,
1821 * Convert wikitext *in the page content language* to HTML and add
1822 * it to the buffer. The result with be language-converted to the
1823 * user's preferred variant. Assumes that the current page title
1824 * will be used if optional $title is not provided. Output will be
1827 * @param string $text Wikitext in the page content language
1828 * @param bool $linestart Is this the start of a line? (Defaults to true)
1829 * @param Title|null $title Optional title to use; default of `null`
1830 * means use current page title.
1831 * @throws MWException if $title is not provided and OutputPage::getTitle()
1835 public function addWikiTextAsContent(
1836 $text, $linestart = true, Title
$title = null
1838 if ( $title === null ) {
1839 $title = $this->getTitle();
1842 throw new MWException( 'Title is null' );
1844 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1848 * Add wikitext with a custom Title object
1850 * @param string $text Wikitext
1851 * @param Title $title
1852 * @param bool $linestart Is this the start of a line?
1853 * @deprecated since 1.32 due to untidy output; use
1854 * addWikiTextAsInterface()
1856 public function addWikiTextWithTitle( $text, Title
$title, $linestart = true ) {
1857 wfDeprecated( __METHOD__
, '1.32' );
1858 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/false, /*interface*/false );
1862 * Add wikitext *in content language* with a custom Title object.
1863 * Output will be tidy.
1865 * @param string $text Wikitext in content language
1866 * @param Title $title
1867 * @param bool $linestart Is this the start of a line?
1868 * @deprecated since 1.32 to rename methods consistently; use
1869 * addWikiTextAsContent()
1871 function addWikiTextTitleTidy( $text, Title
$title, $linestart = true ) {
1872 wfDeprecated( __METHOD__
, '1.32' );
1873 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1877 * Add wikitext *in content language*. Output will be tidy.
1879 * @param string $text Wikitext in content language
1880 * @param bool $linestart Is this the start of a line?
1881 * @deprecated since 1.32 to rename methods consistently; use
1882 * addWikiTextAsContent()
1884 public function addWikiTextTidy( $text, $linestart = true ) {
1885 wfDeprecated( __METHOD__
, '1.32' );
1886 $title = $this->getTitle();
1888 throw new MWException( 'Title is null' );
1890 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*tidy*/true, /*interface*/false );
1894 * Add wikitext with a custom Title object.
1895 * Output is unwrapped.
1897 * @param string $text Wikitext
1898 * @param Title $title
1899 * @param bool $linestart Is this the start of a line?
1900 * @param bool $tidy Whether to use tidy.
1901 * Setting this to false (or omitting it) is deprecated
1902 * since 1.32; all wikitext should be tidied.
1903 * For backwards-compatibility with prior MW releases,
1904 * you may wish to invoke this method but set $tidy=true;
1905 * this will result in equivalent output to the non-deprecated
1906 * addWikiTextAsContent()/addWikiTextAsInterface() methods.
1907 * @param bool $interface Whether it is an interface message
1908 * (for example disables conversion)
1909 * @deprecated since 1.32, use addWikiTextAsContent() or
1910 * addWikiTextAsInterface() (depending on $interface)
1912 public function addWikiTextTitle( $text, Title
$title, $linestart,
1913 $tidy = false, $interface = false
1915 wfDeprecated( __METHOD__
, '1.32' );
1916 return $this->addWikiTextTitleInternal( $text, $title, $linestart, $tidy, $interface );
1920 * Add wikitext with a custom Title object.
1921 * Output is unwrapped.
1923 * @param string $text Wikitext
1924 * @param Title $title
1925 * @param bool $linestart Is this the start of a line?
1926 * @param bool $tidy Whether to use tidy.
1927 * Setting this to false (or omitting it) is deprecated
1928 * since 1.32; all wikitext should be tidied.
1929 * @param bool $interface Whether it is an interface message
1930 * (for example disables conversion)
1931 * @param string $wrapperClass if not empty, wraps the output in
1932 * a `<div class="$wrapperClass">`
1935 private function addWikiTextTitleInternal(
1936 $text, Title
$title, $linestart, $tidy, $interface, $wrapperClass = null
1939 wfDeprecated( 'disabling tidy', '1.32' );
1942 $parserOutput = $this->parseInternal(
1943 $text, $title, $linestart, $tidy, $interface, /*language*/null
1946 $this->addParserOutput( $parserOutput, [
1947 'enableSectionEditLinks' => false,
1948 'wrapperDivClass' => $wrapperClass ??
'',
1953 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1954 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1958 * @param ParserOutput $parserOutput
1960 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1961 $this->mLanguageLinks
=
1962 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1963 $this->addCategoryLinks( $parserOutput->getCategories() );
1964 $this->setIndicators( $parserOutput->getIndicators() );
1965 $this->mNewSectionLink
= $parserOutput->getNewSection();
1966 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1968 if ( !$parserOutput->isCacheable() ) {
1969 $this->enableClientCache( false );
1971 $this->mNoGallery
= $parserOutput->getNoGallery();
1972 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1973 $this->addModules( $parserOutput->getModules() );
1974 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1975 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1976 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1977 $this->mPreventClickjacking
= $this->mPreventClickjacking
1978 ||
$parserOutput->preventClickjacking();
1980 // Template versioning...
1981 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1982 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1983 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1985 $this->mTemplateIds
[$ns] = $dbks;
1988 // File versioning...
1989 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1990 $this->mImageTimeKeys
[$dbk] = $data;
1993 // Hooks registered in the object
1994 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1995 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1996 list( $hookName, $data ) = $hookInfo;
1997 if ( isset( $parserOutputHooks[$hookName] ) ) {
1998 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
2002 // Enable OOUI if requested via ParserOutput
2003 if ( $parserOutput->getEnableOOUI() ) {
2004 $this->enableOOUI();
2007 // Include parser limit report
2008 if ( !$this->limitReportJSData
) {
2009 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
2012 // Link flags are ignored for now, but may in the future be
2013 // used to mark individual language links.
2015 // Avoid PHP 7.1 warning of passing $this by reference
2016 $outputPage = $this;
2017 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
2018 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
2020 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2021 // so that extensions may modify ParserOutput to toggle TOC.
2022 // This cannot be moved to addParserOutputText because that is not
2023 // called by EditPage for Preview.
2024 if ( $parserOutput->getTOCHTML() ) {
2025 $this->mEnableTOC
= true;
2030 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2031 * ParserOutput object, without any other metadata.
2034 * @param ParserOutput $parserOutput
2035 * @param array $poOptions Options to ParserOutput::getText()
2037 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
2038 $this->addParserOutputText( $parserOutput, $poOptions );
2040 $this->addModules( $parserOutput->getModules() );
2041 $this->addModuleScripts( $parserOutput->getModuleScripts() );
2042 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2044 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2048 * Add the HTML associated with a ParserOutput object, without any metadata.
2051 * @param ParserOutput $parserOutput
2052 * @param array $poOptions Options to ParserOutput::getText()
2054 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
2055 $text = $parserOutput->getText( $poOptions );
2056 // Avoid PHP 7.1 warning of passing $this by reference
2057 $outputPage = $this;
2058 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
2059 $this->addHTML( $text );
2063 * Add everything from a ParserOutput object.
2065 * @param ParserOutput $parserOutput
2066 * @param array $poOptions Options to ParserOutput::getText()
2068 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
2069 $this->addParserOutputMetadata( $parserOutput );
2070 $this->addParserOutputText( $parserOutput, $poOptions );
2074 * Add the output of a QuickTemplate to the output buffer
2076 * @param QuickTemplate &$template
2078 public function addTemplate( &$template ) {
2079 $this->addHTML( $template->getHTML() );
2083 * Parse wikitext and return the HTML.
2085 * @todo The output is wrapped in a <div> iff $interface is false; it's
2086 * probably best to always strip the wrapper.
2088 * @param string $text
2089 * @param bool $linestart Is this the start of a line?
2090 * @param bool $interface Use interface language (instead of content language) while parsing
2091 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2092 * LanguageConverter.
2093 * @param Language|null $language Target language object, will override $interface
2094 * @throws MWException
2095 * @return string HTML
2096 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
2097 * use parseAsContent() if $interface is default value or false, or else
2098 * parseAsInterface() if $interface is true.
2100 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
2101 wfDeprecated( __METHOD__
, '1.33' );
2102 return $this->parseInternal(
2103 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
2105 'enableSectionEditLinks' => false,
2110 * Parse wikitext *in the page content language* and return the HTML.
2111 * The result will be language-converted to the user's preferred variant.
2112 * Output will be tidy.
2114 * @param string $text Wikitext in the page content language
2115 * @param bool $linestart Is this the start of a line? (Defaults to true)
2116 * @throws MWException
2117 * @return string HTML
2120 public function parseAsContent( $text, $linestart = true ) {
2121 return $this->parseInternal(
2122 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2124 'enableSectionEditLinks' => false,
2125 'wrapperDivClass' => ''
2130 * Parse wikitext *in the user interface language* and return the HTML.
2131 * The result will not be language-converted, as user interface messages
2132 * are already localized into a specific variant.
2133 * Output will be tidy.
2135 * @param string $text Wikitext in the user interface language
2136 * @param bool $linestart Is this the start of a line? (Defaults to true)
2137 * @throws MWException
2138 * @return string HTML
2141 public function parseAsInterface( $text, $linestart = true ) {
2142 return $this->parseInternal(
2143 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2145 'enableSectionEditLinks' => false,
2146 'wrapperDivClass' => ''
2151 * Parse wikitext *in the user interface language*, strip
2152 * paragraph wrapper, and return the HTML.
2153 * The result will not be language-converted, as user interface messages
2154 * are already localized into a specific variant.
2155 * Output will be tidy. Outer paragraph wrapper will only be stripped
2156 * if the result is a single paragraph.
2158 * @param string $text Wikitext in the user interface language
2159 * @param bool $linestart Is this the start of a line? (Defaults to true)
2160 * @throws MWException
2161 * @return string HTML
2164 public function parseInlineAsInterface( $text, $linestart = true ) {
2165 return Parser
::stripOuterParagraph(
2166 $this->parseAsInterface( $text, $linestart )
2171 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2173 * @param string $text
2174 * @param bool $linestart Is this the start of a line?
2175 * @param bool $interface Use interface language (instead of content language) while parsing
2176 * language sensitive magic words like GRAMMAR and PLURAL
2177 * @return string HTML
2178 * @deprecated since 1.32, due to untidy output and confusing default
2179 * for $interface. Use parseInlineAsInterface() if $interface is
2180 * the default value or false, or else use
2181 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2183 public function parseInline( $text, $linestart = true, $interface = false ) {
2184 wfDeprecated( __METHOD__
, '1.33' );
2185 $parsed = $this->parseInternal(
2186 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2188 'enableSectionEditLinks' => false,
2189 'wrapperDivClass' => '', /* no wrapper div */
2191 return Parser
::stripOuterParagraph( $parsed );
2195 * Parse wikitext and return the HTML (internal implementation helper)
2197 * @param string $text
2198 * @param Title The title to use
2199 * @param bool $linestart Is this the start of a line?
2200 * @param bool $tidy Whether the output should be tidied
2201 * @param bool $interface Use interface language (instead of content language) while parsing
2202 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2203 * LanguageConverter.
2204 * @param Language|null $language Target language object, will override $interface
2205 * @throws MWException
2206 * @return ParserOutput
2208 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2211 if ( is_null( $title ) ) {
2212 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
2215 $popts = $this->parserOptions();
2216 $oldTidy = $popts->setTidy( $tidy );
2217 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2219 if ( $language !== null ) {
2220 $oldLang = $popts->setTargetLanguage( $language );
2223 $parserOutput = $wgParser->getFreshParser()->parse(
2224 $text, $title, $popts,
2225 $linestart, true, $this->mRevisionId
2228 $popts->setTidy( $oldTidy );
2229 $popts->setInterfaceMessage( $oldInterface );
2231 if ( $language !== null ) {
2232 $popts->setTargetLanguage( $oldLang );
2235 return $parserOutput;
2239 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2241 * @param int $maxage Maximum cache time on the CDN, in seconds.
2243 public function setCdnMaxage( $maxage ) {
2244 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
2248 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2249 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2250 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2253 * @param int $maxage Maximum cache time on the CDN, in seconds
2256 public function lowerCdnMaxage( $maxage ) {
2257 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2258 $this->setCdnMaxage( $this->mCdnMaxage
);
2262 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2264 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2265 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2266 * TTL is 90% of the age of the object, subject to the min and max.
2268 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2269 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2270 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2273 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2274 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2275 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2277 if ( $mtime === null ||
$mtime === false ) {
2278 return $minTTL; // entity does not exist
2281 $age = MWTimestamp
::time() - wfTimestamp( TS_UNIX
, $mtime );
2282 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2283 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2285 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2289 * Use enableClientCache(false) to force it to send nocache headers
2291 * @param bool|null $state New value, or null to not set the value
2293 * @return bool Old value
2295 public function enableClientCache( $state ) {
2296 return wfSetVar( $this->mEnableClientCache
, $state );
2300 * Get the list of cookie names that will influence the cache
2304 function getCacheVaryCookies() {
2305 if ( self
::$cacheVaryCookies === null ) {
2306 $config = $this->getConfig();
2307 self
::$cacheVaryCookies = array_values( array_unique( array_merge(
2308 SessionManager
::singleton()->getVaryCookies(),
2312 $config->get( 'CacheVaryCookies' )
2314 Hooks
::run( 'GetCacheVaryCookies', [ $this, &self
::$cacheVaryCookies ] );
2316 return self
::$cacheVaryCookies;
2320 * Check if the request has a cache-varying cookie header
2321 * If it does, it's very important that we don't allow public caching
2325 function haveCacheVaryCookies() {
2326 $request = $this->getRequest();
2327 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2328 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2329 wfDebug( __METHOD__
. ": found $cookieName\n" );
2333 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2338 * Add an HTTP header that will influence on the cache
2340 * @param string $header Header name
2341 * @param string[]|null $option Options for the Key header. See
2342 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2343 * for the list of valid options.
2345 public function addVaryHeader( $header, array $option = null ) {
2346 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2347 $this->mVaryHeader
[$header] = [];
2349 if ( !is_array( $option ) ) {
2352 $this->mVaryHeader
[$header] =
2353 array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2357 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2358 * such as Accept-Encoding or Cookie
2362 public function getVaryHeader() {
2363 // If we vary on cookies, let's make sure it's always included here too.
2364 if ( $this->getCacheVaryCookies() ) {
2365 $this->addVaryHeader( 'Cookie' );
2368 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2369 $this->addVaryHeader( $header, $options );
2371 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2375 * Add an HTTP Link: header
2377 * @param string $header Header value
2379 public function addLinkHeader( $header ) {
2380 $this->mLinkHeader
[] = $header;
2384 * Return a Link: header. Based on the values of $mLinkHeader.
2388 public function getLinkHeader() {
2389 if ( !$this->mLinkHeader
) {
2393 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2397 * Get a complete Key header
2400 * @deprecated in 1.32; the IETF spec for this header expired w/o becoming
2403 public function getKeyHeader() {
2404 wfDeprecated( '$wgUseKeyHeader', '1.32' );
2406 $cvCookies = $this->getCacheVaryCookies();
2408 $cookiesOption = [];
2409 foreach ( $cvCookies as $cookieName ) {
2410 $cookiesOption[] = 'param=' . $cookieName;
2412 $this->addVaryHeader( 'Cookie', $cookiesOption );
2414 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2415 $this->addVaryHeader( $header, $options );
2419 foreach ( $this->mVaryHeader
as $header => $option ) {
2420 $newheader = $header;
2421 if ( is_array( $option ) && count( $option ) > 0 ) {
2422 $newheader .= ';' . implode( ';', $option );
2424 $headers[] = $newheader;
2426 $key = 'Key: ' . implode( ',', $headers );
2432 * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
2435 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2436 * /w/index.php?title=Main_page&variant=zh-cn will not.
2438 private function addAcceptLanguage() {
2439 $title = $this->getTitle();
2440 if ( !$title instanceof Title
) {
2444 $lang = $title->getPageLanguage();
2445 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2446 $variants = $lang->getVariants();
2448 foreach ( $variants as $variant ) {
2449 if ( $variant === $lang->getCode() ) {
2453 // XXX Note that this code is not strictly correct: we
2454 // do a case-insensitive match in
2455 // LanguageConverter::getHeaderVariant() while the
2456 // (abandoned, draft) spec for the `Key` header only
2457 // allows case-sensitive matches. To match the logic
2458 // in LanguageConverter::getHeaderVariant() we should
2459 // also be looking at fallback variants and deprecated
2460 // mediawiki-internal codes, as well as BCP 47
2461 // normalized forms.
2463 $aloption[] = "substr=$variant";
2465 // IE and some other browsers use BCP 47 standards in their Accept-Language header,
2466 // like "zh-CN" or "zh-Hant". We should handle these too.
2467 $variantBCP47 = LanguageCode
::bcp47( $variant );
2468 if ( $variantBCP47 !== $variant ) {
2469 $aloption[] = "substr=$variantBCP47";
2472 $this->addVaryHeader( 'Accept-Language', $aloption );
2477 * Set a flag which will cause an X-Frame-Options header appropriate for
2478 * edit pages to be sent. The header value is controlled by
2479 * $wgEditPageFrameOptions.
2481 * This is the default for special pages. If you display a CSRF-protected
2482 * form on an ordinary view page, then you need to call this function.
2484 * @param bool $enable
2486 public function preventClickjacking( $enable = true ) {
2487 $this->mPreventClickjacking
= $enable;
2491 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2492 * This can be called from pages which do not contain any CSRF-protected
2495 public function allowClickjacking() {
2496 $this->mPreventClickjacking
= false;
2500 * Get the prevent-clickjacking flag
2505 public function getPreventClickjacking() {
2506 return $this->mPreventClickjacking
;
2510 * Get the X-Frame-Options header value (without the name part), or false
2511 * if there isn't one. This is used by Skin to determine whether to enable
2512 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2514 * @return string|false
2516 public function getFrameOptions() {
2517 $config = $this->getConfig();
2518 if ( $config->get( 'BreakFrames' ) ) {
2520 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2521 return $config->get( 'EditPageFrameOptions' );
2527 * Send cache control HTTP headers
2529 public function sendCacheControl() {
2530 $response = $this->getRequest()->response();
2531 $config = $this->getConfig();
2533 $this->addVaryHeader( 'Cookie' );
2534 $this->addAcceptLanguage();
2536 # don't serve compressed data to clients who can't handle it
2537 # maintain different caches for logged-in users and non-logged in ones
2538 $response->header( $this->getVaryHeader() );
2540 if ( $config->get( 'UseKeyHeader' ) ) {
2541 $response->header( $this->getKeyHeader() );
2544 if ( $this->mEnableClientCache
) {
2546 $config->get( 'UseSquid' ) &&
2547 !$response->hasCookies() &&
2548 !SessionManager
::getGlobalSession()->isPersistent() &&
2549 !$this->isPrintable() &&
2550 $this->mCdnMaxage
!= 0 &&
2551 !$this->haveCacheVaryCookies()
2553 if ( $config->get( 'UseESI' ) ) {
2554 wfDeprecated( '$wgUseESI = true', '1.33' );
2555 # We'll purge the proxy cache explicitly, but require end user agents
2556 # to revalidate against the proxy on each visit.
2557 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2558 wfDebug( __METHOD__
.
2559 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2560 # start with a shorter timeout for initial testing
2561 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2563 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2564 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2566 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2568 # We'll purge the proxy cache for anons explicitly, but require end user agents
2569 # to revalidate against the proxy on each visit.
2570 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2571 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2572 wfDebug( __METHOD__
.
2573 ": local proxy caching; {$this->mLastModified} **", 'private' );
2574 # start with a shorter timeout for initial testing
2575 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2576 $response->header( "Cache-Control: " .
2577 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2580 # We do want clients to cache if they can, but they *must* check for updates
2581 # on revisiting the page.
2582 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2583 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2584 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2586 if ( $this->mLastModified
) {
2587 $response->header( "Last-Modified: {$this->mLastModified}" );
2590 wfDebug( __METHOD__
. ": no caching **", 'private' );
2592 # In general, the absence of a last modified header should be enough to prevent
2593 # the client from using its cache. We send a few other things just to make sure.
2594 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2595 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2596 $response->header( 'Pragma: no-cache' );
2601 * Transfer styles and JavaScript modules from skin.
2603 * @param Skin $sk to load modules for
2605 public function loadSkinModules( $sk ) {
2606 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2607 if ( $group === 'styles' ) {
2608 foreach ( $modules as $key => $moduleMembers ) {
2609 $this->addModuleStyles( $moduleMembers );
2612 $this->addModules( $modules );
2618 * Finally, all the text has been munged and accumulated into
2619 * the object, let's actually output it:
2621 * @param bool $return Set to true to get the result as a string rather than sending it
2622 * @return string|null
2624 * @throws FatalError
2625 * @throws MWException
2627 public function output( $return = false ) {
2628 if ( $this->mDoNothing
) {
2629 return $return ?
'' : null;
2632 $response = $this->getRequest()->response();
2633 $config = $this->getConfig();
2635 if ( $this->mRedirect
!= '' ) {
2636 # Standards require redirect URLs to be absolute
2637 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2639 $redirect = $this->mRedirect
;
2640 $code = $this->mRedirectCode
;
2642 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2643 if ( $code == '301' ||
$code == '303' ) {
2644 if ( !$config->get( 'DebugRedirects' ) ) {
2645 $response->statusHeader( $code );
2647 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2649 if ( $config->get( 'VaryOnXFP' ) ) {
2650 $this->addVaryHeader( 'X-Forwarded-Proto' );
2652 $this->sendCacheControl();
2654 $response->header( "Content-Type: text/html; charset=utf-8" );
2655 if ( $config->get( 'DebugRedirects' ) ) {
2656 $url = htmlspecialchars( $redirect );
2657 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2658 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2659 print "</body>\n</html>\n";
2661 $response->header( 'Location: ' . $redirect );
2665 return $return ?
'' : null;
2666 } elseif ( $this->mStatusCode
) {
2667 $response->statusHeader( $this->mStatusCode
);
2670 # Buffer output; final headers may depend on later processing
2673 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2674 $response->header( 'Content-language: ' .
2675 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2677 if ( !$this->mArticleBodyOnly
) {
2678 $sk = $this->getSkin();
2681 $linkHeader = $this->getLinkHeader();
2682 if ( $linkHeader ) {
2683 $response->header( $linkHeader );
2686 // Prevent framing, if requested
2687 $frameOptions = $this->getFrameOptions();
2688 if ( $frameOptions ) {
2689 $response->header( "X-Frame-Options: $frameOptions" );
2692 ContentSecurityPolicy
::sendHeaders( $this );
2694 if ( $this->mArticleBodyOnly
) {
2695 echo $this->mBodytext
;
2697 // Enable safe mode if requested (T152169)
2698 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2699 $this->disallowUserJs();
2702 $sk = $this->getSkin();
2703 $this->loadSkinModules( $sk );
2705 MWDebug
::addModules( $this );
2707 // Avoid PHP 7.1 warning of passing $this by reference
2708 $outputPage = $this;
2709 // Hook that allows last minute changes to the output page, e.g.
2710 // adding of CSS or Javascript by extensions.
2711 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2715 } catch ( Exception
$e ) {
2716 ob_end_clean(); // bug T129657
2722 // This hook allows last minute changes to final overall output by modifying output buffer
2723 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2724 } catch ( Exception
$e ) {
2725 ob_end_clean(); // bug T129657
2729 $this->sendCacheControl();
2732 return ob_get_clean();
2740 * Prepare this object to display an error page; disable caching and
2741 * indexing, clear the current text and redirect, set the page's title
2742 * and optionally an custom HTML title (content of the "<title>" tag).
2744 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2745 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2746 * optional, if not passed the "<title>" attribute will be
2747 * based on $pageTitle
2749 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2750 $this->setPageTitle( $pageTitle );
2751 if ( $htmlTitle !== false ) {
2752 $this->setHTMLTitle( $htmlTitle );
2754 $this->setRobotPolicy( 'noindex,nofollow' );
2755 $this->setArticleRelated( false );
2756 $this->enableClientCache( false );
2757 $this->mRedirect
= '';
2758 $this->clearSubtitle();
2763 * Output a standard error page
2765 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2766 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2767 * showErrorPage( 'titlemsg', $messageObject );
2768 * showErrorPage( $titleMessageObject, $messageObject );
2770 * @param string|Message $title Message key (string) for page title, or a Message object
2771 * @param string|Message $msg Message key (string) for page text, or a Message object
2772 * @param array $params Message parameters; ignored if $msg is a Message object
2774 public function showErrorPage( $title, $msg, $params = [] ) {
2775 if ( !$title instanceof Message
) {
2776 $title = $this->msg( $title );
2779 $this->prepareErrorPage( $title );
2781 if ( $msg instanceof Message
) {
2782 if ( $params !== [] ) {
2783 trigger_error( 'Argument ignored: $params. The message parameters argument '
2784 . 'is discarded when the $msg argument is a Message object instead of '
2785 . 'a string.', E_USER_NOTICE
);
2787 $this->addHTML( $msg->parseAsBlock() );
2789 $this->addWikiMsgArray( $msg, $params );
2792 $this->returnToMain();
2796 * Output a standard permission error page
2798 * @param array $errors Error message keys or [key, param...] arrays
2799 * @param string|null $action Action that was denied or null if unknown
2801 public function showPermissionsErrorPage( array $errors, $action = null ) {
2802 foreach ( $errors as $key => $error ) {
2803 $errors[$key] = (array)$error;
2806 // For some action (read, edit, create and upload), display a "login to do this action"
2807 // error if all of the following conditions are met:
2808 // 1. the user is not logged in
2809 // 2. the only error is insufficient permissions (i.e. no block or something else)
2810 // 3. the error can be avoided simply by logging in
2811 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2812 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2813 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2814 && ( User
::groupHasPermission( 'user', $action )
2815 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2817 $displayReturnto = null;
2819 # Due to T34276, if a user does not have read permissions,
2820 # $this->getTitle() will just give Special:Badtitle, which is
2821 # not especially useful as a returnto parameter. Use the title
2822 # from the request instead, if there was one.
2823 $request = $this->getRequest();
2824 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2825 if ( $action == 'edit' ) {
2826 $msg = 'whitelistedittext';
2827 $displayReturnto = $returnto;
2828 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2829 $msg = 'nocreatetext';
2830 } elseif ( $action == 'upload' ) {
2831 $msg = 'uploadnologintext';
2833 $msg = 'loginreqpagetext';
2834 $displayReturnto = Title
::newMainPage();
2840 $query['returnto'] = $returnto->getPrefixedText();
2842 if ( !$request->wasPosted() ) {
2843 $returntoquery = $request->getValues();
2844 unset( $returntoquery['title'] );
2845 unset( $returntoquery['returnto'] );
2846 unset( $returntoquery['returntoquery'] );
2847 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2850 $title = SpecialPage
::getTitleFor( 'Userlogin' );
2851 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2852 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE
);
2853 $loginLink = $linkRenderer->makeKnownLink(
2855 $this->msg( 'loginreqlink' )->text(),
2860 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2861 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2863 # Don't return to a page the user can't read otherwise
2864 # we'll end up in a pointless loop
2865 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2866 $this->returnToMain( null, $displayReturnto );
2869 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2870 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2875 * Display an error page indicating that a given version of MediaWiki is
2876 * required to use it
2878 * @param mixed $version The version of MediaWiki needed to use the page
2880 public function versionRequired( $version ) {
2881 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2883 $this->addWikiMsg( 'versionrequiredtext', $version );
2884 $this->returnToMain();
2888 * Format a list of error messages
2890 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2891 * @param string|null $action Action that was denied or null if unknown
2892 * @return string The wikitext error-messages, formatted into a list.
2894 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2895 if ( $action == null ) {
2896 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2898 $action_desc = $this->msg( "action-$action" )->plain();
2900 'permissionserrorstext-withaction',
2903 )->plain() . "\n\n";
2906 if ( count( $errors ) > 1 ) {
2907 $text .= '<ul class="permissions-errors">' . "\n";
2909 foreach ( $errors as $error ) {
2911 $text .= $this->msg( ...$error )->plain();
2916 $text .= "<div class=\"permissions-errors\">\n" .
2917 $this->msg( ...reset( $errors ) )->plain() .
2925 * Show a warning about replica DB lag
2927 * If the lag is higher than $wgSlaveLagCritical seconds,
2928 * then the warning is a bit more obvious. If the lag is
2929 * lower than $wgSlaveLagWarning, then no warning is shown.
2931 * @param int $lag Replica lag
2933 public function showLagWarning( $lag ) {
2934 $config = $this->getConfig();
2935 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2936 $lag = floor( $lag ); // floor to avoid nano seconds to display
2937 $message = $lag < $config->get( 'SlaveLagCritical' )
2940 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2941 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2946 * Output an error page
2948 * @note FatalError exception class provides an alternative.
2949 * @param string $message Error to output. Must be escaped for HTML.
2951 public function showFatalError( $message ) {
2952 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2954 $this->addHTML( $message );
2958 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2960 public function showUnexpectedValueError( $name, $val ) {
2961 wfDeprecated( __METHOD__
, '1.32' );
2962 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2966 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2968 public function showFileCopyError( $old, $new ) {
2969 wfDeprecated( __METHOD__
, '1.32' );
2970 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2974 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2976 public function showFileRenameError( $old, $new ) {
2977 wfDeprecated( __METHOD__
, '1.32' );
2978 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
2982 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2984 public function showFileDeleteError( $name ) {
2985 wfDeprecated( __METHOD__
, '1.32' );
2986 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
2990 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2992 public function showFileNotFoundError( $name ) {
2993 wfDeprecated( __METHOD__
, '1.32' );
2994 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
2998 * Add a "return to" link pointing to a specified title
3000 * @param Title $title Title to link
3001 * @param array $query Query string parameters
3002 * @param string|null $text Text of the link (input is not escaped)
3003 * @param array $options Options array to pass to Linker
3005 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3006 $linkRenderer = MediaWikiServices
::getInstance()
3007 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3008 $link = $this->msg( 'returnto' )->rawParams(
3009 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3010 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3014 * Add a "return to" link pointing to a specified title,
3015 * or the title indicated in the request, or else the main page
3017 * @param mixed|null $unused
3018 * @param Title|string|null $returnto Title or String to return to
3019 * @param string|null $returntoquery Query string for the return to link
3021 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3022 if ( $returnto == null ) {
3023 $returnto = $this->getRequest()->getText( 'returnto' );
3026 if ( $returntoquery == null ) {
3027 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
3030 if ( $returnto === '' ) {
3031 $returnto = Title
::newMainPage();
3034 if ( is_object( $returnto ) ) {
3035 $titleObj = $returnto;
3037 $titleObj = Title
::newFromText( $returnto );
3039 // We don't want people to return to external interwiki. That
3040 // might potentially be used as part of a phishing scheme
3041 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
3042 $titleObj = Title
::newMainPage();
3045 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
3048 private function getRlClientContext() {
3049 if ( !$this->rlClientContext
) {
3050 $query = ResourceLoader
::makeLoaderQuery(
3051 [], // modules; not relevant
3052 $this->getLanguage()->getCode(),
3053 $this->getSkin()->getSkinName(),
3054 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
3055 null, // version; not relevant
3056 ResourceLoader
::inDebugMode(),
3057 null, // only; not relevant
3058 $this->isPrintable(),
3059 $this->getRequest()->getBool( 'handheld' )
3061 $this->rlClientContext
= new ResourceLoaderContext(
3062 $this->getResourceLoader(),
3063 new FauxRequest( $query )
3065 if ( $this->contentOverrideCallbacks
) {
3066 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
3067 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
3068 foreach ( $this->contentOverrideCallbacks
as $callback ) {
3069 $content = $callback( $title );
3070 if ( $content !== null ) {
3071 $text = ContentHandler
::getContentText( $content );
3072 if ( strpos( $text, '</script>' ) !== false ) {
3073 // Proactively replace this so that we can display a message
3074 // to the user, instead of letting it go to Html::inlineScript(),
3075 // where it would be considered a server-side issue.
3076 $titleFormatted = $title->getPrefixedText();
3077 $content = new JavaScriptContent(
3078 Xml
::encodeJsCall( 'mw.log.error', [
3079 "Cannot preview $titleFormatted due to script-closing tag."
3090 return $this->rlClientContext
;
3094 * Call this to freeze the module queue and JS config and create a formatter.
3096 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3097 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3098 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3099 * the module filters retroactively. Skins and extension hooks may also add modules until very
3100 * late in the request lifecycle.
3102 * @return ResourceLoaderClientHtml
3104 public function getRlClient() {
3105 if ( !$this->rlClient
) {
3106 $context = $this->getRlClientContext();
3107 $rl = $this->getResourceLoader();
3108 $this->addModules( [
3113 $this->addModuleStyles( [
3118 $this->getSkin()->setupSkinUserCss( $this );
3120 // Prepare exempt modules for buildExemptModules()
3121 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
3123 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3125 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
3126 // Separate user-specific batch for improved cache-hit ratio.
3127 $userBatch = [ 'user.styles', 'user' ];
3128 $siteBatch = array_diff( $moduleStyles, $userBatch );
3129 $dbr = wfGetDB( DB_REPLICA
);
3130 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
3131 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
3133 // Filter out modules handled by buildExemptModules()
3134 $moduleStyles = array_filter( $moduleStyles,
3135 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3136 $module = $rl->getModule( $name );
3138 $group = $module->getGroup();
3139 if ( isset( $exemptGroups[$group] ) ) {
3140 $exemptStates[$name] = 'ready';
3141 if ( !$module->isKnownEmpty( $context ) ) {
3142 // E.g. Don't output empty <styles>
3143 $exemptGroups[$group][] = $name;
3151 $this->rlExemptStyleModules
= $exemptGroups;
3153 $rlClient = new ResourceLoaderClientHtml( $context, [
3154 'target' => $this->getTarget(),
3155 'nonce' => $this->getCSPNonce(),
3156 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3157 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3158 // modules enqueud for loading on this page is filtered to just those.
3159 // However, to make sure we also apply the restriction to dynamic dependencies and
3160 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3161 // StartupModule so that the client-side registry will not contain any restricted
3162 // modules either. (T152169, T185303)
3163 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
3164 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
3167 $rlClient->setConfig( $this->getJSVars() );
3168 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3169 $rlClient->setModuleStyles( $moduleStyles );
3170 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
3171 $rlClient->setExemptStates( $exemptStates );
3172 $this->rlClient
= $rlClient;
3174 return $this->rlClient
;
3178 * @param Skin $sk The given Skin
3179 * @param bool $includeStyle Unused
3180 * @return string The doctype, opening "<html>", and head element.
3182 public function headElement( Skin
$sk, $includeStyle = true ) {
3183 $userdir = $this->getLanguage()->getDir();
3184 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
3187 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
3188 $this->getRlClient()->getDocumentAttributes(),
3189 $sk->getHtmlElementAttributes()
3191 $pieces[] = Html
::openElement( 'head' );
3193 if ( $this->getHTMLTitle() == '' ) {
3194 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3197 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
3198 // Add <meta charset="UTF-8">
3199 // This should be before <title> since it defines the charset used by
3200 // text including the text inside <title>.
3201 // The spec recommends defining XHTML5's charset using the XML declaration
3203 // Our XML declaration is output by Html::htmlHeader.
3204 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3205 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3206 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
3209 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
3210 $pieces[] = $this->getRlClient()->getHeadHtml();
3211 $pieces[] = $this->buildExemptModules();
3212 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3213 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
3215 // Use an IE conditional comment to serve the script only to old IE
3216 $pieces[] = '<!--[if lt IE 9]>' .
3217 ResourceLoaderClientHtml
::makeLoad(
3218 ResourceLoaderContext
::newDummyContext(),
3220 ResourceLoaderModule
::TYPE_SCRIPTS
,
3222 $this->getCSPNonce()
3226 $pieces[] = Html
::closeElement( 'head' );
3228 $bodyClasses = $this->mAdditionalBodyClasses
;
3229 $bodyClasses[] = 'mediawiki';
3231 # Classes for LTR/RTL directionality support
3232 $bodyClasses[] = $userdir;
3233 $bodyClasses[] = "sitedir-$sitedir";
3235 $underline = $this->getUser()->getOption( 'underline' );
3236 if ( $underline < 2 ) {
3237 // The following classes can be used here:
3238 // * mw-underline-always
3239 // * mw-underline-never
3240 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
3243 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3244 # A <body> class is probably not the best way to do this . . .
3245 $bodyClasses[] = 'capitalize-all-nouns';
3248 // Parser feature migration class
3249 // The idea is that this will eventually be removed, after the wikitext
3250 // which requires it is cleaned up.
3251 $bodyClasses[] = 'mw-hide-empty-elt';
3253 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3254 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
3256 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
3259 // While the implode() is not strictly needed, it's used for backwards compatibility
3260 // (this used to be built as a string and hooks likely still expect that).
3261 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3263 // Allow skins and extensions to add body attributes they need
3264 $sk->addToBodyAttributes( $this, $bodyAttrs );
3265 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3267 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3269 return self
::combineWrappedStrings( $pieces );
3273 * Get a ResourceLoader object associated with this OutputPage
3275 * @return ResourceLoader
3277 public function getResourceLoader() {
3278 if ( is_null( $this->mResourceLoader
) ) {
3279 $this->mResourceLoader
= new ResourceLoader(
3281 LoggerFactory
::getInstance( 'resourceloader' )
3284 return $this->mResourceLoader
;
3288 * Explicily load or embed modules on a page.
3290 * @param array|string $modules One or more module names
3291 * @param string $only ResourceLoaderModule TYPE_ class constant
3292 * @param array $extraQuery [optional] Array with extra query parameters for the request
3293 * @return string|WrappedStringList HTML
3295 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3296 // Apply 'target' and 'origin' filters
3297 $modules = $this->filterModules( (array)$modules, null, $only );
3299 return ResourceLoaderClientHtml
::makeLoad(
3300 $this->getRlClientContext(),
3304 $this->getCSPNonce()
3309 * Combine WrappedString chunks and filter out empty ones
3311 * @param array $chunks
3312 * @return string|WrappedStringList HTML
3314 protected static function combineWrappedStrings( array $chunks ) {
3315 // Filter out empty values
3316 $chunks = array_filter( $chunks, 'strlen' );
3317 return WrappedString
::join( "\n", $chunks );
3321 * JS stuff to put at the bottom of the `<body>`.
3322 * These are legacy scripts ($this->mScripts), and user JS.
3324 * @return string|WrappedStringList HTML
3326 public function getBottomScripts() {
3328 $chunks[] = $this->getRlClient()->getBodyHtml();
3330 // Legacy non-ResourceLoader scripts
3331 $chunks[] = $this->mScripts
;
3333 if ( $this->limitReportJSData
) {
3334 $chunks[] = ResourceLoader
::makeInlineScript(
3335 ResourceLoader
::makeConfigSetScript(
3336 [ 'wgPageParseReport' => $this->limitReportJSData
]
3338 $this->getCSPNonce()
3342 return self
::combineWrappedStrings( $chunks );
3346 * Get the javascript config vars to include on this page
3348 * @return array Array of javascript config vars
3351 public function getJsConfigVars() {
3352 return $this->mJsConfigVars
;
3356 * Add one or more variables to be set in mw.config in JavaScript
3358 * @param string|array $keys Key or array of key/value pairs
3359 * @param mixed|null $value [optional] Value of the configuration variable
3361 public function addJsConfigVars( $keys, $value = null ) {
3362 if ( is_array( $keys ) ) {
3363 foreach ( $keys as $key => $value ) {
3364 $this->mJsConfigVars
[$key] = $value;
3369 $this->mJsConfigVars
[$keys] = $value;
3373 * Get an array containing the variables to be set in mw.config in JavaScript.
3375 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3376 * - in other words, page-independent/site-wide variables (without state).
3377 * You will only be adding bloat to the html page and causing page caches to
3378 * have to be purged on configuration changes.
3381 public function getJSVars() {
3384 $canonicalSpecialPageName = false; # T23115
3385 $services = MediaWikiServices
::getInstance();
3387 $title = $this->getTitle();
3388 $ns = $title->getNamespace();
3389 $canonicalNamespace = MWNamespace
::exists( $ns )
3390 ? MWNamespace
::getCanonicalName( $ns )
3391 : $title->getNsText();
3393 $sk = $this->getSkin();
3394 // Get the relevant title so that AJAX features can use the correct page name
3395 // when making API requests from certain special pages (T36972).
3396 $relevantTitle = $sk->getRelevantTitle();
3397 $relevantUser = $sk->getRelevantUser();
3399 if ( $ns == NS_SPECIAL
) {
3400 list( $canonicalSpecialPageName, /*...*/ ) =
3401 $services->getSpecialPageFactory()->
3402 resolveAlias( $title->getDBkey() );
3403 } elseif ( $this->canUseWikiPage() ) {
3404 $wikiPage = $this->getWikiPage();
3405 $curRevisionId = $wikiPage->getLatest();
3406 $articleId = $wikiPage->getId();
3409 $lang = $title->getPageViewLanguage();
3411 // Pre-process information
3412 $separatorTransTable = $lang->separatorTransformTable();
3413 $separatorTransTable = $separatorTransTable ?
: [];
3414 $compactSeparatorTransTable = [
3415 implode( "\t", array_keys( $separatorTransTable ) ),
3416 implode( "\t", $separatorTransTable ),
3418 $digitTransTable = $lang->digitTransformTable();
3419 $digitTransTable = $digitTransTable ?
: [];
3420 $compactDigitTransTable = [
3421 implode( "\t", array_keys( $digitTransTable ) ),
3422 implode( "\t", $digitTransTable ),
3425 $user = $this->getUser();
3428 'wgCanonicalNamespace' => $canonicalNamespace,
3429 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3430 'wgNamespaceNumber' => $title->getNamespace(),
3431 'wgPageName' => $title->getPrefixedDBkey(),
3432 'wgTitle' => $title->getText(),
3433 'wgCurRevisionId' => $curRevisionId,
3434 'wgRevisionId' => (int)$this->getRevisionId(),
3435 'wgArticleId' => $articleId,
3436 'wgIsArticle' => $this->isArticle(),
3437 'wgIsRedirect' => $title->isRedirect(),
3438 'wgAction' => Action
::getActionName( $this->getContext() ),
3439 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3440 'wgUserGroups' => $user->getEffectiveGroups(),
3441 'wgCategories' => $this->getCategories(),
3442 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3443 'wgPageContentLanguage' => $lang->getCode(),
3444 'wgPageContentModel' => $title->getContentModel(),
3445 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3446 'wgDigitTransformTable' => $compactDigitTransTable,
3447 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3448 'wgMonthNames' => $lang->getMonthNamesArray(),
3449 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3450 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3451 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3452 'wgRequestId' => WebRequest
::getRequestId(),
3453 'wgCSPNonce' => $this->getCSPNonce(),
3456 if ( $user->isLoggedIn() ) {
3457 $vars['wgUserId'] = $user->getId();
3458 $vars['wgUserEditCount'] = $user->getEditCount();
3459 $userReg = $user->getRegistration();
3460 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3461 // Get the revision ID of the oldest new message on the user's talk
3462 // page. This can be used for constructing new message alerts on
3464 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3467 $contLang = $services->getContentLanguage();
3468 if ( $contLang->hasVariants() ) {
3469 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3471 // Same test as SkinTemplate
3472 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3473 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3475 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3476 && $relevantTitle->quickUserCan( 'edit', $user )
3477 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3479 foreach ( $title->getRestrictionTypes() as $type ) {
3480 // Following keys are set in $vars:
3481 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3482 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3485 if ( $title->isMainPage() ) {
3486 $vars['wgIsMainPage'] = true;
3489 if ( $this->mRedirectedFrom
) {
3490 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3493 if ( $relevantUser ) {
3494 $vars['wgRelevantUserName'] = $relevantUser->getName();
3497 // Allow extensions to add their custom variables to the mw.config map.
3498 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3499 // page-dependant but site-wide (without state).
3500 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3501 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3503 // Merge in variables from addJsConfigVars last
3504 return array_merge( $vars, $this->getJsConfigVars() );
3508 * To make it harder for someone to slip a user a fake
3509 * JavaScript or CSS preview, a random token
3510 * is associated with the login session. If it's not
3511 * passed back with the preview request, we won't render
3516 public function userCanPreview() {
3517 $request = $this->getRequest();
3519 $request->getVal( 'action' ) !== 'submit' ||
3520 !$request->wasPosted()
3525 $user = $this->getUser();
3527 if ( !$user->isLoggedIn() ) {
3528 // Anons have predictable edit tokens
3531 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3535 $title = $this->getTitle();
3536 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3537 if ( count( $errors ) !== 0 ) {
3545 * @return array Array in format "link name or number => 'link html'".
3547 public function getHeadLinksArray() {
3551 $config = $this->getConfig();
3553 $canonicalUrl = $this->mCanonicalUrl
;
3555 $tags['meta-generator'] = Html
::element( 'meta', [
3556 'name' => 'generator',
3557 'content' => "MediaWiki $wgVersion",
3560 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3561 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3562 // fallbacks should come before the primary value so we need to reverse the array.
3563 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3564 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3565 'name' => 'referrer',
3566 'content' => $policy,
3571 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3572 if ( $p !== 'index,follow' ) {
3573 // http://www.robotstxt.org/wc/meta-user.html
3574 // Only show if it's different from the default robots policy
3575 $tags['meta-robots'] = Html
::element( 'meta', [
3581 foreach ( $this->mMetatags
as $tag ) {
3582 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3584 $tag[0] = substr( $tag[0], 5 );
3585 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3590 $tagName = "meta-{$tag[0]}";
3591 if ( isset( $tags[$tagName] ) ) {
3592 $tagName .= $tag[1];
3594 $tags[$tagName] = Html
::element( 'meta',
3597 'content' => $tag[1]
3602 foreach ( $this->mLinktags
as $tag ) {
3603 $tags[] = Html
::element( 'link', $tag );
3606 # Universal edit button
3607 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3608 $user = $this->getUser();
3609 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3610 && ( $this->getTitle()->exists() ||
3611 $this->getTitle()->quickUserCan( 'create', $user ) )
3613 // Original UniversalEditButton
3614 $msg = $this->msg( 'edit' )->text();
3615 $tags['universal-edit-button'] = Html
::element( 'link', [
3616 'rel' => 'alternate',
3617 'type' => 'application/x-wiki',
3619 'href' => $this->getTitle()->getEditURL(),
3621 // Alternate edit link
3622 $tags['alternative-edit'] = Html
::element( 'link', [
3625 'href' => $this->getTitle()->getEditURL(),
3630 # Generally the order of the favicon and apple-touch-icon links
3631 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3632 # uses whichever one appears later in the HTML source. Make sure
3633 # apple-touch-icon is specified first to avoid this.
3634 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3635 $tags['apple-touch-icon'] = Html
::element( 'link', [
3636 'rel' => 'apple-touch-icon',
3637 'href' => $config->get( 'AppleTouchIcon' )
3641 if ( $config->get( 'Favicon' ) !== false ) {
3642 $tags['favicon'] = Html
::element( 'link', [
3643 'rel' => 'shortcut icon',
3644 'href' => $config->get( 'Favicon' )
3648 # OpenSearch description link
3649 $tags['opensearch'] = Html
::element( 'link', [
3651 'type' => 'application/opensearchdescription+xml',
3652 'href' => wfScript( 'opensearch_desc' ),
3653 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3656 # Real Simple Discovery link, provides auto-discovery information
3657 # for the MediaWiki API (and potentially additional custom API
3658 # support such as WordPress or Twitter-compatible APIs for a
3659 # blogging extension, etc)
3660 $tags['rsd'] = Html
::element( 'link', [
3662 'type' => 'application/rsd+xml',
3663 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3664 // Whether RSD accepts relative or protocol-relative URLs is completely
3665 // undocumented, though.
3666 'href' => wfExpandUrl( wfAppendQuery(
3668 [ 'action' => 'rsd' ] ),
3674 if ( !$config->get( 'DisableLangConversion' ) ) {
3675 $lang = $this->getTitle()->getPageLanguage();
3676 if ( $lang->hasVariants() ) {
3677 $variants = $lang->getVariants();
3678 foreach ( $variants as $variant ) {
3679 $tags["variant-$variant"] = Html
::element( 'link', [
3680 'rel' => 'alternate',
3681 'hreflang' => LanguageCode
::bcp47( $variant ),
3682 'href' => $this->getTitle()->getLocalURL(
3683 [ 'variant' => $variant ] )
3687 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3688 $tags["variant-x-default"] = Html
::element( 'link', [
3689 'rel' => 'alternate',
3690 'hreflang' => 'x-default',
3691 'href' => $this->getTitle()->getLocalURL() ] );
3696 if ( $this->copyrightUrl
!== null ) {
3697 $copyright = $this->copyrightUrl
;
3700 if ( $config->get( 'RightsPage' ) ) {
3701 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3704 $copyright = $copy->getLocalURL();
3708 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3709 $copyright = $config->get( 'RightsUrl' );
3714 $tags['copyright'] = Html
::element( 'link', [
3716 'href' => $copyright ]
3721 if ( $config->get( 'Feed' ) ) {
3724 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3725 # Use the page name for the title. In principle, this could
3726 # lead to issues with having the same name for different feeds
3727 # corresponding to the same page, but we can't avoid that at
3730 $feedLinks[] = $this->feedLink(
3733 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3735 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3740 # Recent changes feed should appear on every page (except recentchanges,
3741 # that would be redundant). Put it after the per-page feed to avoid
3742 # changing existing behavior. It's still available, probably via a
3743 # menu in your browser. Some sites might have a different feed they'd
3744 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3745 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3746 # If so, use it instead.
3747 $sitename = $config->get( 'Sitename' );
3748 if ( $config->get( 'OverrideSiteFeed' ) ) {
3749 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3750 // Note, this->feedLink escapes the url.
3751 $feedLinks[] = $this->feedLink(
3754 $this->msg( "site-{$type}-feed", $sitename )->text()
3757 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3758 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3759 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3760 $feedLinks[] = $this->feedLink(
3762 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3763 # For grep: 'site-rss-feed', 'site-atom-feed'
3764 $this->msg( "site-{$format}-feed", $sitename )->text()
3769 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3770 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3771 # use OutputPage::addFeedLink() instead.
3772 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3774 $tags +
= $feedLinks;
3778 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3779 if ( $canonicalUrl !== false ) {
3780 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3782 if ( $this->isArticleRelated() ) {
3783 // This affects all requests where "setArticleRelated" is true. This is
3784 // typically all requests that show content (query title, curid, oldid, diff),
3785 // and all wikipage actions (edit, delete, purge, info, history etc.).
3786 // It does not apply to File pages and Special pages.
3787 // 'history' and 'info' actions address page metadata rather than the page
3788 // content itself, so they may not be canonicalized to the view page url.
3789 // TODO: this ought to be better encapsulated in the Action class.
3790 $action = Action
::getActionName( $this->getContext() );
3791 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3792 $query = "action={$action}";
3796 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3798 $reqUrl = $this->getRequest()->getRequestURL();
3799 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3803 if ( $canonicalUrl !== false ) {
3804 $tags[] = Html
::element( 'link', [
3805 'rel' => 'canonical',
3806 'href' => $canonicalUrl
3810 // Allow extensions to add, remove and/or otherwise manipulate these links
3811 // If you want only to *add* <head> links, please use the addHeadItem()
3812 // (or addHeadItems() for multiple items) method instead.
3813 // This hook is provided as a last resort for extensions to modify these
3814 // links before the output is sent to client.
3815 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3821 * Generate a "<link rel/>" for a feed.
3823 * @param string $type Feed type
3824 * @param string $url URL to the feed
3825 * @param string $text Value of the "title" attribute
3826 * @return string HTML fragment
3828 private function feedLink( $type, $url, $text ) {
3829 return Html
::element( 'link', [
3830 'rel' => 'alternate',
3831 'type' => "application/$type+xml",
3838 * Add a local or specified stylesheet, with the given media options.
3839 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3841 * @param string $style URL to the file
3842 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3843 * @param string $condition For IE conditional comments, specifying an IE version
3844 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3846 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3849 $options['media'] = $media;
3852 $options['condition'] = $condition;
3855 $options['dir'] = $dir;
3857 $this->styles
[$style] = $options;
3861 * Adds inline CSS styles
3862 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3864 * @param mixed $style_css Inline CSS
3865 * @param string $flip Set to 'flip' to flip the CSS if needed
3867 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3868 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3869 # If wanted, and the interface is right-to-left, flip the CSS
3870 $style_css = CSSJanus
::transform( $style_css, true, false );
3872 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3876 * Build exempt modules and legacy non-ResourceLoader styles.
3878 * @return string|WrappedStringList HTML
3880 protected function buildExemptModules() {
3882 // Things that go after the ResourceLoaderDynamicStyles marker
3885 // We want site, private and user styles to override dynamically added styles from
3886 // general modules, but we want dynamically added styles to override statically added
3887 // style modules. So the order has to be:
3888 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3889 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3890 // - ResourceLoaderDynamicStyles marker
3891 // - site/private/user styles
3893 // Add legacy styles added through addStyle()/addInlineStyle() here
3894 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3896 $chunks[] = Html
::element(
3898 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3901 $separateReq = [ 'site.styles', 'user.styles' ];
3902 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3903 // Combinable modules
3904 $chunks[] = $this->makeResourceLoaderLink(
3905 array_diff( $moduleNames, $separateReq ),
3906 ResourceLoaderModule
::TYPE_STYLES
3909 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3910 // These require their own dedicated request in order to support "@import"
3911 // syntax, which is incompatible with concatenation. (T147667, T37562)
3912 $chunks[] = $this->makeResourceLoaderLink( $name,
3913 ResourceLoaderModule
::TYPE_STYLES
3918 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3924 public function buildCssLinksArray() {
3927 foreach ( $this->styles
as $file => $options ) {
3928 $link = $this->styleLink( $file, $options );
3930 $links[$file] = $link;
3937 * Generate \<link\> tags for stylesheets
3939 * @param string $style URL to the file
3940 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3941 * @return string HTML fragment
3943 protected function styleLink( $style, array $options ) {
3944 if ( isset( $options['dir'] ) ) {
3945 if ( $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' );
4195 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
4197 public function sectionEditLinksEnabled() {
4198 wfDeprecated( __METHOD__
, '1.31' );
4203 * Helper function to setup the PHP implementation of OOUI to use in this request.
4206 * @param string $skinName The Skin name to determine the correct OOUI theme
4207 * @param string $dir Language direction
4209 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4210 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
4211 $theme = $themes[$skinName] ??
$themes['default'];
4212 // For example, 'OOUI\WikimediaUITheme'.
4213 $themeClass = "OOUI\\{$theme}Theme";
4214 OOUI\Theme
::setSingleton( new $themeClass() );
4215 OOUI\Element
::setDefaultDir( $dir );
4219 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4220 * MediaWiki and this OutputPage instance.
4224 public function enableOOUI() {
4226 strtolower( $this->getSkin()->getSkinName() ),
4227 $this->getLanguage()->getDir()
4229 $this->addModuleStyles( [
4230 'oojs-ui-core.styles',
4231 'oojs-ui.styles.indicators',
4232 'oojs-ui.styles.textures',
4233 'mediawiki.widgets.styles',
4234 'oojs-ui.styles.icons-content',
4235 'oojs-ui.styles.icons-alerts',
4236 'oojs-ui.styles.icons-interactions',
4241 * Get (and set if not yet set) the CSP nonce.
4243 * This value needs to be included in any <script> tags on the
4246 * @return string|bool Nonce or false to mean don't output nonce
4249 public function getCSPNonce() {
4250 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
4253 if ( $this->CSPNonce
=== null ) {
4254 // XXX It might be expensive to generate randomness
4255 // on every request, on Windows.
4256 $rand = random_bytes( 15 );
4257 $this->CSPNonce
= base64_encode( $rand );
4259 return $this->CSPNonce
;