ParsoidParser: Record ParserOptions watcher on ParserOutput object
[mediawiki.git] / includes / OutputPage.php
blobf389e02f5147507edd2547caf53f8b92541ef22b
1 <?php
2 /**
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
20 * @file
23 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
24 use MediaWiki\Html\Html;
25 use MediaWiki\Linker\LinkTarget;
26 use MediaWiki\MainConfigNames;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Page\PageRecord;
29 use MediaWiki\Page\PageReference;
30 use MediaWiki\Parser\ParserOutputFlags;
31 use MediaWiki\Permissions\PermissionStatus;
32 use MediaWiki\Request\ContentSecurityPolicy;
33 use MediaWiki\Request\FauxRequest;
34 use MediaWiki\ResourceLoader as RL;
35 use MediaWiki\ResourceLoader\ResourceLoader;
36 use MediaWiki\Session\SessionManager;
37 use MediaWiki\Title\Title;
38 use Wikimedia\AtEase\AtEase;
39 use Wikimedia\Parsoid\Core\TOCData;
40 use Wikimedia\Rdbms\IResultWrapper;
41 use Wikimedia\RelPath;
42 use Wikimedia\WrappedString;
43 use Wikimedia\WrappedStringList;
45 /**
46 * This is one of the Core classes and should
47 * be read at least once by any new developers. Also documented at
48 * https://www.mediawiki.org/wiki/Manual:Architectural_modules/OutputPage
50 * This class is used to prepare the final rendering. A skin is then
51 * applied to the output parameters (links, javascript, html, categories ...).
53 * @todo FIXME: Another class handles sending the whole page to the client.
55 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
56 * in November 2010.
58 * @todo document
60 class OutputPage extends ContextSource {
61 use ProtectedHookAccessorTrait;
63 // Constants for getJSVars()
64 private const JS_VAR_EARLY = 1;
65 private const JS_VAR_LATE = 2;
67 // Core config vars that opt-in to JS_VAR_LATE.
68 // Extensions use the 'LateJSConfigVarNames' attribute instead.
69 private const CORE_LATE_JS_CONFIG_VAR_NAMES = [];
71 /** @var string[][] Should be private. Used with addMeta() which adds "<meta>" */
72 protected $mMetatags = [];
74 /** @var array */
75 protected $mLinktags = [];
77 /** @var string|false */
78 protected $mCanonicalUrl = false;
80 /**
81 * @var string The contents of <h1>
83 private $mPageTitle = '';
85 /**
86 * @var string The displayed title of the page. Different from page title
87 * if overridden by display title magic word or hooks. Can contain safe
88 * HTML. Different from page title which may contain messages such as
89 * "Editing X" which is displayed in h1. This can be used for other places
90 * where the page name is referred on the page.
92 private $displayTitle;
94 /** @var bool See OutputPage::couldBePublicCached. */
95 private $cacheIsFinal = false;
97 /**
98 * @var string Contains all of the "<body>" content. Should be private we
99 * got set/get accessors and the append() method.
101 public $mBodytext = '';
103 /** @var string Stores contents of "<title>" tag */
104 private $mHTMLtitle = '';
107 * @var bool Is the displayed content related to the source of the
108 * corresponding wiki article.
110 private $mIsArticle = false;
112 /** @var bool Stores "article flag" toggle. */
113 private $mIsArticleRelated = true;
115 /** @var bool Is the content subject to copyright */
116 private $mHasCopyright = false;
119 * @var bool We have to set isPrintable(). Some pages should
120 * never be printed (ex: redirections).
122 private $mPrintable = false;
125 * @var ?TOCData Table of Contents information from ParserOutput, or
126 * null if no TOCData was ever set.
128 private $tocData;
131 * @var array Contains the page subtitle. Special pages usually have some
132 * links here. Don't confuse with site subtitle added by skins.
134 private $mSubtitle = [];
136 /** @var string */
137 public $mRedirect = '';
139 /** @var int */
140 protected $mStatusCode;
143 * @var string Used for sending cache control.
144 * The whole caching system should probably be moved into its own class.
146 protected $mLastModified = '';
149 * @var string[][]
150 * @deprecated since 1.38; will be made private (T301020)
152 protected $mCategoryLinks = [];
155 * @var string[][]
156 * @deprecated since 1.38, will be made private (T301020)
158 protected $mCategories = [
159 'hidden' => [],
160 'normal' => [],
164 * @var string[]
165 * @deprecated since 1.38; will be made private (T301020)
167 protected $mIndicators = [];
170 * @var string[] Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
172 private $mLanguageLinks = [];
175 * Used for JavaScript (predates ResourceLoader)
176 * @todo We should split JS / CSS.
177 * mScripts content is inserted as is in "<head>" by Skin. This might
178 * contain either a link to a stylesheet or inline CSS.
180 private $mScripts = '';
182 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
183 protected $mInlineStyles = '';
186 * @var string Used by skin template.
187 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
189 public $mPageLinkTitle = '';
192 * Additional <html> classes; This should be rarely modified; prefer mAdditionalBodyClasses.
193 * @var array
195 protected $mAdditionalHtmlClasses = [];
198 * @var string[] Array of elements in "<head>". Parser might add its own headers!
199 * @deprecated since 1.38; will be made private (T301020)
201 protected $mHeadItems = [];
203 /** @var array Additional <body> classes; there are also <body> classes from other sources */
204 protected $mAdditionalBodyClasses = [];
207 * @var array
208 * @deprecated since 1.38; will be made private (T301020)
210 protected $mModules = [];
213 * @var array
214 * @deprecated since 1.38; will be made private (T301020)
216 protected $mModuleStyles = [];
218 /** @var ResourceLoader */
219 protected $mResourceLoader;
221 /** @var RL\ClientHtml */
222 private $rlClient;
224 /** @var RL\Context */
225 private $rlClientContext;
227 /** @var array */
228 private $rlExemptStyleModules;
231 * @var array
232 * @deprecated since 1.38; will be made private (T301020)
234 protected $mJsConfigVars = [];
237 * @var array<int,array<string,int>>
238 * @deprecated since 1.38; will be made private (T301020)
240 protected $mTemplateIds = [];
242 /** @var array */
243 protected $mImageTimeKeys = [];
245 /** @var string */
246 public $mRedirectCode = '';
248 protected $mFeedLinksAppendQuery = null;
250 /** @var array
251 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
252 * @see RL\Module::$origin
253 * RL\Module::ORIGIN_ALL is assumed unless overridden;
255 protected $mAllowedModules = [
256 RL\Module::TYPE_COMBINED => RL\Module::ORIGIN_ALL,
259 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
260 protected $mDoNothing = false;
262 // Parser related.
265 * lazy initialised, use parserOptions()
266 * @var ParserOptions
268 protected $mParserOptions = null;
271 * Handles the Atom / RSS links.
272 * We probably only support Atom in 2011.
273 * @see $wgAdvertisedFeedTypes
275 private $mFeedLinks = [];
278 * @var bool Set to false to send no-cache headers, disabling
279 * client-side caching. (This variable should really be named
280 * in the opposite sense; see ::disableClientCache().)
281 * @deprecated since 1.38; will be made private (T301020)
283 protected $mEnableClientCache = true;
285 /** @var bool Flag if output should only contain the body of the article. */
286 private $mArticleBodyOnly = false;
289 * @var bool
290 * @deprecated since 1.38; will be made private (T301020)
292 protected $mNewSectionLink = false;
295 * @var bool
296 * @deprecated since 1.38; will be made private (T301020)
298 protected $mHideNewSectionLink = false;
301 * @var bool Comes from the parser. This was probably made to load CSS/JS
302 * only if we had "<gallery>". Used directly in CategoryPage.php.
303 * Looks like ResourceLoader can replace this.
304 * @deprecated since 1.38; will be made private (T301020)
306 public $mNoGallery = false;
308 /** @var int Cache stuff. Looks like mEnableClientCache */
309 protected $mCdnMaxage = 0;
310 /** @var int Upper limit on mCdnMaxage */
311 protected $mCdnMaxageLimit = INF;
314 * @var bool Controls if anti-clickjacking / frame-breaking headers will
315 * be sent. This should be done for pages where edit actions are possible.
316 * Setter: $this->setPreventClickjacking()
318 protected $mPreventClickjacking = true;
320 /** @var int|null To include the variable {{REVISIONID}} */
321 private $mRevisionId = null;
323 /** @var bool|null */
324 private $mRevisionIsCurrent = null;
326 /** @var string */
327 private $mRevisionTimestamp = null;
329 /** @var array */
330 protected $mFileVersion = null;
333 * @var array An array of stylesheet filenames (relative from skins path),
334 * with options for CSS media, IE conditions, and RTL/LTR direction.
335 * For internal use; add settings in the skin via $this->addStyle()
337 * Style again! This seems like a code duplication since we already have
338 * mStyles. This is what makes Open Source amazing.
340 protected $styles = [];
342 private $mIndexPolicy = 'index';
343 private $mFollowPolicy = 'follow';
345 /** @var array */
346 private $mRobotsOptions = [ 'max-image-preview' => 'standard' ];
349 * @var array Headers that cause the cache to vary. Key is header name,
350 * value should always be null. (Value was an array of options for
351 * the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
353 private $mVaryHeader = [
354 'Accept-Encoding' => null,
358 * If the current page was reached through a redirect, $mRedirectedFrom contains the title
359 * of the redirect.
361 * @var PageReference
363 private $mRedirectedFrom = null;
366 * Additional key => value data
368 private $mProperties = [];
371 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
373 private $mTarget = null;
376 * @var bool Whether parser output contains a table of contents
378 private $mEnableTOC = false;
381 * @var array<string,bool> Flags set in the ParserOutput
383 private $mOutputFlags = [];
386 * @var string|null The URL to send in a <link> element with rel=license
388 private $copyrightUrl;
390 /** @var array Profiling data */
391 private $limitReportJSData = [];
393 /** @var array Map Title to Content */
394 private $contentOverrides = [];
396 /** @var callable[] */
397 private $contentOverrideCallbacks = [];
400 * Link: header contents
402 private $mLinkHeader = [];
405 * @var ContentSecurityPolicy
407 private $CSP;
410 * @var array A cache of the names of the cookies that will influence the cache
412 private static $cacheVaryCookies = null;
415 * Constructor for OutputPage. This should not be called directly.
416 * Instead a new RequestContext should be created and it will implicitly create
417 * a OutputPage tied to that context.
418 * @param IContextSource $context
420 public function __construct( IContextSource $context ) {
421 $this->setContext( $context );
422 $this->CSP = new ContentSecurityPolicy(
423 $context->getRequest()->response(),
424 $context->getConfig(),
425 $this->getHookContainer()
430 * Redirect to $url rather than displaying the normal page
432 * @param string $url
433 * @param string|int $responsecode HTTP status code
435 public function redirect( $url, $responsecode = '302' ) {
436 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
437 $this->mRedirect = str_replace( "\n", '', $url );
438 $this->mRedirectCode = (string)$responsecode;
442 * Get the URL to redirect to, or an empty string if not redirect URL set
444 * @return string
446 public function getRedirect() {
447 return $this->mRedirect;
451 * Set the copyright URL to send with the output.
452 * Empty string to omit, null to reset.
454 * @since 1.26
456 * @param string|null $url
458 public function setCopyrightUrl( $url ) {
459 $this->copyrightUrl = $url;
463 * Set the HTTP status code to send with the output.
465 * @param int $statusCode
467 public function setStatusCode( $statusCode ) {
468 $this->mStatusCode = $statusCode;
472 * Add a new "<meta>" tag
473 * To add an http-equiv meta tag, precede the name with "http:"
475 * @param string $name Name of the meta tag
476 * @param string $val Value of the meta tag
478 public function addMeta( $name, $val ) {
479 $this->mMetatags[] = [ $name, $val ];
483 * Returns the current <meta> tags
485 * @since 1.25
486 * @return array
488 public function getMetaTags() {
489 return $this->mMetatags;
493 * Add a new \<link\> tag to the page header.
495 * Note: use setCanonicalUrl() for rel=canonical.
497 * @param array $linkarr Associative array of attributes.
499 public function addLink( array $linkarr ) {
500 $this->mLinktags[] = $linkarr;
504 * Returns the current <link> tags
506 * @since 1.25
507 * @return array
509 public function getLinkTags() {
510 return $this->mLinktags;
514 * Set the URL to be used for the <link rel=canonical>. This should be used
515 * in preference to addLink(), to avoid duplicate link tags.
516 * @param string $url
518 public function setCanonicalUrl( $url ) {
519 $this->mCanonicalUrl = $url;
523 * Returns the URL to be used for the <link rel=canonical> if
524 * one is set.
526 * @since 1.25
527 * @return bool|string
529 public function getCanonicalUrl() {
530 return $this->mCanonicalUrl;
534 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
535 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
536 * if possible.
538 * @param string $script Raw HTML
540 public function addScript( $script ) {
541 $this->mScripts .= $script;
545 * Add a JavaScript file to be loaded as `<script>` on this page.
547 * Internal use only. Use OutputPage::addModules() if possible.
549 * @param string $file URL to file (absolute path, protocol-relative, or full url)
550 * @param string|null $unused Previously used to change the cache-busting query parameter
552 public function addScriptFile( $file, $unused = null ) {
553 $this->addScript( Html::linkedScript( $file, $this->CSP->getNonce() ) );
557 * Add a self-contained script tag with the given contents
558 * Internal use only. Use OutputPage::addModules() if possible.
560 * @param string $script JavaScript text, no script tags
562 public function addInlineScript( $script ) {
563 $this->mScripts .= Html::inlineScript( "\n$script\n", $this->CSP->getNonce() ) . "\n";
567 * Filter an array of modules to remove insufficiently trustworthy members, and modules
568 * which are no longer registered (eg a page is cached before an extension is disabled)
569 * @param string[] $modules
570 * @param string|null $position Unused
571 * @param string $type
572 * @return string[]
574 protected function filterModules( array $modules, $position = null,
575 $type = RL\Module::TYPE_COMBINED
577 $resourceLoader = $this->getResourceLoader();
578 $filteredModules = [];
579 foreach ( $modules as $val ) {
580 $module = $resourceLoader->getModule( $val );
581 if ( $module instanceof RL\Module
582 && $module->getOrigin() <= $this->getAllowedModules( $type )
584 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
585 $this->warnModuleTargetFilter( $module->getName() );
586 continue;
588 $filteredModules[] = $val;
591 return $filteredModules;
594 private function warnModuleTargetFilter( $moduleName ) {
595 static $warnings = [];
596 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
597 return;
599 $warnings[$this->mTarget][$moduleName] = true;
600 $this->getResourceLoader()->getLogger()->debug(
601 'Module "{module}" not loadable on target "{target}".',
603 'module' => $moduleName,
604 'target' => $this->mTarget,
610 * Get the list of modules to include on this page
612 * @param bool $filter Whether to filter out insufficiently trustworthy modules
613 * @param string|null $position Unused
614 * @param string $param
615 * @param string $type
616 * @return string[] Array of module names
618 public function getModules( $filter = false, $position = null, $param = 'mModules',
619 $type = RL\Module::TYPE_COMBINED
621 $modules = array_values( array_unique( $this->$param ) );
622 return $filter
623 ? $this->filterModules( $modules, null, $type )
624 : $modules;
628 * Load one or more ResourceLoader modules on this page.
630 * @param string|array $modules Module name (string) or array of module names
632 public function addModules( $modules ) {
633 $this->mModules = array_merge( $this->mModules, (array)$modules );
637 * Get the list of style-only modules to load on this page.
639 * @param bool $filter
640 * @param string|null $position Unused
641 * @return string[] Array of module names
643 public function getModuleStyles( $filter = false, $position = null ) {
644 return $this->getModules( $filter, null, 'mModuleStyles',
645 RL\Module::TYPE_STYLES
650 * Load the styles of one or more style-only ResourceLoader modules on this page.
652 * Module styles added through this function will be loaded as a stylesheet,
653 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
654 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
656 * @param string|array $modules Module name (string) or array of module names
658 public function addModuleStyles( $modules ) {
659 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
663 * @return null|string ResourceLoader target
665 public function getTarget() {
666 return $this->mTarget;
670 * Sets ResourceLoader target for load.php links. If null, will be omitted
672 * @param string|null $target
674 public function setTarget( $target ) {
675 $this->mTarget = $target;
679 * Force the given Content object for the given page, for things like page preview.
680 * @see self::addContentOverrideCallback()
681 * @since 1.32
682 * @param LinkTarget|PageReference $target
683 * @param Content $content
685 public function addContentOverride( $target, Content $content ) {
686 if ( !$this->contentOverrides ) {
687 // Register a callback for $this->contentOverrides on the first call
688 $this->addContentOverrideCallback( function ( $target ) {
689 $key = $target->getNamespace() . ':' . $target->getDBkey();
690 return $this->contentOverrides[$key] ?? null;
691 } );
694 $key = $target->getNamespace() . ':' . $target->getDBkey();
695 $this->contentOverrides[$key] = $content;
699 * Add a callback for mapping from a Title to a Content object, for things
700 * like page preview.
701 * @see RL\Context::getContentOverrideCallback()
702 * @since 1.32
703 * @param callable $callback
705 public function addContentOverrideCallback( callable $callback ) {
706 $this->contentOverrideCallbacks[] = $callback;
710 * Add a class to the <html> element. This should rarely be used.
711 * Instead use OutputPage::addBodyClasses() if possible.
713 * @unstable Experimental since 1.35. Prefer OutputPage::addBodyClasses()
714 * @param string|string[] $classes One or more classes to add
716 public function addHtmlClasses( $classes ) {
717 $this->mAdditionalHtmlClasses = array_merge( $this->mAdditionalHtmlClasses, (array)$classes );
721 * Get an array of head items
723 * @return string[]
725 public function getHeadItemsArray() {
726 return $this->mHeadItems;
730 * Add or replace a head item to the output
732 * Whenever possible, use more specific options like ResourceLoader modules,
733 * OutputPage::addLink(), OutputPage::addMeta() and OutputPage::addFeedLink()
734 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
735 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
736 * This would be your very LAST fallback.
738 * @param string $name Item name
739 * @param string $value Raw HTML
741 public function addHeadItem( $name, $value ) {
742 $this->mHeadItems[$name] = $value;
746 * Add one or more head items to the output
748 * @since 1.28
749 * @param string|string[] $values Raw HTML
751 public function addHeadItems( $values ) {
752 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
756 * Check if the header item $name is already set
758 * @param string $name Item name
759 * @return bool
761 public function hasHeadItem( $name ) {
762 return isset( $this->mHeadItems[$name] );
766 * Add a class to the <body> element
768 * @since 1.30
769 * @param string|string[] $classes One or more classes to add
771 public function addBodyClasses( $classes ) {
772 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
776 * Set whether the output should only contain the body of the article,
777 * without any skin, sidebar, etc.
778 * Used e.g. when calling with "action=render".
780 * @param bool $only Whether to output only the body of the article
782 public function setArticleBodyOnly( $only ) {
783 $this->mArticleBodyOnly = $only;
787 * Return whether the output will contain only the body of the article
789 * @return bool
791 public function getArticleBodyOnly() {
792 return $this->mArticleBodyOnly;
796 * Set an additional output property
797 * @since 1.21
799 * @param string $name
800 * @param mixed $value
802 public function setProperty( $name, $value ) {
803 $this->mProperties[$name] = $value;
807 * Get an additional output property
808 * @since 1.21
810 * @param string $name
811 * @return mixed Property value or null if not found
813 public function getProperty( $name ) {
814 return $this->mProperties[$name] ?? null;
818 * checkLastModified tells the client to use the client-cached page if
819 * possible. If successful, the OutputPage is disabled so that
820 * any future call to OutputPage->output() have no effect.
822 * Side effect: sets mLastModified for Last-Modified header
824 * @param string $timestamp
826 * @return bool True if cache-ok headers was sent.
828 public function checkLastModified( $timestamp ) {
829 if ( !$timestamp || $timestamp == '19700101000000' ) {
830 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP" );
831 return false;
833 $config = $this->getConfig();
834 if ( !$config->get( MainConfigNames::CachePages ) ) {
835 wfDebug( __METHOD__ . ": CACHE DISABLED" );
836 return false;
839 $timestamp = wfTimestamp( TS_MW, $timestamp );
840 $modifiedTimes = [
841 'page' => $timestamp,
842 'user' => $this->getUser()->getTouched(),
843 'epoch' => $config->get( MainConfigNames::CacheEpoch )
845 if ( $config->get( MainConfigNames::UseCdn ) ) {
846 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
847 time(),
848 $config->get( MainConfigNames::CdnMaxAge )
849 ) );
851 $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this );
853 $maxModified = max( $modifiedTimes );
854 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
856 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
857 if ( $clientHeader === false ) {
858 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
859 return false;
862 # IE sends sizes after the date like this:
863 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
864 # this breaks strtotime().
865 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
867 // E_STRICT system time warnings
868 AtEase::suppressWarnings();
869 $clientHeaderTime = strtotime( $clientHeader );
870 AtEase::restoreWarnings();
871 if ( !$clientHeaderTime ) {
872 wfDebug( __METHOD__
873 . ": unable to parse the client's If-Modified-Since header: $clientHeader" );
874 return false;
876 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
878 # Make debug info
879 $info = '';
880 foreach ( $modifiedTimes as $name => $value ) {
881 if ( $info !== '' ) {
882 $info .= ', ';
884 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
887 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
888 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
889 wfDebug( __METHOD__ . ": effective Last-Modified: " .
890 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
891 if ( $clientHeaderTime < $maxModified ) {
892 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
893 return false;
896 # Not modified
897 # Give a 304 Not Modified response code and disable body output
898 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
899 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
900 ini_set( 'zlib.output_compression', 0 );
901 $this->getRequest()->response()->statusHeader( 304 );
902 $this->sendCacheControl();
903 $this->disable();
905 // Don't output a compressed blob when using ob_gzhandler;
906 // it's technically against HTTP spec and seems to confuse
907 // Firefox when the response gets split over two packets.
908 wfResetOutputBuffers( false );
910 return true;
914 * @param int $reqTime Time of request (eg. now)
915 * @param int $maxAge Cache TTL in seconds
916 * @return int Timestamp
918 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
919 // Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
920 // because even if the wiki page content hasn't changed since, static
921 // resources may have changed (skin HTML, interface messages, urls, etc.)
922 // and must roll-over in a timely manner (T46570)
923 return $reqTime - $maxAge;
927 * Override the last modified timestamp
929 * @param string $timestamp New timestamp, in a format readable by
930 * wfTimestamp()
932 public function setLastModified( $timestamp ) {
933 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
937 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
939 * @param string $policy The literal string to output as the contents of
940 * the meta tag. Will be parsed according to the spec and output in
941 * standardized form.
943 public function setRobotPolicy( $policy ) {
944 $policy = Article::formatRobotPolicy( $policy );
946 if ( isset( $policy['index'] ) ) {
947 $this->setIndexPolicy( $policy['index'] );
949 if ( isset( $policy['follow'] ) ) {
950 $this->setFollowPolicy( $policy['follow'] );
955 * Get the current robot policy for the page as a string in the form
956 * <index policy>,<follow policy>.
958 * @return string
960 public function getRobotPolicy() {
961 return "{$this->mIndexPolicy},{$this->mFollowPolicy}";
965 * Format an array of robots options as a string of directives.
967 * @return string The robots policy options.
969 private function formatRobotsOptions(): string {
970 $options = $this->mRobotsOptions;
971 // Check if options array has any non-integer keys.
972 if ( count( array_filter( array_keys( $options ), 'is_string' ) ) > 0 ) {
973 // Robots meta tags can have directives that are single strings or
974 // have parameters that should be formatted like <directive>:<setting>.
975 // If the options keys are strings, format them accordingly.
976 // https://developers.google.com/search/docs/advanced/robots/robots_meta_tag
977 array_walk( $options, static function ( &$value, $key ) {
978 $value = is_string( $key ) ? "{$key}:{$value}" : "{$value}";
979 } );
981 return implode( ',', $options );
985 * Set the robots policy with options for the page.
987 * @since 1.38
988 * @param array $options An array of key-value pairs or a string
989 * to populate the robots meta tag content attribute as a string.
991 public function setRobotsOptions( array $options = [] ): void {
992 $this->mRobotsOptions = array_merge( $this->mRobotsOptions, $options );
996 * Get the robots policy content attribute for the page
997 * as a string in the form <index policy>,<follow policy>,<options>.
999 * @return string
1001 private function getRobotsContent(): string {
1002 $robotOptionString = $this->formatRobotsOptions();
1003 $robotArgs = ( $this->mIndexPolicy === 'index' &&
1004 $this->mFollowPolicy === 'follow' ) ?
1005 [] :
1007 $this->mIndexPolicy,
1008 $this->mFollowPolicy,
1010 if ( $robotOptionString ) {
1011 $robotArgs[] = $robotOptionString;
1013 return implode( ',', $robotArgs );
1017 * Set the index policy for the page, but leave the follow policy un-
1018 * touched.
1020 * @param string $policy Either 'index' or 'noindex'.
1022 public function setIndexPolicy( $policy ) {
1023 $policy = trim( $policy );
1024 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
1025 $this->mIndexPolicy = $policy;
1030 * Get the current index policy for the page as a string.
1032 * @return string
1034 public function getIndexPolicy() {
1035 return $this->mIndexPolicy;
1039 * Set the follow policy for the page, but leave the index policy un-
1040 * touched.
1042 * @param string $policy Either 'follow' or 'nofollow'.
1044 public function setFollowPolicy( $policy ) {
1045 $policy = trim( $policy );
1046 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
1047 $this->mFollowPolicy = $policy;
1052 * Get the current follow policy for the page as a string.
1054 * @return string
1056 public function getFollowPolicy() {
1057 return $this->mFollowPolicy;
1061 * "HTML title" means the contents of "<title>".
1062 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
1064 * @param string|Message $name
1066 public function setHTMLTitle( $name ) {
1067 if ( $name instanceof Message ) {
1068 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
1069 } else {
1070 $this->mHTMLtitle = $name;
1075 * Return the "HTML title", i.e. the content of the "<title>" tag.
1077 * @return string
1079 public function getHTMLTitle() {
1080 return $this->mHTMLtitle;
1084 * Set $mRedirectedFrom, the page which redirected us to the current page.
1086 * @param PageReference $t
1088 public function setRedirectedFrom( PageReference $t ) {
1089 $this->mRedirectedFrom = $t;
1093 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
1094 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
1095 * but not bad tags like \<script\>. This function automatically sets
1096 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
1097 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
1098 * good tags like \<i\> will be dropped entirely.
1100 * @param string|Message $name
1101 * @param-taint $name tainted
1102 * Phan-taint-check gets very confused by $name being either a string or a Message
1104 public function setPageTitle( $name ) {
1105 if ( $name instanceof Message ) {
1106 $name = $name->setContext( $this->getContext() )->text();
1109 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
1110 # but leave "<i>foobar</i>" alone
1111 $nameWithTags = Sanitizer::removeSomeTags( $name );
1112 $this->mPageTitle = $nameWithTags;
1114 # change "<i>foo&amp;bar</i>" to "foo&bar"
1115 $this->setHTMLTitle(
1116 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer::stripAllTags( $nameWithTags ) )
1117 ->inContentLanguage()
1122 * Return the "page title", i.e. the content of the \<h1\> tag.
1124 * @return string
1126 public function getPageTitle() {
1127 return $this->mPageTitle;
1131 * Same as page title but only contains name of the page, not any other text.
1133 * @since 1.32
1134 * @param string $html Page title text.
1135 * @see OutputPage::setPageTitle
1137 public function setDisplayTitle( $html ) {
1138 $this->displayTitle = $html;
1142 * Returns page display title.
1144 * Performs some normalization, but this not as strict the magic word.
1146 * @since 1.32
1147 * @return string HTML
1149 public function getDisplayTitle() {
1150 $html = $this->displayTitle;
1151 if ( $html === null ) {
1152 return htmlspecialchars( $this->getTitle()->getPrefixedText(), ENT_NOQUOTES );
1155 return Sanitizer::removeSomeTags( $html );
1159 * Returns page display title without namespace prefix if possible.
1161 * This method is unreliable and best avoided. (T314399)
1163 * @since 1.32
1164 * @return string HTML
1166 public function getUnprefixedDisplayTitle() {
1167 $service = MediaWikiServices::getInstance();
1168 $languageConverter = $service->getLanguageConverterFactory()
1169 ->getLanguageConverter( $service->getContentLanguage() );
1170 $text = $this->getDisplayTitle();
1172 // Create a regexp with matching groups as placeholders for the namespace, separator and main text
1173 $pageTitleRegexp = "/^" . str_replace(
1174 preg_quote( '(.+?)', '/' ),
1175 '(.+?)',
1176 preg_quote( Parser::formatPageTitle( '(.+?)', '(.+?)', '(.+?)' ), '/' )
1177 ) . "$/";
1178 $matches = [];
1179 if ( preg_match( $pageTitleRegexp, $text, $matches ) ) {
1180 // The regexp above could be manipulated by malicious user input,
1181 // sanitize the result just in case
1182 return Sanitizer::removeSomeTags( $matches[3] );
1185 $nsPrefix = $languageConverter->convertNamespace(
1186 $this->getTitle()->getNamespace()
1187 ) . ':';
1188 $prefix = preg_quote( $nsPrefix, '/' );
1190 return preg_replace( "/^$prefix/i", '', $text );
1194 * Set the Title object to use
1196 * @param PageReference $t
1198 public function setTitle( PageReference $t ) {
1199 $t = Title::newFromPageReference( $t );
1201 // @phan-suppress-next-next-line PhanUndeclaredMethod
1202 // @fixme Not all implementations of IContextSource have this method!
1203 $this->getContext()->setTitle( $t );
1207 * Replace the subtitle with $str
1209 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1211 public function setSubtitle( $str ) {
1212 $this->clearSubtitle();
1213 $this->addSubtitle( $str );
1217 * Add $str to the subtitle
1219 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1221 public function addSubtitle( $str ) {
1222 if ( $str instanceof Message ) {
1223 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1224 } else {
1225 $this->mSubtitle[] = $str;
1230 * Build message object for a subtitle containing a backlink to a page
1232 * @since 1.25
1233 * @param PageReference $page Title to link to
1234 * @param array $query Array of additional parameters to include in the link
1235 * @return Message
1237 public static function buildBacklinkSubtitle( PageReference $page, $query = [] ) {
1238 if ( $page instanceof PageRecord || $page instanceof Title ) {
1239 // Callers will typically have a PageRecord
1240 if ( $page->isRedirect() ) {
1241 $query['redirect'] = 'no';
1243 } elseif ( $page->getNamespace() !== NS_SPECIAL ) {
1244 // We don't know whether it's a redirect, so add the parameter, just to be sure.
1245 $query['redirect'] = 'no';
1248 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1249 return wfMessage( 'backlinksubtitle' )
1250 ->rawParams( $linkRenderer->makeLink( $page, null, [], $query ) );
1254 * Add a subtitle containing a backlink to a page
1256 * @param PageReference $title Title to link to
1257 * @param array $query Array of additional parameters to include in the link
1259 public function addBacklinkSubtitle( PageReference $title, $query = [] ) {
1260 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1264 * Clear the subtitles
1266 public function clearSubtitle() {
1267 $this->mSubtitle = [];
1271 * @return string
1273 public function getSubtitle() {
1274 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1278 * Set the page as printable, i.e. it'll be displayed with all
1279 * print styles included
1281 public function setPrintable() {
1282 $this->mPrintable = true;
1286 * Return whether the page is "printable"
1288 * @return bool
1290 public function isPrintable() {
1291 return $this->mPrintable;
1295 * Disable output completely, i.e. calling output() will have no effect
1297 public function disable() {
1298 $this->mDoNothing = true;
1302 * Return whether the output will be completely disabled
1304 * @return bool
1306 public function isDisabled() {
1307 return $this->mDoNothing;
1311 * Show an "add new section" link?
1313 * @return bool
1315 public function showNewSectionLink() {
1316 return $this->mNewSectionLink;
1320 * Forcibly hide the new section link?
1322 * @return bool
1324 public function forceHideNewSectionLink() {
1325 return $this->mHideNewSectionLink;
1329 * Add or remove feed links in the page header
1330 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1331 * for the new version
1332 * @see addFeedLink()
1334 * @param bool $show True: add default feeds, false: remove all feeds
1336 public function setSyndicated( $show = true ) {
1337 if ( $show ) {
1338 $this->setFeedAppendQuery( false );
1339 } else {
1340 $this->mFeedLinks = [];
1345 * Return effective list of advertised feed types
1346 * @see addFeedLink()
1348 * @return string[] Array of feed type names ( 'rss', 'atom' )
1350 protected function getAdvertisedFeedTypes() {
1351 if ( $this->getConfig()->get( MainConfigNames::Feed ) ) {
1352 return $this->getConfig()->get( MainConfigNames::AdvertisedFeedTypes );
1353 } else {
1354 return [];
1359 * Add default feeds to the page header
1360 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1361 * for the new version
1362 * @see addFeedLink()
1364 * @param string|false $val Query to append to feed links or false to output
1365 * default links
1367 public function setFeedAppendQuery( $val ) {
1368 $this->mFeedLinks = [];
1370 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1371 $query = "feed=$type";
1372 if ( is_string( $val ) ) {
1373 $query .= '&' . $val;
1375 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1380 * Add a feed link to the page header
1382 * @param string $format Feed type, should be a key of $wgFeedClasses
1383 * @param string $href URL
1385 public function addFeedLink( $format, $href ) {
1386 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1387 $this->mFeedLinks[$format] = $href;
1392 * Should we output feed links for this page?
1393 * @return bool
1395 public function isSyndicated() {
1396 return count( $this->mFeedLinks ) > 0;
1400 * Return URLs for each supported syndication format for this page.
1401 * @return array Associating format keys with URLs
1403 public function getSyndicationLinks() {
1404 return $this->mFeedLinks;
1408 * Will currently always return null
1410 * @return null
1412 public function getFeedAppendQuery() {
1413 return $this->mFeedLinksAppendQuery;
1417 * Set whether the displayed content is related to the source of the
1418 * corresponding article on the wiki
1419 * Setting true will cause the change "article related" toggle to true
1421 * @param bool $newVal
1423 public function setArticleFlag( $newVal ) {
1424 $this->mIsArticle = $newVal;
1425 if ( $newVal ) {
1426 $this->mIsArticleRelated = $newVal;
1431 * Return whether the content displayed page is related to the source of
1432 * the corresponding article on the wiki
1434 * @return bool
1436 public function isArticle() {
1437 return $this->mIsArticle;
1441 * Set whether this page is related an article on the wiki
1442 * Setting false will cause the change of "article flag" toggle to false
1444 * @param bool $newVal
1446 public function setArticleRelated( $newVal ) {
1447 $this->mIsArticleRelated = $newVal;
1448 if ( !$newVal ) {
1449 $this->mIsArticle = false;
1454 * Return whether this page is related an article on the wiki
1456 * @return bool
1458 public function isArticleRelated() {
1459 return $this->mIsArticleRelated;
1463 * Set whether the standard copyright should be shown for the current page.
1465 * @param bool $hasCopyright
1467 public function setCopyright( $hasCopyright ) {
1468 $this->mHasCopyright = $hasCopyright;
1472 * Return whether the standard copyright should be shown for the current page.
1473 * By default, it is true for all articles but other pages
1474 * can signal it by using setCopyright( true ).
1476 * Used by SkinTemplate to decided whether to show the copyright.
1478 * @return bool
1480 public function showsCopyright() {
1481 return $this->isArticle() || $this->mHasCopyright;
1485 * Add new language links
1487 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1488 * (e.g. 'fr:Test page')
1490 public function addLanguageLinks( array $newLinkArray ) {
1491 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1495 * Reset the language links and add new language links
1497 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1498 * (e.g. 'fr:Test page')
1500 public function setLanguageLinks( array $newLinkArray ) {
1501 $this->mLanguageLinks = $newLinkArray;
1505 * Get the list of language links
1507 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1509 public function getLanguageLinks() {
1510 return $this->mLanguageLinks;
1514 * Add an array of categories, with names in the keys
1516 * @param array $categories Mapping category name => sort key
1518 public function addCategoryLinks( array $categories ) {
1519 if ( !$categories ) {
1520 return;
1523 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1525 # Set all the values to 'normal'.
1526 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1527 $pageData = [];
1529 # Mark hidden categories
1530 foreach ( $res as $row ) {
1531 if ( isset( $row->pp_value ) ) {
1532 $categories[$row->page_title] = 'hidden';
1534 // Page exists, cache results
1535 if ( isset( $row->page_id ) ) {
1536 $pageData[$row->page_title] = $row;
1540 # Add the remaining categories to the skin
1541 if ( $this->getHookRunner()->onOutputPageMakeCategoryLinks(
1542 $this, $categories, $this->mCategoryLinks )
1544 $services = MediaWikiServices::getInstance();
1545 $linkRenderer = $services->getLinkRenderer();
1546 $languageConverter = $services->getLanguageConverterFactory()
1547 ->getLanguageConverter( $services->getContentLanguage() );
1548 foreach ( $categories as $category => $type ) {
1549 // array keys will cast numeric category names to ints, so cast back to string
1550 $category = (string)$category;
1551 $origcategory = $category;
1552 if ( array_key_exists( $category, $pageData ) ) {
1553 $title = Title::newFromRow( $pageData[$category] );
1554 } else {
1555 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1557 if ( !$title ) {
1558 continue;
1560 $languageConverter->findVariantLink( $category, $title, true );
1562 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1563 continue;
1565 $text = $languageConverter->convertHtml( $title->getText() );
1566 $this->mCategories[$type][] = $title->getText();
1567 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1573 * @param array $categories
1574 * @return IResultWrapper
1576 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1577 # Add the links to a LinkBatch
1578 $arr = [ NS_CATEGORY => $categories ];
1579 $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
1580 $lb = $linkBatchFactory->newLinkBatch();
1581 $lb->setArray( $arr );
1583 # Fetch existence plus the hiddencat property
1584 $dbr = wfGetDB( DB_REPLICA );
1585 $fields = array_merge(
1586 LinkCache::getSelectFields(),
1587 [ 'pp_value' ]
1590 $res = $dbr->newSelectQueryBuilder()
1591 ->select( $fields )
1592 ->from( 'page' )
1593 ->leftJoin( 'page_props', null, [
1594 'pp_propname' => 'hiddencat',
1595 'pp_page = page_id',
1597 ->where( $lb->constructSet( 'page', $dbr ) )
1598 ->caller( __METHOD__ )
1599 ->fetchResultSet();
1601 # Add the results to the link cache
1602 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1603 $lb->addResultToCache( $linkCache, $res );
1605 return $res;
1609 * Reset the category links (but not the category list) and add $categories
1611 * @param array $categories Mapping category name => sort key
1613 public function setCategoryLinks( array $categories ) {
1614 $this->mCategoryLinks = [];
1615 $this->addCategoryLinks( $categories );
1619 * Get the list of category links, in a 2-D array with the following format:
1620 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1621 * hidden categories) and $link a HTML fragment with a link to the category
1622 * page
1624 * @return string[][]
1625 * @return-taint none
1627 public function getCategoryLinks() {
1628 return $this->mCategoryLinks;
1632 * Get the list of category names this page belongs to.
1634 * @param string $type The type of categories which should be returned. Possible values:
1635 * * all: all categories of all types
1636 * * hidden: only the hidden categories
1637 * * normal: all categories, except hidden categories
1638 * @return string[]
1640 public function getCategories( $type = 'all' ) {
1641 if ( $type === 'all' ) {
1642 $allCategories = [];
1643 foreach ( $this->mCategories as $categories ) {
1644 $allCategories = array_merge( $allCategories, $categories );
1646 return $allCategories;
1648 if ( !isset( $this->mCategories[$type] ) ) {
1649 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1651 return $this->mCategories[$type];
1655 * Add an array of indicators, with their identifiers as array
1656 * keys and HTML contents as values.
1658 * In case of duplicate keys, existing values are overwritten.
1660 * @note External code which calls this method should ensure that
1661 * any indicators sourced from parsed wikitext are wrapped with
1662 * the appropriate class; see note in ::getIndicators().
1664 * @param string[] $indicators
1665 * @since 1.25
1667 public function setIndicators( array $indicators ) {
1668 $this->mIndicators = $indicators + $this->mIndicators;
1669 // Keep ordered by key
1670 ksort( $this->mIndicators );
1674 * Get the indicators associated with this page.
1676 * The array will be internally ordered by item keys.
1678 * @return string[] Keys: identifiers, values: HTML contents
1679 * @since 1.25
1681 public function getIndicators(): array {
1682 // Note that some -- but not all -- indicators will be wrapped
1683 // with a class appropriate for user-generated wikitext content
1684 // (usually .mw-parser-output). The exceptions would be an
1685 // indicator added via ::addHelpLink() below, which adds content
1686 // which don't come from the parser and is not user-generated;
1687 // and any indicators added by extensions which may call
1688 // OutputPage::setIndicators() directly. In the latter case the
1689 // caller is responsible for wrapping any parser-generated
1690 // indicators.
1691 return $this->mIndicators;
1695 * Adds help link with an icon via page indicators.
1696 * Link target can be overridden by a local message containing a wikilink:
1697 * the message key is: lowercase action or special page name + '-helppage'.
1698 * @param string $to Target MediaWiki.org page title or encoded URL.
1699 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MediaWiki.org.
1700 * @since 1.25
1702 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1703 $this->addModuleStyles( 'mediawiki.helplink' );
1704 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1706 if ( $overrideBaseUrl ) {
1707 $helpUrl = $to;
1708 } else {
1709 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1710 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1713 $link = Html::rawElement(
1714 'a',
1716 'href' => $helpUrl,
1717 'target' => '_blank',
1718 'class' => 'mw-helplink',
1720 $text
1723 // See note in ::getIndicators() above -- unlike wikitext-generated
1724 // indicators which come from ParserOutput, this indicator will not
1725 // be wrapped.
1726 $this->setIndicators( [ 'mw-helplink' => $link ] );
1730 * Do not allow scripts which can be modified by wiki users to load on this page;
1731 * only allow scripts bundled with, or generated by, the software.
1732 * Site-wide styles are controlled by a config setting, since they can be
1733 * used to create a custom skin/theme, but not user-specific ones.
1735 * @todo this should be given a more accurate name
1737 public function disallowUserJs() {
1738 $this->reduceAllowedModules(
1739 RL\Module::TYPE_SCRIPTS,
1740 RL\Module::ORIGIN_CORE_INDIVIDUAL
1743 // Site-wide styles are controlled by a config setting, see T73621
1744 // for background on why. User styles are never allowed.
1745 if ( $this->getConfig()->get( MainConfigNames::AllowSiteCSSOnRestrictedPages ) ) {
1746 $styleOrigin = RL\Module::ORIGIN_USER_SITEWIDE;
1747 } else {
1748 $styleOrigin = RL\Module::ORIGIN_CORE_INDIVIDUAL;
1750 $this->reduceAllowedModules(
1751 RL\Module::TYPE_STYLES,
1752 $styleOrigin
1757 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1758 * @see RL\Module::$origin
1759 * @param string $type RL\Module TYPE_ constant
1760 * @return int Module ORIGIN_ class constant
1762 public function getAllowedModules( $type ) {
1763 if ( $type == RL\Module::TYPE_COMBINED ) {
1764 return min( array_values( $this->mAllowedModules ) );
1765 } else {
1766 return $this->mAllowedModules[$type] ?? RL\Module::ORIGIN_ALL;
1771 * Limit the highest level of CSS/JS untrustworthiness allowed.
1773 * If passed the same or a higher level than the current level of untrustworthiness set, the
1774 * level will remain unchanged.
1776 * @param string $type
1777 * @param int $level RL\Module class constant
1779 public function reduceAllowedModules( $type, $level ) {
1780 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1784 * Prepend $text to the body HTML
1786 * @param string $text HTML
1788 public function prependHTML( $text ) {
1789 $this->mBodytext = $text . $this->mBodytext;
1793 * Append $text to the body HTML
1795 * @param string $text HTML
1797 public function addHTML( $text ) {
1798 $this->mBodytext .= $text;
1802 * Shortcut for adding an Html::element via addHTML.
1804 * @since 1.19
1806 * @param string $element
1807 * @param array $attribs
1808 * @param string $contents
1810 public function addElement( $element, array $attribs = [], $contents = '' ) {
1811 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1815 * Clear the body HTML
1817 public function clearHTML() {
1818 $this->mBodytext = '';
1822 * Get the body HTML
1824 * @return string HTML
1826 public function getHTML() {
1827 return $this->mBodytext;
1831 * Get/set the ParserOptions object to use for wikitext parsing
1833 * @return ParserOptions
1835 public function parserOptions() {
1836 if ( !$this->mParserOptions ) {
1837 if ( !$this->getUser()->isSafeToLoad() ) {
1838 // Context user isn't unstubbable yet, so don't try to get a
1839 // ParserOptions for it. And don't cache this ParserOptions
1840 // either.
1841 $po = ParserOptions::newFromAnon();
1842 $po->setAllowUnsafeRawHtml( false );
1843 return $po;
1846 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1847 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1850 return $this->mParserOptions;
1854 * Set the revision ID which will be seen by the wiki text parser
1855 * for things such as embedded {{REVISIONID}} variable use.
1857 * @param int|null $revid A positive integer, or null
1858 * @return mixed Previous value
1860 public function setRevisionId( $revid ) {
1861 $val = $revid === null ? null : intval( $revid );
1862 return wfSetVar( $this->mRevisionId, $val, true );
1866 * Get the displayed revision ID
1868 * @return int|null
1870 public function getRevisionId() {
1871 return $this->mRevisionId;
1875 * Set whether the revision displayed (as set in ::setRevisionId())
1876 * is the latest revision of the page.
1878 * @param bool $isCurrent
1880 public function setRevisionIsCurrent( bool $isCurrent ): void {
1881 $this->mRevisionIsCurrent = $isCurrent;
1885 * Whether the revision displayed is the latest revision of the page
1887 * @since 1.34
1888 * @return bool
1890 public function isRevisionCurrent(): bool {
1891 return $this->mRevisionId == 0 || (
1892 $this->mRevisionIsCurrent ?? (
1893 $this->mRevisionId == $this->getTitle()->getLatestRevID()
1899 * Set the timestamp of the revision which will be displayed. This is used
1900 * to avoid a extra DB call in Skin::lastModified().
1902 * @param string|null $timestamp
1903 * @return mixed Previous value
1905 public function setRevisionTimestamp( $timestamp ) {
1906 return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
1910 * Get the timestamp of displayed revision.
1911 * This will be null if not filled by setRevisionTimestamp().
1913 * @return string|null
1915 public function getRevisionTimestamp() {
1916 return $this->mRevisionTimestamp;
1920 * Set the displayed file version
1922 * @param File|null $file
1923 * @return mixed Previous value
1925 public function setFileVersion( $file ) {
1926 $val = null;
1927 if ( $file instanceof File && $file->exists() ) {
1928 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1930 return wfSetVar( $this->mFileVersion, $val, true );
1934 * Get the displayed file version
1936 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1938 public function getFileVersion() {
1939 return $this->mFileVersion;
1943 * Get the templates used on this page
1945 * @return array<int,array<string,int>> (namespace => dbKey => revId)
1946 * @since 1.18
1948 public function getTemplateIds() {
1949 return $this->mTemplateIds;
1953 * Get the files used on this page
1955 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1956 * @since 1.18
1958 public function getFileSearchOptions() {
1959 return $this->mImageTimeKeys;
1963 * Convert wikitext *in the user interface language* to HTML and
1964 * add it to the buffer. The result will not be
1965 * language-converted, as user interface messages are already
1966 * localized into a specific variant. Assumes that the current
1967 * page title will be used if optional $title is not
1968 * provided. Output will be tidy.
1970 * @param string $text Wikitext in the user interface language
1971 * @param bool $linestart Is this the start of a line? (Defaults to true)
1972 * @param PageReference|null $title Optional title to use; default of `null`
1973 * means use current page title.
1974 * @throws MWException if $title is not provided and OutputPage::getTitle()
1975 * is null
1976 * @since 1.32
1978 public function addWikiTextAsInterface(
1979 $text, $linestart = true, PageReference $title = null
1981 $title ??= $this->getTitle();
1982 if ( !$title ) {
1983 throw new MWException( 'Title is null' );
1985 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1989 * Convert wikitext *in the user interface language* to HTML and
1990 * add it to the buffer with a `<div class="$wrapperClass">`
1991 * wrapper. The result will not be language-converted, as user
1992 * interface messages as already localized into a specific
1993 * variant. The $text will be parsed in start-of-line context.
1994 * Output will be tidy.
1996 * @param string $wrapperClass The class attribute value for the <div>
1997 * wrapper in the output HTML
1998 * @param string $text Wikitext in the user interface language
1999 * @since 1.32
2001 public function wrapWikiTextAsInterface(
2002 $wrapperClass, $text
2004 $this->addWikiTextTitleInternal(
2005 $text, $this->getTitle(),
2006 /*linestart*/true, /*interface*/true,
2007 $wrapperClass
2012 * Convert wikitext *in the page content language* to HTML and add
2013 * it to the buffer. The result with be language-converted to the
2014 * user's preferred variant. Assumes that the current page title
2015 * will be used if optional $title is not provided. Output will be
2016 * tidy.
2018 * @param string $text Wikitext in the page content language
2019 * @param bool $linestart Is this the start of a line? (Defaults to true)
2020 * @param PageReference|null $title Optional title to use; default of `null`
2021 * means use current page title.
2022 * @throws MWException if $title is not provided and OutputPage::getTitle()
2023 * is null
2024 * @since 1.32
2026 public function addWikiTextAsContent(
2027 $text, $linestart = true, PageReference $title = null
2029 $title ??= $this->getTitle();
2030 if ( !$title ) {
2031 throw new MWException( 'Title is null' );
2033 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
2037 * Add wikitext with a custom Title object.
2038 * Output is unwrapped.
2040 * @param string $text Wikitext
2041 * @param PageReference $title
2042 * @param bool $linestart Is this the start of a line?@param
2043 * @param bool $interface Whether it is an interface message
2044 * (for example disables conversion)
2045 * @param string|null $wrapperClass if not empty, wraps the output in
2046 * a `<div class="$wrapperClass">`
2048 private function addWikiTextTitleInternal(
2049 $text, PageReference $title, $linestart, $interface, $wrapperClass = null
2051 $parserOutput = $this->parseInternal(
2052 $text, $title, $linestart, $interface
2055 $this->addParserOutput( $parserOutput, [
2056 'enableSectionEditLinks' => false,
2057 'wrapperDivClass' => $wrapperClass ?? '',
2058 ] );
2062 * Adds Table of Contents data to OutputPage from ParserOutput
2063 * @param TOCData $tocData
2064 * @internal For use by Article.php
2066 public function setTOCData( TOCData $tocData ) {
2067 $this->tocData = $tocData;
2071 * @internal For usage in Skin::getTOCData() only.
2072 * @return ?TOCData Table of Contents data, or
2073 * null if OutputPage::setTOCData() has not been called.
2075 public function getTOCData(): ?TOCData {
2076 return $this->tocData;
2080 * @internal Will be replaced by direct access to
2081 * ParserOutput::getOutputFlag()
2082 * @param string $name A flag name from ParserOutputFlags
2083 * @return bool
2085 public function getOutputFlag( string $name ): bool {
2086 return isset( $this->mOutputFlags[$name] );
2090 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
2091 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
2092 * and so on. It does *not* include section information.
2094 * @since 1.24
2095 * @param ParserOutput $parserOutput
2097 public function addParserOutputMetadata( ParserOutput $parserOutput ) {
2098 // T301020 This should eventually use the standard "merge ParserOutput"
2099 // function between $parserOutput and $this->metadata.
2100 $this->mLanguageLinks =
2101 array_merge( $this->mLanguageLinks, $parserOutput->getLanguageLinks() );
2102 $this->addCategoryLinks( $parserOutput->getCategories() );
2104 // Parser-generated indicators get wrapped like other parser output.
2105 $wrapClass = $parserOutput->getWrapperDivClass();
2106 $result = [];
2107 foreach ( $parserOutput->getIndicators() as $name => $html ) {
2108 if ( $html !== '' && $wrapClass !== '' ) {
2109 $html = Html::rawElement( 'div', [ 'class' => $wrapClass ], $html );
2111 $result[$name] = $html;
2113 $this->setIndicators( $result );
2115 $tocData = $parserOutput->getTOCData();
2116 // Do not override existing TOC data if the new one is empty (T307256#8817705)
2117 // TODO: Invent a way to merge TOCs from multiple outputs (T327429)
2118 if ( $tocData !== null && ( $this->tocData === null || count( $tocData->getSections() ) > 0 ) ) {
2119 $this->setTOCData( $tocData );
2122 // FIXME: Best practice is for OutputPage to be an accumulator, as
2123 // addParserOutputMetadata() may be called multiple times, but the
2124 // following lines overwrite any previous data. These should
2125 // be migrated to an injection pattern. (T301020, T300979)
2126 // (Note that OutputPage::getOutputFlag() also contains this
2127 // information, with flags from each $parserOutput all OR'ed together.)
2128 $this->mNewSectionLink = $parserOutput->getNewSection();
2129 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
2130 $this->mNoGallery = $parserOutput->getNoGallery();
2132 if ( !$parserOutput->isCacheable() ) {
2133 $this->disableClientCache();
2135 $this->addHeadItems( $parserOutput->getHeadItems() );
2136 $this->addModules( $parserOutput->getModules() );
2137 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2138 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2139 $this->mPreventClickjacking = $this->mPreventClickjacking
2140 || $parserOutput->getPreventClickjacking();
2141 $scriptSrcs = $parserOutput->getExtraCSPScriptSrcs();
2142 foreach ( $scriptSrcs as $src ) {
2143 $this->getCSP()->addScriptSrc( $src );
2145 $defaultSrcs = $parserOutput->getExtraCSPDefaultSrcs();
2146 foreach ( $defaultSrcs as $src ) {
2147 $this->getCSP()->addDefaultSrc( $src );
2149 $styleSrcs = $parserOutput->getExtraCSPStyleSrcs();
2150 foreach ( $styleSrcs as $src ) {
2151 $this->getCSP()->addStyleSrc( $src );
2154 // If $wgImagePreconnect is true, and if the output contains images, give the user-agent
2155 // a hint about a remote hosts from which images may be served. Launched in T123582.
2156 if ( $this->getConfig()->get( MainConfigNames::ImagePreconnect ) && count( $parserOutput->getImages() ) ) {
2157 $preconnect = [];
2158 // Optimization: Instead of processing each image, assume that wikis either serve both
2159 // foreign and local from the same remote hostname (e.g. public wikis at WMF), or that
2160 // foreign images are common enough to be worth the preconnect (e.g. private wikis).
2161 $repoGroup = MediaWikiServices::getInstance()->getRepoGroup();
2162 $repoGroup->forEachForeignRepo( static function ( $repo ) use ( &$preconnect ) {
2163 $preconnect[] = $repo->getZoneUrl( 'thumb' );
2164 } );
2165 // Consider both foreign and local repos. While LocalRepo by default uses a relative
2166 // path on the same domain, wiki farms may configure it to use a dedicated hostname.
2167 $preconnect[] = $repoGroup->getLocalRepo()->getZoneUrl( 'thumb' );
2168 foreach ( $preconnect as $url ) {
2169 $host = parse_url( $url, PHP_URL_HOST );
2170 // It is expected that file URLs are often path-only, without hostname (T317329).
2171 if ( $host ) {
2172 $this->addLink( [ 'rel' => 'preconnect', 'href' => '//' . $host ] );
2173 break;
2178 // Template versioning...
2179 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
2180 if ( isset( $this->mTemplateIds[$ns] ) ) {
2181 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
2182 } else {
2183 $this->mTemplateIds[$ns] = $dbks;
2186 // File versioning...
2187 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
2188 $this->mImageTimeKeys[$dbk] = $data;
2191 // Hooks registered in the object
2192 // Deprecated! See T292321; should be done in the OutputPageParserOutput
2193 // hook instead.
2194 $parserOutputHooks = $this->getConfig()->get( MainConfigNames::ParserOutputHooks );
2195 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
2196 [ $hookName, $data ] = $hookInfo;
2197 if ( isset( $parserOutputHooks[$hookName] ) ) {
2198 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
2202 // Enable OOUI if requested via ParserOutput
2203 if ( $parserOutput->getEnableOOUI() ) {
2204 $this->enableOOUI();
2207 // Include parser limit report
2208 // FIXME: This should append, rather than overwrite, or else this
2209 // data should be injected into the OutputPage like is done for the
2210 // other page-level things (like OutputPage::setTOCData()).
2211 if ( !$this->limitReportJSData ) {
2212 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
2215 // Link flags are ignored for now, but may in the future be
2216 // used to mark individual language links.
2217 $linkFlags = [];
2218 $this->getHookRunner()->onLanguageLinks( $this->getTitle(), $this->mLanguageLinks, $linkFlags );
2220 $this->getHookRunner()->onOutputPageParserOutput( $this, $parserOutput );
2222 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2223 // so that extensions may modify ParserOutput to toggle TOC.
2224 // This cannot be moved to addParserOutputText because that is not
2225 // called by EditPage for Preview.
2227 // T294950/T293513: ParserOutput::getTOCHTML() has been
2228 // replaced by ParserOutput::getTOCData(), and
2229 // ParserOutputFlags::SHOW_TOC is used to indicate whether the TOC
2230 // should be shown (or hidden) in the output.
2231 $this->mEnableTOC = $this->mEnableTOC ||
2232 $parserOutput->getOutputFlag( ParserOutputFlags::SHOW_TOC );
2233 // But extensions used to be able to modify ParserOutput::setTOCHTML()
2234 // to toggle TOC in the OutputPageParserOutput hook; so for backward
2235 // compatibility check to see if that happened.
2236 $isTocPresent = $parserOutput->hasTOCHTML();
2237 if ( $isTocPresent && !$this->mEnableTOC ) {
2238 // Eventually we'll emit a deprecation message here (T293513)
2239 $this->mEnableTOC = true;
2241 // Uniform handling of all boolean flags: they are OR'ed together
2242 // (See ParserOutput::collectMetadata())
2243 $flags =
2244 array_flip( $parserOutput->getAllFlags() ) +
2245 array_flip( ParserOutputFlags::cases() );
2246 foreach ( $flags as $name => $ignore ) {
2247 if ( $parserOutput->getOutputFlag( $name ) ) {
2248 $this->mOutputFlags[$name] = true;
2254 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2255 * ParserOutput object, without any other metadata.
2257 * @since 1.24
2258 * @param ParserOutput $parserOutput
2259 * @param array $poOptions Options to ParserOutput::getText()
2261 public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
2262 $this->addParserOutputText( $parserOutput, $poOptions );
2264 $this->addModules( $parserOutput->getModules() );
2265 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2267 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2271 * Add the HTML associated with a ParserOutput object, without any metadata.
2273 * @since 1.24
2274 * @param ParserOutput $parserOutput
2275 * @param array $poOptions Options to ParserOutput::getText()
2277 public function addParserOutputText( ParserOutput $parserOutput, $poOptions = [] ) {
2278 // Add default options from the skin
2279 $skin = $this->getSkin();
2280 $skinOptions = $skin->getOptions();
2281 $poOptions += [
2282 'skin' => $skin,
2283 'injectTOC' => $skinOptions['toc'],
2285 $text = $parserOutput->getText( $poOptions );
2286 $this->getHookRunner()->onOutputPageBeforeHTML( $this, $text );
2287 $this->addHTML( $text );
2291 * Add everything from a ParserOutput object.
2293 * @param ParserOutput $parserOutput
2294 * @param array $poOptions Options to ParserOutput::getText()
2296 public function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
2297 $this->addParserOutputMetadata( $parserOutput );
2298 $this->addParserOutputText( $parserOutput, $poOptions );
2302 * Add the output of a QuickTemplate to the output buffer
2304 * @param QuickTemplate &$template
2306 public function addTemplate( &$template ) {
2307 $this->addHTML( $template->getHTML() );
2311 * Parse wikitext *in the page content language* and return the HTML.
2312 * The result will be language-converted to the user's preferred variant.
2313 * Output will be tidy.
2315 * @param string $text Wikitext in the page content language
2316 * @param bool $linestart Is this the start of a line? (Defaults to true)
2317 * @throws MWException
2318 * @return string HTML
2319 * @since 1.32
2321 public function parseAsContent( $text, $linestart = true ) {
2322 return $this->parseInternal(
2323 $text, $this->getTitle(), $linestart, /*interface*/false
2324 )->getText( [
2325 'allowTOC' => false,
2326 'enableSectionEditLinks' => false,
2327 'wrapperDivClass' => '',
2328 'userLang' => $this->getContext()->getLanguage(),
2329 ] );
2333 * Parse wikitext *in the user interface language* and return the HTML.
2334 * The result will not be language-converted, as user interface messages
2335 * are already localized into a specific variant.
2336 * Output will be tidy.
2338 * @param string $text Wikitext in the user interface language
2339 * @param bool $linestart Is this the start of a line? (Defaults to true)
2340 * @throws MWException
2341 * @return string HTML
2342 * @since 1.32
2344 public function parseAsInterface( $text, $linestart = true ) {
2345 return $this->parseInternal(
2346 $text, $this->getTitle(), $linestart, /*interface*/true
2347 )->getText( [
2348 'allowTOC' => false,
2349 'enableSectionEditLinks' => false,
2350 'wrapperDivClass' => '',
2351 'userLang' => $this->getContext()->getLanguage(),
2352 ] );
2356 * Parse wikitext *in the user interface language*, strip
2357 * paragraph wrapper, and return the HTML.
2358 * The result will not be language-converted, as user interface messages
2359 * are already localized into a specific variant.
2360 * Output will be tidy. Outer paragraph wrapper will only be stripped
2361 * if the result is a single paragraph.
2363 * @param string $text Wikitext in the user interface language
2364 * @param bool $linestart Is this the start of a line? (Defaults to true)
2365 * @throws MWException
2366 * @return string HTML
2367 * @since 1.32
2369 public function parseInlineAsInterface( $text, $linestart = true ) {
2370 return Parser::stripOuterParagraph(
2371 $this->parseAsInterface( $text, $linestart )
2376 * Parse wikitext and return the HTML (internal implementation helper)
2378 * @param string $text
2379 * @param PageReference $title The title to use
2380 * @param bool $linestart Is this the start of a line?
2381 * @param bool $interface Use interface language (instead of content language) while parsing
2382 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2383 * LanguageConverter.
2384 * @throws MWException
2385 * @return ParserOutput
2387 private function parseInternal( $text, $title, $linestart, $interface ) {
2388 if ( $title === null ) {
2389 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
2392 $popts = $this->parserOptions();
2394 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2396 $parserOutput = MediaWikiServices::getInstance()->getParserFactory()->getInstance()
2397 ->parse(
2398 $text, $title, $popts,
2399 $linestart, true, $this->mRevisionId
2402 $popts->setInterfaceMessage( $oldInterface );
2404 return $parserOutput;
2408 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2410 * @param int $maxage Maximum cache time on the CDN, in seconds.
2412 public function setCdnMaxage( $maxage ) {
2413 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2417 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2418 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2419 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2420 * $maxage.
2422 * @param int $maxage Maximum cache time on the CDN, in seconds
2423 * @since 1.27
2425 public function lowerCdnMaxage( $maxage ) {
2426 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2427 $this->setCdnMaxage( $this->mCdnMaxage );
2431 * Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
2433 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2434 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2435 * TTL is 90% of the age of the object, subject to the min and max.
2437 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2438 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2439 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2440 * @since 1.28
2442 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2443 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2444 $maxTTL = $maxTTL ?: $this->getConfig()->get( MainConfigNames::CdnMaxAge );
2446 if ( $mtime === null || $mtime === false ) {
2447 return; // entity does not exist
2450 $age = MWTimestamp::time() - (int)wfTimestamp( TS_UNIX, $mtime );
2451 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2452 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2454 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2458 * Do not send nocache headers
2460 public function enableClientCache(): void {
2461 $this->mEnableClientCache = true;
2465 * Force the page to send nocache headers
2466 * @since 1.38
2468 public function disableClientCache(): void {
2469 $this->mEnableClientCache = false;
2473 * Whether the output might become publicly cached.
2475 * @since 1.34
2476 * @return bool
2478 public function couldBePublicCached() {
2479 if ( !$this->cacheIsFinal ) {
2480 // - The entry point handles its own caching and/or doesn't use OutputPage.
2481 // (such as load.php, or MediaWiki\Rest\EntryPoint).
2483 // - Or, we haven't finished processing the main part of the request yet
2484 // (e.g. Action::show, SpecialPage::execute), and the state may still
2485 // change via enableClientCache().
2486 return true;
2488 // e.g. various error-type pages disable all client caching
2489 return $this->mEnableClientCache;
2493 * Set the expectation that cache control will not change after this point.
2495 * This should be called after the main processing logic has completed
2496 * (e.g. Action::show or SpecialPage::execute), but may be called
2497 * before Skin output has started (OutputPage::output).
2499 * @since 1.34
2501 public function considerCacheSettingsFinal() {
2502 $this->cacheIsFinal = true;
2506 * Get the list of cookie names that will influence the cache
2508 * @return array
2510 public function getCacheVaryCookies() {
2511 if ( self::$cacheVaryCookies === null ) {
2512 $config = $this->getConfig();
2513 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2514 SessionManager::singleton()->getVaryCookies(),
2516 'forceHTTPS',
2518 $config->get( MainConfigNames::CacheVaryCookies )
2519 ) ) );
2520 $this->getHookRunner()->onGetCacheVaryCookies( $this, self::$cacheVaryCookies );
2522 return self::$cacheVaryCookies;
2526 * Check if the request has a cache-varying cookie header
2527 * If it does, it's very important that we don't allow public caching
2529 * @return bool
2531 public function haveCacheVaryCookies() {
2532 $request = $this->getRequest();
2533 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2534 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2535 wfDebug( __METHOD__ . ": found $cookieName" );
2536 return true;
2539 wfDebug( __METHOD__ . ": no cache-varying cookies found" );
2540 return false;
2544 * Add an HTTP header that will influence on the cache
2546 * @param string $header Header name
2547 * @param string[]|null $option Deprecated; formerly options for the
2548 * Key header, deprecated in 1.32 and removed in 1.34. See
2549 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2550 * for the list of formerly-valid options.
2552 public function addVaryHeader( $header, array $option = null ) {
2553 if ( $option !== null && count( $option ) > 0 ) {
2554 wfDeprecatedMsg(
2555 'The $option parameter to addVaryHeader is ignored since MediaWiki 1.34',
2556 '1.34' );
2558 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2559 $this->mVaryHeader[$header] = null;
2564 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2565 * such as Accept-Encoding or Cookie
2567 * @return string
2569 public function getVaryHeader() {
2570 // If we vary on cookies, let's make sure it's always included here too.
2571 if ( $this->getCacheVaryCookies() ) {
2572 $this->addVaryHeader( 'Cookie' );
2575 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2576 $this->addVaryHeader( $header, $options );
2578 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2582 * Add an HTTP Link: header
2584 * @param string $header Header value
2586 public function addLinkHeader( $header ) {
2587 $this->mLinkHeader[] = $header;
2591 * Return a Link: header. Based on the values of $mLinkHeader.
2593 * @return string|false
2595 public function getLinkHeader() {
2596 if ( !$this->mLinkHeader ) {
2597 return false;
2600 return 'Link: ' . implode( ',', $this->mLinkHeader );
2604 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2606 * For example:
2607 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2608 * /w/index.php?title=Main_page&variant=zh-cn will not.
2610 private function addAcceptLanguage() {
2611 $title = $this->getTitle();
2612 if ( !$title instanceof Title ) {
2613 return;
2616 $languageConverter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
2617 ->getLanguageConverter( $title->getPageLanguage() );
2618 if ( !$this->getRequest()->getCheck( 'variant' ) && $languageConverter->hasVariants() ) {
2619 $this->addVaryHeader( 'Accept-Language' );
2624 * Set a flag which will cause an X-Frame-Options header appropriate for
2625 * edit pages to be sent. The header value is controlled by
2626 * $wgEditPageFrameOptions.
2628 * This is the default for special pages. If you display a CSRF-protected
2629 * form on an ordinary view page, then you need to call this function.
2631 * @param bool $enable
2632 * @deprecated since 1.38, use ::setPreventClickjacking( true )
2634 public function preventClickjacking( $enable = true ) {
2635 $this->mPreventClickjacking = $enable;
2639 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2640 * This can be called from pages which do not contain any CSRF-protected
2641 * HTML form.
2643 * @deprecated since 1.38, use ::setPreventClickjacking( false )
2645 public function allowClickjacking() {
2646 $this->mPreventClickjacking = false;
2650 * Set the prevent-clickjacking flag.
2652 * If true, will cause an X-Frame-Options header appropriate for
2653 * edit pages to be sent. The header value is controlled by
2654 * $wgEditPageFrameOptions. This is the default for special
2655 * pages. If you display a CSRF-protected form on an ordinary view
2656 * page, then you need to call this function.
2658 * Setting this flag to false will turn off frame-breaking. This
2659 * can be called from pages which do not contain any
2660 * CSRF-protected HTML form.
2662 * @param bool $enable If true, will cause an X-Frame-Options header
2663 * appropriate for edit pages to be sent.
2665 * @since 1.38
2667 public function setPreventClickjacking( bool $enable ) {
2668 $this->mPreventClickjacking = $enable;
2672 * Get the prevent-clickjacking flag
2674 * @since 1.24
2675 * @return bool
2677 public function getPreventClickjacking() {
2678 return $this->mPreventClickjacking;
2682 * Get the X-Frame-Options header value (without the name part), or false
2683 * if there isn't one. This is used by Skin to determine whether to enable
2684 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2686 * @return string|false
2688 public function getFrameOptions() {
2689 $config = $this->getConfig();
2690 if ( $config->get( MainConfigNames::BreakFrames ) ) {
2691 return 'DENY';
2692 } elseif ( $this->mPreventClickjacking && $config->get( MainConfigNames::EditPageFrameOptions ) ) {
2693 return $config->get( MainConfigNames::EditPageFrameOptions );
2695 return false;
2698 private function getReportTo() {
2699 $config = $this->getConfig();
2701 $expiry = $config->get( MainConfigNames::ReportToExpiry );
2703 if ( !$expiry ) {
2704 return false;
2707 $endpoints = $config->get( MainConfigNames::ReportToEndpoints );
2709 if ( !$endpoints ) {
2710 return false;
2713 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2715 foreach ( $endpoints as $endpoint ) {
2716 $output['endpoints'][] = [ 'url' => $endpoint ];
2719 return json_encode( $output, JSON_UNESCAPED_SLASHES );
2722 private function getFeaturePolicyReportOnly() {
2723 $config = $this->getConfig();
2725 $features = $config->get( MainConfigNames::FeaturePolicyReportOnly );
2726 return implode( ';', $features );
2730 * Send cache control HTTP headers
2732 public function sendCacheControl() {
2733 $response = $this->getRequest()->response();
2734 $config = $this->getConfig();
2736 $this->addVaryHeader( 'Cookie' );
2737 $this->addAcceptLanguage();
2739 # don't serve compressed data to clients who can't handle it
2740 # maintain different caches for logged-in users and non-logged in ones
2741 $response->header( $this->getVaryHeader() );
2743 if ( $this->mEnableClientCache ) {
2744 if ( !$config->get( MainConfigNames::UseCdn ) ) {
2745 $privateReason = 'config';
2746 } elseif ( $response->hasCookies() ) {
2747 $privateReason = 'set-cookies';
2748 // The client might use methods other than cookies to appear logged-in.
2749 // E.g. HTTP headers, or query parameter tokens, OAuth, etc.
2750 } elseif ( SessionManager::getGlobalSession()->isPersistent() ) {
2751 $privateReason = 'session';
2752 } elseif ( $this->isPrintable() ) {
2753 $privateReason = 'printable';
2754 } elseif ( $this->mCdnMaxage == 0 ) {
2755 $privateReason = 'no-maxage';
2756 } elseif ( $this->haveCacheVaryCookies() ) {
2757 $privateReason = 'cache-vary-cookies';
2758 } else {
2759 $privateReason = false;
2762 if ( $privateReason === false ) {
2763 # We'll purge the proxy cache for anons explicitly, but require end user agents
2764 # to revalidate against the proxy on each visit.
2765 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2766 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2767 wfDebug( __METHOD__ .
2768 ": local proxy caching; {$this->mLastModified} **", 'private' );
2769 # start with a shorter timeout for initial testing
2770 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2771 $response->header( "Cache-Control: " .
2772 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2773 } else {
2774 # We do want clients to cache if they can, but they *must* check for updates
2775 # on revisiting the page.
2776 wfDebug( __METHOD__ . ": private caching ($privateReason); {$this->mLastModified} **", 'private' );
2778 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2779 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2781 if ( $this->mLastModified ) {
2782 $response->header( "Last-Modified: {$this->mLastModified}" );
2784 } else {
2785 wfDebug( __METHOD__ . ": no caching **", 'private' );
2787 # In general, the absence of a last modified header should be enough to prevent
2788 # the client from using its cache. We send a few other things just to make sure.
2789 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2790 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2791 $response->header( 'Pragma: no-cache' );
2796 * Transfer styles and JavaScript modules from skin.
2798 * @param Skin $sk to load modules for
2800 public function loadSkinModules( $sk ) {
2801 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2802 if ( $group === 'styles' ) {
2803 foreach ( $modules as $moduleMembers ) {
2804 $this->addModuleStyles( $moduleMembers );
2806 } else {
2807 $this->addModules( $modules );
2813 * Finally, all the text has been munged and accumulated into
2814 * the object, let's actually output it:
2816 * @param bool $return Set to true to get the result as a string rather than sending it
2817 * @return string|null
2818 * @throws Exception
2819 * @throws FatalError
2820 * @throws MWException
2822 public function output( $return = false ) {
2823 if ( $this->mDoNothing ) {
2824 return $return ? '' : null;
2827 $response = $this->getRequest()->response();
2828 $config = $this->getConfig();
2830 if ( $this->mRedirect != '' ) {
2831 $services = MediaWikiServices::getInstance();
2832 # Standards require redirect URLs to be absolute
2833 $this->mRedirect = (string)$services->getUrlUtils()->expand( $this->mRedirect, PROTO_CURRENT );
2835 $redirect = $this->mRedirect;
2836 $code = $this->mRedirectCode;
2837 $content = '';
2839 if ( $this->getHookRunner()->onBeforePageRedirect( $this, $redirect, $code ) ) {
2840 if ( $code == '301' || $code == '303' ) {
2841 if ( !$config->get( MainConfigNames::DebugRedirects ) ) {
2842 $response->statusHeader( (int)$code );
2844 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2846 if ( $config->get( MainConfigNames::VaryOnXFP ) ) {
2847 $this->addVaryHeader( 'X-Forwarded-Proto' );
2849 $this->sendCacheControl();
2851 $response->header( 'Content-Type: text/html; charset=UTF-8' );
2852 if ( $config->get( MainConfigNames::DebugRedirects ) ) {
2853 $url = htmlspecialchars( $redirect );
2854 $content = "<!DOCTYPE html>\n<html>\n<head>\n"
2855 . "<title>Redirect</title>\n</head>\n<body>\n"
2856 . "<p>Location: <a href=\"$url\">$url</a></p>\n"
2857 . "</body>\n</html>\n";
2859 if ( !$return ) {
2860 print $content;
2863 } else {
2864 $response->header( 'Location: ' . $redirect );
2868 return $return ? $content : null;
2869 } elseif ( $this->mStatusCode ) {
2870 $response->statusHeader( $this->mStatusCode );
2873 # Buffer output; final headers may depend on later processing
2874 ob_start();
2876 $response->header( 'Content-type: ' . $config->get( MainConfigNames::MimeType ) . '; charset=UTF-8' );
2877 $response->header( 'Content-language: ' .
2878 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2880 $linkHeader = $this->getLinkHeader();
2881 if ( $linkHeader ) {
2882 $response->header( $linkHeader );
2885 // Prevent framing, if requested
2886 $frameOptions = $this->getFrameOptions();
2887 if ( $frameOptions ) {
2888 $response->header( "X-Frame-Options: $frameOptions" );
2891 // Get the Origin-Trial header values. This is used to enable Chrome Origin
2892 // Trials: https://github.com/GoogleChrome/OriginTrials
2893 $originTrials = $config->get( MainConfigNames::OriginTrials );
2894 foreach ( $originTrials as $originTrial ) {
2895 $response->header( "Origin-Trial: $originTrial", false );
2898 $reportTo = $this->getReportTo();
2899 if ( $reportTo ) {
2900 $response->header( "Report-To: $reportTo" );
2903 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2904 if ( $featurePolicyReportOnly ) {
2905 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2908 if ( $this->mArticleBodyOnly ) {
2909 $this->CSP->sendHeaders();
2910 echo $this->mBodytext;
2911 } else {
2912 // Enable safe mode if requested (T152169)
2913 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2914 $this->disallowUserJs();
2917 $sk = $this->getSkin();
2918 $this->loadSkinModules( $sk );
2920 MWDebug::addModules( $this );
2922 // Hook that allows last minute changes to the output page, e.g.
2923 // adding of CSS or Javascript by extensions, adding CSP sources.
2924 $this->getHookRunner()->onBeforePageDisplay( $this, $sk );
2926 $this->CSP->sendHeaders();
2928 try {
2929 $sk->outputPage();
2930 } catch ( Exception $e ) {
2931 ob_end_clean(); // bug T129657
2932 throw $e;
2936 try {
2937 // This hook allows last minute changes to final overall output by modifying output buffer
2938 $this->getHookRunner()->onAfterFinalPageOutput( $this );
2939 } catch ( Exception $e ) {
2940 ob_end_clean(); // bug T129657
2941 throw $e;
2944 $this->sendCacheControl();
2946 if ( $return ) {
2947 return ob_get_clean();
2948 } else {
2949 ob_end_flush();
2950 return null;
2955 * Prepare this object to display an error page; disable caching and
2956 * indexing, clear the current text and redirect, set the page's title
2957 * and optionally a custom HTML title (content of the "<title>" tag).
2959 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2960 * @param string|Message|false $htmlTitle Will be passed directly to setHTMLTitle();
2961 * optional, if not passed the "<title>" attribute will be
2962 * based on $pageTitle
2964 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2965 $this->setPageTitle( $pageTitle );
2966 if ( $htmlTitle !== false ) {
2967 $this->setHTMLTitle( $htmlTitle );
2969 $this->setRobotPolicy( 'noindex,nofollow' );
2970 $this->setArticleRelated( false );
2971 $this->disableClientCache();
2972 $this->mRedirect = '';
2973 $this->clearSubtitle();
2974 $this->clearHTML();
2978 * Output a standard error page
2980 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2981 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2982 * showErrorPage( 'titlemsg', $messageObject );
2983 * showErrorPage( $titleMessageObject, $messageObject );
2985 * @param string|Message $title Message key (string) for page title, or a Message object
2986 * @param string|Message $msg Message key (string) for page text, or a Message object
2987 * @param array $params Message parameters; ignored if $msg is a Message object
2988 * @param PageReference|LinkTarget|string|null $returnto Page to show a return link to;
2989 * defaults to the 'returnto' URL parameter
2990 * @param string|null $returntoquery Query string for the return to link;
2991 * defaults to the 'returntoquery' URL parameter
2993 public function showErrorPage(
2994 $title, $msg, $params = [], $returnto = null, $returntoquery = null
2996 if ( !$title instanceof Message ) {
2997 $title = $this->msg( $title );
3000 $this->prepareErrorPage( $title );
3002 if ( $msg instanceof Message ) {
3003 if ( $params !== [] ) {
3004 trigger_error( 'Argument ignored: $params. The message parameters argument '
3005 . 'is discarded when the $msg argument is a Message object instead of '
3006 . 'a string.', E_USER_NOTICE );
3008 $this->addHTML( $msg->parseAsBlock() );
3009 } else {
3010 $this->addWikiMsgArray( $msg, $params );
3013 $this->returnToMain( null, $returnto, $returntoquery );
3017 * Output a standard permission error page
3019 * @param array $errors Error message keys or [key, param...] arrays
3020 * @param string|null $action Action that was denied or null if unknown
3022 public function showPermissionsErrorPage( array $errors, $action = null ) {
3023 $services = MediaWikiServices::getInstance();
3024 $groupPermissionsLookup = $services->getGroupPermissionsLookup();
3025 foreach ( $errors as $key => $error ) {
3026 $errors[$key] = (array)$error;
3029 // For some action (read, edit, create and upload), display a "login to do this action"
3030 // error if all of the following conditions are met:
3031 // 1. the user is not logged in
3032 // 2. the only error is insufficient permissions (i.e. no block or something else)
3033 // 3. the error can be avoided simply by logging in
3035 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
3036 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
3037 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
3038 && ( $groupPermissionsLookup->groupHasPermission( 'user', $action )
3039 || $groupPermissionsLookup->groupHasPermission( 'autoconfirmed', $action ) )
3041 $displayReturnto = null;
3043 # Due to T34276, if a user does not have read permissions,
3044 # $this->getTitle() will just give Special:Badtitle, which is
3045 # not especially useful as a returnto parameter. Use the title
3046 # from the request instead, if there was one.
3047 $request = $this->getRequest();
3048 $returnto = Title::newFromText( $request->getText( 'title' ) );
3049 if ( $action == 'edit' ) {
3050 $msg = 'whitelistedittext';
3051 $displayReturnto = $returnto;
3052 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
3053 $msg = 'nocreatetext';
3054 } elseif ( $action == 'upload' ) {
3055 $msg = 'uploadnologintext';
3056 } else { # Read
3057 $msg = 'loginreqpagetext';
3058 $displayReturnto = Title::newMainPage();
3061 $query = [];
3063 if ( $returnto ) {
3064 $query['returnto'] = $returnto->getPrefixedText();
3066 if ( !$request->wasPosted() ) {
3067 $returntoquery = $request->getValues();
3068 unset( $returntoquery['title'] );
3069 unset( $returntoquery['returnto'] );
3070 unset( $returntoquery['returntoquery'] );
3071 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
3075 $title = SpecialPage::getTitleFor( 'Userlogin' );
3076 $linkRenderer = $services->getLinkRenderer();
3077 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
3078 $loginLink = $linkRenderer->makeKnownLink(
3079 $title,
3080 $this->msg( 'loginreqlink' )->text(),
3082 $query
3085 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
3086 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
3088 # Don't return to a page the user can't read otherwise
3089 # we'll end up in a pointless loop
3090 if ( $displayReturnto && $this->getAuthority()->probablyCan( 'read', $displayReturnto ) ) {
3091 $this->returnToMain( null, $displayReturnto );
3093 } else {
3094 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
3095 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
3100 * Display an error page indicating that a given version of MediaWiki is
3101 * required to use it
3103 * @param mixed $version The version of MediaWiki needed to use the page
3105 public function versionRequired( $version ) {
3106 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
3108 $this->addWikiMsg( 'versionrequiredtext', $version );
3109 $this->returnToMain();
3113 * Format permission $status obtained from Authority for display.
3115 * @param PermissionStatus $status
3116 * @param string|null $action that was denied or null if unknown
3117 * @return string
3119 public function formatPermissionStatus( PermissionStatus $status, string $action = null ): string {
3120 if ( $status->isGood() ) {
3121 return '';
3123 return $this->formatPermissionsErrorMessage( $status->toLegacyErrorArray(), $action );
3127 * Format a list of error messages
3129 * @deprecated since 1.36. Use ::formatPermissionStatus instead
3130 * @param array $errors Array of arrays returned by PermissionManager::getPermissionErrors
3131 * @phan-param non-empty-array[] $errors
3132 * @param string|null $action Action that was denied or null if unknown
3133 * @return string The wikitext error-messages, formatted into a list.
3135 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
3136 if ( $action == null ) {
3137 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
3138 } else {
3139 $action_desc = $this->msg( "action-$action" )->plain();
3140 $text = $this->msg(
3141 'permissionserrorstext-withaction',
3142 count( $errors ),
3143 $action_desc
3144 )->plain() . "\n\n";
3147 if ( count( $errors ) > 1 ) {
3148 $text .= '<ul class="permissions-errors">' . "\n";
3150 foreach ( $errors as $error ) {
3151 $text .= '<li>';
3152 $text .= $this->msg( ...$error )->plain();
3153 $text .= "</li>\n";
3155 $text .= '</ul>';
3156 } else {
3157 $text .= "<div class=\"permissions-errors\">\n" .
3158 // @phan-suppress-next-line PhanParamTooFewUnpack Elements of $errors already annotated as non-empty
3159 $this->msg( ...reset( $errors ) )->plain() .
3160 "\n</div>";
3163 return $text;
3167 * Show a warning about replica DB lag
3169 * If the lag is higher than $wgDatabaseReplicaLagCritical seconds,
3170 * then the warning is a bit more obvious. If the lag is
3171 * lower than $wgDatabaseReplicaLagWarning, then no warning is shown.
3173 * @param int $lag Replica lag
3175 public function showLagWarning( $lag ) {
3176 $config = $this->getConfig();
3177 if ( $lag >= $config->get( MainConfigNames::DatabaseReplicaLagWarning ) ) {
3178 $lag = floor( $lag ); // floor to avoid nano seconds to display
3179 $message = $lag < $config->get( MainConfigNames::DatabaseReplicaLagCritical )
3180 ? 'lag-warn-normal'
3181 : 'lag-warn-high';
3182 // For grep: mw-lag-warn-normal, mw-lag-warn-high
3183 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
3184 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
3189 * Output an error page
3191 * @note FatalError exception class provides an alternative.
3192 * @param string $message Error to output. Must be escaped for HTML.
3194 public function showFatalError( $message ) {
3195 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
3197 $this->addHTML( $message );
3201 * Add a "return to" link pointing to a specified title
3203 * @param LinkTarget $title Title to link
3204 * @param array $query Query string parameters
3205 * @param string|null $text Text of the link (input is not escaped)
3206 * @param array $options Options array to pass to Linker
3208 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3209 $linkRenderer = MediaWikiServices::getInstance()
3210 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3211 $link = $this->msg( 'returnto' )->rawParams(
3212 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3213 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3217 * Add a "return to" link pointing to a specified title,
3218 * or the title indicated in the request, or else the main page
3220 * @param mixed|null $unused
3221 * @param PageReference|LinkTarget|string|null $returnto Page to return to
3222 * @param string|null $returntoquery Query string for the return to link
3224 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3225 $returnto ??= $this->getRequest()->getText( 'returnto' );
3227 $returntoquery ??= $this->getRequest()->getText( 'returntoquery' );
3229 if ( $returnto === '' ) {
3230 $returnto = Title::newMainPage();
3233 if ( is_object( $returnto ) ) {
3234 $linkTarget = TitleValue::castPageToLinkTarget( $returnto );
3235 } else {
3236 $linkTarget = Title::newFromText( $returnto );
3239 // We don't want people to return to external interwiki. That
3240 // might potentially be used as part of a phishing scheme
3241 if ( !is_object( $linkTarget ) || $linkTarget->isExternal() ) {
3242 $linkTarget = Title::newMainPage();
3245 $this->addReturnTo( $linkTarget, wfCgiToArray( $returntoquery ) );
3249 * Output a standard "wait for takeover" warning
3251 * This is useful for extensions which are hooking an action and
3252 * suppressing its normal output so it can be taken over with JS.
3254 * showPendingTakeover( 'url', 'pagetextmsg' );
3255 * showPendingTakeover( 'url', 'pagetextmsg', [ 'param1', 'param2' ] );
3256 * showPendingTakeover( 'url', $messageObject );
3258 * @param string $fallbackUrl URL to redirect to if the user doesn't have JavaScript
3259 * or ResourceLoader available; this should ideally be to a page that provides similar
3260 * functionality without requiring JavaScript
3261 * @param string|Message $msg Message key (string) for page text, or a Message object
3262 * @param string|string[]|MessageSpecifier $params Message parameters; ignored if $msg
3263 * is a Message object
3265 public function showPendingTakeover(
3266 $fallbackUrl, $msg, $params = []
3268 if ( $msg instanceof Message ) {
3269 if ( $params !== [] ) {
3270 trigger_error( 'Argument ignored: $params. The message parameters argument '
3271 . 'is discarded when the $msg argument is a Message object instead of '
3272 . 'a string.', E_USER_NOTICE );
3274 $this->addHTML( $msg->parseAsBlock() );
3275 } else {
3276 $this->addWikiMsgArray( $msg, $params );
3279 // Redirect if the user has no JS (<noscript>)
3280 $escapedUrl = htmlspecialchars( $fallbackUrl );
3281 $this->addHeadItem(
3282 'mw-noscript-fallback',
3283 // https://html.spec.whatwg.org/#attr-meta-http-equiv-refresh
3284 // means that if $fallbackUrl contains unencoded quotation marks
3285 // then this will behave confusingly, but shouldn't break the page
3286 "<noscript><meta http-equiv=\"refresh\" content=\"0; url=$escapedUrl\"></noscript>"
3288 // Redirect if the user has no ResourceLoader
3289 $this->addScript( Html::inlineScript(
3290 "(window.NORLQ=window.NORLQ||[]).push(" .
3291 "function(){" .
3292 "location.href=" . json_encode( $fallbackUrl ) . ";" .
3293 "}" .
3294 ");"
3295 ) );
3298 private function getRlClientContext() {
3299 if ( !$this->rlClientContext ) {
3300 $query = ResourceLoader::makeLoaderQuery(
3301 [], // modules; not relevant
3302 $this->getLanguage()->getCode(),
3303 $this->getSkin()->getSkinName(),
3304 $this->getUser()->isRegistered() ? $this->getUser()->getName() : null,
3305 null, // version; not relevant
3306 ResourceLoader::inDebugMode(),
3307 null, // only; not relevant
3308 $this->isPrintable()
3310 $this->rlClientContext = new RL\Context(
3311 $this->getResourceLoader(),
3312 new FauxRequest( $query )
3314 if ( $this->contentOverrideCallbacks ) {
3315 $this->rlClientContext = new RL\DerivativeContext( $this->rlClientContext );
3316 $this->rlClientContext->setContentOverrideCallback( function ( $title ) {
3317 foreach ( $this->contentOverrideCallbacks as $callback ) {
3318 $content = $callback( $title );
3319 if ( $content !== null ) {
3320 $text = ( $content instanceof TextContent ) ? $content->getText() : '';
3321 if ( strpos( $text, '</script>' ) !== false ) {
3322 // Proactively replace this so that we can display a message
3323 // to the user, instead of letting it go to Html::inlineScript(),
3324 // where it would be considered a server-side issue.
3325 $content = new JavaScriptContent(
3326 Xml::encodeJsCall( 'mw.log.error', [
3327 "Cannot preview $title due to script-closing tag."
3331 return $content;
3334 return null;
3335 } );
3338 return $this->rlClientContext;
3342 * Call this to freeze the module queue and JS config and create a formatter.
3344 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3345 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3346 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3347 * the module filters retroactively. Skins and extension hooks may also add modules until very
3348 * late in the request lifecycle.
3350 * @return RL\ClientHtml
3352 public function getRlClient() {
3353 if ( !$this->rlClient ) {
3354 $context = $this->getRlClientContext();
3355 $rl = $this->getResourceLoader();
3356 $this->addModules( [
3357 'user',
3358 'user.options',
3359 ] );
3360 $this->addModuleStyles( [
3361 'site.styles',
3362 'noscript',
3363 'user.styles',
3364 ] );
3366 // Prepare exempt modules for buildExemptModules()
3367 $exemptGroups = [
3368 RL\Module::GROUP_SITE => [],
3369 RL\Module::GROUP_NOSCRIPT => [],
3370 RL\Module::GROUP_PRIVATE => [],
3371 RL\Module::GROUP_USER => []
3373 $exemptStates = [];
3374 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3376 // Preload getTitleInfo for isKnownEmpty calls below and in RL\ClientHtml
3377 // Separate user-specific batch for improved cache-hit ratio.
3378 $userBatch = [ 'user.styles', 'user' ];
3379 $siteBatch = array_diff( $moduleStyles, $userBatch );
3380 $dbr = wfGetDB( DB_REPLICA );
3381 RL\WikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
3382 RL\WikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
3384 // Filter out modules handled by buildExemptModules()
3385 $moduleStyles = array_filter( $moduleStyles,
3386 static function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3387 $module = $rl->getModule( $name );
3388 if ( $module ) {
3389 $group = $module->getGroup();
3390 if ( $group !== null && isset( $exemptGroups[$group] ) ) {
3391 // The `noscript` module is excluded from the client
3392 // side registry, no need to set its state either.
3393 // But we still output it. See T291735
3394 if ( $group !== RL\Module::GROUP_NOSCRIPT ) {
3395 $exemptStates[$name] = 'ready';
3397 if ( !$module->isKnownEmpty( $context ) ) {
3398 // E.g. Don't output empty <styles>
3399 $exemptGroups[$group][] = $name;
3401 return false;
3404 return true;
3407 $this->rlExemptStyleModules = $exemptGroups;
3409 $config = $this->getConfig();
3410 $clientPrefEnabled = (
3411 $config->get( MainConfigNames::ResourceLoaderClientPreferences ) &&
3412 !$this->getUser()->isRegistered()
3414 $clientPrefCookiePrefix = $config->get( MainConfigNames::CookiePrefix );
3416 $rlClient = new RL\ClientHtml( $context, [
3417 'target' => $this->getTarget(),
3418 'nonce' => $this->CSP->getNonce(),
3419 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3420 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3421 // modules enqueued for loading on this page is filtered to just those.
3422 // However, to make sure we also apply the restriction to dynamic dependencies and
3423 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3424 // StartupModule so that the client-side registry will not contain any restricted
3425 // modules either. (T152169, T185303)
3426 'safemode' => ( $this->getAllowedModules( RL\Module::TYPE_COMBINED )
3427 <= RL\Module::ORIGIN_CORE_INDIVIDUAL
3428 ) ? '1' : null,
3429 'clientPrefEnabled' => $clientPrefEnabled,
3430 'clientPrefCookiePrefix' => $clientPrefCookiePrefix,
3431 ] );
3432 $rlClient->setConfig( $this->getJSVars( self::JS_VAR_EARLY ) );
3433 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3434 $rlClient->setModuleStyles( $moduleStyles );
3435 $rlClient->setExemptStates( $exemptStates );
3436 $this->rlClient = $rlClient;
3438 return $this->rlClient;
3442 * @param Skin $sk The given Skin
3443 * @param bool $includeStyle Unused
3444 * @return string The doctype, opening "<html>", and head element.
3446 public function headElement( Skin $sk, $includeStyle = true ) {
3447 $config = $this->getConfig();
3448 $userdir = $this->getLanguage()->getDir();
3449 $services = MediaWikiServices::getInstance();
3450 $sitedir = $services->getContentLanguage()->getDir();
3452 $pieces = [];
3453 $htmlAttribs = Sanitizer::mergeAttributes( Sanitizer::mergeAttributes(
3454 $this->getRlClient()->getDocumentAttributes(),
3455 $sk->getHtmlElementAttributes()
3456 ), [ 'class' => implode( ' ', $this->mAdditionalHtmlClasses ) ] );
3457 $pieces[] = Html::htmlHeader( $htmlAttribs );
3458 $pieces[] = Html::openElement( 'head' );
3460 if ( $this->getHTMLTitle() == '' ) {
3461 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3464 if ( !Html::isXmlMimeType( $config->get( MainConfigNames::MimeType ) ) ) {
3465 // Add <meta charset="UTF-8">
3466 // This should be before <title> since it defines the charset used by
3467 // text including the text inside <title>.
3468 // The spec recommends defining XHTML5's charset using the XML declaration
3469 // instead of meta.
3470 // Our XML declaration is output by Html::htmlHeader.
3471 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3472 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3473 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3476 $pieces[] = Html::element( 'title', [], $this->getHTMLTitle() );
3477 $pieces[] = $this->getRlClient()->getHeadHtml( $htmlAttribs['class'] ?? null );
3478 $pieces[] = $this->buildExemptModules();
3479 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3480 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3482 $pieces[] = Html::closeElement( 'head' );
3484 $skinOptions = $sk->getOptions();
3485 $bodyClasses = array_merge( $this->mAdditionalBodyClasses, $skinOptions['bodyClasses'] );
3486 $bodyClasses[] = 'mediawiki';
3488 # Classes for LTR/RTL directionality support
3489 $bodyClasses[] = $userdir;
3490 $bodyClasses[] = "sitedir-$sitedir";
3492 $underline = $services->getUserOptionsLookup()->getOption( $this->getUser(), 'underline' );
3493 if ( $underline < 2 ) {
3494 // The following classes can be used here:
3495 // * mw-underline-always
3496 // * mw-underline-never
3497 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3500 // Parser feature migration class
3501 // The idea is that this will eventually be removed, after the wikitext
3502 // which requires it is cleaned up.
3503 $bodyClasses[] = 'mw-hide-empty-elt';
3505 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3506 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3507 $bodyClasses[] =
3508 'action-' . Sanitizer::escapeClass( $this->getContext()->getActionName() );
3510 if ( $sk->isResponsive() ) {
3511 $bodyClasses[] = 'skin--responsive';
3514 $bodyAttrs = [];
3515 // While the implode() is not strictly needed, it's used for backwards compatibility
3516 // (this used to be built as a string and hooks likely still expect that).
3517 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3519 // Allow skins and extensions to add body attributes they need
3520 // Get ones from deprecated method
3521 if ( method_exists( $sk, 'addToBodyAttributes' ) ) {
3522 /** @phan-suppress-next-line PhanUndeclaredMethod */
3523 $sk->addToBodyAttributes( $this, $bodyAttrs );
3524 wfDeprecated( 'Skin::addToBodyAttributes method to add body attributes', '1.35' );
3527 // Then run the hook, the recommended way of adding body attributes now
3528 $this->getHookRunner()->onOutputPageBodyAttributes( $this, $sk, $bodyAttrs );
3530 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3532 return self::combineWrappedStrings( $pieces );
3536 * Get a ResourceLoader object associated with this OutputPage
3538 * @return ResourceLoader
3540 public function getResourceLoader() {
3541 if ( $this->mResourceLoader === null ) {
3542 // Lazy-initialise as needed
3543 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3545 return $this->mResourceLoader;
3549 * Explicitly load or embed modules on a page.
3551 * @param array|string $modules One or more module names
3552 * @param string $only RL\Module TYPE_ class constant
3553 * @param array $extraQuery [optional] Array with extra query parameters for the request
3554 * @return string|WrappedStringList HTML
3556 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3557 // Apply 'target' and 'origin' filters
3558 $modules = $this->filterModules( (array)$modules, null, $only );
3560 return RL\ClientHtml::makeLoad(
3561 $this->getRlClientContext(),
3562 $modules,
3563 $only,
3564 $extraQuery,
3565 $this->CSP->getNonce()
3570 * Combine WrappedString chunks and filter out empty ones
3572 * @param array $chunks
3573 * @return string|WrappedStringList HTML
3575 protected static function combineWrappedStrings( array $chunks ) {
3576 // Filter out empty values
3577 $chunks = array_filter( $chunks, 'strlen' );
3578 return WrappedString::join( "\n", $chunks );
3582 * JS stuff to put at the bottom of the `<body>`.
3583 * These are legacy scripts ($this->mScripts), and user JS.
3585 * @param string $extraHtml (only for use by this->tailElement(); will be removed in future)
3586 * @return string|WrappedStringList HTML
3588 public function getBottomScripts( $extraHtml = '' ) {
3589 // Keep the hook appendage separate to preserve WrappedString objects.
3590 // This enables BaseTemplate::getTrail() to merge them where possible.
3591 $this->getHookRunner()->onSkinAfterBottomScripts( $this->getSkin(), $extraHtml );
3593 $chunks = [];
3594 $chunks[] = $this->getRlClient()->getBodyHtml();
3596 // Legacy non-ResourceLoader scripts
3597 $chunks[] = $this->mScripts;
3599 // Keep hostname and backend time as the first variables for quick view-source access.
3600 // This other variables will form a very long inline blob.
3601 $vars = [];
3602 if ( $this->getConfig()->get( MainConfigNames::ShowHostnames ) ) {
3603 $vars['wgHostname'] = wfHostname();
3605 $elapsed = $this->getRequest()->getElapsedTime();
3606 // seconds to milliseconds
3607 $vars['wgBackendResponseTime'] = round( $elapsed * 1000 );
3609 $vars += $this->getJSVars( self::JS_VAR_LATE );
3610 if ( $this->limitReportJSData ) {
3611 $vars['wgPageParseReport'] = $this->limitReportJSData;
3614 $rlContext = $this->getRlClientContext();
3615 $chunks[] = ResourceLoader::makeInlineScript(
3616 'mw.config.set(' . $rlContext->encodeJson( $vars ) . ');',
3617 $this->CSP->getNonce()
3620 $chunks = [ self::combineWrappedStrings( $chunks ) ];
3621 if ( $extraHtml !== '' ) {
3622 $chunks[] = $extraHtml;
3625 return WrappedString::join( "\n", $chunks );
3629 * Get the javascript config vars to include on this page
3631 * @return array Array of javascript config vars
3632 * @since 1.23
3634 public function getJsConfigVars() {
3635 return $this->mJsConfigVars;
3639 * Add one or more variables to be set in mw.config in JavaScript
3641 * @param string|array $keys Key or array of key/value pairs
3642 * @param mixed|null $value [optional] Value of the configuration variable
3644 public function addJsConfigVars( $keys, $value = null ) {
3645 if ( is_array( $keys ) ) {
3646 foreach ( $keys as $key => $value ) {
3647 $this->mJsConfigVars[$key] = $value;
3649 return;
3652 $this->mJsConfigVars[$keys] = $value;
3656 * Get an array containing the variables to be set in mw.config in JavaScript.
3658 * Do not add things here which can be evaluated in RL\StartUpModule,
3659 * in other words, page-independent/site-wide variables (without state).
3660 * These would add a blocking HTML cost to page rendering time, and require waiting for
3661 * HTTP caches to expire before configuration changes take effect everywhere.
3663 * By default, these are loaded in the HTML head and block page rendering.
3664 * Config variable names can be set in CORE_LATE_JS_CONFIG_VAR_NAMES, or
3665 * for extensions via the 'LateJSConfigVarNames' attribute, to opt-in to
3666 * being sent from the end of the HTML body instead, to improve page load time.
3667 * In JavaScript, late variables should be accessed via mw.hook('wikipage.content').
3669 * @param int|null $flag Return only the specified kind of variables: self::JS_VAR_EARLY or self::JS_VAR_LATE.
3670 * For internal use only.
3671 * @return array
3673 public function getJSVars( ?int $flag = null ) {
3674 $curRevisionId = 0;
3675 $articleId = 0;
3676 $canonicalSpecialPageName = false; # T23115
3677 $services = MediaWikiServices::getInstance();
3679 $title = $this->getTitle();
3680 $ns = $title->getNamespace();
3681 $nsInfo = $services->getNamespaceInfo();
3682 $canonicalNamespace = $nsInfo->exists( $ns )
3683 ? $nsInfo->getCanonicalName( $ns )
3684 : $title->getNsText();
3686 $sk = $this->getSkin();
3687 // Get the relevant title so that AJAX features can use the correct page name
3688 // when making API requests from certain special pages (T36972).
3689 $relevantTitle = $sk->getRelevantTitle();
3691 if ( $ns === NS_SPECIAL ) {
3692 [ $canonicalSpecialPageName, /*...*/ ] =
3693 $services->getSpecialPageFactory()->
3694 resolveAlias( $title->getDBkey() );
3695 } elseif ( $this->canUseWikiPage() ) {
3696 $wikiPage = $this->getWikiPage();
3697 // If we already know that the latest revision ID is the same as the revision ID being viewed,
3698 // avoid fetching it again, as it may give inconsistent results (T339164).
3699 if ( $this->isRevisionCurrent() && $this->getRevisionId() ) {
3700 $curRevisionId = $this->getRevisionId();
3701 } else {
3702 $curRevisionId = $wikiPage->getLatest();
3704 $articleId = $wikiPage->getId();
3707 $lang = $title->getPageViewLanguage();
3709 // Pre-process information
3710 $separatorTransTable = $lang->separatorTransformTable();
3711 $separatorTransTable = $separatorTransTable ?: [];
3712 $compactSeparatorTransTable = [
3713 implode( "\t", array_keys( $separatorTransTable ) ),
3714 implode( "\t", $separatorTransTable ),
3716 $digitTransTable = $lang->digitTransformTable();
3717 $digitTransTable = $digitTransTable ?: [];
3718 $compactDigitTransTable = [
3719 implode( "\t", array_keys( $digitTransTable ) ),
3720 implode( "\t", $digitTransTable ),
3723 $user = $this->getUser();
3725 // Internal variables for MediaWiki core
3726 $vars = [
3727 // @internal For mediawiki.page.ready
3728 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3730 // @internal For jquery.tablesorter
3731 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3732 'wgDigitTransformTable' => $compactDigitTransTable,
3733 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3734 'wgMonthNames' => $lang->getMonthNamesArray(),
3736 // @internal For debugging purposes
3737 'wgRequestId' => WebRequest::getRequestId(),
3739 // @internal For mw.loader
3740 'wgCSPNonce' => $this->CSP->getNonce(),
3743 // Start of supported and stable config vars (for use by extensions/gadgets).
3744 $vars += [
3745 'wgCanonicalNamespace' => $canonicalNamespace,
3746 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3747 'wgNamespaceNumber' => $title->getNamespace(),
3748 'wgPageName' => $title->getPrefixedDBkey(),
3749 'wgTitle' => $title->getText(),
3750 'wgCurRevisionId' => $curRevisionId,
3751 'wgRevisionId' => (int)$this->getRevisionId(),
3752 'wgArticleId' => $articleId,
3753 'wgIsArticle' => $this->isArticle(),
3754 'wgIsRedirect' => $title->isRedirect(),
3755 'wgAction' => $this->getContext()->getActionName(),
3756 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3757 'wgUserGroups' => $services->getUserGroupManager()->getUserEffectiveGroups( $user ),
3758 'wgCategories' => $this->getCategories(),
3759 'wgPageViewLanguage' => $lang->getCode(),
3760 'wgPageContentLanguage' => $lang->getCode(),
3761 'wgPageContentModel' => $title->getContentModel(),
3762 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3763 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3765 if ( $user->isRegistered() ) {
3766 $vars['wgUserId'] = $user->getId();
3767 $vars['wgUserIsTemp'] = $user->isTemp();
3768 $vars['wgUserEditCount'] = $user->getEditCount();
3769 $userReg = $user->getRegistration();
3770 $vars['wgUserRegistration'] = $userReg ? (int)wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3771 // Get the revision ID of the oldest new message on the user's talk
3772 // page. This can be used for constructing new message alerts on
3773 // the client side.
3774 $userNewMsgRevId = $this->getLastSeenUserTalkRevId();
3775 // Only occupy precious space in the <head> when it is non-null (T53640)
3776 // mw.config.get returns null by default.
3777 if ( $userNewMsgRevId ) {
3778 $vars['wgUserNewMsgRevisionId'] = $userNewMsgRevId;
3781 $languageConverter = $services->getLanguageConverterFactory()
3782 ->getLanguageConverter( $title->getPageLanguage() );
3783 if ( $languageConverter->hasVariants() ) {
3784 $vars['wgUserVariant'] = $languageConverter->getPreferredVariant();
3786 // Same test as SkinTemplate
3787 $vars['wgIsProbablyEditable'] = $this->getAuthority()->probablyCan( 'edit', $title );
3788 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3789 $this->getAuthority()->probablyCan( 'edit', $relevantTitle );
3790 $restrictionStore = $services->getRestrictionStore();
3791 foreach ( $restrictionStore->listApplicableRestrictionTypes( $title ) as $type ) {
3792 // Following keys are set in $vars:
3793 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3794 $vars['wgRestriction' . ucfirst( $type )] = $restrictionStore->getRestrictions( $title, $type );
3796 if ( $title->isMainPage() ) {
3797 $vars['wgIsMainPage'] = true;
3800 $relevantUser = $sk->getRelevantUser();
3801 if ( $relevantUser ) {
3802 $vars['wgRelevantUserName'] = $relevantUser->getName();
3804 // End of stable config vars
3806 $titleFormatter = $services->getTitleFormatter();
3808 if ( $this->mRedirectedFrom ) {
3809 // @internal For skin JS
3810 $vars['wgRedirectedFrom'] = $titleFormatter->getPrefixedDBkey( $this->mRedirectedFrom );
3813 // Allow extensions to add their custom variables to the mw.config map.
3814 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3815 // page-dependent but site-wide (without state).
3816 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3817 $this->getHookRunner()->onMakeGlobalVariablesScript( $vars, $this );
3819 // Merge in variables from addJsConfigVars last
3820 $vars = array_merge( $vars, $this->getJsConfigVars() );
3822 // Return only early or late vars if requested
3823 if ( $flag !== null ) {
3824 $lateVarNames =
3825 array_fill_keys( self::CORE_LATE_JS_CONFIG_VAR_NAMES, true ) +
3826 array_fill_keys( ExtensionRegistry::getInstance()->getAttribute( 'LateJSConfigVarNames' ), true );
3827 foreach ( array_keys( $vars ) as $name ) {
3828 // If the variable's late flag doesn't match the requested late flag, unset it
3829 if ( isset( $lateVarNames[ $name ] ) !== ( $flag === self::JS_VAR_LATE ) ) {
3830 unset( $vars[ $name ] );
3835 return $vars;
3839 * Get the revision ID for the last user talk page revision viewed by the talk page owner.
3841 * @return int|null
3843 private function getLastSeenUserTalkRevId() {
3844 $services = MediaWikiServices::getInstance();
3845 $user = $this->getUser();
3846 $userHasNewMessages = $services
3847 ->getTalkPageNotificationManager()
3848 ->userHasNewMessages( $user );
3849 if ( !$userHasNewMessages ) {
3850 return null;
3853 $timestamp = $services
3854 ->getTalkPageNotificationManager()
3855 ->getLatestSeenMessageTimestamp( $user );
3856 if ( !$timestamp ) {
3857 return null;
3860 $revRecord = $services->getRevisionLookup()->getRevisionByTimestamp(
3861 $user->getTalkPage(),
3862 $timestamp
3864 return $revRecord ? $revRecord->getId() : null;
3868 * To make it harder for someone to slip a user a fake
3869 * JavaScript or CSS preview, a random token
3870 * is associated with the login session. If it's not
3871 * passed back with the preview request, we won't render
3872 * the code.
3874 * @return bool
3876 public function userCanPreview() {
3877 $request = $this->getRequest();
3878 if (
3879 $request->getRawVal( 'action' ) !== 'submit' ||
3880 !$request->wasPosted()
3882 return false;
3885 $user = $this->getUser();
3887 if ( !$user->isRegistered() ) {
3888 // Anons have predictable edit tokens
3889 return false;
3891 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3892 return false;
3895 $title = $this->getTitle();
3896 if ( !$this->getAuthority()->probablyCan( 'edit', $title ) ) {
3897 return false;
3900 return true;
3904 * @return array Array in format "link name or number => 'link html'".
3906 public function getHeadLinksArray() {
3907 $tags = [];
3908 $config = $this->getConfig();
3910 $tags['meta-generator'] = Html::element( 'meta', [
3911 'name' => 'generator',
3912 'content' => 'MediaWiki ' . MW_VERSION,
3913 ] );
3915 if ( $config->get( MainConfigNames::ReferrerPolicy ) !== false ) {
3916 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3917 // fallbacks should come before the primary value so we need to reverse the array.
3918 foreach ( array_reverse( (array)$config->get( MainConfigNames::ReferrerPolicy ) ) as $i => $policy ) {
3919 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3920 'name' => 'referrer',
3921 'content' => $policy,
3922 ] );
3926 $p = $this->getRobotsContent();
3927 if ( $p ) {
3928 // http://www.robotstxt.org/wc/meta-user.html
3929 // Only show if it's different from the default robots policy
3930 $tags['meta-robots'] = Html::element( 'meta', [
3931 'name' => 'robots',
3932 'content' => $p,
3933 ] );
3936 # Browser based phonenumber detection
3937 if ( $config->get( MainConfigNames::BrowserFormatDetection ) !== false ) {
3938 $tags['meta-format-detection'] = Html::element( 'meta', [
3939 'name' => 'format-detection',
3940 'content' => $config->get( MainConfigNames::BrowserFormatDetection ),
3941 ] );
3944 foreach ( $this->mMetatags as $tag ) {
3945 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3946 $a = 'http-equiv';
3947 $tag[0] = substr( $tag[0], 5 );
3948 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3949 $a = 'property';
3950 } else {
3951 $a = 'name';
3953 $tagName = "meta-{$tag[0]}";
3954 if ( isset( $tags[$tagName] ) ) {
3955 $tagName .= $tag[1];
3957 $tags[$tagName] = Html::element( 'meta',
3959 $a => $tag[0],
3960 'content' => $tag[1]
3965 foreach ( $this->mLinktags as $tag ) {
3966 $tags[] = Html::element( 'link', $tag );
3969 if ( $config->get( MainConfigNames::UniversalEditButton ) && $this->isArticleRelated() ) {
3970 if ( $this->getAuthority()->probablyCan( 'edit', $this->getTitle() ) ) {
3971 $msg = $this->msg( 'edit' )->text();
3972 // Use mime type per https://phabricator.wikimedia.org/T21165#6946526
3973 $tags['universal-edit-button'] = Html::element( 'link', [
3974 'rel' => 'alternate',
3975 'type' => 'application/x-wiki',
3976 'title' => $msg,
3977 'href' => $this->getTitle()->getEditURL(),
3978 ] );
3982 # Generally the order of the favicon and apple-touch-icon links
3983 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3984 # uses whichever one appears later in the HTML source. Make sure
3985 # apple-touch-icon is specified first to avoid this.
3986 if ( $config->get( MainConfigNames::AppleTouchIcon ) !== false ) {
3987 $tags['apple-touch-icon'] = Html::element( 'link', [
3988 'rel' => 'apple-touch-icon',
3989 'href' => $config->get( MainConfigNames::AppleTouchIcon )
3990 ] );
3993 if ( $config->get( MainConfigNames::Favicon ) !== false ) {
3994 $tags['favicon'] = Html::element( 'link', [
3995 'rel' => 'icon',
3996 'href' => $config->get( MainConfigNames::Favicon )
3997 ] );
4000 # OpenSearch description link
4001 $tags['opensearch'] = Html::element( 'link', [
4002 'rel' => 'search',
4003 'type' => 'application/opensearchdescription+xml',
4004 'href' => wfScript( 'opensearch_desc' ),
4005 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
4006 ] );
4008 $services = MediaWikiServices::getInstance();
4010 # Real Simple Discovery link, provides auto-discovery information
4011 # for the MediaWiki API (and potentially additional custom API
4012 # support such as WordPress or Twitter-compatible APIs for a
4013 # blogging extension, etc)
4014 $tags['rsd'] = Html::element( 'link', [
4015 'rel' => 'EditURI',
4016 'type' => 'application/rsd+xml',
4017 // Output a protocol-relative URL here if $wgServer is protocol-relative.
4018 // Whether RSD accepts relative or protocol-relative URLs is completely
4019 // undocumented, though.
4020 'href' => (string)$services->getUrlUtils()->expand( wfAppendQuery(
4021 wfScript( 'api' ),
4022 [ 'action' => 'rsd' ] ),
4023 PROTO_RELATIVE
4025 ] );
4027 $tags = array_merge(
4028 $tags,
4029 $this->getHeadLinksCanonicalURLArray( $config ),
4030 $this->getHeadLinksAlternateURLsArray(),
4031 $this->getHeadLinksCopyrightArray( $config ),
4032 $this->getHeadLinksSyndicationArray( $config ),
4035 // Allow extensions to add, remove and/or otherwise manipulate these links
4036 // If you want only to *add* <head> links, please use the addHeadItem()
4037 // (or addHeadItems() for multiple items) method instead.
4038 // This hook is provided as a last resort for extensions to modify these
4039 // links before the output is sent to client.
4040 $this->getHookRunner()->onOutputPageAfterGetHeadLinksArray( $tags, $this );
4042 return $tags;
4046 * Canonical URL and alternate URLs
4048 * isCanonicalUrlAction affects all requests where "setArticleRelated" is true.
4049 * This is typically all requests that show content (query title, curid, oldid, diff),
4050 * and all wikipage actions (edit, delete, purge, info, history etc.).
4051 * It does not apply to file pages and special pages.
4052 * 'history' and 'info' actions address page metadata rather than the page
4053 * content itself, so they may not be canonicalized to the view page url.
4054 * TODO: this logic should be owned by Action subclasses.
4055 * See T67402
4059 * Get head links relating to the canonical URL
4060 * Note: There should only be one canonical URL.
4061 * @param Config $config
4062 * @return array
4064 private function getHeadLinksCanonicalURLArray( Config $config ) {
4065 $tags = [];
4066 $canonicalUrl = $this->mCanonicalUrl;
4068 if ( $config->get( MainConfigNames::EnableCanonicalServerLink ) ) {
4069 $query = [];
4070 $action = $this->getContext()->getActionName();
4071 $isCanonicalUrlAction = in_array( $action, [ 'history', 'info' ] );
4072 $services = MediaWikiServices::getInstance();
4073 $languageConverterFactory = $services->getLanguageConverterFactory();
4074 $isLangConversionDisabled = $languageConverterFactory->isConversionDisabled();
4075 $pageLang = $this->getTitle()->getPageLanguage();
4076 $pageLanguageConverter = $languageConverterFactory->getLanguageConverter( $pageLang );
4077 $urlVariant = $pageLanguageConverter->getURLVariant();
4079 if ( $canonicalUrl !== false ) {
4080 $canonicalUrl = (string)$services->getUrlUtils()->expand( $canonicalUrl, PROTO_CANONICAL );
4081 } elseif ( $this->isArticleRelated() ) {
4082 if ( $isCanonicalUrlAction ) {
4083 $query['action'] = $action;
4084 } elseif ( !$isLangConversionDisabled && $urlVariant ) {
4085 # T54429, T108443: Making canonical URL language-variant-aware.
4086 $query['variant'] = $urlVariant;
4088 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
4089 } else {
4090 $reqUrl = $this->getRequest()->getRequestURL();
4091 $canonicalUrl = (string)$services->getUrlUtils()->expand( $reqUrl, PROTO_CANONICAL );
4095 if ( $canonicalUrl !== false ) {
4096 $tags['link-canonical'] = Html::element( 'link', [
4097 'rel' => 'canonical',
4098 'href' => $canonicalUrl
4099 ] );
4102 return $tags;
4106 * Get head links relating to alternate URL(s) in languages including language variants
4107 * Output fully-qualified URL since meta alternate URLs must be fully-qualified
4108 * Per https://developers.google.com/search/docs/advanced/crawling/localized-versions
4109 * See T294716
4111 * @return array
4113 private function getHeadLinksAlternateURLsArray() {
4114 $tags = [];
4115 $languageUrls = [];
4116 $action = $this->getContext()->getActionName();
4117 $isCanonicalUrlAction = in_array( $action, [ 'history', 'info' ] );
4118 $services = MediaWikiServices::getInstance();
4119 $languageConverterFactory = $services->getLanguageConverterFactory();
4120 $isLangConversionDisabled = $languageConverterFactory->isConversionDisabled();
4121 $pageLang = $this->getTitle()->getPageLanguage();
4122 $pageLanguageConverter = $languageConverterFactory->getLanguageConverter( $pageLang );
4124 # Language variants
4125 if (
4126 $this->isArticleRelated() &&
4127 !$isCanonicalUrlAction &&
4128 $pageLanguageConverter->hasVariants() &&
4129 !$isLangConversionDisabled
4131 $variants = $pageLanguageConverter->getVariants();
4132 foreach ( $variants as $variant ) {
4133 $bcp47 = LanguageCode::bcp47( $variant );
4134 $languageUrls[$bcp47] = $this->getTitle()
4135 ->getFullURL( [ 'variant' => $variant ], false, PROTO_CURRENT );
4139 # Alternate URLs for interlanguage links would be handeled in HTML body tag instead of
4140 # head tag, see T326829.
4142 if ( $languageUrls ) {
4143 # Force the alternate URL of page language code to be self.
4144 # T123901, T305540, T108443: Override mixed-variant variant link in language variant links.
4145 $currentUrl = $this->getTitle()->getFullURL( [], false, PROTO_CURRENT );
4146 $pageLangCodeBcp47 = LanguageCode::bcp47( $pageLang->getCode() );
4147 $languageUrls[$pageLangCodeBcp47] = $currentUrl;
4149 ksort( $languageUrls );
4151 # Also add x-default link per https://support.google.com/webmasters/answer/189077?hl=en
4152 $languageUrls['x-default'] = $currentUrl;
4154 # Process all of language variants and interlanguage links
4155 foreach ( $languageUrls as $bcp47 => $languageUrl ) {
4156 $bcp47lowercase = strtolower( $bcp47 );
4157 $tags['link-alternate-language-' . $bcp47lowercase] = Html::element( 'link', [
4158 'rel' => 'alternate',
4159 'hreflang' => $bcp47,
4160 'href' => $languageUrl,
4161 ] );
4165 return $tags;
4169 * Get head links relating to copyright
4171 * @param Config $config
4172 * @return array
4174 private function getHeadLinksCopyrightArray( Config $config ) {
4175 $tags = [];
4177 if ( $this->copyrightUrl !== null ) {
4178 $copyright = $this->copyrightUrl;
4179 } else {
4180 $copyright = '';
4181 if ( $config->get( MainConfigNames::RightsPage ) ) {
4182 $copy = Title::newFromText( $config->get( MainConfigNames::RightsPage ) );
4184 if ( $copy ) {
4185 $copyright = $copy->getLocalURL();
4189 if ( !$copyright && $config->get( MainConfigNames::RightsUrl ) ) {
4190 $copyright = $config->get( MainConfigNames::RightsUrl );
4194 if ( $copyright ) {
4195 $tags['copyright'] = Html::element( 'link', [
4196 'rel' => 'license',
4197 'href' => $copyright
4198 ] );
4201 return $tags;
4205 * Get head links relating to syndication feeds.
4207 * @param Config $config
4208 * @return array
4210 private function getHeadLinksSyndicationArray( Config $config ) {
4211 if ( !$config->get( MainConfigNames::Feed ) ) {
4212 return [];
4215 $tags = [];
4216 $feedLinks = [];
4218 foreach ( $this->getSyndicationLinks() as $format => $link ) {
4219 # Use the page name for the title. In principle, this could
4220 # lead to issues with having the same name for different feeds
4221 # corresponding to the same page, but we can't avoid that at
4222 # this low a level.
4224 $feedLinks[] = $this->feedLink(
4225 $format,
4226 $link,
4227 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
4228 $this->msg(
4229 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
4230 )->text()
4234 # Recent changes feed should appear on every page (except recentchanges,
4235 # that would be redundant). Put it after the per-page feed to avoid
4236 # changing existing behavior. It's still available, probably via a
4237 # menu in your browser. Some sites might have a different feed they'd
4238 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
4239 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
4240 # If so, use it instead.
4241 $sitename = $config->get( MainConfigNames::Sitename );
4242 $overrideSiteFeed = $config->get( MainConfigNames::OverrideSiteFeed );
4243 if ( $overrideSiteFeed ) {
4244 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
4245 // Note, this->feedLink escapes the url.
4246 $feedLinks[] = $this->feedLink(
4247 $type,
4248 $feedUrl,
4249 $this->msg( "site-{$type}-feed", $sitename )->text()
4252 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
4253 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
4254 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
4255 $feedLinks[] = $this->feedLink(
4256 $format,
4257 $rctitle->getLocalURL( [ 'feed' => $format ] ),
4258 # For grep: 'site-rss-feed', 'site-atom-feed'
4259 $this->msg( "site-{$format}-feed", $sitename )->text()
4264 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
4265 # manipulating or removing existing feed tags. If you want to add new feeds, you should
4266 # use OutputPage::addFeedLink() instead.
4267 $this->getHookRunner()->onAfterBuildFeedLinks( $feedLinks );
4269 $tags += $feedLinks;
4271 return $tags;
4275 * Generate a "<link rel/>" for a feed.
4277 * @param string $type Feed type
4278 * @param string $url URL to the feed
4279 * @param string $text Value of the "title" attribute
4280 * @return string HTML fragment
4282 private function feedLink( $type, $url, $text ) {
4283 return Html::element( 'link', [
4284 'rel' => 'alternate',
4285 'type' => "application/$type+xml",
4286 'title' => $text,
4287 'href' => $url ]
4292 * Add a local or specified stylesheet, with the given media options.
4293 * Internal use only. Use OutputPage::addModuleStyles() if possible.
4295 * @param string $style URL to the file
4296 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
4297 * @param string $condition For IE conditional comments, specifying an IE version
4298 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
4300 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
4301 $options = [];
4302 if ( $media ) {
4303 $options['media'] = $media;
4305 if ( $condition ) {
4306 $options['condition'] = $condition;
4308 if ( $dir ) {
4309 $options['dir'] = $dir;
4311 $this->styles[$style] = $options;
4315 * Adds inline CSS styles
4316 * Internal use only. Use OutputPage::addModuleStyles() if possible.
4318 * @param mixed $style_css Inline CSS
4319 * @param string $flip Set to 'flip' to flip the CSS if needed
4321 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
4322 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
4323 # If wanted, and the interface is right-to-left, flip the CSS
4324 $style_css = CSSJanus::transform( $style_css, true, false );
4326 $this->mInlineStyles .= Html::inlineStyle( $style_css );
4330 * Build exempt modules and legacy non-ResourceLoader styles.
4332 * @return string|WrappedStringList HTML
4334 protected function buildExemptModules() {
4335 $chunks = [];
4337 // Requirements:
4338 // - Within modules provided by the software (core, skin, extensions),
4339 // styles from skin stylesheets should be overridden by styles
4340 // from modules dynamically loaded with JavaScript.
4341 // - Styles from site-specific, private, and user modules should override
4342 // both of the above.
4344 // The effective order for stylesheets must thus be:
4345 // 1. Page style modules, formatted server-side by RL\ClientHtml.
4346 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
4347 // 3. Styles that are site-specific, private or from the user, formatted
4348 // server-side by this function.
4350 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
4351 // point #2 is.
4353 // Add legacy styles added through addStyle()/addInlineStyle() here
4354 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
4356 // Things that go after the ResourceLoaderDynamicStyles marker
4357 $append = [];
4358 $separateReq = [ 'site.styles', 'user.styles' ];
4359 foreach ( $this->rlExemptStyleModules as $moduleNames ) {
4360 if ( $moduleNames ) {
4361 $append[] = $this->makeResourceLoaderLink(
4362 array_diff( $moduleNames, $separateReq ),
4363 RL\Module::TYPE_STYLES
4366 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
4367 // These require their own dedicated request in order to support "@import"
4368 // syntax, which is incompatible with concatenation. (T147667, T37562)
4369 $append[] = $this->makeResourceLoaderLink( $name,
4370 RL\Module::TYPE_STYLES
4375 if ( $append ) {
4376 $chunks[] = Html::element(
4377 'meta',
4378 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
4380 $chunks = array_merge( $chunks, $append );
4383 return self::combineWrappedStrings( $chunks );
4387 * @return array
4389 public function buildCssLinksArray() {
4390 $links = [];
4392 foreach ( $this->styles as $file => $options ) {
4393 $link = $this->styleLink( $file, $options );
4394 if ( $link ) {
4395 $links[$file] = $link;
4398 return $links;
4402 * Generate \<link\> tags for stylesheets
4404 * @param string $style URL to the file
4405 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
4406 * @return string HTML fragment
4408 protected function styleLink( $style, array $options ) {
4409 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
4410 return '';
4413 if ( isset( $options['media'] ) ) {
4414 $media = self::transformCssMedia( $options['media'] );
4415 if ( $media === null ) {
4416 return '';
4418 } else {
4419 $media = 'all';
4422 if ( str_starts_with( $style, '/' ) ||
4423 str_starts_with( $style, 'http:' ) ||
4424 str_starts_with( $style, 'https:' )
4426 $url = $style;
4427 } else {
4428 $config = $this->getConfig();
4429 // Append file hash as query parameter
4430 $url = self::transformResourcePath(
4431 $config,
4432 $config->get( MainConfigNames::StylePath ) . '/' . $style
4436 $link = Html::linkedStyle( $url, $media );
4438 if ( isset( $options['condition'] ) ) {
4439 $condition = htmlspecialchars( $options['condition'] );
4440 $link = "<!--[if $condition]>$link<![endif]-->";
4442 return $link;
4446 * Transform path to web-accessible static resource.
4448 * This is used to add a validation hash as query string.
4449 * This aids various behaviors:
4451 * - Put long Cache-Control max-age headers on responses for improved
4452 * cache performance.
4453 * - Get the correct version of a file as expected by the current page.
4454 * - Instantly get the updated version of a file after deployment.
4456 * Avoid using this for urls included in HTML as otherwise clients may get different
4457 * versions of a resource when navigating the site depending on when the page was cached.
4458 * If changes to the url propagate, this is not a problem (e.g. if the url is in
4459 * an external stylesheet).
4461 * @since 1.27
4462 * @param Config $config
4463 * @param string $path Path-absolute URL to file (from document root, must start with "/")
4464 * @return string URL
4466 public static function transformResourcePath( Config $config, $path ) {
4467 $localDir = $config->get( MainConfigNames::BaseDirectory );
4468 $remotePathPrefix = $config->get( MainConfigNames::ResourceBasePath );
4469 if ( $remotePathPrefix === '' ) {
4470 // The configured base path is required to be empty string for
4471 // wikis in the domain root
4472 $remotePath = '/';
4473 } else {
4474 $remotePath = $remotePathPrefix;
4476 if ( !str_starts_with( $path, $remotePath ) || str_starts_with( $path, '//' ) ) {
4477 // - Path is outside wgResourceBasePath, ignore.
4478 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
4479 return $path;
4481 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
4482 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
4483 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
4484 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
4485 $uploadPath = $config->get( MainConfigNames::UploadPath );
4486 if ( strpos( $path, $uploadPath ) === 0 ) {
4487 $localDir = $config->get( MainConfigNames::UploadDirectory );
4488 $remotePathPrefix = $remotePath = $uploadPath;
4491 $path = RelPath::getRelativePath( $path, $remotePath );
4492 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
4496 * Utility method for transformResourceFilePath().
4498 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
4500 * @since 1.27
4501 * @param string $remotePathPrefix URL path prefix that points to $localPath
4502 * @param string $localPath File directory exposed at $remotePath
4503 * @param string $file Path to target file relative to $localPath
4504 * @return string URL
4506 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4507 // This MUST match the equivalent logic in CSSMin::remapOne()
4508 $localFile = "$localPath/$file";
4509 $url = "$remotePathPrefix/$file";
4510 if ( is_file( $localFile ) ) {
4511 $hash = md5_file( $localFile );
4512 if ( $hash === false ) {
4513 wfLogWarning( __METHOD__ . ": Failed to hash $localFile" );
4514 $hash = '';
4516 $url .= '?' . substr( $hash, 0, 5 );
4518 return $url;
4522 * Transform "media" attribute based on request parameters
4524 * @param string $media Current value of the "media" attribute
4525 * @return string|null Modified value of the "media" attribute, or null to disable
4526 * this stylesheet
4528 public static function transformCssMedia( $media ) {
4529 global $wgRequest;
4531 if ( $wgRequest->getBool( 'printable' ) ) {
4532 // When browsing with printable=yes, apply "print" media styles
4533 // as if they are screen styles (no media, media="").
4534 if ( $media === 'print' ) {
4535 return '';
4538 // https://www.w3.org/TR/css3-mediaqueries/#syntax
4540 // This regex will not attempt to understand a comma-separated media_query_list
4541 // Example supported values for $media:
4543 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
4545 // Example NOT supported value for $media:
4547 // '3d-glasses, screen, print and resolution > 90dpi'
4549 // If it's a "printable" request, we disable all screen stylesheets.
4550 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
4551 if ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4552 return null;
4556 return $media;
4560 * Add a wikitext-formatted message to the output.
4561 * This is equivalent to:
4563 * $wgOut->addWikiText( wfMessage( ... )->plain() )
4565 * @param mixed ...$args
4567 public function addWikiMsg( ...$args ) {
4568 $name = array_shift( $args );
4569 $this->addWikiMsgArray( $name, $args );
4573 * Add a wikitext-formatted message to the output.
4574 * Like addWikiMsg() except the parameters are taken as an array
4575 * instead of a variable argument list.
4577 * @param string $name
4578 * @param array $args
4580 public function addWikiMsgArray( $name, $args ) {
4581 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
4585 * This function takes a number of message/argument specifications, wraps them in
4586 * some overall structure, and then parses the result and adds it to the output.
4588 * In the $wrap, $1 is replaced with the first message, $2 with the second,
4589 * and so on. The subsequent arguments may be either
4590 * 1) strings, in which case they are message names, or
4591 * 2) arrays, in which case, within each array, the first element is the message
4592 * name, and subsequent elements are the parameters to that message.
4594 * Don't use this for messages that are not in the user's interface language.
4596 * For example:
4598 * $wgOut->wrapWikiMsg( "<div class='customclass'>\n$1\n</div>", 'some-msg-key' );
4600 * Is equivalent to:
4602 * $wgOut->addWikiTextAsInterface( "<div class='customclass'>\n"
4603 * . wfMessage( 'some-msg-key' )->plain() . "\n</div>" );
4605 * The newline after the opening div is needed in some wikitext. See T21226.
4607 * @param string $wrap
4608 * @param mixed ...$msgSpecs
4610 public function wrapWikiMsg( $wrap, ...$msgSpecs ) {
4611 $s = $wrap;
4612 foreach ( $msgSpecs as $n => $spec ) {
4613 if ( is_array( $spec ) ) {
4614 $args = $spec;
4615 $name = array_shift( $args );
4616 } else {
4617 $args = [];
4618 $name = $spec;
4620 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4622 $this->addWikiTextAsInterface( $s );
4626 * Whether the output has a table of contents when the ToC is
4627 * rendered inline.
4628 * @return bool
4629 * @since 1.22
4631 public function isTOCEnabled() {
4632 return $this->mEnableTOC;
4636 * Helper function to setup the PHP implementation of OOUI to use in this request.
4638 * @since 1.26
4639 * @param string $skinName The Skin name to determine the correct OOUI theme
4640 * @param string $dir Language direction
4642 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4643 $themes = RL\OOUIFileModule::getSkinThemeMap();
4644 $theme = $themes[$skinName] ?? $themes['default'];
4645 // For example, 'OOUI\WikimediaUITheme'.
4646 $themeClass = "OOUI\\{$theme}Theme";
4647 OOUI\Theme::setSingleton( new $themeClass() );
4648 OOUI\Element::setDefaultDir( $dir );
4652 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4653 * MediaWiki and this OutputPage instance.
4655 * @since 1.25
4657 public function enableOOUI() {
4658 self::setupOOUI(
4659 strtolower( $this->getSkin()->getSkinName() ),
4660 $this->getLanguage()->getDir()
4662 $this->addModuleStyles( [
4663 'oojs-ui-core.styles',
4664 'oojs-ui.styles.indicators',
4665 'mediawiki.widgets.styles',
4666 'oojs-ui-core.icons',
4667 ] );
4671 * Get (and set if not yet set) the CSP nonce.
4673 * This value needs to be included in any <script> tags on the
4674 * page.
4676 * @return string|false Nonce or false to mean don't output nonce
4677 * @since 1.32
4678 * @deprecated Since 1.35 use getCSP()->getNonce() instead
4680 public function getCSPNonce() {
4681 return $this->CSP->getNonce();
4685 * Get the ContentSecurityPolicy object
4687 * @since 1.35
4688 * @return ContentSecurityPolicy
4690 public function getCSP() {
4691 return $this->CSP;
4695 * The final bits that go to the bottom of a page
4696 * HTML document including the closing tags
4698 * @internal
4699 * @since 1.37
4700 * @param Skin $skin
4701 * @return string
4703 public function tailElement( $skin ) {
4704 // T257704: Temporarily run skin hook here pending
4705 // creation dedicated outputpage hook for this
4706 $extraHtml = '';
4707 $this->getHookRunner()->onSkinAfterBottomScripts( $skin, $extraHtml );
4709 $tail = [
4710 MWDebug::getDebugHTML( $skin ),
4711 $this->getBottomScripts( $extraHtml ),
4712 MWDebug::getHTMLDebugLog(),
4713 Html::closeElement( 'body' ),
4714 Html::closeElement( 'html' ),
4717 return WrappedStringList::join( "\n", $tail );