3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Session\SessionManager
;
27 use Wikimedia\RelPath
;
28 use Wikimedia\WrappedString
;
29 use Wikimedia\WrappedStringList
;
32 * This class should be covered by a general architecture document which does
33 * not exist as of January 2011. This is one of the Core classes and should
34 * be read at least once by any new developers.
36 * This class is used to prepare the final rendering. A skin is then
37 * applied to the output parameters (links, javascript, html, categories ...).
39 * @todo FIXME: Another class handles sending the whole page to the client.
41 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
46 class OutputPage
extends ContextSource
{
47 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
48 protected $mMetatags = [];
51 protected $mLinktags = [];
54 protected $mCanonicalUrl = false;
57 * @var string Should be private - has getter and setter. Contains
59 public $mPagetitle = '';
62 * @var string Contains all of the "<body>" content. Should be private we
63 * got set/get accessors and the append() method.
65 public $mBodytext = '';
67 /** @var string Stores contents of "<title>" tag */
68 private $mHTMLtitle = '';
71 * @var bool Is the displayed content related to the source of the
72 * corresponding wiki article.
74 private $mIsarticle = false;
76 /** @var bool Stores "article flag" toggle. */
77 private $mIsArticleRelated = true;
80 * @var bool We have to set isPrintable(). Some pages should
81 * never be printed (ex: redirections).
83 private $mPrintable = false;
86 * @var array Contains the page subtitle. Special pages usually have some
87 * links here. Don't confuse with site subtitle added by skins.
89 private $mSubtitle = [];
92 public $mRedirect = '';
95 protected $mStatusCode;
98 * @var string Used for sending cache control.
99 * The whole caching system should probably be moved into its own class.
101 protected $mLastModified = '';
104 protected $mCategoryLinks = [];
107 protected $mCategories = [
113 protected $mIndicators = [];
115 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
116 private $mLanguageLinks = [];
119 * Used for JavaScript (predates ResourceLoader)
120 * @todo We should split JS / CSS.
121 * mScripts content is inserted as is in "<head>" by Skin. This might
122 * contain either a link to a stylesheet or inline CSS.
124 private $mScripts = '';
126 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
127 protected $mInlineStyles = '';
130 * @var string Used by skin template.
131 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
133 public $mPageLinkTitle = '';
135 /** @var array Array of elements in "<head>". Parser might add its own headers! */
136 protected $mHeadItems = [];
138 /** @var array Additional <body> classes; there are also <body> classes from other sources */
139 protected $mAdditionalBodyClasses = [];
142 protected $mModules = [];
145 protected $mModuleScripts = [];
148 protected $mModuleStyles = [];
150 /** @var ResourceLoader */
151 protected $mResourceLoader;
153 /** @var ResourceLoaderClientHtml */
156 /** @var ResourceLoaderContext */
157 private $rlClientContext;
160 private $rlExemptStyleModules;
163 protected $mJsConfigVars = [];
166 protected $mTemplateIds = [];
169 protected $mImageTimeKeys = [];
172 public $mRedirectCode = '';
174 protected $mFeedLinksAppendQuery = null;
177 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
178 * @see ResourceLoaderModule::$origin
179 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
181 protected $mAllowedModules = [
182 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
185 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
186 protected $mDoNothing = false;
191 protected $mContainsNewMagic = 0;
194 * lazy initialised, use parserOptions()
197 protected $mParserOptions = null;
200 * Handles the Atom / RSS links.
201 * We probably only support Atom in 2011.
202 * @see $wgAdvertisedFeedTypes
204 private $mFeedLinks = [];
206 // Gwicke work on squid caching? Roughly from 2003.
207 protected $mEnableClientCache = true;
209 /** @var bool Flag if output should only contain the body of the article. */
210 private $mArticleBodyOnly = false;
213 protected $mNewSectionLink = false;
216 protected $mHideNewSectionLink = false;
219 * @var bool Comes from the parser. This was probably made to load CSS/JS
220 * only if we had "<gallery>". Used directly in CategoryPage.php.
221 * Looks like ResourceLoader can replace this.
223 public $mNoGallery = false;
226 private $mPageTitleActionText = '';
228 /** @var int Cache stuff. Looks like mEnableClientCache */
229 protected $mCdnMaxage = 0;
230 /** @var int Upper limit on mCdnMaxage */
231 protected $mCdnMaxageLimit = INF
;
234 * @var bool Controls if anti-clickjacking / frame-breaking headers will
235 * be sent. This should be done for pages where edit actions are possible.
236 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
238 protected $mPreventClickjacking = true;
240 /** @var int To include the variable {{REVISIONID}} */
241 private $mRevisionId = null;
244 private $mRevisionTimestamp = null;
247 protected $mFileVersion = null;
250 * @var array An array of stylesheet filenames (relative from skins path),
251 * with options for CSS media, IE conditions, and RTL/LTR direction.
252 * For internal use; add settings in the skin via $this->addStyle()
254 * Style again! This seems like a code duplication since we already have
255 * mStyles. This is what makes Open Source amazing.
257 protected $styles = [];
259 private $mIndexPolicy = 'index';
260 private $mFollowPolicy = 'follow';
261 private $mVaryHeader = [
262 'Accept-Encoding' => [ 'match=gzip' ],
266 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
271 private $mRedirectedFrom = null;
274 * Additional key => value data
276 private $mProperties = [];
279 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
281 private $mTarget = null;
284 * @var bool Whether parser output contains a table of contents
286 private $mEnableTOC = false;
289 * @var string|null The URL to send in a <link> element with rel=license
291 private $copyrightUrl;
293 /** @var array Profiling data */
294 private $limitReportJSData = [];
296 /** @var array Map Title to Content */
297 private $contentOverrides = [];
299 /** @var callable[] */
300 private $contentOverrideCallbacks = [];
303 * Link: header contents
305 private $mLinkHeader = [];
308 * @var string The nonce for Content-Security-Policy
313 * Constructor for OutputPage. This should not be called directly.
314 * Instead a new RequestContext should be created and it will implicitly create
315 * a OutputPage tied to that context.
316 * @param IContextSource $context
318 function __construct( IContextSource
$context ) {
319 $this->setContext( $context );
323 * Redirect to $url rather than displaying the normal page
326 * @param string $responsecode HTTP status code
328 public function redirect( $url, $responsecode = '302' ) {
329 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
330 $this->mRedirect
= str_replace( "\n", '', $url );
331 $this->mRedirectCode
= $responsecode;
335 * Get the URL to redirect to, or an empty string if not redirect URL set
339 public function getRedirect() {
340 return $this->mRedirect
;
344 * Set the copyright URL to send with the output.
345 * Empty string to omit, null to reset.
349 * @param string|null $url
351 public function setCopyrightUrl( $url ) {
352 $this->copyrightUrl
= $url;
356 * Set the HTTP status code to send with the output.
358 * @param int $statusCode
360 public function setStatusCode( $statusCode ) {
361 $this->mStatusCode
= $statusCode;
365 * Add a new "<meta>" tag
366 * To add an http-equiv meta tag, precede the name with "http:"
368 * @param string $name Name of the meta tag
369 * @param string $val Value of the meta tag
371 function addMeta( $name, $val ) {
372 array_push( $this->mMetatags
, [ $name, $val ] );
376 * Returns the current <meta> tags
381 public function getMetaTags() {
382 return $this->mMetatags
;
386 * Add a new \<link\> tag to the page header.
388 * Note: use setCanonicalUrl() for rel=canonical.
390 * @param array $linkarr Associative array of attributes.
392 function addLink( array $linkarr ) {
393 array_push( $this->mLinktags
, $linkarr );
397 * Returns the current <link> tags
402 public function getLinkTags() {
403 return $this->mLinktags
;
407 * Add a new \<link\> with "rel" attribute set to "meta"
409 * @param array $linkarr Associative array mapping attribute names to their
410 * values, both keys and values will be escaped, and the
411 * "rel" attribute will be automatically added
413 function addMetadataLink( array $linkarr ) {
414 $linkarr['rel'] = $this->getMetadataAttribute();
415 $this->addLink( $linkarr );
419 * Set the URL to be used for the <link rel=canonical>. This should be used
420 * in preference to addLink(), to avoid duplicate link tags.
423 function setCanonicalUrl( $url ) {
424 $this->mCanonicalUrl
= $url;
428 * Returns the URL to be used for the <link rel=canonical> if
432 * @return bool|string
434 public function getCanonicalUrl() {
435 return $this->mCanonicalUrl
;
439 * Get the value of the "rel" attribute for metadata links
443 public function getMetadataAttribute() {
444 # note: buggy CC software only reads first "meta" link
445 static $haveMeta = false;
447 return 'alternate meta';
455 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
456 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
459 * @param string $script Raw HTML
461 function addScript( $script ) {
462 $this->mScripts
.= $script;
466 * Add a JavaScript file to be loaded as `<script>` on this page.
468 * Internal use only. Use OutputPage::addModules() if possible.
470 * @param string $file URL to file (absolute path, protocol-relative, or full url)
471 * @param string $unused Previously used to change the cache-busting query parameter
473 public function addScriptFile( $file, $unused = null ) {
474 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
475 // This is not an absolute path, protocol-relative url, or full scheme url,
476 // presumed to be an old call intended to include a file from /w/skins/common,
477 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
478 wfDeprecated( __METHOD__
, '1.24' );
481 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
485 * Add a self-contained script tag with the given contents
486 * Internal use only. Use OutputPage::addModules() if possible.
488 * @param string $script JavaScript text, no script tags
490 public function addInlineScript( $script ) {
491 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
495 * Filter an array of modules to remove insufficiently trustworthy members, and modules
496 * which are no longer registered (eg a page is cached before an extension is disabled)
497 * @param array $modules
498 * @param string|null $position Unused
499 * @param string $type
502 protected function filterModules( array $modules, $position = null,
503 $type = ResourceLoaderModule
::TYPE_COMBINED
505 $resourceLoader = $this->getResourceLoader();
506 $filteredModules = [];
507 foreach ( $modules as $val ) {
508 $module = $resourceLoader->getModule( $val );
509 if ( $module instanceof ResourceLoaderModule
510 && $module->getOrigin() <= $this->getAllowedModules( $type )
512 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
513 $this->warnModuleTargetFilter( $module->getName() );
516 $filteredModules[] = $val;
519 return $filteredModules;
522 private function warnModuleTargetFilter( $moduleName ) {
523 static $warnings = [];
524 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
527 $warnings[$this->mTarget
][$moduleName] = true;
528 $this->getResourceLoader()->getLogger()->debug(
529 'Module "{module}" not loadable on target "{target}".',
531 'module' => $moduleName,
532 'target' => $this->mTarget
,
538 * Get the list of modules to include on this page
540 * @param bool $filter Whether to filter out insufficiently trustworthy modules
541 * @param string|null $position Unused
542 * @param string $param
543 * @param string $type
544 * @return array Array of module names
546 public function getModules( $filter = false, $position = null, $param = 'mModules',
547 $type = ResourceLoaderModule
::TYPE_COMBINED
549 $modules = array_values( array_unique( $this->$param ) );
551 ?
$this->filterModules( $modules, null, $type )
556 * Load one or more ResourceLoader modules on this page.
558 * @param string|array $modules Module name (string) or array of module names
560 public function addModules( $modules ) {
561 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
565 * Get the list of script-only modules to load on this page.
567 * @param bool $filter
568 * @param string|null $position Unused
569 * @return array Array of module names
571 public function getModuleScripts( $filter = false, $position = null ) {
572 return $this->getModules( $filter, null, 'mModuleScripts',
573 ResourceLoaderModule
::TYPE_SCRIPTS
578 * Load the scripts of one or more ResourceLoader modules, on this page.
580 * This method exists purely to provide the legacy behaviour of loading
581 * a module's scripts in the global scope, and without dependency resolution.
582 * See <https://phabricator.wikimedia.org/T188689>.
584 * @deprecated since 1.31 Use addModules() instead.
585 * @param string|array $modules Module name (string) or array of module names
587 public function addModuleScripts( $modules ) {
588 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
592 * Get the list of style-only modules to load on this page.
594 * @param bool $filter
595 * @param string|null $position Unused
596 * @return array Array of module names
598 public function getModuleStyles( $filter = false, $position = null ) {
599 return $this->getModules( $filter, null, 'mModuleStyles',
600 ResourceLoaderModule
::TYPE_STYLES
605 * Load the styles of one or more ResourceLoader modules on this page.
607 * Module styles added through this function will be loaded as a stylesheet,
608 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
609 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
611 * @param string|array $modules Module name (string) or array of module names
613 public function addModuleStyles( $modules ) {
614 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
618 * @return null|string ResourceLoader target
620 public function getTarget() {
621 return $this->mTarget
;
625 * Sets ResourceLoader target for load.php links. If null, will be omitted
627 * @param string|null $target
629 public function setTarget( $target ) {
630 $this->mTarget
= $target;
634 * Add a mapping from a LinkTarget to a Content, for things like page preview.
635 * @see self::addContentOverrideCallback()
637 * @param LinkTarget $target
638 * @param Content $content
640 public function addContentOverride( LinkTarget
$target, Content
$content ) {
641 if ( !$this->contentOverrides
) {
642 // Register a callback for $this->contentOverrides on the first call
643 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
644 $key = $target->getNamespace() . ':' . $target->getDBkey();
645 return $this->contentOverrides
[$key] ??
null;
649 $key = $target->getNamespace() . ':' . $target->getDBkey();
650 $this->contentOverrides
[$key] = $content;
654 * Add a callback for mapping from a Title to a Content object, for things
656 * @see ResourceLoaderContext::getContentOverrideCallback()
658 * @param callable $callback
660 public function addContentOverrideCallback( callable
$callback ) {
661 $this->contentOverrideCallbacks
[] = $callback;
665 * Get an array of head items
669 function getHeadItemsArray() {
670 return $this->mHeadItems
;
674 * Add or replace a head item to the output
676 * Whenever possible, use more specific options like ResourceLoader modules,
677 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
678 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
679 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
680 * This would be your very LAST fallback.
682 * @param string $name Item name
683 * @param string $value Raw HTML
685 public function addHeadItem( $name, $value ) {
686 $this->mHeadItems
[$name] = $value;
690 * Add one or more head items to the output
693 * @param string|string[] $values Raw HTML
695 public function addHeadItems( $values ) {
696 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
700 * Check if the header item $name is already set
702 * @param string $name Item name
705 public function hasHeadItem( $name ) {
706 return isset( $this->mHeadItems
[$name] );
710 * Add a class to the <body> element
713 * @param string|string[] $classes One or more classes to add
715 public function addBodyClasses( $classes ) {
716 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
720 * Set whether the output should only contain the body of the article,
721 * without any skin, sidebar, etc.
722 * Used e.g. when calling with "action=render".
724 * @param bool $only Whether to output only the body of the article
726 public function setArticleBodyOnly( $only ) {
727 $this->mArticleBodyOnly
= $only;
731 * Return whether the output will contain only the body of the article
735 public function getArticleBodyOnly() {
736 return $this->mArticleBodyOnly
;
740 * Set an additional output property
743 * @param string $name
744 * @param mixed $value
746 public function setProperty( $name, $value ) {
747 $this->mProperties
[$name] = $value;
751 * Get an additional output property
754 * @param string $name
755 * @return mixed Property value or null if not found
757 public function getProperty( $name ) {
758 if ( isset( $this->mProperties
[$name] ) ) {
759 return $this->mProperties
[$name];
766 * checkLastModified tells the client to use the client-cached page if
767 * possible. If successful, the OutputPage is disabled so that
768 * any future call to OutputPage->output() have no effect.
770 * Side effect: sets mLastModified for Last-Modified header
772 * @param string $timestamp
774 * @return bool True if cache-ok headers was sent.
776 public function checkLastModified( $timestamp ) {
777 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
778 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
781 $config = $this->getConfig();
782 if ( !$config->get( 'CachePages' ) ) {
783 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
787 $timestamp = wfTimestamp( TS_MW
, $timestamp );
789 'page' => $timestamp,
790 'user' => $this->getUser()->getTouched(),
791 'epoch' => $config->get( 'CacheEpoch' )
793 if ( $config->get( 'UseSquid' ) ) {
794 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
796 $config->get( 'SquidMaxage' )
799 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
801 $maxModified = max( $modifiedTimes );
802 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
804 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
805 if ( $clientHeader === false ) {
806 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
810 # IE sends sizes after the date like this:
811 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
812 # this breaks strtotime().
813 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
815 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
816 $clientHeaderTime = strtotime( $clientHeader );
817 Wikimedia\restoreWarnings
();
818 if ( !$clientHeaderTime ) {
820 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
823 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
827 foreach ( $modifiedTimes as $name => $value ) {
828 if ( $info !== '' ) {
831 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
834 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
835 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
836 wfDebug( __METHOD__
. ": effective Last-Modified: " .
837 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
838 if ( $clientHeaderTime < $maxModified ) {
839 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
844 # Give a 304 Not Modified response code and disable body output
845 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
846 ini_set( 'zlib.output_compression', 0 );
847 $this->getRequest()->response()->statusHeader( 304 );
848 $this->sendCacheControl();
851 // Don't output a compressed blob when using ob_gzhandler;
852 // it's technically against HTTP spec and seems to confuse
853 // Firefox when the response gets split over two packets.
854 wfClearOutputBuffers();
860 * @param int $reqTime Time of request (eg. now)
861 * @param int $maxAge Cache TTL in seconds
862 * @return int Timestamp
864 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
865 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
866 // because even if the wiki page content hasn't changed since, static
867 // resources may have changed (skin HTML, interface messages, urls, etc.)
868 // and must roll-over in a timely manner (T46570)
869 return $reqTime - $maxAge;
873 * Override the last modified timestamp
875 * @param string $timestamp New timestamp, in a format readable by
878 public function setLastModified( $timestamp ) {
879 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
883 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
885 * @param string $policy The literal string to output as the contents of
886 * the meta tag. Will be parsed according to the spec and output in
890 public function setRobotPolicy( $policy ) {
891 $policy = Article
::formatRobotPolicy( $policy );
893 if ( isset( $policy['index'] ) ) {
894 $this->setIndexPolicy( $policy['index'] );
896 if ( isset( $policy['follow'] ) ) {
897 $this->setFollowPolicy( $policy['follow'] );
902 * Set the index policy for the page, but leave the follow policy un-
905 * @param string $policy Either 'index' or 'noindex'.
908 public function setIndexPolicy( $policy ) {
909 $policy = trim( $policy );
910 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
911 $this->mIndexPolicy
= $policy;
916 * Set the follow policy for the page, but leave the index policy un-
919 * @param string $policy Either 'follow' or 'nofollow'.
922 public function setFollowPolicy( $policy ) {
923 $policy = trim( $policy );
924 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
925 $this->mFollowPolicy
= $policy;
930 * Set the new value of the "action text", this will be added to the
931 * "HTML title", separated from it with " - ".
933 * @param string $text New value of the "action text"
935 public function setPageTitleActionText( $text ) {
936 $this->mPageTitleActionText
= $text;
940 * Get the value of the "action text"
944 public function getPageTitleActionText() {
945 return $this->mPageTitleActionText
;
949 * "HTML title" means the contents of "<title>".
950 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
952 * @param string|Message $name
954 public function setHTMLTitle( $name ) {
955 if ( $name instanceof Message
) {
956 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
958 $this->mHTMLtitle
= $name;
963 * Return the "HTML title", i.e. the content of the "<title>" tag.
967 public function getHTMLTitle() {
968 return $this->mHTMLtitle
;
972 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
976 public function setRedirectedFrom( $t ) {
977 $this->mRedirectedFrom
= $t;
981 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
982 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
983 * but not bad tags like \<script\>. This function automatically sets
984 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
985 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
986 * good tags like \<i\> will be dropped entirely.
988 * @param string|Message $name
990 public function setPageTitle( $name ) {
991 if ( $name instanceof Message
) {
992 $name = $name->setContext( $this->getContext() )->text();
995 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
996 # but leave "<i>foobar</i>" alone
997 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
998 $this->mPagetitle
= $nameWithTags;
1000 # change "<i>foo&bar</i>" to "foo&bar"
1001 $this->setHTMLTitle(
1002 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
1003 ->inContentLanguage()
1008 * Return the "page title", i.e. the content of the \<h1\> tag.
1012 public function getPageTitle() {
1013 return $this->mPagetitle
;
1017 * Set the Title object to use
1021 public function setTitle( Title
$t ) {
1022 $this->getContext()->setTitle( $t );
1026 * Replace the subtitle with $str
1028 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1030 public function setSubtitle( $str ) {
1031 $this->clearSubtitle();
1032 $this->addSubtitle( $str );
1036 * Add $str to the subtitle
1038 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1040 public function addSubtitle( $str ) {
1041 if ( $str instanceof Message
) {
1042 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1044 $this->mSubtitle
[] = $str;
1049 * Build message object for a subtitle containing a backlink to a page
1051 * @param Title $title Title to link to
1052 * @param array $query Array of additional parameters to include in the link
1056 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1057 if ( $title->isRedirect() ) {
1058 $query['redirect'] = 'no';
1060 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1061 return wfMessage( 'backlinksubtitle' )
1062 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1066 * Add a subtitle containing a backlink to a page
1068 * @param Title $title Title to link to
1069 * @param array $query Array of additional parameters to include in the link
1071 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1072 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1076 * Clear the subtitles
1078 public function clearSubtitle() {
1079 $this->mSubtitle
= [];
1087 public function getSubtitle() {
1088 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1092 * Set the page as printable, i.e. it'll be displayed with all
1093 * print styles included
1095 public function setPrintable() {
1096 $this->mPrintable
= true;
1100 * Return whether the page is "printable"
1104 public function isPrintable() {
1105 return $this->mPrintable
;
1109 * Disable output completely, i.e. calling output() will have no effect
1111 public function disable() {
1112 $this->mDoNothing
= true;
1116 * Return whether the output will be completely disabled
1120 public function isDisabled() {
1121 return $this->mDoNothing
;
1125 * Show an "add new section" link?
1129 public function showNewSectionLink() {
1130 return $this->mNewSectionLink
;
1134 * Forcibly hide the new section link?
1138 public function forceHideNewSectionLink() {
1139 return $this->mHideNewSectionLink
;
1143 * Add or remove feed links in the page header
1144 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1145 * for the new version
1146 * @see addFeedLink()
1148 * @param bool $show True: add default feeds, false: remove all feeds
1150 public function setSyndicated( $show = true ) {
1152 $this->setFeedAppendQuery( false );
1154 $this->mFeedLinks
= [];
1159 * Add default feeds to the page header
1160 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1161 * for the new version
1162 * @see addFeedLink()
1164 * @param string $val Query to append to feed links or false to output
1167 public function setFeedAppendQuery( $val ) {
1168 $this->mFeedLinks
= [];
1170 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1171 $query = "feed=$type";
1172 if ( is_string( $val ) ) {
1173 $query .= '&' . $val;
1175 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1180 * Add a feed link to the page header
1182 * @param string $format Feed type, should be a key of $wgFeedClasses
1183 * @param string $href URL
1185 public function addFeedLink( $format, $href ) {
1186 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1187 $this->mFeedLinks
[$format] = $href;
1192 * Should we output feed links for this page?
1195 public function isSyndicated() {
1196 return count( $this->mFeedLinks
) > 0;
1200 * Return URLs for each supported syndication format for this page.
1201 * @return array Associating format keys with URLs
1203 public function getSyndicationLinks() {
1204 return $this->mFeedLinks
;
1208 * Will currently always return null
1212 public function getFeedAppendQuery() {
1213 return $this->mFeedLinksAppendQuery
;
1217 * Set whether the displayed content is related to the source of the
1218 * corresponding article on the wiki
1219 * Setting true will cause the change "article related" toggle to true
1223 public function setArticleFlag( $v ) {
1224 $this->mIsarticle
= $v;
1226 $this->mIsArticleRelated
= $v;
1231 * Return whether the content displayed page is related to the source of
1232 * the corresponding article on the wiki
1236 public function isArticle() {
1237 return $this->mIsarticle
;
1241 * Set whether this page is related an article on the wiki
1242 * Setting false will cause the change of "article flag" toggle to false
1246 public function setArticleRelated( $v ) {
1247 $this->mIsArticleRelated
= $v;
1249 $this->mIsarticle
= false;
1254 * Return whether this page is related an article on the wiki
1258 public function isArticleRelated() {
1259 return $this->mIsArticleRelated
;
1263 * Add new language links
1265 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1266 * (e.g. 'fr:Test page')
1268 public function addLanguageLinks( array $newLinkArray ) {
1269 $this->mLanguageLinks +
= $newLinkArray;
1273 * Reset the language links and add new language links
1275 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1276 * (e.g. 'fr:Test page')
1278 public function setLanguageLinks( array $newLinkArray ) {
1279 $this->mLanguageLinks
= $newLinkArray;
1283 * Get the list of language links
1285 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1287 public function getLanguageLinks() {
1288 return $this->mLanguageLinks
;
1292 * Add an array of categories, with names in the keys
1294 * @param array $categories Mapping category name => sort key
1296 public function addCategoryLinks( array $categories ) {
1299 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1303 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1305 # Set all the values to 'normal'.
1306 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1308 # Mark hidden categories
1309 foreach ( $res as $row ) {
1310 if ( isset( $row->pp_value
) ) {
1311 $categories[$row->page_title
] = 'hidden';
1315 // Avoid PHP 7.1 warning of passing $this by reference
1316 $outputPage = $this;
1317 # Add the remaining categories to the skin
1319 'OutputPageMakeCategoryLinks',
1320 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1322 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1323 foreach ( $categories as $category => $type ) {
1324 // array keys will cast numeric category names to ints, so cast back to string
1325 $category = (string)$category;
1326 $origcategory = $category;
1327 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1331 $wgContLang->findVariantLink( $category, $title, true );
1332 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1335 $text = $wgContLang->convertHtml( $title->getText() );
1336 $this->mCategories
[$type][] = $title->getText();
1337 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1343 * @param array $categories
1344 * @return bool|ResultWrapper
1346 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1347 # Add the links to a LinkBatch
1348 $arr = [ NS_CATEGORY
=> $categories ];
1349 $lb = new LinkBatch
;
1350 $lb->setArray( $arr );
1352 # Fetch existence plus the hiddencat property
1353 $dbr = wfGetDB( DB_REPLICA
);
1354 $fields = array_merge(
1355 LinkCache
::getSelectFields(),
1356 [ 'page_namespace', 'page_title', 'pp_value' ]
1359 $res = $dbr->select( [ 'page', 'page_props' ],
1361 $lb->constructSet( 'page', $dbr ),
1364 [ 'page_props' => [ 'LEFT JOIN', [
1365 'pp_propname' => 'hiddencat',
1370 # Add the results to the link cache
1371 $lb->addResultToCache( LinkCache
::singleton(), $res );
1377 * Reset the category links (but not the category list) and add $categories
1379 * @param array $categories Mapping category name => sort key
1381 public function setCategoryLinks( array $categories ) {
1382 $this->mCategoryLinks
= [];
1383 $this->addCategoryLinks( $categories );
1387 * Get the list of category links, in a 2-D array with the following format:
1388 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1389 * hidden categories) and $link a HTML fragment with a link to the category
1394 public function getCategoryLinks() {
1395 return $this->mCategoryLinks
;
1399 * Get the list of category names this page belongs to.
1401 * @param string $type The type of categories which should be returned. Possible values:
1402 * * all: all categories of all types
1403 * * hidden: only the hidden categories
1404 * * normal: all categories, except hidden categories
1405 * @return array Array of strings
1407 public function getCategories( $type = 'all' ) {
1408 if ( $type === 'all' ) {
1409 $allCategories = [];
1410 foreach ( $this->mCategories
as $categories ) {
1411 $allCategories = array_merge( $allCategories, $categories );
1413 return $allCategories;
1415 if ( !isset( $this->mCategories
[$type] ) ) {
1416 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1418 return $this->mCategories
[$type];
1422 * Add an array of indicators, with their identifiers as array
1423 * keys and HTML contents as values.
1425 * In case of duplicate keys, existing values are overwritten.
1427 * @param array $indicators
1430 public function setIndicators( array $indicators ) {
1431 $this->mIndicators
= $indicators +
$this->mIndicators
;
1432 // Keep ordered by key
1433 ksort( $this->mIndicators
);
1437 * Get the indicators associated with this page.
1439 * The array will be internally ordered by item keys.
1441 * @return array Keys: identifiers, values: HTML contents
1444 public function getIndicators() {
1445 return $this->mIndicators
;
1449 * Adds help link with an icon via page indicators.
1450 * Link target can be overridden by a local message containing a wikilink:
1451 * the message key is: lowercase action or special page name + '-helppage'.
1452 * @param string $to Target MediaWiki.org page title or encoded URL.
1453 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1456 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1457 $this->addModuleStyles( 'mediawiki.helplink' );
1458 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1460 if ( $overrideBaseUrl ) {
1463 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1464 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1467 $link = Html
::rawElement(
1471 'target' => '_blank',
1472 'class' => 'mw-helplink',
1477 $this->setIndicators( [ 'mw-helplink' => $link ] );
1481 * Do not allow scripts which can be modified by wiki users to load on this page;
1482 * only allow scripts bundled with, or generated by, the software.
1483 * Site-wide styles are controlled by a config setting, since they can be
1484 * used to create a custom skin/theme, but not user-specific ones.
1486 * @todo this should be given a more accurate name
1488 public function disallowUserJs() {
1489 $this->reduceAllowedModules(
1490 ResourceLoaderModule
::TYPE_SCRIPTS
,
1491 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1494 // Site-wide styles are controlled by a config setting, see T73621
1495 // for background on why. User styles are never allowed.
1496 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1497 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1499 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1501 $this->reduceAllowedModules(
1502 ResourceLoaderModule
::TYPE_STYLES
,
1508 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1509 * @see ResourceLoaderModule::$origin
1510 * @param string $type ResourceLoaderModule TYPE_ constant
1511 * @return int ResourceLoaderModule ORIGIN_ class constant
1513 public function getAllowedModules( $type ) {
1514 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1515 return min( array_values( $this->mAllowedModules
) );
1517 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1522 * Limit the highest level of CSS/JS untrustworthiness allowed.
1524 * If passed the same or a higher level than the current level of untrustworthiness set, the
1525 * level will remain unchanged.
1527 * @param string $type
1528 * @param int $level ResourceLoaderModule class constant
1530 public function reduceAllowedModules( $type, $level ) {
1531 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1535 * Prepend $text to the body HTML
1537 * @param string $text HTML
1539 public function prependHTML( $text ) {
1540 $this->mBodytext
= $text . $this->mBodytext
;
1544 * Append $text to the body HTML
1546 * @param string $text HTML
1548 public function addHTML( $text ) {
1549 $this->mBodytext
.= $text;
1553 * Shortcut for adding an Html::element via addHTML.
1557 * @param string $element
1558 * @param array $attribs
1559 * @param string $contents
1561 public function addElement( $element, array $attribs = [], $contents = '' ) {
1562 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1566 * Clear the body HTML
1568 public function clearHTML() {
1569 $this->mBodytext
= '';
1575 * @return string HTML
1577 public function getHTML() {
1578 return $this->mBodytext
;
1582 * Get/set the ParserOptions object to use for wikitext parsing
1584 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1585 * current ParserOption object. This parameter is deprecated since 1.31.
1586 * @return ParserOptions
1588 public function parserOptions( $options = null ) {
1589 if ( $options !== null ) {
1590 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1593 if ( $options !== null && !empty( $options->isBogus
) ) {
1594 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1595 // been changed somehow, and keep it if so.
1596 $anonPO = ParserOptions
::newFromAnon();
1597 $anonPO->setAllowUnsafeRawHtml( false );
1598 if ( !$options->matches( $anonPO ) ) {
1599 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1600 $options->isBogus
= false;
1604 if ( !$this->mParserOptions
) {
1605 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1606 // $wgUser isn't unstubbable yet, so don't try to get a
1607 // ParserOptions for it. And don't cache this ParserOptions
1609 $po = ParserOptions
::newFromAnon();
1610 $po->setAllowUnsafeRawHtml( false );
1611 $po->isBogus
= true;
1612 if ( $options !== null ) {
1613 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1618 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1619 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1622 if ( $options !== null && !empty( $options->isBogus
) ) {
1623 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1625 return wfSetVar( $this->mParserOptions
, null, true );
1627 return wfSetVar( $this->mParserOptions
, $options );
1632 * Set the revision ID which will be seen by the wiki text parser
1633 * for things such as embedded {{REVISIONID}} variable use.
1635 * @param int|null $revid An positive integer, or null
1636 * @return mixed Previous value
1638 public function setRevisionId( $revid ) {
1639 $val = is_null( $revid ) ?
null : intval( $revid );
1640 return wfSetVar( $this->mRevisionId
, $val );
1644 * Get the displayed revision ID
1648 public function getRevisionId() {
1649 return $this->mRevisionId
;
1653 * Set the timestamp of the revision which will be displayed. This is used
1654 * to avoid a extra DB call in Skin::lastModified().
1656 * @param string|null $timestamp
1657 * @return mixed Previous value
1659 public function setRevisionTimestamp( $timestamp ) {
1660 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1664 * Get the timestamp of displayed revision.
1665 * This will be null if not filled by setRevisionTimestamp().
1667 * @return string|null
1669 public function getRevisionTimestamp() {
1670 return $this->mRevisionTimestamp
;
1674 * Set the displayed file version
1676 * @param File|bool $file
1677 * @return mixed Previous value
1679 public function setFileVersion( $file ) {
1681 if ( $file instanceof File
&& $file->exists() ) {
1682 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1684 return wfSetVar( $this->mFileVersion
, $val, true );
1688 * Get the displayed file version
1690 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1692 public function getFileVersion() {
1693 return $this->mFileVersion
;
1697 * Get the templates used on this page
1699 * @return array (namespace => dbKey => revId)
1702 public function getTemplateIds() {
1703 return $this->mTemplateIds
;
1707 * Get the files used on this page
1709 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1712 public function getFileSearchOptions() {
1713 return $this->mImageTimeKeys
;
1717 * Convert wikitext to HTML and add it to the buffer
1718 * Default assumes that the current page title will be used.
1720 * @param string $text
1721 * @param bool $linestart Is this the start of a line?
1722 * @param bool $interface Is this text in the user interface language?
1723 * @throws MWException
1725 public function addWikiText( $text, $linestart = true, $interface = true ) {
1726 $title = $this->getTitle(); // Work around E_STRICT
1728 throw new MWException( 'Title is null' );
1730 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1734 * Add wikitext with a custom Title object
1736 * @param string $text Wikitext
1737 * @param Title &$title
1738 * @param bool $linestart Is this the start of a line?
1740 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1741 $this->addWikiTextTitle( $text, $title, $linestart );
1745 * Add wikitext with a custom Title object and tidy enabled.
1747 * @param string $text Wikitext
1748 * @param Title &$title
1749 * @param bool $linestart Is this the start of a line?
1751 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1752 $this->addWikiTextTitle( $text, $title, $linestart, true );
1756 * Add wikitext with tidy enabled
1758 * @param string $text Wikitext
1759 * @param bool $linestart Is this the start of a line?
1761 public function addWikiTextTidy( $text, $linestart = true ) {
1762 $title = $this->getTitle();
1763 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1767 * Add wikitext with a custom Title object
1769 * @param string $text Wikitext
1770 * @param Title $title
1771 * @param bool $linestart Is this the start of a line?
1772 * @param bool $tidy Whether to use tidy
1773 * @param bool $interface Whether it is an interface message
1774 * (for example disables conversion)
1776 public function addWikiTextTitle( $text, Title
$title, $linestart,
1777 $tidy = false, $interface = false
1781 $popts = $this->parserOptions();
1782 $oldTidy = $popts->setTidy( $tidy );
1783 $popts->setInterfaceMessage( (bool)$interface );
1785 $parserOutput = $wgParser->getFreshParser()->parse(
1786 $text, $title, $popts,
1787 $linestart, true, $this->mRevisionId
1790 $popts->setTidy( $oldTidy );
1792 $this->addParserOutput( $parserOutput, [
1793 'enableSectionEditLinks' => false,
1798 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1799 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1803 * @param ParserOutput $parserOutput
1805 public function addParserOutputMetadata( $parserOutput ) {
1806 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1807 $this->addCategoryLinks( $parserOutput->getCategories() );
1808 $this->setIndicators( $parserOutput->getIndicators() );
1809 $this->mNewSectionLink
= $parserOutput->getNewSection();
1810 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1812 if ( !$parserOutput->isCacheable() ) {
1813 $this->enableClientCache( false );
1815 $this->mNoGallery
= $parserOutput->getNoGallery();
1816 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1817 $this->addModules( $parserOutput->getModules() );
1818 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1819 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1820 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1821 $this->mPreventClickjacking
= $this->mPreventClickjacking
1822 ||
$parserOutput->preventClickjacking();
1824 // Template versioning...
1825 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1826 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1827 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1829 $this->mTemplateIds
[$ns] = $dbks;
1832 // File versioning...
1833 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1834 $this->mImageTimeKeys
[$dbk] = $data;
1837 // Hooks registered in the object
1838 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1839 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1840 list( $hookName, $data ) = $hookInfo;
1841 if ( isset( $parserOutputHooks[$hookName] ) ) {
1842 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1846 // Enable OOUI if requested via ParserOutput
1847 if ( $parserOutput->getEnableOOUI() ) {
1848 $this->enableOOUI();
1851 // Include parser limit report
1852 if ( !$this->limitReportJSData
) {
1853 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1856 // Link flags are ignored for now, but may in the future be
1857 // used to mark individual language links.
1859 // Avoid PHP 7.1 warning of passing $this by reference
1860 $outputPage = $this;
1861 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1862 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1864 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1865 // so that extensions may modify ParserOutput to toggle TOC.
1866 // This cannot be moved to addParserOutputText because that is not
1867 // called by EditPage for Preview.
1868 if ( $parserOutput->getTOCHTML() ) {
1869 $this->mEnableTOC
= true;
1874 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1875 * ParserOutput object, without any other metadata.
1878 * @param ParserOutput $parserOutput
1879 * @param array $poOptions Options to ParserOutput::getText()
1881 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1882 $this->addParserOutputText( $parserOutput, $poOptions );
1884 $this->addModules( $parserOutput->getModules() );
1885 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1886 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1888 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1892 * Add the HTML associated with a ParserOutput object, without any metadata.
1895 * @param ParserOutput $parserOutput
1896 * @param array $poOptions Options to ParserOutput::getText()
1898 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1899 $text = $parserOutput->getText( $poOptions );
1900 // Avoid PHP 7.1 warning of passing $this by reference
1901 $outputPage = $this;
1902 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1903 $this->addHTML( $text );
1907 * Add everything from a ParserOutput object.
1909 * @param ParserOutput $parserOutput
1910 * @param array $poOptions Options to ParserOutput::getText()
1912 function addParserOutput( $parserOutput, $poOptions = [] ) {
1913 $this->addParserOutputMetadata( $parserOutput );
1914 $this->addParserOutputText( $parserOutput, $poOptions );
1918 * Add the output of a QuickTemplate to the output buffer
1920 * @param QuickTemplate &$template
1922 public function addTemplate( &$template ) {
1923 $this->addHTML( $template->getHTML() );
1927 * Parse wikitext and return the HTML.
1929 * @param string $text
1930 * @param bool $linestart Is this the start of a line?
1931 * @param bool $interface Use interface language ($wgLang instead of
1932 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1933 * This also disables LanguageConverter.
1934 * @param Language $language Target language object, will override $interface
1935 * @throws MWException
1936 * @return string HTML
1938 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1941 if ( is_null( $this->getTitle() ) ) {
1942 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1945 $popts = $this->parserOptions();
1947 $popts->setInterfaceMessage( true );
1949 if ( $language !== null ) {
1950 $oldLang = $popts->setTargetLanguage( $language );
1953 $parserOutput = $wgParser->getFreshParser()->parse(
1954 $text, $this->getTitle(), $popts,
1955 $linestart, true, $this->mRevisionId
1959 $popts->setInterfaceMessage( false );
1961 if ( $language !== null ) {
1962 $popts->setTargetLanguage( $oldLang );
1965 return $parserOutput->getText( [
1966 'enableSectionEditLinks' => false,
1971 * Parse wikitext, strip paragraphs, and return the HTML.
1973 * @param string $text
1974 * @param bool $linestart Is this the start of a line?
1975 * @param bool $interface Use interface language ($wgLang instead of
1976 * $wgContLang) while parsing language sensitive magic
1977 * words like GRAMMAR and PLURAL
1978 * @return string HTML
1980 public function parseInline( $text, $linestart = true, $interface = false ) {
1981 $parsed = $this->parse( $text, $linestart, $interface );
1982 return Parser
::stripOuterParagraph( $parsed );
1986 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1988 * @param int $maxage Maximum cache time on the CDN, in seconds.
1990 public function setCdnMaxage( $maxage ) {
1991 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1995 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1997 * @param int $maxage Maximum cache time on the CDN, in seconds
2000 public function lowerCdnMaxage( $maxage ) {
2001 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2002 $this->setCdnMaxage( $this->mCdnMaxage
);
2006 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2008 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2009 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2010 * TTL is 90% of the age of the object, subject to the min and max.
2012 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2013 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2014 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2015 * @return int TTL in seconds
2018 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2019 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2020 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2022 if ( $mtime === null ||
$mtime === false ) {
2023 return $minTTL; // entity does not exist
2026 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2027 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2028 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2030 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2032 return $adaptiveTTL;
2036 * Use enableClientCache(false) to force it to send nocache headers
2038 * @param bool $state
2042 public function enableClientCache( $state ) {
2043 return wfSetVar( $this->mEnableClientCache
, $state );
2047 * Get the list of cookies that will influence on the cache
2051 function getCacheVaryCookies() {
2053 if ( $cookies === null ) {
2054 $config = $this->getConfig();
2055 $cookies = array_merge(
2056 SessionManager
::singleton()->getVaryCookies(),
2060 $config->get( 'CacheVaryCookies' )
2062 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2068 * Check if the request has a cache-varying cookie header
2069 * If it does, it's very important that we don't allow public caching
2073 function haveCacheVaryCookies() {
2074 $request = $this->getRequest();
2075 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2076 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2077 wfDebug( __METHOD__
. ": found $cookieName\n" );
2081 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2086 * Add an HTTP header that will influence on the cache
2088 * @param string $header Header name
2089 * @param string[]|null $option Options for the Key header. See
2090 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2091 * for the list of valid options.
2093 public function addVaryHeader( $header, array $option = null ) {
2094 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2095 $this->mVaryHeader
[$header] = [];
2097 if ( !is_array( $option ) ) {
2100 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2104 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2105 * such as Accept-Encoding or Cookie
2109 public function getVaryHeader() {
2110 // If we vary on cookies, let's make sure it's always included here too.
2111 if ( $this->getCacheVaryCookies() ) {
2112 $this->addVaryHeader( 'Cookie' );
2115 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2116 $this->addVaryHeader( $header, $options );
2118 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2122 * Add an HTTP Link: header
2124 * @param string $header Header value
2126 public function addLinkHeader( $header ) {
2127 $this->mLinkHeader
[] = $header;
2131 * Return a Link: header. Based on the values of $mLinkHeader.
2135 public function getLinkHeader() {
2136 if ( !$this->mLinkHeader
) {
2140 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2144 * Get a complete Key header
2148 public function getKeyHeader() {
2149 $cvCookies = $this->getCacheVaryCookies();
2151 $cookiesOption = [];
2152 foreach ( $cvCookies as $cookieName ) {
2153 $cookiesOption[] = 'param=' . $cookieName;
2155 $this->addVaryHeader( 'Cookie', $cookiesOption );
2157 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2158 $this->addVaryHeader( $header, $options );
2162 foreach ( $this->mVaryHeader
as $header => $option ) {
2163 $newheader = $header;
2164 if ( is_array( $option ) && count( $option ) > 0 ) {
2165 $newheader .= ';' . implode( ';', $option );
2167 $headers[] = $newheader;
2169 $key = 'Key: ' . implode( ',', $headers );
2175 * T23672: Add Accept-Language to Vary and Key headers
2176 * if there's no 'variant' parameter existed in GET.
2179 * /w/index.php?title=Main_page should always be served; but
2180 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2182 function addAcceptLanguage() {
2183 $title = $this->getTitle();
2184 if ( !$title instanceof Title
) {
2188 $lang = $title->getPageLanguage();
2189 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2190 $variants = $lang->getVariants();
2192 foreach ( $variants as $variant ) {
2193 if ( $variant === $lang->getCode() ) {
2196 $aloption[] = 'substr=' . $variant;
2198 // IE and some other browsers use BCP 47 standards in
2199 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2200 // We should handle these too.
2201 $variantBCP47 = LanguageCode
::bcp47( $variant );
2202 if ( $variantBCP47 !== $variant ) {
2203 $aloption[] = 'substr=' . $variantBCP47;
2207 $this->addVaryHeader( 'Accept-Language', $aloption );
2212 * Set a flag which will cause an X-Frame-Options header appropriate for
2213 * edit pages to be sent. The header value is controlled by
2214 * $wgEditPageFrameOptions.
2216 * This is the default for special pages. If you display a CSRF-protected
2217 * form on an ordinary view page, then you need to call this function.
2219 * @param bool $enable
2221 public function preventClickjacking( $enable = true ) {
2222 $this->mPreventClickjacking
= $enable;
2226 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2227 * This can be called from pages which do not contain any CSRF-protected
2230 public function allowClickjacking() {
2231 $this->mPreventClickjacking
= false;
2235 * Get the prevent-clickjacking flag
2240 public function getPreventClickjacking() {
2241 return $this->mPreventClickjacking
;
2245 * Get the X-Frame-Options header value (without the name part), or false
2246 * if there isn't one. This is used by Skin to determine whether to enable
2247 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2249 * @return string|false
2251 public function getFrameOptions() {
2252 $config = $this->getConfig();
2253 if ( $config->get( 'BreakFrames' ) ) {
2255 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2256 return $config->get( 'EditPageFrameOptions' );
2262 * Send cache control HTTP headers
2264 public function sendCacheControl() {
2265 $response = $this->getRequest()->response();
2266 $config = $this->getConfig();
2268 $this->addVaryHeader( 'Cookie' );
2269 $this->addAcceptLanguage();
2271 # don't serve compressed data to clients who can't handle it
2272 # maintain different caches for logged-in users and non-logged in ones
2273 $response->header( $this->getVaryHeader() );
2275 if ( $config->get( 'UseKeyHeader' ) ) {
2276 $response->header( $this->getKeyHeader() );
2279 if ( $this->mEnableClientCache
) {
2281 $config->get( 'UseSquid' ) &&
2282 !$response->hasCookies() &&
2283 !SessionManager
::getGlobalSession()->isPersistent() &&
2284 !$this->isPrintable() &&
2285 $this->mCdnMaxage
!= 0 &&
2286 !$this->haveCacheVaryCookies()
2288 if ( $config->get( 'UseESI' ) ) {
2289 # We'll purge the proxy cache explicitly, but require end user agents
2290 # to revalidate against the proxy on each visit.
2291 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2292 wfDebug( __METHOD__
.
2293 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2294 # start with a shorter timeout for initial testing
2295 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2297 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2298 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2300 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2302 # We'll purge the proxy cache for anons explicitly, but require end user agents
2303 # to revalidate against the proxy on each visit.
2304 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2305 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2306 wfDebug( __METHOD__
.
2307 ": local proxy caching; {$this->mLastModified} **", 'private' );
2308 # start with a shorter timeout for initial testing
2309 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2310 $response->header( "Cache-Control: " .
2311 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2314 # We do want clients to cache if they can, but they *must* check for updates
2315 # on revisiting the page.
2316 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2317 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2318 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2320 if ( $this->mLastModified
) {
2321 $response->header( "Last-Modified: {$this->mLastModified}" );
2324 wfDebug( __METHOD__
. ": no caching **", 'private' );
2326 # In general, the absence of a last modified header should be enough to prevent
2327 # the client from using its cache. We send a few other things just to make sure.
2328 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2329 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2330 $response->header( 'Pragma: no-cache' );
2335 * Transfer styles and JavaScript modules from skin.
2337 * @param Skin $sk to load modules for
2339 public function loadSkinModules( $sk ) {
2340 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2341 if ( $group === 'styles' ) {
2342 foreach ( $modules as $key => $moduleMembers ) {
2343 $this->addModuleStyles( $moduleMembers );
2346 $this->addModules( $modules );
2352 * Finally, all the text has been munged and accumulated into
2353 * the object, let's actually output it:
2355 * @param bool $return Set to true to get the result as a string rather than sending it
2356 * @return string|null
2358 * @throws FatalError
2359 * @throws MWException
2361 public function output( $return = false ) {
2364 if ( $this->mDoNothing
) {
2365 return $return ?
'' : null;
2368 $response = $this->getRequest()->response();
2369 $config = $this->getConfig();
2371 if ( $this->mRedirect
!= '' ) {
2372 # Standards require redirect URLs to be absolute
2373 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2375 $redirect = $this->mRedirect
;
2376 $code = $this->mRedirectCode
;
2378 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2379 if ( $code == '301' ||
$code == '303' ) {
2380 if ( !$config->get( 'DebugRedirects' ) ) {
2381 $response->statusHeader( $code );
2383 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2385 if ( $config->get( 'VaryOnXFP' ) ) {
2386 $this->addVaryHeader( 'X-Forwarded-Proto' );
2388 $this->sendCacheControl();
2390 $response->header( "Content-Type: text/html; charset=utf-8" );
2391 if ( $config->get( 'DebugRedirects' ) ) {
2392 $url = htmlspecialchars( $redirect );
2393 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2394 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2395 print "</body>\n</html>\n";
2397 $response->header( 'Location: ' . $redirect );
2401 return $return ?
'' : null;
2402 } elseif ( $this->mStatusCode
) {
2403 $response->statusHeader( $this->mStatusCode
);
2406 # Buffer output; final headers may depend on later processing
2409 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2410 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2412 if ( !$this->mArticleBodyOnly
) {
2413 $sk = $this->getSkin();
2415 if ( $sk->shouldPreloadLogo() ) {
2416 $this->addLogoPreloadLinkHeaders();
2420 $linkHeader = $this->getLinkHeader();
2421 if ( $linkHeader ) {
2422 $response->header( $linkHeader );
2425 // Prevent framing, if requested
2426 $frameOptions = $this->getFrameOptions();
2427 if ( $frameOptions ) {
2428 $response->header( "X-Frame-Options: $frameOptions" );
2431 ContentSecurityPolicy
::sendHeaders( $this );
2433 if ( $this->mArticleBodyOnly
) {
2434 echo $this->mBodytext
;
2436 // Enable safe mode if requested (T152169)
2437 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2438 $this->disallowUserJs();
2441 $sk = $this->getSkin();
2442 $this->loadSkinModules( $sk );
2444 MWDebug
::addModules( $this );
2446 // Avoid PHP 7.1 warning of passing $this by reference
2447 $outputPage = $this;
2448 // Hook that allows last minute changes to the output page, e.g.
2449 // adding of CSS or Javascript by extensions.
2450 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2454 } catch ( Exception
$e ) {
2455 ob_end_clean(); // bug T129657
2461 // This hook allows last minute changes to final overall output by modifying output buffer
2462 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2463 } catch ( Exception
$e ) {
2464 ob_end_clean(); // bug T129657
2468 $this->sendCacheControl();
2471 return ob_get_clean();
2479 * Prepare this object to display an error page; disable caching and
2480 * indexing, clear the current text and redirect, set the page's title
2481 * and optionally an custom HTML title (content of the "<title>" tag).
2483 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2484 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2485 * optional, if not passed the "<title>" attribute will be
2486 * based on $pageTitle
2488 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2489 $this->setPageTitle( $pageTitle );
2490 if ( $htmlTitle !== false ) {
2491 $this->setHTMLTitle( $htmlTitle );
2493 $this->setRobotPolicy( 'noindex,nofollow' );
2494 $this->setArticleRelated( false );
2495 $this->enableClientCache( false );
2496 $this->mRedirect
= '';
2497 $this->clearSubtitle();
2502 * Output a standard error page
2504 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2505 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2506 * showErrorPage( 'titlemsg', $messageObject );
2507 * showErrorPage( $titleMessageObject, $messageObject );
2509 * @param string|Message $title Message key (string) for page title, or a Message object
2510 * @param string|Message $msg Message key (string) for page text, or a Message object
2511 * @param array $params Message parameters; ignored if $msg is a Message object
2513 public function showErrorPage( $title, $msg, $params = [] ) {
2514 if ( !$title instanceof Message
) {
2515 $title = $this->msg( $title );
2518 $this->prepareErrorPage( $title );
2520 if ( $msg instanceof Message
) {
2521 if ( $params !== [] ) {
2522 trigger_error( 'Argument ignored: $params. The message parameters argument '
2523 . 'is discarded when the $msg argument is a Message object instead of '
2524 . 'a string.', E_USER_NOTICE
);
2526 $this->addHTML( $msg->parseAsBlock() );
2528 $this->addWikiMsgArray( $msg, $params );
2531 $this->returnToMain();
2535 * Output a standard permission error page
2537 * @param array $errors Error message keys or [key, param...] arrays
2538 * @param string $action Action that was denied or null if unknown
2540 public function showPermissionsErrorPage( array $errors, $action = null ) {
2541 foreach ( $errors as $key => $error ) {
2542 $errors[$key] = (array)$error;
2545 // For some action (read, edit, create and upload), display a "login to do this action"
2546 // error if all of the following conditions are met:
2547 // 1. the user is not logged in
2548 // 2. the only error is insufficient permissions (i.e. no block or something else)
2549 // 3. the error can be avoided simply by logging in
2550 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2551 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2552 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2553 && ( User
::groupHasPermission( 'user', $action )
2554 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2556 $displayReturnto = null;
2558 # Due to T34276, if a user does not have read permissions,
2559 # $this->getTitle() will just give Special:Badtitle, which is
2560 # not especially useful as a returnto parameter. Use the title
2561 # from the request instead, if there was one.
2562 $request = $this->getRequest();
2563 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2564 if ( $action == 'edit' ) {
2565 $msg = 'whitelistedittext';
2566 $displayReturnto = $returnto;
2567 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2568 $msg = 'nocreatetext';
2569 } elseif ( $action == 'upload' ) {
2570 $msg = 'uploadnologintext';
2572 $msg = 'loginreqpagetext';
2573 $displayReturnto = Title
::newMainPage();
2579 $query['returnto'] = $returnto->getPrefixedText();
2581 if ( !$request->wasPosted() ) {
2582 $returntoquery = $request->getValues();
2583 unset( $returntoquery['title'] );
2584 unset( $returntoquery['returnto'] );
2585 unset( $returntoquery['returntoquery'] );
2586 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2589 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2590 $loginLink = $linkRenderer->makeKnownLink(
2591 SpecialPage
::getTitleFor( 'Userlogin' ),
2592 $this->msg( 'loginreqlink' )->text(),
2597 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2598 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2600 # Don't return to a page the user can't read otherwise
2601 # we'll end up in a pointless loop
2602 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2603 $this->returnToMain( null, $displayReturnto );
2606 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2607 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2612 * Display an error page indicating that a given version of MediaWiki is
2613 * required to use it
2615 * @param mixed $version The version of MediaWiki needed to use the page
2617 public function versionRequired( $version ) {
2618 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2620 $this->addWikiMsg( 'versionrequiredtext', $version );
2621 $this->returnToMain();
2625 * Format a list of error messages
2627 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2628 * @param string $action Action that was denied or null if unknown
2629 * @return string The wikitext error-messages, formatted into a list.
2631 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2632 if ( $action == null ) {
2633 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2635 $action_desc = $this->msg( "action-$action" )->plain();
2637 'permissionserrorstext-withaction',
2640 )->plain() . "\n\n";
2643 if ( count( $errors ) > 1 ) {
2644 $text .= '<ul class="permissions-errors">' . "\n";
2646 foreach ( $errors as $error ) {
2648 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2653 $text .= "<div class=\"permissions-errors\">\n" .
2654 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2662 * Show a warning about replica DB lag
2664 * If the lag is higher than $wgSlaveLagCritical seconds,
2665 * then the warning is a bit more obvious. If the lag is
2666 * lower than $wgSlaveLagWarning, then no warning is shown.
2668 * @param int $lag Slave lag
2670 public function showLagWarning( $lag ) {
2671 $config = $this->getConfig();
2672 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2673 $lag = floor( $lag ); // floor to avoid nano seconds to display
2674 $message = $lag < $config->get( 'SlaveLagCritical' )
2677 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2678 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2682 public function showFatalError( $message ) {
2683 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2685 $this->addHTML( $message );
2688 public function showUnexpectedValueError( $name, $val ) {
2689 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2692 public function showFileCopyError( $old, $new ) {
2693 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2696 public function showFileRenameError( $old, $new ) {
2697 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2700 public function showFileDeleteError( $name ) {
2701 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2704 public function showFileNotFoundError( $name ) {
2705 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2709 * Add a "return to" link pointing to a specified title
2711 * @param Title $title Title to link
2712 * @param array $query Query string parameters
2713 * @param string $text Text of the link (input is not escaped)
2714 * @param array $options Options array to pass to Linker
2716 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2717 $linkRenderer = MediaWikiServices
::getInstance()
2718 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2719 $link = $this->msg( 'returnto' )->rawParams(
2720 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2721 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2725 * Add a "return to" link pointing to a specified title,
2726 * or the title indicated in the request, or else the main page
2728 * @param mixed $unused
2729 * @param Title|string $returnto Title or String to return to
2730 * @param string $returntoquery Query string for the return to link
2732 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2733 if ( $returnto == null ) {
2734 $returnto = $this->getRequest()->getText( 'returnto' );
2737 if ( $returntoquery == null ) {
2738 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2741 if ( $returnto === '' ) {
2742 $returnto = Title
::newMainPage();
2745 if ( is_object( $returnto ) ) {
2746 $titleObj = $returnto;
2748 $titleObj = Title
::newFromText( $returnto );
2750 // We don't want people to return to external interwiki. That
2751 // might potentially be used as part of a phishing scheme
2752 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2753 $titleObj = Title
::newMainPage();
2756 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2759 private function getRlClientContext() {
2760 if ( !$this->rlClientContext
) {
2761 $query = ResourceLoader
::makeLoaderQuery(
2762 [], // modules; not relevant
2763 $this->getLanguage()->getCode(),
2764 $this->getSkin()->getSkinName(),
2765 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2766 null, // version; not relevant
2767 ResourceLoader
::inDebugMode(),
2768 null, // only; not relevant
2769 $this->isPrintable(),
2770 $this->getRequest()->getBool( 'handheld' )
2772 $this->rlClientContext
= new ResourceLoaderContext(
2773 $this->getResourceLoader(),
2774 new FauxRequest( $query )
2776 if ( $this->contentOverrideCallbacks
) {
2777 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2778 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2779 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2780 $content = call_user_func( $callback, $title );
2781 if ( $content !== null ) {
2789 return $this->rlClientContext
;
2793 * Call this to freeze the module queue and JS config and create a formatter.
2795 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2796 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2797 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2798 * the module filters retroactively. Skins and extension hooks may also add modules until very
2799 * late in the request lifecycle.
2801 * @return ResourceLoaderClientHtml
2803 public function getRlClient() {
2804 if ( !$this->rlClient
) {
2805 $context = $this->getRlClientContext();
2806 $rl = $this->getResourceLoader();
2807 $this->addModules( [
2812 $this->addModuleStyles( [
2817 $this->getSkin()->setupSkinUserCss( $this );
2819 // Prepare exempt modules for buildExemptModules()
2820 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2822 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2824 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2825 // Separate user-specific batch for improved cache-hit ratio.
2826 $userBatch = [ 'user.styles', 'user' ];
2827 $siteBatch = array_diff( $moduleStyles, $userBatch );
2828 $dbr = wfGetDB( DB_REPLICA
);
2829 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2830 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2832 // Filter out modules handled by buildExemptModules()
2833 $moduleStyles = array_filter( $moduleStyles,
2834 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2835 $module = $rl->getModule( $name );
2837 $group = $module->getGroup();
2838 if ( isset( $exemptGroups[$group] ) ) {
2839 $exemptStates[$name] = 'ready';
2840 if ( !$module->isKnownEmpty( $context ) ) {
2841 // E.g. Don't output empty <styles>
2842 $exemptGroups[$group][] = $name;
2850 $this->rlExemptStyleModules
= $exemptGroups;
2852 $rlClient = new ResourceLoaderClientHtml( $context, [
2853 'target' => $this->getTarget(),
2854 'nonce' => $this->getCSPNonce(),
2855 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2856 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2857 // modules enqueud for loading on this page is filtered to just those.
2858 // However, to make sure we also apply the restriction to dynamic dependencies and
2859 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2860 // StartupModule so that the client-side registry will not contain any restricted
2861 // modules either. (T152169, T185303)
2862 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2863 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2866 $rlClient->setConfig( $this->getJSVars() );
2867 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2868 $rlClient->setModuleStyles( $moduleStyles );
2869 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2870 $rlClient->setExemptStates( $exemptStates );
2871 $this->rlClient
= $rlClient;
2873 return $this->rlClient
;
2877 * @param Skin $sk The given Skin
2878 * @param bool $includeStyle Unused
2879 * @return string The doctype, opening "<html>", and head element.
2881 public function headElement( Skin
$sk, $includeStyle = true ) {
2884 $userdir = $this->getLanguage()->getDir();
2885 $sitedir = $wgContLang->getDir();
2888 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2889 $this->getRlClient()->getDocumentAttributes(),
2890 $sk->getHtmlElementAttributes()
2892 $pieces[] = Html
::openElement( 'head' );
2894 if ( $this->getHTMLTitle() == '' ) {
2895 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2898 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2899 // Add <meta charset="UTF-8">
2900 // This should be before <title> since it defines the charset used by
2901 // text including the text inside <title>.
2902 // The spec recommends defining XHTML5's charset using the XML declaration
2904 // Our XML declaration is output by Html::htmlHeader.
2905 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2906 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2907 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2910 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2911 $pieces[] = $this->getRlClient()->getHeadHtml();
2912 $pieces[] = $this->buildExemptModules();
2913 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2914 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2916 // Use an IE conditional comment to serve the script only to old IE
2917 $pieces[] = '<!--[if lt IE 9]>' .
2918 ResourceLoaderClientHtml
::makeLoad(
2919 ResourceLoaderContext
::newDummyContext(),
2921 ResourceLoaderModule
::TYPE_SCRIPTS
,
2923 $this->getCSPNonce()
2927 $pieces[] = Html
::closeElement( 'head' );
2929 $bodyClasses = $this->mAdditionalBodyClasses
;
2930 $bodyClasses[] = 'mediawiki';
2932 # Classes for LTR/RTL directionality support
2933 $bodyClasses[] = $userdir;
2934 $bodyClasses[] = "sitedir-$sitedir";
2936 $underline = $this->getUser()->getOption( 'underline' );
2937 if ( $underline < 2 ) {
2938 // The following classes can be used here:
2939 // * mw-underline-always
2940 // * mw-underline-never
2941 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2944 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2945 # A <body> class is probably not the best way to do this . . .
2946 $bodyClasses[] = 'capitalize-all-nouns';
2949 // Parser feature migration class
2950 // The idea is that this will eventually be removed, after the wikitext
2951 // which requires it is cleaned up.
2952 $bodyClasses[] = 'mw-hide-empty-elt';
2954 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2955 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2957 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2960 // While the implode() is not strictly needed, it's used for backwards compatibility
2961 // (this used to be built as a string and hooks likely still expect that).
2962 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2964 // Allow skins and extensions to add body attributes they need
2965 $sk->addToBodyAttributes( $this, $bodyAttrs );
2966 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2968 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2970 return self
::combineWrappedStrings( $pieces );
2974 * Get a ResourceLoader object associated with this OutputPage
2976 * @return ResourceLoader
2978 public function getResourceLoader() {
2979 if ( is_null( $this->mResourceLoader
) ) {
2980 $this->mResourceLoader
= new ResourceLoader(
2982 LoggerFactory
::getInstance( 'resourceloader' )
2985 return $this->mResourceLoader
;
2989 * Explicily load or embed modules on a page.
2991 * @param array|string $modules One or more module names
2992 * @param string $only ResourceLoaderModule TYPE_ class constant
2993 * @param array $extraQuery [optional] Array with extra query parameters for the request
2994 * @return string|WrappedStringList HTML
2996 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2997 // Apply 'target' and 'origin' filters
2998 $modules = $this->filterModules( (array)$modules, null, $only );
3000 return ResourceLoaderClientHtml
::makeLoad(
3001 $this->getRlClientContext(),
3005 $this->getCSPNonce()
3010 * Combine WrappedString chunks and filter out empty ones
3012 * @param array $chunks
3013 * @return string|WrappedStringList HTML
3015 protected static function combineWrappedStrings( array $chunks ) {
3016 // Filter out empty values
3017 $chunks = array_filter( $chunks, 'strlen' );
3018 return WrappedString
::join( "\n", $chunks );
3022 * JS stuff to put at the bottom of the `<body>`.
3023 * These are legacy scripts ($this->mScripts), and user JS.
3025 * @return string|WrappedStringList HTML
3027 public function getBottomScripts() {
3029 $chunks[] = $this->getRlClient()->getBodyHtml();
3031 // Legacy non-ResourceLoader scripts
3032 $chunks[] = $this->mScripts
;
3034 if ( $this->limitReportJSData
) {
3035 $chunks[] = ResourceLoader
::makeInlineScript(
3036 ResourceLoader
::makeConfigSetScript(
3037 [ 'wgPageParseReport' => $this->limitReportJSData
]
3039 $this->getCSPNonce()
3043 return self
::combineWrappedStrings( $chunks );
3047 * Get the javascript config vars to include on this page
3049 * @return array Array of javascript config vars
3052 public function getJsConfigVars() {
3053 return $this->mJsConfigVars
;
3057 * Add one or more variables to be set in mw.config in JavaScript
3059 * @param string|array $keys Key or array of key/value pairs
3060 * @param mixed $value [optional] Value of the configuration variable
3062 public function addJsConfigVars( $keys, $value = null ) {
3063 if ( is_array( $keys ) ) {
3064 foreach ( $keys as $key => $value ) {
3065 $this->mJsConfigVars
[$key] = $value;
3070 $this->mJsConfigVars
[$keys] = $value;
3074 * Get an array containing the variables to be set in mw.config in JavaScript.
3076 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3077 * - in other words, page-independent/site-wide variables (without state).
3078 * You will only be adding bloat to the html page and causing page caches to
3079 * have to be purged on configuration changes.
3082 public function getJSVars() {
3087 $canonicalSpecialPageName = false; # T23115
3089 $title = $this->getTitle();
3090 $ns = $title->getNamespace();
3091 $canonicalNamespace = MWNamespace
::exists( $ns )
3092 ? MWNamespace
::getCanonicalName( $ns )
3093 : $title->getNsText();
3095 $sk = $this->getSkin();
3096 // Get the relevant title so that AJAX features can use the correct page name
3097 // when making API requests from certain special pages (T36972).
3098 $relevantTitle = $sk->getRelevantTitle();
3099 $relevantUser = $sk->getRelevantUser();
3101 if ( $ns == NS_SPECIAL
) {
3102 list( $canonicalSpecialPageName, /*...*/ ) =
3103 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3104 } elseif ( $this->canUseWikiPage() ) {
3105 $wikiPage = $this->getWikiPage();
3106 $curRevisionId = $wikiPage->getLatest();
3107 $articleId = $wikiPage->getId();
3110 $lang = $title->getPageViewLanguage();
3112 // Pre-process information
3113 $separatorTransTable = $lang->separatorTransformTable();
3114 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3115 $compactSeparatorTransTable = [
3116 implode( "\t", array_keys( $separatorTransTable ) ),
3117 implode( "\t", $separatorTransTable ),
3119 $digitTransTable = $lang->digitTransformTable();
3120 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3121 $compactDigitTransTable = [
3122 implode( "\t", array_keys( $digitTransTable ) ),
3123 implode( "\t", $digitTransTable ),
3126 $user = $this->getUser();
3129 'wgCanonicalNamespace' => $canonicalNamespace,
3130 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3131 'wgNamespaceNumber' => $title->getNamespace(),
3132 'wgPageName' => $title->getPrefixedDBkey(),
3133 'wgTitle' => $title->getText(),
3134 'wgCurRevisionId' => $curRevisionId,
3135 'wgRevisionId' => (int)$this->getRevisionId(),
3136 'wgArticleId' => $articleId,
3137 'wgIsArticle' => $this->isArticle(),
3138 'wgIsRedirect' => $title->isRedirect(),
3139 'wgAction' => Action
::getActionName( $this->getContext() ),
3140 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3141 'wgUserGroups' => $user->getEffectiveGroups(),
3142 'wgCategories' => $this->getCategories(),
3143 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3144 'wgPageContentLanguage' => $lang->getCode(),
3145 'wgPageContentModel' => $title->getContentModel(),
3146 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3147 'wgDigitTransformTable' => $compactDigitTransTable,
3148 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3149 'wgMonthNames' => $lang->getMonthNamesArray(),
3150 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3151 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3152 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3153 'wgRequestId' => WebRequest
::getRequestId(),
3156 if ( $user->isLoggedIn() ) {
3157 $vars['wgUserId'] = $user->getId();
3158 $vars['wgUserEditCount'] = $user->getEditCount();
3159 $userReg = $user->getRegistration();
3160 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3161 // Get the revision ID of the oldest new message on the user's talk
3162 // page. This can be used for constructing new message alerts on
3164 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3167 if ( $wgContLang->hasVariants() ) {
3168 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3170 // Same test as SkinTemplate
3171 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3172 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3174 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3175 && $relevantTitle->quickUserCan( 'edit', $user )
3176 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3178 foreach ( $title->getRestrictionTypes() as $type ) {
3179 // Following keys are set in $vars:
3180 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3181 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3184 if ( $title->isMainPage() ) {
3185 $vars['wgIsMainPage'] = true;
3188 if ( $this->mRedirectedFrom
) {
3189 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3192 if ( $relevantUser ) {
3193 $vars['wgRelevantUserName'] = $relevantUser->getName();
3196 // Allow extensions to add their custom variables to the mw.config map.
3197 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3198 // page-dependant but site-wide (without state).
3199 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3200 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3202 // Merge in variables from addJsConfigVars last
3203 return array_merge( $vars, $this->getJsConfigVars() );
3207 * To make it harder for someone to slip a user a fake
3208 * JavaScript or CSS preview, a random token
3209 * is associated with the login session. If it's not
3210 * passed back with the preview request, we won't render
3215 public function userCanPreview() {
3216 $request = $this->getRequest();
3218 $request->getVal( 'action' ) !== 'submit' ||
3219 !$request->wasPosted()
3224 $user = $this->getUser();
3226 if ( !$user->isLoggedIn() ) {
3227 // Anons have predictable edit tokens
3230 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3234 $title = $this->getTitle();
3235 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3236 if ( count( $errors ) !== 0 ) {
3244 * @return array Array in format "link name or number => 'link html'".
3246 public function getHeadLinksArray() {
3250 $config = $this->getConfig();
3252 $canonicalUrl = $this->mCanonicalUrl
;
3254 $tags['meta-generator'] = Html
::element( 'meta', [
3255 'name' => 'generator',
3256 'content' => "MediaWiki $wgVersion",
3259 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3260 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3261 // fallbacks should come before the primary value so we need to reverse the array.
3262 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3263 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3264 'name' => 'referrer',
3265 'content' => $policy,
3270 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3271 if ( $p !== 'index,follow' ) {
3272 // http://www.robotstxt.org/wc/meta-user.html
3273 // Only show if it's different from the default robots policy
3274 $tags['meta-robots'] = Html
::element( 'meta', [
3280 foreach ( $this->mMetatags
as $tag ) {
3281 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3283 $tag[0] = substr( $tag[0], 5 );
3284 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3289 $tagName = "meta-{$tag[0]}";
3290 if ( isset( $tags[$tagName] ) ) {
3291 $tagName .= $tag[1];
3293 $tags[$tagName] = Html
::element( 'meta',
3296 'content' => $tag[1]
3301 foreach ( $this->mLinktags
as $tag ) {
3302 $tags[] = Html
::element( 'link', $tag );
3305 # Universal edit button
3306 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3307 $user = $this->getUser();
3308 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3309 && ( $this->getTitle()->exists() ||
3310 $this->getTitle()->quickUserCan( 'create', $user ) )
3312 // Original UniversalEditButton
3313 $msg = $this->msg( 'edit' )->text();
3314 $tags['universal-edit-button'] = Html
::element( 'link', [
3315 'rel' => 'alternate',
3316 'type' => 'application/x-wiki',
3318 'href' => $this->getTitle()->getEditURL(),
3320 // Alternate edit link
3321 $tags['alternative-edit'] = Html
::element( 'link', [
3324 'href' => $this->getTitle()->getEditURL(),
3329 # Generally the order of the favicon and apple-touch-icon links
3330 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3331 # uses whichever one appears later in the HTML source. Make sure
3332 # apple-touch-icon is specified first to avoid this.
3333 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3334 $tags['apple-touch-icon'] = Html
::element( 'link', [
3335 'rel' => 'apple-touch-icon',
3336 'href' => $config->get( 'AppleTouchIcon' )
3340 if ( $config->get( 'Favicon' ) !== false ) {
3341 $tags['favicon'] = Html
::element( 'link', [
3342 'rel' => 'shortcut icon',
3343 'href' => $config->get( 'Favicon' )
3347 # OpenSearch description link
3348 $tags['opensearch'] = Html
::element( 'link', [
3350 'type' => 'application/opensearchdescription+xml',
3351 'href' => wfScript( 'opensearch_desc' ),
3352 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3355 # Real Simple Discovery link, provides auto-discovery information
3356 # for the MediaWiki API (and potentially additional custom API
3357 # support such as WordPress or Twitter-compatible APIs for a
3358 # blogging extension, etc)
3359 $tags['rsd'] = Html
::element( 'link', [
3361 'type' => 'application/rsd+xml',
3362 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3363 // Whether RSD accepts relative or protocol-relative URLs is completely
3364 // undocumented, though.
3365 'href' => wfExpandUrl( wfAppendQuery(
3367 [ 'action' => 'rsd' ] ),
3373 if ( !$config->get( 'DisableLangConversion' ) ) {
3374 $lang = $this->getTitle()->getPageLanguage();
3375 if ( $lang->hasVariants() ) {
3376 $variants = $lang->getVariants();
3377 foreach ( $variants as $variant ) {
3378 $tags["variant-$variant"] = Html
::element( 'link', [
3379 'rel' => 'alternate',
3380 'hreflang' => LanguageCode
::bcp47( $variant ),
3381 'href' => $this->getTitle()->getLocalURL(
3382 [ 'variant' => $variant ] )
3386 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3387 $tags["variant-x-default"] = Html
::element( 'link', [
3388 'rel' => 'alternate',
3389 'hreflang' => 'x-default',
3390 'href' => $this->getTitle()->getLocalURL() ] );
3395 if ( $this->copyrightUrl
!== null ) {
3396 $copyright = $this->copyrightUrl
;
3399 if ( $config->get( 'RightsPage' ) ) {
3400 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3403 $copyright = $copy->getLocalURL();
3407 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3408 $copyright = $config->get( 'RightsUrl' );
3413 $tags['copyright'] = Html
::element( 'link', [
3415 'href' => $copyright ]
3420 if ( $config->get( 'Feed' ) ) {
3423 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3424 # Use the page name for the title. In principle, this could
3425 # lead to issues with having the same name for different feeds
3426 # corresponding to the same page, but we can't avoid that at
3429 $feedLinks[] = $this->feedLink(
3432 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3434 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3439 # Recent changes feed should appear on every page (except recentchanges,
3440 # that would be redundant). Put it after the per-page feed to avoid
3441 # changing existing behavior. It's still available, probably via a
3442 # menu in your browser. Some sites might have a different feed they'd
3443 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3444 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3445 # If so, use it instead.
3446 $sitename = $config->get( 'Sitename' );
3447 if ( $config->get( 'OverrideSiteFeed' ) ) {
3448 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3449 // Note, this->feedLink escapes the url.
3450 $feedLinks[] = $this->feedLink(
3453 $this->msg( "site-{$type}-feed", $sitename )->text()
3456 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3457 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3458 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3459 $feedLinks[] = $this->feedLink(
3461 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3462 # For grep: 'site-rss-feed', 'site-atom-feed'
3463 $this->msg( "site-{$format}-feed", $sitename )->text()
3468 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3469 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3470 # use OutputPage::addFeedLink() instead.
3471 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3473 $tags +
= $feedLinks;
3477 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3478 if ( $canonicalUrl !== false ) {
3479 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3481 if ( $this->isArticleRelated() ) {
3482 // This affects all requests where "setArticleRelated" is true. This is
3483 // typically all requests that show content (query title, curid, oldid, diff),
3484 // and all wikipage actions (edit, delete, purge, info, history etc.).
3485 // It does not apply to File pages and Special pages.
3486 // 'history' and 'info' actions address page metadata rather than the page
3487 // content itself, so they may not be canonicalized to the view page url.
3488 // TODO: this ought to be better encapsulated in the Action class.
3489 $action = Action
::getActionName( $this->getContext() );
3490 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3491 $query = "action={$action}";
3495 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3497 $reqUrl = $this->getRequest()->getRequestURL();
3498 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3502 if ( $canonicalUrl !== false ) {
3503 $tags[] = Html
::element( 'link', [
3504 'rel' => 'canonical',
3505 'href' => $canonicalUrl
3513 * Generate a "<link rel/>" for a feed.
3515 * @param string $type Feed type
3516 * @param string $url URL to the feed
3517 * @param string $text Value of the "title" attribute
3518 * @return string HTML fragment
3520 private function feedLink( $type, $url, $text ) {
3521 return Html
::element( 'link', [
3522 'rel' => 'alternate',
3523 'type' => "application/$type+xml",
3530 * Add a local or specified stylesheet, with the given media options.
3531 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3533 * @param string $style URL to the file
3534 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3535 * @param string $condition For IE conditional comments, specifying an IE version
3536 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3538 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3541 $options['media'] = $media;
3544 $options['condition'] = $condition;
3547 $options['dir'] = $dir;
3549 $this->styles
[$style] = $options;
3553 * Adds inline CSS styles
3554 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3556 * @param mixed $style_css Inline CSS
3557 * @param string $flip Set to 'flip' to flip the CSS if needed
3559 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3560 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3561 # If wanted, and the interface is right-to-left, flip the CSS
3562 $style_css = CSSJanus
::transform( $style_css, true, false );
3564 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3568 * Build exempt modules and legacy non-ResourceLoader styles.
3570 * @return string|WrappedStringList HTML
3572 protected function buildExemptModules() {
3574 // Things that go after the ResourceLoaderDynamicStyles marker
3577 // We want site, private and user styles to override dynamically added styles from
3578 // general modules, but we want dynamically added styles to override statically added
3579 // style modules. So the order has to be:
3580 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3581 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3582 // - ResourceLoaderDynamicStyles marker
3583 // - site/private/user styles
3585 // Add legacy styles added through addStyle()/addInlineStyle() here
3586 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3588 $chunks[] = Html
::element(
3590 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3593 $separateReq = [ 'site.styles', 'user.styles' ];
3594 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3595 // Combinable modules
3596 $chunks[] = $this->makeResourceLoaderLink(
3597 array_diff( $moduleNames, $separateReq ),
3598 ResourceLoaderModule
::TYPE_STYLES
3601 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3602 // These require their own dedicated request in order to support "@import"
3603 // syntax, which is incompatible with concatenation. (T147667, T37562)
3604 $chunks[] = $this->makeResourceLoaderLink( $name,
3605 ResourceLoaderModule
::TYPE_STYLES
3610 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3616 public function buildCssLinksArray() {
3619 foreach ( $this->styles
as $file => $options ) {
3620 $link = $this->styleLink( $file, $options );
3622 $links[$file] = $link;
3629 * Generate \<link\> tags for stylesheets
3631 * @param string $style URL to the file
3632 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3633 * @return string HTML fragment
3635 protected function styleLink( $style, array $options ) {
3636 if ( isset( $options['dir'] ) ) {
3637 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3642 if ( isset( $options['media'] ) ) {
3643 $media = self
::transformCssMedia( $options['media'] );
3644 if ( is_null( $media ) ) {
3651 if ( substr( $style, 0, 1 ) == '/' ||
3652 substr( $style, 0, 5 ) == 'http:' ||
3653 substr( $style, 0, 6 ) == 'https:' ) {
3656 $config = $this->getConfig();
3657 // Append file hash as query parameter
3658 $url = self
::transformResourcePath(
3660 $config->get( 'StylePath' ) . '/' . $style
3664 $link = Html
::linkedStyle( $url, $media );
3666 if ( isset( $options['condition'] ) ) {
3667 $condition = htmlspecialchars( $options['condition'] );
3668 $link = "<!--[if $condition]>$link<![endif]-->";
3674 * Transform path to web-accessible static resource.
3676 * This is used to add a validation hash as query string.
3677 * This aids various behaviors:
3679 * - Put long Cache-Control max-age headers on responses for improved
3680 * cache performance.
3681 * - Get the correct version of a file as expected by the current page.
3682 * - Instantly get the updated version of a file after deployment.
3684 * Avoid using this for urls included in HTML as otherwise clients may get different
3685 * versions of a resource when navigating the site depending on when the page was cached.
3686 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3687 * an external stylesheet).
3690 * @param Config $config
3691 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3692 * @return string URL
3694 public static function transformResourcePath( Config
$config, $path ) {
3698 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3699 if ( $remotePathPrefix === '' ) {
3700 // The configured base path is required to be empty string for
3701 // wikis in the domain root
3704 $remotePath = $remotePathPrefix;
3706 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3707 // - Path is outside wgResourceBasePath, ignore.
3708 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3711 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3712 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3713 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3714 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3715 $uploadPath = $config->get( 'UploadPath' );
3716 if ( strpos( $path, $uploadPath ) === 0 ) {
3717 $localDir = $config->get( 'UploadDirectory' );
3718 $remotePathPrefix = $remotePath = $uploadPath;
3721 $path = RelPath
::getRelativePath( $path, $remotePath );
3722 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3726 * Utility method for transformResourceFilePath().
3728 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3731 * @param string $remotePathPrefix URL path prefix that points to $localPath
3732 * @param string $localPath File directory exposed at $remotePath
3733 * @param string $file Path to target file relative to $localPath
3734 * @return string URL
3736 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3737 $hash = md5_file( "$localPath/$file" );
3738 if ( $hash === false ) {
3739 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3742 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3746 * Transform "media" attribute based on request parameters
3748 * @param string $media Current value of the "media" attribute
3749 * @return string Modified value of the "media" attribute, or null to skip
3752 public static function transformCssMedia( $media ) {
3755 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3756 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3758 // Switch in on-screen display for media testing
3760 'printable' => 'print',
3761 'handheld' => 'handheld',
3763 foreach ( $switches as $switch => $targetMedia ) {
3764 if ( $wgRequest->getBool( $switch ) ) {
3765 if ( $media == $targetMedia ) {
3767 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3768 /* This regex will not attempt to understand a comma-separated media_query_list
3770 * Example supported values for $media:
3771 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3772 * Example NOT supported value for $media:
3773 * '3d-glasses, screen, print and resolution > 90dpi'
3775 * If it's a print request, we never want any kind of screen stylesheets
3776 * If it's a handheld request (currently the only other choice with a switch),
3777 * we don't want simple 'screen' but we might want screen queries that
3778 * have a max-width or something, so we'll pass all others on and let the
3779 * client do the query.
3781 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3792 * Add a wikitext-formatted message to the output.
3793 * This is equivalent to:
3795 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3797 public function addWikiMsg( /*...*/ ) {
3798 $args = func_get_args();
3799 $name = array_shift( $args );
3800 $this->addWikiMsgArray( $name, $args );
3804 * Add a wikitext-formatted message to the output.
3805 * Like addWikiMsg() except the parameters are taken as an array
3806 * instead of a variable argument list.
3808 * @param string $name
3809 * @param array $args
3811 public function addWikiMsgArray( $name, $args ) {
3812 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3816 * This function takes a number of message/argument specifications, wraps them in
3817 * some overall structure, and then parses the result and adds it to the output.
3819 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3820 * and so on. The subsequent arguments may be either
3821 * 1) strings, in which case they are message names, or
3822 * 2) arrays, in which case, within each array, the first element is the message
3823 * name, and subsequent elements are the parameters to that message.
3825 * Don't use this for messages that are not in the user's interface language.
3829 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3833 * $wgOut->addWikiText( "<div class='error'>\n"
3834 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3836 * The newline after the opening div is needed in some wikitext. See T21226.
3838 * @param string $wrap
3840 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3841 $msgSpecs = func_get_args();
3842 array_shift( $msgSpecs );
3843 $msgSpecs = array_values( $msgSpecs );
3845 foreach ( $msgSpecs as $n => $spec ) {
3846 if ( is_array( $spec ) ) {
3848 $name = array_shift( $args );
3849 if ( isset( $args['options'] ) ) {
3850 unset( $args['options'] );
3852 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3860 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3862 $this->addWikiText( $s );
3866 * Whether the output has a table of contents
3870 public function isTOCEnabled() {
3871 return $this->mEnableTOC
;
3875 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3878 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3880 public function enableSectionEditLinks( $flag = true ) {
3881 wfDeprecated( __METHOD__
, '1.31' );
3887 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3889 public function sectionEditLinksEnabled() {
3890 wfDeprecated( __METHOD__
, '1.31' );
3895 * Helper function to setup the PHP implementation of OOUI to use in this request.
3898 * @param String $skinName The Skin name to determine the correct OOUI theme
3899 * @param String $dir Language direction
3901 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3902 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3903 $theme = $themes[$skinName] ??
$themes['default'];
3904 // For example, 'OOUI\WikimediaUITheme'.
3905 $themeClass = "OOUI\\{$theme}Theme";
3906 OOUI\Theme
::setSingleton( new $themeClass() );
3907 OOUI\Element
::setDefaultDir( $dir );
3911 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3912 * MediaWiki and this OutputPage instance.
3916 public function enableOOUI() {
3918 strtolower( $this->getSkin()->getSkinName() ),
3919 $this->getLanguage()->getDir()
3921 $this->addModuleStyles( [
3922 'oojs-ui-core.styles',
3923 'oojs-ui.styles.indicators',
3924 'oojs-ui.styles.textures',
3925 'mediawiki.widgets.styles',
3926 'oojs-ui.styles.icons-content',
3927 'oojs-ui.styles.icons-alerts',
3928 'oojs-ui.styles.icons-interactions',
3933 * Add Link headers for preloading the wiki's logo.
3937 protected function addLogoPreloadLinkHeaders() {
3938 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3944 if ( !is_array( $logo ) ) {
3945 // No media queries required if we only have one variant
3946 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3950 if ( isset( $logo['svg'] ) ) {
3951 // No media queries required if we only have a 1x and svg variant
3952 // because all preload-capable browsers support SVGs
3953 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3957 foreach ( $logo as $dppx => $src ) {
3958 // Keys are in this format: "1.5x"
3959 $dppx = substr( $dppx, 0, -1 );
3960 $logosPerDppx[$dppx] = $src;
3963 // Because PHP can't have floats as array keys
3964 uksort( $logosPerDppx, function ( $a , $b ) {
3965 $a = floatval( $a );
3966 $b = floatval( $b );
3967 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3971 foreach ( $logosPerDppx as $dppx => $src ) {
3972 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3975 $logosCount = count( $logos );
3976 // Logic must match ResourceLoaderSkinModule:
3977 // - 1x applies to resolution < 1.5dppx
3978 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3979 // - 2x applies to resolution >= 2dppx
3980 // Note that min-resolution and max-resolution are both inclusive.
3981 for ( $i = 0; $i < $logosCount; $i++
) {
3984 // min-resolution is ">=" (larger than or equal to)
3985 // "not min-resolution" is essentially "<"
3986 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3987 } elseif ( $i !== $logosCount - 1 ) {
3989 // Media query expressions can only apply "not" to the entire expression
3990 // (e.g. can't express ">= 1.5 and not >= 2).
3991 // Workaround: Use <= 1.9999 in place of < 2.
3992 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
3993 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3994 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3997 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4000 $this->addLinkHeader(
4001 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
4007 * Get (and set if not yet set) the CSP nonce.
4009 * This value needs to be included in any <script> tags on the
4012 * @return string|bool Nonce or false to mean don't output nonce
4015 public function getCSPNonce() {
4016 if ( !ContentSecurityPolicy
::isEnabled( $this->getConfig() ) ) {
4019 if ( $this->CSPNonce
=== null ) {
4020 // XXX It might be expensive to generate randomness
4021 // on every request, on windows.
4022 $rand = MWCryptRand
::generate( 15 );
4023 $this->CSPNonce
= base64_encode( $rand );
4025 return $this->CSPNonce
;