Sync up with Parsoid parserTests.txt
[mediawiki.git] / includes / OutputPage.php
blobcb7baaf99bc1ad77527cbc91c97d7b18d47193f4
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\Linker\LinkTarget;
25 use MediaWiki\MainConfigNames;
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Page\PageRecord;
28 use MediaWiki\Page\PageReference;
29 use MediaWiki\Parser\ParserOutputFlags;
30 use MediaWiki\Permissions\PermissionStatus;
31 use MediaWiki\ResourceLoader as RL;
32 use MediaWiki\ResourceLoader\ResourceLoader;
33 use MediaWiki\Session\SessionManager;
34 use Wikimedia\AtEase\AtEase;
35 use Wikimedia\Rdbms\IResultWrapper;
36 use Wikimedia\RelPath;
37 use Wikimedia\WrappedString;
38 use Wikimedia\WrappedStringList;
40 /**
41 * This is one of the Core classes and should
42 * be read at least once by any new developers. Also documented at
43 * https://www.mediawiki.org/wiki/Manual:Architectural_modules/OutputPage
45 * This class is used to prepare the final rendering. A skin is then
46 * applied to the output parameters (links, javascript, html, categories ...).
48 * @todo FIXME: Another class handles sending the whole page to the client.
50 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
51 * in November 2010.
53 * @todo document
55 class OutputPage extends ContextSource {
56 use ProtectedHookAccessorTrait;
58 /** @var string[][] Should be private. Used with addMeta() which adds "<meta>" */
59 protected $mMetatags = [];
61 /** @var array */
62 protected $mLinktags = [];
64 /** @var string|bool */
65 protected $mCanonicalUrl = false;
67 /**
68 * @var string The contents of <h1>
70 private $mPageTitle = '';
72 /**
73 * @var string The displayed title of the page. Different from page title
74 * if overridden by display title magic word or hooks. Can contain safe
75 * HTML. Different from page title which may contain messages such as
76 * "Editing X" which is displayed in h1. This can be used for other places
77 * where the page name is referred on the page.
79 private $displayTitle;
81 /** @var bool See OutputPage::couldBePublicCached. */
82 private $cacheIsFinal = false;
84 /**
85 * @var string Contains all of the "<body>" content. Should be private we
86 * got set/get accessors and the append() method.
88 public $mBodytext = '';
90 /** @var string Stores contents of "<title>" tag */
91 private $mHTMLtitle = '';
93 /**
94 * @var bool Is the displayed content related to the source of the
95 * corresponding wiki article.
97 private $mIsArticle = false;
99 /** @var bool Stores "article flag" toggle. */
100 private $mIsArticleRelated = true;
102 /** @var bool Is the content subject to copyright */
103 private $mHasCopyright = false;
106 * @var bool We have to set isPrintable(). Some pages should
107 * never be printed (ex: redirections).
109 private $mPrintable = false;
112 * @var array sections from ParserOutput
114 private $mSections = [];
117 * @var array Contains the page subtitle. Special pages usually have some
118 * links here. Don't confuse with site subtitle added by skins.
120 private $mSubtitle = [];
122 /** @var string */
123 public $mRedirect = '';
125 /** @var int */
126 protected $mStatusCode;
129 * @var string Used for sending cache control.
130 * The whole caching system should probably be moved into its own class.
132 protected $mLastModified = '';
135 * @var string[][]
136 * @deprecated since 1.38; will be made private (T301020)
138 protected $mCategoryLinks = [];
141 * @var string[][]
142 * @deprecated since 1.38, will be made private (T301020)
144 protected $mCategories = [
145 'hidden' => [],
146 'normal' => [],
150 * @var string[]
151 * @deprecated since 1.38; will be made private (T301020)
153 protected $mIndicators = [];
156 * @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
158 private $mLanguageLinks = [];
161 * Used for JavaScript (predates ResourceLoader)
162 * @todo We should split JS / CSS.
163 * mScripts content is inserted as is in "<head>" by Skin. This might
164 * contain either a link to a stylesheet or inline CSS.
166 private $mScripts = '';
168 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
169 protected $mInlineStyles = '';
172 * @var string Used by skin template.
173 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
175 public $mPageLinkTitle = '';
178 * Additional <html> classes; This should be rarely modified; prefer mAdditionalBodyClasses.
179 * @var array
181 protected $mAdditionalHtmlClasses = [];
184 * @var array Array of elements in "<head>". Parser might add its own headers!
185 * @deprecated since 1.38; will be made private (T301020)
187 protected $mHeadItems = [];
189 /** @var array Additional <body> classes; there are also <body> classes from other sources */
190 protected $mAdditionalBodyClasses = [];
193 * @var array
194 * @deprecated since 1.38; will be made private (T301020)
196 protected $mModules = [];
199 * @var array
200 * @deprecated since 1.38; will be made private (T301020)
202 protected $mModuleStyles = [];
204 /** @var ResourceLoader */
205 protected $mResourceLoader;
207 /** @var RL\ClientHtml */
208 private $rlClient;
210 /** @var RL\Context */
211 private $rlClientContext;
213 /** @var array */
214 private $rlExemptStyleModules;
217 * @var array
218 * @deprecated since 1.38; will be made private (T301020)
220 protected $mJsConfigVars = [];
223 * @var array
224 * @deprecated since 1.38; will be made private (T301020)
226 protected $mTemplateIds = [];
228 /** @var array */
229 protected $mImageTimeKeys = [];
231 /** @var string */
232 public $mRedirectCode = '';
234 protected $mFeedLinksAppendQuery = null;
236 /** @var array
237 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
238 * @see RL\Module::$origin
239 * RL\Module::ORIGIN_ALL is assumed unless overridden;
241 protected $mAllowedModules = [
242 RL\Module::TYPE_COMBINED => RL\Module::ORIGIN_ALL,
245 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
246 protected $mDoNothing = false;
248 // Parser related.
251 * lazy initialised, use parserOptions()
252 * @var ParserOptions
254 protected $mParserOptions = null;
257 * Handles the Atom / RSS links.
258 * We probably only support Atom in 2011.
259 * @see $wgAdvertisedFeedTypes
261 private $mFeedLinks = [];
264 * @var bool Set to false to send no-cache headers, disabling
265 * client-side caching. (This variable should really be named
266 * in the opposite sense; see ::disableClientCache().)
267 * @deprecated since 1.38; will be made private (T301020)
269 protected $mEnableClientCache = true;
271 /** @var bool Flag if output should only contain the body of the article. */
272 private $mArticleBodyOnly = false;
275 * @var bool
276 * @deprecated since 1.38; will be made private (T301020)
278 protected $mNewSectionLink = false;
281 * @var bool
282 * @deprecated since 1.38; will be made private (T301020)
284 protected $mHideNewSectionLink = false;
287 * @var bool Comes from the parser. This was probably made to load CSS/JS
288 * only if we had "<gallery>". Used directly in CategoryPage.php.
289 * Looks like ResourceLoader can replace this.
290 * @deprecated since 1.38; will be made private (T301020)
292 public $mNoGallery = false;
294 /** @var int Cache stuff. Looks like mEnableClientCache */
295 protected $mCdnMaxage = 0;
296 /** @var int Upper limit on mCdnMaxage */
297 protected $mCdnMaxageLimit = INF;
300 * @var bool Controls if anti-clickjacking / frame-breaking headers will
301 * be sent. This should be done for pages where edit actions are possible.
302 * Setter: $this->setPreventClickjacking()
304 protected $mPreventClickjacking = true;
306 /** @var int|null To include the variable {{REVISIONID}} */
307 private $mRevisionId = null;
309 /** @var bool|null */
310 private $mRevisionIsCurrent = null;
312 /** @var string */
313 private $mRevisionTimestamp = null;
315 /** @var array */
316 protected $mFileVersion = null;
319 * @var array An array of stylesheet filenames (relative from skins path),
320 * with options for CSS media, IE conditions, and RTL/LTR direction.
321 * For internal use; add settings in the skin via $this->addStyle()
323 * Style again! This seems like a code duplication since we already have
324 * mStyles. This is what makes Open Source amazing.
326 protected $styles = [];
328 private $mIndexPolicy = 'index';
329 private $mFollowPolicy = 'follow';
331 /** @var array */
332 private $mRobotsOptions = [];
335 * @var array Headers that cause the cache to vary. Key is header name,
336 * value should always be null. (Value was an array of options for
337 * the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
339 private $mVaryHeader = [
340 'Accept-Encoding' => null,
344 * If the current page was reached through a redirect, $mRedirectedFrom contains the title
345 * of the redirect.
347 * @var PageReference
349 private $mRedirectedFrom = null;
352 * Additional key => value data
354 private $mProperties = [];
357 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
359 private $mTarget = null;
362 * @var bool Whether parser output contains a table of contents
364 private $mEnableTOC = false;
367 * @var string|null The URL to send in a <link> element with rel=license
369 private $copyrightUrl;
371 /** @var array Profiling data */
372 private $limitReportJSData = [];
374 /** @var array Map Title to Content */
375 private $contentOverrides = [];
377 /** @var callable[] */
378 private $contentOverrideCallbacks = [];
381 * Link: header contents
383 private $mLinkHeader = [];
386 * @var ContentSecurityPolicy
388 private $CSP;
391 * @var array A cache of the names of the cookies that will influence the cache
393 private static $cacheVaryCookies = null;
396 * Constructor for OutputPage. This should not be called directly.
397 * Instead a new RequestContext should be created and it will implicitly create
398 * a OutputPage tied to that context.
399 * @param IContextSource $context
401 public function __construct( IContextSource $context ) {
402 $this->setContext( $context );
403 $this->CSP = new ContentSecurityPolicy(
404 $context->getRequest()->response(),
405 $context->getConfig(),
406 $this->getHookContainer()
411 * Redirect to $url rather than displaying the normal page
413 * @param string $url
414 * @param string|int $responsecode HTTP status code
416 public function redirect( $url, $responsecode = '302' ) {
417 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
418 $this->mRedirect = str_replace( "\n", '', $url );
419 $this->mRedirectCode = (string)$responsecode;
423 * Get the URL to redirect to, or an empty string if not redirect URL set
425 * @return string
427 public function getRedirect() {
428 return $this->mRedirect;
432 * Set the copyright URL to send with the output.
433 * Empty string to omit, null to reset.
435 * @since 1.26
437 * @param string|null $url
439 public function setCopyrightUrl( $url ) {
440 $this->copyrightUrl = $url;
444 * Set the HTTP status code to send with the output.
446 * @param int $statusCode
448 public function setStatusCode( $statusCode ) {
449 $this->mStatusCode = $statusCode;
453 * Add a new "<meta>" tag
454 * To add an http-equiv meta tag, precede the name with "http:"
456 * @param string $name Name of the meta tag
457 * @param string $val Value of the meta tag
459 public function addMeta( $name, $val ) {
460 $this->mMetatags[] = [ $name, $val ];
464 * Returns the current <meta> tags
466 * @since 1.25
467 * @return array
469 public function getMetaTags() {
470 return $this->mMetatags;
474 * Add a new \<link\> tag to the page header.
476 * Note: use setCanonicalUrl() for rel=canonical.
478 * @param array $linkarr Associative array of attributes.
480 public function addLink( array $linkarr ) {
481 $this->mLinktags[] = $linkarr;
485 * Returns the current <link> tags
487 * @since 1.25
488 * @return array
490 public function getLinkTags() {
491 return $this->mLinktags;
495 * Set the URL to be used for the <link rel=canonical>. This should be used
496 * in preference to addLink(), to avoid duplicate link tags.
497 * @param string $url
499 public function setCanonicalUrl( $url ) {
500 $this->mCanonicalUrl = $url;
504 * Returns the URL to be used for the <link rel=canonical> if
505 * one is set.
507 * @since 1.25
508 * @return bool|string
510 public function getCanonicalUrl() {
511 return $this->mCanonicalUrl;
515 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
516 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
517 * if possible.
519 * @param string $script Raw HTML
521 public function addScript( $script ) {
522 $this->mScripts .= $script;
526 * Add a JavaScript file to be loaded as `<script>` on this page.
528 * Internal use only. Use OutputPage::addModules() if possible.
530 * @param string $file URL to file (absolute path, protocol-relative, or full url)
531 * @param string|null $unused Previously used to change the cache-busting query parameter
533 public function addScriptFile( $file, $unused = null ) {
534 $this->addScript( Html::linkedScript( $file, $this->CSP->getNonce() ) );
538 * Add a self-contained script tag with the given contents
539 * Internal use only. Use OutputPage::addModules() if possible.
541 * @param string $script JavaScript text, no script tags
543 public function addInlineScript( $script ) {
544 $this->mScripts .= Html::inlineScript( "\n$script\n", $this->CSP->getNonce() ) . "\n";
548 * Filter an array of modules to remove insufficiently trustworthy members, and modules
549 * which are no longer registered (eg a page is cached before an extension is disabled)
550 * @param string[] $modules
551 * @param string|null $position Unused
552 * @param string $type
553 * @return string[]
555 protected function filterModules( array $modules, $position = null,
556 $type = RL\Module::TYPE_COMBINED
558 $resourceLoader = $this->getResourceLoader();
559 $filteredModules = [];
560 foreach ( $modules as $val ) {
561 $module = $resourceLoader->getModule( $val );
562 if ( $module instanceof RL\Module
563 && $module->getOrigin() <= $this->getAllowedModules( $type )
565 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
566 $this->warnModuleTargetFilter( $module->getName() );
567 continue;
569 $filteredModules[] = $val;
572 return $filteredModules;
575 private function warnModuleTargetFilter( $moduleName ) {
576 static $warnings = [];
577 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
578 return;
580 $warnings[$this->mTarget][$moduleName] = true;
581 $this->getResourceLoader()->getLogger()->debug(
582 'Module "{module}" not loadable on target "{target}".',
584 'module' => $moduleName,
585 'target' => $this->mTarget,
591 * Get the list of modules to include on this page
593 * @param bool $filter Whether to filter out insufficiently trustworthy modules
594 * @param string|null $position Unused
595 * @param string $param
596 * @param string $type
597 * @return string[] Array of module names
599 public function getModules( $filter = false, $position = null, $param = 'mModules',
600 $type = RL\Module::TYPE_COMBINED
602 $modules = array_values( array_unique( $this->$param ) );
603 return $filter
604 ? $this->filterModules( $modules, null, $type )
605 : $modules;
609 * Load one or more ResourceLoader modules on this page.
611 * @param string|array $modules Module name (string) or array of module names
613 public function addModules( $modules ) {
614 $this->mModules = array_merge( $this->mModules, (array)$modules );
618 * Get the list of style-only modules to load on this page.
620 * @param bool $filter
621 * @param string|null $position Unused
622 * @return string[] Array of module names
624 public function getModuleStyles( $filter = false, $position = null ) {
625 return $this->getModules( $filter, null, 'mModuleStyles',
626 RL\Module::TYPE_STYLES
631 * Load the styles of one or more style-only ResourceLoader modules on this page.
633 * Module styles added through this function will be loaded as a stylesheet,
634 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
635 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
637 * @param string|array $modules Module name (string) or array of module names
639 public function addModuleStyles( $modules ) {
640 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
644 * @return null|string ResourceLoader target
646 public function getTarget() {
647 return $this->mTarget;
651 * Sets ResourceLoader target for load.php links. If null, will be omitted
653 * @param string|null $target
655 public function setTarget( $target ) {
656 $this->mTarget = $target;
660 * Force the given Content object for the given page, for things like page preview.
661 * @see self::addContentOverrideCallback()
662 * @since 1.32
663 * @param LinkTarget|PageReference $target
664 * @param Content $content
666 public function addContentOverride( $target, Content $content ) {
667 if ( !$this->contentOverrides ) {
668 // Register a callback for $this->contentOverrides on the first call
669 $this->addContentOverrideCallback( function ( $target ) {
670 $key = $target->getNamespace() . ':' . $target->getDBkey();
671 return $this->contentOverrides[$key] ?? null;
672 } );
675 $key = $target->getNamespace() . ':' . $target->getDBkey();
676 $this->contentOverrides[$key] = $content;
680 * Add a callback for mapping from a Title to a Content object, for things
681 * like page preview.
682 * @see RL\Context::getContentOverrideCallback()
683 * @since 1.32
684 * @param callable $callback
686 public function addContentOverrideCallback( callable $callback ) {
687 $this->contentOverrideCallbacks[] = $callback;
691 * Add a class to the <html> element. This should rarely be used.
692 * Instead use OutputPage::addBodyClasses() if possible.
694 * @unstable Experimental since 1.35. Prefer OutputPage::addBodyClasses()
695 * @param string|string[] $classes One or more classes to add
697 public function addHtmlClasses( $classes ) {
698 $this->mAdditionalHtmlClasses = array_merge( $this->mAdditionalHtmlClasses, (array)$classes );
702 * Get an array of head items
704 * @return array
706 public function getHeadItemsArray() {
707 return $this->mHeadItems;
711 * Add or replace a head item to the output
713 * Whenever possible, use more specific options like ResourceLoader modules,
714 * OutputPage::addLink(), OutputPage::addMeta() and OutputPage::addFeedLink()
715 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
716 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
717 * This would be your very LAST fallback.
719 * @param string $name Item name
720 * @param string $value Raw HTML
722 public function addHeadItem( $name, $value ) {
723 $this->mHeadItems[$name] = $value;
727 * Add one or more head items to the output
729 * @since 1.28
730 * @param string|string[] $values Raw HTML
732 public function addHeadItems( $values ) {
733 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
737 * Check if the header item $name is already set
739 * @param string $name Item name
740 * @return bool
742 public function hasHeadItem( $name ) {
743 return isset( $this->mHeadItems[$name] );
747 * Add a class to the <body> element
749 * @since 1.30
750 * @param string|string[] $classes One or more classes to add
752 public function addBodyClasses( $classes ) {
753 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
757 * Set whether the output should only contain the body of the article,
758 * without any skin, sidebar, etc.
759 * Used e.g. when calling with "action=render".
761 * @param bool $only Whether to output only the body of the article
763 public function setArticleBodyOnly( $only ) {
764 $this->mArticleBodyOnly = $only;
768 * Return whether the output will contain only the body of the article
770 * @return bool
772 public function getArticleBodyOnly() {
773 return $this->mArticleBodyOnly;
777 * Set an additional output property
778 * @since 1.21
780 * @param string $name
781 * @param mixed $value
783 public function setProperty( $name, $value ) {
784 $this->mProperties[$name] = $value;
788 * Get an additional output property
789 * @since 1.21
791 * @param string $name
792 * @return mixed Property value or null if not found
794 public function getProperty( $name ) {
795 return $this->mProperties[$name] ?? null;
799 * checkLastModified tells the client to use the client-cached page if
800 * possible. If successful, the OutputPage is disabled so that
801 * any future call to OutputPage->output() have no effect.
803 * Side effect: sets mLastModified for Last-Modified header
805 * @param string $timestamp
807 * @return bool True if cache-ok headers was sent.
809 public function checkLastModified( $timestamp ) {
810 if ( !$timestamp || $timestamp == '19700101000000' ) {
811 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP" );
812 return false;
814 $config = $this->getConfig();
815 if ( !$config->get( MainConfigNames::CachePages ) ) {
816 wfDebug( __METHOD__ . ": CACHE DISABLED" );
817 return false;
820 $timestamp = wfTimestamp( TS_MW, $timestamp );
821 $modifiedTimes = [
822 'page' => $timestamp,
823 'user' => $this->getUser()->getTouched(),
824 'epoch' => $config->get( MainConfigNames::CacheEpoch )
826 if ( $config->get( MainConfigNames::UseCdn ) ) {
827 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
828 time(),
829 $config->get( MainConfigNames::CdnMaxAge )
830 ) );
832 $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this );
834 $maxModified = max( $modifiedTimes );
835 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
837 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
838 if ( $clientHeader === false ) {
839 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
840 return false;
843 # IE sends sizes after the date like this:
844 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
845 # this breaks strtotime().
846 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
848 // E_STRICT system time warnings
849 AtEase::suppressWarnings();
850 $clientHeaderTime = strtotime( $clientHeader );
851 AtEase::restoreWarnings();
852 if ( !$clientHeaderTime ) {
853 wfDebug( __METHOD__
854 . ": unable to parse the client's If-Modified-Since header: $clientHeader" );
855 return false;
857 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
859 # Make debug info
860 $info = '';
861 foreach ( $modifiedTimes as $name => $value ) {
862 if ( $info !== '' ) {
863 $info .= ', ';
865 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
868 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
869 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
870 wfDebug( __METHOD__ . ": effective Last-Modified: " .
871 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
872 if ( $clientHeaderTime < $maxModified ) {
873 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
874 return false;
877 # Not modified
878 # Give a 304 Not Modified response code and disable body output
879 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
880 // @phan-suppress-next-line PhanTypeMismatchArgumentInternal Scalar okay with php8.1
881 ini_set( 'zlib.output_compression', 0 );
882 $this->getRequest()->response()->statusHeader( 304 );
883 $this->sendCacheControl();
884 $this->disable();
886 // Don't output a compressed blob when using ob_gzhandler;
887 // it's technically against HTTP spec and seems to confuse
888 // Firefox when the response gets split over two packets.
889 wfResetOutputBuffers( false );
891 return true;
895 * @param int $reqTime Time of request (eg. now)
896 * @param int $maxAge Cache TTL in seconds
897 * @return int Timestamp
899 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
900 // Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
901 // because even if the wiki page content hasn't changed since, static
902 // resources may have changed (skin HTML, interface messages, urls, etc.)
903 // and must roll-over in a timely manner (T46570)
904 return $reqTime - $maxAge;
908 * Override the last modified timestamp
910 * @param string $timestamp New timestamp, in a format readable by
911 * wfTimestamp()
913 public function setLastModified( $timestamp ) {
914 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
918 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
920 * @param string $policy The literal string to output as the contents of
921 * the meta tag. Will be parsed according to the spec and output in
922 * standardized form.
924 public function setRobotPolicy( $policy ) {
925 $policy = Article::formatRobotPolicy( $policy );
927 if ( isset( $policy['index'] ) ) {
928 $this->setIndexPolicy( $policy['index'] );
930 if ( isset( $policy['follow'] ) ) {
931 $this->setFollowPolicy( $policy['follow'] );
936 * Get the current robot policy for the page as a string in the form
937 * <index policy>,<follow policy>.
939 * @return string
941 public function getRobotPolicy() {
942 return "{$this->mIndexPolicy},{$this->mFollowPolicy}";
946 * Format an array of robots options as a string of directives.
948 * @return string The robots policy options.
950 private function formatRobotsOptions(): string {
951 $options = $this->mRobotsOptions;
952 // Check if options array has any non-integer keys.
953 if ( count( array_filter( array_keys( $options ), 'is_string' ) ) > 0 ) {
954 // Robots meta tags can have directives that are single strings or
955 // have parameters that should be formatted like <directive>:<setting>.
956 // If the options keys are strings, format them accordingly.
957 // https://developers.google.com/search/docs/advanced/robots/robots_meta_tag
958 array_walk( $options, static function ( &$value, $key ) {
959 $value = is_string( $key ) ? "{$key}:{$value}" : "{$value}";
960 } );
962 return implode( ',', $options );
966 * Set the robots policy with options for the page.
968 * @since 1.38
969 * @param array $options An array of key-value pairs or a string
970 * to populate the robots meta tag content attribute as a string.
972 public function setRobotsOptions( array $options = [] ): void {
973 $this->mRobotsOptions = array_merge( $this->mRobotsOptions, $options );
977 * Get the robots policy content attribute for the page
978 * as a string in the form <index policy>,<follow policy>,<options>.
980 * @return string
982 private function getRobotsContent(): string {
983 $robotOptionString = $this->formatRobotsOptions();
984 $robotArgs = ( $this->mIndexPolicy === 'index' &&
985 $this->mFollowPolicy === 'follow' ) ?
986 [] :
988 $this->mIndexPolicy,
989 $this->mFollowPolicy,
991 if ( $robotOptionString ) {
992 $robotArgs[] = $robotOptionString;
994 return implode( ',', $robotArgs );
998 * Set the index policy for the page, but leave the follow policy un-
999 * touched.
1001 * @param string $policy Either 'index' or 'noindex'.
1003 public function setIndexPolicy( $policy ) {
1004 $policy = trim( $policy );
1005 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
1006 $this->mIndexPolicy = $policy;
1011 * Get the current index policy for the page as a string.
1013 * @return string
1015 public function getIndexPolicy() {
1016 return $this->mIndexPolicy;
1020 * Set the follow policy for the page, but leave the index policy un-
1021 * touched.
1023 * @param string $policy Either 'follow' or 'nofollow'.
1025 public function setFollowPolicy( $policy ) {
1026 $policy = trim( $policy );
1027 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
1028 $this->mFollowPolicy = $policy;
1033 * Get the current follow policy for the page as a string.
1035 * @return string
1037 public function getFollowPolicy() {
1038 return $this->mFollowPolicy;
1042 * "HTML title" means the contents of "<title>".
1043 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
1045 * @param string|Message $name
1047 public function setHTMLTitle( $name ) {
1048 if ( $name instanceof Message ) {
1049 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
1050 } else {
1051 $this->mHTMLtitle = $name;
1056 * Return the "HTML title", i.e. the content of the "<title>" tag.
1058 * @return string
1060 public function getHTMLTitle() {
1061 return $this->mHTMLtitle;
1065 * Set $mRedirectedFrom, the page which redirected us to the current page.
1067 * @param PageReference $t
1069 public function setRedirectedFrom( PageReference $t ) {
1070 $this->mRedirectedFrom = $t;
1074 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
1075 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
1076 * but not bad tags like \<script\>. This function automatically sets
1077 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
1078 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
1079 * good tags like \<i\> will be dropped entirely.
1081 * @param string|Message $name
1082 * @param-taint $name tainted
1083 * Phan-taint-check gets very confused by $name being either a string or a Message
1085 public function setPageTitle( $name ) {
1086 if ( $name instanceof Message ) {
1087 $name = $name->setContext( $this->getContext() )->text();
1090 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
1091 # but leave "<i>foobar</i>" alone
1092 $nameWithTags = Sanitizer::removeSomeTags( $name );
1093 $this->mPageTitle = $nameWithTags;
1095 # change "<i>foo&amp;bar</i>" to "foo&bar"
1096 $this->setHTMLTitle(
1097 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer::stripAllTags( $nameWithTags ) )
1098 ->inContentLanguage()
1103 * Return the "page title", i.e. the content of the \<h1\> tag.
1105 * @return string
1107 public function getPageTitle() {
1108 return $this->mPageTitle;
1112 * Same as page title but only contains name of the page, not any other text.
1114 * @since 1.32
1115 * @param string $html Page title text.
1116 * @see OutputPage::setPageTitle
1118 public function setDisplayTitle( $html ) {
1119 $this->displayTitle = $html;
1123 * Returns page display title.
1125 * Performs some normalization, but this not as strict the magic word.
1127 * @since 1.32
1128 * @return string HTML
1130 public function getDisplayTitle() {
1131 $html = $this->displayTitle;
1132 if ( $html === null ) {
1133 return htmlspecialchars( $this->getTitle()->getPrefixedText(), ENT_NOQUOTES );
1136 return Sanitizer::removeSomeTags( $html );
1140 * Returns page display title without namespace prefix if possible.
1142 * This method is unreliable and best avoided. (T314399)
1144 * @since 1.32
1145 * @return string HTML
1147 public function getUnprefixedDisplayTitle() {
1148 $service = MediaWikiServices::getInstance();
1149 $languageConverter = $service->getLanguageConverterFactory()
1150 ->getLanguageConverter( $service->getContentLanguage() );
1151 $text = $this->getDisplayTitle();
1153 // Create a regexp with matching groups as placeholders for the namespace, separator and main text
1154 $pageTitleRegexp = "/^" . str_replace(
1155 preg_quote( '(.+?)', '/' ),
1156 '(.+?)',
1157 preg_quote( Parser::formatPageTitle( '(.+?)', '(.+?)', '(.+?)' ), '/' )
1158 ) . "$/";
1159 $matches = [];
1160 if ( preg_match( $pageTitleRegexp, $text, $matches ) ) {
1161 // The regexp above could be manipulated by malicious user input,
1162 // sanitize the result just in case
1163 return Sanitizer::removeSomeTags( $matches[3] );
1166 $nsPrefix = $languageConverter->convertNamespace(
1167 $this->getTitle()->getNamespace()
1168 ) . ':';
1169 $prefix = preg_quote( $nsPrefix, '/' );
1171 return preg_replace( "/^$prefix/i", '', $text );
1175 * Set the Title object to use
1177 * @param PageReference $t
1179 public function setTitle( PageReference $t ) {
1180 $t = Title::castFromPageReference( $t );
1182 // @phan-suppress-next-next-line PhanUndeclaredMethod
1183 // @fixme Not all implementations of IContextSource have this method!
1184 $this->getContext()->setTitle( $t );
1188 * Replace the subtitle with $str
1190 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1192 public function setSubtitle( $str ) {
1193 $this->clearSubtitle();
1194 $this->addSubtitle( $str );
1198 * Add $str to the subtitle
1200 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1202 public function addSubtitle( $str ) {
1203 if ( $str instanceof Message ) {
1204 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1205 } else {
1206 $this->mSubtitle[] = $str;
1211 * Build message object for a subtitle containing a backlink to a page
1213 * @since 1.25
1214 * @param PageReference $page Title to link to
1215 * @param array $query Array of additional parameters to include in the link
1216 * @return Message
1218 public static function buildBacklinkSubtitle( PageReference $page, $query = [] ) {
1219 if ( $page instanceof PageRecord || $page instanceof Title ) {
1220 // Callers will typically have a PageRecord
1221 if ( $page->isRedirect() ) {
1222 $query['redirect'] = 'no';
1224 } elseif ( $page->getNamespace() !== NS_SPECIAL ) {
1225 // We don't know whether it's a redirect, so add the parameter, just to be sure.
1226 $query['redirect'] = 'no';
1229 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1230 return wfMessage( 'backlinksubtitle' )
1231 ->rawParams( $linkRenderer->makeLink( $page, null, [], $query ) );
1235 * Add a subtitle containing a backlink to a page
1237 * @param PageReference $title Title to link to
1238 * @param array $query Array of additional parameters to include in the link
1240 public function addBacklinkSubtitle( PageReference $title, $query = [] ) {
1241 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1245 * Clear the subtitles
1247 public function clearSubtitle() {
1248 $this->mSubtitle = [];
1252 * @return string
1254 public function getSubtitle() {
1255 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1259 * Set the page as printable, i.e. it'll be displayed with all
1260 * print styles included
1262 public function setPrintable() {
1263 $this->mPrintable = true;
1267 * Return whether the page is "printable"
1269 * @return bool
1271 public function isPrintable() {
1272 return $this->mPrintable;
1276 * Disable output completely, i.e. calling output() will have no effect
1278 public function disable() {
1279 $this->mDoNothing = true;
1283 * Return whether the output will be completely disabled
1285 * @return bool
1287 public function isDisabled() {
1288 return $this->mDoNothing;
1292 * Show an "add new section" link?
1294 * @return bool
1296 public function showNewSectionLink() {
1297 return $this->mNewSectionLink;
1301 * Forcibly hide the new section link?
1303 * @return bool
1305 public function forceHideNewSectionLink() {
1306 return $this->mHideNewSectionLink;
1310 * Add or remove feed links in the page header
1311 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1312 * for the new version
1313 * @see addFeedLink()
1315 * @param bool $show True: add default feeds, false: remove all feeds
1317 public function setSyndicated( $show = true ) {
1318 if ( $show ) {
1319 $this->setFeedAppendQuery( false );
1320 } else {
1321 $this->mFeedLinks = [];
1326 * Return effective list of advertised feed types
1327 * @see addFeedLink()
1329 * @return string[] Array of feed type names ( 'rss', 'atom' )
1331 protected function getAdvertisedFeedTypes() {
1332 if ( $this->getConfig()->get( MainConfigNames::Feed ) ) {
1333 return $this->getConfig()->get( MainConfigNames::AdvertisedFeedTypes );
1334 } else {
1335 return [];
1340 * Add default feeds to the page header
1341 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1342 * for the new version
1343 * @see addFeedLink()
1345 * @param string|false $val Query to append to feed links or false to output
1346 * default links
1348 public function setFeedAppendQuery( $val ) {
1349 $this->mFeedLinks = [];
1351 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1352 $query = "feed=$type";
1353 if ( is_string( $val ) ) {
1354 $query .= '&' . $val;
1356 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1361 * Add a feed link to the page header
1363 * @param string $format Feed type, should be a key of $wgFeedClasses
1364 * @param string $href URL
1366 public function addFeedLink( $format, $href ) {
1367 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1368 $this->mFeedLinks[$format] = $href;
1373 * Should we output feed links for this page?
1374 * @return bool
1376 public function isSyndicated() {
1377 return count( $this->mFeedLinks ) > 0;
1381 * Return URLs for each supported syndication format for this page.
1382 * @return array Associating format keys with URLs
1384 public function getSyndicationLinks() {
1385 return $this->mFeedLinks;
1389 * Will currently always return null
1391 * @return null
1393 public function getFeedAppendQuery() {
1394 return $this->mFeedLinksAppendQuery;
1398 * Set whether the displayed content is related to the source of the
1399 * corresponding article on the wiki
1400 * Setting true will cause the change "article related" toggle to true
1402 * @param bool $newVal
1404 public function setArticleFlag( $newVal ) {
1405 $this->mIsArticle = $newVal;
1406 if ( $newVal ) {
1407 $this->mIsArticleRelated = $newVal;
1412 * Return whether the content displayed page is related to the source of
1413 * the corresponding article on the wiki
1415 * @return bool
1417 public function isArticle() {
1418 return $this->mIsArticle;
1422 * Set whether this page is related an article on the wiki
1423 * Setting false will cause the change of "article flag" toggle to false
1425 * @param bool $newVal
1427 public function setArticleRelated( $newVal ) {
1428 $this->mIsArticleRelated = $newVal;
1429 if ( !$newVal ) {
1430 $this->mIsArticle = false;
1435 * Return whether this page is related an article on the wiki
1437 * @return bool
1439 public function isArticleRelated() {
1440 return $this->mIsArticleRelated;
1444 * Set whether the standard copyright should be shown for the current page.
1446 * @param bool $hasCopyright
1448 public function setCopyright( $hasCopyright ) {
1449 $this->mHasCopyright = $hasCopyright;
1453 * Return whether the standard copyright should be shown for the current page.
1454 * By default, it is true for all articles but other pages
1455 * can signal it by using setCopyright( true ).
1457 * Used by SkinTemplate to decided whether to show the copyright.
1459 * @return bool
1461 public function showsCopyright() {
1462 return $this->isArticle() || $this->mHasCopyright;
1466 * Add new language links
1468 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1469 * (e.g. 'fr:Test page')
1471 public function addLanguageLinks( array $newLinkArray ) {
1472 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1476 * Reset the language links and add new language links
1478 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1479 * (e.g. 'fr:Test page')
1481 public function setLanguageLinks( array $newLinkArray ) {
1482 $this->mLanguageLinks = $newLinkArray;
1486 * Get the list of language links
1488 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1490 public function getLanguageLinks() {
1491 return $this->mLanguageLinks;
1495 * Add an array of categories, with names in the keys
1497 * @param array $categories Mapping category name => sort key
1499 public function addCategoryLinks( array $categories ) {
1500 if ( !$categories ) {
1501 return;
1504 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1506 # Set all the values to 'normal'.
1507 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1508 $pageData = [];
1510 # Mark hidden categories
1511 foreach ( $res as $row ) {
1512 if ( isset( $row->pp_value ) ) {
1513 $categories[$row->page_title] = 'hidden';
1515 // Page exists, cache results
1516 if ( isset( $row->page_id ) ) {
1517 $pageData[$row->page_title] = $row;
1521 # Add the remaining categories to the skin
1522 if ( $this->getHookRunner()->onOutputPageMakeCategoryLinks(
1523 $this, $categories, $this->mCategoryLinks )
1525 $services = MediaWikiServices::getInstance();
1526 $linkRenderer = $services->getLinkRenderer();
1527 $languageConverter = $services->getLanguageConverterFactory()
1528 ->getLanguageConverter( $services->getContentLanguage() );
1529 foreach ( $categories as $category => $type ) {
1530 // array keys will cast numeric category names to ints, so cast back to string
1531 $category = (string)$category;
1532 $origcategory = $category;
1533 if ( array_key_exists( $category, $pageData ) ) {
1534 $title = Title::newFromRow( $pageData[$category] );
1535 } else {
1536 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1538 if ( !$title ) {
1539 continue;
1541 $languageConverter->findVariantLink( $category, $title, true );
1543 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1544 continue;
1546 $text = $languageConverter->convertHtml( $title->getText() );
1547 $this->mCategories[$type][] = $title->getText();
1548 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1554 * @param array $categories
1555 * @return bool|IResultWrapper
1557 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1558 # Add the links to a LinkBatch
1559 $arr = [ NS_CATEGORY => $categories ];
1560 $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
1561 $lb = $linkBatchFactory->newLinkBatch();
1562 $lb->setArray( $arr );
1564 # Fetch existence plus the hiddencat property
1565 $dbr = wfGetDB( DB_REPLICA );
1566 $fields = array_merge(
1567 LinkCache::getSelectFields(),
1568 [ 'pp_value' ]
1571 $res = $dbr->newSelectQueryBuilder()
1572 ->select( $fields )
1573 ->from( 'page' )
1574 ->leftJoin( 'page_props', null, [
1575 'pp_propname' => 'hiddencat',
1576 'pp_page = page_id',
1578 ->where( $lb->constructSet( 'page', $dbr ) )
1579 ->caller( __METHOD__ )
1580 ->fetchResultSet();
1582 # Add the results to the link cache
1583 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1584 $lb->addResultToCache( $linkCache, $res );
1586 return $res;
1590 * Reset the category links (but not the category list) and add $categories
1592 * @param array $categories Mapping category name => sort key
1594 public function setCategoryLinks( array $categories ) {
1595 $this->mCategoryLinks = [];
1596 $this->addCategoryLinks( $categories );
1600 * Get the list of category links, in a 2-D array with the following format:
1601 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1602 * hidden categories) and $link a HTML fragment with a link to the category
1603 * page
1605 * @return string[][]
1606 * @return-taint none
1608 public function getCategoryLinks() {
1609 return $this->mCategoryLinks;
1613 * Get the list of category names this page belongs to.
1615 * @param string $type The type of categories which should be returned. Possible values:
1616 * * all: all categories of all types
1617 * * hidden: only the hidden categories
1618 * * normal: all categories, except hidden categories
1619 * @return string[]
1621 public function getCategories( $type = 'all' ) {
1622 if ( $type === 'all' ) {
1623 $allCategories = [];
1624 foreach ( $this->mCategories as $categories ) {
1625 $allCategories = array_merge( $allCategories, $categories );
1627 return $allCategories;
1629 if ( !isset( $this->mCategories[$type] ) ) {
1630 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1632 return $this->mCategories[$type];
1636 * Add an array of indicators, with their identifiers as array
1637 * keys and HTML contents as values.
1639 * In case of duplicate keys, existing values are overwritten.
1641 * @note External code which calls this method should ensure that
1642 * any indicators sourced from parsed wikitext are wrapped with
1643 * the appropriate class; see note in ::getIndicators().
1645 * @param string[] $indicators
1646 * @since 1.25
1648 public function setIndicators( array $indicators ) {
1649 $this->mIndicators = $indicators + $this->mIndicators;
1650 // Keep ordered by key
1651 ksort( $this->mIndicators );
1655 * Get the indicators associated with this page.
1657 * The array will be internally ordered by item keys.
1659 * @return string[] Keys: identifiers, values: HTML contents
1660 * @since 1.25
1662 public function getIndicators() {
1663 // Note that some -- but not all -- indicators will be wrapped
1664 // with a class appropriate for user-generated wikitext content
1665 // (usually .mw-parser-output). The exceptions would be an
1666 // indicator added via ::addHelpLink() below, which adds content
1667 // which don't come from the parser and is not user-generated;
1668 // and any indicators added by extensions which may call
1669 // OutputPage::setIndicators() directly. In the latter case the
1670 // caller is responsible for wrapping any parser-generated
1671 // indicators.
1672 return $this->mIndicators;
1676 * Adds help link with an icon via page indicators.
1677 * Link target can be overridden by a local message containing a wikilink:
1678 * the message key is: lowercase action or special page name + '-helppage'.
1679 * @param string $to Target MediaWiki.org page title or encoded URL.
1680 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1681 * @since 1.25
1683 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1684 $this->addModuleStyles( 'mediawiki.helplink' );
1685 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1687 if ( $overrideBaseUrl ) {
1688 $helpUrl = $to;
1689 } else {
1690 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1691 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1694 $link = Html::rawElement(
1695 'a',
1697 'href' => $helpUrl,
1698 'target' => '_blank',
1699 'class' => 'mw-helplink',
1701 $text
1704 // See note in ::getIndicators() above -- unlike wikitext-generated
1705 // indicators which come from ParserOutput, this indicator will not
1706 // be wrapped.
1707 $this->setIndicators( [ 'mw-helplink' => $link ] );
1711 * Do not allow scripts which can be modified by wiki users to load on this page;
1712 * only allow scripts bundled with, or generated by, the software.
1713 * Site-wide styles are controlled by a config setting, since they can be
1714 * used to create a custom skin/theme, but not user-specific ones.
1716 * @todo this should be given a more accurate name
1718 public function disallowUserJs() {
1719 $this->reduceAllowedModules(
1720 RL\Module::TYPE_SCRIPTS,
1721 RL\Module::ORIGIN_CORE_INDIVIDUAL
1724 // Site-wide styles are controlled by a config setting, see T73621
1725 // for background on why. User styles are never allowed.
1726 if ( $this->getConfig()->get( MainConfigNames::AllowSiteCSSOnRestrictedPages ) ) {
1727 $styleOrigin = RL\Module::ORIGIN_USER_SITEWIDE;
1728 } else {
1729 $styleOrigin = RL\Module::ORIGIN_CORE_INDIVIDUAL;
1731 $this->reduceAllowedModules(
1732 RL\Module::TYPE_STYLES,
1733 $styleOrigin
1738 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1739 * @see RL\Module::$origin
1740 * @param string $type RL\Module TYPE_ constant
1741 * @return int Module ORIGIN_ class constant
1743 public function getAllowedModules( $type ) {
1744 if ( $type == RL\Module::TYPE_COMBINED ) {
1745 return min( array_values( $this->mAllowedModules ) );
1746 } else {
1747 return $this->mAllowedModules[$type] ?? RL\Module::ORIGIN_ALL;
1752 * Limit the highest level of CSS/JS untrustworthiness allowed.
1754 * If passed the same or a higher level than the current level of untrustworthiness set, the
1755 * level will remain unchanged.
1757 * @param string $type
1758 * @param int $level RL\Module class constant
1760 public function reduceAllowedModules( $type, $level ) {
1761 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1765 * Prepend $text to the body HTML
1767 * @param string $text HTML
1769 public function prependHTML( $text ) {
1770 $this->mBodytext = $text . $this->mBodytext;
1774 * Append $text to the body HTML
1776 * @param string $text HTML
1778 public function addHTML( $text ) {
1779 $this->mBodytext .= $text;
1783 * Shortcut for adding an Html::element via addHTML.
1785 * @since 1.19
1787 * @param string $element
1788 * @param array $attribs
1789 * @param string $contents
1791 public function addElement( $element, array $attribs = [], $contents = '' ) {
1792 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1796 * Clear the body HTML
1798 public function clearHTML() {
1799 $this->mBodytext = '';
1803 * Get the body HTML
1805 * @return string HTML
1807 public function getHTML() {
1808 return $this->mBodytext;
1812 * Get/set the ParserOptions object to use for wikitext parsing
1814 * @return ParserOptions
1815 * @suppress PhanUndeclaredProperty For isBogus
1817 public function parserOptions() {
1818 if ( !$this->mParserOptions ) {
1819 if ( !$this->getUser()->isSafeToLoad() ) {
1820 // Context user isn't unstubbable yet, so don't try to get a
1821 // ParserOptions for it. And don't cache this ParserOptions
1822 // either.
1823 $po = ParserOptions::newFromAnon();
1824 $po->setAllowUnsafeRawHtml( false );
1825 $po->isBogus = true;
1826 return $po;
1829 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1830 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1833 return $this->mParserOptions;
1837 * Set the revision ID which will be seen by the wiki text parser
1838 * for things such as embedded {{REVISIONID}} variable use.
1840 * @param int|null $revid A positive integer, or null
1841 * @return mixed Previous value
1843 public function setRevisionId( $revid ) {
1844 $val = $revid === null ? null : intval( $revid );
1845 return wfSetVar( $this->mRevisionId, $val, true );
1849 * Get the displayed revision ID
1851 * @return int|null
1853 public function getRevisionId() {
1854 return $this->mRevisionId;
1858 * Set whether the revision displayed (as set in ::setRevisionId())
1859 * is the latest revision of the page.
1861 * @param bool $isCurrent
1863 public function setRevisionIsCurrent( bool $isCurrent ): void {
1864 $this->mRevisionIsCurrent = $isCurrent;
1868 * Whether the revision displayed is the latest revision of the page
1870 * @since 1.34
1871 * @return bool
1873 public function isRevisionCurrent(): bool {
1874 return $this->mRevisionId == 0 || (
1875 $this->mRevisionIsCurrent ?? (
1876 $this->mRevisionId == $this->getTitle()->getLatestRevID()
1882 * Set the timestamp of the revision which will be displayed. This is used
1883 * to avoid a extra DB call in Skin::lastModified().
1885 * @param string|null $timestamp
1886 * @return mixed Previous value
1888 public function setRevisionTimestamp( $timestamp ) {
1889 return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
1893 * Get the timestamp of displayed revision.
1894 * This will be null if not filled by setRevisionTimestamp().
1896 * @return string|null
1898 public function getRevisionTimestamp() {
1899 return $this->mRevisionTimestamp;
1903 * Set the displayed file version
1905 * @param File|null $file
1906 * @return mixed Previous value
1908 public function setFileVersion( $file ) {
1909 $val = null;
1910 if ( $file instanceof File && $file->exists() ) {
1911 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1913 return wfSetVar( $this->mFileVersion, $val, true );
1917 * Get the displayed file version
1919 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1921 public function getFileVersion() {
1922 return $this->mFileVersion;
1926 * Get the templates used on this page
1928 * @return array (namespace => dbKey => revId)
1929 * @since 1.18
1931 public function getTemplateIds() {
1932 return $this->mTemplateIds;
1936 * Get the files used on this page
1938 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1939 * @since 1.18
1941 public function getFileSearchOptions() {
1942 return $this->mImageTimeKeys;
1946 * Convert wikitext *in the user interface language* to HTML and
1947 * add it to the buffer. The result will not be
1948 * language-converted, as user interface messages are already
1949 * localized into a specific variant. Assumes that the current
1950 * page title will be used if optional $title is not
1951 * provided. Output will be tidy.
1953 * @param string $text Wikitext in the user interface language
1954 * @param bool $linestart Is this the start of a line? (Defaults to true)
1955 * @param PageReference|null $title Optional title to use; default of `null`
1956 * means use current page title.
1957 * @throws MWException if $title is not provided and OutputPage::getTitle()
1958 * is null
1959 * @since 1.32
1961 public function addWikiTextAsInterface(
1962 $text, $linestart = true, PageReference $title = null
1964 if ( $title === null ) {
1965 $title = $this->getTitle();
1967 if ( !$title ) {
1968 throw new MWException( 'Title is null' );
1970 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1974 * Convert wikitext *in the user interface language* to HTML and
1975 * add it to the buffer with a `<div class="$wrapperClass">`
1976 * wrapper. The result will not be language-converted, as user
1977 * interface messages as already localized into a specific
1978 * variant. The $text will be parsed in start-of-line context.
1979 * Output will be tidy.
1981 * @param string $wrapperClass The class attribute value for the <div>
1982 * wrapper in the output HTML
1983 * @param string $text Wikitext in the user interface language
1984 * @since 1.32
1986 public function wrapWikiTextAsInterface(
1987 $wrapperClass, $text
1989 $this->addWikiTextTitleInternal(
1990 $text, $this->getTitle(),
1991 /*linestart*/true, /*interface*/true,
1992 $wrapperClass
1997 * Convert wikitext *in the page content language* to HTML and add
1998 * it to the buffer. The result with be language-converted to the
1999 * user's preferred variant. Assumes that the current page title
2000 * will be used if optional $title is not provided. Output will be
2001 * tidy.
2003 * @param string $text Wikitext in the page content language
2004 * @param bool $linestart Is this the start of a line? (Defaults to true)
2005 * @param PageReference|null $title Optional title to use; default of `null`
2006 * means use current page title.
2007 * @throws MWException if $title is not provided and OutputPage::getTitle()
2008 * is null
2009 * @since 1.32
2011 public function addWikiTextAsContent(
2012 $text, $linestart = true, PageReference $title = null
2014 if ( $title === null ) {
2015 $title = $this->getTitle();
2017 if ( !$title ) {
2018 throw new MWException( 'Title is null' );
2020 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
2024 * Add wikitext with a custom Title object.
2025 * Output is unwrapped.
2027 * @param string $text Wikitext
2028 * @param PageReference $title
2029 * @param bool $linestart Is this the start of a line?@param
2030 * @param bool $interface Whether it is an interface message
2031 * (for example disables conversion)
2032 * @param string|null $wrapperClass if not empty, wraps the output in
2033 * a `<div class="$wrapperClass">`
2035 private function addWikiTextTitleInternal(
2036 $text, PageReference $title, $linestart, $interface, $wrapperClass = null
2038 $parserOutput = $this->parseInternal(
2039 $text, $title, $linestart, $interface
2042 $this->addParserOutput( $parserOutput, [
2043 'enableSectionEditLinks' => false,
2044 'wrapperDivClass' => $wrapperClass ?? '',
2045 ] );
2049 * Adds sections to OutputPage from ParserOutput
2050 * @param array $sections
2051 * @internal For use by Article.php
2053 public function setSections( array $sections ) {
2054 $this->mSections = $sections;
2058 * @internal For usage in Skin::getSectionsData() only.
2059 * @return array Array of sections.
2060 * Empty if OutputPage::setSections() has not been called.
2062 public function getSections(): array {
2063 return $this->mSections;
2067 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
2068 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
2069 * and so on. It does *not* include section information.
2071 * @since 1.24
2072 * @param ParserOutput $parserOutput
2074 public function addParserOutputMetadata( ParserOutput $parserOutput ) {
2075 // T301020 This should eventually use the standard "merge ParserOutput"
2076 // function between $parserOutput and $this->metadata.
2077 $this->mLanguageLinks =
2078 array_merge( $this->mLanguageLinks, $parserOutput->getLanguageLinks() );
2079 $this->addCategoryLinks( $parserOutput->getCategories() );
2081 // Parser-generated indicators get wrapped like other parser output.
2082 $wrapClass = $parserOutput->getWrapperDivClass();
2083 $result = [];
2084 foreach ( $parserOutput->getIndicators() as $name => $html ) {
2085 if ( $html !== '' && $wrapClass !== '' ) {
2086 $html = Html::rawElement( 'div', [ 'class' => $wrapClass ], $html );
2088 $result[$name] = $html;
2090 $this->setIndicators( $result );
2092 // FIXME: Best practice is for OutputPage to be an accumulator, as
2093 // addParserOutputMetadata() may be called multiple times, but the
2094 // following lines overwrite any previous data. These should
2095 // be migrated to an injection pattern. (T301020, T300979)
2096 $this->mNewSectionLink = $parserOutput->getNewSection();
2097 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
2098 $this->mNoGallery = $parserOutput->getNoGallery();
2100 if ( !$parserOutput->isCacheable() ) {
2101 $this->disableClientCache();
2103 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
2104 $this->addModules( $parserOutput->getModules() );
2105 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2106 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2107 $this->mPreventClickjacking = $this->mPreventClickjacking
2108 || $parserOutput->getPreventClickjacking();
2109 $scriptSrcs = $parserOutput->getExtraCSPScriptSrcs();
2110 foreach ( $scriptSrcs as $src ) {
2111 $this->getCSP()->addScriptSrc( $src );
2113 $defaultSrcs = $parserOutput->getExtraCSPDefaultSrcs();
2114 foreach ( $defaultSrcs as $src ) {
2115 $this->getCSP()->addDefaultSrc( $src );
2117 $styleSrcs = $parserOutput->getExtraCSPStyleSrcs();
2118 foreach ( $styleSrcs as $src ) {
2119 $this->getCSP()->addStyleSrc( $src );
2122 // If $wgImagePreconnect is true, and if the output contains images, give the user-agent
2123 // a hint about a remote hosts from which images may be served. Launched in T123582.
2124 if ( $this->getConfig()->get( MainConfigNames::ImagePreconnect ) && count( $parserOutput->getImages() ) ) {
2125 $preconnect = [];
2126 // Optimization: Instead of processing each image, assume that wikis either serve both
2127 // foreign and local from the same remote hostname (e.g. public wikis at WMF), or that
2128 // foreign images are common enough to be worth the preconnect (e.g. private wikis).
2129 $repoGroup = MediaWikiServices::getInstance()->getRepoGroup();
2130 $repoGroup->forEachForeignRepo( static function ( $repo ) use ( &$preconnect ) {
2131 $preconnect[] = $repo->getZoneUrl( 'thumb' );
2132 } );
2133 // Consider both foreign and local repos. While LocalRepo by default uses a relative
2134 // path on the same domain, wiki farms may configure it to use a dedicated hostname.
2135 $preconnect[] = $repoGroup->getLocalRepo()->getZoneUrl( 'thumb' );
2136 foreach ( $preconnect as $url ) {
2137 $host = parse_url( $url, PHP_URL_HOST );
2138 // It is expected that file URLs are often path-only, without hostname (T317329).
2139 if ( $host ) {
2140 $this->addLink( [ 'rel' => 'preconnect', 'href' => '//' . $host ] );
2141 break;
2146 // Template versioning...
2147 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
2148 if ( isset( $this->mTemplateIds[$ns] ) ) {
2149 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
2150 } else {
2151 $this->mTemplateIds[$ns] = $dbks;
2154 // File versioning...
2155 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
2156 $this->mImageTimeKeys[$dbk] = $data;
2159 // Hooks registered in the object
2160 // Deprecated! See T292321; should be done in the OutputPageParserOutput
2161 // hook instead.
2162 $parserOutputHooks = $this->getConfig()->get( MainConfigNames::ParserOutputHooks );
2163 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
2164 [ $hookName, $data ] = $hookInfo;
2165 if ( isset( $parserOutputHooks[$hookName] ) ) {
2166 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
2170 // Enable OOUI if requested via ParserOutput
2171 if ( $parserOutput->getEnableOOUI() ) {
2172 $this->enableOOUI();
2175 // Include parser limit report
2176 // FIXME: This should append, rather than overwrite, or else this
2177 // data should be injected into the OutputPage like is done for the
2178 // other page-level things (like OutputPage::setSections()).
2179 if ( !$this->limitReportJSData ) {
2180 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
2183 // Link flags are ignored for now, but may in the future be
2184 // used to mark individual language links.
2185 $linkFlags = [];
2186 $this->getHookRunner()->onLanguageLinks( $this->getTitle(), $this->mLanguageLinks, $linkFlags );
2188 $this->getHookRunner()->onOutputPageParserOutput( $this, $parserOutput );
2190 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2191 // so that extensions may modify ParserOutput to toggle TOC.
2192 // This cannot be moved to addParserOutputText because that is not
2193 // called by EditPage for Preview.
2195 // T294950/T293513: ParserOutput::getTOCHTML() will be
2196 // replaced by ParserOutput::getSections(), and
2197 // ParserOutputFlags::SHOW_TOC is used to indicate whether the TOC
2198 // should be shown (or hidden) in the output.
2199 $this->mEnableTOC = $this->mEnableTOC ||
2200 $parserOutput->getOutputFlag( ParserOutputFlags::SHOW_TOC );
2201 // But extensions used to be able to modify ParserOutput::setTOCHTML()
2202 // to toggle TOC in the OutputPageParserOutput hook; so for backward
2203 // compatibility check to see if that happened.
2204 $isTocPresent = (bool)$parserOutput->getTOCHTML();
2205 if ( $isTocPresent && !$this->mEnableTOC ) {
2206 // Eventually we'll emit a deprecation message here (T293513)
2207 $this->mEnableTOC = true;
2212 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2213 * ParserOutput object, without any other metadata.
2215 * @since 1.24
2216 * @param ParserOutput $parserOutput
2217 * @param array $poOptions Options to ParserOutput::getText()
2219 public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
2220 $this->addParserOutputText( $parserOutput, $poOptions );
2222 $this->addModules( $parserOutput->getModules() );
2223 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2225 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2229 * Add the HTML associated with a ParserOutput object, without any metadata.
2231 * @since 1.24
2232 * @param ParserOutput $parserOutput
2233 * @param array $poOptions Options to ParserOutput::getText()
2235 public function addParserOutputText( ParserOutput $parserOutput, $poOptions = [] ) {
2236 // Add default options from the skin
2237 $skin = $this->getSkin();
2238 $skinOptions = $skin->getOptions();
2239 $poOptions += [
2240 'skin' => $skin,
2241 'injectTOC' => $skinOptions['toc'],
2243 $text = $parserOutput->getText( $poOptions );
2244 $this->getHookRunner()->onOutputPageBeforeHTML( $this, $text );
2245 $this->addHTML( $text );
2249 * Add everything from a ParserOutput object.
2251 * @param ParserOutput $parserOutput
2252 * @param array $poOptions Options to ParserOutput::getText()
2254 public function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
2255 $this->addParserOutputMetadata( $parserOutput );
2256 $this->addParserOutputText( $parserOutput, $poOptions );
2260 * Add the output of a QuickTemplate to the output buffer
2262 * @param QuickTemplate &$template
2264 public function addTemplate( &$template ) {
2265 $this->addHTML( $template->getHTML() );
2269 * Parse wikitext *in the page content language* and return the HTML.
2270 * The result will be language-converted to the user's preferred variant.
2271 * Output will be tidy.
2273 * @param string $text Wikitext in the page content language
2274 * @param bool $linestart Is this the start of a line? (Defaults to true)
2275 * @throws MWException
2276 * @return string HTML
2277 * @since 1.32
2279 public function parseAsContent( $text, $linestart = true ) {
2280 return $this->parseInternal(
2281 $text, $this->getTitle(), $linestart, /*interface*/false
2282 )->getText( [
2283 'enableSectionEditLinks' => false,
2284 'wrapperDivClass' => ''
2285 ] );
2289 * Parse wikitext *in the user interface language* and return the HTML.
2290 * The result will not be language-converted, as user interface messages
2291 * are already localized into a specific variant.
2292 * Output will be tidy.
2294 * @param string $text Wikitext in the user interface language
2295 * @param bool $linestart Is this the start of a line? (Defaults to true)
2296 * @throws MWException
2297 * @return string HTML
2298 * @since 1.32
2300 public function parseAsInterface( $text, $linestart = true ) {
2301 return $this->parseInternal(
2302 $text, $this->getTitle(), $linestart, /*interface*/true
2303 )->getText( [
2304 'enableSectionEditLinks' => false,
2305 'wrapperDivClass' => ''
2306 ] );
2310 * Parse wikitext *in the user interface language*, strip
2311 * paragraph wrapper, and return the HTML.
2312 * The result will not be language-converted, as user interface messages
2313 * are already localized into a specific variant.
2314 * Output will be tidy. Outer paragraph wrapper will only be stripped
2315 * if the result is a single paragraph.
2317 * @param string $text Wikitext in the user interface language
2318 * @param bool $linestart Is this the start of a line? (Defaults to true)
2319 * @throws MWException
2320 * @return string HTML
2321 * @since 1.32
2323 public function parseInlineAsInterface( $text, $linestart = true ) {
2324 return Parser::stripOuterParagraph(
2325 $this->parseAsInterface( $text, $linestart )
2330 * Parse wikitext and return the HTML (internal implementation helper)
2332 * @param string $text
2333 * @param PageReference $title The title to use
2334 * @param bool $linestart Is this the start of a line?
2335 * @param bool $interface Use interface language (instead of content language) while parsing
2336 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2337 * LanguageConverter.
2338 * @throws MWException
2339 * @return ParserOutput
2341 private function parseInternal( $text, $title, $linestart, $interface ) {
2342 if ( $title === null ) {
2343 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
2346 $popts = $this->parserOptions();
2348 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2350 $parserOutput = MediaWikiServices::getInstance()->getParserFactory()->getInstance()
2351 ->parse(
2352 $text, $title, $popts,
2353 $linestart, true, $this->mRevisionId
2356 $popts->setInterfaceMessage( $oldInterface );
2358 return $parserOutput;
2362 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2364 * @param int $maxage Maximum cache time on the CDN, in seconds.
2366 public function setCdnMaxage( $maxage ) {
2367 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2371 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2372 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2373 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2374 * $maxage.
2376 * @param int $maxage Maximum cache time on the CDN, in seconds
2377 * @since 1.27
2379 public function lowerCdnMaxage( $maxage ) {
2380 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2381 $this->setCdnMaxage( $this->mCdnMaxage );
2385 * Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
2387 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2388 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2389 * TTL is 90% of the age of the object, subject to the min and max.
2391 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2392 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2393 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2394 * @since 1.28
2396 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2397 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2398 $maxTTL = $maxTTL ?: $this->getConfig()->get( MainConfigNames::CdnMaxAge );
2400 if ( $mtime === null || $mtime === false ) {
2401 return; // entity does not exist
2404 $age = MWTimestamp::time() - (int)wfTimestamp( TS_UNIX, $mtime );
2405 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2406 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2408 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2412 * Do not send nocache headers
2414 public function enableClientCache(): void {
2415 $this->mEnableClientCache = true;
2419 * Force the page to send nocache headers
2420 * @since 1.38
2422 public function disableClientCache(): void {
2423 $this->mEnableClientCache = false;
2427 * Whether the output might become publicly cached.
2429 * @since 1.34
2430 * @return bool
2432 public function couldBePublicCached() {
2433 if ( !$this->cacheIsFinal ) {
2434 // - The entry point handles its own caching and/or doesn't use OutputPage.
2435 // (such as load.php, or MediaWiki\Rest\EntryPoint).
2437 // - Or, we haven't finished processing the main part of the request yet
2438 // (e.g. Action::show, SpecialPage::execute), and the state may still
2439 // change via enableClientCache().
2440 return true;
2442 // e.g. various error-type pages disable all client caching
2443 return $this->mEnableClientCache;
2447 * Set the expectation that cache control will not change after this point.
2449 * This should be called after the main processing logic has completed
2450 * (e.g. Action::show or SpecialPage::execute), but may be called
2451 * before Skin output has started (OutputPage::output).
2453 * @since 1.34
2455 public function considerCacheSettingsFinal() {
2456 $this->cacheIsFinal = true;
2460 * Get the list of cookie names that will influence the cache
2462 * @return array
2464 public function getCacheVaryCookies() {
2465 if ( self::$cacheVaryCookies === null ) {
2466 $config = $this->getConfig();
2467 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2468 SessionManager::singleton()->getVaryCookies(),
2470 'forceHTTPS',
2472 $config->get( MainConfigNames::CacheVaryCookies )
2473 ) ) );
2474 $this->getHookRunner()->onGetCacheVaryCookies( $this, self::$cacheVaryCookies );
2476 return self::$cacheVaryCookies;
2480 * Check if the request has a cache-varying cookie header
2481 * If it does, it's very important that we don't allow public caching
2483 * @return bool
2485 public function haveCacheVaryCookies() {
2486 $request = $this->getRequest();
2487 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2488 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2489 wfDebug( __METHOD__ . ": found $cookieName" );
2490 return true;
2493 wfDebug( __METHOD__ . ": no cache-varying cookies found" );
2494 return false;
2498 * Add an HTTP header that will influence on the cache
2500 * @param string $header Header name
2501 * @param string[]|null $option Deprecated; formerly options for the
2502 * Key header, deprecated in 1.32 and removed in 1.34. See
2503 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2504 * for the list of formerly-valid options.
2506 public function addVaryHeader( $header, array $option = null ) {
2507 if ( $option !== null && count( $option ) > 0 ) {
2508 wfDeprecatedMsg(
2509 'The $option parameter to addVaryHeader is ignored since MediaWiki 1.34',
2510 '1.34' );
2512 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2513 $this->mVaryHeader[$header] = null;
2518 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2519 * such as Accept-Encoding or Cookie
2521 * @return string
2523 public function getVaryHeader() {
2524 // If we vary on cookies, let's make sure it's always included here too.
2525 if ( $this->getCacheVaryCookies() ) {
2526 $this->addVaryHeader( 'Cookie' );
2529 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2530 $this->addVaryHeader( $header, $options );
2532 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2536 * Add an HTTP Link: header
2538 * @param string $header Header value
2540 public function addLinkHeader( $header ) {
2541 $this->mLinkHeader[] = $header;
2545 * Return a Link: header. Based on the values of $mLinkHeader.
2547 * @return string|false
2549 public function getLinkHeader() {
2550 if ( !$this->mLinkHeader ) {
2551 return false;
2554 return 'Link: ' . implode( ',', $this->mLinkHeader );
2558 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2560 * For example:
2561 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2562 * /w/index.php?title=Main_page&variant=zh-cn will not.
2564 private function addAcceptLanguage() {
2565 $title = $this->getTitle();
2566 if ( !$title instanceof Title ) {
2567 return;
2570 $languageConverter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
2571 ->getLanguageConverter( $title->getPageLanguage() );
2572 if ( !$this->getRequest()->getCheck( 'variant' ) && $languageConverter->hasVariants() ) {
2573 $this->addVaryHeader( 'Accept-Language' );
2578 * Set a flag which will cause an X-Frame-Options header appropriate for
2579 * edit pages to be sent. The header value is controlled by
2580 * $wgEditPageFrameOptions.
2582 * This is the default for special pages. If you display a CSRF-protected
2583 * form on an ordinary view page, then you need to call this function.
2585 * @param bool $enable
2586 * @deprecated since 1.38, use ::setPreventClickjacking( true )
2588 public function preventClickjacking( $enable = true ) {
2589 $this->mPreventClickjacking = $enable;
2593 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2594 * This can be called from pages which do not contain any CSRF-protected
2595 * HTML form.
2597 * @deprecated since 1.38, use ::setPreventClickjacking( false )
2599 public function allowClickjacking() {
2600 $this->mPreventClickjacking = false;
2604 * Set the prevent-clickjacking flag.
2606 * If true, will cause an X-Frame-Options header appropriate for
2607 * edit pages to be sent. The header value is controlled by
2608 * $wgEditPageFrameOptions. This is the default for special
2609 * pages. If you display a CSRF-protected form on an ordinary view
2610 * page, then you need to call this function.
2612 * Setting this flag to false will turn off frame-breaking. This
2613 * can be called from pages which do not contain any
2614 * CSRF-protected HTML form.
2616 * @param bool $enable If true, will cause an X-Frame-Options header
2617 * appropriate for edit pages to be sent.
2619 * @since 1.38
2621 public function setPreventClickjacking( bool $enable ) {
2622 $this->mPreventClickjacking = $enable;
2626 * Get the prevent-clickjacking flag
2628 * @since 1.24
2629 * @return bool
2631 public function getPreventClickjacking() {
2632 return $this->mPreventClickjacking;
2636 * Get the X-Frame-Options header value (without the name part), or false
2637 * if there isn't one. This is used by Skin to determine whether to enable
2638 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2640 * @return string|false
2642 public function getFrameOptions() {
2643 $config = $this->getConfig();
2644 if ( $config->get( MainConfigNames::BreakFrames ) ) {
2645 return 'DENY';
2646 } elseif ( $this->mPreventClickjacking && $config->get( MainConfigNames::EditPageFrameOptions ) ) {
2647 return $config->get( MainConfigNames::EditPageFrameOptions );
2649 return false;
2653 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2654 * Trials: https://github.com/GoogleChrome/OriginTrials
2656 * @return array
2658 private function getOriginTrials() {
2659 $config = $this->getConfig();
2661 return $config->get( MainConfigNames::OriginTrials );
2664 private function getReportTo() {
2665 $config = $this->getConfig();
2667 $expiry = $config->get( MainConfigNames::ReportToExpiry );
2669 if ( !$expiry ) {
2670 return false;
2673 $endpoints = $config->get( MainConfigNames::ReportToEndpoints );
2675 if ( !$endpoints ) {
2676 return false;
2679 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2681 foreach ( $endpoints as $endpoint ) {
2682 $output['endpoints'][] = [ 'url' => $endpoint ];
2685 return json_encode( $output, JSON_UNESCAPED_SLASHES );
2688 private function getFeaturePolicyReportOnly() {
2689 $config = $this->getConfig();
2691 $features = $config->get( MainConfigNames::FeaturePolicyReportOnly );
2692 return implode( ';', $features );
2696 * Send cache control HTTP headers
2698 public function sendCacheControl() {
2699 $response = $this->getRequest()->response();
2700 $config = $this->getConfig();
2702 $this->addVaryHeader( 'Cookie' );
2703 $this->addAcceptLanguage();
2705 # don't serve compressed data to clients who can't handle it
2706 # maintain different caches for logged-in users and non-logged in ones
2707 $response->header( $this->getVaryHeader() );
2709 if ( $this->mEnableClientCache ) {
2710 if ( !$config->get( MainConfigNames::UseCdn ) ) {
2711 $privateReason = 'config';
2712 } elseif ( $response->hasCookies() ) {
2713 $privateReason = 'set-cookies';
2714 // The client might use methods other than cookies to appear logged-in.
2715 // E.g. HTTP headers, or query parameter tokens, OAuth, etc.
2716 } elseif ( SessionManager::getGlobalSession()->isPersistent() ) {
2717 $privateReason = 'session';
2718 } elseif ( $this->isPrintable() ) {
2719 $privateReason = 'printable';
2720 } elseif ( $this->mCdnMaxage == 0 ) {
2721 $privateReason = 'no-maxage';
2722 } elseif ( $this->haveCacheVaryCookies() ) {
2723 $privateReason = 'cache-vary-cookies';
2724 } else {
2725 $privateReason = false;
2728 if ( $privateReason === false ) {
2729 # We'll purge the proxy cache for anons explicitly, but require end user agents
2730 # to revalidate against the proxy on each visit.
2731 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2732 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2733 wfDebug( __METHOD__ .
2734 ": local proxy caching; {$this->mLastModified} **", 'private' );
2735 # start with a shorter timeout for initial testing
2736 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2737 $response->header( "Cache-Control: " .
2738 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2739 } else {
2740 # We do want clients to cache if they can, but they *must* check for updates
2741 # on revisiting the page.
2742 wfDebug( __METHOD__ . ": private caching ($privateReason); {$this->mLastModified} **", 'private' );
2744 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2745 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2747 if ( $this->mLastModified ) {
2748 $response->header( "Last-Modified: {$this->mLastModified}" );
2750 } else {
2751 wfDebug( __METHOD__ . ": no caching **", 'private' );
2753 # In general, the absence of a last modified header should be enough to prevent
2754 # the client from using its cache. We send a few other things just to make sure.
2755 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2756 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2757 $response->header( 'Pragma: no-cache' );
2762 * Transfer styles and JavaScript modules from skin.
2764 * @param Skin $sk to load modules for
2766 public function loadSkinModules( $sk ) {
2767 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2768 if ( $group === 'styles' ) {
2769 foreach ( $modules as $moduleMembers ) {
2770 $this->addModuleStyles( $moduleMembers );
2772 } else {
2773 $this->addModules( $modules );
2779 * Finally, all the text has been munged and accumulated into
2780 * the object, let's actually output it:
2782 * @param bool $return Set to true to get the result as a string rather than sending it
2783 * @return string|null
2784 * @throws Exception
2785 * @throws FatalError
2786 * @throws MWException
2788 public function output( $return = false ) {
2789 if ( $this->mDoNothing ) {
2790 return $return ? '' : null;
2793 $response = $this->getRequest()->response();
2794 $config = $this->getConfig();
2796 if ( $this->mRedirect != '' ) {
2797 # Standards require redirect URLs to be absolute
2798 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2800 $redirect = $this->mRedirect;
2801 $code = $this->mRedirectCode;
2802 $content = '';
2804 if ( $this->getHookRunner()->onBeforePageRedirect( $this, $redirect, $code ) ) {
2805 if ( $code == '301' || $code == '303' ) {
2806 if ( !$config->get( MainConfigNames::DebugRedirects ) ) {
2807 $response->statusHeader( (int)$code );
2809 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2811 if ( $config->get( MainConfigNames::VaryOnXFP ) ) {
2812 $this->addVaryHeader( 'X-Forwarded-Proto' );
2814 $this->sendCacheControl();
2816 $response->header( 'Content-Type: text/html; charset=UTF-8' );
2817 if ( $config->get( MainConfigNames::DebugRedirects ) ) {
2818 $url = htmlspecialchars( $redirect );
2819 $content = "<!DOCTYPE html>\n<html>\n<head>\n"
2820 . "<title>Redirect</title>\n</head>\n<body>\n"
2821 . "<p>Location: <a href=\"$url\">$url</a></p>\n"
2822 . "</body>\n</html>\n";
2824 if ( !$return ) {
2825 print $content;
2828 } else {
2829 $response->header( 'Location: ' . $redirect );
2833 return $return ? $content : null;
2834 } elseif ( $this->mStatusCode ) {
2835 $response->statusHeader( $this->mStatusCode );
2838 # Buffer output; final headers may depend on later processing
2839 ob_start();
2841 $response->header( 'Content-type: ' . $config->get( MainConfigNames::MimeType ) . '; charset=UTF-8' );
2842 $response->header( 'Content-language: ' .
2843 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2845 $linkHeader = $this->getLinkHeader();
2846 if ( $linkHeader ) {
2847 $response->header( $linkHeader );
2850 // Prevent framing, if requested
2851 $frameOptions = $this->getFrameOptions();
2852 if ( $frameOptions ) {
2853 $response->header( "X-Frame-Options: $frameOptions" );
2856 $originTrials = $this->getOriginTrials();
2857 foreach ( $originTrials as $originTrial ) {
2858 $response->header( "Origin-Trial: $originTrial", false );
2861 $reportTo = $this->getReportTo();
2862 if ( $reportTo ) {
2863 $response->header( "Report-To: $reportTo" );
2866 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2867 if ( $featurePolicyReportOnly ) {
2868 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2871 if ( $this->mArticleBodyOnly ) {
2872 $this->CSP->sendHeaders();
2873 echo $this->mBodytext;
2874 } else {
2875 // Enable safe mode if requested (T152169)
2876 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2877 $this->disallowUserJs();
2880 $sk = $this->getSkin();
2881 $this->loadSkinModules( $sk );
2883 MWDebug::addModules( $this );
2885 // Hook that allows last minute changes to the output page, e.g.
2886 // adding of CSS or Javascript by extensions, adding CSP sources.
2887 $this->getHookRunner()->onBeforePageDisplay( $this, $sk );
2889 $this->CSP->sendHeaders();
2891 try {
2892 $sk->outputPage();
2893 } catch ( Exception $e ) {
2894 ob_end_clean(); // bug T129657
2895 throw $e;
2899 try {
2900 // This hook allows last minute changes to final overall output by modifying output buffer
2901 $this->getHookRunner()->onAfterFinalPageOutput( $this );
2902 } catch ( Exception $e ) {
2903 ob_end_clean(); // bug T129657
2904 throw $e;
2907 $this->sendCacheControl();
2909 if ( $return ) {
2910 return ob_get_clean();
2911 } else {
2912 ob_end_flush();
2913 return null;
2918 * Prepare this object to display an error page; disable caching and
2919 * indexing, clear the current text and redirect, set the page's title
2920 * and optionally an custom HTML title (content of the "<title>" tag).
2922 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2923 * @param string|Message|false $htmlTitle Will be passed directly to setHTMLTitle();
2924 * optional, if not passed the "<title>" attribute will be
2925 * based on $pageTitle
2927 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2928 $this->setPageTitle( $pageTitle );
2929 if ( $htmlTitle !== false ) {
2930 $this->setHTMLTitle( $htmlTitle );
2932 $this->setRobotPolicy( 'noindex,nofollow' );
2933 $this->setArticleRelated( false );
2934 $this->disableClientCache();
2935 $this->mRedirect = '';
2936 $this->clearSubtitle();
2937 $this->clearHTML();
2941 * Output a standard error page
2943 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2944 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2945 * showErrorPage( 'titlemsg', $messageObject );
2946 * showErrorPage( $titleMessageObject, $messageObject );
2948 * @param string|Message $title Message key (string) for page title, or a Message object
2949 * @param string|Message $msg Message key (string) for page text, or a Message object
2950 * @param array $params Message parameters; ignored if $msg is a Message object
2951 * @param PageReference|LinkTarget|string|null $returnto Page to show a return link to;
2952 * defaults to the 'returnto' URL parameter
2953 * @param string|null $returntoquery Query string for the return to link;
2954 * defaults to the 'returntoquery' URL parameter
2956 public function showErrorPage(
2957 $title, $msg, $params = [], $returnto = null, $returntoquery = null
2959 if ( !$title instanceof Message ) {
2960 $title = $this->msg( $title );
2963 $this->prepareErrorPage( $title );
2965 if ( $msg instanceof Message ) {
2966 if ( $params !== [] ) {
2967 trigger_error( 'Argument ignored: $params. The message parameters argument '
2968 . 'is discarded when the $msg argument is a Message object instead of '
2969 . 'a string.', E_USER_NOTICE );
2971 $this->addHTML( $msg->parseAsBlock() );
2972 } else {
2973 $this->addWikiMsgArray( $msg, $params );
2976 $this->returnToMain( null, $returnto, $returntoquery );
2980 * Output a standard permission error page
2982 * @param array $errors Error message keys or [key, param...] arrays
2983 * @param string|null $action Action that was denied or null if unknown
2985 public function showPermissionsErrorPage( array $errors, $action = null ) {
2986 $services = MediaWikiServices::getInstance();
2987 $permissionManager = $services->getPermissionManager();
2988 foreach ( $errors as $key => $error ) {
2989 $errors[$key] = (array)$error;
2992 // For some action (read, edit, create and upload), display a "login to do this action"
2993 // error if all of the following conditions are met:
2994 // 1. the user is not logged in
2995 // 2. the only error is insufficient permissions (i.e. no block or something else)
2996 // 3. the error can be avoided simply by logging in
2998 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2999 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
3000 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
3001 && ( $permissionManager->groupHasPermission( 'user', $action )
3002 || $permissionManager->groupHasPermission( 'autoconfirmed', $action ) )
3004 $displayReturnto = null;
3006 # Due to T34276, if a user does not have read permissions,
3007 # $this->getTitle() will just give Special:Badtitle, which is
3008 # not especially useful as a returnto parameter. Use the title
3009 # from the request instead, if there was one.
3010 $request = $this->getRequest();
3011 $returnto = Title::newFromText( $request->getText( 'title' ) );
3012 if ( $action == 'edit' ) {
3013 $msg = 'whitelistedittext';
3014 $displayReturnto = $returnto;
3015 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
3016 $msg = 'nocreatetext';
3017 } elseif ( $action == 'upload' ) {
3018 $msg = 'uploadnologintext';
3019 } else { # Read
3020 $msg = 'loginreqpagetext';
3021 $displayReturnto = Title::newMainPage();
3024 $query = [];
3026 if ( $returnto ) {
3027 $query['returnto'] = $returnto->getPrefixedText();
3029 if ( !$request->wasPosted() ) {
3030 $returntoquery = $request->getValues();
3031 unset( $returntoquery['title'] );
3032 unset( $returntoquery['returnto'] );
3033 unset( $returntoquery['returntoquery'] );
3034 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
3038 $title = SpecialPage::getTitleFor( 'Userlogin' );
3039 $linkRenderer = $services->getLinkRenderer();
3040 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
3041 $loginLink = $linkRenderer->makeKnownLink(
3042 $title,
3043 $this->msg( 'loginreqlink' )->text(),
3045 $query
3048 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
3049 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
3051 # Don't return to a page the user can't read otherwise
3052 # we'll end up in a pointless loop
3053 if ( $displayReturnto && $this->getAuthority()->probablyCan( 'read', $displayReturnto ) ) {
3054 $this->returnToMain( null, $displayReturnto );
3056 } else {
3057 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
3058 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
3063 * Display an error page indicating that a given version of MediaWiki is
3064 * required to use it
3066 * @param mixed $version The version of MediaWiki needed to use the page
3068 public function versionRequired( $version ) {
3069 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
3071 $this->addWikiMsg( 'versionrequiredtext', $version );
3072 $this->returnToMain();
3076 * Format permission $status obtained from Authority for display.
3078 * @param PermissionStatus $status
3079 * @param string|null $action that was denied or null if unknown
3080 * @return string
3082 public function formatPermissionStatus( PermissionStatus $status, string $action = null ): string {
3083 if ( $status->isGood() ) {
3084 return '';
3086 return $this->formatPermissionsErrorMessage( $status->toLegacyErrorArray(), $action );
3090 * Format a list of error messages
3092 * @deprecated since 1.36. Use ::formatPermissionStatus instead
3093 * @param array $errors Array of arrays returned by PermissionManager::getPermissionErrors
3094 * @param string|null $action Action that was denied or null if unknown
3095 * @return string The wikitext error-messages, formatted into a list.
3097 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
3098 if ( $action == null ) {
3099 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
3100 } else {
3101 $action_desc = $this->msg( "action-$action" )->plain();
3102 $text = $this->msg(
3103 'permissionserrorstext-withaction',
3104 count( $errors ),
3105 $action_desc
3106 )->plain() . "\n\n";
3109 if ( count( $errors ) > 1 ) {
3110 $text .= '<ul class="permissions-errors">' . "\n";
3112 foreach ( $errors as $error ) {
3113 $text .= '<li>';
3114 $text .= $this->msg( ...$error )->plain();
3115 $text .= "</li>\n";
3117 $text .= '</ul>';
3118 } else {
3119 $text .= "<div class=\"permissions-errors\">\n" .
3120 $this->msg( ...reset( $errors ) )->plain() .
3121 "\n</div>";
3124 return $text;
3128 * Show a warning about replica DB lag
3130 * If the lag is higher than $wgDatabaseReplicaLagCritical seconds,
3131 * then the warning is a bit more obvious. If the lag is
3132 * lower than $wgDatabaseReplicaLagWarning, then no warning is shown.
3134 * @param int $lag Replica lag
3136 public function showLagWarning( $lag ) {
3137 $config = $this->getConfig();
3138 if ( $lag >= $config->get( MainConfigNames::DatabaseReplicaLagWarning ) ) {
3139 $lag = floor( $lag ); // floor to avoid nano seconds to display
3140 $message = $lag < $config->get( MainConfigNames::DatabaseReplicaLagCritical )
3141 ? 'lag-warn-normal'
3142 : 'lag-warn-high';
3143 // For grep: mw-lag-warn-normal, mw-lag-warn-high
3144 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
3145 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
3150 * Output an error page
3152 * @note FatalError exception class provides an alternative.
3153 * @param string $message Error to output. Must be escaped for HTML.
3155 public function showFatalError( $message ) {
3156 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
3158 $this->addHTML( $message );
3162 * Add a "return to" link pointing to a specified title
3164 * @param LinkTarget $title Title to link
3165 * @param array $query Query string parameters
3166 * @param string|null $text Text of the link (input is not escaped)
3167 * @param array $options Options array to pass to Linker
3169 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3170 $linkRenderer = MediaWikiServices::getInstance()
3171 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3172 $link = $this->msg( 'returnto' )->rawParams(
3173 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3174 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3178 * Add a "return to" link pointing to a specified title,
3179 * or the title indicated in the request, or else the main page
3181 * @param mixed|null $unused
3182 * @param PageReference|LinkTarget|string|null $returnto Page to return to
3183 * @param string|null $returntoquery Query string for the return to link
3185 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3186 if ( $returnto == null ) {
3187 $returnto = $this->getRequest()->getText( 'returnto' );
3190 if ( $returntoquery == null ) {
3191 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
3194 if ( $returnto === '' ) {
3195 $returnto = Title::newMainPage();
3198 if ( is_object( $returnto ) ) {
3199 $linkTarget = TitleValue::castPageToLinkTarget( $returnto );
3200 } else {
3201 $linkTarget = Title::newFromText( $returnto );
3204 // We don't want people to return to external interwiki. That
3205 // might potentially be used as part of a phishing scheme
3206 if ( !is_object( $linkTarget ) || $linkTarget->isExternal() ) {
3207 $linkTarget = Title::newMainPage();
3210 $this->addReturnTo( $linkTarget, wfCgiToArray( $returntoquery ) );
3213 private function getRlClientContext() {
3214 if ( !$this->rlClientContext ) {
3215 $query = ResourceLoader::makeLoaderQuery(
3216 [], // modules; not relevant
3217 $this->getLanguage()->getCode(),
3218 $this->getSkin()->getSkinName(),
3219 $this->getUser()->isRegistered() ? $this->getUser()->getName() : null,
3220 null, // version; not relevant
3221 ResourceLoader::inDebugMode(),
3222 null, // only; not relevant
3223 $this->isPrintable()
3225 $this->rlClientContext = new RL\Context(
3226 $this->getResourceLoader(),
3227 new FauxRequest( $query )
3229 if ( $this->contentOverrideCallbacks ) {
3230 $this->rlClientContext = new RL\DerivativeContext( $this->rlClientContext );
3231 $this->rlClientContext->setContentOverrideCallback( function ( $title ) {
3232 foreach ( $this->contentOverrideCallbacks as $callback ) {
3233 $content = $callback( $title );
3234 if ( $content !== null ) {
3235 $text = ( $content instanceof TextContent ) ? $content->getText() : '';
3236 if ( strpos( $text, '</script>' ) !== false ) {
3237 // Proactively replace this so that we can display a message
3238 // to the user, instead of letting it go to Html::inlineScript(),
3239 // where it would be considered a server-side issue.
3240 $content = new JavaScriptContent(
3241 Xml::encodeJsCall( 'mw.log.error', [
3242 "Cannot preview $title due to script-closing tag."
3246 return $content;
3249 return null;
3250 } );
3253 return $this->rlClientContext;
3257 * Call this to freeze the module queue and JS config and create a formatter.
3259 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3260 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3261 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3262 * the module filters retroactively. Skins and extension hooks may also add modules until very
3263 * late in the request lifecycle.
3265 * @return RL\ClientHtml
3267 public function getRlClient() {
3268 if ( !$this->rlClient ) {
3269 $context = $this->getRlClientContext();
3270 $rl = $this->getResourceLoader();
3271 $this->addModules( [
3272 'user',
3273 'user.options',
3274 ] );
3275 $this->addModuleStyles( [
3276 'site.styles',
3277 'noscript',
3278 'user.styles',
3279 ] );
3281 // Prepare exempt modules for buildExemptModules()
3282 $exemptGroups = [
3283 RL\Module::GROUP_SITE => [],
3284 RL\Module::GROUP_NOSCRIPT => [],
3285 RL\Module::GROUP_PRIVATE => [],
3286 RL\Module::GROUP_USER => []
3288 $exemptStates = [];
3289 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3291 // Preload getTitleInfo for isKnownEmpty calls below and in RL\ClientHtml
3292 // Separate user-specific batch for improved cache-hit ratio.
3293 $userBatch = [ 'user.styles', 'user' ];
3294 $siteBatch = array_diff( $moduleStyles, $userBatch );
3295 $dbr = wfGetDB( DB_REPLICA );
3296 RL\WikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
3297 RL\WikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
3299 // Filter out modules handled by buildExemptModules()
3300 $moduleStyles = array_filter( $moduleStyles,
3301 static function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3302 $module = $rl->getModule( $name );
3303 if ( $module ) {
3304 $group = $module->getGroup();
3305 if ( $group !== null && isset( $exemptGroups[$group] ) ) {
3306 // The `noscript` module is excluded from the client
3307 // side registry, no need to set its state either.
3308 // But we still output it. See T291735
3309 if ( $group !== RL\Module::GROUP_NOSCRIPT ) {
3310 $exemptStates[$name] = 'ready';
3312 if ( !$module->isKnownEmpty( $context ) ) {
3313 // E.g. Don't output empty <styles>
3314 $exemptGroups[$group][] = $name;
3316 return false;
3319 return true;
3322 $this->rlExemptStyleModules = $exemptGroups;
3324 $rlClient = new RL\ClientHtml( $context, [
3325 'target' => $this->getTarget(),
3326 'nonce' => $this->CSP->getNonce(),
3327 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3328 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3329 // modules enqueued for loading on this page is filtered to just those.
3330 // However, to make sure we also apply the restriction to dynamic dependencies and
3331 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3332 // StartupModule so that the client-side registry will not contain any restricted
3333 // modules either. (T152169, T185303)
3334 'safemode' => ( $this->getAllowedModules( RL\Module::TYPE_COMBINED )
3335 <= RL\Module::ORIGIN_CORE_INDIVIDUAL
3336 ) ? '1' : null,
3337 ] );
3338 $rlClient->setConfig( $this->getJSVars() );
3339 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3340 $rlClient->setModuleStyles( $moduleStyles );
3341 $rlClient->setExemptStates( $exemptStates );
3342 $this->rlClient = $rlClient;
3344 return $this->rlClient;
3348 * @param Skin $sk The given Skin
3349 * @param bool $includeStyle Unused
3350 * @return string The doctype, opening "<html>", and head element.
3352 public function headElement( Skin $sk, $includeStyle = true ) {
3353 $config = $this->getConfig();
3354 $userdir = $this->getLanguage()->getDir();
3355 $services = MediaWikiServices::getInstance();
3356 $sitedir = $services->getContentLanguage()->getDir();
3358 $pieces = [];
3359 $htmlAttribs = Sanitizer::mergeAttributes( Sanitizer::mergeAttributes(
3360 $this->getRlClient()->getDocumentAttributes(),
3361 $sk->getHtmlElementAttributes()
3362 ), [ 'class' => implode( ' ', $this->mAdditionalHtmlClasses ) ] );
3363 $pieces[] = Html::htmlHeader( $htmlAttribs );
3364 $pieces[] = Html::openElement( 'head' );
3366 if ( $this->getHTMLTitle() == '' ) {
3367 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3370 if ( !Html::isXmlMimeType( $config->get( MainConfigNames::MimeType ) ) ) {
3371 // Add <meta charset="UTF-8">
3372 // This should be before <title> since it defines the charset used by
3373 // text including the text inside <title>.
3374 // The spec recommends defining XHTML5's charset using the XML declaration
3375 // instead of meta.
3376 // Our XML declaration is output by Html::htmlHeader.
3377 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3378 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3379 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3382 $pieces[] = Html::element( 'title', [], $this->getHTMLTitle() );
3383 $pieces[] = $this->getRlClient()->getHeadHtml( $htmlAttribs['class'] ?? null );
3384 $pieces[] = $this->buildExemptModules();
3385 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3386 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3388 $pieces[] = Html::closeElement( 'head' );
3390 $skinOptions = $sk->getOptions();
3391 $bodyClasses = array_merge( $this->mAdditionalBodyClasses, $skinOptions['bodyClasses'] );
3392 $bodyClasses[] = 'mediawiki';
3394 # Classes for LTR/RTL directionality support
3395 $bodyClasses[] = $userdir;
3396 $bodyClasses[] = "sitedir-$sitedir";
3398 $underline = $services->getUserOptionsLookup()->getOption( $this->getUser(), 'underline' );
3399 if ( $underline < 2 ) {
3400 // The following classes can be used here:
3401 // * mw-underline-always
3402 // * mw-underline-never
3403 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3406 // Parser feature migration class
3407 // The idea is that this will eventually be removed, after the wikitext
3408 // which requires it is cleaned up.
3409 $bodyClasses[] = 'mw-hide-empty-elt';
3411 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3412 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3413 $bodyClasses[] =
3414 'action-' . Sanitizer::escapeClass( $this->getContext()->getActionName() );
3416 if ( $sk->isResponsive() ) {
3417 $bodyClasses[] = 'skin--responsive';
3420 $bodyAttrs = [];
3421 // While the implode() is not strictly needed, it's used for backwards compatibility
3422 // (this used to be built as a string and hooks likely still expect that).
3423 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3425 // Allow skins and extensions to add body attributes they need
3426 // Get ones from deprecated method
3427 if ( method_exists( $sk, 'addToBodyAttributes' ) ) {
3428 /** @phan-suppress-next-line PhanUndeclaredMethod */
3429 $sk->addToBodyAttributes( $this, $bodyAttrs );
3430 wfDeprecated( 'Skin::addToBodyAttributes method to add body attributes', '1.35' );
3433 // Then run the hook, the recommended way of adding body attributes now
3434 $this->getHookRunner()->onOutputPageBodyAttributes( $this, $sk, $bodyAttrs );
3436 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3438 return self::combineWrappedStrings( $pieces );
3442 * Get a ResourceLoader object associated with this OutputPage
3444 * @return ResourceLoader
3446 public function getResourceLoader() {
3447 if ( $this->mResourceLoader === null ) {
3448 // Lazy-initialise as needed
3449 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3451 return $this->mResourceLoader;
3455 * Explicitly load or embed modules on a page.
3457 * @param array|string $modules One or more module names
3458 * @param string $only RL\Module TYPE_ class constant
3459 * @param array $extraQuery [optional] Array with extra query parameters for the request
3460 * @return string|WrappedStringList HTML
3462 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3463 // Apply 'target' and 'origin' filters
3464 $modules = $this->filterModules( (array)$modules, null, $only );
3466 return RL\ClientHtml::makeLoad(
3467 $this->getRlClientContext(),
3468 $modules,
3469 $only,
3470 $extraQuery,
3471 $this->CSP->getNonce()
3476 * Combine WrappedString chunks and filter out empty ones
3478 * @param array $chunks
3479 * @return string|WrappedStringList HTML
3481 protected static function combineWrappedStrings( array $chunks ) {
3482 // Filter out empty values
3483 $chunks = array_filter( $chunks, 'strlen' );
3484 return WrappedString::join( "\n", $chunks );
3488 * JS stuff to put at the bottom of the `<body>`.
3489 * These are legacy scripts ($this->mScripts), and user JS.
3491 * @param string $extraHtml (only for use by this->tailElement(); will be removed in future)
3492 * @return string|WrappedStringList HTML
3494 public function getBottomScripts( $extraHtml = '' ) {
3495 $chunks = [];
3496 $chunks[] = $this->getRlClient()->getBodyHtml();
3498 // Legacy non-ResourceLoader scripts
3499 $chunks[] = $this->mScripts;
3501 if ( $this->limitReportJSData ) {
3502 $chunks[] = ResourceLoader::makeInlineScript(
3503 ResourceLoader::makeConfigSetScript(
3504 [ 'wgPageParseReport' => $this->limitReportJSData ]
3506 $this->CSP->getNonce()
3509 // Keep the hook appendage separate to preserve WrappedString objects.
3510 // This enables BaseTemplate::getTrail() to merge them where possible.
3511 $this->getHookRunner()->onSkinAfterBottomScripts( $this->getSkin(), $extraHtml );
3512 $chunks = [ self::combineWrappedStrings( $chunks ) ];
3513 if ( $extraHtml !== '' ) {
3514 $chunks[] = $extraHtml;
3517 return WrappedString::join( "\n", $chunks );
3521 * Get the javascript config vars to include on this page
3523 * @return array Array of javascript config vars
3524 * @since 1.23
3526 public function getJsConfigVars() {
3527 return $this->mJsConfigVars;
3531 * Add one or more variables to be set in mw.config in JavaScript
3533 * @param string|array $keys Key or array of key/value pairs
3534 * @param mixed|null $value [optional] Value of the configuration variable
3536 public function addJsConfigVars( $keys, $value = null ) {
3537 if ( is_array( $keys ) ) {
3538 foreach ( $keys as $key => $value ) {
3539 $this->mJsConfigVars[$key] = $value;
3541 return;
3544 $this->mJsConfigVars[$keys] = $value;
3548 * Get an array containing the variables to be set in mw.config in JavaScript.
3550 * Do not add things here which can be evaluated in RL\StartUpModule
3551 * - in other words, page-independent/site-wide variables (without state).
3552 * You will only be adding bloat to the html page and causing page caches to
3553 * have to be purged on configuration changes.
3554 * @return array
3556 public function getJSVars() {
3557 $curRevisionId = 0;
3558 $articleId = 0;
3559 $canonicalSpecialPageName = false; # T23115
3560 $services = MediaWikiServices::getInstance();
3562 $title = $this->getTitle();
3563 $ns = $title->getNamespace();
3564 $nsInfo = $services->getNamespaceInfo();
3565 $canonicalNamespace = $nsInfo->exists( $ns )
3566 ? $nsInfo->getCanonicalName( $ns )
3567 : $title->getNsText();
3569 $sk = $this->getSkin();
3570 // Get the relevant title so that AJAX features can use the correct page name
3571 // when making API requests from certain special pages (T36972).
3572 $relevantTitle = $sk->getRelevantTitle();
3574 if ( $ns === NS_SPECIAL ) {
3575 [ $canonicalSpecialPageName, /*...*/ ] =
3576 $services->getSpecialPageFactory()->
3577 resolveAlias( $title->getDBkey() );
3578 } elseif ( $this->canUseWikiPage() ) {
3579 $wikiPage = $this->getWikiPage();
3580 $curRevisionId = $wikiPage->getLatest();
3581 $articleId = $wikiPage->getId();
3584 $lang = $title->getPageViewLanguage();
3586 // Pre-process information
3587 $separatorTransTable = $lang->separatorTransformTable();
3588 $separatorTransTable = $separatorTransTable ?: [];
3589 $compactSeparatorTransTable = [
3590 implode( "\t", array_keys( $separatorTransTable ) ),
3591 implode( "\t", $separatorTransTable ),
3593 $digitTransTable = $lang->digitTransformTable();
3594 $digitTransTable = $digitTransTable ?: [];
3595 $compactDigitTransTable = [
3596 implode( "\t", array_keys( $digitTransTable ) ),
3597 implode( "\t", $digitTransTable ),
3600 $user = $this->getUser();
3602 // Internal variables for MediaWiki core
3603 $vars = [
3604 // @internal For mediawiki.page.ready
3605 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3607 // @internal For jquery.tablesorter
3608 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3609 'wgDigitTransformTable' => $compactDigitTransTable,
3610 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3611 'wgMonthNames' => $lang->getMonthNamesArray(),
3613 // @internal For debugging purposes
3614 'wgRequestId' => WebRequest::getRequestId(),
3616 // @internal For mw.loader
3617 'wgCSPNonce' => $this->CSP->getNonce(),
3620 // Start of supported and stable config vars (for use by extensions/gadgets).
3621 $vars += [
3622 'wgCanonicalNamespace' => $canonicalNamespace,
3623 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3624 'wgNamespaceNumber' => $title->getNamespace(),
3625 'wgPageName' => $title->getPrefixedDBkey(),
3626 'wgTitle' => $title->getText(),
3627 'wgCurRevisionId' => $curRevisionId,
3628 'wgRevisionId' => (int)$this->getRevisionId(),
3629 'wgArticleId' => $articleId,
3630 'wgIsArticle' => $this->isArticle(),
3631 'wgIsRedirect' => $title->isRedirect(),
3632 'wgAction' => $this->getContext()->getActionName(),
3633 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3634 'wgUserGroups' => $services->getUserGroupManager()->getUserEffectiveGroups( $user ),
3635 'wgCategories' => $this->getCategories(),
3636 'wgPageContentLanguage' => $lang->getCode(),
3637 'wgPageContentModel' => $title->getContentModel(),
3638 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3639 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3641 if ( $user->isRegistered() ) {
3642 $vars['wgUserId'] = $user->getId();
3643 $vars['wgUserEditCount'] = $user->getEditCount();
3644 $userReg = $user->getRegistration();
3645 $vars['wgUserRegistration'] = $userReg ? (int)wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3646 // Get the revision ID of the oldest new message on the user's talk
3647 // page. This can be used for constructing new message alerts on
3648 // the client side.
3649 $userNewMsgRevId = $this->getLastSeenUserTalkRevId();
3650 // Only occupy precious space in the <head> when it is non-null (T53640)
3651 // mw.config.get returns null by default.
3652 if ( $userNewMsgRevId ) {
3653 $vars['wgUserNewMsgRevisionId'] = $userNewMsgRevId;
3656 $languageConverter = $services->getLanguageConverterFactory()
3657 ->getLanguageConverter( $title->getPageLanguage() );
3658 if ( $languageConverter->hasVariants() ) {
3659 $vars['wgUserVariant'] = $languageConverter->getPreferredVariant();
3661 // Same test as SkinTemplate
3662 $vars['wgIsProbablyEditable'] = $this->getAuthority()->probablyCan( 'edit', $title );
3663 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3664 $this->getAuthority()->probablyCan( 'edit', $relevantTitle );
3665 $restrictionStore = $services->getRestrictionStore();
3666 foreach ( $restrictionStore->listApplicableRestrictionTypes( $title ) as $type ) {
3667 // Following keys are set in $vars:
3668 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3669 $vars['wgRestriction' . ucfirst( $type )] = $restrictionStore->getRestrictions( $title, $type );
3671 if ( $title->isMainPage() ) {
3672 $vars['wgIsMainPage'] = true;
3675 $relevantUser = $sk->getRelevantUser();
3676 if ( $relevantUser ) {
3677 $vars['wgRelevantUserName'] = $relevantUser->getName();
3679 // End of stable config vars
3681 $titleFormatter = $services->getTitleFormatter();
3683 if ( $this->mRedirectedFrom ) {
3684 // @internal For skin JS
3685 $vars['wgRedirectedFrom'] = $titleFormatter->getPrefixedDBkey( $this->mRedirectedFrom );
3688 // Allow extensions to add their custom variables to the mw.config map.
3689 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3690 // page-dependent but site-wide (without state).
3691 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3692 $this->getHookRunner()->onMakeGlobalVariablesScript( $vars, $this );
3694 // Merge in variables from addJsConfigVars last
3695 return array_merge( $vars, $this->getJsConfigVars() );
3699 * Get the revision ID for the last user talk page revision viewed by the talk page owner.
3701 * @return int|null
3703 private function getLastSeenUserTalkRevId() {
3704 $services = MediaWikiServices::getInstance();
3705 $user = $this->getUser();
3706 $userHasNewMessages = $services
3707 ->getTalkPageNotificationManager()
3708 ->userHasNewMessages( $user );
3709 if ( !$userHasNewMessages ) {
3710 return null;
3713 $timestamp = $services
3714 ->getTalkPageNotificationManager()
3715 ->getLatestSeenMessageTimestamp( $user );
3717 if ( !$timestamp ) {
3718 return null;
3721 $revRecord = $services->getRevisionLookup()->getRevisionByTimestamp(
3722 $user->getTalkPage(),
3723 $timestamp
3726 if ( !$revRecord ) {
3727 return null;
3730 return $revRecord->getId();
3734 * To make it harder for someone to slip a user a fake
3735 * JavaScript or CSS preview, a random token
3736 * is associated with the login session. If it's not
3737 * passed back with the preview request, we won't render
3738 * the code.
3740 * @return bool
3742 public function userCanPreview() {
3743 $request = $this->getRequest();
3744 if (
3745 $request->getRawVal( 'action' ) !== 'submit' ||
3746 !$request->wasPosted()
3748 return false;
3751 $user = $this->getUser();
3753 if ( !$user->isRegistered() ) {
3754 // Anons have predictable edit tokens
3755 return false;
3757 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3758 return false;
3761 $title = $this->getTitle();
3762 if ( !$this->getAuthority()->probablyCan( 'edit', $title ) ) {
3763 return false;
3766 return true;
3770 * @return array Array in format "link name or number => 'link html'".
3772 public function getHeadLinksArray() {
3773 $tags = [];
3774 $config = $this->getConfig();
3776 $canonicalUrl = $this->mCanonicalUrl;
3778 $tags['meta-generator'] = Html::element( 'meta', [
3779 'name' => 'generator',
3780 'content' => 'MediaWiki ' . MW_VERSION,
3781 ] );
3783 if ( $config->get( MainConfigNames::ReferrerPolicy ) !== false ) {
3784 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3785 // fallbacks should come before the primary value so we need to reverse the array.
3786 foreach ( array_reverse( (array)$config->get( MainConfigNames::ReferrerPolicy ) ) as $i => $policy ) {
3787 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3788 'name' => 'referrer',
3789 'content' => $policy,
3790 ] );
3794 $p = $this->getRobotsContent();
3795 if ( $p ) {
3796 // http://www.robotstxt.org/wc/meta-user.html
3797 // Only show if it's different from the default robots policy
3798 $tags['meta-robots'] = Html::element( 'meta', [
3799 'name' => 'robots',
3800 'content' => $p,
3801 ] );
3804 # Browser based phonenumber detection
3805 if ( $config->get( MainConfigNames::BrowserFormatDetection ) !== false ) {
3806 $tags['meta-format-detection'] = Html::element( 'meta', [
3807 'name' => 'format-detection',
3808 'content' => $config->get( MainConfigNames::BrowserFormatDetection ),
3809 ] );
3812 foreach ( $this->mMetatags as $tag ) {
3813 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3814 $a = 'http-equiv';
3815 $tag[0] = substr( $tag[0], 5 );
3816 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3817 $a = 'property';
3818 } else {
3819 $a = 'name';
3821 $tagName = "meta-{$tag[0]}";
3822 if ( isset( $tags[$tagName] ) ) {
3823 $tagName .= $tag[1];
3825 $tags[$tagName] = Html::element( 'meta',
3827 $a => $tag[0],
3828 'content' => $tag[1]
3833 foreach ( $this->mLinktags as $tag ) {
3834 $tags[] = Html::element( 'link', $tag );
3837 if ( $config->get( MainConfigNames::UniversalEditButton ) && $this->isArticleRelated() ) {
3838 if ( $this->getAuthority()->probablyCan( 'edit', $this->getTitle() ) ) {
3839 $msg = $this->msg( 'edit' )->text();
3840 // Use mime type per https://phabricator.wikimedia.org/T21165#6946526
3841 $tags['universal-edit-button'] = Html::element( 'link', [
3842 'rel' => 'alternate',
3843 'type' => 'application/x-wiki',
3844 'title' => $msg,
3845 'href' => $this->getTitle()->getEditURL(),
3846 ] );
3850 # Generally the order of the favicon and apple-touch-icon links
3851 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3852 # uses whichever one appears later in the HTML source. Make sure
3853 # apple-touch-icon is specified first to avoid this.
3854 if ( $config->get( MainConfigNames::AppleTouchIcon ) !== false ) {
3855 $tags['apple-touch-icon'] = Html::element( 'link', [
3856 'rel' => 'apple-touch-icon',
3857 'href' => $config->get( MainConfigNames::AppleTouchIcon )
3858 ] );
3861 if ( $config->get( MainConfigNames::Favicon ) !== false ) {
3862 $tags['favicon'] = Html::element( 'link', [
3863 'rel' => 'icon',
3864 'href' => $config->get( MainConfigNames::Favicon )
3865 ] );
3868 # OpenSearch description link
3869 $tags['opensearch'] = Html::element( 'link', [
3870 'rel' => 'search',
3871 'type' => 'application/opensearchdescription+xml',
3872 'href' => wfScript( 'opensearch_desc' ),
3873 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3874 ] );
3876 # Real Simple Discovery link, provides auto-discovery information
3877 # for the MediaWiki API (and potentially additional custom API
3878 # support such as WordPress or Twitter-compatible APIs for a
3879 # blogging extension, etc)
3880 $tags['rsd'] = Html::element( 'link', [
3881 'rel' => 'EditURI',
3882 'type' => 'application/rsd+xml',
3883 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3884 // Whether RSD accepts relative or protocol-relative URLs is completely
3885 // undocumented, though.
3886 'href' => wfExpandUrl( wfAppendQuery(
3887 wfScript( 'api' ),
3888 [ 'action' => 'rsd' ] ),
3889 PROTO_RELATIVE
3891 ] );
3893 # Language variants
3894 $services = MediaWikiServices::getInstance();
3895 $languageConverterFactory = $services->getLanguageConverterFactory();
3896 $disableLangConversion = $languageConverterFactory->isConversionDisabled();
3897 if ( !$disableLangConversion ) {
3898 $lang = $this->getTitle()->getPageLanguage();
3899 $languageConverter = $languageConverterFactory->getLanguageConverter( $lang );
3900 if ( $languageConverter->hasVariants() ) {
3901 $variants = $languageConverter->getVariants();
3902 foreach ( $variants as $variant ) {
3903 $tags["variant-$variant"] = Html::element( 'link', [
3904 'rel' => 'alternate',
3905 'hreflang' => LanguageCode::bcp47( $variant ),
3906 'href' => $this->getTitle()->getLocalURL(
3907 [ 'variant' => $variant ] )
3911 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3912 $tags["variant-x-default"] = Html::element( 'link', [
3913 'rel' => 'alternate',
3914 'hreflang' => 'x-default',
3915 'href' => $this->getTitle()->getLocalURL() ] );
3919 # Copyright
3920 if ( $this->copyrightUrl !== null ) {
3921 $copyright = $this->copyrightUrl;
3922 } else {
3923 $copyright = '';
3924 if ( $config->get( MainConfigNames::RightsPage ) ) {
3925 $copy = Title::newFromText( $config->get( MainConfigNames::RightsPage ) );
3927 if ( $copy ) {
3928 $copyright = $copy->getLocalURL();
3932 if ( !$copyright && $config->get( MainConfigNames::RightsUrl ) ) {
3933 $copyright = $config->get( MainConfigNames::RightsUrl );
3937 if ( $copyright ) {
3938 $tags['copyright'] = Html::element( 'link', [
3939 'rel' => 'license',
3940 'href' => $copyright ]
3944 # Feeds
3945 if ( $config->get( MainConfigNames::Feed ) ) {
3946 $feedLinks = [];
3948 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3949 # Use the page name for the title. In principle, this could
3950 # lead to issues with having the same name for different feeds
3951 # corresponding to the same page, but we can't avoid that at
3952 # this low a level.
3954 $feedLinks[] = $this->feedLink(
3955 $format,
3956 $link,
3957 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3958 $this->msg(
3959 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3960 )->text()
3964 # Recent changes feed should appear on every page (except recentchanges,
3965 # that would be redundant). Put it after the per-page feed to avoid
3966 # changing existing behavior. It's still available, probably via a
3967 # menu in your browser. Some sites might have a different feed they'd
3968 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3969 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3970 # If so, use it instead.
3971 $sitename = $config->get( MainConfigNames::Sitename );
3972 $overrideSiteFeed = $config->get( MainConfigNames::OverrideSiteFeed );
3973 if ( $overrideSiteFeed ) {
3974 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3975 // Note, this->feedLink escapes the url.
3976 $feedLinks[] = $this->feedLink(
3977 $type,
3978 $feedUrl,
3979 $this->msg( "site-{$type}-feed", $sitename )->text()
3982 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3983 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3984 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3985 $feedLinks[] = $this->feedLink(
3986 $format,
3987 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3988 # For grep: 'site-rss-feed', 'site-atom-feed'
3989 $this->msg( "site-{$format}-feed", $sitename )->text()
3994 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3995 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3996 # use OutputPage::addFeedLink() instead.
3997 $this->getHookRunner()->onAfterBuildFeedLinks( $feedLinks );
3999 $tags += $feedLinks;
4002 # Canonical URL
4003 if ( $config->get( MainConfigNames::EnableCanonicalServerLink ) ) {
4004 if ( $canonicalUrl !== false ) {
4005 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
4006 } elseif ( $this->isArticleRelated() ) {
4007 // This affects all requests where "setArticleRelated" is true. This is
4008 // typically all requests that show content (query title, curid, oldid, diff),
4009 // and all wikipage actions (edit, delete, purge, info, history etc.).
4010 // It does not apply to File pages and Special pages.
4012 // 'history' and 'info' actions address page metadata rather than the page
4013 // content itself, so they may not be canonicalized to the view page url.
4015 // TODO: this logic should be owned by Action subclasses.
4016 $action = $this->getContext()->getActionName();
4017 if ( in_array( $action, [ 'history', 'info' ] ) ) {
4018 $query = "action={$action}";
4019 } else {
4020 $query = '';
4022 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
4023 } else {
4024 $reqUrl = $this->getRequest()->getRequestURL();
4025 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
4028 if ( $canonicalUrl !== false ) {
4029 $tags[] = Html::element( 'link', [
4030 'rel' => 'canonical',
4031 'href' => $canonicalUrl
4032 ] );
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 * Generate a "<link rel/>" for a feed.
4048 * @param string $type Feed type
4049 * @param string $url URL to the feed
4050 * @param string $text Value of the "title" attribute
4051 * @return string HTML fragment
4053 private function feedLink( $type, $url, $text ) {
4054 return Html::element( 'link', [
4055 'rel' => 'alternate',
4056 'type' => "application/$type+xml",
4057 'title' => $text,
4058 'href' => $url ]
4063 * Add a local or specified stylesheet, with the given media options.
4064 * Internal use only. Use OutputPage::addModuleStyles() if possible.
4066 * @param string $style URL to the file
4067 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
4068 * @param string $condition For IE conditional comments, specifying an IE version
4069 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
4071 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
4072 $options = [];
4073 if ( $media ) {
4074 $options['media'] = $media;
4076 if ( $condition ) {
4077 $options['condition'] = $condition;
4079 if ( $dir ) {
4080 $options['dir'] = $dir;
4082 $this->styles[$style] = $options;
4086 * Adds inline CSS styles
4087 * Internal use only. Use OutputPage::addModuleStyles() if possible.
4089 * @param mixed $style_css Inline CSS
4090 * @param string $flip Set to 'flip' to flip the CSS if needed
4092 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
4093 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
4094 # If wanted, and the interface is right-to-left, flip the CSS
4095 $style_css = CSSJanus::transform( $style_css, true, false );
4097 $this->mInlineStyles .= Html::inlineStyle( $style_css );
4101 * Build exempt modules and legacy non-ResourceLoader styles.
4103 * @return string|WrappedStringList HTML
4105 protected function buildExemptModules() {
4106 $chunks = [];
4108 // Requirements:
4109 // - Within modules provided by the software (core, skin, extensions),
4110 // styles from skin stylesheets should be overridden by styles
4111 // from modules dynamically loaded with JavaScript.
4112 // - Styles from site-specific, private, and user modules should override
4113 // both of the above.
4115 // The effective order for stylesheets must thus be:
4116 // 1. Page style modules, formatted server-side by RL\ClientHtml.
4117 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
4118 // 3. Styles that are site-specific, private or from the user, formatted
4119 // server-side by this function.
4121 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
4122 // point #2 is.
4124 // Add legacy styles added through addStyle()/addInlineStyle() here
4125 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
4127 // Things that go after the ResourceLoaderDynamicStyles marker
4128 $append = [];
4129 $separateReq = [ 'site.styles', 'user.styles' ];
4130 foreach ( $this->rlExemptStyleModules as $moduleNames ) {
4131 if ( $moduleNames ) {
4132 $append[] = $this->makeResourceLoaderLink(
4133 array_diff( $moduleNames, $separateReq ),
4134 RL\Module::TYPE_STYLES
4137 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
4138 // These require their own dedicated request in order to support "@import"
4139 // syntax, which is incompatible with concatenation. (T147667, T37562)
4140 $append[] = $this->makeResourceLoaderLink( $name,
4141 RL\Module::TYPE_STYLES
4146 if ( $append ) {
4147 $chunks[] = Html::element(
4148 'meta',
4149 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
4151 $chunks = array_merge( $chunks, $append );
4154 return self::combineWrappedStrings( $chunks );
4158 * @return array
4160 public function buildCssLinksArray() {
4161 $links = [];
4163 foreach ( $this->styles as $file => $options ) {
4164 $link = $this->styleLink( $file, $options );
4165 if ( $link ) {
4166 $links[$file] = $link;
4169 return $links;
4173 * Generate \<link\> tags for stylesheets
4175 * @param string $style URL to the file
4176 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
4177 * @return string HTML fragment
4179 protected function styleLink( $style, array $options ) {
4180 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
4181 return '';
4184 if ( isset( $options['media'] ) ) {
4185 $media = self::transformCssMedia( $options['media'] );
4186 if ( $media === null ) {
4187 return '';
4189 } else {
4190 $media = 'all';
4193 if ( substr( $style, 0, 1 ) == '/' ||
4194 substr( $style, 0, 5 ) == 'http:' ||
4195 substr( $style, 0, 6 ) == 'https:' ) {
4196 $url = $style;
4197 } else {
4198 $config = $this->getConfig();
4199 // Append file hash as query parameter
4200 $url = self::transformResourcePath(
4201 $config,
4202 $config->get( MainConfigNames::StylePath ) . '/' . $style
4206 $link = Html::linkedStyle( $url, $media );
4208 if ( isset( $options['condition'] ) ) {
4209 $condition = htmlspecialchars( $options['condition'] );
4210 $link = "<!--[if $condition]>$link<![endif]-->";
4212 return $link;
4216 * Transform path to web-accessible static resource.
4218 * This is used to add a validation hash as query string.
4219 * This aids various behaviors:
4221 * - Put long Cache-Control max-age headers on responses for improved
4222 * cache performance.
4223 * - Get the correct version of a file as expected by the current page.
4224 * - Instantly get the updated version of a file after deployment.
4226 * Avoid using this for urls included in HTML as otherwise clients may get different
4227 * versions of a resource when navigating the site depending on when the page was cached.
4228 * If changes to the url propagate, this is not a problem (e.g. if the url is in
4229 * an external stylesheet).
4231 * @since 1.27
4232 * @param Config $config
4233 * @param string $path Path-absolute URL to file (from document root, must start with "/")
4234 * @return string URL
4236 public static function transformResourcePath( Config $config, $path ) {
4237 $localDir = $config->get( MainConfigNames::BaseDirectory );
4238 $remotePathPrefix = $config->get( MainConfigNames::ResourceBasePath );
4239 if ( $remotePathPrefix === '' ) {
4240 // The configured base path is required to be empty string for
4241 // wikis in the domain root
4242 $remotePath = '/';
4243 } else {
4244 $remotePath = $remotePathPrefix;
4246 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
4247 // - Path is outside wgResourceBasePath, ignore.
4248 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
4249 return $path;
4251 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
4252 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
4253 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
4254 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
4255 $uploadPath = $config->get( MainConfigNames::UploadPath );
4256 if ( strpos( $path, $uploadPath ) === 0 ) {
4257 $localDir = $config->get( MainConfigNames::UploadDirectory );
4258 $remotePathPrefix = $remotePath = $uploadPath;
4261 $path = RelPath::getRelativePath( $path, $remotePath );
4262 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
4266 * Utility method for transformResourceFilePath().
4268 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
4270 * @since 1.27
4271 * @param string $remotePathPrefix URL path prefix that points to $localPath
4272 * @param string $localPath File directory exposed at $remotePath
4273 * @param string $file Path to target file relative to $localPath
4274 * @return string URL
4276 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4277 // This MUST match the equivalent logic in CSSMin::remapOne()
4278 $localFile = "$localPath/$file";
4279 $url = "$remotePathPrefix/$file";
4280 if ( is_file( $localFile ) ) {
4281 $hash = md5_file( $localFile );
4282 if ( $hash === false ) {
4283 wfLogWarning( __METHOD__ . ": Failed to hash $localFile" );
4284 $hash = '';
4286 $url .= '?' . substr( $hash, 0, 5 );
4288 return $url;
4292 * Transform "media" attribute based on request parameters
4294 * @param string $media Current value of the "media" attribute
4295 * @return string|null Modified value of the "media" attribute, or null to disable
4296 * this stylesheet
4298 public static function transformCssMedia( $media ) {
4299 global $wgRequest;
4301 if ( $wgRequest->getBool( 'printable' ) ) {
4302 // When browsing with printable=yes, apply "print" media styles
4303 // as if they are screen styles (no media, media="").
4304 if ( $media === 'print' ) {
4305 return '';
4308 // https://www.w3.org/TR/css3-mediaqueries/#syntax
4310 // This regex will not attempt to understand a comma-separated media_query_list
4311 // Example supported values for $media:
4313 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
4315 // Example NOT supported value for $media:
4317 // '3d-glasses, screen, print and resolution > 90dpi'
4319 // If it's a "printable" request, we disable all screen stylesheets.
4320 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
4321 if ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4322 return null;
4326 return $media;
4330 * Add a wikitext-formatted message to the output.
4331 * This is equivalent to:
4333 * $wgOut->addWikiText( wfMessage( ... )->plain() )
4335 * @param mixed ...$args
4337 public function addWikiMsg( ...$args ) {
4338 $name = array_shift( $args );
4339 $this->addWikiMsgArray( $name, $args );
4343 * Add a wikitext-formatted message to the output.
4344 * Like addWikiMsg() except the parameters are taken as an array
4345 * instead of a variable argument list.
4347 * @param string $name
4348 * @param array $args
4350 public function addWikiMsgArray( $name, $args ) {
4351 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
4355 * This function takes a number of message/argument specifications, wraps them in
4356 * some overall structure, and then parses the result and adds it to the output.
4358 * In the $wrap, $1 is replaced with the first message, $2 with the second,
4359 * and so on. The subsequent arguments may be either
4360 * 1) strings, in which case they are message names, or
4361 * 2) arrays, in which case, within each array, the first element is the message
4362 * name, and subsequent elements are the parameters to that message.
4364 * Don't use this for messages that are not in the user's interface language.
4366 * For example:
4368 * $wgOut->wrapWikiMsg( "<div class='customclass'>\n$1\n</div>", 'some-msg-key' );
4370 * Is equivalent to:
4372 * $wgOut->addWikiTextAsInterface( "<div class='customclass'>\n"
4373 * . wfMessage( 'some-msg-key' )->plain() . "\n</div>" );
4375 * The newline after the opening div is needed in some wikitext. See T21226.
4377 * @param string $wrap
4378 * @param mixed ...$msgSpecs
4380 public function wrapWikiMsg( $wrap, ...$msgSpecs ) {
4381 $s = $wrap;
4382 foreach ( $msgSpecs as $n => $spec ) {
4383 if ( is_array( $spec ) ) {
4384 $args = $spec;
4385 $name = array_shift( $args );
4386 } else {
4387 $args = [];
4388 $name = $spec;
4390 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4392 $this->addWikiTextAsInterface( $s );
4396 * Whether the output has a table of contents
4397 * @return bool
4398 * @since 1.22
4400 public function isTOCEnabled() {
4401 return $this->mEnableTOC;
4405 * Helper function to setup the PHP implementation of OOUI to use in this request.
4407 * @since 1.26
4408 * @param string $skinName The Skin name to determine the correct OOUI theme
4409 * @param string $dir Language direction
4411 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4412 $themes = RL\OOUIFileModule::getSkinThemeMap();
4413 $theme = $themes[$skinName] ?? $themes['default'];
4414 // For example, 'OOUI\WikimediaUITheme'.
4415 $themeClass = "OOUI\\{$theme}Theme";
4416 OOUI\Theme::setSingleton( new $themeClass() );
4417 OOUI\Element::setDefaultDir( $dir );
4421 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4422 * MediaWiki and this OutputPage instance.
4424 * @since 1.25
4426 public function enableOOUI() {
4427 self::setupOOUI(
4428 strtolower( $this->getSkin()->getSkinName() ),
4429 $this->getLanguage()->getDir()
4431 $this->addModuleStyles( [
4432 'oojs-ui-core.styles',
4433 'oojs-ui.styles.indicators',
4434 'mediawiki.widgets.styles',
4435 'oojs-ui-core.icons',
4436 ] );
4440 * Get (and set if not yet set) the CSP nonce.
4442 * This value needs to be included in any <script> tags on the
4443 * page.
4445 * @return string|false Nonce or false to mean don't output nonce
4446 * @since 1.32
4447 * @deprecated Since 1.35 use getCSP()->getNonce() instead
4449 public function getCSPNonce() {
4450 return $this->CSP->getNonce();
4454 * Get the ContentSecurityPolicy object
4456 * @since 1.35
4457 * @return ContentSecurityPolicy
4459 public function getCSP() {
4460 return $this->CSP;
4464 * The final bits that go to the bottom of a page
4465 * HTML document including the closing tags
4467 * @internal
4468 * @since 1.37
4469 * @param Skin $skin
4470 * @return string
4472 public function tailElement( $skin ) {
4473 // T257704: Temporarily run skin hook here pending
4474 // creation dedicated outputpage hook for this
4475 $extraHtml = '';
4476 $this->getHookRunner()->onSkinAfterBottomScripts( $skin, $extraHtml );
4478 $tail = [
4479 MWDebug::getDebugHTML( $skin ),
4480 $this->getBottomScripts( $extraHtml ),
4481 wfReportTime( $this->getCSP()->getNonce() ),
4482 MWDebug::getHTMLDebugLog(),
4483 Html::closeElement( 'body' ),
4484 Html::closeElement( 'html' ),
4487 return WrappedStringList::join( "\n", $tail );