3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Linker\LinkTarget
;
24 use MediaWiki\Logger\LoggerFactory
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Session\SessionManager
;
27 use Wikimedia\Rdbms\IResultWrapper
;
28 use Wikimedia\RelPath
;
29 use Wikimedia\WrappedString
;
30 use Wikimedia\WrappedStringList
;
33 * This class should be covered by a general architecture document which does
34 * not exist as of January 2011. This is one of the Core classes and should
35 * be read at least once by any new developers.
37 * This class is used to prepare the final rendering. A skin is then
38 * applied to the output parameters (links, javascript, html, categories ...).
40 * @todo FIXME: Another class handles sending the whole page to the client.
42 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
47 class OutputPage
extends ContextSource
{
48 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
49 protected $mMetatags = [];
52 protected $mLinktags = [];
55 protected $mCanonicalUrl = false;
58 * @var string The contents of <h1> */
59 private $mPageTitle = '';
62 * @var string The displayed title of the page. Different from page title
63 * if overridden by display title magic word or hooks. Can contain safe
64 * HTML. Different from page title which may contain messages such as
65 * "Editing X" which is displayed in h1. This can be used for other places
66 * where the page name is referred on the page.
68 private $displayTitle;
71 * @var string Contains all of the "<body>" content. Should be private we
72 * got set/get accessors and the append() method.
74 public $mBodytext = '';
76 /** @var string Stores contents of "<title>" tag */
77 private $mHTMLtitle = '';
80 * @var bool Is the displayed content related to the source of the
81 * corresponding wiki article.
83 private $mIsArticle = false;
85 /** @var bool Stores "article flag" toggle. */
86 private $mIsArticleRelated = true;
89 * @var bool We have to set isPrintable(). Some pages should
90 * never be printed (ex: redirections).
92 private $mPrintable = false;
95 * @var array Contains the page subtitle. Special pages usually have some
96 * links here. Don't confuse with site subtitle added by skins.
98 private $mSubtitle = [];
101 public $mRedirect = '';
104 protected $mStatusCode;
107 * @var string Used for sending cache control.
108 * The whole caching system should probably be moved into its own class.
110 protected $mLastModified = '';
113 protected $mCategoryLinks = [];
116 protected $mCategories = [
122 protected $mIndicators = [];
124 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
125 private $mLanguageLinks = [];
128 * Used for JavaScript (predates ResourceLoader)
129 * @todo We should split JS / CSS.
130 * mScripts content is inserted as is in "<head>" by Skin. This might
131 * contain either a link to a stylesheet or inline CSS.
133 private $mScripts = '';
135 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
136 protected $mInlineStyles = '';
139 * @var string Used by skin template.
140 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
142 public $mPageLinkTitle = '';
144 /** @var array Array of elements in "<head>". Parser might add its own headers! */
145 protected $mHeadItems = [];
147 /** @var array Additional <body> classes; there are also <body> classes from other sources */
148 protected $mAdditionalBodyClasses = [];
151 protected $mModules = [];
154 protected $mModuleScripts = [];
157 protected $mModuleStyles = [];
159 /** @var ResourceLoader */
160 protected $mResourceLoader;
162 /** @var ResourceLoaderClientHtml */
165 /** @var ResourceLoaderContext */
166 private $rlClientContext;
169 private $rlExemptStyleModules;
172 protected $mJsConfigVars = [];
175 protected $mTemplateIds = [];
178 protected $mImageTimeKeys = [];
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
186 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
187 * @see ResourceLoaderModule::$origin
188 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
190 protected $mAllowedModules = [
191 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
194 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
195 protected $mDoNothing = false;
200 protected $mContainsNewMagic = 0;
203 * lazy initialised, use parserOptions()
206 protected $mParserOptions = null;
209 * Handles the Atom / RSS links.
210 * We probably only support Atom in 2011.
211 * @see $wgAdvertisedFeedTypes
213 private $mFeedLinks = [];
215 // Gwicke work on squid caching? Roughly from 2003.
216 protected $mEnableClientCache = true;
218 /** @var bool Flag if output should only contain the body of the article. */
219 private $mArticleBodyOnly = false;
222 protected $mNewSectionLink = false;
225 protected $mHideNewSectionLink = false;
228 * @var bool Comes from the parser. This was probably made to load CSS/JS
229 * only if we had "<gallery>". Used directly in CategoryPage.php.
230 * Looks like ResourceLoader can replace this.
232 public $mNoGallery = false;
234 /** @var int Cache stuff. Looks like mEnableClientCache */
235 protected $mCdnMaxage = 0;
236 /** @var int Upper limit on mCdnMaxage */
237 protected $mCdnMaxageLimit = INF
;
240 * @var bool Controls if anti-clickjacking / frame-breaking headers will
241 * be sent. This should be done for pages where edit actions are possible.
242 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
244 protected $mPreventClickjacking = true;
246 /** @var int To include the variable {{REVISIONID}} */
247 private $mRevisionId = null;
250 private $mRevisionTimestamp = null;
253 protected $mFileVersion = null;
256 * @var array An array of stylesheet filenames (relative from skins path),
257 * with options for CSS media, IE conditions, and RTL/LTR direction.
258 * For internal use; add settings in the skin via $this->addStyle()
260 * Style again! This seems like a code duplication since we already have
261 * mStyles. This is what makes Open Source amazing.
263 protected $styles = [];
265 private $mIndexPolicy = 'index';
266 private $mFollowPolicy = 'follow';
269 * @var array Headers that cause the cache to vary. Key is header name, value is an array of
270 * options for the Key header.
272 private $mVaryHeader = [
273 'Accept-Encoding' => [ 'match=gzip' ],
277 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
282 private $mRedirectedFrom = null;
285 * Additional key => value data
287 private $mProperties = [];
290 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
292 private $mTarget = null;
295 * @var bool Whether parser output contains a table of contents
297 private $mEnableTOC = false;
300 * @var string|null The URL to send in a <link> element with rel=license
302 private $copyrightUrl;
304 /** @var array Profiling data */
305 private $limitReportJSData = [];
307 /** @var array Map Title to Content */
308 private $contentOverrides = [];
310 /** @var callable[] */
311 private $contentOverrideCallbacks = [];
314 * Link: header contents
316 private $mLinkHeader = [];
319 * @var string The nonce for Content-Security-Policy
324 * Constructor for OutputPage. This should not be called directly.
325 * Instead a new RequestContext should be created and it will implicitly create
326 * a OutputPage tied to that context.
327 * @param IContextSource $context
329 function __construct( IContextSource
$context ) {
330 $this->setContext( $context );
334 * Redirect to $url rather than displaying the normal page
337 * @param string $responsecode HTTP status code
339 public function redirect( $url, $responsecode = '302' ) {
340 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
341 $this->mRedirect
= str_replace( "\n", '', $url );
342 $this->mRedirectCode
= $responsecode;
346 * Get the URL to redirect to, or an empty string if not redirect URL set
350 public function getRedirect() {
351 return $this->mRedirect
;
355 * Set the copyright URL to send with the output.
356 * Empty string to omit, null to reset.
360 * @param string|null $url
362 public function setCopyrightUrl( $url ) {
363 $this->copyrightUrl
= $url;
367 * Set the HTTP status code to send with the output.
369 * @param int $statusCode
371 public function setStatusCode( $statusCode ) {
372 $this->mStatusCode
= $statusCode;
376 * Add a new "<meta>" tag
377 * To add an http-equiv meta tag, precede the name with "http:"
379 * @param string $name Name of the meta tag
380 * @param string $val Value of the meta tag
382 function addMeta( $name, $val ) {
383 array_push( $this->mMetatags
, [ $name, $val ] );
387 * Returns the current <meta> tags
392 public function getMetaTags() {
393 return $this->mMetatags
;
397 * Add a new \<link\> tag to the page header.
399 * Note: use setCanonicalUrl() for rel=canonical.
401 * @param array $linkarr Associative array of attributes.
403 function addLink( array $linkarr ) {
404 array_push( $this->mLinktags
, $linkarr );
408 * Returns the current <link> tags
413 public function getLinkTags() {
414 return $this->mLinktags
;
418 * Set the URL to be used for the <link rel=canonical>. This should be used
419 * in preference to addLink(), to avoid duplicate link tags.
422 function setCanonicalUrl( $url ) {
423 $this->mCanonicalUrl
= $url;
427 * Returns the URL to be used for the <link rel=canonical> if
431 * @return bool|string
433 public function getCanonicalUrl() {
434 return $this->mCanonicalUrl
;
438 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
439 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
442 * @param string $script Raw HTML
444 function addScript( $script ) {
445 $this->mScripts
.= $script;
449 * Add a JavaScript file to be loaded as `<script>` on this page.
451 * Internal use only. Use OutputPage::addModules() if possible.
453 * @param string $file URL to file (absolute path, protocol-relative, or full url)
454 * @param string|null $unused Previously used to change the cache-busting query parameter
456 public function addScriptFile( $file, $unused = null ) {
457 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
458 // This is not an absolute path, protocol-relative url, or full scheme url,
459 // presumed to be an old call intended to include a file from /w/skins/common,
460 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
461 wfDeprecated( __METHOD__
, '1.24' );
464 $this->addScript( Html
::linkedScript( $file, $this->getCSPNonce() ) );
468 * Add a self-contained script tag with the given contents
469 * Internal use only. Use OutputPage::addModules() if possible.
471 * @param string $script JavaScript text, no script tags
473 public function addInlineScript( $script ) {
474 $this->mScripts
.= Html
::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
478 * Filter an array of modules to remove insufficiently trustworthy members, and modules
479 * which are no longer registered (eg a page is cached before an extension is disabled)
480 * @param array $modules
481 * @param string|null $position Unused
482 * @param string $type
485 protected function filterModules( array $modules, $position = null,
486 $type = ResourceLoaderModule
::TYPE_COMBINED
488 $resourceLoader = $this->getResourceLoader();
489 $filteredModules = [];
490 foreach ( $modules as $val ) {
491 $module = $resourceLoader->getModule( $val );
492 if ( $module instanceof ResourceLoaderModule
493 && $module->getOrigin() <= $this->getAllowedModules( $type )
495 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
496 $this->warnModuleTargetFilter( $module->getName() );
499 $filteredModules[] = $val;
502 return $filteredModules;
505 private function warnModuleTargetFilter( $moduleName ) {
506 static $warnings = [];
507 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
510 $warnings[$this->mTarget
][$moduleName] = true;
511 $this->getResourceLoader()->getLogger()->debug(
512 'Module "{module}" not loadable on target "{target}".',
514 'module' => $moduleName,
515 'target' => $this->mTarget
,
521 * Get the list of modules to include on this page
523 * @param bool $filter Whether to filter out insufficiently trustworthy modules
524 * @param string|null $position Unused
525 * @param string $param
526 * @param string $type
527 * @return array Array of module names
529 public function getModules( $filter = false, $position = null, $param = 'mModules',
530 $type = ResourceLoaderModule
::TYPE_COMBINED
532 $modules = array_values( array_unique( $this->$param ) );
534 ?
$this->filterModules( $modules, null, $type )
539 * Load one or more ResourceLoader modules on this page.
541 * @param string|array $modules Module name (string) or array of module names
543 public function addModules( $modules ) {
544 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
548 * Get the list of script-only modules to load on this page.
550 * @param bool $filter
551 * @param string|null $position Unused
552 * @return array Array of module names
554 public function getModuleScripts( $filter = false, $position = null ) {
555 return $this->getModules( $filter, null, 'mModuleScripts',
556 ResourceLoaderModule
::TYPE_SCRIPTS
561 * Load the scripts of one or more ResourceLoader modules, on this page.
563 * This method exists purely to provide the legacy behaviour of loading
564 * a module's scripts in the global scope, and without dependency resolution.
565 * See <https://phabricator.wikimedia.org/T188689>.
567 * @deprecated since 1.31 Use addModules() instead.
568 * @param string|array $modules Module name (string) or array of module names
570 public function addModuleScripts( $modules ) {
571 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
575 * Get the list of style-only modules to load on this page.
577 * @param bool $filter
578 * @param string|null $position Unused
579 * @return array Array of module names
581 public function getModuleStyles( $filter = false, $position = null ) {
582 return $this->getModules( $filter, null, 'mModuleStyles',
583 ResourceLoaderModule
::TYPE_STYLES
588 * Load the styles of one or more ResourceLoader modules on this page.
590 * Module styles added through this function will be loaded as a stylesheet,
591 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
592 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
594 * @param string|array $modules Module name (string) or array of module names
596 public function addModuleStyles( $modules ) {
597 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
601 * @return null|string ResourceLoader target
603 public function getTarget() {
604 return $this->mTarget
;
608 * Sets ResourceLoader target for load.php links. If null, will be omitted
610 * @param string|null $target
612 public function setTarget( $target ) {
613 $this->mTarget
= $target;
617 * Add a mapping from a LinkTarget to a Content, for things like page preview.
618 * @see self::addContentOverrideCallback()
620 * @param LinkTarget $target
621 * @param Content $content
623 public function addContentOverride( LinkTarget
$target, Content
$content ) {
624 if ( !$this->contentOverrides
) {
625 // Register a callback for $this->contentOverrides on the first call
626 $this->addContentOverrideCallback( function ( LinkTarget
$target ) {
627 $key = $target->getNamespace() . ':' . $target->getDBkey();
628 return $this->contentOverrides
[$key] ??
null;
632 $key = $target->getNamespace() . ':' . $target->getDBkey();
633 $this->contentOverrides
[$key] = $content;
637 * Add a callback for mapping from a Title to a Content object, for things
639 * @see ResourceLoaderContext::getContentOverrideCallback()
641 * @param callable $callback
643 public function addContentOverrideCallback( callable
$callback ) {
644 $this->contentOverrideCallbacks
[] = $callback;
648 * Get an array of head items
652 function getHeadItemsArray() {
653 return $this->mHeadItems
;
657 * Add or replace a head item to the output
659 * Whenever possible, use more specific options like ResourceLoader modules,
660 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
661 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
662 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
663 * This would be your very LAST fallback.
665 * @param string $name Item name
666 * @param string $value Raw HTML
668 public function addHeadItem( $name, $value ) {
669 $this->mHeadItems
[$name] = $value;
673 * Add one or more head items to the output
676 * @param string|string[] $values Raw HTML
678 public function addHeadItems( $values ) {
679 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
683 * Check if the header item $name is already set
685 * @param string $name Item name
688 public function hasHeadItem( $name ) {
689 return isset( $this->mHeadItems
[$name] );
693 * Add a class to the <body> element
696 * @param string|string[] $classes One or more classes to add
698 public function addBodyClasses( $classes ) {
699 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
703 * Set whether the output should only contain the body of the article,
704 * without any skin, sidebar, etc.
705 * Used e.g. when calling with "action=render".
707 * @param bool $only Whether to output only the body of the article
709 public function setArticleBodyOnly( $only ) {
710 $this->mArticleBodyOnly
= $only;
714 * Return whether the output will contain only the body of the article
718 public function getArticleBodyOnly() {
719 return $this->mArticleBodyOnly
;
723 * Set an additional output property
726 * @param string $name
727 * @param mixed $value
729 public function setProperty( $name, $value ) {
730 $this->mProperties
[$name] = $value;
734 * Get an additional output property
737 * @param string $name
738 * @return mixed Property value or null if not found
740 public function getProperty( $name ) {
741 return $this->mProperties
[$name] ??
null;
745 * checkLastModified tells the client to use the client-cached page if
746 * possible. If successful, the OutputPage is disabled so that
747 * any future call to OutputPage->output() have no effect.
749 * Side effect: sets mLastModified for Last-Modified header
751 * @param string $timestamp
753 * @return bool True if cache-ok headers was sent.
755 public function checkLastModified( $timestamp ) {
756 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
757 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
760 $config = $this->getConfig();
761 if ( !$config->get( 'CachePages' ) ) {
762 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
766 $timestamp = wfTimestamp( TS_MW
, $timestamp );
768 'page' => $timestamp,
769 'user' => $this->getUser()->getTouched(),
770 'epoch' => $config->get( 'CacheEpoch' )
772 if ( $config->get( 'UseSquid' ) ) {
773 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
775 $config->get( 'SquidMaxage' )
778 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
780 $maxModified = max( $modifiedTimes );
781 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
783 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
784 if ( $clientHeader === false ) {
785 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
789 # IE sends sizes after the date like this:
790 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
791 # this breaks strtotime().
792 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
794 Wikimedia\
suppressWarnings(); // E_STRICT system time warnings
795 $clientHeaderTime = strtotime( $clientHeader );
796 Wikimedia\restoreWarnings
();
797 if ( !$clientHeaderTime ) {
799 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
802 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
806 foreach ( $modifiedTimes as $name => $value ) {
807 if ( $info !== '' ) {
810 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
813 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
814 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
815 wfDebug( __METHOD__
. ": effective Last-Modified: " .
816 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
817 if ( $clientHeaderTime < $maxModified ) {
818 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
823 # Give a 304 Not Modified response code and disable body output
824 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
825 ini_set( 'zlib.output_compression', 0 );
826 $this->getRequest()->response()->statusHeader( 304 );
827 $this->sendCacheControl();
830 // Don't output a compressed blob when using ob_gzhandler;
831 // it's technically against HTTP spec and seems to confuse
832 // Firefox when the response gets split over two packets.
833 wfClearOutputBuffers();
839 * @param int $reqTime Time of request (eg. now)
840 * @param int $maxAge Cache TTL in seconds
841 * @return int Timestamp
843 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
844 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
845 // because even if the wiki page content hasn't changed since, static
846 // resources may have changed (skin HTML, interface messages, urls, etc.)
847 // and must roll-over in a timely manner (T46570)
848 return $reqTime - $maxAge;
852 * Override the last modified timestamp
854 * @param string $timestamp New timestamp, in a format readable by
857 public function setLastModified( $timestamp ) {
858 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
862 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
864 * @param string $policy The literal string to output as the contents of
865 * the meta tag. Will be parsed according to the spec and output in
869 public function setRobotPolicy( $policy ) {
870 $policy = Article
::formatRobotPolicy( $policy );
872 if ( isset( $policy['index'] ) ) {
873 $this->setIndexPolicy( $policy['index'] );
875 if ( isset( $policy['follow'] ) ) {
876 $this->setFollowPolicy( $policy['follow'] );
881 * Set the index policy for the page, but leave the follow policy un-
884 * @param string $policy Either 'index' or 'noindex'.
887 public function setIndexPolicy( $policy ) {
888 $policy = trim( $policy );
889 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
890 $this->mIndexPolicy
= $policy;
895 * Set the follow policy for the page, but leave the index policy un-
898 * @param string $policy Either 'follow' or 'nofollow'.
901 public function setFollowPolicy( $policy ) {
902 $policy = trim( $policy );
903 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
904 $this->mFollowPolicy
= $policy;
909 * "HTML title" means the contents of "<title>".
910 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
912 * @param string|Message $name
914 public function setHTMLTitle( $name ) {
915 if ( $name instanceof Message
) {
916 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
918 $this->mHTMLtitle
= $name;
923 * Return the "HTML title", i.e. the content of the "<title>" tag.
927 public function getHTMLTitle() {
928 return $this->mHTMLtitle
;
932 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
936 public function setRedirectedFrom( $t ) {
937 $this->mRedirectedFrom
= $t;
941 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
942 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
943 * but not bad tags like \<script\>. This function automatically sets
944 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
945 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
946 * good tags like \<i\> will be dropped entirely.
948 * @param string|Message $name
950 public function setPageTitle( $name ) {
951 if ( $name instanceof Message
) {
952 $name = $name->setContext( $this->getContext() )->text();
955 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
956 # but leave "<i>foobar</i>" alone
957 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
958 $this->mPageTitle
= $nameWithTags;
960 # change "<i>foo&bar</i>" to "foo&bar"
962 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
963 ->inContentLanguage()
968 * Return the "page title", i.e. the content of the \<h1\> tag.
972 public function getPageTitle() {
973 return $this->mPageTitle
;
977 * Same as page title but only contains name of the page, not any other text.
980 * @param string $html Page title text.
981 * @see OutputPage::setPageTitle
983 public function setDisplayTitle( $html ) {
984 $this->displayTitle
= $html;
988 * Returns page display title.
990 * Performs some normalization, but this not as strict the magic word.
993 * @return string HTML
995 public function getDisplayTitle() {
996 $html = $this->displayTitle
;
997 if ( $html === null ) {
998 $html = $this->getTitle()->getPrefixedText();
1001 return Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $html ) );
1005 * Returns page display title without namespace prefix if possible.
1008 * @return string HTML
1010 public function getUnprefixedDisplayTitle() {
1011 $text = $this->getDisplayTitle();
1012 $nsPrefix = $this->getTitle()->getNsText() . ':';
1013 $prefix = preg_quote( $nsPrefix, '/' );
1015 return preg_replace( "/^$prefix/i", '', $text );
1019 * Set the Title object to use
1023 public function setTitle( Title
$t ) {
1024 $this->getContext()->setTitle( $t );
1028 * Replace the subtitle with $str
1030 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1032 public function setSubtitle( $str ) {
1033 $this->clearSubtitle();
1034 $this->addSubtitle( $str );
1038 * Add $str to the subtitle
1040 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1042 public function addSubtitle( $str ) {
1043 if ( $str instanceof Message
) {
1044 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1046 $this->mSubtitle
[] = $str;
1051 * Build message object for a subtitle containing a backlink to a page
1053 * @param Title $title Title to link to
1054 * @param array $query Array of additional parameters to include in the link
1058 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1059 if ( $title->isRedirect() ) {
1060 $query['redirect'] = 'no';
1062 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1063 return wfMessage( 'backlinksubtitle' )
1064 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1068 * Add a subtitle containing a backlink to a page
1070 * @param Title $title Title to link to
1071 * @param array $query Array of additional parameters to include in the link
1073 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1074 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1078 * Clear the subtitles
1080 public function clearSubtitle() {
1081 $this->mSubtitle
= [];
1089 public function getSubtitle() {
1090 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1094 * Set the page as printable, i.e. it'll be displayed with all
1095 * print styles included
1097 public function setPrintable() {
1098 $this->mPrintable
= true;
1102 * Return whether the page is "printable"
1106 public function isPrintable() {
1107 return $this->mPrintable
;
1111 * Disable output completely, i.e. calling output() will have no effect
1113 public function disable() {
1114 $this->mDoNothing
= true;
1118 * Return whether the output will be completely disabled
1122 public function isDisabled() {
1123 return $this->mDoNothing
;
1127 * Show an "add new section" link?
1131 public function showNewSectionLink() {
1132 return $this->mNewSectionLink
;
1136 * Forcibly hide the new section link?
1140 public function forceHideNewSectionLink() {
1141 return $this->mHideNewSectionLink
;
1145 * Add or remove feed links in the page header
1146 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1147 * for the new version
1148 * @see addFeedLink()
1150 * @param bool $show True: add default feeds, false: remove all feeds
1152 public function setSyndicated( $show = true ) {
1154 $this->setFeedAppendQuery( false );
1156 $this->mFeedLinks
= [];
1161 * Add default feeds to the page header
1162 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1163 * for the new version
1164 * @see addFeedLink()
1166 * @param string $val Query to append to feed links or false to output
1169 public function setFeedAppendQuery( $val ) {
1170 $this->mFeedLinks
= [];
1172 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1173 $query = "feed=$type";
1174 if ( is_string( $val ) ) {
1175 $query .= '&' . $val;
1177 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1182 * Add a feed link to the page header
1184 * @param string $format Feed type, should be a key of $wgFeedClasses
1185 * @param string $href URL
1187 public function addFeedLink( $format, $href ) {
1188 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1189 $this->mFeedLinks
[$format] = $href;
1194 * Should we output feed links for this page?
1197 public function isSyndicated() {
1198 return count( $this->mFeedLinks
) > 0;
1202 * Return URLs for each supported syndication format for this page.
1203 * @return array Associating format keys with URLs
1205 public function getSyndicationLinks() {
1206 return $this->mFeedLinks
;
1210 * Will currently always return null
1214 public function getFeedAppendQuery() {
1215 return $this->mFeedLinksAppendQuery
;
1219 * Set whether the displayed content is related to the source of the
1220 * corresponding article on the wiki
1221 * Setting true will cause the change "article related" toggle to true
1223 * @param bool $newVal
1225 public function setArticleFlag( $newVal ) {
1226 $this->mIsArticle
= $newVal;
1228 $this->mIsArticleRelated
= $newVal;
1233 * Return whether the content displayed page is related to the source of
1234 * the corresponding article on the wiki
1238 public function isArticle() {
1239 return $this->mIsArticle
;
1243 * Set whether this page is related an article on the wiki
1244 * Setting false will cause the change of "article flag" toggle to false
1246 * @param bool $newVal
1248 public function setArticleRelated( $newVal ) {
1249 $this->mIsArticleRelated
= $newVal;
1251 $this->mIsArticle
= false;
1256 * Return whether this page is related an article on the wiki
1260 public function isArticleRelated() {
1261 return $this->mIsArticleRelated
;
1265 * Add new language links
1267 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1268 * (e.g. 'fr:Test page')
1270 public function addLanguageLinks( array $newLinkArray ) {
1271 $this->mLanguageLinks
= array_merge( $this->mLanguageLinks
, $newLinkArray );
1275 * Reset the language links and add new language links
1277 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1278 * (e.g. 'fr:Test page')
1280 public function setLanguageLinks( array $newLinkArray ) {
1281 $this->mLanguageLinks
= $newLinkArray;
1285 * Get the list of language links
1287 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1289 public function getLanguageLinks() {
1290 return $this->mLanguageLinks
;
1294 * Add an array of categories, with names in the keys
1296 * @param array $categories Mapping category name => sort key
1298 public function addCategoryLinks( array $categories ) {
1299 if ( !$categories ) {
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 $services = MediaWikiServices
::getInstance();
1323 $linkRenderer = $services->getLinkRenderer();
1324 foreach ( $categories as $category => $type ) {
1325 // array keys will cast numeric category names to ints, so cast back to string
1326 $category = (string)$category;
1327 $origcategory = $category;
1328 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1332 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1333 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1336 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1337 $this->mCategories
[$type][] = $title->getText();
1338 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1344 * @param array $categories
1345 * @return bool|IResultWrapper
1347 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1348 # Add the links to a LinkBatch
1349 $arr = [ NS_CATEGORY
=> $categories ];
1350 $lb = new LinkBatch
;
1351 $lb->setArray( $arr );
1353 # Fetch existence plus the hiddencat property
1354 $dbr = wfGetDB( DB_REPLICA
);
1355 $fields = array_merge(
1356 LinkCache
::getSelectFields(),
1357 [ 'page_namespace', 'page_title', 'pp_value' ]
1360 $res = $dbr->select( [ 'page', 'page_props' ],
1362 $lb->constructSet( 'page', $dbr ),
1365 [ 'page_props' => [ 'LEFT JOIN', [
1366 'pp_propname' => 'hiddencat',
1371 # Add the results to the link cache
1372 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1373 $lb->addResultToCache( $linkCache, $res );
1379 * Reset the category links (but not the category list) and add $categories
1381 * @param array $categories Mapping category name => sort key
1383 public function setCategoryLinks( array $categories ) {
1384 $this->mCategoryLinks
= [];
1385 $this->addCategoryLinks( $categories );
1389 * Get the list of category links, in a 2-D array with the following format:
1390 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1391 * hidden categories) and $link a HTML fragment with a link to the category
1396 public function getCategoryLinks() {
1397 return $this->mCategoryLinks
;
1401 * Get the list of category names this page belongs to.
1403 * @param string $type The type of categories which should be returned. Possible values:
1404 * * all: all categories of all types
1405 * * hidden: only the hidden categories
1406 * * normal: all categories, except hidden categories
1407 * @return array Array of strings
1409 public function getCategories( $type = 'all' ) {
1410 if ( $type === 'all' ) {
1411 $allCategories = [];
1412 foreach ( $this->mCategories
as $categories ) {
1413 $allCategories = array_merge( $allCategories, $categories );
1415 return $allCategories;
1417 if ( !isset( $this->mCategories
[$type] ) ) {
1418 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1420 return $this->mCategories
[$type];
1424 * Add an array of indicators, with their identifiers as array
1425 * keys and HTML contents as values.
1427 * In case of duplicate keys, existing values are overwritten.
1429 * @param array $indicators
1432 public function setIndicators( array $indicators ) {
1433 $this->mIndicators
= $indicators +
$this->mIndicators
;
1434 // Keep ordered by key
1435 ksort( $this->mIndicators
);
1439 * Get the indicators associated with this page.
1441 * The array will be internally ordered by item keys.
1443 * @return array Keys: identifiers, values: HTML contents
1446 public function getIndicators() {
1447 return $this->mIndicators
;
1451 * Adds help link with an icon via page indicators.
1452 * Link target can be overridden by a local message containing a wikilink:
1453 * the message key is: lowercase action or special page name + '-helppage'.
1454 * @param string $to Target MediaWiki.org page title or encoded URL.
1455 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1458 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1459 $this->addModuleStyles( 'mediawiki.helplink' );
1460 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1462 if ( $overrideBaseUrl ) {
1465 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1466 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1469 $link = Html
::rawElement(
1473 'target' => '_blank',
1474 'class' => 'mw-helplink',
1479 $this->setIndicators( [ 'mw-helplink' => $link ] );
1483 * Do not allow scripts which can be modified by wiki users to load on this page;
1484 * only allow scripts bundled with, or generated by, the software.
1485 * Site-wide styles are controlled by a config setting, since they can be
1486 * used to create a custom skin/theme, but not user-specific ones.
1488 * @todo this should be given a more accurate name
1490 public function disallowUserJs() {
1491 $this->reduceAllowedModules(
1492 ResourceLoaderModule
::TYPE_SCRIPTS
,
1493 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1496 // Site-wide styles are controlled by a config setting, see T73621
1497 // for background on why. User styles are never allowed.
1498 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1499 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1501 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1503 $this->reduceAllowedModules(
1504 ResourceLoaderModule
::TYPE_STYLES
,
1510 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1511 * @see ResourceLoaderModule::$origin
1512 * @param string $type ResourceLoaderModule TYPE_ constant
1513 * @return int ResourceLoaderModule ORIGIN_ class constant
1515 public function getAllowedModules( $type ) {
1516 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1517 return min( array_values( $this->mAllowedModules
) );
1519 return $this->mAllowedModules
[$type] ?? ResourceLoaderModule
::ORIGIN_ALL
;
1524 * Limit the highest level of CSS/JS untrustworthiness allowed.
1526 * If passed the same or a higher level than the current level of untrustworthiness set, the
1527 * level will remain unchanged.
1529 * @param string $type
1530 * @param int $level ResourceLoaderModule class constant
1532 public function reduceAllowedModules( $type, $level ) {
1533 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1537 * Prepend $text to the body HTML
1539 * @param string $text HTML
1541 public function prependHTML( $text ) {
1542 $this->mBodytext
= $text . $this->mBodytext
;
1546 * Append $text to the body HTML
1548 * @param string $text HTML
1550 public function addHTML( $text ) {
1551 $this->mBodytext
.= $text;
1555 * Shortcut for adding an Html::element via addHTML.
1559 * @param string $element
1560 * @param array $attribs
1561 * @param string $contents
1563 public function addElement( $element, array $attribs = [], $contents = '' ) {
1564 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1568 * Clear the body HTML
1570 public function clearHTML() {
1571 $this->mBodytext
= '';
1577 * @return string HTML
1579 public function getHTML() {
1580 return $this->mBodytext
;
1584 * Get/set the ParserOptions object to use for wikitext parsing
1586 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1587 * current ParserOption object. This parameter is deprecated since 1.31.
1588 * @return ParserOptions
1590 public function parserOptions( $options = null ) {
1591 if ( $options !== null ) {
1592 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1595 if ( $options !== null && !empty( $options->isBogus
) ) {
1596 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1597 // been changed somehow, and keep it if so.
1598 $anonPO = ParserOptions
::newFromAnon();
1599 $anonPO->setAllowUnsafeRawHtml( false );
1600 if ( !$options->matches( $anonPO ) ) {
1601 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1602 $options->isBogus
= false;
1606 if ( !$this->mParserOptions
) {
1607 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1608 // $wgUser isn't unstubbable yet, so don't try to get a
1609 // ParserOptions for it. And don't cache this ParserOptions
1611 $po = ParserOptions
::newFromAnon();
1612 $po->setAllowUnsafeRawHtml( false );
1613 $po->isBogus
= true;
1614 if ( $options !== null ) {
1615 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1620 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1621 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1624 if ( $options !== null && !empty( $options->isBogus
) ) {
1625 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1627 return wfSetVar( $this->mParserOptions
, null, true );
1629 return wfSetVar( $this->mParserOptions
, $options );
1634 * Set the revision ID which will be seen by the wiki text parser
1635 * for things such as embedded {{REVISIONID}} variable use.
1637 * @param int|null $revid A positive integer, or null
1638 * @return mixed Previous value
1640 public function setRevisionId( $revid ) {
1641 $val = is_null( $revid ) ?
null : intval( $revid );
1642 return wfSetVar( $this->mRevisionId
, $val, true );
1646 * Get the displayed revision ID
1650 public function getRevisionId() {
1651 return $this->mRevisionId
;
1655 * Set the timestamp of the revision which will be displayed. This is used
1656 * to avoid a extra DB call in Skin::lastModified().
1658 * @param string|null $timestamp
1659 * @return mixed Previous value
1661 public function setRevisionTimestamp( $timestamp ) {
1662 return wfSetVar( $this->mRevisionTimestamp
, $timestamp, true );
1666 * Get the timestamp of displayed revision.
1667 * This will be null if not filled by setRevisionTimestamp().
1669 * @return string|null
1671 public function getRevisionTimestamp() {
1672 return $this->mRevisionTimestamp
;
1676 * Set the displayed file version
1678 * @param File|null $file
1679 * @return mixed Previous value
1681 public function setFileVersion( $file ) {
1683 if ( $file instanceof File
&& $file->exists() ) {
1684 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1686 return wfSetVar( $this->mFileVersion
, $val, true );
1690 * Get the displayed file version
1692 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1694 public function getFileVersion() {
1695 return $this->mFileVersion
;
1699 * Get the templates used on this page
1701 * @return array (namespace => dbKey => revId)
1704 public function getTemplateIds() {
1705 return $this->mTemplateIds
;
1709 * Get the files used on this page
1711 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1714 public function getFileSearchOptions() {
1715 return $this->mImageTimeKeys
;
1719 * Convert wikitext to HTML and add it to the buffer
1720 * Default assumes that the current page title will be used.
1722 * @param string $text
1723 * @param bool $linestart Is this the start of a line?
1724 * @param bool $interface Is this text in the user interface language?
1725 * @throws MWException
1727 public function addWikiText( $text, $linestart = true, $interface = true ) {
1728 $title = $this->getTitle(); // Work around E_STRICT
1730 throw new MWException( 'Title is null' );
1732 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1736 * Add wikitext with a custom Title object
1738 * @param string $text Wikitext
1739 * @param Title $title
1740 * @param bool $linestart Is this the start of a line?
1742 public function addWikiTextWithTitle( $text, Title
$title, $linestart = true ) {
1743 $this->addWikiTextTitle( $text, $title, $linestart );
1747 * Add wikitext with a custom Title object and tidy enabled.
1749 * @param string $text Wikitext
1750 * @param Title $title
1751 * @param bool $linestart Is this the start of a line?
1753 function addWikiTextTitleTidy( $text, Title
$title, $linestart = true ) {
1754 $this->addWikiTextTitle( $text, $title, $linestart, true );
1758 * Add wikitext with tidy enabled
1760 * @param string $text Wikitext
1761 * @param bool $linestart Is this the start of a line?
1763 public function addWikiTextTidy( $text, $linestart = true ) {
1764 $title = $this->getTitle();
1765 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1769 * Add wikitext with a custom Title object.
1770 * Output is unwrapped.
1772 * @param string $text Wikitext
1773 * @param Title $title
1774 * @param bool $linestart Is this the start of a line?
1775 * @param bool $tidy Whether to use tidy
1776 * @param bool $interface Whether it is an interface message
1777 * (for example disables conversion)
1779 public function addWikiTextTitle( $text, Title
$title, $linestart,
1780 $tidy = false, $interface = false
1784 $popts = $this->parserOptions();
1785 $oldTidy = $popts->setTidy( $tidy );
1786 $popts->setInterfaceMessage( (bool)$interface );
1788 $parserOutput = $wgParser->getFreshParser()->parse(
1789 $text, $title, $popts,
1790 $linestart, true, $this->mRevisionId
1793 $popts->setTidy( $oldTidy );
1795 $this->addParserOutput( $parserOutput, [
1796 'enableSectionEditLinks' => false,
1797 'wrapperDivClass' => '',
1802 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1803 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1807 * @param ParserOutput $parserOutput
1809 public function addParserOutputMetadata( ParserOutput
$parserOutput ) {
1810 $this->mLanguageLinks
=
1811 array_merge( $this->mLanguageLinks
, $parserOutput->getLanguageLinks() );
1812 $this->addCategoryLinks( $parserOutput->getCategories() );
1813 $this->setIndicators( $parserOutput->getIndicators() );
1814 $this->mNewSectionLink
= $parserOutput->getNewSection();
1815 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1817 if ( !$parserOutput->isCacheable() ) {
1818 $this->enableClientCache( false );
1820 $this->mNoGallery
= $parserOutput->getNoGallery();
1821 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1822 $this->addModules( $parserOutput->getModules() );
1823 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1824 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1825 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1826 $this->mPreventClickjacking
= $this->mPreventClickjacking
1827 ||
$parserOutput->preventClickjacking();
1829 // Template versioning...
1830 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1831 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1832 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1834 $this->mTemplateIds
[$ns] = $dbks;
1837 // File versioning...
1838 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1839 $this->mImageTimeKeys
[$dbk] = $data;
1842 // Hooks registered in the object
1843 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1844 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1845 list( $hookName, $data ) = $hookInfo;
1846 if ( isset( $parserOutputHooks[$hookName] ) ) {
1847 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1851 // Enable OOUI if requested via ParserOutput
1852 if ( $parserOutput->getEnableOOUI() ) {
1853 $this->enableOOUI();
1856 // Include parser limit report
1857 if ( !$this->limitReportJSData
) {
1858 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1861 // Link flags are ignored for now, but may in the future be
1862 // used to mark individual language links.
1864 // Avoid PHP 7.1 warning of passing $this by reference
1865 $outputPage = $this;
1866 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1867 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1869 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1870 // so that extensions may modify ParserOutput to toggle TOC.
1871 // This cannot be moved to addParserOutputText because that is not
1872 // called by EditPage for Preview.
1873 if ( $parserOutput->getTOCHTML() ) {
1874 $this->mEnableTOC
= true;
1879 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1880 * ParserOutput object, without any other metadata.
1883 * @param ParserOutput $parserOutput
1884 * @param array $poOptions Options to ParserOutput::getText()
1886 public function addParserOutputContent( ParserOutput
$parserOutput, $poOptions = [] ) {
1887 $this->addParserOutputText( $parserOutput, $poOptions );
1889 $this->addModules( $parserOutput->getModules() );
1890 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1891 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1893 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1897 * Add the HTML associated with a ParserOutput object, without any metadata.
1900 * @param ParserOutput $parserOutput
1901 * @param array $poOptions Options to ParserOutput::getText()
1903 public function addParserOutputText( ParserOutput
$parserOutput, $poOptions = [] ) {
1904 $text = $parserOutput->getText( $poOptions );
1905 // Avoid PHP 7.1 warning of passing $this by reference
1906 $outputPage = $this;
1907 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1908 $this->addHTML( $text );
1912 * Add everything from a ParserOutput object.
1914 * @param ParserOutput $parserOutput
1915 * @param array $poOptions Options to ParserOutput::getText()
1917 function addParserOutput( ParserOutput
$parserOutput, $poOptions = [] ) {
1918 $this->addParserOutputMetadata( $parserOutput );
1919 $this->addParserOutputText( $parserOutput, $poOptions );
1923 * Add the output of a QuickTemplate to the output buffer
1925 * @param QuickTemplate &$template
1927 public function addTemplate( &$template ) {
1928 $this->addHTML( $template->getHTML() );
1932 * Parse wikitext and return the HTML.
1934 * @param string $text
1935 * @param bool $linestart Is this the start of a line?
1936 * @param bool $interface Use interface language (instead of content language) while parsing
1937 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1938 * LanguageConverter.
1939 * @param Language|null $language Target language object, will override $interface
1940 * @throws MWException
1941 * @return string HTML
1943 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1946 if ( is_null( $this->getTitle() ) ) {
1947 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1950 $popts = $this->parserOptions();
1952 $popts->setInterfaceMessage( true );
1954 if ( $language !== null ) {
1955 $oldLang = $popts->setTargetLanguage( $language );
1958 $parserOutput = $wgParser->getFreshParser()->parse(
1959 $text, $this->getTitle(), $popts,
1960 $linestart, true, $this->mRevisionId
1964 $popts->setInterfaceMessage( false );
1966 if ( $language !== null ) {
1967 $popts->setTargetLanguage( $oldLang );
1970 return $parserOutput->getText( [
1971 'enableSectionEditLinks' => false,
1976 * Parse wikitext, strip paragraphs, and return the HTML.
1978 * @param string $text
1979 * @param bool $linestart Is this the start of a line?
1980 * @param bool $interface Use interface language (instead of content language) while parsing
1981 * language sensitive magic words like GRAMMAR and PLURAL
1982 * @return string HTML
1984 public function parseInline( $text, $linestart = true, $interface = false ) {
1985 $parsed = $this->parse( $text, $linestart, $interface );
1986 return Parser
::stripOuterParagraph( $parsed );
1990 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1992 * @param int $maxage Maximum cache time on the CDN, in seconds.
1994 public function setCdnMaxage( $maxage ) {
1995 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1999 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2000 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2001 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2004 * @param int $maxage Maximum cache time on the CDN, in seconds
2007 public function lowerCdnMaxage( $maxage ) {
2008 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
2009 $this->setCdnMaxage( $this->mCdnMaxage
);
2013 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2015 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2016 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2017 * TTL is 90% of the age of the object, subject to the min and max.
2019 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2020 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2021 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2022 * @return int TTL in seconds passed to lowerCdnMaxage() (may not be the same as the new
2026 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2027 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2028 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2030 if ( $mtime === null ||
$mtime === false ) {
2031 return $minTTL; // entity does not exist
2034 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2035 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2036 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2038 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2040 return $adaptiveTTL;
2044 * Use enableClientCache(false) to force it to send nocache headers
2046 * @param bool|null $state New value, or null to not set the value
2048 * @return bool Old value
2050 public function enableClientCache( $state ) {
2051 return wfSetVar( $this->mEnableClientCache
, $state );
2055 * Get the list of cookie names that will influence the cache
2059 function getCacheVaryCookies() {
2061 if ( $cookies === null ) {
2062 $config = $this->getConfig();
2063 $cookies = array_merge(
2064 SessionManager
::singleton()->getVaryCookies(),
2068 $config->get( 'CacheVaryCookies' )
2070 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2076 * Check if the request has a cache-varying cookie header
2077 * If it does, it's very important that we don't allow public caching
2081 function haveCacheVaryCookies() {
2082 $request = $this->getRequest();
2083 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2084 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2085 wfDebug( __METHOD__
. ": found $cookieName\n" );
2089 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2094 * Add an HTTP header that will influence on the cache
2096 * @param string $header Header name
2097 * @param string[]|null $option Options for the Key header. See
2098 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2099 * for the list of valid options.
2101 public function addVaryHeader( $header, array $option = null ) {
2102 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2103 $this->mVaryHeader
[$header] = [];
2105 if ( !is_array( $option ) ) {
2108 $this->mVaryHeader
[$header] =
2109 array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2113 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2114 * such as Accept-Encoding or Cookie
2118 public function getVaryHeader() {
2119 // If we vary on cookies, let's make sure it's always included here too.
2120 if ( $this->getCacheVaryCookies() ) {
2121 $this->addVaryHeader( 'Cookie' );
2124 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2125 $this->addVaryHeader( $header, $options );
2127 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2131 * Add an HTTP Link: header
2133 * @param string $header Header value
2135 public function addLinkHeader( $header ) {
2136 $this->mLinkHeader
[] = $header;
2140 * Return a Link: header. Based on the values of $mLinkHeader.
2144 public function getLinkHeader() {
2145 if ( !$this->mLinkHeader
) {
2149 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2153 * Get a complete Key header
2157 public function getKeyHeader() {
2158 $cvCookies = $this->getCacheVaryCookies();
2160 $cookiesOption = [];
2161 foreach ( $cvCookies as $cookieName ) {
2162 $cookiesOption[] = 'param=' . $cookieName;
2164 $this->addVaryHeader( 'Cookie', $cookiesOption );
2166 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2167 $this->addVaryHeader( $header, $options );
2171 foreach ( $this->mVaryHeader
as $header => $option ) {
2172 $newheader = $header;
2173 if ( is_array( $option ) && count( $option ) > 0 ) {
2174 $newheader .= ';' . implode( ';', $option );
2176 $headers[] = $newheader;
2178 $key = 'Key: ' . implode( ',', $headers );
2184 * T23672: Add Accept-Language to Vary and Key headers if there's no 'variant' parameter in GET.
2187 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2188 * /w/index.php?title=Main_page&variant=zh-cn will not.
2190 private function addAcceptLanguage() {
2191 $title = $this->getTitle();
2192 if ( !$title instanceof Title
) {
2196 $lang = $title->getPageLanguage();
2197 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2198 $variants = $lang->getVariants();
2200 foreach ( $variants as $variant ) {
2201 if ( $variant === $lang->getCode() ) {
2205 $aloption[] = "substr=$variant";
2207 // IE and some other browsers use BCP 47 standards in their Accept-Language header,
2208 // like "zh-CN" or "zh-Hant". We should handle these too.
2209 $variantBCP47 = LanguageCode
::bcp47( $variant );
2210 if ( $variantBCP47 !== $variant ) {
2211 $aloption[] = "substr=$variantBCP47";
2214 $this->addVaryHeader( 'Accept-Language', $aloption );
2219 * Set a flag which will cause an X-Frame-Options header appropriate for
2220 * edit pages to be sent. The header value is controlled by
2221 * $wgEditPageFrameOptions.
2223 * This is the default for special pages. If you display a CSRF-protected
2224 * form on an ordinary view page, then you need to call this function.
2226 * @param bool $enable
2228 public function preventClickjacking( $enable = true ) {
2229 $this->mPreventClickjacking
= $enable;
2233 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2234 * This can be called from pages which do not contain any CSRF-protected
2237 public function allowClickjacking() {
2238 $this->mPreventClickjacking
= false;
2242 * Get the prevent-clickjacking flag
2247 public function getPreventClickjacking() {
2248 return $this->mPreventClickjacking
;
2252 * Get the X-Frame-Options header value (without the name part), or false
2253 * if there isn't one. This is used by Skin to determine whether to enable
2254 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2256 * @return string|false
2258 public function getFrameOptions() {
2259 $config = $this->getConfig();
2260 if ( $config->get( 'BreakFrames' ) ) {
2262 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2263 return $config->get( 'EditPageFrameOptions' );
2269 * Send cache control HTTP headers
2271 public function sendCacheControl() {
2272 $response = $this->getRequest()->response();
2273 $config = $this->getConfig();
2275 $this->addVaryHeader( 'Cookie' );
2276 $this->addAcceptLanguage();
2278 # don't serve compressed data to clients who can't handle it
2279 # maintain different caches for logged-in users and non-logged in ones
2280 $response->header( $this->getVaryHeader() );
2282 if ( $config->get( 'UseKeyHeader' ) ) {
2283 $response->header( $this->getKeyHeader() );
2286 if ( $this->mEnableClientCache
) {
2288 $config->get( 'UseSquid' ) &&
2289 !$response->hasCookies() &&
2290 !SessionManager
::getGlobalSession()->isPersistent() &&
2291 !$this->isPrintable() &&
2292 $this->mCdnMaxage
!= 0 &&
2293 !$this->haveCacheVaryCookies()
2295 if ( $config->get( 'UseESI' ) ) {
2296 # We'll purge the proxy cache explicitly, but require end user agents
2297 # to revalidate against the proxy on each visit.
2298 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2299 wfDebug( __METHOD__
.
2300 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2301 # start with a shorter timeout for initial testing
2302 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2304 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2305 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2307 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2309 # We'll purge the proxy cache for anons explicitly, but require end user agents
2310 # to revalidate against the proxy on each visit.
2311 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2312 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2313 wfDebug( __METHOD__
.
2314 ": local proxy caching; {$this->mLastModified} **", 'private' );
2315 # start with a shorter timeout for initial testing
2316 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2317 $response->header( "Cache-Control: " .
2318 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2321 # We do want clients to cache if they can, but they *must* check for updates
2322 # on revisiting the page.
2323 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2324 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2325 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2327 if ( $this->mLastModified
) {
2328 $response->header( "Last-Modified: {$this->mLastModified}" );
2331 wfDebug( __METHOD__
. ": no caching **", 'private' );
2333 # In general, the absence of a last modified header should be enough to prevent
2334 # the client from using its cache. We send a few other things just to make sure.
2335 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2336 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2337 $response->header( 'Pragma: no-cache' );
2342 * Transfer styles and JavaScript modules from skin.
2344 * @param Skin $sk to load modules for
2346 public function loadSkinModules( $sk ) {
2347 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2348 if ( $group === 'styles' ) {
2349 foreach ( $modules as $key => $moduleMembers ) {
2350 $this->addModuleStyles( $moduleMembers );
2353 $this->addModules( $modules );
2359 * Finally, all the text has been munged and accumulated into
2360 * the object, let's actually output it:
2362 * @param bool $return Set to true to get the result as a string rather than sending it
2363 * @return string|null
2365 * @throws FatalError
2366 * @throws MWException
2368 public function output( $return = false ) {
2369 if ( $this->mDoNothing
) {
2370 return $return ?
'' : null;
2373 $response = $this->getRequest()->response();
2374 $config = $this->getConfig();
2376 if ( $this->mRedirect
!= '' ) {
2377 # Standards require redirect URLs to be absolute
2378 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2380 $redirect = $this->mRedirect
;
2381 $code = $this->mRedirectCode
;
2383 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2384 if ( $code == '301' ||
$code == '303' ) {
2385 if ( !$config->get( 'DebugRedirects' ) ) {
2386 $response->statusHeader( $code );
2388 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2390 if ( $config->get( 'VaryOnXFP' ) ) {
2391 $this->addVaryHeader( 'X-Forwarded-Proto' );
2393 $this->sendCacheControl();
2395 $response->header( "Content-Type: text/html; charset=utf-8" );
2396 if ( $config->get( 'DebugRedirects' ) ) {
2397 $url = htmlspecialchars( $redirect );
2398 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2399 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2400 print "</body>\n</html>\n";
2402 $response->header( 'Location: ' . $redirect );
2406 return $return ?
'' : null;
2407 } elseif ( $this->mStatusCode
) {
2408 $response->statusHeader( $this->mStatusCode
);
2411 # Buffer output; final headers may depend on later processing
2414 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2415 $response->header( 'Content-language: ' .
2416 MediaWikiServices
::getInstance()->getContentLanguage()->getHtmlCode() );
2418 if ( !$this->mArticleBodyOnly
) {
2419 $sk = $this->getSkin();
2422 $linkHeader = $this->getLinkHeader();
2423 if ( $linkHeader ) {
2424 $response->header( $linkHeader );
2427 // Prevent framing, if requested
2428 $frameOptions = $this->getFrameOptions();
2429 if ( $frameOptions ) {
2430 $response->header( "X-Frame-Options: $frameOptions" );
2433 ContentSecurityPolicy
::sendHeaders( $this );
2435 if ( $this->mArticleBodyOnly
) {
2436 echo $this->mBodytext
;
2438 // Enable safe mode if requested (T152169)
2439 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2440 $this->disallowUserJs();
2443 $sk = $this->getSkin();
2444 $this->loadSkinModules( $sk );
2446 MWDebug
::addModules( $this );
2448 // Avoid PHP 7.1 warning of passing $this by reference
2449 $outputPage = $this;
2450 // Hook that allows last minute changes to the output page, e.g.
2451 // adding of CSS or Javascript by extensions.
2452 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2456 } catch ( Exception
$e ) {
2457 ob_end_clean(); // bug T129657
2463 // This hook allows last minute changes to final overall output by modifying output buffer
2464 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2465 } catch ( Exception
$e ) {
2466 ob_end_clean(); // bug T129657
2470 $this->sendCacheControl();
2473 return ob_get_clean();
2481 * Prepare this object to display an error page; disable caching and
2482 * indexing, clear the current text and redirect, set the page's title
2483 * and optionally an custom HTML title (content of the "<title>" tag).
2485 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2486 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2487 * optional, if not passed the "<title>" attribute will be
2488 * based on $pageTitle
2490 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2491 $this->setPageTitle( $pageTitle );
2492 if ( $htmlTitle !== false ) {
2493 $this->setHTMLTitle( $htmlTitle );
2495 $this->setRobotPolicy( 'noindex,nofollow' );
2496 $this->setArticleRelated( false );
2497 $this->enableClientCache( false );
2498 $this->mRedirect
= '';
2499 $this->clearSubtitle();
2504 * Output a standard error page
2506 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2507 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2508 * showErrorPage( 'titlemsg', $messageObject );
2509 * showErrorPage( $titleMessageObject, $messageObject );
2511 * @param string|Message $title Message key (string) for page title, or a Message object
2512 * @param string|Message $msg Message key (string) for page text, or a Message object
2513 * @param array $params Message parameters; ignored if $msg is a Message object
2515 public function showErrorPage( $title, $msg, $params = [] ) {
2516 if ( !$title instanceof Message
) {
2517 $title = $this->msg( $title );
2520 $this->prepareErrorPage( $title );
2522 if ( $msg instanceof Message
) {
2523 if ( $params !== [] ) {
2524 trigger_error( 'Argument ignored: $params. The message parameters argument '
2525 . 'is discarded when the $msg argument is a Message object instead of '
2526 . 'a string.', E_USER_NOTICE
);
2528 $this->addHTML( $msg->parseAsBlock() );
2530 $this->addWikiMsgArray( $msg, $params );
2533 $this->returnToMain();
2537 * Output a standard permission error page
2539 * @param array $errors Error message keys or [key, param...] arrays
2540 * @param string|null $action Action that was denied or null if unknown
2542 public function showPermissionsErrorPage( array $errors, $action = null ) {
2543 foreach ( $errors as $key => $error ) {
2544 $errors[$key] = (array)$error;
2547 // For some action (read, edit, create and upload), display a "login to do this action"
2548 // error if all of the following conditions are met:
2549 // 1. the user is not logged in
2550 // 2. the only error is insufficient permissions (i.e. no block or something else)
2551 // 3. the error can be avoided simply by logging in
2552 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2553 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2554 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2555 && ( User
::groupHasPermission( 'user', $action )
2556 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2558 $displayReturnto = null;
2560 # Due to T34276, if a user does not have read permissions,
2561 # $this->getTitle() will just give Special:Badtitle, which is
2562 # not especially useful as a returnto parameter. Use the title
2563 # from the request instead, if there was one.
2564 $request = $this->getRequest();
2565 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2566 if ( $action == 'edit' ) {
2567 $msg = 'whitelistedittext';
2568 $displayReturnto = $returnto;
2569 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2570 $msg = 'nocreatetext';
2571 } elseif ( $action == 'upload' ) {
2572 $msg = 'uploadnologintext';
2574 $msg = 'loginreqpagetext';
2575 $displayReturnto = Title
::newMainPage();
2581 $query['returnto'] = $returnto->getPrefixedText();
2583 if ( !$request->wasPosted() ) {
2584 $returntoquery = $request->getValues();
2585 unset( $returntoquery['title'] );
2586 unset( $returntoquery['returnto'] );
2587 unset( $returntoquery['returntoquery'] );
2588 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2591 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2592 $loginLink = $linkRenderer->makeKnownLink(
2593 SpecialPage
::getTitleFor( 'Userlogin' ),
2594 $this->msg( 'loginreqlink' )->text(),
2599 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2600 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2602 # Don't return to a page the user can't read otherwise
2603 # we'll end up in a pointless loop
2604 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2605 $this->returnToMain( null, $displayReturnto );
2608 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2609 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2614 * Display an error page indicating that a given version of MediaWiki is
2615 * required to use it
2617 * @param mixed $version The version of MediaWiki needed to use the page
2619 public function versionRequired( $version ) {
2620 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2622 $this->addWikiMsg( 'versionrequiredtext', $version );
2623 $this->returnToMain();
2627 * Format a list of error messages
2629 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2630 * @param string|null $action Action that was denied or null if unknown
2631 * @return string The wikitext error-messages, formatted into a list.
2633 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2634 if ( $action == null ) {
2635 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2637 $action_desc = $this->msg( "action-$action" )->plain();
2639 'permissionserrorstext-withaction',
2642 )->plain() . "\n\n";
2645 if ( count( $errors ) > 1 ) {
2646 $text .= '<ul class="permissions-errors">' . "\n";
2648 foreach ( $errors as $error ) {
2650 $text .= $this->msg( ...$error )->plain();
2655 $text .= "<div class=\"permissions-errors\">\n" .
2656 $this->msg( ...reset( $errors ) )->plain() .
2664 * Show a warning about replica DB lag
2666 * If the lag is higher than $wgSlaveLagCritical seconds,
2667 * then the warning is a bit more obvious. If the lag is
2668 * lower than $wgSlaveLagWarning, then no warning is shown.
2670 * @param int $lag Slave lag
2672 public function showLagWarning( $lag ) {
2673 $config = $this->getConfig();
2674 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2675 $lag = floor( $lag ); // floor to avoid nano seconds to display
2676 $message = $lag < $config->get( 'SlaveLagCritical' )
2679 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2680 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2685 * Output an error page
2687 * @note FatalError exception class provides an alternative.
2688 * @param string $message Error to output. Must be escaped for HTML.
2690 public function showFatalError( $message ) {
2691 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2693 $this->addHTML( $message );
2697 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2699 public function showUnexpectedValueError( $name, $val ) {
2700 wfDeprecated( __METHOD__
, '1.32' );
2701 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->escaped() );
2705 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2707 public function showFileCopyError( $old, $new ) {
2708 wfDeprecated( __METHOD__
, '1.32' );
2709 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->escaped() );
2713 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2715 public function showFileRenameError( $old, $new ) {
2716 wfDeprecated( __METHOD__
, '1.32' );
2717 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->escpaed() );
2721 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2723 public function showFileDeleteError( $name ) {
2724 wfDeprecated( __METHOD__
, '1.32' );
2725 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->escaped() );
2729 * @deprecated 1.32 Use OutputPage::showFatalError or throw FatalError instead.
2731 public function showFileNotFoundError( $name ) {
2732 wfDeprecated( __METHOD__
, '1.32' );
2733 $this->showFatalError( $this->msg( 'filenotfound', $name )->escaped() );
2737 * Add a "return to" link pointing to a specified title
2739 * @param Title $title Title to link
2740 * @param array $query Query string parameters
2741 * @param string|null $text Text of the link (input is not escaped)
2742 * @param array $options Options array to pass to Linker
2744 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2745 $linkRenderer = MediaWikiServices
::getInstance()
2746 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2747 $link = $this->msg( 'returnto' )->rawParams(
2748 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2749 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2753 * Add a "return to" link pointing to a specified title,
2754 * or the title indicated in the request, or else the main page
2756 * @param mixed|null $unused
2757 * @param Title|string|null $returnto Title or String to return to
2758 * @param string|null $returntoquery Query string for the return to link
2760 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2761 if ( $returnto == null ) {
2762 $returnto = $this->getRequest()->getText( 'returnto' );
2765 if ( $returntoquery == null ) {
2766 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2769 if ( $returnto === '' ) {
2770 $returnto = Title
::newMainPage();
2773 if ( is_object( $returnto ) ) {
2774 $titleObj = $returnto;
2776 $titleObj = Title
::newFromText( $returnto );
2778 // We don't want people to return to external interwiki. That
2779 // might potentially be used as part of a phishing scheme
2780 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2781 $titleObj = Title
::newMainPage();
2784 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2787 private function getRlClientContext() {
2788 if ( !$this->rlClientContext
) {
2789 $query = ResourceLoader
::makeLoaderQuery(
2790 [], // modules; not relevant
2791 $this->getLanguage()->getCode(),
2792 $this->getSkin()->getSkinName(),
2793 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2794 null, // version; not relevant
2795 ResourceLoader
::inDebugMode(),
2796 null, // only; not relevant
2797 $this->isPrintable(),
2798 $this->getRequest()->getBool( 'handheld' )
2800 $this->rlClientContext
= new ResourceLoaderContext(
2801 $this->getResourceLoader(),
2802 new FauxRequest( $query )
2804 if ( $this->contentOverrideCallbacks
) {
2805 $this->rlClientContext
= new DerivativeResourceLoaderContext( $this->rlClientContext
);
2806 $this->rlClientContext
->setContentOverrideCallback( function ( Title
$title ) {
2807 foreach ( $this->contentOverrideCallbacks
as $callback ) {
2808 $content = $callback( $title );
2809 if ( $content !== null ) {
2810 $text = ContentHandler
::getContentText( $content );
2811 if ( strpos( $text, '</script>' ) !== false ) {
2812 // Proactively replace this so that we can display a message
2813 // to the user, instead of letting it go to Html::inlineScript(),
2814 // where it would be considered a server-side issue.
2815 $titleFormatted = $title->getPrefixedText();
2816 $content = new JavaScriptContent(
2817 Xml
::encodeJsCall( 'mw.log.error', [
2818 "Cannot preview $titleFormatted due to script-closing tag."
2829 return $this->rlClientContext
;
2833 * Call this to freeze the module queue and JS config and create a formatter.
2835 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2836 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2837 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2838 * the module filters retroactively. Skins and extension hooks may also add modules until very
2839 * late in the request lifecycle.
2841 * @return ResourceLoaderClientHtml
2843 public function getRlClient() {
2844 if ( !$this->rlClient
) {
2845 $context = $this->getRlClientContext();
2846 $rl = $this->getResourceLoader();
2847 $this->addModules( [
2852 $this->addModuleStyles( [
2857 $this->getSkin()->setupSkinUserCss( $this );
2859 // Prepare exempt modules for buildExemptModules()
2860 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2862 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2864 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2865 // Separate user-specific batch for improved cache-hit ratio.
2866 $userBatch = [ 'user.styles', 'user' ];
2867 $siteBatch = array_diff( $moduleStyles, $userBatch );
2868 $dbr = wfGetDB( DB_REPLICA
);
2869 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2870 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2872 // Filter out modules handled by buildExemptModules()
2873 $moduleStyles = array_filter( $moduleStyles,
2874 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2875 $module = $rl->getModule( $name );
2877 $group = $module->getGroup();
2878 if ( isset( $exemptGroups[$group] ) ) {
2879 $exemptStates[$name] = 'ready';
2880 if ( !$module->isKnownEmpty( $context ) ) {
2881 // E.g. Don't output empty <styles>
2882 $exemptGroups[$group][] = $name;
2890 $this->rlExemptStyleModules
= $exemptGroups;
2892 $rlClient = new ResourceLoaderClientHtml( $context, [
2893 'target' => $this->getTarget(),
2894 'nonce' => $this->getCSPNonce(),
2895 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2896 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2897 // modules enqueud for loading on this page is filtered to just those.
2898 // However, to make sure we also apply the restriction to dynamic dependencies and
2899 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2900 // StartupModule so that the client-side registry will not contain any restricted
2901 // modules either. (T152169, T185303)
2902 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2903 <= ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
2906 $rlClient->setConfig( $this->getJSVars() );
2907 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2908 $rlClient->setModuleStyles( $moduleStyles );
2909 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2910 $rlClient->setExemptStates( $exemptStates );
2911 $this->rlClient
= $rlClient;
2913 return $this->rlClient
;
2917 * @param Skin $sk The given Skin
2918 * @param bool $includeStyle Unused
2919 * @return string The doctype, opening "<html>", and head element.
2921 public function headElement( Skin
$sk, $includeStyle = true ) {
2922 $userdir = $this->getLanguage()->getDir();
2923 $sitedir = MediaWikiServices
::getInstance()->getContentLanguage()->getDir();
2926 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2927 $this->getRlClient()->getDocumentAttributes(),
2928 $sk->getHtmlElementAttributes()
2930 $pieces[] = Html
::openElement( 'head' );
2932 if ( $this->getHTMLTitle() == '' ) {
2933 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2936 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2937 // Add <meta charset="UTF-8">
2938 // This should be before <title> since it defines the charset used by
2939 // text including the text inside <title>.
2940 // The spec recommends defining XHTML5's charset using the XML declaration
2942 // Our XML declaration is output by Html::htmlHeader.
2943 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2944 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2945 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2948 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2949 $pieces[] = $this->getRlClient()->getHeadHtml();
2950 $pieces[] = $this->buildExemptModules();
2951 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2952 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2954 // Use an IE conditional comment to serve the script only to old IE
2955 $pieces[] = '<!--[if lt IE 9]>' .
2956 ResourceLoaderClientHtml
::makeLoad(
2957 ResourceLoaderContext
::newDummyContext(),
2959 ResourceLoaderModule
::TYPE_SCRIPTS
,
2961 $this->getCSPNonce()
2965 $pieces[] = Html
::closeElement( 'head' );
2967 $bodyClasses = $this->mAdditionalBodyClasses
;
2968 $bodyClasses[] = 'mediawiki';
2970 # Classes for LTR/RTL directionality support
2971 $bodyClasses[] = $userdir;
2972 $bodyClasses[] = "sitedir-$sitedir";
2974 $underline = $this->getUser()->getOption( 'underline' );
2975 if ( $underline < 2 ) {
2976 // The following classes can be used here:
2977 // * mw-underline-always
2978 // * mw-underline-never
2979 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2982 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2983 # A <body> class is probably not the best way to do this . . .
2984 $bodyClasses[] = 'capitalize-all-nouns';
2987 // Parser feature migration class
2988 // The idea is that this will eventually be removed, after the wikitext
2989 // which requires it is cleaned up.
2990 $bodyClasses[] = 'mw-hide-empty-elt';
2992 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2993 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2995 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2998 // While the implode() is not strictly needed, it's used for backwards compatibility
2999 // (this used to be built as a string and hooks likely still expect that).
3000 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3002 // Allow skins and extensions to add body attributes they need
3003 $sk->addToBodyAttributes( $this, $bodyAttrs );
3004 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3006 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
3008 return self
::combineWrappedStrings( $pieces );
3012 * Get a ResourceLoader object associated with this OutputPage
3014 * @return ResourceLoader
3016 public function getResourceLoader() {
3017 if ( is_null( $this->mResourceLoader
) ) {
3018 $this->mResourceLoader
= new ResourceLoader(
3020 LoggerFactory
::getInstance( 'resourceloader' )
3023 return $this->mResourceLoader
;
3027 * Explicily load or embed modules on a page.
3029 * @param array|string $modules One or more module names
3030 * @param string $only ResourceLoaderModule TYPE_ class constant
3031 * @param array $extraQuery [optional] Array with extra query parameters for the request
3032 * @return string|WrappedStringList HTML
3034 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3035 // Apply 'target' and 'origin' filters
3036 $modules = $this->filterModules( (array)$modules, null, $only );
3038 return ResourceLoaderClientHtml
::makeLoad(
3039 $this->getRlClientContext(),
3043 $this->getCSPNonce()
3048 * Combine WrappedString chunks and filter out empty ones
3050 * @param array $chunks
3051 * @return string|WrappedStringList HTML
3053 protected static function combineWrappedStrings( array $chunks ) {
3054 // Filter out empty values
3055 $chunks = array_filter( $chunks, 'strlen' );
3056 return WrappedString
::join( "\n", $chunks );
3060 * JS stuff to put at the bottom of the `<body>`.
3061 * These are legacy scripts ($this->mScripts), and user JS.
3063 * @return string|WrappedStringList HTML
3065 public function getBottomScripts() {
3067 $chunks[] = $this->getRlClient()->getBodyHtml();
3069 // Legacy non-ResourceLoader scripts
3070 $chunks[] = $this->mScripts
;
3072 if ( $this->limitReportJSData
) {
3073 $chunks[] = ResourceLoader
::makeInlineScript(
3074 ResourceLoader
::makeConfigSetScript(
3075 [ 'wgPageParseReport' => $this->limitReportJSData
]
3077 $this->getCSPNonce()
3081 return self
::combineWrappedStrings( $chunks );
3085 * Get the javascript config vars to include on this page
3087 * @return array Array of javascript config vars
3090 public function getJsConfigVars() {
3091 return $this->mJsConfigVars
;
3095 * Add one or more variables to be set in mw.config in JavaScript
3097 * @param string|array $keys Key or array of key/value pairs
3098 * @param mixed|null $value [optional] Value of the configuration variable
3100 public function addJsConfigVars( $keys, $value = null ) {
3101 if ( is_array( $keys ) ) {
3102 foreach ( $keys as $key => $value ) {
3103 $this->mJsConfigVars
[$key] = $value;
3108 $this->mJsConfigVars
[$keys] = $value;
3112 * Get an array containing the variables to be set in mw.config in JavaScript.
3114 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3115 * - in other words, page-independent/site-wide variables (without state).
3116 * You will only be adding bloat to the html page and causing page caches to
3117 * have to be purged on configuration changes.
3120 public function getJSVars() {
3123 $canonicalSpecialPageName = false; # T23115
3124 $services = MediaWikiServices
::getInstance();
3126 $title = $this->getTitle();
3127 $ns = $title->getNamespace();
3128 $canonicalNamespace = MWNamespace
::exists( $ns )
3129 ? MWNamespace
::getCanonicalName( $ns )
3130 : $title->getNsText();
3132 $sk = $this->getSkin();
3133 // Get the relevant title so that AJAX features can use the correct page name
3134 // when making API requests from certain special pages (T36972).
3135 $relevantTitle = $sk->getRelevantTitle();
3136 $relevantUser = $sk->getRelevantUser();
3138 if ( $ns == NS_SPECIAL
) {
3139 list( $canonicalSpecialPageName, /*...*/ ) =
3140 $services->getSpecialPageFactory()->
3141 resolveAlias( $title->getDBkey() );
3142 } elseif ( $this->canUseWikiPage() ) {
3143 $wikiPage = $this->getWikiPage();
3144 $curRevisionId = $wikiPage->getLatest();
3145 $articleId = $wikiPage->getId();
3148 $lang = $title->getPageViewLanguage();
3150 // Pre-process information
3151 $separatorTransTable = $lang->separatorTransformTable();
3152 $separatorTransTable = $separatorTransTable ?
: [];
3153 $compactSeparatorTransTable = [
3154 implode( "\t", array_keys( $separatorTransTable ) ),
3155 implode( "\t", $separatorTransTable ),
3157 $digitTransTable = $lang->digitTransformTable();
3158 $digitTransTable = $digitTransTable ?
: [];
3159 $compactDigitTransTable = [
3160 implode( "\t", array_keys( $digitTransTable ) ),
3161 implode( "\t", $digitTransTable ),
3164 $user = $this->getUser();
3167 'wgCanonicalNamespace' => $canonicalNamespace,
3168 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3169 'wgNamespaceNumber' => $title->getNamespace(),
3170 'wgPageName' => $title->getPrefixedDBkey(),
3171 'wgTitle' => $title->getText(),
3172 'wgCurRevisionId' => $curRevisionId,
3173 'wgRevisionId' => (int)$this->getRevisionId(),
3174 'wgArticleId' => $articleId,
3175 'wgIsArticle' => $this->isArticle(),
3176 'wgIsRedirect' => $title->isRedirect(),
3177 'wgAction' => Action
::getActionName( $this->getContext() ),
3178 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3179 'wgUserGroups' => $user->getEffectiveGroups(),
3180 'wgCategories' => $this->getCategories(),
3181 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3182 'wgPageContentLanguage' => $lang->getCode(),
3183 'wgPageContentModel' => $title->getContentModel(),
3184 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3185 'wgDigitTransformTable' => $compactDigitTransTable,
3186 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3187 'wgMonthNames' => $lang->getMonthNamesArray(),
3188 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3189 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3190 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3191 'wgRequestId' => WebRequest
::getRequestId(),
3192 'wgCSPNonce' => $this->getCSPNonce(),
3195 if ( $user->isLoggedIn() ) {
3196 $vars['wgUserId'] = $user->getId();
3197 $vars['wgUserEditCount'] = $user->getEditCount();
3198 $userReg = $user->getRegistration();
3199 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3200 // Get the revision ID of the oldest new message on the user's talk
3201 // page. This can be used for constructing new message alerts on
3203 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3206 $contLang = $services->getContentLanguage();
3207 if ( $contLang->hasVariants() ) {
3208 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3210 // Same test as SkinTemplate
3211 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3212 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3214 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3215 && $relevantTitle->quickUserCan( 'edit', $user )
3216 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3218 foreach ( $title->getRestrictionTypes() as $type ) {
3219 // Following keys are set in $vars:
3220 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3221 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3224 if ( $title->isMainPage() ) {
3225 $vars['wgIsMainPage'] = true;
3228 if ( $this->mRedirectedFrom
) {
3229 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3232 if ( $relevantUser ) {
3233 $vars['wgRelevantUserName'] = $relevantUser->getName();
3236 // Allow extensions to add their custom variables to the mw.config map.
3237 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3238 // page-dependant but site-wide (without state).
3239 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3240 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3242 // Merge in variables from addJsConfigVars last
3243 return array_merge( $vars, $this->getJsConfigVars() );
3247 * To make it harder for someone to slip a user a fake
3248 * JavaScript or CSS preview, a random token
3249 * is associated with the login session. If it's not
3250 * passed back with the preview request, we won't render
3255 public function userCanPreview() {
3256 $request = $this->getRequest();
3258 $request->getVal( 'action' ) !== 'submit' ||
3259 !$request->wasPosted()
3264 $user = $this->getUser();
3266 if ( !$user->isLoggedIn() ) {
3267 // Anons have predictable edit tokens
3270 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3274 $title = $this->getTitle();
3275 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3276 if ( count( $errors ) !== 0 ) {
3284 * @return array Array in format "link name or number => 'link html'".
3286 public function getHeadLinksArray() {
3290 $config = $this->getConfig();
3292 $canonicalUrl = $this->mCanonicalUrl
;
3294 $tags['meta-generator'] = Html
::element( 'meta', [
3295 'name' => 'generator',
3296 'content' => "MediaWiki $wgVersion",
3299 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3300 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3301 // fallbacks should come before the primary value so we need to reverse the array.
3302 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3303 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3304 'name' => 'referrer',
3305 'content' => $policy,
3310 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3311 if ( $p !== 'index,follow' ) {
3312 // http://www.robotstxt.org/wc/meta-user.html
3313 // Only show if it's different from the default robots policy
3314 $tags['meta-robots'] = Html
::element( 'meta', [
3320 foreach ( $this->mMetatags
as $tag ) {
3321 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3323 $tag[0] = substr( $tag[0], 5 );
3324 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3329 $tagName = "meta-{$tag[0]}";
3330 if ( isset( $tags[$tagName] ) ) {
3331 $tagName .= $tag[1];
3333 $tags[$tagName] = Html
::element( 'meta',
3336 'content' => $tag[1]
3341 foreach ( $this->mLinktags
as $tag ) {
3342 $tags[] = Html
::element( 'link', $tag );
3345 # Universal edit button
3346 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3347 $user = $this->getUser();
3348 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3349 && ( $this->getTitle()->exists() ||
3350 $this->getTitle()->quickUserCan( 'create', $user ) )
3352 // Original UniversalEditButton
3353 $msg = $this->msg( 'edit' )->text();
3354 $tags['universal-edit-button'] = Html
::element( 'link', [
3355 'rel' => 'alternate',
3356 'type' => 'application/x-wiki',
3358 'href' => $this->getTitle()->getEditURL(),
3360 // Alternate edit link
3361 $tags['alternative-edit'] = Html
::element( 'link', [
3364 'href' => $this->getTitle()->getEditURL(),
3369 # Generally the order of the favicon and apple-touch-icon links
3370 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3371 # uses whichever one appears later in the HTML source. Make sure
3372 # apple-touch-icon is specified first to avoid this.
3373 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3374 $tags['apple-touch-icon'] = Html
::element( 'link', [
3375 'rel' => 'apple-touch-icon',
3376 'href' => $config->get( 'AppleTouchIcon' )
3380 if ( $config->get( 'Favicon' ) !== false ) {
3381 $tags['favicon'] = Html
::element( 'link', [
3382 'rel' => 'shortcut icon',
3383 'href' => $config->get( 'Favicon' )
3387 # OpenSearch description link
3388 $tags['opensearch'] = Html
::element( 'link', [
3390 'type' => 'application/opensearchdescription+xml',
3391 'href' => wfScript( 'opensearch_desc' ),
3392 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3395 # Real Simple Discovery link, provides auto-discovery information
3396 # for the MediaWiki API (and potentially additional custom API
3397 # support such as WordPress or Twitter-compatible APIs for a
3398 # blogging extension, etc)
3399 $tags['rsd'] = Html
::element( 'link', [
3401 'type' => 'application/rsd+xml',
3402 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3403 // Whether RSD accepts relative or protocol-relative URLs is completely
3404 // undocumented, though.
3405 'href' => wfExpandUrl( wfAppendQuery(
3407 [ 'action' => 'rsd' ] ),
3413 if ( !$config->get( 'DisableLangConversion' ) ) {
3414 $lang = $this->getTitle()->getPageLanguage();
3415 if ( $lang->hasVariants() ) {
3416 $variants = $lang->getVariants();
3417 foreach ( $variants as $variant ) {
3418 $tags["variant-$variant"] = Html
::element( 'link', [
3419 'rel' => 'alternate',
3420 'hreflang' => LanguageCode
::bcp47( $variant ),
3421 'href' => $this->getTitle()->getLocalURL(
3422 [ 'variant' => $variant ] )
3426 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3427 $tags["variant-x-default"] = Html
::element( 'link', [
3428 'rel' => 'alternate',
3429 'hreflang' => 'x-default',
3430 'href' => $this->getTitle()->getLocalURL() ] );
3435 if ( $this->copyrightUrl
!== null ) {
3436 $copyright = $this->copyrightUrl
;
3439 if ( $config->get( 'RightsPage' ) ) {
3440 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3443 $copyright = $copy->getLocalURL();
3447 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3448 $copyright = $config->get( 'RightsUrl' );
3453 $tags['copyright'] = Html
::element( 'link', [
3455 'href' => $copyright ]
3460 if ( $config->get( 'Feed' ) ) {
3463 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3464 # Use the page name for the title. In principle, this could
3465 # lead to issues with having the same name for different feeds
3466 # corresponding to the same page, but we can't avoid that at
3469 $feedLinks[] = $this->feedLink(
3472 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3474 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3479 # Recent changes feed should appear on every page (except recentchanges,
3480 # that would be redundant). Put it after the per-page feed to avoid
3481 # changing existing behavior. It's still available, probably via a
3482 # menu in your browser. Some sites might have a different feed they'd
3483 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3484 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3485 # If so, use it instead.
3486 $sitename = $config->get( 'Sitename' );
3487 if ( $config->get( 'OverrideSiteFeed' ) ) {
3488 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3489 // Note, this->feedLink escapes the url.
3490 $feedLinks[] = $this->feedLink(
3493 $this->msg( "site-{$type}-feed", $sitename )->text()
3496 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3497 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3498 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3499 $feedLinks[] = $this->feedLink(
3501 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3502 # For grep: 'site-rss-feed', 'site-atom-feed'
3503 $this->msg( "site-{$format}-feed", $sitename )->text()
3508 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3509 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3510 # use OutputPage::addFeedLink() instead.
3511 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3513 $tags +
= $feedLinks;
3517 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3518 if ( $canonicalUrl !== false ) {
3519 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3521 if ( $this->isArticleRelated() ) {
3522 // This affects all requests where "setArticleRelated" is true. This is
3523 // typically all requests that show content (query title, curid, oldid, diff),
3524 // and all wikipage actions (edit, delete, purge, info, history etc.).
3525 // It does not apply to File pages and Special pages.
3526 // 'history' and 'info' actions address page metadata rather than the page
3527 // content itself, so they may not be canonicalized to the view page url.
3528 // TODO: this ought to be better encapsulated in the Action class.
3529 $action = Action
::getActionName( $this->getContext() );
3530 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3531 $query = "action={$action}";
3535 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3537 $reqUrl = $this->getRequest()->getRequestURL();
3538 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3542 if ( $canonicalUrl !== false ) {
3543 $tags[] = Html
::element( 'link', [
3544 'rel' => 'canonical',
3545 'href' => $canonicalUrl
3549 // Allow extensions to add, remove and/or otherwise manipulate these links
3550 // If you want only to *add* <head> links, please use the addHeadItem()
3551 // (or addHeadItems() for multiple items) method instead.
3552 // This hook is provided as a last resort for extensions to modify these
3553 // links before the output is sent to client.
3554 Hooks
::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3560 * Generate a "<link rel/>" for a feed.
3562 * @param string $type Feed type
3563 * @param string $url URL to the feed
3564 * @param string $text Value of the "title" attribute
3565 * @return string HTML fragment
3567 private function feedLink( $type, $url, $text ) {
3568 return Html
::element( 'link', [
3569 'rel' => 'alternate',
3570 'type' => "application/$type+xml",
3577 * Add a local or specified stylesheet, with the given media options.
3578 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3580 * @param string $style URL to the file
3581 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3582 * @param string $condition For IE conditional comments, specifying an IE version
3583 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3585 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3588 $options['media'] = $media;
3591 $options['condition'] = $condition;
3594 $options['dir'] = $dir;
3596 $this->styles
[$style] = $options;
3600 * Adds inline CSS styles
3601 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3603 * @param mixed $style_css Inline CSS
3604 * @param string $flip Set to 'flip' to flip the CSS if needed
3606 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3607 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3608 # If wanted, and the interface is right-to-left, flip the CSS
3609 $style_css = CSSJanus
::transform( $style_css, true, false );
3611 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3615 * Build exempt modules and legacy non-ResourceLoader styles.
3617 * @return string|WrappedStringList HTML
3619 protected function buildExemptModules() {
3621 // Things that go after the ResourceLoaderDynamicStyles marker
3624 // We want site, private and user styles to override dynamically added styles from
3625 // general modules, but we want dynamically added styles to override statically added
3626 // style modules. So the order has to be:
3627 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3628 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3629 // - ResourceLoaderDynamicStyles marker
3630 // - site/private/user styles
3632 // Add legacy styles added through addStyle()/addInlineStyle() here
3633 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3635 $chunks[] = Html
::element(
3637 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3640 $separateReq = [ 'site.styles', 'user.styles' ];
3641 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3642 // Combinable modules
3643 $chunks[] = $this->makeResourceLoaderLink(
3644 array_diff( $moduleNames, $separateReq ),
3645 ResourceLoaderModule
::TYPE_STYLES
3648 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3649 // These require their own dedicated request in order to support "@import"
3650 // syntax, which is incompatible with concatenation. (T147667, T37562)
3651 $chunks[] = $this->makeResourceLoaderLink( $name,
3652 ResourceLoaderModule
::TYPE_STYLES
3657 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3663 public function buildCssLinksArray() {
3666 foreach ( $this->styles
as $file => $options ) {
3667 $link = $this->styleLink( $file, $options );
3669 $links[$file] = $link;
3676 * Generate \<link\> tags for stylesheets
3678 * @param string $style URL to the file
3679 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3680 * @return string HTML fragment
3682 protected function styleLink( $style, array $options ) {
3683 if ( isset( $options['dir'] ) ) {
3684 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3689 if ( isset( $options['media'] ) ) {
3690 $media = self
::transformCssMedia( $options['media'] );
3691 if ( is_null( $media ) ) {
3698 if ( substr( $style, 0, 1 ) == '/' ||
3699 substr( $style, 0, 5 ) == 'http:' ||
3700 substr( $style, 0, 6 ) == 'https:' ) {
3703 $config = $this->getConfig();
3704 // Append file hash as query parameter
3705 $url = self
::transformResourcePath(
3707 $config->get( 'StylePath' ) . '/' . $style
3711 $link = Html
::linkedStyle( $url, $media );
3713 if ( isset( $options['condition'] ) ) {
3714 $condition = htmlspecialchars( $options['condition'] );
3715 $link = "<!--[if $condition]>$link<![endif]-->";
3721 * Transform path to web-accessible static resource.
3723 * This is used to add a validation hash as query string.
3724 * This aids various behaviors:
3726 * - Put long Cache-Control max-age headers on responses for improved
3727 * cache performance.
3728 * - Get the correct version of a file as expected by the current page.
3729 * - Instantly get the updated version of a file after deployment.
3731 * Avoid using this for urls included in HTML as otherwise clients may get different
3732 * versions of a resource when navigating the site depending on when the page was cached.
3733 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3734 * an external stylesheet).
3737 * @param Config $config
3738 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3739 * @return string URL
3741 public static function transformResourcePath( Config
$config, $path ) {
3745 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3746 if ( $remotePathPrefix === '' ) {
3747 // The configured base path is required to be empty string for
3748 // wikis in the domain root
3751 $remotePath = $remotePathPrefix;
3753 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3754 // - Path is outside wgResourceBasePath, ignore.
3755 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3758 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3759 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3760 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3761 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3762 $uploadPath = $config->get( 'UploadPath' );
3763 if ( strpos( $path, $uploadPath ) === 0 ) {
3764 $localDir = $config->get( 'UploadDirectory' );
3765 $remotePathPrefix = $remotePath = $uploadPath;
3768 $path = RelPath
::getRelativePath( $path, $remotePath );
3769 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3773 * Utility method for transformResourceFilePath().
3775 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3778 * @param string $remotePathPrefix URL path prefix that points to $localPath
3779 * @param string $localPath File directory exposed at $remotePath
3780 * @param string $file Path to target file relative to $localPath
3781 * @return string URL
3783 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3784 $hash = md5_file( "$localPath/$file" );
3785 if ( $hash === false ) {
3786 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3789 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3793 * Transform "media" attribute based on request parameters
3795 * @param string $media Current value of the "media" attribute
3796 * @return string Modified value of the "media" attribute, or null to skip
3799 public static function transformCssMedia( $media ) {
3802 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3803 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3805 // Switch in on-screen display for media testing
3807 'printable' => 'print',
3808 'handheld' => 'handheld',
3810 foreach ( $switches as $switch => $targetMedia ) {
3811 if ( $wgRequest->getBool( $switch ) ) {
3812 if ( $media == $targetMedia ) {
3814 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3815 /* This regex will not attempt to understand a comma-separated media_query_list
3817 * Example supported values for $media:
3818 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3819 * Example NOT supported value for $media:
3820 * '3d-glasses, screen, print and resolution > 90dpi'
3822 * If it's a print request, we never want any kind of screen stylesheets
3823 * If it's a handheld request (currently the only other choice with a switch),
3824 * we don't want simple 'screen' but we might want screen queries that
3825 * have a max-width or something, so we'll pass all others on and let the
3826 * client do the query.
3828 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3839 * Add a wikitext-formatted message to the output.
3840 * This is equivalent to:
3842 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3844 public function addWikiMsg( /*...*/ ) {
3845 $args = func_get_args();
3846 $name = array_shift( $args );
3847 $this->addWikiMsgArray( $name, $args );
3851 * Add a wikitext-formatted message to the output.
3852 * Like addWikiMsg() except the parameters are taken as an array
3853 * instead of a variable argument list.
3855 * @param string $name
3856 * @param array $args
3858 public function addWikiMsgArray( $name, $args ) {
3859 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3863 * This function takes a number of message/argument specifications, wraps them in
3864 * some overall structure, and then parses the result and adds it to the output.
3866 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3867 * and so on. The subsequent arguments may be either
3868 * 1) strings, in which case they are message names, or
3869 * 2) arrays, in which case, within each array, the first element is the message
3870 * name, and subsequent elements are the parameters to that message.
3872 * Don't use this for messages that are not in the user's interface language.
3876 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3880 * $wgOut->addWikiText( "<div class='error'>\n"
3881 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3883 * The newline after the opening div is needed in some wikitext. See T21226.
3885 * @param string $wrap
3887 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3888 $msgSpecs = func_get_args();
3889 array_shift( $msgSpecs );
3890 $msgSpecs = array_values( $msgSpecs );
3892 foreach ( $msgSpecs as $n => $spec ) {
3893 if ( is_array( $spec ) ) {
3895 $name = array_shift( $args );
3896 if ( isset( $args['options'] ) ) {
3897 unset( $args['options'] );
3899 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3907 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3909 $this->addWikiText( $s );
3913 * Whether the output has a table of contents
3917 public function isTOCEnabled() {
3918 return $this->mEnableTOC
;
3922 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3925 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3927 public function enableSectionEditLinks( $flag = true ) {
3928 wfDeprecated( __METHOD__
, '1.31' );
3934 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3936 public function sectionEditLinksEnabled() {
3937 wfDeprecated( __METHOD__
, '1.31' );
3942 * Helper function to setup the PHP implementation of OOUI to use in this request.
3945 * @param String $skinName The Skin name to determine the correct OOUI theme
3946 * @param String $dir Language direction
3948 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3949 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3950 $theme = $themes[$skinName] ??
$themes['default'];
3951 // For example, 'OOUI\WikimediaUITheme'.
3952 $themeClass = "OOUI\\{$theme}Theme";
3953 OOUI\Theme
::setSingleton( new $themeClass() );
3954 OOUI\Element
::setDefaultDir( $dir );
3958 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3959 * MediaWiki and this OutputPage instance.
3963 public function enableOOUI() {
3965 strtolower( $this->getSkin()->getSkinName() ),
3966 $this->getLanguage()->getDir()
3968 $this->addModuleStyles( [
3969 'oojs-ui-core.styles',
3970 'oojs-ui.styles.indicators',
3971 'oojs-ui.styles.textures',
3972 'mediawiki.widgets.styles',
3973 'oojs-ui.styles.icons-content',
3974 'oojs-ui.styles.icons-alerts',
3975 'oojs-ui.styles.icons-interactions',
3980 * Get (and set if not yet set) the CSP nonce.
3982 * This value needs to be included in any <script> tags on the
3985 * @return string|bool Nonce or false to mean don't output nonce
3988 public function getCSPNonce() {
3989 if ( !ContentSecurityPolicy
::isNonceRequired( $this->getConfig() ) ) {
3992 if ( $this->CSPNonce
=== null ) {
3993 // XXX It might be expensive to generate randomness
3994 // on every request, on Windows.
3995 $rand = random_bytes( 15 );
3996 $this->CSPNonce
= base64_encode( $rand );
3998 return $this->CSPNonce
;